repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
EnigmaGuest/fnk-server
service-core/service-core-system/src/main/java/fun/isite/service/core/system/mapper/UserRoleMapper.java
[ { "identifier": "SystemMenu", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/SystemMenu.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"system_menu\")\n@Schema(name = \"SystemMenu\", description = \"系统菜单\")\npublic class SystemMenu extends BaseEntity<SystemMenu> {\n\n /**\n * 上级ID\n */\n @Schema(description=\"上级ID\")\n private String rootId;\n\n /**\n * 菜单名称\n */\n @Schema(description=\"菜单名称\")\n private String name;\n\n /**\n * 路由key全局唯一\n */\n @Schema(description=\"路由key全局唯一\")\n private String routeKey;\n\n /**\n * 显示顺序\n */\n @Schema(description=\"显示顺序\")\n private Integer orderSort;\n\n /**\n * 是否为网页\n */\n @Schema(description=\"是否为网页\")\n private Boolean isIframe;\n\n /**\n * 请求路径\n */\n @Schema(description=\"请求路径\")\n private String path;\n\n /**\n * icones\n */\n @Schema(description=\"icones\")\n private String icon;\n\n /**\n * 本地icon\n */\n @Schema(description=\"本地icon\")\n private String localIcon;\n\n /**\n * 是否显示\n */\n @Schema(description=\"是否显示\")\n private Boolean visible;\n\n /**\n * 权限标识\n */\n @Schema(description=\"权限标识\")\n private String permission;\n\n /**\n * 菜单类型(table目录 menu菜单 button按钮)\n */\n @Schema(description=\"菜单类型(table目录 menu菜单 button按钮)\")\n private MenuTypeEnum type;\n\n /**\n * 备注\n */\n @Schema(description=\"备注\")\n private String remark;\n\n\n}" }, { "identifier": "UserRole", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/UserRole.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"user_role\")\n@Schema(name = \"UserRole\", description = \"用户和角色关联\")\npublic class UserRole extends BaseEntity<UserRole> {\n\n /**\n * 系统用户ID\n */\n @Schema(description=\"系统用户ID\")\n private String userId;\n\n /**\n * 角色ID\n */\n @Schema(description=\"角色ID\")\n private String roleId;\n\n\n}" } ]
import fun.isite.service.core.system.entity.SystemMenu; import fun.isite.service.core.system.entity.UserRole; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List;
852
package fun.isite.service.core.system.mapper; /** * <p> * 用户和角色关联 Mapper 接口 * </p> * * @author Enigma * @since 2023-12-18 */ @Mapper public interface UserRoleMapper extends BaseMapper<UserRole> { @Delete("delete from user_role where user_id = #{userId}") int deleteByUserId(String userId); @Select("select role_id from user_role where user_id = #{userId}") List<String> queryRoleIdsByUserId(String userId);
package fun.isite.service.core.system.mapper; /** * <p> * 用户和角色关联 Mapper 接口 * </p> * * @author Enigma * @since 2023-12-18 */ @Mapper public interface UserRoleMapper extends BaseMapper<UserRole> { @Delete("delete from user_role where user_id = #{userId}") int deleteByUserId(String userId); @Select("select role_id from user_role where user_id = #{userId}") List<String> queryRoleIdsByUserId(String userId);
List<SystemMenu> queryMenusByUserId(String userId);
0
2023-12-26 01:55:01+00:00
2k
yutianqaq/BypassAV-Online
BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/service/impl/CompileServiceImpl.java
[ { "identifier": "CompilationResult", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/controller/domain/CompilationResult.java", "snippet": "@Getter\n@Setter\npublic class CompilationResult {\n private byte[] fileBytes;\n private String fileName;\n\n public CompilationResult(byte[] fileBytes, String fileName) {\n this.fileBytes = fileBytes;\n this.fileName = fileName;\n }\n\n\n}" }, { "identifier": "CompilationResponseDTO", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/dto/CompilationResponseDTO.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString\npublic class CompilationResponseDTO {\n private String downloadLink;\n}" }, { "identifier": "CompileRequestDTO", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/dto/CompileRequestDTO.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString\npublic class CompileRequestDTO {\n private String code;\n private String templateName;\n\n}" }, { "identifier": "CompileService", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/service/CompileService.java", "snippet": "public interface CompileService {\n CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException;\n CompilationResponseDTO compileCodeNIM(CompileRequestDTO request) throws IOException;\n}" }, { "identifier": "CodeCompilationUtils", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/utils/CodeCompilationUtils.java", "snippet": "@Component\npublic class CodeCompilationUtils {\n\n private static ApplicationProperties applicationProperties;\n\n @Autowired\n public void setApplicationProperties(ApplicationProperties applicationProperties) {\n CodeCompilationUtils.applicationProperties = applicationProperties;\n }\n public static CompilationResult compileCCode(String code, String templateFileName) throws IOException {\n\n String processedCode = TextFileProcessor.processTemplate(code, templateFileName); // 处理模板\n // 将处理后的代码保存到临时文件\n // 生成临时文件名\n String tempFileName = UUID.randomUUID().toString() + \".c\";\n String compiledFileName = UUID.randomUUID().toString() + \".exe\";\n File tempFile = new File(tempFileName);\n\n // 保存处理后的代码到临时文件\n try (FileWriter writer = new FileWriter(tempFile)) {\n writer.write(processedCode);\n }\n\n // 编译代码为EXE文件\n ProcessBuilder processBuilder = new ProcessBuilder(applicationProperties.getCompilerC(), tempFile.getAbsolutePath(), \"-o\", compiledFileName);\n Process process = processBuilder.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n // 读取编译后的EXE文件\n File outputFile = new File(compiledFileName);\n byte[] fileBytes = Files.readAllBytes(outputFile.toPath());\n\n // 删除临时文件和输出文件\n tempFile.delete();\n outputFile.delete();\n\n return new CompilationResult(fileBytes, compiledFileName);\n }\n public static CompilationResult compileNimCode(String code, String templateFileName) throws IOException {\n\n String processedCode = TextFileProcessor.processTemplate(code, templateFileName); // 处理模板\n\n // 将处理后的代码保存到临时文件\n // 生成临时文件名\n String randomLetters = TextFileProcessor.generateRandomFileName();\n\n String uniqueId = UUID.randomUUID().toString().replace(\"-\", \"\");\n String tempFileName = randomLetters + uniqueId + \".nim\";\n String compiledFileName = randomLetters + uniqueId + \".exe\";\n File tempFile = new File(tempFileName);\n\n // 保存处理后的代码到临时文件\n try (FileWriter writer = new FileWriter(tempFile)) {\n writer.write(processedCode);\n }\n System.out.println(compiledFileName);\n System.out.println(tempFile.getAbsolutePath());\n\n // nim c -d=release --cc:gcc --app=gui --cpu=amd64 -o:x1.exe x1Ldr.nim\n try {\n ProcessBuilder processBuilder = new ProcessBuilder(applicationProperties.getCompilerNIM(), \"c\", \"-d=release\", \"-d=mingw\", \"--app=gui\", \"-d:strip\", \"--opt:size\",\n \"--cpu=amd64\", \"-o:\" + compiledFileName, tempFile.getAbsolutePath());\n List<String> command = processBuilder.command();\n\n Process process = processBuilder.start();\n\n // 等待进程执行完成\n int exitCode = process.waitFor();\n\n } catch (IOException e) {\n // 处理进程启动的IO异常\n e.printStackTrace();\n } catch (InterruptedException e) {\n // 处理进程等待过程中的中断异常\n e.printStackTrace();\n }\n\n // 读取编译后的EXE文件\n File outputFile = new File(compiledFileName);\n byte[] fileBytes = Files.readAllBytes(outputFile.toPath());\n\n // 删除临时文件和输出文件\n tempFile.delete();\n outputFile.delete();\n\n return new CompilationResult(fileBytes, compiledFileName);\n }\n\n}" }, { "identifier": "saveFile", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/utils/FileProcessor.java", "snippet": "public static String saveFile(byte[] fileBytes, String fileName) throws IOException {\n File storageDirectory = new File(applicationProperties.getStorageDirector());\n if (!storageDirectory.exists()) {\n storageDirectory.mkdirs();\n }\n\n Path filePath = storageDirectory.toPath().resolve(fileName);\n\n Files.write(filePath, fileBytes);\n String modifiedFileName = fileName.substring(0, fileName.length() - 4);\n String filename = storageDirectory + File.separator + modifiedFileName + \".zip\";\n ZipFile zipFile = new ZipFile( filename, \"yutian\".toCharArray());\n\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setEncryptFiles(true);\n\n zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);\n\n zipFile.addFile(filePath.toFile(), zipParameters);\n Files.deleteIfExists(filePath);\n\n return modifiedFileName + \".zip\";\n}" } ]
import com.yutian4090.bypass.controller.domain.CompilationResult; import com.yutian4090.bypass.dto.CompilationResponseDTO; import com.yutian4090.bypass.dto.CompileRequestDTO; import com.yutian4090.bypass.service.CompileService; import com.yutian4090.bypass.utils.CodeCompilationUtils; import org.springframework.stereotype.Service; import java.io.IOException; import static com.yutian4090.bypass.utils.FileProcessor.saveFile;
1,588
package com.yutian4090.bypass.service.impl; @Service public class CompileServiceImpl implements CompileService { @Override
package com.yutian4090.bypass.service.impl; @Service public class CompileServiceImpl implements CompileService { @Override
public CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException {
1
2023-12-28 06:22:12+00:00
2k
codingmiao/hppt
ss/src/main/java/org/wowtools/hppt/ss/StartSs.java
[ { "identifier": "Constant", "path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java", "snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory());\n\n public static final String sessionIdJoinFlag = \",\";\n\n //ss端执行的命令代码\n public static final class SsCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n }\n\n //Sc端执行的命令代码\n public static final class ScCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //Cs端执行的命令代码\n public static final class CsCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //cc端执行的命令代码\n public static final class CcCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n\n //新建会话 2sessionId host port\n public static final char CreateSession = '2';\n }\n\n}" }, { "identifier": "SsConfig", "path": "ss/src/main/java/org/wowtools/hppt/ss/pojo/SsConfig.java", "snippet": "public class SsConfig {\n public int port;\n\n /**\n * 超过sessionTimeout,给客户端发送存活确认命令,若下一个sessionTimeout内未收到确认,则强制关闭服务\n */\n public long sessionTimeout = 120000;\n\n /**\n * 接收到客户端/真实端口的数据时,数据被暂存在一个队列里,队列满后强制关闭会话\n */\n public int messageQueueSize = 2048;\n\n /**\n * 上传/下载文件用的目录\n */\n public String fileDir;\n\n /**\n * 是否启用压缩,默认启用\n */\n public boolean enableCompress = true;\n\n /**\n * 是否启用内容加密,默认启用\n */\n public boolean enableEncrypt = true;\n\n /**\n * 允许的客户端\n */\n public ArrayList<String> clientIds;\n}" } ]
import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.core.config.Configurator; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ErrorPageErrorHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.wowtools.common.utils.ResourcesReader; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.ss.pojo.SsConfig; import org.wowtools.hppt.ss.servlet.*; import java.io.File;
916
package org.wowtools.hppt.ss; /** * @author liuyu * @date 2023/11/25 */ @Slf4j public class StartSs {
package org.wowtools.hppt.ss; /** * @author liuyu * @date 2023/11/25 */ @Slf4j public class StartSs {
public static final SsConfig config;
1
2023-12-22 14:14:27+00:00
2k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/pathfinder/Path.java
[ { "identifier": "CanBeInvalidated", "path": "src/main/java/me/earth/phobot/invalidation/CanBeInvalidated.java", "snippet": "public interface CanBeInvalidated {\n boolean isValid();\n\n void invalidate();\n\n}" }, { "identifier": "PathfindingNode", "path": "src/main/java/me/earth/phobot/pathfinder/algorithm/PathfindingNode.java", "snippet": "public interface PathfindingNode<N extends PathfindingNode<N>> extends Comparable<N> {\n N[] getAdjacent();\n\n double getRenderX();\n\n double getRenderY();\n\n double getRenderZ();\n\n int getChunkX();\n\n int getChunkZ();\n\n double distanceSq(N node);\n\n default double distance(N node) {\n return Math.sqrt(distanceSq(node));\n }\n\n default boolean isValid() {\n return true;\n }\n\n}" }, { "identifier": "MeshNode", "path": "src/main/java/me/earth/phobot/pathfinder/mesh/MeshNode.java", "snippet": "@Getter\n@Setter\npublic class MeshNode extends Abstract3iNode<MeshNode> implements CanBeInvalidated {\n public static final int[] OPPOSITE_INDEX = {1, 0, 3, 2};\n public static final Vec3i[] OFFSETS = new Vec3i[] {\n new Vec3i(1, 0, 0),\n new Vec3i(-1, 0, 0),\n new Vec3i(0, 0, 1),\n new Vec3i(0, 0, -1)\n };\n\n // TODO: also track how \"safe\" (how many blocks around) a node are, and prefer strafing between bedrock blocks before strafing above\n\n private final MeshNode[] adjacent = new MeshNode[4];\n private final ChunkWorker chunk;\n private final int version;\n\n private boolean headSpace = false;\n private boolean valid = true;\n\n public MeshNode(ChunkWorker chunk, int x, int y, int z) {\n this(chunk, chunk.getVersion(), x, y, z);\n }\n\n public MeshNode(ChunkWorker chunk, int version, int x, int y, int z) {\n super(x, y, z);\n this.chunk = chunk;\n this.version = version;\n }\n\n @Override\n public boolean isValid() {\n return valid && getChunk().getVersion() == this.getVersion();\n }\n\n @Override\n public void invalidate() {\n setValid(false);\n }\n\n}" } ]
import lombok.Data; import me.earth.phobot.invalidation.CanBeInvalidated; import me.earth.phobot.pathfinder.algorithm.PathfindingNode; import me.earth.phobot.pathfinder.mesh.MeshNode; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import java.util.List; import java.util.Set; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet;
719
package me.earth.phobot.pathfinder; @Data public class Path<T extends PathfindingNode<T>> implements CanBeInvalidated {
package me.earth.phobot.pathfinder; @Data public class Path<T extends PathfindingNode<T>> implements CanBeInvalidated {
private static final Path<?> INVALID = new Path<>(Vec3.ZERO, Vec3.ZERO, BlockPos.ZERO, BlockPos.ZERO, emptySet(), emptyList(), MeshNode.class) {
2
2023-12-22 14:32:16+00:00
2k
Video-Hub-Org/video-hub
backend/src/main/java/org/videohub/service/RedBookService.java
[ { "identifier": "VideoHubConstants", "path": "backend/src/main/java/org/videohub/constant/VideoHubConstants.java", "snippet": "public class VideoHubConstants {\n // 文件下载路径,默认为项目同级目录下\n public static final String VIDEOHUB_FILEPATH = \"videoHubDownload/\";\n\n public static final String USER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\";\n\n // 小红书笔记匹配正则\n public static final String REDBOOK_NODE_REGEX_01 = \"http://xhslink\\\\.com/\\\\w+\";\n public static final String REDBOOK_NODE_REGEX_02 = \"https://www.xiaohongshu.com/explore/([a-zA-Z0-9]+)\";\n public static final String REDBOOK_NODE_REGEX_03 = \"https://www.xiaohongshu.com/discovery/item/([a-zA-Z0-9]+)\";\n\n // 小红书用户匹配正则\n public static final String REDBOOK_USER_REGEX_01 = \"https://www.xiaohongshu.com/user/profile/([a-zA-Z0-9]+)\";\n\n public static final String REDBOOK_NODE_REGEX_EXPLORE = \"https://www.xiaohongshu.com/explore/\";\n\n public static final String IMAGE_PREFIX = \"https://sns-img-qc.xhscdn.com/\";\n public static final String VIDEO_PREFIX = \"http://sns-video-qc.xhscdn.com/\";\n\n}" }, { "identifier": "VideoHubUtils", "path": "backend/src/main/java/org/videohub/utils/VideoHubUtils.java", "snippet": "@Slf4j\npublic final class VideoHubUtils {\n // 以#开头的行将被忽略,如果你不想下载或某些链接已被下载过,可以在开头添加#\n public static String readLinkFromFile(String fileName) {\n try {\n Path filePath = Paths.get(ClassLoader.getSystemResource(fileName).toURI());\n List<String> lines = Files.readAllLines(filePath);\n\n // 过滤以\"#\"开头的行,然后将每行用空格分隔并拼接成一个字符串\n return lines.stream().filter(line -> !line.trim().startsWith(\"#\")).collect(Collectors.joining(\" \"));\n } catch (IOException | URISyntaxException e) {\n log.error(\"读取{}文件失败\", fileName, e);\n return \"\"; // 处理文件读取失败的情况\n }\n }\n\n public static List<String> matchURL(String text, String... regexArray) {\n List<String> matchedValues = new ArrayList<>();\n\n for (String regex : regexArray) {\n // 使用正则表达式匹配\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n\n // 查找匹配项\n while (matcher.find()) {\n String match = matcher.group();\n matchedValues.add(match);\n log.info(\"匹配到URL:{}\", match);\n }\n }\n\n return matchedValues;\n }\n\n public static void mkdir4download(String folderPath) throws IOException {\n try {\n // 获取项目运行的上级目录\n Path parentDirectory = Paths.get(\"..\").toAbsolutePath().normalize();\n // 创建文件夹路径\n Path fullPath = parentDirectory.resolve(folderPath);\n // 创建文件夹\n Files.createDirectories(fullPath);\n log.info(\"文件夹创建成功 ---\");\n } catch (FileAlreadyExistsException e) {\n log.info(\"文件夹已经存在 ---\");\n } catch (IOException e) {\n log.error(\"创建文件夹失败\", e);\n throw e;\n }\n }\n}" } ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import org.videohub.constant.VideoHubConstants; import org.videohub.utils.VideoHubUtils; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,583
package org.videohub.service; /** * 小红书笔记下载实现类 * * @author @fmz200 * @date 2023-12-18 */ @Slf4j public class RedBookService { // 下载视频超时时间,默认60秒 @Value("${videoDownloadTimeout}") private static int videoDownloadTimeout; // 下载文件的保存位置 @Value("${fileSavePath}") private static String fileSavePath; private static final ExecutorService executorService = Executors.newCachedThreadPool(); public static void downloadNodeBatch(String url) { try { if (videoDownloadTimeout < 1) videoDownloadTimeout = 180; if (!StringUtils.hasText(fileSavePath)) fileSavePath = VideoHubConstants.VIDEOHUB_FILEPATH; Document doc = Jsoup.connect(url).userAgent(VideoHubConstants.USER_AGENT).get(); String match = "window.__INITIAL_STATE__"; for (Element script : doc.select("script")) { String scriptData = script.data(); if (!scriptData.contains(match)) { continue; } String jsonString = scriptData.substring(scriptData.indexOf("=") + 1); log.info("发现笔记信息~~~~"); JSONObject jsonObject = JSON.parseObject(jsonString); JSONObject object = jsonObject.getJSONObject("note"); String firstNoteId = object.getString("firstNoteId"); JSONObject note = object.getJSONObject("noteDetailMap").getJSONObject(firstNoteId).getJSONObject("note"); String ipLocation = Optional.ofNullable(note.getString("ipLocation")).orElse("偶买噶,居然不知道TA在哪"); JSONObject user = note.getJSONObject("user"); String userId = user.getString("userId"); String nickname = user.getString("nickname"); // String avatar = user.getString("avatar"); log.info("用户信息-->用户ID:{},昵称:{},IP位置:{}", userId, nickname, ipLocation); String noteId = note.getString("noteId"); String title = note.getString("title"); log.info("笔记信息-->笔记ID:{},标题:{}", noteId, title); // 创建文件夹 String folder = fileSavePath + "redBook/" + userId + "/" + noteId;
package org.videohub.service; /** * 小红书笔记下载实现类 * * @author @fmz200 * @date 2023-12-18 */ @Slf4j public class RedBookService { // 下载视频超时时间,默认60秒 @Value("${videoDownloadTimeout}") private static int videoDownloadTimeout; // 下载文件的保存位置 @Value("${fileSavePath}") private static String fileSavePath; private static final ExecutorService executorService = Executors.newCachedThreadPool(); public static void downloadNodeBatch(String url) { try { if (videoDownloadTimeout < 1) videoDownloadTimeout = 180; if (!StringUtils.hasText(fileSavePath)) fileSavePath = VideoHubConstants.VIDEOHUB_FILEPATH; Document doc = Jsoup.connect(url).userAgent(VideoHubConstants.USER_AGENT).get(); String match = "window.__INITIAL_STATE__"; for (Element script : doc.select("script")) { String scriptData = script.data(); if (!scriptData.contains(match)) { continue; } String jsonString = scriptData.substring(scriptData.indexOf("=") + 1); log.info("发现笔记信息~~~~"); JSONObject jsonObject = JSON.parseObject(jsonString); JSONObject object = jsonObject.getJSONObject("note"); String firstNoteId = object.getString("firstNoteId"); JSONObject note = object.getJSONObject("noteDetailMap").getJSONObject(firstNoteId).getJSONObject("note"); String ipLocation = Optional.ofNullable(note.getString("ipLocation")).orElse("偶买噶,居然不知道TA在哪"); JSONObject user = note.getJSONObject("user"); String userId = user.getString("userId"); String nickname = user.getString("nickname"); // String avatar = user.getString("avatar"); log.info("用户信息-->用户ID:{},昵称:{},IP位置:{}", userId, nickname, ipLocation); String noteId = note.getString("noteId"); String title = note.getString("title"); log.info("笔记信息-->笔记ID:{},标题:{}", noteId, title); // 创建文件夹 String folder = fileSavePath + "redBook/" + userId + "/" + noteId;
VideoHubUtils.mkdir4download(folder);
1
2023-12-23 03:43:13+00:00
2k
PENEKhun/baekjoon-java-starter
src/main/java/kr/huni/BojStarter.java
[ { "identifier": "CodeGenerator", "path": "src/main/java/kr/huni/code_generator/CodeGenerator.java", "snippet": "public interface CodeGenerator {\n\n GeneratedCode generate(Problem problem);\n}" }, { "identifier": "CodeOpenManager", "path": "src/main/java/kr/huni/code_runner/CodeOpenManager.java", "snippet": "public interface CodeOpenManager {\n\n /**\n * @param codePath 소스코드의 경로\n * @throws IOException 실행 실패\n * @implSpec 주어진 codePath를 IDE로 열어준다\n */\n void run(String codePath, OperatingSystem operatingSystem) throws IOException;\n\n}" }, { "identifier": "JavaSourceCodeFile", "path": "src/main/java/kr/huni/file_generator/JavaSourceCodeFile.java", "snippet": "@Slf4j\npublic class JavaSourceCodeFile implements SourceCodeFile {\n\n @Override\n public void write(String sourceRootDirectory, String sourceCode, String testCode)\n throws IOException {\n File srcDir = new File(sourceRootDirectory, \"src\");\n\n log.info(\"srcDir : {}\", srcDir.getAbsolutePath());\n srcDir.mkdirs();\n\n log.info(\"소스코드 디렉토리 생성 완료\");\n writeToFile(srcDir, \"Main.java\", sourceCode);\n writeToFile(srcDir, \"TestHelper.java\", testCode);\n }\n\n}" }, { "identifier": "OperatingSystem", "path": "src/main/java/kr/huni/os/OperatingSystem.java", "snippet": "public enum OperatingSystem {\n WINDOWS,\n LINUX,\n MAC;\n\n public static OperatingSystem getOperatingSystem() {\n String osName = System.getProperty(\"os.name\").toLowerCase();\n if (osName.contains(\"win\")) {\n return WINDOWS;\n } else if (osName.contains(\"nix\") || osName.contains(\"nux\") || osName.contains(\"aix\")) {\n return LINUX;\n } else if (osName.contains(\"mac\")) {\n return MAC;\n } else {\n throw new RuntimeException(\"지원하지 않는 운영체제입니다. (현재 운영체제: \" + osName + \")\");\n }\n }\n}" }, { "identifier": "BaekjoonProblemParser", "path": "src/main/java/kr/huni/problem_parser/BaekjoonProblemParser.java", "snippet": "public class BaekjoonProblemParser {\n\n static final String PROBLEM_URL = \"https://www.acmicpc.net/problem/\";\n static final String USER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) \"\n + \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\";\n static final String PROBLEM_TITLE_SELECTOR = \"span#problem_title\";\n static final String PROBLEM_INPUT_SELECTOR = \"pre[id^=sample-input]\";\n static final String PROBLEM_OUTPUT_SELECTOR = \"pre[id^=sample-output]\";\n private final WebParser webParser;\n\n /**\n * 생성자\n *\n * @param webParser 파싱에 사용할 WebParser\n */\n public BaekjoonProblemParser(WebParser webParser) {\n this.webParser = webParser;\n }\n\n /**\n * 문제 번호를 받아 해당 문제를 파싱합니다.\n *\n * @param problemNumber 백준 문제 번호\n * @return Problem 객체\n */\n public Problem parse(int problemNumber) {\n String title = webParser.parse(PROBLEM_TITLE_SELECTOR)[0];\n final ArrayList<TestCase> testCases = new ArrayList<>();\n\n String[] inputs = webParser.parse(PROBLEM_INPUT_SELECTOR);\n String[] outputs = webParser.parse(PROBLEM_OUTPUT_SELECTOR);\n\n assert inputs.length == outputs.length;\n for (int i = 0; i < inputs.length; i++) {\n testCases.add(new TestCase(inputs[i], outputs[i]));\n }\n\n return new Problem(problemNumber, title, testCases);\n }\n\n}" }, { "identifier": "Problem", "path": "src/main/java/kr/huni/problem_parser/Problem.java", "snippet": "@Getter\npublic class Problem {\n\n private final int number;\n private final String title;\n private final String sourceRootDirectory;\n private final List<TestCase> testCases;\n\n public Problem(int number, String title, List<TestCase> testCases) {\n UserConfiguration configuration = UserConfigurationLoader.getInstance();\n\n this.number = number;\n this.title = title;\n this.sourceRootDirectory = configuration.srcDirPrefix.getValue() + number;\n this.testCases = testCases;\n }\n\n}" } ]
import java.io.IOException; import kr.huni.code_generator.CodeGenerator; import kr.huni.code_generator.GeneratedCode; import kr.huni.code_runner.CodeOpenManager; import kr.huni.file_generator.JavaSourceCodeFile; import kr.huni.os.OperatingSystem; import kr.huni.problem_parser.BaekjoonProblemParser; import kr.huni.problem_parser.Problem; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
1,168
package kr.huni; @Slf4j @RequiredArgsConstructor public class BojStarter {
package kr.huni; @Slf4j @RequiredArgsConstructor public class BojStarter {
private final CodeOpenManager codeOpenManager;
1
2023-12-22 09:23:38+00:00
2k
ydb-platform/ydb-java-dialects
hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/BaseTest.java
[ { "identifier": "YdbDialect", "path": "hibernate-dialect-v5/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java", "snippet": "public class YdbDialect extends Dialect {\n private static final int IN_EXPRESSION_COUNT_LIMIT = 10_000;\n\n private static final Exporter<ForeignKey> FOREIGN_KEY_EMPTY_EXPORTER = new EmptyExporter<>();\n\n public YdbDialect() {\n registerColumnType(Types.BIT, \"Bool\");\n registerColumnType(Types.BOOLEAN, \"Bool\");\n registerColumnType(Types.TINYINT, \"Int8\");\n registerColumnType(Types.SMALLINT, \"Int16\");\n registerColumnType(Types.INTEGER, \"Int32\");\n registerColumnType(Types.BIGINT, \"Int64\");\n registerColumnType(Types.FLOAT, \"Float\");\n registerColumnType(Types.DOUBLE, \"Double\");\n registerColumnType(Types.NUMERIC, \"Decimal (22,9)\");\n registerColumnType(Types.DECIMAL, \"Decimal (22,9)\");\n registerColumnType(Types.REAL, \"Float\");\n\n registerColumnType(Types.DATE, \"Date\");\n registerColumnType(Types.TIME, \"Datetime\");\n registerColumnType(Types.TIMESTAMP, \"Timestamp\");\n\n registerColumnType(Types.VARBINARY, \"Bytes\");\n registerColumnType(Types.LONGVARBINARY, \"Bytes\");\n registerColumnType(Types.BLOB, \"Bytes\");\n registerColumnType(Types.BINARY, \"Bytes\");\n\n registerColumnType(Types.CHAR, \"Text\");\n registerColumnType(Types.VARCHAR, \"Text\");\n registerColumnType(Types.LONGVARCHAR, \"Text\");\n registerColumnType(Types.CLOB, \"Text\");\n\n registerColumnType(Types.NCHAR, \"Text\");\n registerColumnType(Types.NVARCHAR, \"Text\");\n registerColumnType(Types.LONGNVARCHAR, \"Text\");\n registerColumnType(Types.NCLOB, \"Text\");\n\n registerColumnType(Types.TIME_WITH_TIMEZONE, \"TzDateTime\");\n registerColumnType(Types.TIMESTAMP_WITH_TIMEZONE, \"TzTimestamp\");\n }\n\n @Override\n public LimitHandler getLimitHandler() {\n return LimitOffsetLimitHandler.INSTANCE;\n }\n\n @Override\n public Exporter<ForeignKey> getForeignKeyExporter() {\n return FOREIGN_KEY_EMPTY_EXPORTER;\n }\n\n @Override\n public boolean supportsLockTimeouts() {\n return false;\n }\n\n @Override\n public boolean supportsOuterJoinForUpdate() {\n return false;\n }\n\n @Override\n public boolean supportsUnionAll() {\n return true;\n }\n\n @Override\n public boolean supportsCaseInsensitiveLike() {\n return true;\n }\n\n @Override\n public String getCaseInsensitiveLike() {\n return \"ilike\";\n }\n\n @Override\n public String toBooleanValueString(boolean bool) {\n return String.valueOf(bool);\n }\n\n @Override\n public NameQualifierSupport getNameQualifierSupport() {\n return NameQualifierSupport.NONE;\n }\n\n @Override\n public char openQuote() {\n return '`';\n }\n\n @Override\n public char closeQuote() {\n return '`';\n }\n\n @Override\n public String getAddColumnString() {\n return \"add column\";\n }\n\n @Override\n public boolean supportsSelectAliasInGroupByClause() {\n return true;\n }\n\n @Override\n public boolean supportsPartitionBy() {\n return true;\n }\n\n @Override\n public boolean supportsValuesList() {\n return true;\n }\n\n @Override\n public boolean supportsExistsInSelect() {\n return false;\n }\n\n @Override\n public int getInExpressionCountLimit() {\n return IN_EXPRESSION_COUNT_LIMIT;\n }\n}" }, { "identifier": "Group", "path": "hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/entity/Group.java", "snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@Table(name = \"Groups\")\npublic class Group {\n\n @Id\n private int groupId;\n\n @Column(name = \"name\", unique = true)\n private String name;\n}" }, { "identifier": "Student", "path": "hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/entity/Student.java", "snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@EqualsAndHashCode\n@Table(name = \"Students\")\npublic class Student {\n\n @Id\n private int studentId;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"groupId\")\n private int groupId;\n}" } ]
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.RegisterExtension; import tech.ydb.hibernate.dialect.YdbDialect; import tech.ydb.hibernate.entity.Group; import tech.ydb.hibernate.entity.Student; import tech.ydb.jdbc.YdbDriver; import tech.ydb.test.junit5.YdbHelperExtension; import javax.persistence.EntityManager; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Stream;
1,476
package tech.ydb.hibernate; /** * @author Kirill Kurdyukov */ public abstract class BaseTest { @RegisterExtension public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension(); protected static SessionFactory SESSION_FACTORY; @BeforeAll static void beforeAll() { StringBuilder jdbc = new StringBuilder("jdbc:ydb:") .append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://") .append(YDB_HELPER_EXTENSION.endpoint()) .append(YDB_HELPER_EXTENSION.database()); if (YDB_HELPER_EXTENSION.authToken() != null) { jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken()); } Properties properties = new Properties(); properties.put(Environment.DRIVER, YdbDriver.class.getName()); properties.put(Environment.URL, jdbc.toString()); properties.put(Environment.DIALECT, YdbDialect.class.getName()); properties.put(Environment.HBM2DDL_AUTO, "create"); properties.put(Environment.SHOW_SQL, true); SESSION_FACTORY = new Configuration().addProperties(properties)
package tech.ydb.hibernate; /** * @author Kirill Kurdyukov */ public abstract class BaseTest { @RegisterExtension public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension(); protected static SessionFactory SESSION_FACTORY; @BeforeAll static void beforeAll() { StringBuilder jdbc = new StringBuilder("jdbc:ydb:") .append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://") .append(YDB_HELPER_EXTENSION.endpoint()) .append(YDB_HELPER_EXTENSION.database()); if (YDB_HELPER_EXTENSION.authToken() != null) { jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken()); } Properties properties = new Properties(); properties.put(Environment.DRIVER, YdbDriver.class.getName()); properties.put(Environment.URL, jdbc.toString()); properties.put(Environment.DIALECT, YdbDialect.class.getName()); properties.put(Environment.HBM2DDL_AUTO, "create"); properties.put(Environment.SHOW_SQL, true); SESSION_FACTORY = new Configuration().addProperties(properties)
.addAnnotatedClass(Student.class)
2
2023-12-25 18:31:13+00:00
2k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/datagen/ItemTagsProvider.java
[ { "identifier": "GlideItemTags", "path": "src/main/java/eu/pb4/glideaway/item/GlideItemTags.java", "snippet": "public class GlideItemTags {\n public static final TagKey<Item> HANG_GLIDERS = of(\"hand_gliders\");\n public static final TagKey<Item> SPECIAL_HANG_GLIDERS = of(\"special_hand_gliders\");\n private static TagKey<Item> of(String path) {\n return TagKey.of(RegistryKeys.ITEM, ModInit.id(path));\n }\n}" }, { "identifier": "GlideItems", "path": "src/main/java/eu/pb4/glideaway/item/GlideItems.java", "snippet": "public class GlideItems {\n\n public static final WindInABottleItem WIND_IN_A_BOTTLE = register(\"wind_in_a_bottle\", new WindInABottleItem(new Item.Settings().maxCount(2), true));\n public static final WindInABottleItem INFINITE_WIND_IN_A_BOTTLE = register(\"infinite_wind_in_a_bottle\", new WindInABottleItem(new Item.Settings().maxCount(1), false));\n public static final DyeableHangGliderItem HANG_GLIDER = register(\"hang_glider\", new DyeableHangGliderItem(new Item.Settings().maxDamage(250)));\n public static final ParticleHangGliderItem CHERRY_HANG_GLIDER = register(\"cherry_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.CHERRY_LEAVES));\n public static final ParticleHangGliderItem SCULK_HANG_GLIDER = register(\"sculk_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.SCULK_CHARGE_POP));\n public static final ParticleHangGliderItem AZALEA_HANG_GLIDER = register(\"azalea_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.SPORE_BLOSSOM_AIR));\n\n public static void register() {\n PolymerItemGroupUtils.registerPolymerItemGroup(new Identifier(ModInit.ID, \"a_group\"), ItemGroup.create(ItemGroup.Row.BOTTOM, -1)\n .icon(HANG_GLIDER::getDefaultStack)\n .displayName(Text.translatable(\"itemgroup.\" + ModInit.ID))\n .entries(((context, entries) -> {\n entries.add(HANG_GLIDER);\n for (var color : DyeColor.values()) {\n if (color != DyeColor.WHITE) {\n var glider = HANG_GLIDER.getDefaultStack();\n var c = color.getColorComponents();\n HANG_GLIDER.setColor(glider, MathHelper.packRgb(c[0], c[1], c[2]));\n entries.add(glider);\n }\n }\n entries.add(CHERRY_HANG_GLIDER);\n entries.add(SCULK_HANG_GLIDER);\n entries.add(AZALEA_HANG_GLIDER);\n\n entries.add(WIND_IN_A_BOTTLE);\n entries.add(INFINITE_WIND_IN_A_BOTTLE);\n })).build()\n );\n\n UseEntityCallback.EVENT.register(WIND_IN_A_BOTTLE::useOnEntityEvent);\n\n TradeOfferHelper.registerWanderingTraderOffers(2, (b) -> {\n b.add(new TradeOffers.SellItemFactory(GlideItems.AZALEA_HANG_GLIDER, 16, 1, 1, 5));\n b.add(new TradeOffers.SellItemFactory(GlideItems.CHERRY_HANG_GLIDER, 16, 1, 1, 5));\n b.add(new TradeOffers.SellItemFactory(GlideItems.SCULK_HANG_GLIDER, 16, 1, 1, 5));\n });\n\n TradeOfferHelper.registerRebalancedWanderingTraderOffers((b) -> {\n b.pool(id(\"hang_gliders\"), 1,\n new TradeOffers.SellItemFactory(GlideItems.AZALEA_HANG_GLIDER, 16, 1, 1, 5),\n new TradeOffers.SellItemFactory(GlideItems.CHERRY_HANG_GLIDER, 16, 1, 1, 5),\n new TradeOffers.SellItemFactory(GlideItems.SCULK_HANG_GLIDER, 16, 1, 1, 5)\n );\n });\n }\n\n public static <T extends Item> T register(String path, T item) {\n Registry.register(Registries.ITEM, new Identifier(ModInit.ID, path), item);\n return item;\n }\n\n public static <E extends Block & PolymerBlock> BlockItem register(E block) {\n var id = Registries.BLOCK.getId(block);\n BlockItem item;\n if (block instanceof MultiBlock multiBlock) {\n item = new MultiBlockItem(multiBlock, new Item.Settings());\n } else {\n item = new FactoryBlockItem(block, new Item.Settings());\n }\n\n Registry.register(Registries.ITEM, id, item);\n return item;\n }\n}" } ]
import eu.pb4.glideaway.item.GlideItemTags; import eu.pb4.glideaway.item.GlideItems; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider; import net.minecraft.registry.RegistryWrapper; import org.jetbrains.annotations.Nullable; import java.util.concurrent.CompletableFuture;
1,296
package eu.pb4.glideaway.datagen; class ItemTagsProvider extends FabricTagProvider.ItemTagProvider { public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) { super(output, registriesFuture, blockTagProvider); } @Override protected void configure(RegistryWrapper.WrapperLookup arg) {
package eu.pb4.glideaway.datagen; class ItemTagsProvider extends FabricTagProvider.ItemTagProvider { public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) { super(output, registriesFuture, blockTagProvider); } @Override protected void configure(RegistryWrapper.WrapperLookup arg) {
this.getOrCreateTagBuilder(GlideItemTags.HANG_GLIDERS)
0
2023-12-22 11:00:52+00:00
2k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/business/utils/ExceptionGenerationUtils.java
[ { "identifier": "AuthenticationException", "path": "src/main/java/es/storeapp/business/exceptions/AuthenticationException.java", "snippet": "public class AuthenticationException extends Exception {\n \n private static final long serialVersionUID = 9047626511480506926L;\n\n public AuthenticationException(String message) {\n super(message);\n }\n \n}" }, { "identifier": "DuplicatedResourceException", "path": "src/main/java/es/storeapp/business/exceptions/DuplicatedResourceException.java", "snippet": "public class DuplicatedResourceException extends Exception {\n \n private static final long serialVersionUID = 6896927410877749980L;\n\n private final String resource;\n private final String value;\n\n public DuplicatedResourceException(String resource, String value, String message) {\n super(message);\n this.resource = resource;\n this.value = value;\n }\n\n public Object getResource() {\n return resource;\n }\n\n public Object getValue() {\n return value;\n }\n \n}" }, { "identifier": "InstanceNotFoundException", "path": "src/main/java/es/storeapp/business/exceptions/InstanceNotFoundException.java", "snippet": "public class InstanceNotFoundException extends Exception {\n\n private static final long serialVersionUID = -4208426212843868046L;\n\n private final Long id;\n private final String type;\n\n public InstanceNotFoundException(Long id, String type, String message) {\n super(message);\n this.id = id;\n this.type = type;\n }\n\n public Object getId() {\n return id;\n }\n\n public String getType() {\n return type;\n }\n \n}" }, { "identifier": "InvalidStateException", "path": "src/main/java/es/storeapp/business/exceptions/InvalidStateException.java", "snippet": "public class InvalidStateException extends Exception {\n\n private static final long serialVersionUID = 3026551774263871416L;\n\n public InvalidStateException(String message) {\n super(message);\n }\n \n}" } ]
import es.storeapp.business.exceptions.AuthenticationException; import es.storeapp.business.exceptions.DuplicatedResourceException; import es.storeapp.business.exceptions.InstanceNotFoundException; import es.storeapp.business.exceptions.InvalidStateException; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component;
729
package es.storeapp.business.utils; @Component public class ExceptionGenerationUtils { @Autowired private MessageSource messageSource; public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey) throws InstanceNotFoundException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale); return new InstanceNotFoundException(id, type, message); } public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey) throws DuplicatedResourceException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale); return new DuplicatedResourceException(resource, value, message); } public AuthenticationException toAuthenticationException(String messageKey, String user) throws AuthenticationException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[] {user}, locale); return new AuthenticationException(message); }
package es.storeapp.business.utils; @Component public class ExceptionGenerationUtils { @Autowired private MessageSource messageSource; public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey) throws InstanceNotFoundException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale); return new InstanceNotFoundException(id, type, message); } public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey) throws DuplicatedResourceException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale); return new DuplicatedResourceException(resource, value, message); } public AuthenticationException toAuthenticationException(String messageKey, String user) throws AuthenticationException { Locale locale = LocaleContextHolder.getLocale(); String message = messageSource.getMessage(messageKey, new Object[] {user}, locale); return new AuthenticationException(message); }
public InvalidStateException toInvalidStateException(String messageKey) throws InvalidStateException {
3
2023-12-24 19:24:49+00:00
2k
Brath1024/SensiCheck
src/main/java/cn/brath/sensicheck/strategy/SensiCheckContext.java
[ { "identifier": "SensiCheckType", "path": "src/main/java/cn/brath/sensicheck/constants/SensiCheckType.java", "snippet": "public enum SensiCheckType {\n\n /**\n * 替换\n */\n REPLACE,\n\n /**\n * 抛异常\n */\n ERROR,\n\n /**\n * 不做动作\n */\n NON,\n\n}" }, { "identifier": "SenFilterErrorImpl", "path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterErrorImpl.java", "snippet": "public class SenFilterErrorImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.ERROR;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n String sens = super.sensiHolder.existsStr(value);\n if (sens != null) throw new SenException(errorText + \" 可能涉及到的敏感词:[\" + sens + \"]\", value);\n return value;\n }\n\n}" }, { "identifier": "SenFilterNonImpl", "path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterNonImpl.java", "snippet": "public class SenFilterNonImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.NON;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n return value;\n }\n\n}" }, { "identifier": "SenFilterReplaceImpl", "path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterReplaceImpl.java", "snippet": "public class SenFilterReplaceImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.REPLACE;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n return super.sensiHolder.replace(value, this.replaceValue);\n }\n}" } ]
import cn.brath.sensicheck.constants.SensiCheckType; import cn.brath.sensicheck.strategy.impl.SenFilterErrorImpl; import cn.brath.sensicheck.strategy.impl.SenFilterNonImpl; import cn.brath.sensicheck.strategy.impl.SenFilterReplaceImpl; import java.util.HashMap; import java.util.List; import java.util.Map;
770
package cn.brath.sensicheck.strategy; /** * 策略器上下文处理 * * @author Brath * @since 2023/7/28 15:44 */ public class SensiCheckContext { private final Map<SensiCheckType, SensiCheckStrategy> strategyMap; private static SensiCheckContext instance = null; private SensiCheckContext() { this.strategyMap = new HashMap<>(); this.strategyMap.put(SensiCheckType.REPLACE, new SenFilterReplaceImpl()); this.strategyMap.put(SensiCheckType.ERROR, new SenFilterErrorImpl());
package cn.brath.sensicheck.strategy; /** * 策略器上下文处理 * * @author Brath * @since 2023/7/28 15:44 */ public class SensiCheckContext { private final Map<SensiCheckType, SensiCheckStrategy> strategyMap; private static SensiCheckContext instance = null; private SensiCheckContext() { this.strategyMap = new HashMap<>(); this.strategyMap.put(SensiCheckType.REPLACE, new SenFilterReplaceImpl()); this.strategyMap.put(SensiCheckType.ERROR, new SenFilterErrorImpl());
this.strategyMap.put(SensiCheckType.NON, new SenFilterNonImpl());
2
2023-12-28 04:50:04+00:00
2k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/chessComponent/SquareComponent.java
[ { "identifier": "ClickController", "path": "CS109_2022_Fall/Chess/controller/ClickController.java", "snippet": "public class ClickController {\r\n private final Chessboard chessboard;\r\n private SquareComponent first;\r\n\r\n public ClickController(Chessboard chessboard) {\r\n this.chessboard = chessboard;\r\n }\r\n\r\n private int count = 0;\r\n\r\n public void onClick(SquareComponent squareComponent) {\r\n Main.playNotifyMusic(\"click\");\r\n\r\n //判断第一次点击\r\n if (first == null) {\r\n if (handleFirst(squareComponent)) {\r\n squareComponent.setSelected(true);\r\n first = squareComponent;\r\n first.repaint();//还没有实现显示可以当前棋子可以移动的坐标\r\n }\r\n } else {\r\n if (first == squareComponent) { // 再次点击取消选取\r\n squareComponent.setSelected(false);\r\n SquareComponent recordFirst = first;\r\n first = null;\r\n recordFirst.repaint();\r\n } else if (handleSecond(squareComponent)) {\r\n //repaint in swap chess method.\r\n chessboard.swapChessComponents(first, squareComponent);\r\n chessboard.clickController.swapPlayer();\r\n\r\n first.setSelected(false);\r\n first = null;\r\n }\r\n }\r\n }\r\n\r\n\r\n /**\r\n * @param squareComponent 目标选取的棋子\r\n * @return 目标选取的棋子是否与棋盘记录的当前行棋方颜色相同\r\n */\r\n\r\n private boolean handleFirst(SquareComponent squareComponent) {\r\n if (!squareComponent.isReversal()) {\r\n squareComponent.setReversal(true);\r\n squareComponent.setCheating(false);\r\n System.out.printf(\"onClick to reverse a chess [%d,%d]\\n\", squareComponent.getChessboardPoint().getX(), squareComponent.getChessboardPoint().getY());\r\n chessboard.isPlayerDo = true;\r\n Chessboard.isComReverse = true;\r\n Chessboard.Now.push(squareComponent);\r\n squareComponent.repaint();\r\n if (count == 0) {\r\n count++;\r\n chessboard.setCurrentColor(squareComponent.getChessColor());\r\n chessboard.setPlayerColor(squareComponent.getChessColor());\r\n if (squareComponent.getChessColor() == ChessColor.BLACK) {\r\n JOptionPane.showMessageDialog(null, \"你是黑色,开始博弈吧!\");\r\n chessboard.setEnemyColor(ChessColor.RED);\r\n } else {\r\n chessboard.setEnemyColor(ChessColor.BLACK);\r\n JOptionPane.showMessageDialog(null, \"你是红色,开始博弈吧!\");\r\n }\r\n }\r\n chessboard.clickController.swapPlayer();\r\n try {\r\n Thread.currentThread().sleep(1000);\r\n } catch (Exception e) {\r\n }\r\n return false;\r\n }\r\n return squareComponent.getChessColor() == chessboard.getCurrentColor();\r\n }\r\n\r\n /**\r\n * @param squareComponent first棋子目标移动到的棋子second\r\n * @return first棋子是否能够移动到second棋子位置\r\n */\r\n\r\n /*\r\n *\r\n * 对局主逻辑填充在这里\r\n */\r\n private boolean handleSecond(SquareComponent squareComponent) {\r\n\r\n return first.canMoveTo(chessboard.getChessComponents(), squareComponent.getChessboardPoint(), first.getChessboardPoint(), chessboard.getPlayerColor());\r\n }\r\n\r\n public void swapPlayer() {\r\n chessboard.setCurrentColor(chessboard.getCurrentColor() == ChessColor.BLACK ? ChessColor.RED : ChessColor.BLACK);\r\n ChessGameFrame.getStatusLabel().setText(String.format(\"%s走棋\", (chessboard.getCurrentColor().getName().equals(\"BLACK\")) ? \"黑\" : \"红\"));\r\n ChessGameFrame.getStatusLabel().setForeground((chessboard.getCurrentColor() == ChessColor.BLACK) ? Main.getThemeColor(\"indicatorBlack\") : ChessColor.RED.getColor());\r\n if (chessboard.getCurrentColor() == chessboard.getEnemyColor() && (chessboard.ModeChoice == 1 || chessboard.ModeChoice == 2)) {\r\n chessboard.Comround();\r\n swapPlayer();\r\n }\r\n }\r\n}\r" }, { "identifier": "ChessColor", "path": "CS109_2022_Fall/Chess/model/ChessColor.java", "snippet": "public enum ChessColor {\r\n BLACK(\"BLACK\", Color.decode(\"#251f1e\")), RED(\"RED\", Color.decode(\"#e83505\")), NONE(\"No Player\", Color.WHITE);\r\n\r\n private final String name;\r\n private final Color color;\r\n\r\n ChessColor(String name, Color color) {\r\n this.name = name;\r\n this.color = color;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public Color getColor() {\r\n return color;\r\n }\r\n}\r" }, { "identifier": "ChessboardPoint", "path": "CS109_2022_Fall/Chess/model/ChessboardPoint.java", "snippet": "public class ChessboardPoint {\r\n private int x, y;\r\n\r\n /**\r\n * @param x: row\r\n * @param y: col\r\n */\r\n public ChessboardPoint(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n public int getX() {\r\n return x;\r\n }\r\n\r\n public int getY() {\r\n return y;\r\n }\r\n\r\n\r\n @Override\r\n public String toString() {\r\n return \"(\" + x + \",\" + y + \") \" + \"on the chessboard is clicked!\";\r\n }\r\n}\r" }, { "identifier": "serifFont", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public static Font titleFont, sansFont, serifFont;\r" } ]
import Chess.controller.ClickController; import Chess.model.ChessColor; import Chess.model.ChessboardPoint; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import static Chess.Main.serifFont;
1,481
package Chess.chessComponent; /** * 这个类是一个抽象类,主要表示8*4棋盘上每个格子的棋子情况。 * 有两个子类: * 1. EmptySlotComponent: 空棋子 * 2. ChessComponent: 表示非空棋子 */ public abstract class SquareComponent extends JComponent { private static final Color squareColor = new Color(250, 220, 190, 0); protected static int spacingLength;
package Chess.chessComponent; /** * 这个类是一个抽象类,主要表示8*4棋盘上每个格子的棋子情况。 * 有两个子类: * 1. EmptySlotComponent: 空棋子 * 2. ChessComponent: 表示非空棋子 */ public abstract class SquareComponent extends JComponent { private static final Color squareColor = new Color(250, 220, 190, 0); protected static int spacingLength;
protected static final Font CHESS_FONT = serifFont.deriveFont(Font.BOLD, 30);
3
2023-12-31 05:50:13+00:00
2k
Ertinox45/ImmersiveAddon
src/main/java/fr/dynamx/addons/immersive/common/network/ImmersiveAddonPacketHandler.java
[ { "identifier": "ImmersiveAddon", "path": "src/main/java/fr/dynamx/addons/immersive/ImmersiveAddon.java", "snippet": "@Mod(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, version = \"1.0\", dependencies = \"before: dynamxmod\")\n@DynamXAddon(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, version = \"1.0\")\npublic class ImmersiveAddon {\n public static final String ID = \"dynamx_immersive\";\n public static final String NAME = \"ImmersiveAddon\";\n\n public static RadioPlayer radioPlayer = new RadioPlayer();\n\n @DynamXAddon.AddonEventSubscriber\n public static void initAddon() {\n //if (FMLCommonHandler.instance().getSide().isClient()) {}\n }\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n ModSyncedDataKeys.initKeys();\n MinecraftForge.EVENT_BUS.register(new HandAnimationEventHandler());\n if (event.getSide().isClient()) {\n MinecraftForge.EVENT_BUS.register(new HandAnimClientEventHandler());\n //MinecraftForge.EVENT_BUS.register(new Common());\n if (event.getSide().isClient()) {\n // MinecraftForge.EVENT_BUS.register(new Client());\n KeyBindings.register();\n }\n\n ImmersiveAddonConfig.init(event.getSuggestedConfigurationFile());\n ImmersiveAddonPacketHandler.getInstance().registerPackets();\n\n //network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID);\n //network.registerMessage(PacketAttachTrailer.Handler.class, PacketAttachTrailer.class, 0, Side.SERVER);\n }\n }\n\n @Mod.EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n }\n}" }, { "identifier": "SendRadioFreqConfig", "path": "src/main/java/fr/dynamx/addons/immersive/common/network/packets/SendRadioFreqConfig.java", "snippet": "public class SendRadioFreqConfig implements IMessage {\n\n private String json;\n\n public SendRadioFreqConfig() {\n }\n\n public SendRadioFreqConfig(String json) {\n this.json = json;\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n json = ByteBufUtils.readUTF8String(buf);\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n ByteBufUtils.writeUTF8String(buf, json);\n }\n\n public static class Handler implements IMessageHandler<SendRadioFreqConfig, IMessage> {\n\n @Override\n public IMessage onMessage(SendRadioFreqConfig message, MessageContext ctx) {\n try\n {\n ConfigReader.writeToFileString(message.json);\n ConfigReader.readFromFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n }\n}" } ]
import fr.dynamx.addons.immersive.ImmersiveAddon; import fr.dynamx.addons.immersive.common.network.packets.SendRadioFreqConfig; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side;
879
package fr.dynamx.addons.immersive.common.network; public class ImmersiveAddonPacketHandler { private static ImmersiveAddonPacketHandler instance; private SimpleNetworkWrapper network; private int nextID = 0; public static ImmersiveAddonPacketHandler getInstance() { if (instance == null) instance = new ImmersiveAddonPacketHandler(); return instance; } public SimpleNetworkWrapper getNetwork() { return network; } public void registerPackets() { this.network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID.toUpperCase());
package fr.dynamx.addons.immersive.common.network; public class ImmersiveAddonPacketHandler { private static ImmersiveAddonPacketHandler instance; private SimpleNetworkWrapper network; private int nextID = 0; public static ImmersiveAddonPacketHandler getInstance() { if (instance == null) instance = new ImmersiveAddonPacketHandler(); return instance; } public SimpleNetworkWrapper getNetwork() { return network; } public void registerPackets() { this.network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID.toUpperCase());
this.registerPacket(SendRadioFreqConfig.Handler.class, SendRadioFreqConfig.class, Side.CLIENT);
1
2023-12-30 08:33:54+00:00
2k
Patbox/serveruifix
src/main/java/eu/pb4/serveruifix/polydex/PolydexCompatImpl.java
[ { "identifier": "GuiTextures", "path": "src/main/java/eu/pb4/serveruifix/util/GuiTextures.java", "snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> STONECUTTER = background(\"stonecutter\");\n\n public static final Supplier<GuiElementBuilder> POLYDEX_BUTTON = icon32(\"polydex\");\n public static final Supplier<GuiElementBuilder> LEFT_BUTTON = icon16(\"left\");\n public static final Supplier<GuiElementBuilder> RIGHT_BUTTON = icon16(\"right\");\n\n public static void register() {\n }\n\n\n public record Progress(GuiElement[] elements) {\n\n public GuiElement get(float progress) {\n return elements[Math.min((int) (progress * elements.length), elements.length - 1)];\n }\n\n public static Progress createVertical(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n public static Progress createVertical32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n }\n\n}" }, { "identifier": "GuiUtils", "path": "src/main/java/eu/pb4/serveruifix/util/GuiUtils.java", "snippet": "public class GuiUtils {\n public static final GuiElement EMPTY = GuiElement.EMPTY;\n\n public static final void playClickSound(ServerPlayerEntity player) {\n player.playSound(SoundEvents.UI_BUTTON_CLICK.value(), SoundCategory.MASTER, 0.5f, 1);\n }\n}" } ]
import eu.pb4.polydex.api.v1.recipe.*; import eu.pb4.serveruifix.util.GuiTextures; import eu.pb4.serveruifix.util.GuiUtils; import eu.pb4.sgui.api.elements.GuiElement; import net.minecraft.recipe.RecipeType; import net.minecraft.text.Text;
1,076
package eu.pb4.serveruifix.polydex; public class PolydexCompatImpl { public static void register() { } public static GuiElement getButton(RecipeType<?> type) { var category = PolydexCategory.of(type); return GuiTextures.POLYDEX_BUTTON.get() .setName(Text.translatable("text.serveruifix.recipes")) .setCallback((index, type1, action, gui) -> { PolydexPageUtils.openCategoryUi(gui.getPlayer(), category, gui::open);
package eu.pb4.serveruifix.polydex; public class PolydexCompatImpl { public static void register() { } public static GuiElement getButton(RecipeType<?> type) { var category = PolydexCategory.of(type); return GuiTextures.POLYDEX_BUTTON.get() .setName(Text.translatable("text.serveruifix.recipes")) .setCallback((index, type1, action, gui) -> { PolydexPageUtils.openCategoryUi(gui.getPlayer(), category, gui::open);
GuiUtils.playClickSound(gui.getPlayer());
1
2023-12-28 23:01:30+00:00
2k
psobiech/opengr8on
tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPDataPacket.java
[ { "identifier": "TFTPPacketType", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPPacketType.java", "snippet": "public enum TFTPPacketType {\n UNKNOWN(\n 0,\n payload -> {\n throw new TFTPPacketException(\"Bad packet. Invalid TFTP operator code.\");\n }\n ),\n READ_REQUEST(1, TFTPReadRequestPacket::new),\n WRITE_REQUEST(2, TFTPWriteRequestPacket::new),\n DATA(3, TFTPDataPacket::new),\n ACKNOWLEDGEMENT(4, TFTPAckPacket::new),\n ERROR(5, TFTPErrorPacket::new),\n //\n ;\n\n private final byte packetType;\n\n private final Parser parser;\n\n TFTPPacketType(int packetType, Parser parser) {\n if (packetType < 0 || packetType > 0xFF) {\n throw new IllegalArgumentException();\n }\n\n this.packetType = (byte) (packetType & 0xFF);\n this.parser = parser;\n }\n\n public byte packetType() {\n return packetType;\n }\n\n public TFTPPacket parse(Payload payload) throws TFTPPacketException {\n return parser.parse(payload);\n }\n\n public static TFTPPacketType ofPacketType(byte packetType) {\n for (TFTPPacketType value : values()) {\n if (value.packetType() == packetType) {\n return value;\n }\n }\n\n return UNKNOWN;\n }\n\n @FunctionalInterface\n private interface Parser {\n TFTPPacket parse(Payload payload) throws TFTPPacketException;\n }\n}" }, { "identifier": "TFTPPacketException", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/exceptions/TFTPPacketException.java", "snippet": "public class TFTPPacketException extends Exception {\n private final TFTPErrorType error;\n\n public TFTPPacketException(TFTPErrorPacket errorPacket) {\n this(errorPacket.getError(), errorPacket.getMessage());\n }\n\n public TFTPPacketException(TFTPErrorType error, IOException exception) {\n super(exception);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message) {\n super(message);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message, Throwable throwable) {\n super(message, throwable);\n\n this.error = error;\n }\n\n public TFTPPacketException(String message) {\n super(message);\n\n this.error = TFTPErrorType.UNDEFINED;\n }\n\n public TFTPErrorPacket asError(InetAddress address, int port) {\n final String message;\n final Throwable cause = getCause();\n if (cause == null) {\n message = getMessage();\n } else {\n message = cause.getClass().getSimpleName() + \": \" + getMessage();\n }\n\n return new TFTPErrorPacket(\n address, port,\n getError(), message\n );\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n}" } ]
import java.io.IOException; import java.io.UncheckedIOException; import java.net.DatagramPacket; import java.net.InetAddress; import pl.psobiech.opengr8on.tftp.TFTPPacketType; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.util.SocketUtil.Payload;
1,107
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.packets; public class TFTPDataPacket extends TFTPBlockPacket { public static final int MAX_DATA_LENGTH = 512; private final int length; private final int offset; private final byte[] buffer; public TFTPDataPacket(Payload payload) throws TFTPPacketException {
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.packets; public class TFTPDataPacket extends TFTPBlockPacket { public static final int MAX_DATA_LENGTH = 512; private final int length; private final int offset; private final byte[] buffer; public TFTPDataPacket(Payload payload) throws TFTPPacketException {
super(TFTPPacketType.DATA, payload.address(), payload.port(), getBlockNumber(payload));
0
2023-12-23 09:56:14+00:00
2k
Daniil-Tsiunchyk/DatsBlack-Hackathon
Gold/src/main/java/org/example/scripts/ScriptCommand.java
[ { "identifier": "ScanResult", "path": "Gold/src/main/java/org/example/models/ScanResult.java", "snippet": "@Data\npublic class ScanResult {\n private ScanData scan;\n private boolean success;\n private Error[] errors;\n\n @Data\n public static class ScanData {\n private Ship[] myShips;\n private Ship[] enemyShips;\n private Zone zone;\n }\n\n @Data\n public static class Ship {\n private int id;\n private int x;\n private int y;\n private int size;\n private int hp;\n private String direction;\n private int speed;\n private int cannonCooldown;\n private int cannonCooldownLeft;\n private int cannonShootSuccessCount;\n private int numberTarget = 0;\n\n public void move() {\n switch (direction.toLowerCase()) {\n case NORTH:\n y -= speed;\n break;\n case SOUTH:\n y += speed;\n break;\n case WEST:\n x -= speed;\n break;\n case EAST:\n x += speed;\n break;\n default:\n System.out.println(\"Неправильное направление: \" + direction);\n break;\n }\n }\n }\n\n @Data\n public static class Zone {\n private int x;\n private int y;\n private int radius;\n }\n\n @Data\n public static class Error {\n private String message;\n }\n}" }, { "identifier": "parseResponse", "path": "Gold/src/main/java/org/example/CommonScripts.java", "snippet": "public static String parseResponse(String responseBody) {\n Response response = gson.fromJson(responseBody, Response.class);\n return response.toString();\n}" }, { "identifier": "Const", "path": "Gold/src/main/java/org/example/Const.java", "snippet": "public class Const {\n public static final HttpClient httpClient = HttpClient.newHttpClient();\n public static final String apiKey = \"a7e670d0-c3ff-4467-96ca-3ffcd79dca89\";\n public static final Gson gson = new Gson();\n public static final String baseUrl = \"https://datsblack.datsteam.dev/api/\";\n public static final String mapUrl = \"https://datsblack.datsteam.dev/json/map/6586b267d01324.88322035.json\";\n public final static int DISTANCE_SCAN = 25;\n public static final String NORTH = \"north\";\n public static final String SOUTH = \"south\";\n public static final String EAST = \"east\";\n public static final String WEST = \"west\";\n public static final int THIS_TICK = 75;\n}" }, { "identifier": "fetchScanResult", "path": "Gold/src/main/java/org/example/scripts/ScriptMap.java", "snippet": "static ScanResult fetchScanResult() throws IOException, InterruptedException {\n HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(baseUrl + \"scan\"))\n .header(\"X-API-Key\", apiKey)\n .build();\n\n HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n\n Gson gson = new Gson();\n return gson.fromJson(response.body(), ScanResult.class);\n}" } ]
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import org.example.models.ScanResult; import java.io.IOException; import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.ArrayList; import java.util.List; import static org.example.CommonScripts.parseResponse; import static org.example.Const.*; import static org.example.scripts.ScriptMap.fetchScanResult;
1,216
package org.example.scripts; public class ScriptCommand { public static final Integer CHANGE_SPEED = null; // Изменяемая скорость public static final Integer ROTATE_ANGLE = null; // Угол поворота public static void main(String[] args) { try { System.out.println("Запуск команды контроля кораблей"); ScanResult scanResult = fetchScanResult(); ScanResult.Ship[] myShips = scanResult.getScan().getMyShips(); // Gson gson = new GsonBuilder().setPrettyPrinting().create(); // String prettyJson = gson.toJson(scanResult); // System.out.println("Обработанный результат сканирования: \n" + prettyJson); sendShipCommands(myShips); } catch (IOException | InterruptedException e) { System.err.println("Ошибка: " + e.getMessage()); } } @Data @AllArgsConstructor static class ShipsWrapper { private List<ShipCommand> ships; } public static void sendShipCommands(ScanResult.Ship[] myShips) throws IOException, InterruptedException { List<ShipCommand> commands = new ArrayList<>(); for (ScanResult.Ship ship : myShips) { ShipCommand command = new ShipCommand(ship.getId(), CHANGE_SPEED, ROTATE_ANGLE); commands.add(command); } ShipsWrapper shipsWrapper = new ShipsWrapper(commands); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(shipsWrapper); System.out.println("Отправляемые команды: " + requestBody); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl + "shipCommand")) .header("X-API-Key", apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
package org.example.scripts; public class ScriptCommand { public static final Integer CHANGE_SPEED = null; // Изменяемая скорость public static final Integer ROTATE_ANGLE = null; // Угол поворота public static void main(String[] args) { try { System.out.println("Запуск команды контроля кораблей"); ScanResult scanResult = fetchScanResult(); ScanResult.Ship[] myShips = scanResult.getScan().getMyShips(); // Gson gson = new GsonBuilder().setPrettyPrinting().create(); // String prettyJson = gson.toJson(scanResult); // System.out.println("Обработанный результат сканирования: \n" + prettyJson); sendShipCommands(myShips); } catch (IOException | InterruptedException e) { System.err.println("Ошибка: " + e.getMessage()); } } @Data @AllArgsConstructor static class ShipsWrapper { private List<ShipCommand> ships; } public static void sendShipCommands(ScanResult.Ship[] myShips) throws IOException, InterruptedException { List<ShipCommand> commands = new ArrayList<>(); for (ScanResult.Ship ship : myShips) { ShipCommand command = new ShipCommand(ship.getId(), CHANGE_SPEED, ROTATE_ANGLE); commands.add(command); } ShipsWrapper shipsWrapper = new ShipsWrapper(commands); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(shipsWrapper); System.out.println("Отправляемые команды: " + requestBody); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl + "shipCommand")) .header("X-API-Key", apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Результат: " + parseResponse(response.body()));
1
2023-12-23 11:29:47+00:00
2k
Pigmice2733/frc-2024
src/main/java/frc/robot/commands/actions/HandoffToShooter.java
[ { "identifier": "AutoConfig", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static class AutoConfig {\n public final static double INTAKE_MOVE_TIME = 3;\n public final static double INTAKE_FEED_TIME = 1;\n public final static double FLYWHEEL_SPINUP_TIME = 3;\n\n}" }, { "identifier": "IntakeState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum IntakeState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n IntakeState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "Intake", "path": "src/main/java/frc/robot/subsystems/Intake.java", "snippet": "public class Intake extends PIDSubsystemBase {\n private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);\n\n public Intake() {\n super(new CANSparkMax(CANConfig.INTAKE_PIVOT, MotorType.kBrushless), IntakeConfig.P, IntakeConfig.I,\n IntakeConfig.D, new Constraints(IntakeConfig.MAX_VELOCITY, IntakeConfig.MAX_ACCELERATION), false,\n IntakeConfig.MOTOR_POSITION_CONVERSION, 50, Constants.INTAKE_TAB, true);\n\n wheelsMotor.restoreFactoryDefaults();\n wheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.INTAKE_TAB, () -> wheelsMotor.get());\n }\n\n /** Sets the intake motor to a percent output (0.0 - 1.0) */\n public void outputToMotor(double percent) {\n wheelsMotor.set(percent);\n }\n\n /** Spins intake wheels to intake balls. */\n public Command runWheelsForward() {\n return Commands.runOnce(() -> outputToMotor(IntakeConfig.WHEELS_SPEED));\n }\n\n /** Spins intake wheels to eject balls. */\n public Command runWheelsBackward() {\n return Commands.runOnce(() -> outputToMotor(-IntakeConfig.WHEELS_SPEED));\n }\n\n /** Sets intake wheels to zero output. */\n public Command stopWheels() {\n return Commands.runOnce(() -> outputToMotor(0));\n }\n\n /** Sets the rotation state of the intake */\n public Command setTargetState(IntakeState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "Shooter", "path": "src/main/java/frc/robot/subsystems/Shooter.java", "snippet": "public class Shooter extends SubsystemBase {\n private final CANSparkMax flywheelsMotor = new CANSparkMax(CANConfig.SHOOTER_MOTOR, MotorType.kBrushless);\n private final CANSparkMax feederMotor = new CANSparkMax(CANConfig.FEEDER_MOTOR, MotorType.kBrushless);\n\n public Shooter() {\n flywheelsMotor.restoreFactoryDefaults();\n flywheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.SHOOTER_TAB, () -> flywheelsMotor.get());\n }\n\n private void outputToFlywheels(double output) {\n flywheelsMotor.set(output);\n }\n\n public Command spinFlywheelsForward() {\n return Commands.runOnce(() -> outputToFlywheels(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFlywheelsBackward() {\n return Commands.runOnce(() -> outputToFlywheels(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFlywheels() {\n return Commands.runOnce(() -> outputToFlywheels(0));\n }\n\n private void outputToFeeder(double output) {\n feederMotor.set(output);\n }\n\n public Command spinFeederForward() {\n return Commands.runOnce(() -> outputToFeeder(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFeederBackward() {\n return Commands.runOnce(() -> outputToFeeder(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFeeder() {\n return Commands.runOnce(() -> outputToFeeder(0));\n }\n}" } ]
import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler; import edu.wpi.first.wpilibj.GenericHID.RumbleType; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.robot.Constants.AutoConfig; import frc.robot.Constants.IntakeConfig.IntakeState; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter;
1,181
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.actions; public class HandoffToShooter extends SequentialCommandGroup { public HandoffToShooter(Intake intake, Shooter shooter) {
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.actions; public class HandoffToShooter extends SequentialCommandGroup { public HandoffToShooter(Intake intake, Shooter shooter) {
addCommands(intake.setTargetState(IntakeState.UP),
1
2023-12-30 06:06:45+00:00
2k
NeckitWin/Medallions
src/main/java/net/neckitwin/medallions/common/block/BlockMegaChest.java
[ { "identifier": "Medallions", "path": "src/main/java/net/neckitwin/medallions/Medallions.java", "snippet": "@Mod(modid = MOD_ID, version = VERSION, name = MOD_NAME)\npublic class Medallions {\n public static final String MOD_ID = \"medallions\";\n public static final String MOD_NAME = \"Medallions\";\n public static final String VERSION = \"1.0\";\n\n @SidedProxy(\n clientSide = \"net.neckitwin.medallions.common.ClientProxy\",\n serverSide = \"net.neckitwin.medallions.common.CommonProxy\"\n )\n public static CommonProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n proxy.preInit(event);\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n }\n}" }, { "identifier": "ModTab", "path": "src/main/java/net/neckitwin/medallions/common/handler/ModTab.java", "snippet": "public class ModTab extends CreativeTabs {\n public static final ModTab INSTANCE = new ModTab();\n\n private ModTab() {\n super(Medallions.MOD_ID);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return ModItems.SHADOWY_MEDALLION;\n }\n}" }, { "identifier": "TileMegaChest", "path": "src/main/java/net/neckitwin/medallions/common/tile/TileMegaChest.java", "snippet": "public class TileMegaChest extends TileEntity {\n private ItemStack stack;\n private static final String INV_TAG = \"inventory\";\n\n @Override\n public void writeToNBT(NBTTagCompound nbt) {\n super.writeToNBT(nbt);\n\n if (stack != null) {\n NBTTagCompound inventoryTag = new NBTTagCompound();\n stack.writeToNBT(inventoryTag);\n nbt.setTag(INV_TAG, inventoryTag);\n }\n }\n\n @Override\n public void readFromNBT(NBTTagCompound nbt) {\n super.readFromNBT(nbt);\n\n if (nbt.hasKey(INV_TAG, Constants.NBT.TAG_COMPOUND)) {\n NBTTagCompound inventoryTag = nbt.getCompoundTag(INV_TAG);\n stack = ItemStack.loadItemStackFromNBT(inventoryTag);\n }\n }\n\n @Override\n public boolean canUpdate() {\n return false;\n }\n\n public boolean hasStack() {\n return stack != null;\n }\n\n public void handleInputStack(EntityPlayer player, ItemStack stack) {\n // Если в StorageTile есть стек, то выполнится действия со взятием предмета из StorageTile\n if (hasStack()) {\n // Если инвентарь заполнен, то предмет будет выброшен, в ином случае будет добавлен игроку в инвентарь.\n if (!player.inventory.addItemStackToInventory(this.stack)) {\n player.dropPlayerItemWithRandomChoice(this.stack, false);\n } else {\n // Иногда бывает, что предмет не отображается в инвентаре после активации блока, данный код исправляет это.\n player.inventoryContainer.detectAndSendChanges();\n }\n // Очищаем стек из StorageTile\n this.stack = null;\n }\n // Если стек в руке не равен null, то он будет положен в кол-ве 1 шт., в StorageTile\n else if (stack != null) {\n // Создаём копию стека и устанавливаем ей размер в 1 шт.\n ItemStack copy = stack.copy();\n copy.stackSize = 1;\n this.stack = copy;\n // Убираем один предмет из инвентаря игрока.\n --stack.stackSize;\n }\n // Не забываем пометить Tile Entity как \"грязный\", чтобы игра сохранила наши данные.\n markDirty();\n }\n}" } ]
import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.neckitwin.medallions.Medallions; import net.neckitwin.medallions.common.handler.ModTab; import net.neckitwin.medallions.common.tile.TileMegaChest;
1,205
package net.neckitwin.medallions.common.block; public class BlockMegaChest extends BlockContainer { public BlockMegaChest() { super(Material.wood); setBlockName("megachest"); setBlockTextureName(Medallions.MOD_ID + ":megachest"); setCreativeTab(ModTab.INSTANCE); } @Override public TileEntity createNewTileEntity(World world, int metadata) {
package net.neckitwin.medallions.common.block; public class BlockMegaChest extends BlockContainer { public BlockMegaChest() { super(Material.wood); setBlockName("megachest"); setBlockTextureName(Medallions.MOD_ID + ":megachest"); setCreativeTab(ModTab.INSTANCE); } @Override public TileEntity createNewTileEntity(World world, int metadata) {
return new TileMegaChest();
2
2023-12-29 23:19:12+00:00
2k
373675032/kaka-shop
src/main/java/world/xuewei/service/impl/CollectionServiceImpl.java
[ { "identifier": "Collection", "path": "src/main/java/world/xuewei/entity/Collection.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Collection implements Serializable {\n\n private static final long serialVersionUID = -94320018064732696L;\n\n /**\n * 主键ID\n */\n private Integer id;\n\n /**\n * 用户ID\n */\n private Integer userId;\n\n /**\n * 商品ID\n */\n private Integer commodityId;\n\n /**\n * 收藏时间\n */\n private Date addTime;\n\n}" }, { "identifier": "BaseService", "path": "src/main/java/world/xuewei/service/BaseService.java", "snippet": "public class BaseService {\n\n @Resource\n protected AddressMapper addressMapper;\n\n @Resource\n protected CartMapper cartMapper;\n\n @Resource\n protected ClassifyMapper classifyMapper;\n\n @Resource\n protected CollectionMapper collectionMapper;\n\n @Resource\n protected CommodityCommentMapper commodityCommentMapper;\n\n @Resource\n protected CommodityMapper commodityMapper;\n\n @Resource\n protected OrderMapper orderMapper;\n\n @Resource\n protected UserMapper userMapper;\n\n}" }, { "identifier": "CollectionService", "path": "src/main/java/world/xuewei/service/CollectionService.java", "snippet": "public interface CollectionService {\n\n /**\n * @param collection 实例对象\n * @return 是否成功\n * 添加Collection\n */\n boolean insert(Collection collection);\n\n /**\n * @param id 主键\n * @return 是否成功\n * 删除Collection\n */\n boolean deleteById(Integer id);\n\n /**\n * @param id 主键\n * @return 实例对象\n * 查询单条数据\n */\n Collection getById(Integer id);\n\n /**\n * @return 对象列表\n * 查询全部数据\n * 分页使用MyBatis的插件实现\n */\n List<Collection> listCollections();\n\n /**\n * @param collection 实例对象\n * @return 对象列表\n * 实体作为筛选条件查询数据\n */\n List<Collection> listCollections(Collection collection);\n\n /**\n * @param collection 实例对象\n * @return 结果数量\n * 实体作为筛选条件获取结果数量\n */\n int countCollections(Collection collection);\n\n /**\n * @param collection 实例对象\n * @return 是否成功\n * 修改数据,哪个属性不为空就修改哪个属性\n */\n boolean update(Collection collection);\n\n}" } ]
import org.springframework.stereotype.Service; import world.xuewei.entity.Collection; import world.xuewei.service.BaseService; import world.xuewei.service.CollectionService; import java.util.List;
780
package world.xuewei.service.impl; /** * @author XUEW * @ClassName CollectionServiceImpl * 收藏表(Collection)表业务接口实现类 * @date 2021-02-28 21:07:19 * @Version 1.0 **/ @Service("collectionService") public class CollectionServiceImpl extends BaseService implements CollectionService { @Override
package world.xuewei.service.impl; /** * @author XUEW * @ClassName CollectionServiceImpl * 收藏表(Collection)表业务接口实现类 * @date 2021-02-28 21:07:19 * @Version 1.0 **/ @Service("collectionService") public class CollectionServiceImpl extends BaseService implements CollectionService { @Override
public boolean insert(Collection collection) {
0
2023-12-27 15:17:13+00:00
2k
fatorius/DUCO-Android-Miner
DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/MiningThread.java
[ { "identifier": "DUCOS1Hasher", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/algorithms/DUCOS1Hasher.java", "snippet": "public class DUCOS1Hasher {\n private int lastNonce;\n private float hashingTimeDeltaSeconds;\n\n public DUCOS1Hasher(){\n }\n\n public int mine(String lastHash, String expectedHash, int difficulty, float efficiency){\n float hashingStartTimeSeconds = SystemClock.elapsedRealtime() / 1000.0f;\n\n lastNonce = findNonce(lastHash, expectedHash, difficulty, efficiency);\n float hashingEndTimeSeconds = SystemClock.elapsedRealtime() / 1000.0f;\n\n hashingTimeDeltaSeconds = hashingEndTimeSeconds - hashingStartTimeSeconds;\n\n return lastNonce;\n }\n\n public native int findNonce(String lastHash, String expectedHash, int difficulty, float efficiency);\n\n public float getTimeElapsed(){\n return hashingTimeDeltaSeconds;\n }\n\n public float getHashrate(){\n return lastNonce / (hashingTimeDeltaSeconds);\n }\n}" }, { "identifier": "MinerInfo", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/infos/MinerInfo.java", "snippet": "public class MinerInfo {\n public static String MINER_NAME = \"Fatorius' Android Miner\";\n}" }, { "identifier": "Client", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/tcp/Client.java", "snippet": "public class Client {\n String ip;\n int port;\n\n Socket socket;\n PrintWriter socketSender;\n BufferedReader socketReader;\n\n public Client(String ip, int port) throws IOException {\n this.ip = ip;\n this.port = port;\n\n socket = new Socket(ip, port);\n\n socketSender = new PrintWriter(socket.getOutputStream(), true);\n socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n\n Log.d(\"Socket connection\", \"TCP connection started to \" + ip + \":\" + port);\n\n send(\"PING\");\n socketReader.readLine();\n }\n\n public void send(String msg){\n Log.d(\"Sending to socket\", msg);\n socketSender.println(msg);\n }\n\n public String readLine() throws IOException {\n String receivedMsg = socketReader.readLine();\n\n if (receivedMsg == null){\n this.restartConnection();\n receivedMsg = \"Connection restarted\";\n }\n\n Log.d(\"Received from socket\", receivedMsg);\n\n return receivedMsg;\n }\n\n public void closeConnection() throws IOException {\n socket.close();\n socketSender.close();\n socketReader.close();\n\n Log.d(\"Socket connection ended\", \"Connection exit\");\n }\n\n public void restartConnection() throws IOException {\n Log.d(\"Socket connection restarted\", \"Connection restarting\");\n\n socket.close();\n socketSender.close();\n socketReader.close();\n\n socket = new Socket(ip, port);\n\n socketSender = new PrintWriter(socket.getOutputStream(), true);\n socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n\n send(\"PING\");\n socketReader.readLine();\n }\n}" } ]
import android.os.Build; import android.util.Log; import com.fatorius.duinocoinminer.algorithms.DUCOS1Hasher; import com.fatorius.duinocoinminer.infos.MinerInfo; import com.fatorius.duinocoinminer.tcp.Client; import java.io.IOException;
892
package com.fatorius.duinocoinminer.threads; public class MiningThread implements Runnable{ static{ System.loadLibrary("ducohasher"); } public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread"; String ip; int port; int threadNo;
package com.fatorius.duinocoinminer.threads; public class MiningThread implements Runnable{ static{ System.loadLibrary("ducohasher"); } public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread"; String ip; int port; int threadNo;
Client tcpClient;
2
2023-12-27 06:00:05+00:00
2k
tommyskeff/JObserve
src/main/java/dev/tommyjs/jobserve/observer/ObserverEmitter.java
[ { "identifier": "ObserverEmitterImpl", "path": "src/main/java/dev/tommyjs/jobserve/observer/impl/ObserverEmitterImpl.java", "snippet": "public class ObserverEmitterImpl implements ObserverEmitter {\n\n private final Random random;\n private final @NotNull Map<ObserverKey, AtomicReference<Set<ObserverSubscription>>> observers;\n\n public ObserverEmitterImpl() {\n this.random = new SecureRandom();\n this.observers = new ConcurrentHashMap<>();\n }\n\n protected @NotNull ObserverSubscription observe0(@NotNull ObserverKey key, @NotNull Consumer<Object> consumer) {\n ObserverSubscription subscription = new ObserverSubscriptionImpl(this, random.nextInt(), key, consumer);\n\n observers.compute(key, (_k, ref) -> {\n if (ref == null) {\n ref = new AtomicReference<>(new HashSet<>());\n }\n\n ref.get().add(subscription);\n return ref;\n });\n\n return subscription;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer) {\n return observe0(key, o -> consumer.accept((T) o));\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <K, V> @NotNull ObserverSubscription observe(@NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer) {\n return observe0(key, o -> {\n Object[] objects = (Object[]) o;\n consumer.accept((K) objects[0], (V) objects[1]);\n });\n }\n\n protected void emit0(@NotNull ObserverKey key, @Nullable Object value) {\n observers.compute(key, (_k, ref) -> {\n if (ref == null) {\n return null;\n }\n\n for (ObserverSubscription subscription : ref.get()) {\n subscription.getConsumer().accept(value);\n }\n\n return ref;\n });\n }\n\n @Override\n public <T> void emit(@NotNull MonoKey<T> key, @Nullable T value) {\n emit0(key, value);\n }\n\n @Override\n public <K, V> void emit(@NotNull DuplexKey<K, V> key, @Nullable K value1, @Nullable V value2) {\n emit0(key, new Object[]{value1, value2});\n }\n\n @Override\n public void cancel(@NotNull ObserverSubscription subscription) {\n observers.compute(subscription.getKey(), (key, ref) -> {\n if (ref != null) {\n ref.get().remove(subscription);\n }\n\n return ref;\n });\n }\n\n}" }, { "identifier": "DuplexKey", "path": "src/main/java/dev/tommyjs/jobserve/observer/key/DuplexKey.java", "snippet": "@SuppressWarnings(\"unused\")\npublic final class DuplexKey<K, V> extends ObserverKey {\n\n private final @NotNull Class<K> type1;\n private final @NotNull Class<V> type2;\n\n private DuplexKey(int keyId, @NotNull Class<K> type1, @NotNull Class<V> type2) {\n super(keyId);\n this.type1 = type1;\n this.type2 = type2;\n }\n\n public @NotNull Class<K> getType1() {\n return type1;\n }\n\n public @NotNull Class<V> getType2() {\n return type2;\n }\n\n public static <K, V> DuplexKey<K, V> register(@NotNull Class<K> type1, @NotNull Class<V> type2) {\n return new DuplexKey<>(RANDOM.nextInt(), type1, type2);\n }\n\n}" }, { "identifier": "MonoKey", "path": "src/main/java/dev/tommyjs/jobserve/observer/key/MonoKey.java", "snippet": "@SuppressWarnings(\"unused\")\npublic final class MonoKey<T> extends ObserverKey {\n\n private final @NotNull Class<T> type;\n\n private MonoKey(int keyId, @NotNull Class<T> type) {\n super(keyId);\n this.type = type;\n }\n\n public @NotNull Class<T> getType() {\n return type;\n }\n\n public static <T> @NotNull MonoKey<T> register(@NotNull Class<T> type) {\n return new MonoKey<>(RANDOM.nextInt(), type);\n }\n\n}" } ]
import dev.tommyjs.jobserve.observer.impl.ObserverEmitterImpl; import dev.tommyjs.jobserve.observer.key.DuplexKey; import dev.tommyjs.jobserve.observer.key.MonoKey; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.function.BiConsumer; import java.util.function.Consumer;
1,130
package dev.tommyjs.jobserve.observer; public interface ObserverEmitter { <T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer);
package dev.tommyjs.jobserve.observer; public interface ObserverEmitter { <T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer);
<K, V> @NotNull ObserverSubscription observe(@NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer);
1
2023-12-26 17:02:45+00:00
2k
fanxiaoning/framifykit
framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/KD100QueryTrackRes.java
[ { "identifier": "BaseRes", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/res/BaseRes.java", "snippet": "@Data\npublic class BaseRes {\n\n}" }, { "identifier": "KD100QueryTrackDataDetail", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryTrackDataDetail.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class KD100QueryTrackDataDetail {\n /**\n * 时间,原始格式\n */\n private String time;\n /**\n * 物流轨迹节点内容\n */\n private String context;\n /**\n * 标题\n */\n private String title;\n /**\n * 格式化后时间\n */\n private String ftime;\n /**\n * 行政区域的编码\n */\n private String areaCode;\n /**\n * 行政区域的名称\n */\n private String areaName;\n /**\n * 签收状态 (0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投)\n */\n private String status;\n\n public KD100QueryTrackDataDetail() {\n }\n\n public KD100QueryTrackDataDetail(KD100QueryTraceData traceDTO) {\n this.time = traceDTO.getOpeTime();\n this.context = traceDTO.getOpeRemark();\n this.ftime = DateUtil.format(DateUtil.parse(time, \"yyyy/MM/dd HH:mm:ss\"), \"yyyy-MM-dd HH:mm:ss\");\n this.title = traceDTO.getOpeTitle();\n }\n}" }, { "identifier": "KD100QueryTrackRouteInfo", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryTrackRouteInfo.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class KD100QueryTrackRouteInfo {\n /**\n * 出发位置\n */\n private KD100QueryTrackPosition from;\n /**\n * 当前位置\n */\n private KD100QueryTrackPosition cur;\n /**\n * 收货地\n */\n private KD100QueryTrackPosition to;\n}" } ]
import com.framifykit.starter.logistics.executor.domain.res.BaseRes; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryTrackDataDetail; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryTrackRouteInfo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List;
1,020
package com.framifykit.starter.logistics.platform.kd100.domain.res; /** * <p> * 快递100 查询物流信息res * </p> * * @author fxn * @since 1.0.0 **/ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class KD100QueryTrackRes extends BaseRes { /** * 消息体,请忽略 */ private String message; /** * 快递单号 */ private String nu; /** * 是否签收标记 */ private String ischeck; /** * 快递公司编码,一律用小写字母 */ private String com; /** * 通讯状态 */ private String status; /** * 轨迹详情数组 */ private List<KD100QueryTrackDataDetail> data = new ArrayList<>(); /** * 快递单当前状态,包括0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投,10待清关,11清关中,12已清关,13清关异常,14拒签 等13个状态 */ private String state; /** * 快递单明细状态标记 */ private String condition;
package com.framifykit.starter.logistics.platform.kd100.domain.res; /** * <p> * 快递100 查询物流信息res * </p> * * @author fxn * @since 1.0.0 **/ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class KD100QueryTrackRes extends BaseRes { /** * 消息体,请忽略 */ private String message; /** * 快递单号 */ private String nu; /** * 是否签收标记 */ private String ischeck; /** * 快递公司编码,一律用小写字母 */ private String com; /** * 通讯状态 */ private String status; /** * 轨迹详情数组 */ private List<KD100QueryTrackDataDetail> data = new ArrayList<>(); /** * 快递单当前状态,包括0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投,10待清关,11清关中,12已清关,13清关异常,14拒签 等13个状态 */ private String state; /** * 快递单明细状态标记 */ private String condition;
private KD100QueryTrackRouteInfo routeInfo;
2
2023-12-31 03:48:33+00:00
2k
yangpluseven/Simulate-Something
simulation/src/simulator/GridMap.java
[ { "identifier": "Constants", "path": "simulation/src/constants/Constants.java", "snippet": "public class Constants {\n\n\tpublic static final Size INIT_GRID_SIZE = new Size(10, 10);\n\tpublic static final Size NUM_OF_COL_ROW = new Size(50, 30);\n\tpublic static final int BACKGROUND_Z_ORDER = 0;\n\tpublic static final int TERRAIN_BOTTOM_Z_ORDER = 1;\n\tpublic static final int CREATURE_BOTTOM_Z_ORDER = 6;\n\tpublic static final boolean ZOOM_IN = true;\n\tpublic static final boolean ZOOM_OUT = false;\n\t\n}" }, { "identifier": "Location", "path": "simulation/src/entities/Location.java", "snippet": "public class Location extends Pair<Integer, Integer> implements Comparable<Pair<Integer, Integer>> {\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic Location() {\n\t\tleft = 0;\n\t\tright = 0;\n\t}\n\n\t/**\n\t * Represent a row and column.\n\t * \n\t * @param row The row.\n\t * @param col The column.\n\t */\n\tpublic Location(int col, int row) {\n\t\tleft = col;\n\t\tright = row;\n\t}\n\n\t/**\n\t * Update the location.\n\t * \n\t * @param row\n\t * @param col\n\t */\n\tpublic void update(int col, int row) {\n\t\tleft = col;\n\t\tright = row;\n\t}\n\n\t/**\n\t * @return The column.\n\t */\n\tpublic int getCol() {\n\t\treturn left;\n\t}\n\n\t/**\n\t * @return The row.\n\t */\n\tpublic int getRow() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic int compareTo(Pair<Integer, Integer> o) {\n\t\treturn this.left == o.left ? this.right - o.right : this.left - o.left;\n\t}\n\n}" }, { "identifier": "Pair", "path": "simulation/src/entities/Pair.java", "snippet": "public class Pair<L, R> implements Entry<L, R> {\n\n\tprotected L left;\n\tprotected R right;\n\n\tpublic Pair() {\n\t}\n\n\tpublic Pair(L left, R right) {\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn (left == null ? 0 : left.hashCode()) ^ (right == null ? 0 : right.hashCode());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj instanceof Pair) {\n\t\t\tPair<?, ?> other = (Pair<?, ?>) obj;\n\t\t\treturn left == other.getLeft() && right == other.getRight();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + left.toString() + right.toString() + \")\";\n\t}\n\n\t@Override\n\tpublic L getKey() {\n\t\treturn left;\n\t}\n\n\t@Override\n\tpublic R getValue() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic R setValue(R value) {\n\t\tR former = right;\n\t\tright = value;\n\t\treturn former;\n\t}\n\n\tpublic L getLeft() {\n\t\treturn left;\n\t}\n\n\tpublic void setLeft(L left) {\n\t\tthis.left = left;\n\t}\n\n\tpublic R getRight() {\n\t\treturn right;\n\t}\n\n\tpublic void setRight(R right) {\n\t\tthis.right = right;\n\t}\n\n}" }, { "identifier": "SimuObject", "path": "simulation/src/entities/SimuObject.java", "snippet": "public abstract class SimuObject {\n\t\n\tprotected Painter painter;\n\tprotected GridMap gridMap;\n\tprotected Location location;\n\tprotected Color color;\n\t\n\tpublic SimuObject() {\n\t\t// TODO SimuObject constructor\n\t}\n\t\n\tpublic void moveTo(Location location) {\n\t\tgridMap.remove(this.location);\n\t\tthis.location = location;\n\t\tgridMap.addObjectAt(this, location);\n\t}\n\t\n\tpublic Color getColor() {\n\t\treturn color;\n\t}\n\n\tpublic Painter getPainter() {\n\t\treturn painter;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn location;\n\t}\n\t\n\tpublic abstract void forward();\n\n}" }, { "identifier": "Size", "path": "simulation/src/entities/Size.java", "snippet": "public class Size extends Pair<Integer, Integer> implements Comparable<Pair<Integer, Integer>> {\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic Size() {\n\t\tleft = 0;\n\t\tright = 0;\n\t}\n\n\t/**\n\t * Represent a width and height.\n\t * \n\t * @param width\n\t * @param height\n\t */\n\tpublic Size(int width, int height) {\n\t\tleft = width;\n\t\tright = height;\n\t}\n\n\t/**\n\t * Update the size.\n\t * \n\t * @param width\n\t * @param height\n\t */\n\tpublic void update(int width, int height) {\n\t\tleft = width;\n\t\tright = height;\n\t}\n\n\t/**\n\t * @return width\n\t */\n\tpublic int getWidth() {\n\t\treturn left;\n\t}\n\n\t/**\n\t * @return height\n\t */\n\tpublic int getHeight() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic int compareTo(Pair<Integer, Integer> o) {\n\t\treturn this.left == o.left ? this.right - o.right : this.left - o.left;\n\t}\n\n}" } ]
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import constants.Constants; import entities.Location; import entities.Pair; import entities.SimuObject; import entities.Size;
1,464
package simulator; /** * GridMap takes up all the SimuObjects in the simulation. * * @author pluseven */ public class GridMap implements Map<Location, simulator.GridMap.Grid> { private Grid[][] grids; private Size numCR; private int numOfObjs; /** * Default constructor. */ public GridMap() {
package simulator; /** * GridMap takes up all the SimuObjects in the simulation. * * @author pluseven */ public class GridMap implements Map<Location, simulator.GridMap.Grid> { private Grid[][] grids; private Size numCR; private int numOfObjs; /** * Default constructor. */ public GridMap() {
numCR = Constants.NUM_OF_COL_ROW;
0
2023-12-23 13:51:12+00:00
2k
zxx1119/best-adrules
src/main/java/org/fordes/adg/rule/AdgRuleApplication.java
[ { "identifier": "OutputConfig", "path": "src/main/java/org/fordes/adg/rule/config/OutputConfig.java", "snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"application.output\")\npublic class OutputConfig {\n\n /**\n * 输出文件路径\n */\n private String path;\n\n /**\n * 输出文件列表\n */\n private Map<String, List<RuleType>> files;\n}" }, { "identifier": "RuleConfig", "path": "src/main/java/org/fordes/adg/rule/config/RuleConfig.java", "snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"application.rule\")\npublic class RuleConfig {\n\n /**\n * 远程规则,http或https\n */\n private List<String> remote;\n\n /**\n * 本地规则\n */\n private List<String> local;\n}" }, { "identifier": "RuleType", "path": "src/main/java/org/fordes/adg/rule/enums/RuleType.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum RuleType {\n\n /**\n * 域名规则,形如 xxx.com、xx.oo.com\n */\n DOMAIN(\"域名规则\", true, null, new String[]{\"^([\\\\w,\\\\d,-]+\\\\.)+[\\\\w,\\\\d,-]+(\\\\^$)?$\"}, null),\n\n /**\n * Hosts规则\n */\n HOSTS(\"Hosts规则\", true, null, new String[]{\"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\s+.*$\"}, null),\n\n /**\n * 正则规则,包含修饰规则\n */\n REGEX(\"正则规则\", true, null, new String[]{},\n new String[]{\"[/,#,&,=,:]\", \"^[\\\\*,@,\\\\-,_,\\\\.,&,\\\\?]\",\"[\\\\$][^\\\\s]\", \"[\\\\^][^\\\\s]\"}),\n\n\n /**\n * 修饰规则,不被adGuardHome支持\n */\n MODIFY(\"修饰规则\", false, null, null, null)\n ;\n\n\n /**\n * 描述\n */\n private final String desc;\n\n /**\n * 支持性,true则adGuardHome支持\n */\n private final boolean usually;\n\n /**\n * 识别标识,包含即通过\n */\n private final String[] identify;\n\n /**\n * 正向 正则,匹配一个即为通过\n */\n private final String[] match;\n\n /**\n * 排除 正则,全部不匹配即为通过\n */\n private final String[] exclude;\n}" }, { "identifier": "LocalRuleThread", "path": "src/main/java/org/fordes/adg/rule/thread/LocalRuleThread.java", "snippet": "public class LocalRuleThread extends AbstractRuleThread {\n\n\n public LocalRuleThread(String ruleUrl, Map<RuleType, Set<File>> typeFileMap, BloomFilter<String> filter) {\n super(ruleUrl, typeFileMap, filter);\n }\n\n @Override\n InputStream getContentStream() {\n return FileUtil.getInputStream(getRuleUrl());\n }\n}" }, { "identifier": "RemoteRuleThread", "path": "src/main/java/org/fordes/adg/rule/thread/RemoteRuleThread.java", "snippet": "@Slf4j\npublic class RemoteRuleThread extends AbstractRuleThread {\n\n\n public RemoteRuleThread(String ruleUrl, Map<RuleType, Set<File>> typeFileMap, BloomFilter<String> filter) {\n super(ruleUrl, typeFileMap, filter);\n }\n\n @Override\n InputStream getContentStream() {\n try {\n HttpResponse response = HttpRequest.get(getRuleUrl())\n .setFollowRedirects(true)\n .timeout(20000)\n .execute();\n if (response.isOk()) {\n setCharset(Charset.forName(response.charset()));\n return response.bodyStream();\n }\n }catch (Exception e) {\n log.error(getRuleUrl());\n log.error(ExceptionUtil.stacktraceToString(e));\n }\n return IoUtil.toStream(new byte[0]);\n }\n\n}" } ]
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.io.FileUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.thread.ExecutorBuilder; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnels; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.fordes.adg.rule.config.OutputConfig; import org.fordes.adg.rule.config.RuleConfig; import org.fordes.adg.rule.enums.RuleType; import org.fordes.adg.rule.thread.LocalRuleThread; import org.fordes.adg.rule.thread.RemoteRuleThread; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; import java.io.File; import java.nio.charset.Charset; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadPoolExecutor;
1,530
package org.fordes.adg.rule; @Slf4j @Component @AllArgsConstructor @SpringBootApplication public class AdgRuleApplication implements ApplicationRunner { private final static int N = Runtime.getRuntime().availableProcessors(); private final RuleConfig ruleConfig; private final OutputConfig outputConfig; private final ThreadPoolExecutor executor = ExecutorBuilder.create() .setCorePoolSize(2 * N) .setMaxPoolSize(2 * N) .setHandler(new ThreadPoolExecutor.CallerRunsPolicy()) .build(); @Override public void run(ApplicationArguments args) throws Exception { TimeInterval interval = DateUtil.timer(); // 初始化,根据配置建立文件 final Map<RuleType, Set<File>> typeFileMap = MapUtil.newHashMap(); if (!outputConfig.getFiles().isEmpty()) { outputConfig.getFiles().forEach((fileName, types) -> { File file = Util.createFile(outputConfig.getPath() + File.separator + fileName); types.forEach(type -> Util.safePut(typeFileMap, type, Util.createFile(file))); }); } //使用布隆过滤器实现去重 BloomFilter<String> filter = BloomFilter .create(Funnels.stringFunnel(Charset.defaultCharset()), 1000000); //远程规则 ruleConfig.getRemote().stream() .filter(StrUtil::isNotBlank) .map(URLUtil::normalize)
package org.fordes.adg.rule; @Slf4j @Component @AllArgsConstructor @SpringBootApplication public class AdgRuleApplication implements ApplicationRunner { private final static int N = Runtime.getRuntime().availableProcessors(); private final RuleConfig ruleConfig; private final OutputConfig outputConfig; private final ThreadPoolExecutor executor = ExecutorBuilder.create() .setCorePoolSize(2 * N) .setMaxPoolSize(2 * N) .setHandler(new ThreadPoolExecutor.CallerRunsPolicy()) .build(); @Override public void run(ApplicationArguments args) throws Exception { TimeInterval interval = DateUtil.timer(); // 初始化,根据配置建立文件 final Map<RuleType, Set<File>> typeFileMap = MapUtil.newHashMap(); if (!outputConfig.getFiles().isEmpty()) { outputConfig.getFiles().forEach((fileName, types) -> { File file = Util.createFile(outputConfig.getPath() + File.separator + fileName); types.forEach(type -> Util.safePut(typeFileMap, type, Util.createFile(file))); }); } //使用布隆过滤器实现去重 BloomFilter<String> filter = BloomFilter .create(Funnels.stringFunnel(Charset.defaultCharset()), 1000000); //远程规则 ruleConfig.getRemote().stream() .filter(StrUtil::isNotBlank) .map(URLUtil::normalize)
.forEach(e -> executor.execute(new RemoteRuleThread(e, typeFileMap, filter)));
4
2023-12-30 04:47:07+00:00
2k
bmarwell/sipper
impl/src/main/java/io/github/bmarwell/sipper/impl/SocketInConnectionReader.java
[ { "identifier": "QueueingSipIncomingMessageHandler", "path": "impl/src/main/java/io/github/bmarwell/sipper/impl/proto/QueueingSipIncomingMessageHandler.java", "snippet": "public class QueueingSipIncomingMessageHandler implements SipIncomingMessageHandler {\n\n private static final Logger LOG = LoggerFactory.getLogger(QueueingSipIncomingMessageHandler.class);\n\n private final ArrayList<RawSipMessage> messages = new ArrayList<>();\n\n @Override\n public void accept(RawSipMessage sipMessage) {\n LOG.trace(\"Incoming message:\\n[{}]\", sipMessage);\n\n switch (sipMessage.method()) {\n case \"REGISTER\":\n this.messages.add(sipMessage);\n break;\n case \"INVITE\":\n default:\n throw new UnsupportedOperationException(\n \"not yet implemented: [io.github.bmarwell.sipper.impl.proto.QueueingSipIncomingMessageHandler::accept].\");\n }\n }\n\n public List<RawSipMessage> getMessages() {\n return List.copyOf(this.messages);\n }\n\n public void remove(RawSipMessage message) {\n this.messages.remove(message);\n }\n}" }, { "identifier": "LangUtil", "path": "impl/src/main/java/io/github/bmarwell/sipper/impl/util/LangUtil.java", "snippet": "public final class LangUtil {\n\n public static OptionalInt isIntegerOrEmpty(String maybeNumber) {\n try {\n final var parsedLong = Integer.parseInt(maybeNumber);\n return OptionalInt.of(parsedLong);\n } catch (NumberFormatException nfe) {\n return OptionalInt.empty();\n }\n }\n}" } ]
import io.github.bmarwell.sipper.impl.proto.QueueingSipIncomingMessageHandler; import io.github.bmarwell.sipper.impl.proto.RawSipMessage; import io.github.bmarwell.sipper.impl.util.LangUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.SocketException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
1,221
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl; public class SocketInConnectionReader implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(SocketInConnectionReader.class); private ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor(); private final BufferedReader socketReader; private final QueueingSipIncomingMessageHandler msgHandler; private boolean interrupted = false; public SocketInConnectionReader(InputStream socketInput, QueueingSipIncomingMessageHandler msgHandler) { this.socketReader = new BufferedReader(new InputStreamReader(socketInput)); this.msgHandler = msgHandler; } @Override public void run() { StringBuilder currentMessage = new StringBuilder(); String readLine; try { checkInterrupted(); LOG.trace("Now listening for incoming messages"); while (!this.interrupted && (readLine = this.socketReader.readLine()) != null) { checkInterrupted(); if (this.interrupted) { return; } currentMessage.append(readLine); currentMessage.append('\n'); final var currentMessageString = currentMessage.toString(); if (currentMessageString.endsWith("\n\n")) { checkInterrupted(); LOG.trace("Received message:\n[{}]", currentMessage); final RawSipMessage rawSipMessage; // probably end of message, UNLESS it is a header with a following body. if (isMessageWithBody(currentMessageString)) { LOG.trace("Message with body"); rawSipMessage = processMessageWithBody(currentMessageString); } else { rawSipMessage = new RawSipMessage(currentMessageString); } try { CompletableFuture.runAsync(() -> this.msgHandler.accept(rawSipMessage), executorService); } catch (Exception e) { LOG.trace("Unable to process message.", e); } currentMessage = new StringBuilder(); } } } catch (SocketException se) { // probably OK... Thread.currentThread().interrupt(); } catch (IOException ioException) { LOG.error("Problem while reading input from socket.", ioException); } catch (InterruptedException interruptedException) { // all ok, nothing to clean up. Thread.currentThread().interrupt(); } } private static boolean isMessageWithBody(String currentMessageString) { return currentMessageString.startsWith("INVITE") && currentMessageString.contains("\nContent-Length: ") && !currentMessageString.contains("\nContent-Length: 0\n"); } private RawSipMessage processMessageWithBody(String currentMessageString) throws IOException { final String bodyLengthString = currentMessageString .lines() .filter(line -> line.startsWith("Content-Length: ")) .findFirst() .orElseThrow(); final var bodyLengthNumber = bodyLengthString.split(":", 2)[1].trim();
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl; public class SocketInConnectionReader implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(SocketInConnectionReader.class); private ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor(); private final BufferedReader socketReader; private final QueueingSipIncomingMessageHandler msgHandler; private boolean interrupted = false; public SocketInConnectionReader(InputStream socketInput, QueueingSipIncomingMessageHandler msgHandler) { this.socketReader = new BufferedReader(new InputStreamReader(socketInput)); this.msgHandler = msgHandler; } @Override public void run() { StringBuilder currentMessage = new StringBuilder(); String readLine; try { checkInterrupted(); LOG.trace("Now listening for incoming messages"); while (!this.interrupted && (readLine = this.socketReader.readLine()) != null) { checkInterrupted(); if (this.interrupted) { return; } currentMessage.append(readLine); currentMessage.append('\n'); final var currentMessageString = currentMessage.toString(); if (currentMessageString.endsWith("\n\n")) { checkInterrupted(); LOG.trace("Received message:\n[{}]", currentMessage); final RawSipMessage rawSipMessage; // probably end of message, UNLESS it is a header with a following body. if (isMessageWithBody(currentMessageString)) { LOG.trace("Message with body"); rawSipMessage = processMessageWithBody(currentMessageString); } else { rawSipMessage = new RawSipMessage(currentMessageString); } try { CompletableFuture.runAsync(() -> this.msgHandler.accept(rawSipMessage), executorService); } catch (Exception e) { LOG.trace("Unable to process message.", e); } currentMessage = new StringBuilder(); } } } catch (SocketException se) { // probably OK... Thread.currentThread().interrupt(); } catch (IOException ioException) { LOG.error("Problem while reading input from socket.", ioException); } catch (InterruptedException interruptedException) { // all ok, nothing to clean up. Thread.currentThread().interrupt(); } } private static boolean isMessageWithBody(String currentMessageString) { return currentMessageString.startsWith("INVITE") && currentMessageString.contains("\nContent-Length: ") && !currentMessageString.contains("\nContent-Length: 0\n"); } private RawSipMessage processMessageWithBody(String currentMessageString) throws IOException { final String bodyLengthString = currentMessageString .lines() .filter(line -> line.startsWith("Content-Length: ")) .findFirst() .orElseThrow(); final var bodyLengthNumber = bodyLengthString.split(":", 2)[1].trim();
final var bodyLengthOpt = LangUtil.isIntegerOrEmpty(bodyLengthNumber);
1
2023-12-28 13:13:07+00:00
2k
Deenu143/GradleParser
app/src/main/java/org/deenu/gradle/parser/Main.java
[ { "identifier": "ParserFailedException", "path": "app/src/main/java/org/deenu/gradle/parser/exception/ParserFailedException.java", "snippet": "public class ParserFailedException extends Exception {\n\n public ParserFailedException(String message, Throwable t) {\n super(message, t);\n }\n\n public ParserFailedException(Exception exception) {\n super(exception);\n }\n\n public ParserFailedException(String message) {\n super(message);\n }\n}" }, { "identifier": "GradleScript", "path": "app/src/main/java/org/deenu/gradle/script/GradleScript.java", "snippet": "public class GradleScript {\n\n private File gradleFile;\n private AstBuilder astBuilder;\n private List<ASTNode> aSTNodes;\n private String scriptContents;\n private GradleScriptVisitor gradleScriptVisitor;\n\n public GradleScript(File gradleFile) throws Exception, FileNotFoundException {\n this.gradleFile = gradleFile;\n if (gradleFile == null || !gradleFile.exists()) {\n throw new FileNotFoundException(\"Failed to get '.gradle' or '.gradle.kts' file.\");\n } else if (gradleFile != null) {\n String fileName = gradleFile.getName();\n String[] fileExtensions = new String[] {\".gradle\", \".gradle.kts\"};\n\n if (fileName != null) {\n if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) {\n throw new UnsupportedFileException(\"Unsupported file: \" + gradleFile.getAbsolutePath());\n }\n }\n }\n\n this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath()));\n init(scriptContents, gradleFile);\n }\n\n private void init(String script, File gradleFile) throws Exception {\n if (script == null || script.isEmpty()) {\n throw new Exception(\"Failed to get gradle script from file: \" + gradleFile.getAbsolutePath());\n }\n this.astBuilder = new AstBuilder();\n this.aSTNodes = getASTNodes();\n }\n\n public File getGradleFile() {\n return this.gradleFile;\n }\n\n public String getGradleFileName() {\n return this.gradleFile.getName();\n }\n\n public boolean isGradleBuildFile() {\n return getGradleFileName().startsWith(\"build.gradle\");\n }\n\n public boolean isGradleSettingsFile() {\n return getGradleFileName().startsWith(\"settings.gradle\");\n }\n\n private List<ASTNode> getASTNodes() throws Exception {\n return this.astBuilder.buildFromString(scriptContents);\n }\n\n public List<Plugin> getPlugins() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getPlugins();\n }\n\n public List<Repository> getRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getRepositories();\n }\n\n public List<Repository> getBuildScriptRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getBuildScriptRepositories();\n }\n\n public List<Repository> getAllProjectsRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getAllProjectsRepositories();\n }\n\n public List<FlatDir> getAllProjectsRepositoriesFlatDirDirs() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getAllProjectsRepositoriesFlatDirDirs();\n }\n\n public List<Repository> getPluginManagementRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getPluginManagementRepositories();\n }\n\n public List<Repository> getDependencyResolutionManagementRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencyResolutionManagementRepositories();\n }\n\n public List<FlatDir> getDependencyResolutionManagementRepositoriesFlatDirDirs() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencyResolutionManagementRepositoriesFlatDirDirs();\n }\n\n public List<Dependency> getDependencies() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencies();\n }\n\n public List<Dependency> getBuildScriptDependencies() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getBuildScriptDependencies();\n }\n\n public String getRootProjectName() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getRootProjectName();\n }\n\n public List<Include> getIncludes() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getIncludes();\n }\n\n private void walkScript(GroovyCodeVisitor visitor) {\n for (ASTNode astNode : aSTNodes) {\n astNode.visit(visitor);\n }\n }\n\n public GradleScriptVisitor getGradleScriptVisitor() {\n return this.gradleScriptVisitor;\n }\n}" } ]
import java.io.File; import org.deenu.gradle.parser.exception.ParserFailedException; import org.deenu.gradle.script.GradleScript;
1,367
package org.deenu.gradle.parser; public class Main { public static void main(String[] args) { try { File buildGradle = new File("/storage/emulated/0/test/build.gradle");
package org.deenu.gradle.parser; public class Main { public static void main(String[] args) { try { File buildGradle = new File("/storage/emulated/0/test/build.gradle");
GradleScript gradleScript = new GradleScript(buildGradle);
1
2023-12-27 10:10:31+00:00
2k
refutix/flink-sql-template-jar
flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/SqlRunner.java
[ { "identifier": "SqlParseUtil", "path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/common/SqlParseUtil.java", "snippet": "public class SqlParseUtil {\n\n private static final String STATEMENT_DELIMITER = \";\";\n\n private static final String MASK = \"--.*$\";\n\n private static final String BEGINNING_MASK = \"^(\\\\s)*--.*$\";\n\n private SqlParseUtil() {\n\n }\n\n public static Operation parseSingleStatement(Parser parser, String statement) {\n List<Operation> operations;\n try {\n operations = parser.parse(statement);\n } catch (Exception e) {\n throw new SqlParseException(\"Failed to parse sql statement: \" + statement, e);\n }\n if (operations.isEmpty()) {\n throw new SqlParseException(\"Failed to parse sql statement: \" + statement);\n }\n return operations.get(0);\n }\n\n public static String formatSql(String sql) {\n if (sql == null) {\n return \"\";\n }\n String trimmed = sql.trim();\n StringBuilder formatted = new StringBuilder();\n formatted.append(trimmed);\n if (!trimmed.endsWith(STATEMENT_DELIMITER)) {\n formatted.append(\";\");\n }\n return formatted.toString();\n }\n\n public static List<String> splitContent(String content) {\n List<String> statements = new ArrayList<>();\n List<String> buffer = new ArrayList<>();\n for (String line : content.split(\"\\n\")) {\n if (isEndOfStatement(line)) {\n buffer.add(line);\n statements.add(normalize(buffer));\n buffer.clear();\n } else {\n buffer.add(line);\n }\n\n }\n return statements;\n }\n\n private static String normalize(List<String> buffer) {\n return buffer.stream().map(line -> line.replaceAll(BEGINNING_MASK, \"\"))\n .collect(Collectors.joining(\"\\n\"));\n }\n\n private static boolean isEndOfStatement(String line) {\n return line.replaceAll(MASK, \"\").trim().endsWith(\";\");\n }\n}" }, { "identifier": "FlinkSqlProvider", "path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/provider/sql/FlinkSqlProvider.java", "snippet": "public interface FlinkSqlProvider {\n String getSql(Properties properties);\n}" }, { "identifier": "FlinkSqlProviderFactory", "path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/provider/sql/FlinkSqlProviderFactory.java", "snippet": "public class FlinkSqlProviderFactory {\n\n public static FlinkSqlProvider getProvider(Properties properties) {\n if (\"file\".equals(properties.get(\"sqlProvider\"))) {\n return new FileFlinkSqlProvider();\n }\n throw new SqlProviderNotFoundException();\n }\n}" } ]
import java.util.Properties; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.TableEnvironment; import org.apache.flink.table.api.internal.TableEnvironmentInternal; import org.apache.flink.table.delegation.Parser; import org.apache.flink.table.operations.Operation; import org.refutix.flink.sql.template.common.SqlParseUtil; import org.refutix.flink.sql.template.provider.sql.FlinkSqlProvider; import org.refutix.flink.sql.template.provider.sql.FlinkSqlProviderFactory; import java.time.ZoneId; import java.util.List;
987
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.flink.sql.template; /** * Main class for executing SQL scripts. */ public class SqlRunner { public static void main(String[] args) { ParameterTool parameterTool = ParameterTool.fromArgs(args); Properties properties = parameterTool.getProperties();
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.flink.sql.template; /** * Main class for executing SQL scripts. */ public class SqlRunner { public static void main(String[] args) { ParameterTool parameterTool = ParameterTool.fromArgs(args); Properties properties = parameterTool.getProperties();
FlinkSqlProvider provider = FlinkSqlProviderFactory.getProvider(properties);
2
2023-12-25 16:29:40+00:00
2k
NickReset/JavaNPM
src/main/java/social/nickrest/npm/module/InstalledNPMPackage.java
[ { "identifier": "NPM", "path": "src/main/java/social/nickrest/npm/NPM.java", "snippet": "@Getter @Setter\npublic class NPM {\n\n public static final String BASE_URL = \"https://registry.npmjs.org\";\n\n private final File nodeModulesDir;\n private NPMLogger logger;\n\n public NPM(File nodeModulesDir) {\n this.nodeModulesDir = nodeModulesDir;\n this.logger = new DefualtNPMLogger();\n }\n\n public NPMPackage getPackage(String name) {\n return new NPMPackage(this, name);\n }\n\n public InstalledNPMPackage getInstalledPackage(String name) {\n File dir = new File(nodeModulesDir, name);\n\n if(!dir.exists()) return null;\n\n return new InstalledNPMPackage(this, dir);\n }\n\n public boolean isOutdated(String name) {\n InstalledNPMPackage installed = getInstalledPackage(name);\n\n if(installed == null) return false;\n\n return installed.getPackageJson() == null || !installed.getVersion().equals(getPackage(name).getVersion());\n }\n\n public boolean isInstalled(String name) {\n InstalledNPMPackage installed = getInstalledPackage(name);\n\n if(installed == null) return false;\n\n return installed.getPackageJson() != null;\n }\n\n}" }, { "identifier": "IOUtils", "path": "src/main/java/social/nickrest/npm/util/IOUtils.java", "snippet": "@UtilityClass\npublic class IOUtils {\n\n public static String readConnection(@NonNull URLConnection connection) {\n try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n StringBuilder response = new StringBuilder();\n\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n\n return response.toString();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static void downloadConnection(HttpURLConnection connection, File directory) {\n try {\n FileUtils.copyInputStreamToFile(connection.getInputStream(), directory);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static InputStream getFileStream(File file) {\n try {\n URL url = file.toURI().toURL();\n URLConnection connection = url.openConnection();\n connection.setRequestProperty(\"Accept\", \"application/octet-stream\");\n\n return connection.getInputStream();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static void deleteDirectoryAndContents(File file) {\n try {\n FileUtils.deleteDirectory(file);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" } ]
import lombok.Getter; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import social.nickrest.npm.NPM; import social.nickrest.npm.util.IOUtils; import java.io.File; import java.io.FileReader; import java.util.function.Consumer;
921
package social.nickrest.npm.module; @Getter public class InstalledNPMPackage { private final NPM parent; private final File dir; private JSONObject packageJson; private NPMPackageData data; public InstalledNPMPackage(NPM parent, File dir) { this.parent = parent; this.dir = dir; StringBuilder builder = new StringBuilder(); File packageJson = new File(dir, "package.json"); if(!packageJson.exists()) return; try(FileReader reader = new FileReader(packageJson)) { int i; while((i = reader.read()) != -1) { builder.append((char) i); } this.packageJson = (JSONObject) new JSONParser().parse(builder.toString()); this.data = new NPMPackageData((String) this.packageJson.get("version"), (String) this.packageJson.get("name")); } catch (Exception e) { e.printStackTrace(); } } public void uninstall(Consumer<InstalledNPMPackage> callback) {
package social.nickrest.npm.module; @Getter public class InstalledNPMPackage { private final NPM parent; private final File dir; private JSONObject packageJson; private NPMPackageData data; public InstalledNPMPackage(NPM parent, File dir) { this.parent = parent; this.dir = dir; StringBuilder builder = new StringBuilder(); File packageJson = new File(dir, "package.json"); if(!packageJson.exists()) return; try(FileReader reader = new FileReader(packageJson)) { int i; while((i = reader.read()) != -1) { builder.append((char) i); } this.packageJson = (JSONObject) new JSONParser().parse(builder.toString()); this.data = new NPMPackageData((String) this.packageJson.get("version"), (String) this.packageJson.get("name")); } catch (Exception e) { e.printStackTrace(); } } public void uninstall(Consumer<InstalledNPMPackage> callback) {
IOUtils.deleteDirectoryAndContents(dir);
1
2023-12-22 20:46:10+00:00
2k
Renzythedev/Chat-Program-With-Netty
Server/Server.java
[ { "identifier": "ChannelManager", "path": "Server/Managers/ChannelManager.java", "snippet": "public class ChannelManager {\r\n\r\n private HashMap<String,Channel> channels;\r\n\r\n public ChannelManager() {\r\n channels = new HashMap<String, Channel>();\r\n }\r\n\r\n public void addChannel(Channel channel) {\r\n channels.put(Channels.getIP(channel),channel);\r\n }\r\n\r\n public void removeChannel(Channel channel) {\r\n channels.remove(Channels.getIP(channel), channel);\r\n }\r\n\r\n public boolean isActive(Channel channel) {\r\n return channels.containsKey(Channels.getIP(channel));\r\n }\r\n\r\n public Channel getChannel(String ip) {\r\n Channel channel = channels.get(ip);\r\n return channel;\r\n }\r\n\r\n public void sendMessage(Channel channel,String msg) {\r\n String ip = Channels.getIP(channel);\r\n Channel toChannel = channels.get(ip);\r\n toChannel.writeAndFlush(msg);\r\n }\r\n\r\n public void sendMessageToAllChannels(String msg) {\r\n for(Map.Entry<String, Channel> ctx : channels.entrySet()) {\r\n Channel toChannel = ctx.getValue();\r\n toChannel.writeAndFlush(msg);\r\n }\r\n }\r\n\r\n public void sendMessageToAllChannels(Channel channel, String msg) {\r\n for(Map.Entry<String, Channel> ctx : channels.entrySet()) {\r\n Channel toChannel = ctx.getValue();\r\n if(!(toChannel == channel)) {\r\n toChannel.writeAndFlush(msg);\r\n }\r\n\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "Group", "path": "Server/Utils/Group.java", "snippet": "public class Group {\r\n\r\n public static void stop(EventLoopGroup patern, EventLoopGroup child) {\r\n patern.shutdownGracefully();\r\n child.shutdownGracefully();\r\n }\r\n}\r" } ]
import Server.Managers.ChannelManager; import Server.Utils.Group; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler;
722
package Server; public class Server { public static ChannelManager channels; public static void main(String[] args) { channels = new ChannelManager(); run(); } public static void run(){ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap server = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler()); } }); Channel channel = server.bind(8000).sync().channel(); System.out.println("Server started on 8000 port"); channel.closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally {
package Server; public class Server { public static ChannelManager channels; public static void main(String[] args) { channels = new ChannelManager(); run(); } public static void run(){ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap server = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler()); } }); Channel channel = server.bind(8000).sync().channel(); System.out.println("Server started on 8000 port"); channel.closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally {
Group.stop(bossGroup, workerGroup);
1
2023-12-30 15:54:33+00:00
2k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/config/api/autogen/CustomImage.java
[ { "identifier": "EmptyCustomImageFactory", "path": "common/src/main/java/dev/tcl/config/impl/autogen/EmptyCustomImageFactory.java", "snippet": "public class EmptyCustomImageFactory implements CustomImage.CustomImageFactory<Object> {\n\n @Override\n public CompletableFuture<ImageRenderer> createImage(Object value, ConfigField<Object> field, OptionAccess access) {\n throw new IllegalStateException();\n }\n}" }, { "identifier": "ConfigField", "path": "common/src/main/java/dev/tcl/config/api/ConfigField.java", "snippet": "public interface ConfigField<T> {\n /**\n * Gets the accessor for the field on the main instance.\n * (Accessed through {@link ConfigClassHandler#instance()})\n */\n FieldAccess<T> access();\n\n /**\n * Gets the accessor for the field on the default instance.\n */\n ReadOnlyFieldAccess<T> defaultAccess();\n\n /**\n * @return the parent config class handler that manages this field.\n */\n ConfigClassHandler<?> parent();\n\n /**\n * The serial entry metadata for this field, if it exists.\n */\n Optional<SerialField> serial();\n\n /**\n * The auto-gen metadata for this field, if it exists.\n */\n Optional<AutoGenField> autoGen();\n}" }, { "identifier": "ImageRenderer", "path": "common/src/main/java/dev/tcl/gui/image/ImageRenderer.java", "snippet": "@Environment(EnvType.CLIENT)\npublic interface ImageRenderer {\n int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta);\n\n void close();\n\n default void tick() {}\n}" } ]
import dev.tcl.config.impl.autogen.EmptyCustomImageFactory; import dev.tcl.config.api.ConfigField; import dev.tcl.gui.image.ImageRenderer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.CompletableFuture;
875
package dev.tcl.config.api.autogen; /** * Defines a custom image for an option. * Without this annotation, the option factory will look * for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}. * WEBP was chosen as the default format because file sizes are greatly reduced, * which is important to keep your JAR size down, if you're so bothered. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CustomImage { /** * The resource path to the image, a {@link net.minecraft.resources.ResourceLocation} * is constructed with the namespace being the modid of the config, and the path being * this value. * <p> * The following file formats are supported: * <ul> * <li>{@code .png}</li> * <li>{@code .webp}</li> * <li>{@code .jpg}, {@code .jpeg}</li> * </ul> * <p> * If left blank, then {@link CustomImage#factory()} is used. */ String value() default ""; /** * The width of the image, in pixels. * <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong> */ int width() default 0; /** * The width of the image, in pixels. * <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong> */ int height() default 0; /** * The factory to create the image with. * For the average user, this should not be used as it breaks out of the * API-safe environment where things could change at any time, but required * when creating anything advanced with the {@link ImageRenderer}. * <p> * The factory should contain a public, no-args constructor that will be * invoked via reflection. * * @return the class of the factory */
package dev.tcl.config.api.autogen; /** * Defines a custom image for an option. * Without this annotation, the option factory will look * for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}. * WEBP was chosen as the default format because file sizes are greatly reduced, * which is important to keep your JAR size down, if you're so bothered. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CustomImage { /** * The resource path to the image, a {@link net.minecraft.resources.ResourceLocation} * is constructed with the namespace being the modid of the config, and the path being * this value. * <p> * The following file formats are supported: * <ul> * <li>{@code .png}</li> * <li>{@code .webp}</li> * <li>{@code .jpg}, {@code .jpeg}</li> * </ul> * <p> * If left blank, then {@link CustomImage#factory()} is used. */ String value() default ""; /** * The width of the image, in pixels. * <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong> */ int width() default 0; /** * The width of the image, in pixels. * <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong> */ int height() default 0; /** * The factory to create the image with. * For the average user, this should not be used as it breaks out of the * API-safe environment where things could change at any time, but required * when creating anything advanced with the {@link ImageRenderer}. * <p> * The factory should contain a public, no-args constructor that will be * invoked via reflection. * * @return the class of the factory */
Class<? extends CustomImageFactory<?>> factory() default EmptyCustomImageFactory.class;
0
2023-12-25 14:48:27+00:00
2k
flyingpig2016/itheima_web_project
tlias-web-management/src/main/java/com/itheima/filter/LoginCheckFilter.java
[ { "identifier": "Result", "path": "springboot-web-config2/src/main/java/com/itheima/pojo/Result.java", "snippet": "@Data\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class Result {\r\n private Integer code;//响应码,1 代表成功; 0 代表失败\r\n private String msg; //响应码 描述字符串\r\n private Object data; //返回的数据\r\n\r\n //增删改 成功响应\r\n public static Result success(){\r\n return new Result(1,\"success\",null);\r\n }\r\n //查询 成功响应\r\n public static Result success(Object data){\r\n return new Result(1,\"success\",data);\r\n }\r\n //失败响应\r\n public static Result error(String msg){\r\n return new Result(0,msg,null);\r\n }\r\n}\r" }, { "identifier": "JwtUtils", "path": "tlias-web-management/src/main/java/com/itheima/utils/JwtUtils.java", "snippet": "public class JwtUtils {\r\n\r\n private static String signKey = \"itheima\";\r\n private static Long expire = 43200000L;\r\n\r\n /**\r\n * 生成JWT令牌\r\n * @param claims JWT第二部分负载 payload 中存储的内容\r\n * @return\r\n */\r\n public static String generateJwt(Map<String, Object> claims){\r\n String jwt = Jwts.builder()\r\n .addClaims(claims)\r\n .signWith(SignatureAlgorithm.HS256, signKey)\r\n .setExpiration(new Date(System.currentTimeMillis() + expire))\r\n .compact();\r\n return jwt;\r\n }\r\n\r\n /**\r\n * 解析JWT令牌\r\n * @param jwt JWT令牌\r\n * @return JWT第二部分负载 payload 中存储的内容\r\n */\r\n public static Claims parseJWT(String jwt){\r\n Claims claims = Jwts.parser()\r\n .setSigningKey(signKey)\r\n .parseClaimsJws(jwt)\r\n .getBody();\r\n return claims;\r\n }\r\n}\r" } ]
import com.alibaba.fastjson.JSONObject; import com.aliyuncs.utils.StringUtils; import com.itheima.pojo.Result; import com.itheima.utils.JwtUtils; import io.jsonwebtoken.Claims; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import java.io.IOException;
864
package com.itheima.filter; @Slf4j //@WebFilter(urlPatterns = "/*") public class LoginCheckFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; // 1. 获取请求url String url = req.getRequestURI().toString(); System.out.println("请求的url是:" + url); // 2. 判断url是否包含Login,如果包含,放行 if (url.contains("/login")) { filterChain.doFilter(req, resp); return; } // 3. 获取请求头里面的token String token = req.getHeader("token"); // 4. 判断token是否为空,如果不存在,返回错误结果(未登录) if (StringUtils.isEmpty(token)) { log.info("请求头token为空,返回未登录的信息"); Result error = Result.error("NOT_LOGIN"); //手动转换对象 --json ------>阿里巴巴fastJSON String notLogin = JSONObject.toJSONString(error); resp.getWriter().write(notLogin); return; } // 5. 判断token是否有效,如果解析失败,返回错误结果未登录 try {
package com.itheima.filter; @Slf4j //@WebFilter(urlPatterns = "/*") public class LoginCheckFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; // 1. 获取请求url String url = req.getRequestURI().toString(); System.out.println("请求的url是:" + url); // 2. 判断url是否包含Login,如果包含,放行 if (url.contains("/login")) { filterChain.doFilter(req, resp); return; } // 3. 获取请求头里面的token String token = req.getHeader("token"); // 4. 判断token是否为空,如果不存在,返回错误结果(未登录) if (StringUtils.isEmpty(token)) { log.info("请求头token为空,返回未登录的信息"); Result error = Result.error("NOT_LOGIN"); //手动转换对象 --json ------>阿里巴巴fastJSON String notLogin = JSONObject.toJSONString(error); resp.getWriter().write(notLogin); return; } // 5. 判断token是否有效,如果解析失败,返回错误结果未登录 try {
Claims claims = JwtUtils.parseJWT(token);
1
2023-12-25 08:52:04+00:00
2k
vadage/rs4j
src/main/java/space/provided/rs/result/Result.java
[ { "identifier": "ValueAccessError", "path": "src/main/java/space/provided/rs/error/ValueAccessError.java", "snippet": "public final class ValueAccessError extends Error {\n\n public ValueAccessError(String message) {\n super(message);\n }\n}" }, { "identifier": "ArgInvokable", "path": "src/main/java/space/provided/rs/ops/ArgInvokable.java", "snippet": "@FunctionalInterface\npublic interface ArgInvokable<Value, ReturnType> {\n\n ReturnType invoke(Value value);\n}" }, { "identifier": "ArgVoidInvokable", "path": "src/main/java/space/provided/rs/ops/ArgVoidInvokable.java", "snippet": "@FunctionalInterface\npublic interface ArgVoidInvokable<Value> {\n\n void invoke(Value value);\n}" } ]
import space.provided.rs.error.ValueAccessError; import space.provided.rs.ops.ArgInvokable; import space.provided.rs.ops.ArgVoidInvokable;
850
package space.provided.rs.result; public final class Result<Ok, Error> { private final Ok ok; private final Error error; private final ResultType type; private Result(ResultType type, Ok ok, Error error) { this.type = type; this.ok = ok; this.error = error; } public static <Ok, Err> Result<Ok, Err> ok() { return ok(null); } public static <Ok, Err> Result<Ok, Err> ok(Ok value) { return new Result<>(ResultType.OK, value, null); } public static <Ok, Err> Result<Ok, Err> error() { return error(null); } public static <Ok, Err> Result<Ok, Err> error(Err value) { return new Result<>(ResultType.ERROR, null, value); } public Ok unwrap() throws ValueAccessError { if (!isOk()) { throw new ValueAccessError("Called `unwrap` on %1$s Result.".formatted(type)); } return ok; } public Error unwrapError() throws ValueAccessError { if (!isError()) { throw new ValueAccessError("Called `unwrapError` on %1$s Result.".formatted(type)); } return error; } public boolean isOk() { return type.equals(ResultType.OK); } public boolean isOkAnd(ArgInvokable<Ok, Boolean> invokable) { return switch (type) { case ERROR -> false; case OK -> invokable.invoke(ok); }; } public boolean isError() { return !isOk(); } public boolean isErrorAnd(ArgInvokable<Error, Boolean> invokable) { return switch (type) { case OK -> false; case ERROR -> invokable.invoke(error); }; } public <Mapped> Result<Mapped, Error> map(ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> Result.ok(invokable.invoke(ok)); case ERROR -> Result.error(error); }; } public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> fallback; }; } public <Mapped> Mapped mapOrElse(ArgInvokable<Error, Mapped> fallback, ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> fallback.invoke(error); }; } public Result<Ok, Error> and(Result<Ok, Error> result) { return switch (type) { case OK -> result; case ERROR -> Result.error(error); }; } public Result<Ok, Error> andThen(ArgInvokable<Ok, Result<Ok, Error>> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> Result.error(error); }; }
package space.provided.rs.result; public final class Result<Ok, Error> { private final Ok ok; private final Error error; private final ResultType type; private Result(ResultType type, Ok ok, Error error) { this.type = type; this.ok = ok; this.error = error; } public static <Ok, Err> Result<Ok, Err> ok() { return ok(null); } public static <Ok, Err> Result<Ok, Err> ok(Ok value) { return new Result<>(ResultType.OK, value, null); } public static <Ok, Err> Result<Ok, Err> error() { return error(null); } public static <Ok, Err> Result<Ok, Err> error(Err value) { return new Result<>(ResultType.ERROR, null, value); } public Ok unwrap() throws ValueAccessError { if (!isOk()) { throw new ValueAccessError("Called `unwrap` on %1$s Result.".formatted(type)); } return ok; } public Error unwrapError() throws ValueAccessError { if (!isError()) { throw new ValueAccessError("Called `unwrapError` on %1$s Result.".formatted(type)); } return error; } public boolean isOk() { return type.equals(ResultType.OK); } public boolean isOkAnd(ArgInvokable<Ok, Boolean> invokable) { return switch (type) { case ERROR -> false; case OK -> invokable.invoke(ok); }; } public boolean isError() { return !isOk(); } public boolean isErrorAnd(ArgInvokable<Error, Boolean> invokable) { return switch (type) { case OK -> false; case ERROR -> invokable.invoke(error); }; } public <Mapped> Result<Mapped, Error> map(ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> Result.ok(invokable.invoke(ok)); case ERROR -> Result.error(error); }; } public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> fallback; }; } public <Mapped> Mapped mapOrElse(ArgInvokable<Error, Mapped> fallback, ArgInvokable<Ok, Mapped> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> fallback.invoke(error); }; } public Result<Ok, Error> and(Result<Ok, Error> result) { return switch (type) { case OK -> result; case ERROR -> Result.error(error); }; } public Result<Ok, Error> andThen(ArgInvokable<Ok, Result<Ok, Error>> invokable) { return switch (type) { case OK -> invokable.invoke(ok); case ERROR -> Result.error(error); }; }
public Result<Ok, Error> andThenContinue(ArgVoidInvokable<Ok> invokable) {
2
2023-12-27 15:33:17+00:00
2k
wicksonZhang/Spring-Cloud
03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/service/impl/PaymentServiceImpl.java
[ { "identifier": "PaymentConvert", "path": "03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/convert/PaymentConvert.java", "snippet": "@Mapper\npublic interface PaymentConvert {\n\n PaymentConvert INSTANCE = Mappers.getMapper(PaymentConvert.class);\n\n /**\n * 转实体\n *\n * @param paymentVO\n * @return Payment\n */\n Payment toEntity(PaymentCreateReqVO paymentVO);\n\n /**\n * 转DTO\n *\n * @param payment\n * @return PaymentRespDTO\n */\n PaymentRespDTO toDTO(Payment payment);\n}" }, { "identifier": "IPaymentService", "path": "03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/service/IPaymentService.java", "snippet": "public interface IPaymentService {\n\n /**\n * 创建支付订单信息\n *\n * @param paymentVO 支付info\n */\n void create(PaymentCreateReqVO paymentVO);\n\n /**\n * 返回指定信息\n *\n * @param id 订单id\n * @return PaymentRespDTO\n */\n PaymentRespDTO getById(Long id);\n}" }, { "identifier": "PaymentRespDTO", "path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/dto/PaymentRespDTO.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class PaymentRespDTO implements ResultUnpacked, Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 支付ID\n */\n private Long id;\n\n /**\n * 支付金额\n */\n private String amount;\n\n /**\n * 请求端口\n */\n private int port;\n\n /**\n * 获取类实例\n *\n * @return\n */\n public static PaymentRespDTO getInstance() {\n return new PaymentRespDTO();\n }\n\n}" }, { "identifier": "Payment", "path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/entity/Payment.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Payment implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 支付ID\n */\n private Long id;\n\n /**\n * 支付金额\n */\n private String amount;\n\n}" }, { "identifier": "PaymentCreateReqVO", "path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/vo/PaymentCreateReqVO.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PaymentCreateReqVO {\n\n /**\n * 支付ID\n */\n @NotNull(message = \"支付ID不为空\")\n private Long id;\n\n /**\n * 支付金额\n */\n @NotNull(message = \"支付金额不为空\")\n private BigDecimal amount;\n\n}" } ]
import cn.hutool.core.collection.CollUtil; import cn.wickson.cloud.cluster.eureka.payment2.convert.PaymentConvert; import cn.wickson.cloud.cluster.eureka.payment2.service.IPaymentService; import cn.wickson.cloud.common.model.dto.PaymentRespDTO; import cn.wickson.cloud.common.model.entity.Payment; import cn.wickson.cloud.common.model.vo.PaymentCreateReqVO; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
918
package cn.wickson.cloud.cluster.eureka.payment2.service.impl; /** * 支付服务-应用服务实现类 * * @author ZhangZiHeng * @date 2023-12-27 */ @Service public class PaymentServiceImpl implements IPaymentService {
package cn.wickson.cloud.cluster.eureka.payment2.service.impl; /** * 支付服务-应用服务实现类 * * @author ZhangZiHeng * @date 2023-12-27 */ @Service public class PaymentServiceImpl implements IPaymentService {
private static final List<Payment> LIST = new ArrayList<>();
3
2023-12-27 09:42:02+00:00
2k
behnamnasehi/playsho
app/src/main/java/com/playsho/android/db/SessionStorage.java
[ { "identifier": "ApplicationLoader", "path": "app/src/main/java/com/playsho/android/base/ApplicationLoader.java", "snippet": "public class ApplicationLoader extends Application {\n private static final String TAG = \"ApplicationLoader\";\n @SuppressLint(\"StaticFieldLeak\")\n private static Context context;\n\n private static Gson gson;\n private static SessionStorage sessionStorage;\n\n /**\n * Gets the name of the ApplicationLoader class.\n *\n * @return The name of the ApplicationLoader class.\n */\n @NonNull\n public static String getOriginName() {\n return ApplicationLoader.class.getSimpleName();\n }\n\n /**\n * Called when the application is first created. Initializes the application context, Gson, and SessionStorage.\n */\n public void onCreate() {\n super.onCreate();\n context = getApplicationContext();\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n gson = new Gson();\n ApplicationLoader.sessionStorage = new SessionStorage();\n try {\n DimensionUtils.checkDisplaySize(context, null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Gets the application context.\n *\n * @return The application context.\n */\n public static Context getAppContext() {\n return ApplicationLoader.context;\n }\n\n /**\n * Called when the configuration of the device changes.\n *\n * @param newConfig The new configuration.\n */\n @Override\n public void onConfigurationChanged(@NonNull Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n try {\n DimensionUtils.checkDisplaySize(context, newConfig);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Gets the SessionStorage instance for managing session storage.\n *\n * @return The SessionStorage instance.\n */\n public static SessionStorage getSessionStorage() {\n return ApplicationLoader.sessionStorage;\n }\n\n /**\n * Gets the Gson instance for JSON serialization and deserialization.\n *\n * @return The Gson instance.\n */\n public static Gson getGson() {\n return ApplicationLoader.gson;\n }\n\n}" }, { "identifier": "Validator", "path": "app/src/main/java/com/playsho/android/utils/Validator.java", "snippet": "public class Validator {\n\n /**\n * Checks if a string is null or empty.\n *\n * @param string The string to check.\n * @return {@code true} if the string is null or empty, {@code false} otherwise.\n */\n public static boolean isNullOrEmpty(String string) {\n return TextUtils.isEmpty(string);\n }\n\n /**\n * Checks if a reference is null.\n *\n * @param reference The reference to check.\n * @param <T> The type of the reference.\n * @return {@code true} if the reference is null, {@code false} otherwise.\n */\n public static <T> boolean isNull(T reference) {\n return reference == null;\n }\n\n /**\n * Checks if a string is a valid Iran phone number.\n *\n * @param phone The phone number to check.\n * @return {@code true} if the phone number is a valid Iran phone number, {@code false} otherwise.\n */\n public static boolean isIranPhoneNumber(String phone) {\n if (isNullOrEmpty(phone)) return false;\n boolean starter = phone.startsWith(\"09\") || phone.startsWith(\"+98\");\n return starter && phone.length() >= 11;\n }\n\n /**\n * Checks if a string has a specific length.\n *\n * @param content The string to check.\n * @param length The expected length.\n * @return {@code true} if the string has the specified length, {@code false} otherwise.\n */\n public static boolean hasLength(String content, int length) {\n return !isNullOrEmpty(content) && content.length() == length;\n }\n\n /**\n * Checks if the length of a string is greater than a specified value.\n *\n * @param content The string to check.\n * @param length The minimum length.\n * @return {@code true} if the string length is greater than the specified value, {@code false} otherwise.\n */\n public static boolean isGreaterThan(String content, int length) {\n return !isNullOrEmpty(content) && content.length() > length;\n }\n\n /**\n * Gets the string value or a default if it is null or empty.\n *\n * @param s The string to check.\n * @param def The default value.\n * @return The original string if not null or empty, otherwise the default value.\n */\n public static String getDefaultIfNullOrEmpty(String s, String def) {\n return isNullOrEmpty(s) ? def : s;\n }\n\n /**\n * Checks if the length of a string is smaller than a specified value.\n *\n * @param content The string to check.\n * @param length The maximum length.\n * @return {@code true} if the string length is smaller than the specified value, {@code false} otherwise.\n */\n public static boolean isSmallerThan(String content, int length) {\n return !isNullOrEmpty(content) && content.length() < length;\n }\n\n /**\n * Checks if two integers are equal.\n *\n * @param a The first integer.\n * @param b The second integer.\n * @return {@code true} if the integers are equal, {@code false} otherwise.\n */\n public static boolean isEqual(int a, int b) {\n return a == b;\n }\n\n /**\n * Checks if two strings are equal (handling null values).\n *\n * @param a The first string.\n * @param b The second string.\n * @return {@code true} if the strings are equal, {@code false} otherwise.\n */\n public static boolean isEqual(String a, String b) {\n return Objects.equals(a, b);\n }\n}" } ]
import android.content.Context; import android.content.SharedPreferences; import com.playsho.android.base.ApplicationLoader; import com.playsho.android.utils.Validator;
1,547
package com.playsho.android.db; /** * A class for managing session storage using SharedPreferences. */ public class SessionStorage { private final SharedPreferences pref; private final SharedPreferences.Editor editor; // Name of the shared preference file private final String SHARED_PREFERENCE_NAME = "main_sp"; /** * Constructs a SessionStorage instance and initializes SharedPreferences and its editor. */ public SessionStorage() {
package com.playsho.android.db; /** * A class for managing session storage using SharedPreferences. */ public class SessionStorage { private final SharedPreferences pref; private final SharedPreferences.Editor editor; // Name of the shared preference file private final String SHARED_PREFERENCE_NAME = "main_sp"; /** * Constructs a SessionStorage instance and initializes SharedPreferences and its editor. */ public SessionStorage() {
this.pref = ApplicationLoader.getAppContext().getSharedPreferences(
0
2023-12-26 08:14:29+00:00
2k

RepoBench v1.1 (Java)

Introduction

This dataset presents the Java portion of RepoBench v1.1 (ICLR 2024). The data encompasses a collection from GitHub, spanning the period from October 6th to December 31st, 2023. With a commitment to data integrity, we've implemented a deduplication process based on file content against the Stack v2 dataset (coming soon), aiming to mitigate data leakage and memorization concerns.

Resources and Links

FAQs

  • Q: What do the features in the dataset mean?

    A: Imagine you're coding and you want to write the next line of your code. The dataset provides you the following information:

    • repo_name (string): the name of the repository
    • file_path (string): the path of the current file
    • context (list): the cross-file code snippets that might be helpful for writing the next line:
      • identifier (string): the identifier of the code snippet
      • path (string): the path of the code snippet
      • snippet (string): the code snippet
    • import_statement (string): the import statement of the current file
    • cropped_code (string): the cropped code of the current file (up to previous 120 lines)
    • all_code (string): the entire code of the current file (not cropped)
    • next_line (string): the next line of the code (this serves as the target)
    • gold_snippet_index (int): the index of the gold snippet in the context (which will be used in next line, just for reference, you should not use this for next line prediction)
    • created_at (string): the creation time of the repository
    • level (string): the level of next line completion, which is measured by the number of tokens for the whole prompt (including all the context, import statement, cropped code and some neccessary separator tokens)
  • Q: How does the level be defined?

    A: The level is determined by the number of tokens for the whole prompt (including all the context, import statement, cropped code and some neccessary separator tokens). The token number is calculated by the tokenizer of GPT-4 by using tiktoken. The following table shows the level definition:

    Level Prompt Length (Number of Tokens)
    2k 640 - 1,600
    4k 1,600 - 3,600
    8k 3,600 - 7,200
    12k 7,200 - 10,800
    16k 10,800 - 14,400
    24k 14,400 - 21,600
    32k 21,600 - 28,800
    64k 28,800 - 57,600
    128k 57,600 - 100,000
  • Q: What does the different splits mean?

    A: The dataset is split into three parts:

    • cross_file_first: the next line of code utilizes content from a cross-file code snippet and it is its first usage within current file.
    • cross_file_random: the next line of code utilizes content from a cross-file code snippet and it is NOT its first usage within current file.
    • in_file: the next line of code does not utilize content from a cross-file code snippet.
  • Q: How to construct the prompt for next line prediction?

    A: We hereby provide the official implementation for constructing prompts. Please note that the methods described below are not necessarily the optimal way of construction. Reordering, retrieval argumentation, or employing different cropping/construction techniques could potentially lead to varying degrees of improvement. Ensure that your model evaluations are conducted in a fair manner.

    import re
    
    def construct_prompt(
        data: dict, 
        language: str = "java",
        tokenizer= None,
        max_token_nums: int = 15800
        ) -> str:
        """
        Construct the prompt for next line prediction.
    
        :param data: data point from the dataset
        :param language: the language of the code
        :param tokenizer: the tokenizer of the evaluation model
        :param max_token_nums: the maximum number of tokens constraint for the prompt
    
        :return: the constructed prompt
        """
    
        # comment symbol for different languages
        comment_symbol = "#" if language == "python" else "//"
    
        # construct the cross-file prompt and in-file prompt separately
        # cross-file prompt
        cross_file_prompt = f"{comment_symbol} Repo Name: {data['repo_name']}\n"
    
        for snippet in data['context']:
            cross_file_prompt += f"{comment_symbol} Path: {snippet['path']}\n{snippet['snippet']}" + "\n\n"
        
        # in-file prompt
        in_file_prompt = f"{comment_symbol} Path: {data['file_path']}\n{data['import_statement']}\n{data['cropped_code']}\n"
    
        # if we assign the tokenizer and the max_token_nums, we will truncate the cross-file prompt to meet the constraint
        if tokenizer is not None and max_token_nums is not None:
            
            cross_file_prompt_token_nums = len(tokenizer.encode(cross_file_prompt))
            in_file_prompt_token_nums = len(tokenizer.encode(in_file_prompt))
    
            exceed_token_nums = cross_file_prompt_token_nums + in_file_prompt_token_nums - max_token_nums
    
            if exceed_token_nums > 0:
                # split the cross-file prompt into lines
                cross_file_prompt_lines = cross_file_prompt.split("\n")
                # drop lines from end until the extra token number is less than 0
                for i in range(len(repo_prompt_lines)-1, -1, -1):
                    extra_token_num -= len(tokenizer.encode(cross_file_prompt_lines[i]))
                    if extra_token_num < 0:
                        break
                
                # join the lines back
                cross_file_prompt = "\n".join(cross_file_prompt_lines[:i]) + "\n\n"
        
        # combine the cross-file prompt and in-file prompt
        prompt = cross_file_prompt + in_file_prompt
    
        # normalize some empty lines
        prompt = re.sub(r'\n{4,}', '\n\n', prompt)
    
        return prompt
    
  • Q: How to load the dataset?

    A: You can simply use the following code to load the dataset:

    from datasets import load_dataset
    
    dataset = load_dataset("tianyang/repobench_java_v1.1")
    

    To construct the prompt for next line prediction, you can refer to the official implementation provided in the previous question and use the construct_prompt function to construct the prompt, for example:

    from transformers import AutoTokenizer, AutoModelForCausalLM
    
    tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-1.3b-base")
    model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-1.3b-base")
    
    prompt = construct_prompt(dataset['cross_file_first'][0], language="java", tokenizer=tokenizer, max_token_nums=15800)
    
  • Q: How often will the dataset be updated?

    A: We plan to update the dataset every three months, but there might be slight delays considering the time required for data crawling and our own schedules. If you require updated data, please feel free to contact us, and we can coordinate the timing and expedite the process.

  • Q: What models should I use to evaluate the dataset?

    A: RepoBench is designed to evaluate base models, not those that have been instruction fine-tuned. Please use base models for evaluation.

  • Q: I am training a new model but the knowledge cutoff date is after the dataset's. Can you provide me with the latest data?

    A: Sure! We are happy to provide you with the latest data (even customized data with specific requirements). Please feel free to contact us.

  • Q: Can I opt-out?

    A: Yes, you can opt-out your repository from the dataset. Please check Am I in RepoBench?, we will upload the raw data of the repository information we crawled at least 15 days before the dataset creation and release. We will respect your decision and remove your repository from the dataset if you opt-out.

Citation

If you find RepoBench useful in your research, please consider citing the paper using the following BibTeX entry:

@misc{liu2023repobench,
      title={RepoBench: Benchmarking Repository-Level Code Auto-Completion Systems}, 
      author={Tianyang Liu and Canwen Xu and Julian McAuley},
      year={2024},
      url={https://arxiv.org/abs/2306.03091},
      booktitle={International Conference on Learning Representations}
}

Your interest and contributions to RepoBench are immensely valued. Happy coding! 🚀

Downloads last month
163
Edit dataset card