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
zxzf1234/jimmer-ruoyivuepro
backend/yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/apilog/core/service/ApiAccessLogFrameworkServiceImpl.java
[ { "identifier": "ApiAccessLogApi", "path": "backend/yudao-service/yudao-service-api/src/main/java/cn/iocoder/yudao/service/api/infra/logger/ApiAccessLogApi.java", "snippet": "public interface ApiAccessLogApi {\n\n /**\n * 创建 API 访问日志\n *\n * @param createDTO 创建信息\n */\n void createApiAccessLog(@Valid ApiAccessLogCreateReqDTO createDTO);\n\n}" }, { "identifier": "ApiAccessLogCreateReqDTO", "path": "backend/yudao-service/yudao-service-api/src/main/java/cn/iocoder/yudao/service/api/infra/logger/dto/ApiAccessLogCreateReqDTO.java", "snippet": "@Data\npublic class ApiAccessLogCreateReqDTO {\n\n /**\n * 链路追踪编号\n */\n private String traceId;\n /**\n * 用户编号\n */\n private Long userId;\n /**\n * 用户类型\n */\n private Integer userType;\n /**\n * 应用名\n */\n @NotNull(message = \"应用名不能为空\")\n private String applicationName;\n\n /**\n * 请求方法名\n */\n @NotNull(message = \"http 请求方法不能为空\")\n private String requestMethod;\n /**\n * 访问地址\n */\n @NotNull(message = \"访问地址不能为空\")\n private String requestUrl;\n /**\n * 请求参数\n */\n @NotNull(message = \"请求参数不能为空\")\n private String requestParams;\n /**\n * 用户 IP\n */\n @NotNull(message = \"ip 不能为空\")\n private String userIp;\n /**\n * 浏览器 UA\n */\n @NotNull(message = \"User-Agent 不能为空\")\n private String userAgent;\n\n /**\n * 开始请求时间\n */\n @NotNull(message = \"开始请求时间不能为空\")\n private LocalDateTime beginTime;\n /**\n * 结束请求时间\n */\n @NotNull(message = \"结束请求时间不能为空\")\n private LocalDateTime endTime;\n /**\n * 执行时长,单位:毫秒\n */\n @NotNull(message = \"执行时长不能为空\")\n private Integer duration;\n /**\n * 结果码\n */\n @NotNull(message = \"错误码不能为空\")\n private Integer resultCode;\n /**\n * 结果提示\n */\n private String resultMsg;\n\n}" } ]
import cn.hutool.core.bean.BeanUtil; import cn.iocoder.yudao.service.api.infra.logger.ApiAccessLogApi; import cn.iocoder.yudao.service.api.infra.logger.dto.ApiAccessLogCreateReqDTO; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.annotation.Async;
749
package cn.iocoder.yudao.framework.apilog.core.service; /** * API 访问日志 Framework Service 实现类 * * 基于 {@link ApiAccessLogApi} 服务,记录访问日志 * * @author 芋道源码 */ @RequiredArgsConstructor public class ApiAccessLogFrameworkServiceImpl implements ApiAccessLogFrameworkService {
package cn.iocoder.yudao.framework.apilog.core.service; /** * API 访问日志 Framework Service 实现类 * * 基于 {@link ApiAccessLogApi} 服务,记录访问日志 * * @author 芋道源码 */ @RequiredArgsConstructor public class ApiAccessLogFrameworkServiceImpl implements ApiAccessLogFrameworkService {
private final ApiAccessLogApi apiAccessLogApi;
0
2023-10-27 06:35:24+00:00
2k
matheusmisumoto/workout-logger-api
src/main/java/dev/matheusmisumoto/workoutloggerapi/model/Exercise.java
[ { "identifier": "ExerciseEquipmentType", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/type/ExerciseEquipmentType.java", "snippet": "public enum ExerciseEquipmentType {\r\n\tBANDS(\"Bands\"),\r\n\tFOAM_ROLL(\"Foam Roll\"),\r\n\tBARBELL(\"Barbell\"),\r\n\tKETTLEBELLS(\"Kettlebells\"),\r\n\tBODY_ONLY(\"Body Only\"),\r\n\tMACHINE(\"Machine\"),\r\n\tCABLE(\"Cable\"),\r\n\tMEDICINE_BALL(\"Medicine Ball\"),\r\n\tDUMBBELL(\"Dumbbell\"),\r\n\tEZ_CURL_BAR(\"E-Z Curl Bar\"),\r\n\tEXERCISE_BALL(\"Exercise Ball\"),\r\n\tOTHER(\"Other\");\r\n\t\r\n\tprivate final String description;\r\n\r\n\tprivate ExerciseEquipmentType(String description) {\r\n\t\tthis.description = description;\r\n\t}\r\n\r\n\tpublic String getDescription() {\r\n\t\treturn description;\r\n\t}\r\n\t\r\n\t public static ExerciseEquipmentType valueOfDescription(String description) {\r\n\t\t for (ExerciseEquipmentType equipment : ExerciseEquipmentType.values()) {\r\n\t\t\t if (equipment.getDescription().equalsIgnoreCase(description)) {\r\n\t\t\t\t return equipment;\r\n\t }\r\n\t }\r\n\t throw new IllegalArgumentException(\"No matching ExerciseEquipmentType for description: \" + description);\r\n\t }\r\n\t\r\n\r\n}\r" }, { "identifier": "ExerciseTargetType", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/type/ExerciseTargetType.java", "snippet": "public enum ExerciseTargetType {\r\n\tCHEST(\"Chest\"),\r\n\tFOREARMS(\"Forearms\"),\r\n\tLATS(\"Lats\"),\r\n\tMIDDLE_BACK(\"Middle Back\"),\r\n\tLOWER_BACK(\"Lower Back\"),\r\n\tNECK(\"Neck\"),\r\n\tQUADRICEPS(\"Quadriceps\"),\r\n\tHAMSTRINGS(\"Hamstrings\"),\r\n\tCALVES(\"Calves\"),\r\n\tTRICEPS(\"Triceps\"),\r\n\tTRAPS(\"Traps\"),\r\n\tSHOULDERS(\"Shoulders\"),\r\n\tABDOMINALS(\"Abdominals\"),\r\n\tGLUTES(\"Glutes\"),\r\n\tBICEPS(\"Biceps\"),\r\n\tADDUCTORS(\"Adductors\"),\r\n\tABDUCTORS(\"Abductors\"),\r\n\tOTHER(\"Other\");\r\n\t\r\n\tprivate final String description;\r\n\t\r\n\tprivate ExerciseTargetType(String description) {\r\n\t\tthis.description = description;\r\n\t}\r\n\r\n\tpublic String getDescription() {\r\n\t\treturn description;\r\n\t}\r\n\r\n\t public static ExerciseTargetType valueOfDescription(String description) {\r\n\t\t for (ExerciseTargetType muscleType : ExerciseTargetType.values()) {\r\n\t\t\t if (muscleType.getDescription().equalsIgnoreCase(description)) {\r\n\t\t\t\t return muscleType;\r\n\t }\r\n\t }\r\n\t throw new IllegalArgumentException(\"No matching ExerciseMuscleType for description: \" + description);\r\n\t }\r\n}\r" } ]
import java.io.Serializable; import java.util.UUID; import org.springframework.hateoas.RepresentationModel; import dev.matheusmisumoto.workoutloggerapi.type.ExerciseEquipmentType; import dev.matheusmisumoto.workoutloggerapi.type.ExerciseTargetType; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table;
845
package dev.matheusmisumoto.workoutloggerapi.model; @Entity @Table(name = "exercises") public class Exercise extends RepresentationModel<Exercise> implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private UUID id; private String name; @Enumerated(EnumType.STRING) private ExerciseTargetType target; @Enumerated(EnumType.STRING)
package dev.matheusmisumoto.workoutloggerapi.model; @Entity @Table(name = "exercises") public class Exercise extends RepresentationModel<Exercise> implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private UUID id; private String name; @Enumerated(EnumType.STRING) private ExerciseTargetType target; @Enumerated(EnumType.STRING)
private ExerciseEquipmentType equipment;
0
2023-10-29 23:18:38+00:00
2k
jaszlo/Playerautoma
src/main/java/net/jasper/mod/automation/QuickSlots.java
[ { "identifier": "PlayerAutomaClient", "path": "src/main/java/net/jasper/mod/PlayerAutomaClient.java", "snippet": "public class PlayerAutomaClient implements ClientModInitializer {\n\n public static final Logger LOGGER = LoggerFactory.getLogger(\"playerautoma::client\");\n\tpublic static final String RECORDING_FOLDER_NAME = \"Recordings\";\n\tpublic static final String RECORDING_PATH = Path.of(MinecraftClient.getInstance().runDirectory.getAbsolutePath(), RECORDING_FOLDER_NAME).toString();\n\n\n\t@Override\n\tpublic void onInitializeClient() {\n\t\t// Create folder for recordings if not exists\n\t\tFile recordingFolder = new File(RECORDING_PATH);\n\t\tif (!recordingFolder.exists()) {\n\t\t\tboolean failed = !recordingFolder.mkdir();\n\t\t\t// Do not initialize mod if failed to create folder (should not happen)\n\t\t\tif (failed) {\n\t\t\t\tLOGGER.error(\"Failed to create recording folder - PlayerAutoma will not be initialized\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Initialize New Keybinds\n\t\tPlayerAutomaKeyBinds.register();\n\n\t\t// Register Inventory-Automations (Re-Stacking of Blocks)\n\t\tInventoryAutomation.registerInventoryAutomation();\n\n\t\t// Register Player-Recorder (Recording & Replaying)\n\t\tPlayerRecorder.registerInputRecorder();\n\n\t\t// Register Quick slots for Player-Recorder\n\t\tQuickSlots.register();\n\t}\n}" }, { "identifier": "PlayerController", "path": "src/main/java/net/jasper/mod/util/PlayerController.java", "snippet": "public class PlayerController {\n public static void centerPlayer() {\n // Center Camera\n PlayerEntity player= MinecraftClient.getInstance().player;\n assert player != null;\n player.setPitch(0);\n player.setYaw(90);\n\n // Center player on current block\n Vec3d playerPos = player.getPos();\n BlockPos blockPos = new BlockPos((int) Math.floor(playerPos.x), (int) Math.floor(playerPos.y) - 1, (int) Math.floor(playerPos.z));\n player.setPosition(blockPos.getX() + 0.5, blockPos.getY() + 1.0, blockPos.getZ() + 0.5);\n }\n\n public static void writeToChat(String message) {\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.sendMessage(Text.of(message));\n }\n }\n\n public static void clickSlot(SlotClick click) {\n MinecraftClient client = MinecraftClient.getInstance();\n assert client.player != null;\n assert client.interactionManager != null;\n client.interactionManager.clickSlot(client.player.currentScreenHandler.syncId, click.slotId(), click.button(), click.actionType(), client.player);\n }\n}" }, { "identifier": "Recording", "path": "src/main/java/net/jasper/mod/util/data/Recording.java", "snippet": "public class Recording implements Serializable {\n public record RecordEntry(\n List<Boolean> keysPressed,\n LookingDirection lookingDirection,\n int slotSelection,\n SlotClick slotClicked, Class<?> currentScreen\n ) implements Serializable {}\n\n public final List<RecordEntry> entries = new ArrayList<>();\n\n public String toString() {\n return \"Recording[\" + this.entries.size() + \"]\";\n }\n\n public void clear() {\n entries.clear();\n }\n\n public void add(RecordEntry entry) {\n entries.add(entry);\n }\n public boolean isEmpty() {\n return entries.isEmpty();\n }\n\n public Recording copy() {\n Recording copy = new Recording();\n copy.entries.addAll(this.entries);\n return copy;\n }\n}" } ]
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.jasper.mod.PlayerAutomaClient; import net.jasper.mod.util.PlayerController; import net.jasper.mod.util.data.Recording; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import org.lwjgl.glfw.GLFW; import java.util.Arrays;
1,493
package net.jasper.mod.automation; /** * QuickSlots for storing and loading Recordings for the PlayerRecorder */ public class QuickSlots { public static Recording[] quickSlots = new Recording[9]; // KeyBinding State private static final int[] storeCooldowns = new int[9]; private static final int[] loadCooldowns = new int[9]; private static final boolean[] CTRLPressed = new boolean[9]; private static final boolean[] ALTPressed = new boolean[9]; private static final int COOLDOWN = 5; public static void store(int slot, Recording recording) { quickSlots[slot] = recording; } public static Recording load(int slot) { return quickSlots[slot]; } // Initialize State static { Arrays.fill(quickSlots, null); Arrays.fill(ALTPressed, false); Arrays.fill(CTRLPressed, false); Arrays.fill(storeCooldowns, 0); Arrays.fill(loadCooldowns, 0); } private static void handleQuickSlotKeyPress(long handle, int[] cooldowns, boolean[] pressed) { for (int i = 0; i < pressed.length; i++) { if (cooldowns[i] > 0) { cooldowns[i]--; continue; } pressed[i] = InputUtil.isKeyPressed(handle, GLFW.GLFW_KEY_1 + i); if (pressed[i]) { // Fill all cooldowns to prevent double key press Arrays.fill(cooldowns, COOLDOWN); return; } } } private static void consumeKeyPress(KeyBinding key, int limit) { int error = 0; while (key.wasPressed()) { key.setPressed(false); if (error++ > limit) { PlayerAutomaClient.LOGGER.warn("Could not unset keybinding for QuickSlot"); break; } } } public static void register() { ClientTickEvents.START_CLIENT_TICK.register(client -> { if (client.player == null) { return; } long handle = client.getWindow().getHandle(); // Check Store QuickSlot KeyBindings if (CTRLPressed(handle)) { handleQuickSlotKeyPress(handle, storeCooldowns, CTRLPressed); } // Check Load QuickSlot KeyBindings if (ALTPressed(handle)) { handleQuickSlotKeyPress(handle, loadCooldowns, ALTPressed); } for (int i = 0; i < CTRLPressed.length; i++) { // Store Recording to QuickSlot if (CTRLPressed[i]) { // Unset key to not change selectedSlot consumeKeyPress(client.options.hotbarKeys[i], 10); // Check if store operation can be done if (PlayerRecorder.state != PlayerRecorder.State.IDLE) {
package net.jasper.mod.automation; /** * QuickSlots for storing and loading Recordings for the PlayerRecorder */ public class QuickSlots { public static Recording[] quickSlots = new Recording[9]; // KeyBinding State private static final int[] storeCooldowns = new int[9]; private static final int[] loadCooldowns = new int[9]; private static final boolean[] CTRLPressed = new boolean[9]; private static final boolean[] ALTPressed = new boolean[9]; private static final int COOLDOWN = 5; public static void store(int slot, Recording recording) { quickSlots[slot] = recording; } public static Recording load(int slot) { return quickSlots[slot]; } // Initialize State static { Arrays.fill(quickSlots, null); Arrays.fill(ALTPressed, false); Arrays.fill(CTRLPressed, false); Arrays.fill(storeCooldowns, 0); Arrays.fill(loadCooldowns, 0); } private static void handleQuickSlotKeyPress(long handle, int[] cooldowns, boolean[] pressed) { for (int i = 0; i < pressed.length; i++) { if (cooldowns[i] > 0) { cooldowns[i]--; continue; } pressed[i] = InputUtil.isKeyPressed(handle, GLFW.GLFW_KEY_1 + i); if (pressed[i]) { // Fill all cooldowns to prevent double key press Arrays.fill(cooldowns, COOLDOWN); return; } } } private static void consumeKeyPress(KeyBinding key, int limit) { int error = 0; while (key.wasPressed()) { key.setPressed(false); if (error++ > limit) { PlayerAutomaClient.LOGGER.warn("Could not unset keybinding for QuickSlot"); break; } } } public static void register() { ClientTickEvents.START_CLIENT_TICK.register(client -> { if (client.player == null) { return; } long handle = client.getWindow().getHandle(); // Check Store QuickSlot KeyBindings if (CTRLPressed(handle)) { handleQuickSlotKeyPress(handle, storeCooldowns, CTRLPressed); } // Check Load QuickSlot KeyBindings if (ALTPressed(handle)) { handleQuickSlotKeyPress(handle, loadCooldowns, ALTPressed); } for (int i = 0; i < CTRLPressed.length; i++) { // Store Recording to QuickSlot if (CTRLPressed[i]) { // Unset key to not change selectedSlot consumeKeyPress(client.options.hotbarKeys[i], 10); // Check if store operation can be done if (PlayerRecorder.state != PlayerRecorder.State.IDLE) {
PlayerController.writeToChat("Cannot store Recording while Recording or Replaying");
1
2023-10-25 11:30:02+00:00
2k
achmaddaniel24/kupass
app/src/main/java/com/achmaddaniel/kupass/activity/SettingsPage.java
[ { "identifier": "SettingsAdapter", "path": "app/src/main/java/com/achmaddaniel/kupass/adapter/SettingsAdapter.java", "snippet": "public class SettingsAdapter extends BaseAdapter {\n\t\n\tprivate ArrayList<ListSettings> mList = new ArrayList<>();\n\tprivate Context mContext;\n\t\n\tpublic SettingsAdapter(Context context, ArrayList<ListSettings> list) {\n\t\tmContext = context;\n\t\tmList = list;\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\treturn mList.size();\n\t}\n\t\n\t@Override\n\tpublic Object getItem(int position) {\n\t\treturn mList.get(position);\n\t}\n\t\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn position;\n\t}\n\t\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tconvertView = LayoutInflater.from(mContext).inflate(R.layout.settings_item_list_layout, parent, false);\n\t\t((TextView)convertView.findViewById(R.id.title)).setText(mList.get(position).getTitle());\n\t\t((TextView)convertView.findViewById(R.id.subtitle)).setText(mList.get(position).getSubtitle());\n\t\treturn convertView;\n\t}\n}" }, { "identifier": "ListSettings", "path": "app/src/main/java/com/achmaddaniel/kupass/adapter/ListSettings.java", "snippet": "public class ListSettings {\n\t\n\tprivate String mTitle;\n\tprivate String mSubtitle;\n\t\n\tpublic ListSettings(String title, String subtitle) {\n\t\tmTitle = title;\n\t\tmSubtitle = subtitle;\n\t}\n\t\n\tpublic String getTitle() {\n\t\treturn mTitle;\n\t}\n\t\n\tpublic String getSubtitle() {\n\t\treturn mSubtitle;\n\t}\n}" }, { "identifier": "Preference", "path": "app/src/main/java/com/achmaddaniel/kupass/database/Preference.java", "snippet": "public class Preference {\n\t\n\tprivate static Context mContext;\n\t\n\tprivate static SharedPreferences get(Context context) {\n\t\treturn mContext.getSharedPreferences(\"preferences\", mContext.MODE_PRIVATE);\n\t}\n\t\n\tpublic static void init(Context context) {\n\t\tmContext = context;\n\t}\n\t\n\tpublic static void setExportMethod(int method) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"export_method\", method);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getExportMethod() {\n\t\treturn get(mContext).getInt(\"export_method\", ConstantVar.EXPORT_TEXT);\n\t}\n\t\n\tpublic static void setLanguage(int language) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"language\", language);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getLanguage() {\n\t\treturn get(mContext).getInt(\"language\", ConstantVar.LANG_EN);\n\t}\n\t\n\tpublic static void setTheme(int theme) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"theme\", theme);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getTheme() {\n\t\treturn get(mContext).getInt(\"theme\", ConstantVar.THEME_SYSTEM);\n\t}\n}" }, { "identifier": "ConstantVar", "path": "app/src/main/java/com/achmaddaniel/kupass/core/ConstantVar.java", "snippet": "public class ConstantVar {\n\t\n\tpublic static final int LANG_EN = 0;\n\tpublic static final int LANG_IN = 1;\n\t\n\tpublic static final int THEME_SYSTEM = 0;\n\tpublic static final int THEME_LIGHT\t = 1;\n\tpublic static final int THEME_DARK\t = 2;\n\t\n\t// public static final int EXPORT_CSV\t= 0;\n\tpublic static final int EXPORT_JSON = 0; // Default: 1\n\tpublic static final int EXPORT_TEXT = 1; // Default: 2\n\t// public static final int EXPORT_XLSX = 3; // Depedencies not support in CodeAssist\n\t\n\tpublic static final String STRING_NULL\t= null;\n\tpublic static final String STRING_EMPTY = \"\";\n}" } ]
import com.achmaddaniel.kupass.R; import com.achmaddaniel.kupass.adapter.SettingsAdapter; import com.achmaddaniel.kupass.adapter.ListSettings; import com.achmaddaniel.kupass.database.Preference; import com.achmaddaniel.kupass.core.ConstantVar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import android.os.Bundle; import android.net.Uri; import android.content.Intent; import android.view.View; import android.view.LayoutInflater; import android.widget.ListView; import java.util.ArrayList;
1,383
package com.achmaddaniel.kupass.activity; public class SettingsPage extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings_page); ArrayList<ListSettings> listSettings = new ArrayList<>(); String[] settingsItemTitle = getResources().getStringArray(R.array.settings_item_title); String[] settingsItemSubtitle = getResources().getStringArray(R.array.settings_item_subtitle); ListView listView = findViewById(R.id.list_view); for(int i = 0; i < settingsItemTitle.length; i++) listSettings.add(new ListSettings(settingsItemTitle[i], settingsItemSubtitle[i])); listView.setAdapter(new SettingsAdapter(SettingsPage.this, listSettings)); listView.setOnItemClickListener((adapter, view, position, id) -> { switch(position) { case 0: // Appearance dialogChangeTheme(); break; case 1: // Language dialogChangeLanguage(); break; case 2: // About Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://linktr.ee/achmaddaniel")); // Dont change the link, Respect for the author! startActivity(intent); break; } }); } private void dialogChangeTheme() { CharSequence[] listTheme = getResources().getStringArray(R.array.theme_list); new MaterialAlertDialogBuilder(SettingsPage.this) .setTitle(getString(R.string.dialog_title_theme)) .setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> { }) .setPositiveButton(getString(R.string.dialog_apply), (dialog, which) -> {
package com.achmaddaniel.kupass.activity; public class SettingsPage extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings_page); ArrayList<ListSettings> listSettings = new ArrayList<>(); String[] settingsItemTitle = getResources().getStringArray(R.array.settings_item_title); String[] settingsItemSubtitle = getResources().getStringArray(R.array.settings_item_subtitle); ListView listView = findViewById(R.id.list_view); for(int i = 0; i < settingsItemTitle.length; i++) listSettings.add(new ListSettings(settingsItemTitle[i], settingsItemSubtitle[i])); listView.setAdapter(new SettingsAdapter(SettingsPage.this, listSettings)); listView.setOnItemClickListener((adapter, view, position, id) -> { switch(position) { case 0: // Appearance dialogChangeTheme(); break; case 1: // Language dialogChangeLanguage(); break; case 2: // About Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://linktr.ee/achmaddaniel")); // Dont change the link, Respect for the author! startActivity(intent); break; } }); } private void dialogChangeTheme() { CharSequence[] listTheme = getResources().getStringArray(R.array.theme_list); new MaterialAlertDialogBuilder(SettingsPage.this) .setTitle(getString(R.string.dialog_title_theme)) .setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> { }) .setPositiveButton(getString(R.string.dialog_apply), (dialog, which) -> {
switch(Preference.getTheme()) {
2
2023-10-26 20:28:08+00:00
2k
MachineMC/Cogwheel
cogwheel-core/src/main/java/org/machinemc/cogwheel/NodeFilter.java
[ { "identifier": "ConfigNode", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigNode.java", "snippet": "public sealed abstract class ConfigNode<A extends AnnotatedElement> permits FieldNode, RecordComponentNode {\n\n protected final A element;\n private final String formattedName;\n private final String @Nullable [] comments;\n private final @Nullable String inlineComment;\n private final boolean optional, hidden;\n\n public ConfigNode(A element, Function<ConfigNode<A>, SerializerContext> contextFunction) {\n this.element = element;\n SerializerContext context = contextFunction.apply(this);\n String name = getAnnotation(Key.class).map(Key::value).orElse(getName());\n KeyFormatter formatter = getAnnotation(FormatKeyWith.class)\n .map(FormatKeyWith::value)\n .map(JavaUtils::newInstance)\n .orElse(null);\n if (formatter == null) formatter = context.properties().keyFormatter();\n this.formattedName = formatter != null ? formatter.format(name) : name;\n\n this.comments = getAnnotation(Comment.class).map(Comment::value).orElse(null);\n this.inlineComment = getAnnotation(Comment.Inline.class).map(Comment.Inline::value).orElse(null);\n\n this.optional = getAnnotation(org.machinemc.cogwheel.annotations.Optional.class).isPresent();\n this.hidden = getAnnotation(Hidden.class).isPresent();\n }\n\n public Class<?> getActualType() {\n return JavaUtils.asClass(getAnnotatedType());\n }\n\n public Class<?> getType() {\n Class<?> type = getActualType();\n return type.isPrimitive() ? JavaUtils.wrapPrimitiveClass(type) : type;\n }\n\n public String getFormattedName() {\n return formattedName;\n }\n\n public abstract String getName();\n\n public abstract Object getValue(Object holder);\n\n public <T extends Annotation> Optional<T> getAnnotation(Class<T> annotationClass) {\n return Optional.ofNullable(getAnnotatedElement().getAnnotation(annotationClass));\n }\n\n public abstract AnnotatedElement getAnnotatedElement();\n\n public abstract AnnotatedType getAnnotatedType();\n\n public String @Nullable [] getComments() {\n return comments;\n }\n\n public @Nullable String getInlineComment() {\n return inlineComment;\n }\n\n public boolean isOptional() {\n return optional || isHidden();\n }\n\n public boolean isHidden() {\n return hidden;\n }\n\n @Override\n public String toString() {\n return new StringJoiner(\", \", getClass().getSimpleName() + \"[\", \"]\")\n .add(\"type=\" + getActualType())\n .add(\"formattedName='\" + formattedName + \"'\")\n .add(\"optional=\" + optional)\n .add(\"hidden=\" + hidden)\n .toString();\n }\n\n}" }, { "identifier": "FieldNode", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/FieldNode.java", "snippet": "public final class FieldNode extends ConfigNode<Field> {\n\n public FieldNode(Field field, Function<ConfigNode<Field>, SerializerContext> contextFunction) {\n super(field, contextFunction);\n }\n\n @Override\n public String getName() {\n return element.getName();\n }\n\n @Override\n public Object getValue(Object holder) {\n return JavaUtils.getValue(element, holder);\n }\n\n @Override\n public Field getAnnotatedElement() {\n return element;\n }\n\n @Override\n public AnnotatedType getAnnotatedType() {\n return element.getAnnotatedType();\n }\n\n}" }, { "identifier": "RecordComponentNode", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/RecordComponentNode.java", "snippet": "public final class RecordComponentNode extends ConfigNode<RecordComponent> {\n\n public RecordComponentNode(RecordComponent recordComponent, Function<ConfigNode<RecordComponent>, SerializerContext> contextFunction) {\n super(recordComponent, contextFunction);\n }\n\n @Override\n public String getName() {\n return element.getName();\n }\n\n @Override\n public Object getValue(Object holder) {\n return JavaUtils.getValue(element, holder);\n }\n\n @Override\n public RecordComponent getAnnotatedElement() {\n return element;\n }\n\n @Override\n public AnnotatedType getAnnotatedType() {\n return element.getAnnotatedType();\n }\n\n}" } ]
import org.machinemc.cogwheel.config.ConfigNode; import org.machinemc.cogwheel.config.FieldNode; import org.machinemc.cogwheel.config.RecordComponentNode; import java.util.function.Predicate;
1,152
package org.machinemc.cogwheel; public interface NodeFilter extends Predicate<ConfigNode<?>> { NodeFilter DEFAULT = new DefaultNodeFilter(); default boolean check(ConfigNode<?> node) { return switch (node) {
package org.machinemc.cogwheel; public interface NodeFilter extends Predicate<ConfigNode<?>> { NodeFilter DEFAULT = new DefaultNodeFilter(); default boolean check(ConfigNode<?> node) { return switch (node) {
case FieldNode fieldNode -> check(fieldNode);
1
2023-10-25 11:31:02+00:00
2k
GQS-2023/BancoJunit-Suite
src/test/java/junitTests/Conta/GerenciadoraContas_1_Test.java
[ { "identifier": "ContaCorrente", "path": "src/main/java/banco/ContaCorrente.java", "snippet": "public class ContaCorrente {\n\n private final int id;\n private double saldo;\n private boolean ativa;\n private final int idCliente;\n\n public ContaCorrente(int id, int idCliente) {\n this.id = id;\n this.saldo = 0;\n this.ativa = true;\n this.idCliente = idCliente;\n }\n\n public int getId() {\n return id;\n }\n\n public double getSaldo() {\n return saldo;\n }\n\n public boolean isAtiva() {\n return ativa;\n }\n\n public void setAtiva(boolean ativa) {\n this.ativa = ativa;\n }\n\n public int getIdCliente() {\n return idCliente;\n }\n\n public void depositar(double valor) {\n this.saldo += valor;\n }\n\n public boolean sacar(double valor) {\n boolean sacado = false;\n if (valor <= saldo) {\n this.saldo -= valor;\n sacado = true;\n }\n return sacado;\n }\n\n @Override\n public String toString() {\n return \"=========================\\n\"\n + \"Id: \" + this.id + \"\\n\"\n + \"Saldo: \" + this.saldo + \"\\n\"\n + \"Status: \" + (ativa ? \"Ativa\" : \"Inativa\") + \"\\n\"\n + \"Cliente: \" + this.idCliente + \"\\n\"\n + \"=========================\";\n }\n\n}" }, { "identifier": "GerenciadoraContas", "path": "src/main/java/banco/GerenciadoraContas.java", "snippet": "public class GerenciadoraContas {\n\n private List<ContaCorrente> contas;\n\n public GerenciadoraContas(List<ContaCorrente> contas) {\n this.contas = contas;\n }\n\n public List<ContaCorrente> getContas() {\n return contas;\n }\n\n public ContaCorrente pesquisaConta(int idConta) {\n for (ContaCorrente contaCorrente : contas) {\n if (contaCorrente.getId() == idConta) {\n return contaCorrente;\n }\n }\n return null;\n }\n\n public void adicionaConta(ContaCorrente novaConta) {\n this.contas.add(novaConta);\n }\n\n public boolean removeConta(int idConta) {\n\n boolean contaRemovida = false;\n\n for (ContaCorrente conta : contas) {\n if (conta.getId() == idConta) {\n contas.remove(conta);\n break;\n }\n }\n return contaRemovida;\n }\n\n public boolean ativaConta(int idConta) {\n\n boolean contaAtiva = false;\n\n for (ContaCorrente conta : contas) {\n if (conta.getId() == idConta) {\n if (conta.isAtiva()) {\n contaAtiva = true;\n break;\n }\n }\n }\n return contaAtiva;\n }\n\n public boolean transfereValor(int idContaOrigem, double valor, int idContaDestino) {\n\n boolean sucesso = false;\n\n ContaCorrente contaOrigem = pesquisaConta(idContaOrigem);\n ContaCorrente contaDestino = pesquisaConta(idContaDestino);\n\n if (contaOrigem.getSaldo() >= valor) {\n contaOrigem.sacar(valor);\n contaDestino.depositar(valor); \n sucesso = true;\n }\n return sucesso;\n }\n public void limpar() {\n contas.clear();\n }\n}" } ]
import banco.ContaCorrente; import banco.GerenciadoraContas; import java.util.ArrayList; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.AfterEach; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test;
1,098
package junitTests.Conta; /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ /** * * @author rafaelamoreira */ @Tag("dev") public class GerenciadoraContas_1_Test { List<ContaCorrente> contas;
package junitTests.Conta; /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ /** * * @author rafaelamoreira */ @Tag("dev") public class GerenciadoraContas_1_Test { List<ContaCorrente> contas;
GerenciadoraContas gcc;
1
2023-10-30 20:31:27+00:00
2k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/equitiesmarketdata/EquitiesMarketData.java
[ { "identifier": "IEXHttpClient", "path": "src/main/java/io/github/f4pl0/IEXHttpClient.java", "snippet": "public class IEXHttpClient {\n private static IEXHttpClient instance;\n @IEXConfiguration\n private IEXCloudConfig config;\n\n private final CloseableHttpClient httpClient;\n\n private IEXHttpClient() {\n this.httpClient = HttpClients.createDefault();\n }\n\n @SneakyThrows\n public CloseableHttpResponse execute(String requestUri) {\n URI uri = new URIBuilder(config.getBaseEndpoint() + requestUri)\n .addParameter(\"token\", config.getPublishableToken())\n .build();\n\n HttpGet request = new HttpGet(uri);\n\n CloseableHttpResponse response = httpClient.execute(request);\n\n if (response.getStatusLine().getStatusCode() >= 400) {\n throw new IOException(\"Request failed: \" + response.getStatusLine());\n }\n\n return response;\n }\n\n public static IEXHttpClient getInstance() {\n if (instance == null) {\n instance = new IEXHttpClient();\n }\n return instance;\n }\n}" }, { "identifier": "IEXCloudConfig", "path": "src/main/java/io/github/f4pl0/config/IEXCloudConfig.java", "snippet": "@Data\npublic class IEXCloudConfig {\n private String publishableToken;\n private String secretToken;\n private String baseEndpoint;\n}" }, { "identifier": "IEXDEEP", "path": "src/main/java/io/github/f4pl0/equitiesmarketdata/data/IEXDEEP.java", "snippet": "public class IEXDEEP {\n public String symbol;\n public BigDecimal marketPercent;\n public long volume;\n public BigDecimal lastSalePrice;\n public long lastSaleSize;\n public long lastSaleTime;\n public long lastUpdated;\n public List<IEXAskBid> bids;\n public List<IEXAskBid> asks;\n public List<IEXDEEPTrade> trades;\n public IEXDEEPSecurityEvent securityEvent;\n public IEXDEEPSystemEvent systemEvent;\n public List<IEXDEEPTradeBreak> tradeBreaks;\n}" }, { "identifier": "IEXIntradayEquityPrice", "path": "src/main/java/io/github/f4pl0/equitiesmarketdata/data/IEXIntradayEquityPrice.java", "snippet": "public class IEXIntradayEquityPrice {\n // TODO: Update the model to match all possible fields.\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd\")\n public Date date;\n public String minute;\n public String label;\n public BigDecimal high;\n public BigDecimal low;\n public BigDecimal open;\n public BigDecimal close;\n public BigDecimal average;\n public long volume;\n public BigDecimal notional;\n public long numberOfTrades;\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import io.github.f4pl0.IEXHttpClient; import io.github.f4pl0.config.IEXCloudConfig; import io.github.f4pl0.equitiesmarketdata.data.IEXDEEP; import io.github.f4pl0.equitiesmarketdata.data.IEXIntradayEquityPrice; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List;
1,052
package io.github.f4pl0.equitiesmarketdata; public class EquitiesMarketData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * IEX Depth of Book (DEEP) * * <p> * DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations * received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not * indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed * portions of reserve orders are not represented in DEEP. * </p> * * <p> * DEEP also provides last trade price and size information. Trades resulting from either displayed or * non-displayed orders matching on IEX will be reported. Routed executions will not be reported. * </p> * * @see <a href="https://iexcloud.io/docs/core/IEX_DEEP#iex-depth-of-book-deep">IEX Cloud API</a> * @param symbol The stock symbol to get the DEEP data for. * @return The DEEP data for the given stock symbol. * @throws IOException If the request fails. */
package io.github.f4pl0.equitiesmarketdata; public class EquitiesMarketData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * IEX Depth of Book (DEEP) * * <p> * DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations * received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not * indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed * portions of reserve orders are not represented in DEEP. * </p> * * <p> * DEEP also provides last trade price and size information. Trades resulting from either displayed or * non-displayed orders matching on IEX will be reported. Routed executions will not be reported. * </p> * * @see <a href="https://iexcloud.io/docs/core/IEX_DEEP#iex-depth-of-book-deep">IEX Cloud API</a> * @param symbol The stock symbol to get the DEEP data for. * @return The DEEP data for the given stock symbol. * @throws IOException If the request fails. */
public IEXDEEP getDEEP(@NonNull String symbol) throws IOException {
2
2023-10-27 17:56:14+00:00
2k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Subsytems/DriveBase.java
[ { "identifier": "Constants", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Constants.java", "snippet": "public abstract class Constants {\n\n // ---------- ELEVATOR CONSTANTS ---------- //\n\n public static int MAX_ELEVATOR_EXTENSION = 3045;\n public static int HALF_ELEVATOR_EXTENSION = 1520;\n\n public static int BOTTOM_EXTEND_POSITION = 1890;\n public static int BOTTOM_ROT_POSITION = 528;\n\n public static int LOW_EXTEND_POSITION = 2041;\n public static int LOW_ROT_POSITION = 633;\n\n public static int MED_EXTEND_POSITION = 2421;\n public static int MED_ROT_POSITION = 804;\n\n public static int HIGH_EXTEND_POSITION = 2983;\n public static int HIGH_ROT_POSITION = 947;\n\n public static int TOP_EXTEND_POSITION = 3045;\n public static int TOP_ROT_POSITION = 1107;\n\n public static int LAUNCH_POSITION = 1630;\n public static int HANG_POSITION = 2326;\n\n\n // ----------- DRIVE CONSTANTS ---------- //\n\n public static final double DEAD_ZONE_LOW = -0.05d;\n public static final double DEAD_ZONE_HIGH = 0.05d;\n\n\n // ----------- INTAKE CONSTANTS ---------- //\n\n public static final double INTAKE_POSITION = 0.25d;\n public static final double HOLD_POSITION = 0.47d;\n public static final double OUTTAKE_POSITION = 0.17d;\n\n public static final double BOTTOM_WRIST_POSITION = 0.9;\n public static final double LOW_WRIST_POSITION = 0.9;\n public static final double MED_WRIST_POSITION = 0.75;\n public static final double HIGH_WRIST_POSITION = 0.6;\n public static final double TOP_WRIST_POSITION = 0.6;\n\n // ---------- LAUNCHER CONSTANTS ---------- //\n\n public static final double LAUNCHER_SERVO_POSITION = 1;\n\n // ---------- CAMERA CONSTANTS ---------- //\n public static final int IMAGE_WIDTH = 340;\n}" }, { "identifier": "MotorUtility", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/TeleOp/Utility/MotorUtility.java", "snippet": "public abstract class MotorUtility {\n\n /**\n * Sets the run mode of the supplied motors\n * @param runMode The mode to run the motors in\n * @param motors The motors to set the mode of\n */\n public static void setMode(@NonNull RunMode runMode, @NonNull DcMotor ... motors) {\n for (DcMotor motor : motors) { motor.setMode(runMode); }\n }\n\n /**\n * Sets the zero power behavior of the supplied motors\n * @param zeroPowerBehavior The zero power behaviour to set the motors to\n * @param motors The motors you are setting the zero power behaviour of\n */\n public static void setZeroPowerBehaviour(@NonNull ZeroPowerBehavior zeroPowerBehavior, @NonNull DcMotor ... motors) {\n for (DcMotor motor : motors) { motor.setZeroPowerBehavior(zeroPowerBehavior); }\n }\n\n /**\n * Sets the direction of the supplied motors\n * @param direction The direction to set the motors\n * @param motors The motors you are setting the direction of\n */\n public static void setDirection(@NonNull Direction direction, @NonNull DcMotor ... motors) {\n for (DcMotor motor : motors) { motor.setDirection(direction); }\n }\n\n /**\n * Sets the target position of the supplied motors\n * @param targetPosition The target position to set the motors to.\n * @param motors The motors you are modifying.\n */\n public static void setTargetPosition(int targetPosition, @NonNull DcMotorEx ... motors) {\n for (DcMotorEx motor : motors) { motor.setTargetPosition(targetPosition); }\n }\n\n /**\n * Sets the velocity of the supplied motors\n *\n * @param velocity The velocity you would like to set the motors to; Ticks/Second\n * @param motors The motors to set the velocity of\n */\n public static void setVelocity(int velocity, @NonNull DcMotorEx ... motors) {\n for (DcMotorEx motor : motors) { motor.setVelocity(velocity); }\n }\n\n /**\n * Sets the target position tolerance of the supplied motors\n *\n * @param Tolerance The tolerance in ticks\n * @param motors The motors to set the velocity of\n */\n public static void setPositionTolerance(int tolerance, @NonNull DcMotorEx ... motors) {\n for (DcMotorEx motor : motors) { motor.setTargetPositionTolerance(tolerance); }\n }\n\n /**\n * Sets the target power of the supplied motors\n *\n * @param Power The power of the motors\n * @param motors The motors to set the power of\n */\n public static void setPower(double power, @NonNull DcMotorEx ... motors) {\n for (DcMotorEx motor : motors) { motor.setPower(power); }\n }\n}" } ]
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotorImplEx; import static com.qualcomm.robotcore.hardware.DcMotor.ZeroPowerBehavior.*; import static com.qualcomm.robotcore.hardware.DcMotorSimple.Direction.*; import com.qualcomm.robotcore.hardware.Gamepad; import com.qualcomm.robotcore.hardware.HardwareMap; import static org.firstinspires.ftc.teamcode.Constants.*; import androidx.annotation.NonNull; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.TeleOp.Utility.MotorUtility;
1,591
package org.firstinspires.ftc.teamcode.Subsytems; public final class DriveBase { public enum StrafeDirections { RIGHT, LEFT } private double motorPowerRatio; private double drive, strafe, turn; private double fLPower, fRPower, bLPower, bRPower; private final DcMotorImplEx fL, fR, bL, bR; /** * Drive Base Subsystem Constructor * @param opMode The opMode you are using the drive base in, likely "this" */ public DriveBase(@NonNull HardwareMap hardwareMap) { fL = hardwareMap.get(DcMotorImplEx.class, "fldm"); fR = hardwareMap.get(DcMotorImplEx.class, "frdm"); bL = hardwareMap.get(DcMotorImplEx.class, "bldm"); bR = hardwareMap.get(DcMotorImplEx.class, "brdm");
package org.firstinspires.ftc.teamcode.Subsytems; public final class DriveBase { public enum StrafeDirections { RIGHT, LEFT } private double motorPowerRatio; private double drive, strafe, turn; private double fLPower, fRPower, bLPower, bRPower; private final DcMotorImplEx fL, fR, bL, bR; /** * Drive Base Subsystem Constructor * @param opMode The opMode you are using the drive base in, likely "this" */ public DriveBase(@NonNull HardwareMap hardwareMap) { fL = hardwareMap.get(DcMotorImplEx.class, "fldm"); fR = hardwareMap.get(DcMotorImplEx.class, "frdm"); bL = hardwareMap.get(DcMotorImplEx.class, "bldm"); bR = hardwareMap.get(DcMotorImplEx.class, "brdm");
MotorUtility.setZeroPowerBehaviour(BRAKE, fL, fR, bL, bR);
1
2023-10-31 16:06:46+00:00
2k
Fuzss/diagonalwalls
1.18/Fabric/src/main/java/fuzs/diagonalwindows/mixin/client/ParticleEngineFabricMixin.java
[ { "identifier": "DiagonalBlock", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/api/world/level/block/DiagonalBlock.java", "snippet": "public interface DiagonalBlock extends IDiagonalBlock {\n BooleanProperty NORTH_EAST = BooleanProperty.create(\"north_east\");\n BooleanProperty SOUTH_EAST = BooleanProperty.create(\"south_east\");\n BooleanProperty SOUTH_WEST = BooleanProperty.create(\"south_west\");\n BooleanProperty NORTH_WEST = BooleanProperty.create(\"north_west\");\n\n /**\n * @return have diagonal properties successfully been applied to this block\n */\n @Override\n boolean hasProperties();\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n @Override\n default boolean canConnectDiagonally() {\n return this.supportsDiagonalConnections();\n }\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n boolean supportsDiagonalConnections();\n\n /**\n * @param neighborState neighbor block state to check if it can connect to me diagonally\n * @param neighborDirectionToMe my direction from the neighbor blocks point of view\n * @return is a diagonal connection between both blocks allowed\n */\n boolean canConnectToMe(BlockState neighborState, EightWayDirection neighborDirectionToMe);\n}" }, { "identifier": "DestroyEffectsHelper", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/client/model/DestroyEffectsHelper.java", "snippet": "public class DestroyEffectsHelper {\n\n public static boolean addDestroyEffects(BlockState state, Level level, BlockPos pos, ParticleEngine manager) {\n VoxelShape voxelshape = state.getShape(level, pos);\n if (!(voxelshape instanceof VoxelCollection voxelCollection)) return false;\n voxelCollection.forAllParticleBoxes((p_172273_, p_172274_, p_172275_, p_172276_, p_172277_, p_172278_) -> {\n double d1 = Math.min(1.0D, p_172276_ - p_172273_);\n double d2 = Math.min(1.0D, p_172277_ - p_172274_);\n double d3 = Math.min(1.0D, p_172278_ - p_172275_);\n int i = Math.max(2, Mth.ceil(d1 / 0.25D));\n int j = Math.max(2, Mth.ceil(d2 / 0.25D));\n int k = Math.max(2, Mth.ceil(d3 / 0.25D));\n\n for(int l = 0; l < i; ++l) {\n for(int i1 = 0; i1 < j; ++i1) {\n for(int j1 = 0; j1 < k; ++j1) {\n double d4 = ((double)l + 0.5D) / (double)i;\n double d5 = ((double)i1 + 0.5D) / (double)j;\n double d6 = ((double)j1 + 0.5D) / (double)k;\n double d7 = d4 * d1 + p_172273_;\n double d8 = d5 * d2 + p_172274_;\n double d9 = d6 * d3 + p_172275_;\n manager.add(new TerrainParticle((ClientLevel) level, (double)pos.getX() + d7, (double)pos.getY() + d8, (double)pos.getZ() + d9, d4 - 0.5D, d5 - 0.5D, d6 - 0.5D, state, pos));\n }\n }\n }\n });\n return true;\n }\n}" } ]
import fuzs.diagonalwindows.api.world.level.block.DiagonalBlock; import fuzs.diagonalwindows.client.model.DestroyEffectsHelper; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.ParticleEngine; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
1,089
package fuzs.diagonalwindows.mixin.client; @Mixin(ParticleEngine.class) abstract class ParticleEngineFabricMixin { @Shadow protected ClientLevel level; @Inject(method = "destroy", at = @At("HEAD"), cancellable = true) public void destroy(BlockPos blockPos, BlockState blockState, CallbackInfo callback) { if (blockState.getBlock() instanceof DiagonalBlock block && block.hasProperties()) {
package fuzs.diagonalwindows.mixin.client; @Mixin(ParticleEngine.class) abstract class ParticleEngineFabricMixin { @Shadow protected ClientLevel level; @Inject(method = "destroy", at = @At("HEAD"), cancellable = true) public void destroy(BlockPos blockPos, BlockState blockState, CallbackInfo callback) { if (blockState.getBlock() instanceof DiagonalBlock block && block.hasProperties()) {
if (DestroyEffectsHelper.addDestroyEffects(blockState, this.level, blockPos, ParticleEngine.class.cast(this))) {
1
2023-10-27 09:06:16+00:00
2k
slatepowered/slate
slate-common/src/main/java/slatepowered/slate/service/singleton/SingletonKey.java
[ { "identifier": "ServiceKey", "path": "slate-common/src/main/java/slatepowered/slate/service/ServiceKey.java", "snippet": "public interface ServiceKey<T extends Service> {\r\n\r\n /**\r\n * Get the service class. This is the base\r\n * parameter of the service tag.\r\n *\r\n * @return The service class.\r\n */\r\n Class<T> getServiceClass();\r\n\r\n /**\r\n * Called when the service associated with this\r\n * tag is registered to the given manager.\r\n *\r\n * @param manager The manager.\r\n * @param service The service.\r\n */\r\n void register(ServiceManager manager, T service);\r\n\r\n /**\r\n * Used to get the tag for retrieving the local instance.\r\n *\r\n * @return The local tag, can be this.\r\n */\r\n default ServiceKey<T> toLocal() {\r\n return this;\r\n }\r\n\r\n static <T extends Service> ServiceKey<T> local(Class<T> tClass) {\r\n return new ServiceKey<T>() {\r\n @Override\r\n public Class<T> getServiceClass() {\r\n return tClass;\r\n }\r\n\r\n @Override\r\n public void register(ServiceManager manager, T service) {\r\n // noop\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return tClass.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) return true;\r\n if (!(obj instanceof ServiceKey)) return false;\r\n return tClass == ((ServiceKey<?>)obj).getServiceClass();\r\n }\r\n };\r\n }\r\n\r\n}\r" }, { "identifier": "ServiceManager", "path": "slate-common/src/main/java/slatepowered/slate/service/ServiceManager.java", "snippet": "public class ServiceManager implements ServiceProvider {\r\n\r\n /** The network which provides this service manager. */\r\n private final Network network;\r\n\r\n /** The parent service manager. */\r\n private final ServiceManager parent;\r\n\r\n /** All registered local services. */\r\n private final Map<ServiceKey<?>, Service> localServices = new HashMap<>();\r\n\r\n public ServiceManager(Network network, ServiceManager parent) {\r\n this.network = network;\r\n this.parent = parent;\r\n }\r\n\r\n public ServiceManager(ServiceManager parent) {\r\n this(parent.getNetwork(), parent);\r\n }\r\n\r\n public ServiceManager(Network network) {\r\n this(network, null);\r\n }\r\n\r\n /**\r\n * Get the local network instance this service manager is attached to.\r\n *\r\n * @return The network instance.\r\n */\r\n public Network getNetwork() {\r\n return network;\r\n }\r\n\r\n @Override\r\n public ServiceManager serviceManager() {\r\n return this;\r\n }\r\n\r\n /**\r\n * Retrieves the given service from this service manager with the\r\n * given provider as source.\r\n *\r\n * @param key The service key.\r\n * @param provider The service provider used to invoke this.\r\n * @param <T> The service instance type.\r\n * @return The service instance.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public <T extends Service> T getService(ServiceKey<T> key, ServiceProvider provider) throws UnsupportedOperationException {\r\n Service service;\r\n System.out.println(\"Service: Finding service for key(\" + key + \") in manager(\" + this + \")\");\r\n\r\n // check local service registry\r\n service = localServices.get(key.toLocal());\r\n if (service != null) {\r\n System.out.println(\"Service: found local service for key(\" + key + \"): \" + service);\r\n return (T) service;\r\n }\r\n\r\n // create dynamically\r\n if (key instanceof DynamicServiceKey) {\r\n System.out.println(\"Service: creating service from dynamic service key: \" + key);\r\n DynamicServiceKey<T> serviceTag = (DynamicServiceKey<T>) key;\r\n return serviceTag.create(provider == null ? this : provider);\r\n }\r\n\r\n // find in parent\r\n if (parent != null) {\r\n System.out.println(\"Service: attempting to find service in parent(\" + parent + \")\");\r\n return parent.getService(key, provider);\r\n }\r\n\r\n System.out.println(\"Service: could not find service, returning null\");\r\n return null;\r\n }\r\n\r\n /**\r\n * Retrieves the given service from this service manager with the\r\n * given provider as source.\r\n *\r\n * @param key The service key.\r\n * @param <T> The service instance type.\r\n * @return The service instance.\r\n */\r\n @Override\r\n @SuppressWarnings(\"unchecked\")\r\n public <T extends Service> T getService(ServiceKey<T> key) throws UnsupportedOperationException {\r\n return getService(key, null);\r\n }\r\n\r\n /**\r\n * Registers the given service locally to this service manager.\r\n *\r\n * @param key The key to register it under.\r\n * @param service The service instance.\r\n * @param <T> The service instance type.\r\n * @return This.\r\n */\r\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n public <T extends Service> ServiceManager register(ServiceKey<T> key, T service) {\r\n ServiceKey<T> localKey = key.toLocal();\r\n localServices.put(localKey, service);\r\n localKey.register(this, service);\r\n return this;\r\n }\r\n\r\n public <T> ServiceManager registerSingleton(Class<T> tClass, T value) {\r\n return register(SingletonKey.of(tClass), new SingletonContainer<T>().value(value));\r\n }\r\n\r\n @Override\r\n public <T extends Service> ServiceKey<T> qualifyServiceKey(ServiceKey<T> key) throws UnsupportedOperationException {\r\n return key;\r\n }\r\n\r\n @Override\r\n public ServiceProvider parentServiceResolver() {\r\n return parent;\r\n }\r\n\r\n}\r" } ]
import lombok.AllArgsConstructor; import slatepowered.slate.service.ServiceKey; import slatepowered.slate.service.ServiceManager; import java.util.Objects;
1,532
package slatepowered.slate.service.singleton; /** * A singleton instance key which you can query in a service manager * to get a singleton container. * * @param <T> The service type. */ @SuppressWarnings("rawtypes") @AllArgsConstructor public class SingletonKey<T> implements ServiceKey<SingletonContainer<T>> { public static <T> SingletonKey<T> of(Class<T> valueClass) { return new SingletonKey<>(valueClass); } /** * The value class. */ private Class<?> valueClass; @Override @SuppressWarnings("unchecked") public Class<SingletonContainer<T>> getServiceClass() { return (Class<SingletonContainer<T>>)(Object) SingletonContainer.class; } @Override
package slatepowered.slate.service.singleton; /** * A singleton instance key which you can query in a service manager * to get a singleton container. * * @param <T> The service type. */ @SuppressWarnings("rawtypes") @AllArgsConstructor public class SingletonKey<T> implements ServiceKey<SingletonContainer<T>> { public static <T> SingletonKey<T> of(Class<T> valueClass) { return new SingletonKey<>(valueClass); } /** * The value class. */ private Class<?> valueClass; @Override @SuppressWarnings("unchecked") public Class<SingletonContainer<T>> getServiceClass() { return (Class<SingletonContainer<T>>)(Object) SingletonContainer.class; } @Override
public void register(ServiceManager manager, SingletonContainer service) {
1
2023-10-30 08:58:02+00:00
2k
The2019/NewBase-1.20.2
src/client/java/net/The2019/NewBase/features/render/BeeHiveHelper.java
[ { "identifier": "readModule", "path": "src/client/java/net/The2019/NewBase/config/ModuleConfig.java", "snippet": "public static boolean readModule(String module){\n try (FileReader reader = new FileReader(configFile)) {\n JsonObject json = gson.fromJson(reader, JsonObject.class);\n if (json != null && json.has(module)) {\n return json.get(module).getAsBoolean();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return true;\n}" }, { "identifier": "beehiveRender", "path": "src/client/java/net/The2019/NewBase/config/ModuleStates.java", "snippet": "public static String beehiveRender = \"beehiverender\";" }, { "identifier": "renderBlock", "path": "src/client/java/net/The2019/NewBase/render/WorldRender.java", "snippet": "public static void renderBlock(WorldRenderContext context, Box box){\n\n Vec3d camera = context.camera().getPos();\n MatrixStack matrixStack = context.matrixStack();\n\n Tessellator tessellator = Tessellator.getInstance();\n BufferBuilder buffer = tessellator.getBuffer();\n\n RenderSystem.setShader(GameRenderer::getRenderTypeLinesProgram);\n RenderSystem.setShaderColor(1f, 1f, 1f, 1f);\n RenderSystem.lineWidth(1f);\n RenderSystem.disableCull();\n RenderSystem.enableDepthTest();\n RenderSystem.depthFunc(GL11.GL_ALWAYS);\n\n matrixStack.push();\n matrixStack.translate(-camera.getX(), -camera.getY(), -camera.getZ());\n\n buffer.begin(VertexFormat.DrawMode.LINES, VertexFormats.LINES);\n WorldRenderer.drawBox(matrixStack, buffer, box, 1f, 1f, 1f, 1f);\n tessellator.draw();\n\n matrixStack.pop();\n RenderSystem.lineWidth(1f);\n RenderSystem.enableCull();\n RenderSystem.disableDepthTest();\n RenderSystem.depthFunc(GL11.GL_LEQUAL);\n}" }, { "identifier": "getBlockEntities", "path": "src/client/java/net/The2019/NewBase/utils/ChunkStream.java", "snippet": "public static Stream<BlockEntity> getBlockEntities() {\n return getLoadedChunks().flatMap(chunk -> chunk.getBlockEntities().values().stream());\n}" } ]
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.minecraft.block.entity.BeehiveBlockEntity; import net.minecraft.block.entity.BlockEntity; import net.minecraft.client.MinecraftClient; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import java.util.ArrayList; import java.util.stream.Collectors; import static net.The2019.NewBase.config.ModuleConfig.readModule; import static net.The2019.NewBase.config.ModuleStates.beehiveRender; import static net.The2019.NewBase.render.WorldRender.renderBlock; import static net.The2019.NewBase.utils.ChunkStream.getBlockEntities;
669
package net.The2019.NewBase.features.render; public class BeeHiveHelper { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void register() { WorldRenderEvents.END.register(context -> {
package net.The2019.NewBase.features.render; public class BeeHiveHelper { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void register() { WorldRenderEvents.END.register(context -> {
if(readModule(beehiveRender)) {
0
2023-10-28 10:33:51+00:00
2k
Ax3dGaming/Sons-Of-Sins-Organs-Addition
src/main/java/com/axed/block/ModBlocks.java
[ { "identifier": "ModItems", "path": "src/main/java/com/axed/items/ModItems.java", "snippet": "public class ModItems {\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, sosorgans.MODID);\n\n public static final RegistryObject<Item> SOULIUM_INGOT = ITEMS.register(\"soulium_ingot\", () -> new Item(new Item.Properties()));\n public static final RegistryObject<Item> BOTTLE = ITEMS.register(\"bottle\", () -> (new Item(new Item.Properties().stacksTo(1))));\n public static final RegistryObject<Item> SOULIUM_DAGGER = ITEMS.register(\"soulium_dagger\",\n () -> new SwordItem(Tiers.IRON, 4, 2, new Item.Properties()));\n //WIWI\n public static final RegistryObject<Item> WITHER_SKELETON_SOUL = ITEMS.register(\"wither_skeleton_soul\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> WITHER_SKELETON_RIBS = ITEMS.register(\"wither_skeleton_ribs\", () -> new Item(new Item.Properties()));\n public static final RegistryObject<Item> WITHER_SKELETON_HEART = ITEMS.register(\"wither_skeleton_heart\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> WITHER_SKELETON_MUSCLE = ITEMS.register(\"wither_skeleton_muscle\", () -> (new Item(new Item.Properties())));\n //BLAZE\n public static final RegistryObject<Item> BLAZE_SOUL = ITEMS.register(\"blaze_soul\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> BLAZE_RIBS = ITEMS.register(\"blaze_ribs\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> BLAZE_HEART = ITEMS.register(\"blaze_heart\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> BLAZE_MUSCLE = ITEMS.register(\"blaze_muscle\", () -> (new Item(new Item.Properties())));\n //OCELOT\n public static final RegistryObject<Item> OCELOT_SOUL = ITEMS.register(\"ocelot_soul\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> OCELOT_RIBS = ITEMS.register(\"ocelot_ribs\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> OCELOT_HEART = ITEMS.register(\"ocelot_heart\", () -> (new Item(new Item.Properties())));\n public static final RegistryObject<Item> OCELOT_MUSCLE = ITEMS.register(\"ocelot_muscle\", () -> (new Item(new Item.Properties())));\n\n\n}" }, { "identifier": "sosorgans", "path": "src/main/java/com/axed/sosorgans.java", "snippet": "@Mod(sosorgans.MODID)\npublic class sosorgans\n{\n public static final String MODID = \"sosorgans\";\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public sosorgans()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n SERIALIZERS.register(modEventBus);\n BLOCKS.register(modEventBus);\n ITEMS.register(modEventBus);\n BLOCK_ENTITIES.register(modEventBus);\n CREATIVE_MODE_TABS.register(modEventBus);\n MENUS.register(modEventBus);\n\n MinecraftForge.EVENT_BUS.register(this);\n\n //modEventBus.addListener(this::addCreative);\n\n ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);\n }\n\n private void commonSetup(final FMLCommonSetupEvent event){}\n\n //private void addCreative(BuildCreativeModeTabContentsEvent event)\n //{\n //if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)\n //event.accept();\n //}\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n // Do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n MenuScreens.register(ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreatorScreen::new);\n }\n }\n}" } ]
import com.axed.items.ModItems; import com.axed.sosorgans; import net.minecraft.world.item.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Supplier;
1,343
package com.axed.block; public class ModBlocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID); public static final RegistryObject<Block> ORGAN_CREATOR = registerBlock("organ_creator", () -> new OrganCreatorBlock()); private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block) { RegistryObject<T> toReturn = BLOCKS.register(name, block); registerBlockItem(name, toReturn); return toReturn; } private static <T extends Block> RegistryObject<Item> registerBlockItem(String name, RegistryObject<T> block) {
package com.axed.block; public class ModBlocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID); public static final RegistryObject<Block> ORGAN_CREATOR = registerBlock("organ_creator", () -> new OrganCreatorBlock()); private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block) { RegistryObject<T> toReturn = BLOCKS.register(name, block); registerBlockItem(name, toReturn); return toReturn; } private static <T extends Block> RegistryObject<Item> registerBlockItem(String name, RegistryObject<T> block) {
return ModItems.ITEMS.register(name, () -> new BlockItem(block.get(), new Item.Properties()));
0
2023-10-25 19:33:18+00:00
2k
DarlanNoetzold/anPerformaticEcommerce
src/main/java/tech/noetzold/anPerformaticEcommerce/message/consumer/CommerceItemConsumer.java
[ { "identifier": "RabbitmqQueues", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/message/config/RabbitmqQueues.java", "snippet": "public class RabbitmqQueues {\n\n public static final String SHOP_CART_QUEUE = \"SHOP_CART\";\n public static final String ORDER_QUEUE = \"ORDER\";\n public static final String CUSTOMER_QUEUE = \"CUSTOMER\";\n public static final String COMMERCE_ITEM_QUEUE = \"COMMERCE_ITEM\";\n public static final String ADDRESS_QUEUE = \"ADDRESS\";\n public static final String SHIPPING_QUEUE = \"SHIPPING\";\n public static final String PROMOTION_QUEUE = \"PROMOTION\";\n public static final String COUPON_QUEUE = \"COUPON\";\n public static final String PIX_QUEUE = \"PIX\";\n public static final String PAYPAL_QUEUE = \"PAYPAL\";\n public static final String PAYMENT_QUEUE = \"PAYMENT\";\n public static final String INVOICE_QUEUE = \"INVOICE\";\n public static final String CARD_QUEUE = \"CARD\";\n public static final String BOLETO_QUEUE = \"BOLETO\";\n public static final String SKU_QUEUE = \"SKU\";\n public static final String PRODUCT_QUEUE = \"PRODUCT\";\n public static final String MEDIA_QUEUE = \"MEDIA\";\n public static final String KEY_WORD_QUEUE = \"KEY_WORD\";\n public static final String CATEGORY_QUEUE = \"CATEGORY\";\n public static final String ATTRIBUTE_QUEUE = \"ATTRIBUTE\";\n\n}" }, { "identifier": "CommerceItem", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/model/CommerceItem.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\npublic class CommerceItem implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID commerceItemId;\n\n @OneToOne\n private SkuModel skuModel;\n\n @Temporal(TemporalType.DATE)\n private Date enabledDate;\n\n private boolean enable;\n}" }, { "identifier": "CommerceItemService", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/service/CommerceItemService.java", "snippet": "@Service\n@Cacheable(\"commerceitem\")\npublic class CommerceItemService {\n\n @Autowired\n CommerceItemRepository commerceItemRepository;\n\n @Transactional\n public List<CommerceItem> findAllCommerceItem(){\n return commerceItemRepository.findAll();\n }\n\n @Transactional\n public CommerceItem findCommerceItemById(UUID id){\n return commerceItemRepository.findById(id).orElse(null);\n }\n\n @Transactional\n public CommerceItem updateCommerceItem(UUID id, CommerceItem commerceItem){\n commerceItem.setCommerceItemId(id);\n return commerceItemRepository.save(commerceItem);\n }\n \n @Transactional\n public CommerceItem saveCommerceItem(CommerceItem commerceItem){\n return commerceItemRepository.save(commerceItem);\n }\n\n @Transactional\n public void deleteCommerceItem(UUID id){\n commerceItemRepository.deleteById(id);\n }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.AmqpRejectAndDontRequeueException; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import tech.noetzold.anPerformaticEcommerce.message.config.RabbitmqQueues; import tech.noetzold.anPerformaticEcommerce.model.CommerceItem; import tech.noetzold.anPerformaticEcommerce.service.CommerceItemService;
857
package tech.noetzold.anPerformaticEcommerce.message.consumer; @Component public class CommerceItemConsumer { @Autowired CommerceItemService commerceItemService; private static final Logger logger = LoggerFactory.getLogger(CommerceItemConsumer.class); @Transactional
package tech.noetzold.anPerformaticEcommerce.message.consumer; @Component public class CommerceItemConsumer { @Autowired CommerceItemService commerceItemService; private static final Logger logger = LoggerFactory.getLogger(CommerceItemConsumer.class); @Transactional
@RabbitListener(queues = RabbitmqQueues.COMMERCE_ITEM_QUEUE)
0
2023-10-28 12:30:24+00:00
2k
gianlucameloni/shelly-em
src/main/java/com/gmeloni/shelly/model/HourlyEMEnergy.java
[ { "identifier": "DailyAggregate", "path": "src/main/java/com/gmeloni/shelly/dto/db/DailyAggregate.java", "snippet": "@Data\npublic class DailyAggregate {\n\n @JsonProperty(\"day\")\n private String day;\n @JsonProperty(\"grid_energy_in\")\n private String gridEnergyIn;\n @JsonProperty(\"grid_energy_out\")\n private String gridEnergyOut;\n @JsonProperty(\"pv_energy_in\")\n private String pvEnergyIn;\n @JsonProperty(\"pv_energy_out\")\n private String pvEnergyOut;\n\n public DailyAggregate(String day, Double gridEnergyIn, Double gridEnergyOut, Double pvEnergyIn, Double pvEnergyOut) {\n DecimalFormat dataFormat = new DecimalFormat(ENERGY_DECIMAL_FORMAT);\n this.day = Utilities.padLeftWithZeros(day, 2);\n this.gridEnergyIn = gridEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyIn);\n this.gridEnergyOut = gridEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyOut);\n this.pvEnergyIn = pvEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyIn);\n this.pvEnergyOut = pvEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyOut);\n }\n\n}" }, { "identifier": "EnergyTotals", "path": "src/main/java/com/gmeloni/shelly/dto/db/EnergyTotals.java", "snippet": "@Data\npublic class EnergyTotals {\n\n @JsonProperty(\"grid_energy_in\")\n private String gridEnergyIn;\n @JsonProperty(\"grid_energy_out\")\n private String gridEnergyOut;\n @JsonProperty(\"pv_energy_in\")\n private String pvEnergyIn;\n @JsonProperty(\"pv_energy_out\")\n private String pvEnergyOut;\n @JsonProperty(\"pv_energy_consumed\")\n private String pvEnergyConsumed;\n\n public EnergyTotals(Double gridEnergyIn, Double gridEnergyOut, Double pvEnergyIn, Double pvEnergyOut, Double pvEnergyConsumed) {\n DecimalFormat dataFormat = new DecimalFormat(ENERGY_DECIMAL_FORMAT);\n this.gridEnergyIn = gridEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyIn);\n this.gridEnergyOut = gridEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyOut);\n this.pvEnergyIn = pvEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyIn);\n this.pvEnergyOut = pvEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyOut);\n this.pvEnergyConsumed = pvEnergyConsumed == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyConsumed);\n }\n\n}" }, { "identifier": "HourlyAggregate", "path": "src/main/java/com/gmeloni/shelly/dto/db/HourlyAggregate.java", "snippet": "@Data\npublic class HourlyAggregate {\n\n @JsonProperty(\"hour\")\n private String hour;\n @JsonProperty(\"grid_energy_in\")\n private String gridEnergyIn;\n @JsonProperty(\"grid_energy_out\")\n private String gridEnergyOut;\n @JsonProperty(\"pv_energy_in\")\n private String pvEnergyIn;\n @JsonProperty(\"pv_energy_out\")\n private String pvEnergyOut;\n\n public HourlyAggregate(String hour, Double gridEnergyIn, Double gridEnergyOut, Double pvEnergyIn, Double pvEnergyOut) {\n DecimalFormat dataFormat = new DecimalFormat(ENERGY_DECIMAL_FORMAT);\n this.hour = Utilities.padLeftWithZeros(hour, 2);\n this.gridEnergyIn = gridEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyIn);\n this.gridEnergyOut = gridEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyOut);\n this.pvEnergyIn = pvEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyIn);\n this.pvEnergyOut = pvEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyOut);\n }\n\n}" }, { "identifier": "MonthlyAggregate", "path": "src/main/java/com/gmeloni/shelly/dto/db/MonthlyAggregate.java", "snippet": "public class MonthlyAggregate {\n\n @JsonProperty(\"month\")\n private final String month;\n @JsonProperty(\"grid_energy_in\")\n private final String gridEnergyIn;\n @JsonProperty(\"grid_energy_out\")\n private final String gridEnergyOut;\n @JsonProperty(\"pv_energy_in\")\n private final String pvEnergyIn;\n @JsonProperty(\"pv_energy_out\")\n private final String pvEnergyOut;\n\n public MonthlyAggregate(String month, Double gridEnergyIn, Double gridEnergyOut, Double pvEnergyIn, Double pvEnergyOut) {\n DecimalFormat dataFormat = new DecimalFormat(ENERGY_DECIMAL_FORMAT);\n this.month = Utilities.padLeftWithZeros(month, 2);\n this.gridEnergyIn = gridEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyIn);\n this.gridEnergyOut = gridEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(gridEnergyOut);\n this.pvEnergyIn = pvEnergyIn == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyIn);\n this.pvEnergyOut = pvEnergyOut == null ? ENERGY_DECIMAL_FORMAT : dataFormat.format(pvEnergyOut);\n }\n\n}" } ]
import com.gmeloni.shelly.dto.db.DailyAggregate; import com.gmeloni.shelly.dto.db.EnergyTotals; import com.gmeloni.shelly.dto.db.HourlyAggregate; import com.gmeloni.shelly.dto.db.MonthlyAggregate; import jakarta.persistence.*; import lombok.*; import java.io.Serializable; import java.time.LocalDateTime;
1,566
package com.gmeloni.shelly.model; @Entity @Table(name = "hourly_em_energy") @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor(access = AccessLevel.PUBLIC) @Getter @EqualsAndHashCode @NamedNativeQuery( name = "SelectHourlyAggregateByYearMonthDay", query = """ select hour(from_timestamp) as hour, grid_energy_in, grid_energy_out, pv_energy_in, pv_energy_out from hourly_em_energy where year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd')) order by hour desc """, resultSetMapping = "SelectHourlyAggregateByYearMonthDayMapping" ) @SqlResultSetMapping( name = "SelectHourlyAggregateByYearMonthDayMapping", classes = { @ConstructorResult( columns = { @ColumnResult(name = "hour", type = String.class), @ColumnResult(name = "grid_energy_in", type = Double.class), @ColumnResult(name = "grid_energy_out", type = Double.class), @ColumnResult(name = "pv_energy_in", type = Double.class), @ColumnResult(name = "pv_energy_out", type = Double.class), },
package com.gmeloni.shelly.model; @Entity @Table(name = "hourly_em_energy") @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor(access = AccessLevel.PUBLIC) @Getter @EqualsAndHashCode @NamedNativeQuery( name = "SelectHourlyAggregateByYearMonthDay", query = """ select hour(from_timestamp) as hour, grid_energy_in, grid_energy_out, pv_energy_in, pv_energy_out from hourly_em_energy where year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd')) order by hour desc """, resultSetMapping = "SelectHourlyAggregateByYearMonthDayMapping" ) @SqlResultSetMapping( name = "SelectHourlyAggregateByYearMonthDayMapping", classes = { @ConstructorResult( columns = { @ColumnResult(name = "hour", type = String.class), @ColumnResult(name = "grid_energy_in", type = Double.class), @ColumnResult(name = "grid_energy_out", type = Double.class), @ColumnResult(name = "pv_energy_in", type = Double.class), @ColumnResult(name = "pv_energy_out", type = Double.class), },
targetClass = HourlyAggregate.class
2
2023-10-26 19:52:00+00:00
2k
DimitarDSimeonov/ShopApp
src/test/java/bg/softuni/shop_app/service/impl/CommentServiceImplTest.java
[ { "identifier": "CommentAddDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/comment/CommentAddDTO.java", "snippet": "@Getter\n@Setter\npublic class CommentAddDTO {\n\n private String content;\n}" }, { "identifier": "CommentViewDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/comment/CommentViewDTO.java", "snippet": "@Getter\n@Setter\npublic class CommentViewDTO {\n\n private Long id;\n private String content;\n private String author;\n}" }, { "identifier": "Comment", "path": "src/main/java/bg/softuni/shop_app/model/entity/Comment.java", "snippet": "@Getter @Setter\n@Entity\n@Table(name = \"comments\")\npublic class Comment extends BaseEntity{\n\n @Column(columnDefinition = \"TEXT\", nullable = false)\n private String content;\n\n @Column\n private LocalDateTime date;\n\n @ManyToOne\n private Product product;\n\n @ManyToOne\n private User author;\n\n public String getAuthorFullName() {\n return author.getFirstName() + \" \" + author.getLastName();\n }\n}" }, { "identifier": "Product", "path": "src/main/java/bg/softuni/shop_app/model/entity/Product.java", "snippet": "@Getter\n@Setter\n@Entity\n@Table(name = \"products\")\npublic class Product extends BaseEntity{\n\n @Column(nullable = false)\n private String title;\n\n @Column(columnDefinition = \"TEXT\", nullable = false)\n private String description;\n\n @Column(name = \"price\", nullable = false)\n private BigDecimal price;\n\n @Enumerated(EnumType.STRING)\n private Category category;\n\n @Column(name = \"date_of_post\")\n private LocalDateTime dateOfPost;\n\n @Enumerated(EnumType.STRING)\n private Location location;\n\n @OneToMany(mappedBy = \"product\")\n private List<Comment> comments;\n\n @OneToMany(mappedBy = \"product\", fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n private List<Picture> pictures;\n\n @ManyToOne\n private User seller;\n\n public Product() {\n pictures = new ArrayList<>();\n }\n}" }, { "identifier": "User", "path": "src/main/java/bg/softuni/shop_app/model/entity/User.java", "snippet": "@Getter\n@Setter\n@Entity\n@Table(name = \"users\")\npublic class User extends BaseEntity{\n\n @Column(nullable = false, unique = true)\n private String username;\n\n @Column(nullable = false)\n private String password;\n\n @Column(name = \"first_name\", nullable = false)\n private String firstName;\n\n @Column(name = \"last_name\", nullable = false)\n private String lastName;\n\n @Column(nullable = false, unique = true)\n private String email;\n\n @Column(name = \"phone_number\", nullable = false, unique = true)\n private String phoneNumber;\n\n @OneToOne(mappedBy = \"user\")\n private OrderHistory orderHistory;\n\n @OneToOne(mappedBy = \"user\")\n private Order order;\n\n @ManyToMany(fetch = FetchType.EAGER)\n private List<Role> roles;\n\n @OneToOne(mappedBy = \"user\")\n private Picture picture;\n\n @OneToMany(mappedBy = \"seller\", fetch = FetchType.EAGER)\n private List<Product> offerProduct;\n\n public User() {\n roles = new ArrayList<>();\n }\n}" }, { "identifier": "CommentRepository", "path": "src/main/java/bg/softuni/shop_app/repository/CommentRepository.java", "snippet": "@Repository\npublic interface CommentRepository extends JpaRepository<Comment, Long> {\n\n List<Comment> findAllByProduct_Id(Long id);\n}" }, { "identifier": "ProductService", "path": "src/main/java/bg/softuni/shop_app/service/ProductService.java", "snippet": "public interface ProductService {\n Long createProduct(AddProductDTO addProductDTO, String username);\n\n void deleteById(Long id);\n\n ProductOwnerViewDTO getOwnerViewById(Long id);\n\n Product getById(Long id);\n\n List<ProductViewDTO> searchByInput(ProductSearchDTO productSearchDTO);\n\n ProductViewDTO getDetailsViewById(Long id);\n\n void clearOldProduct();\n\n List<ProductViewDTO> getLastProducts();\n\n List<ProductViewDTO> getAllProducts();\n}" }, { "identifier": "UserService", "path": "src/main/java/bg/softuni/shop_app/service/UserService.java", "snippet": "public interface UserService {\n\n boolean existUsername(String username);\n\n boolean existEmail(String email);\n\n boolean existPhoneNumber(String phoneNumber);\n\n void register(UserRegisterDTO userRegisterDTO);\n\n User getByUsername(String username);\n\n List<ProductHomePageViewDTO> getMyOffers(String username);\n\n List<UserViewDTO> getAllUsers(String username);\n\n void addAdminRole(Long id);\n\n void removeAdminRole(Long id);\n}" } ]
import bg.softuni.shop_app.model.dto.comment.CommentAddDTO; import bg.softuni.shop_app.model.dto.comment.CommentViewDTO; import bg.softuni.shop_app.model.entity.Comment; import bg.softuni.shop_app.model.entity.Product; import bg.softuni.shop_app.model.entity.User; import bg.softuni.shop_app.repository.CommentRepository; import bg.softuni.shop_app.service.ProductService; import bg.softuni.shop_app.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import java.util.ArrayList; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
1,441
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class CommentServiceImplTest { private CommentServiceImpl commentServiceToTest; @Mock private CommentRepository mockCommentRepository; @Mock private ProductService mockProductService; @Mock private ModelMapper mockModelMapper; @Mock private UserService mockUserService; @BeforeEach void setUp() { commentServiceToTest = new CommentServiceImpl(mockCommentRepository, mockProductService, mockModelMapper, mockUserService); } @Test void createComment() { Long id = 1L; String username = "username"; CommentAddDTO commentAddDTO = new CommentAddDTO();
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class CommentServiceImplTest { private CommentServiceImpl commentServiceToTest; @Mock private CommentRepository mockCommentRepository; @Mock private ProductService mockProductService; @Mock private ModelMapper mockModelMapper; @Mock private UserService mockUserService; @BeforeEach void setUp() { commentServiceToTest = new CommentServiceImpl(mockCommentRepository, mockProductService, mockModelMapper, mockUserService); } @Test void createComment() { Long id = 1L; String username = "username"; CommentAddDTO commentAddDTO = new CommentAddDTO();
Comment comment = new Comment();
2
2023-10-27 13:33:23+00:00
2k
Lucas16AR/Busca_Trip_Backend
trip/src/main/java/com/trip/controllers/PassengerController.java
[ { "identifier": "PassengerModel", "path": "trip/src/main/java/com/trip/models/PassengerModel.java", "snippet": "@Entity\n@Table(name = \"passengers\")\npublic class PassengerModel implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"last_name\")\n private String lastName;\n\n @Column(name = \"id_number\")\n private int idNumber;\n\n @Column(name = \"gender\")\n private String gender;\n\n @OneToMany(mappedBy = \"passengers\")\n private List<BookingModel> bookings;\n\n @Column(name = \"is_admin\")\n private boolean isAdmin;\n\n public PassengerModel() {\n // Empty constructor required by JPA\n }\n\n public PassengerModel(String name, String lastName, int idNumber, String gender, boolean isAdmin) {\n this.name = name;\n this.lastName = lastName;\n this.idNumber = idNumber;\n this.gender = gender;\n this.isAdmin = isAdmin;\n }\n\n // Getters and Setters...\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public int getIdNumber() {\n return idNumber;\n }\n\n public void setIdNumber(int idNumber) {\n this.idNumber = idNumber;\n }\n\n public String getGender() {\n return gender;\n }\n\n public void setGender(String gender) {\n this.gender = gender;\n }\n\n public List<BookingModel> getBookings() {\n return bookings;\n }\n\n public void setBookings(List<BookingModel> bookings) {\n this.bookings = bookings;\n }\n\n public boolean isAdmin() {\n return isAdmin;\n }\n\n public void setAdmin(boolean isAdmin) {\n this.isAdmin = isAdmin;\n }\n}" }, { "identifier": "PassengerRepository", "path": "trip/src/main/java/com/trip/repositories/PassengerRepository.java", "snippet": "public interface PassengerRepository extends CrudRepository<PassengerModel, Long> {\n}" } ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.trip.models.PassengerModel; import com.trip.repositories.PassengerRepository; import javax.validation.Valid; import java.util.List;
684
package com.trip.controllers; @RestController @RequestMapping("/passenger") public class PassengerController { @Autowired
package com.trip.controllers; @RestController @RequestMapping("/passenger") public class PassengerController { @Autowired
private PassengerRepository passengerRepository;
1
2023-10-31 14:36:20+00:00
2k
achrafaitibba/invoiceYou
src/main/java/com/onxshield/invoiceyou/invoicestatement/controller/inventoryController.java
[ { "identifier": "category", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/category.java", "snippet": "public enum category {\n CONSTRUCTION,\n PLUMBING,\n PAINTING,\n ELECTRICITY,\n HARDWARE,\n UNCATEGORIZED\n}" }, { "identifier": "unit", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/unit.java", "snippet": "public enum unit {\n KG,\n G,\n T,\n L,\n M3,\n M2,\n M,\n CM,\n COUNT,\n}" }, { "identifier": "inventoryService", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/service/inventoryService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional\npublic class inventoryService {\n\n private final productRepository productRepository;\n private final inventoryRepository inventoryRepository;\n public productResponse createProduct(productRequest request) {\n product productToSave = productRepository.save(\n product.builder()\n .name(request.name())\n .unit(unit.valueOf(request.unit()))\n .categoryList(\n Arrays.toString(request.categories())\n )\n .build()\n );\n inventory inventory = new inventory();\n inventory.setProduct(productToSave);\n inventoryRepository.save(inventory);\n return new productResponse(\n productToSave.getProductId(),\n productToSave.getName(),\n productToSave.getUnit().toString(),\n productToSave.getCategoryList()\n );\n }\n\n\n public List<productResponse> getAllProducts() {\n return productRepository.findAll().stream()\n .map(product -> new productResponse(\n product.getProductId(),\n product.getName(),\n product.getUnit().toString(),\n product.getCategoryList()\n )).toList();\n }\n\n public productResponse getProductById(Long id) {\n Optional<product> toFind = productRepository.findById(id);\n if(toFind.isPresent()){\n return new productResponse(\n toFind.get().getProductId(),\n toFind.get().getName(),\n toFind.get().getUnit().toString(),\n toFind.get().getCategoryList()\n\n );\n }else {\n throw new requestException(\"The id you provided doesn't exist.\", HttpStatus.NOT_FOUND); }\n\n }\n\n public productResponse updateProduct(Long id, productRequest request) {\n Optional<product> toUpdate = productRepository.findById(id);\n if(toUpdate.isPresent()){\n toUpdate.get().setName(request.name());\n toUpdate.get().setUnit(unit.valueOf(request.unit()));\n toUpdate.get().setCategoryList(Arrays.toString(request.categories()));\n productRepository.save(toUpdate.get());\n return new productResponse(\n id,\n toUpdate.get().getName(),\n toUpdate.get().getUnit().toString(),\n toUpdate.get().getCategoryList()\n\n );\n }else throw new requestException(\"The id you provided doesn't exist.\", HttpStatus.NOT_FOUND);\n }\n\n public Integer deleteProduct(Long id) {\n Optional<product> toRemove = productRepository.findById(id);\n if(toRemove.isPresent()){\n inventoryRepository.deleteByProductProductId(id);\n productRepository.deleteById(id);\n return 1;\n }else throw new requestException(\"The id you provided doesn't exist.\", HttpStatus.NOT_FOUND);\n }\n\n public List<inventoryResponse> getInventory() {\n return inventoryRepository.findAll().stream()\n .map(\n inventory -> new inventoryResponse(\n new productResponse(\n inventory.getProduct().getProductId(),\n inventory.getProduct().getName(),\n inventory.getProduct().getUnit().toString(),\n inventory.getProduct().getCategoryList()\n ),\n inventory.getInventoryId(),\n inventory.getAvailability(),\n inventory.getBuyPrice(),\n inventory.getSellPrice()\n\n )\n )\n .toList();\n }\n\n public inventoryResponse updateProductInventory(Long productId, inventoryRequest request) {\n Optional<product> product = productRepository.findById(productId);\n if(product.isPresent()){\n Optional<inventory> inventory = inventoryRepository.findByProductProductId(productId);\n inventory.get().setAvailability(request.availability());\n inventory.get().setBuyPrice(request.buyPrice());\n inventory.get().setSellPrice(request.sellPrice());\n inventoryRepository.save(inventory.get());\n return new inventoryResponse(\n new productResponse(\n productId,\n product.get().getName(),\n product.get().getUnit().toString(),\n product.get().getCategoryList()\n ),\n inventory.get().getInventoryId(),\n inventory.get().getAvailability(),\n inventory.get().getBuyPrice(),\n inventory.get().getSellPrice()\n\n\n );\n }else {\n throw new requestException(\"Product doesn't exit with id:\"+productId, HttpStatus.NOT_FOUND);\n }\n }\n\n\n public inventoryResponse getProductInventory(Long productId) {\n Optional<product> product = productRepository.findById(productId);\n if(product.isPresent()){\n Optional<inventory> inventory = inventoryRepository.findByProductProductId(productId);\n return new inventoryResponse(\n new productResponse(\n productId,\n product.get().getName(),\n product.get().getUnit().toString(),\n product.get().getCategoryList()\n ),\n inventory.get().getInventoryId(),\n inventory.get().getAvailability(),\n inventory.get().getBuyPrice(),\n inventory.get().getSellPrice()\n\n\n );\n }\n else throw new requestException(\"Product doesn't exit with id:\"+productId, HttpStatus.NOT_FOUND);\n }\n}" } ]
import com.onxshield.invoiceyou.invoicestatement.dto.request.inventoryRequest; import com.onxshield.invoiceyou.invoicestatement.dto.request.productRequest; import com.onxshield.invoiceyou.invoicestatement.dto.response.inventoryResponse; import com.onxshield.invoiceyou.invoicestatement.dto.response.productResponse; import com.onxshield.invoiceyou.invoicestatement.model.category; import com.onxshield.invoiceyou.invoicestatement.model.unit; import com.onxshield.invoiceyou.invoicestatement.service.inventoryService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
1,464
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/inventories") @RequiredArgsConstructor public class inventoryController { private final inventoryService inventoryService; @GetMapping("/products/categories")
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/inventories") @RequiredArgsConstructor public class inventoryController { private final inventoryService inventoryService; @GetMapping("/products/categories")
public ResponseEntity<category[]> getAllCategories(){
0
2023-10-29 11:16:37+00:00
2k
Melledy/LunarCore
src/main/java/emu/lunarcore/data/config/SummonUnitInfo.java
[ { "identifier": "MazeSkillAction", "path": "src/main/java/emu/lunarcore/game/battle/skills/MazeSkillAction.java", "snippet": "public abstract class MazeSkillAction {\n \n public void onCast(GameAvatar caster, MotionInfo castPosition) {\n \n }\n \n public void onCastHit(GameAvatar caster, List<? extends GameEntity> entities) {\n \n }\n \n public void onAttack(GameAvatar caster, List<? extends GameEntity> targets) {\n \n }\n \n}" }, { "identifier": "MazeSkillAddBuff", "path": "src/main/java/emu/lunarcore/game/battle/skills/MazeSkillAddBuff.java", "snippet": "@Getter\npublic class MazeSkillAddBuff extends MazeSkillAction {\n private int buffId;\n private int duration;\n \n @Setter\n private boolean sendBuffPacket;\n \n public MazeSkillAddBuff(int buffId, int duration) {\n this.buffId = buffId;\n this.duration = duration;\n }\n \n @Override\n public void onCast(GameAvatar caster, MotionInfo castPosition) {\n caster.addBuff(buffId, duration);\n }\n \n @Override\n public void onCastHit(GameAvatar caster, List<? extends GameEntity> entities) {\n for (GameEntity entity : entities) {\n if (entity instanceof EntityMonster monster) {\n // Add buff to monster\n var buff = monster.addBuff(caster.getAvatarId(), buffId, duration);\n \n // Send packet\n if (buff != null && this.sendBuffPacket) {\n caster.getOwner().sendPacket(new PacketSyncEntityBuffChangeListScNotify(entity.getEntityId(), buff));\n }\n }\n }\n }\n \n @Override\n public void onAttack(GameAvatar caster, List<? extends GameEntity> targets) {\n // Add debuff to monsters\n for (GameEntity target : targets) {\n if (target instanceof EntityMonster monster) {\n // Set as temp buff\n monster.setTempBuff(new SceneBuff(caster.getAvatarId(), buffId));\n }\n }\n }\n}" }, { "identifier": "MazeSkillHitProp", "path": "src/main/java/emu/lunarcore/game/battle/skills/MazeSkillHitProp.java", "snippet": "@Getter\npublic class MazeSkillHitProp extends MazeSkillAction {\n\n @Override\n public void onCastHit(GameAvatar caster, List<? extends GameEntity> entities) {\n for (GameEntity entity : entities) {\n if (entity instanceof EntityProp prop) {\n caster.getScene().destroyProp(prop);\n }\n }\n }\n\n}" } ]
import java.util.ArrayList; import java.util.List; import emu.lunarcore.game.battle.skills.MazeSkillAction; import emu.lunarcore.game.battle.skills.MazeSkillAddBuff; import emu.lunarcore.game.battle.skills.MazeSkillHitProp; import lombok.Getter;
1,056
package emu.lunarcore.data.config; /** * Original name: SummonUnitConfig */ @Getter public class SummonUnitInfo { private String AttachPoint; private SummonUnitTriggers TriggerConfig; public List<SummonUnitCustomTrigger> getCustomTriggers() { return TriggerConfig.getCustomTriggers(); } public SummonUnitCustomTrigger getTriggerByName(String name) { return getCustomTriggers().stream() .filter(c -> c.getTriggerName().equals(name)) .findFirst() .orElse(null); } public void buildMazeSkillActions() { for (var customTrigger : getCustomTriggers()) { customTrigger.buildMazeSkillActions(); } } /** * Original name: SummonUnitTriggerConfig */ @Getter public static class SummonUnitTriggers { private List<SummonUnitCustomTrigger> CustomTriggers; } /** * Original name: UnitCustomTriggerConfig */ @Getter public static class SummonUnitCustomTrigger { private String TriggerName; private List<TaskInfo> OnTriggerEnter; private transient List<MazeSkillAction> actions; public void buildMazeSkillActions() { // Create actions list this.actions = new ArrayList<>(); // Sanity check if (this.OnTriggerEnter == null) return; // Build maze actions for (var task : this.OnTriggerEnter) { if (task.getType().contains("AddMazeBuff")) { // TODO get duration from params if buff duration is dynamic var actionAddBuff = new MazeSkillAddBuff(task.getID(), 5); actionAddBuff.setSendBuffPacket(true); actions.add(actionAddBuff); } else if (task.getType().contains("TriggerHitProp")) {
package emu.lunarcore.data.config; /** * Original name: SummonUnitConfig */ @Getter public class SummonUnitInfo { private String AttachPoint; private SummonUnitTriggers TriggerConfig; public List<SummonUnitCustomTrigger> getCustomTriggers() { return TriggerConfig.getCustomTriggers(); } public SummonUnitCustomTrigger getTriggerByName(String name) { return getCustomTriggers().stream() .filter(c -> c.getTriggerName().equals(name)) .findFirst() .orElse(null); } public void buildMazeSkillActions() { for (var customTrigger : getCustomTriggers()) { customTrigger.buildMazeSkillActions(); } } /** * Original name: SummonUnitTriggerConfig */ @Getter public static class SummonUnitTriggers { private List<SummonUnitCustomTrigger> CustomTriggers; } /** * Original name: UnitCustomTriggerConfig */ @Getter public static class SummonUnitCustomTrigger { private String TriggerName; private List<TaskInfo> OnTriggerEnter; private transient List<MazeSkillAction> actions; public void buildMazeSkillActions() { // Create actions list this.actions = new ArrayList<>(); // Sanity check if (this.OnTriggerEnter == null) return; // Build maze actions for (var task : this.OnTriggerEnter) { if (task.getType().contains("AddMazeBuff")) { // TODO get duration from params if buff duration is dynamic var actionAddBuff = new MazeSkillAddBuff(task.getID(), 5); actionAddBuff.setSendBuffPacket(true); actions.add(actionAddBuff); } else if (task.getType().contains("TriggerHitProp")) {
actions.add(new MazeSkillHitProp());
2
2023-10-10 12:57:35+00:00
2k
jar-analyzer/jar-analyzer
src/main/java/me/n1ar4/jar/analyzer/plugins/chatgpt/ChatGPT.java
[ { "identifier": "LogManager", "path": "src/main/java/me/n1ar4/log/LogManager.java", "snippet": "public class LogManager {\n static LogLevel logLevel = LogLevel.INFO;\n\n public static void setLevel(LogLevel level) {\n logLevel = level;\n }\n\n public static Logger getLogger() {\n return new Logger();\n }\n}" }, { "identifier": "Logger", "path": "src/main/java/me/n1ar4/log/Logger.java", "snippet": "@SuppressWarnings(\"all\")\npublic class Logger {\n private String formatMessage(String message, Object[] args) {\n int start = 0;\n StringBuilder sb = new StringBuilder();\n int argIndex = 0;\n while (start < message.length()) {\n int open = message.indexOf(\"{}\", start);\n if (open == -1) {\n sb.append(message.substring(start));\n break;\n }\n sb.append(message.substring(start, open));\n if (argIndex < args.length) {\n sb.append(args[argIndex++]);\n } else {\n sb.append(\"{}\");\n }\n start = open + 2;\n }\n return sb.toString();\n }\n\n public void info(String message) {\n Log.info(message);\n }\n\n public void info(String message, Object... args) {\n Log.info(formatMessage(message, args));\n }\n\n public void error(String message) {\n Log.error(message);\n }\n\n public void error(String message, Object... args) {\n Log.error(formatMessage(message, args));\n }\n\n public void debug(String message) {\n Log.debug(message);\n }\n\n public void debug(String message, Object... args) {\n Log.debug(formatMessage(message, args));\n }\n\n public void warn(String message) {\n Log.warn(message);\n }\n\n public void warn(String message, Object... args) {\n Log.warn(formatMessage(message, args));\n }\n}" }, { "identifier": "JSON", "path": "src/main/java/me/n1ar4/y4json/JSON.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class JSON implements JSONConst {\n /**\n * 序列化对象到 JSON 字符串\n *\n * @param object 对象\n * @return 字符串\n */\n public static String toJSONString(Object object) {\n StringBuilder sb = new StringBuilder();\n CoreWriter.deepParse(object, sb);\n return sb.toString();\n }\n\n /**\n * 反序列化 JSON 到 Map\n *\n * @param text 字符串\n * @return JSONObject\n */\n public static JSONObject parseObject(String text) {\n CoreReader reader = new CoreReader(text);\n return reader.readJSON();\n }\n\n public static JSONArray parseArray(String text) {\n CoreReader reader = new CoreReader(text);\n return reader.readJsonArray();\n }\n}" }, { "identifier": "JSONArray", "path": "src/main/java/me/n1ar4/y4json/JSONArray.java", "snippet": "public class JSONArray extends ArrayList<Object> {\n}" }, { "identifier": "JSONObject", "path": "src/main/java/me/n1ar4/y4json/JSONObject.java", "snippet": "public class JSONObject extends HashMap<String, Object> {\n private static final RuntimeException exp = new RuntimeException(\"invalid json object value\");\n\n @Override\n public Object get(Object key) {\n Object val = super.get(key);\n if (val instanceof StringToken) {\n return ((StringToken) val).getValue();\n } else if (val instanceof NumberToken) {\n NumberToken num = (NumberToken) val;\n if (num.getType() == int.class) {\n return num.getIntValue();\n } else if (num.getType() == double.class) {\n return num.getDoubleValue();\n } else if (num.getType() == long.class) {\n return num.getLongValue();\n } else {\n throw exp;\n }\n } else if (val instanceof TrueToken) {\n return ((TrueToken) val).getValue();\n } else if (val instanceof FalseToken) {\n return ((FalseToken) val).getValue();\n } else if (val instanceof NullToken) {\n return ((NullToken) val).getValue();\n } else {\n if (val instanceof JSONObject) {\n return val;\n } else if (val instanceof JSONArray) {\n return val;\n } else {\n throw exp;\n }\n }\n }\n\n @Override\n public String toString() {\n Iterator<Entry<String, Object>> iterator = this.entrySet().iterator();\n if (!iterator.hasNext()) {\n return \"{}\";\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n while (true) {\n Map.Entry<String, Object> entry = iterator.next();\n String key = entry.getKey();\n Object value = this.get(key);\n sb.append(key);\n sb.append('=');\n sb.append(value);\n if (!iterator.hasNext()) {\n return sb.append('}').toString();\n }\n sb.append(',').append(' ');\n }\n }\n}" } ]
import me.n1ar4.http.*; import me.n1ar4.log.LogManager; import me.n1ar4.log.Logger; import me.n1ar4.y4json.JSON; import me.n1ar4.y4json.JSONArray; import me.n1ar4.y4json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map;
1,578
package me.n1ar4.jar.analyzer.plugins.chatgpt; public class ChatGPT { private static final Logger logger = LogManager.getLogger(); public static final String openaiHost = "https://api.openai.com"; public static final String chatAnywhereHost = "https://api.chatanywhere.com.cn"; private final String apiKey; private final String apiHost; private boolean initialized; private final Y4Client client; public ChatGPT(String apiKey, String apiHost, Y4Client client) { this.apiKey = apiKey; this.apiHost = apiHost; this.client = client; this.initialized = false; } public ChatGPT init() { initialized = true; return this; } public String chat(String input) { if (!initialized) { throw new IllegalStateException("need init chat gpt"); } String json = JSON.toJSONString(new GPTRequest(input)); logger.info("start chat"); HttpRequest request = getHttpRequest(json); HttpResponse response = client.request(request); if (response.getBody().length == 0) { return "none"; } if (!response.getHeaders().get(HttpHeaders.ContentType).contains("json")) { return "none"; } String respBody = new String(response.getBody()); JSONObject resp = JSON.parseObject(respBody); Object choices = resp.get("choices"); if (choices == null) { return "none"; }
package me.n1ar4.jar.analyzer.plugins.chatgpt; public class ChatGPT { private static final Logger logger = LogManager.getLogger(); public static final String openaiHost = "https://api.openai.com"; public static final String chatAnywhereHost = "https://api.chatanywhere.com.cn"; private final String apiKey; private final String apiHost; private boolean initialized; private final Y4Client client; public ChatGPT(String apiKey, String apiHost, Y4Client client) { this.apiKey = apiKey; this.apiHost = apiHost; this.client = client; this.initialized = false; } public ChatGPT init() { initialized = true; return this; } public String chat(String input) { if (!initialized) { throw new IllegalStateException("need init chat gpt"); } String json = JSON.toJSONString(new GPTRequest(input)); logger.info("start chat"); HttpRequest request = getHttpRequest(json); HttpResponse response = client.request(request); if (response.getBody().length == 0) { return "none"; } if (!response.getHeaders().get(HttpHeaders.ContentType).contains("json")) { return "none"; } String respBody = new String(response.getBody()); JSONObject resp = JSON.parseObject(respBody); Object choices = resp.get("choices"); if (choices == null) { return "none"; }
if (!(choices instanceof JSONArray)) {
3
2023-10-07 15:42:35+00:00
2k
EasyProgramming/easy-mqtt
server/src/main/java/com/ep/mqtt/server/processor/ConnectMqttProcessor.java
[ { "identifier": "Session", "path": "server/src/main/java/com/ep/mqtt/server/session/Session.java", "snippet": "@Data\npublic class Session {\n\n private String clientId;\n\n private String sessionId;\n\n private Boolean isCleanSession;\n\n private Integer keepAliveTimeSeconds;\n\n private ChannelHandlerContext channelHandlerContext;\n\n public Long getDataExpireTime() {\n return getKeepAliveTimeSeconds() * 3L;\n }\n\n public TimeUnit getDataExpireTimeUnit() {\n return TimeUnit.SECONDS;\n }\n\n public Long getDataExpireTimeMilliSecond() {\n return TimeoutUtils.toMillis(getDataExpireTime(), getDataExpireTimeUnit());\n }\n}" }, { "identifier": "SessionManager", "path": "server/src/main/java/com/ep/mqtt/server/session/SessionManager.java", "snippet": "public class SessionManager {\n\n private static final Map<String, Session> SESSION_MAP = Maps.newConcurrentMap();\n\n public static void bind(String clientId, Session session) {\n NettyUtil.setClientId(session.getChannelHandlerContext(), clientId);\n SESSION_MAP.put(clientId, session);\n }\n\n public static void unbind(String clientId) {\n Session session = get(clientId);\n if (session != null) {\n NettyUtil.setClientId(session.getChannelHandlerContext(), null);\n }\n SESSION_MAP.remove(clientId);\n }\n\n public static Session get(String clientId) {\n return SESSION_MAP.get(clientId);\n }\n\n}" }, { "identifier": "NettyUtil", "path": "server/src/main/java/com/ep/mqtt/server/util/NettyUtil.java", "snippet": "public class NettyUtil {\n\n private static final AttributeKey<String> CLIENT_ID_ATTR_KEY = AttributeKey.valueOf(\"clientId\");\n\n public static void setClientId(ChannelHandlerContext channelHandlerContext, String clientId) {\n channelHandlerContext.channel().attr(CLIENT_ID_ATTR_KEY).set(clientId);\n }\n\n public static String getClientId(ChannelHandlerContext channelHandlerContext) {\n return channelHandlerContext.channel().attr(CLIENT_ID_ATTR_KEY).get();\n }\n\n public static String getSessionId(ChannelHandlerContext channelHandlerContext) {\n return channelHandlerContext.channel().id().asLongText();\n }\n\n}" }, { "identifier": "ClientInfoVo", "path": "server/src/main/java/com/ep/mqtt/server/vo/ClientInfoVo.java", "snippet": "@Data\npublic class ClientInfoVo {\n\n /**\n * 客户端id\n */\n private String clientId;\n\n /**\n * 连接时间\n */\n private Long connectTime;\n\n}" } ]
import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.ep.mqtt.server.session.Session; import com.ep.mqtt.server.session.SessionManager; import com.ep.mqtt.server.util.NettyUtil; import com.ep.mqtt.server.vo.ClientInfoVo; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.*; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j;
994
package com.ep.mqtt.server.processor; /** * 建立连接 * * @author zbz * @date 2023/7/14 16:42 */ @Slf4j @Component public class ConnectMqttProcessor extends AbstractMqttProcessor<MqttConnectMessage> { private static final int MIN_KEEP_ALIVE_TIME_SECONDS = 30; @Override public void process(ChannelHandlerContext channelHandlerContext, MqttConnectMessage mqttConnectMessage) { try { // 判断协议版本 if (!validVersion(mqttConnectMessage.variableHeader().version())) { sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION, false, true); return; } String clientIdentifier = mqttConnectMessage.payload().clientIdentifier(); // 与协议不一致,这里强制客户端上传id if (StringUtils.isBlank(clientIdentifier)) { sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false, true); return; } if (!defaultDeal.authentication(mqttConnectMessage)) { // 认证失败,返回错误的ack消息 sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD, false, true); return; } int keepAliveTimeSeconds = keepAlive(channelHandlerContext, mqttConnectMessage);
package com.ep.mqtt.server.processor; /** * 建立连接 * * @author zbz * @date 2023/7/14 16:42 */ @Slf4j @Component public class ConnectMqttProcessor extends AbstractMqttProcessor<MqttConnectMessage> { private static final int MIN_KEEP_ALIVE_TIME_SECONDS = 30; @Override public void process(ChannelHandlerContext channelHandlerContext, MqttConnectMessage mqttConnectMessage) { try { // 判断协议版本 if (!validVersion(mqttConnectMessage.variableHeader().version())) { sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION, false, true); return; } String clientIdentifier = mqttConnectMessage.payload().clientIdentifier(); // 与协议不一致,这里强制客户端上传id if (StringUtils.isBlank(clientIdentifier)) { sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false, true); return; } if (!defaultDeal.authentication(mqttConnectMessage)) { // 认证失败,返回错误的ack消息 sendConnectAck(channelHandlerContext, MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD, false, true); return; } int keepAliveTimeSeconds = keepAlive(channelHandlerContext, mqttConnectMessage);
ClientInfoVo clientInfo = defaultDeal.getClientInfo(clientIdentifier);
3
2023-10-08 06:41:33+00:00
2k
fuzhengwei/chatglm-sdk-java
src/main/java/cn/bugstack/chatglm/session/defaults/DefaultOpenAiSessionFactory.java
[ { "identifier": "IOpenAiApi", "path": "src/main/java/cn/bugstack/chatglm/IOpenAiApi.java", "snippet": "public interface IOpenAiApi {\n\n String v3_completions = \"api/paas/v3/model-api/{model}/sse-invoke\";\n String v3_completions_sync = \"api/paas/v3/model-api/{model}/invoke\";\n\n @POST(v3_completions)\n Single<ChatCompletionResponse> completions(@Path(\"model\") String model, @Body ChatCompletionRequest chatCompletionRequest);\n\n @POST(v3_completions_sync)\n Single<ChatCompletionSyncResponse> completions(@Body ChatCompletionRequest chatCompletionRequest);\n\n}" }, { "identifier": "OpenAiHTTPInterceptor", "path": "src/main/java/cn/bugstack/chatglm/interceptor/OpenAiHTTPInterceptor.java", "snippet": "public class OpenAiHTTPInterceptor implements Interceptor {\n\n /**\n * 智普Ai,Jwt加密Token\n */\n private final Configuration configuration;\n\n public OpenAiHTTPInterceptor(Configuration configuration) {\n this.configuration = configuration;\n }\n\n @Override\n public @NotNull Response intercept(Chain chain) throws IOException {\n // 1. 获取原始 Request\n Request original = chain.request();\n // 2. 构建请求\n Request request = original.newBuilder()\n .url(original.url())\n .header(\"Authorization\", \"Bearer \" + BearerTokenUtils.getToken(configuration.getApiKey(), configuration.getApiSecret()))\n .header(\"Content-Type\", Configuration.JSON_CONTENT_TYPE)\n .header(\"User-Agent\", Configuration.DEFAULT_USER_AGENT)\n .header(\"Accept\", null != original.header(\"Accept\") ? original.header(\"Accept\") : Configuration.SSE_CONTENT_TYPE)\n .method(original.method(), original.body())\n .build();\n\n // 3. 返回执行结果\n return chain.proceed(request);\n }\n\n}" }, { "identifier": "Configuration", "path": "src/main/java/cn/bugstack/chatglm/session/Configuration.java", "snippet": "@Slf4j\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Configuration {\n\n // 智普Ai ChatGlM 请求地址\n @Getter\n @Setter\n private String apiHost = \"https://open.bigmodel.cn/api/paas/\";\n\n // 智普Ai https://open.bigmodel.cn/usercenter/apikeys - apiSecretKey = {apiKey}.{apiSecret}\n private String apiSecretKey;\n\n public void setApiSecretKey(String apiSecretKey) {\n this.apiSecretKey = apiSecretKey;\n String[] arrStr = apiSecretKey.split(\"\\\\.\");\n if (arrStr.length != 2) {\n throw new RuntimeException(\"invalid apiSecretKey\");\n }\n this.apiKey = arrStr[0];\n this.apiSecret = arrStr[1];\n }\n\n @Getter\n private String apiKey;\n @Getter\n private String apiSecret;\n\n // Api 服务\n @Setter\n @Getter\n private IOpenAiApi openAiApi;\n\n @Getter\n @Setter\n private OkHttpClient okHttpClient;\n\n public EventSource.Factory createRequestFactory() {\n return EventSources.createFactory(okHttpClient);\n }\n\n // OkHttp 配置信息\n @Setter\n @Getter\n private HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;\n @Setter\n @Getter\n private long connectTimeout = 450;\n @Setter\n @Getter\n private long writeTimeout = 450;\n @Setter\n @Getter\n private long readTimeout = 450;\n\n // http keywords\n public static final String SSE_CONTENT_TYPE = \"text/event-stream\";\n public static final String DEFAULT_USER_AGENT = \"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\";\n public static final String APPLICATION_JSON = \"application/json\";\n public static final String JSON_CONTENT_TYPE = APPLICATION_JSON + \"; charset=utf-8\";\n\n}" }, { "identifier": "OpenAiSession", "path": "src/main/java/cn/bugstack/chatglm/session/OpenAiSession.java", "snippet": "public interface OpenAiSession {\n\n EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException;\n\n CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException;\n\n ChatCompletionSyncResponse completionsSync(ChatCompletionRequest chatCompletionRequest) throws IOException;\n\n}" }, { "identifier": "OpenAiSessionFactory", "path": "src/main/java/cn/bugstack/chatglm/session/OpenAiSessionFactory.java", "snippet": "public interface OpenAiSessionFactory {\n\n OpenAiSession openSession();\n\n}" } ]
import cn.bugstack.chatglm.IOpenAiApi; import cn.bugstack.chatglm.interceptor.OpenAiHTTPInterceptor; import cn.bugstack.chatglm.session.Configuration; import cn.bugstack.chatglm.session.OpenAiSession; import cn.bugstack.chatglm.session.OpenAiSessionFactory; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; import java.util.concurrent.TimeUnit;
1,488
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话工厂 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class DefaultOpenAiSessionFactory implements OpenAiSessionFactory { private final Configuration configuration; public DefaultOpenAiSessionFactory(Configuration configuration) { this.configuration = configuration; } @Override public OpenAiSession openSession() { // 1. 日志配置 HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(configuration.getLevel()); // 2. 开启 Http 客户端 OkHttpClient okHttpClient = new OkHttpClient .Builder() .addInterceptor(httpLoggingInterceptor) .addInterceptor(new OpenAiHTTPInterceptor(configuration)) .connectTimeout(configuration.getConnectTimeout(), TimeUnit.SECONDS) .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS) .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS) .build(); configuration.setOkHttpClient(okHttpClient); // 3. 创建 API 服务
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话工厂 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ public class DefaultOpenAiSessionFactory implements OpenAiSessionFactory { private final Configuration configuration; public DefaultOpenAiSessionFactory(Configuration configuration) { this.configuration = configuration; } @Override public OpenAiSession openSession() { // 1. 日志配置 HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(configuration.getLevel()); // 2. 开启 Http 客户端 OkHttpClient okHttpClient = new OkHttpClient .Builder() .addInterceptor(httpLoggingInterceptor) .addInterceptor(new OpenAiHTTPInterceptor(configuration)) .connectTimeout(configuration.getConnectTimeout(), TimeUnit.SECONDS) .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS) .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS) .build(); configuration.setOkHttpClient(okHttpClient); // 3. 创建 API 服务
IOpenAiApi openAiApi = new Retrofit.Builder()
0
2023-10-10 13:49:59+00:00
2k
lunasaw/gb28181-proxy
gb28181-test/src/main/java/io/github/lunasaw/gbproxy/test/user/server/DefaultSubscribeResponseProcessorServer.java
[ { "identifier": "Device", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/entity/Device.java", "snippet": "@Data\npublic abstract class Device {\n\n /**\n * 用户Id\n */\n private String userId;\n\n /**\n * 域\n */\n private String realm;\n\n /**\n * 传输协议\n * UDP/TCP\n */\n private String transport;\n\n /**\n * 数据流传输模式\n * UDP:udp传输\n * TCP-ACTIVE:tcp主动模式\n * TCP-PASSIVE:tcp被动模式\n */\n private String streamMode;\n\n /**\n * wan地址_ip\n */\n private String ip;\n\n /**\n * wan地址_port\n */\n private int port;\n\n /**\n * wan地址\n */\n private String hostAddress;\n\n /**\n * 密码\n */\n private String password;\n\n\n /**\n * 编码\n */\n private String charset;\n\n public String getCharset() {\n if (this.charset == null) {\n return \"UTF-8\";\n }\n return charset;\n }\n\n public void setHostAddress(String hostAddress) {\n this.hostAddress = hostAddress;\n }\n\n public String getHostAddress() {\n if (StringUtils.isBlank(hostAddress)) {\n return ip + \":\" + port;\n }\n return hostAddress;\n }\n}" }, { "identifier": "DeviceSubscribe", "path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/response/DeviceSubscribe.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@XmlRootElement(name = \"Response\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceSubscribe extends DeviceBase {\n\n /**\n * OK\n */\n @XmlElement(name = \"Result\")\n private String Result = \"OK\";\n\n public DeviceSubscribe(String cmdType, String sn, String deviceId) {\n super(cmdType, sn, deviceId);\n }\n\n}" }, { "identifier": "SubscribeResponseProcessorServer", "path": "gb28181-server/src/main/java/io/github/lunasaw/gbproxy/server/transimit/response/subscribe/SubscribeResponseProcessorServer.java", "snippet": "public interface SubscribeResponseProcessorServer {\n void subscribeResult(DeviceSubscribe deviceSubscribe);\n\n}" }, { "identifier": "DeviceConfig", "path": "gb28181-test/src/main/java/io/github/lunasaw/gbproxy/test/config/DeviceConfig.java", "snippet": "@Configuration\npublic class DeviceConfig {\n\n public static final String LOOP_IP = \"192.168.2.101\";\n\n public static final String LOOP_IP_LOCAL = \"0.0.0.0\";\n\n public static final String REMOTE_IP = \"10.37.5.132\";\n\n public static Map<String, Device> DEVICE_MAP = new ConcurrentHashMap<>();\n\n public static Map<String, Device> DEVICE_CLIENT_VIEW_MAP = new ConcurrentHashMap<>();\n\n public static Map<String, Device> DEVICE_SERVER_VIEW_MAP = new ConcurrentHashMap<>();\n\n static {\n FromDevice clientFrom = FromDevice.getInstance(\"33010602011187000001\", LOOP_IP, 8118);\n DEVICE_MAP.put(\"client_from\", clientFrom);\n\n ToDevice clientTo = ToDevice.getInstance(\"41010500002000000001\", LOOP_IP, 8117);\n clientTo.setPassword(\"bajiuwulian1006\");\n clientTo.setRealm(\"4101050000\");\n DEVICE_MAP.put(\"client_to\", clientTo);\n\n FromDevice serverFrom = FromDevice.getInstance(\"41010500002000000001\", LOOP_IP, 8117);\n serverFrom.setPassword(\"bajiuwulian1006\");\n serverFrom.setRealm(\"4101050000\");\n DEVICE_MAP.put(\"server_from\", serverFrom);\n\n ToDevice serverTo = ToDevice.getInstance(\"33010602011187000001\", LOOP_IP, 8118);\n DEVICE_MAP.put(\"server_to\", serverTo);\n }\n\n @Bean\n @Qualifier(\"clientFrom\")\n public Device clientFrom() {\n return DEVICE_MAP.get(\"client_from\");\n }\n\n @Bean\n @Qualifier(\"clientTo\")\n public Device clientTo() {\n return DEVICE_MAP.get(\"client_to\");\n }\n\n @Bean\n @Qualifier(\"serverFrom\")\n public Device serverDevice() {\n return DEVICE_MAP.get(\"server_from\");\n }\n\n @Bean\n @Qualifier(\"serverTo\")\n public Device cleientDevice() {\n return DEVICE_MAP.get(\"server_to\");\n }\n}" } ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.alibaba.fastjson2.JSON; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.gb28181.common.entity.response.DeviceSubscribe; import io.github.lunasaw.gbproxy.server.transimit.response.subscribe.SubscribeResponseProcessorServer; import io.github.lunasaw.gbproxy.test.config.DeviceConfig; import lombok.extern.slf4j.Slf4j;
1,287
package io.github.lunasaw.gbproxy.test.user.server; /** * @author luna * @version 1.0 * @date 2023/12/11 * @description: */ @Component @Slf4j public class DefaultSubscribeResponseProcessorServer implements SubscribeResponseProcessorServer { @Autowired @Qualifier("serverFrom")
package io.github.lunasaw.gbproxy.test.user.server; /** * @author luna * @version 1.0 * @date 2023/12/11 * @description: */ @Component @Slf4j public class DefaultSubscribeResponseProcessorServer implements SubscribeResponseProcessorServer { @Autowired @Qualifier("serverFrom")
private Device fromDevice;
0
2023-10-11 06:56:28+00:00
2k
Michi4/LuminAI
LuminAi/src/main/java/com/data/fetcher/driver/Driver.java
[ { "identifier": "DataFetcher", "path": "LuminAi/src/main/java/com/data/fetcher/DataFetcher.java", "snippet": "public interface DataFetcher {\n void invoke();\n}" }, { "identifier": "SensorData", "path": "LuminAi/src/main/java/com/data/model/SensorData.java", "snippet": "@Entity\npublic class SensorData {\n @Id\n @GeneratedValue\n @Column(name = \"v_id\")\n private Long id;\n\n private Double value;\n\n @ManyToOne\n @Nullable\n @JoinColumn(name = \"d_id\")\n private Sensor sensor;\n\n //<editor-fold desc=\"Getter and Setter\">\n public Long getId() {\n return id;\n }\n\n public Double getValue() {\n return value;\n }\n\n public void setValue(Double value) {\n this.value = value;\n }\n\n public Sensor getDevice() {\n return sensor;\n }\n\n public void setDevice(Sensor sensor) {\n this.sensor = sensor;\n }\n //</editor-fold>\n}" }, { "identifier": "SensorDataRepository", "path": "LuminAi/src/main/java/com/data/repository/SensorDataRepository.java", "snippet": "@ApplicationScoped\npublic class SensorDataRepository {\n @Inject\n EntityManager entityManager;\n\n @Transactional\n public void addData(SensorData data) {\n entityManager.persist(data);\n }\n\n @Transactional\n public void addData(List<SensorData> data) {\n if (data != null) {\n data.forEach(d -> entityManager.persist(d));\n }\n }\n\n\n public List<SensorData> getAllData() {\n return entityManager.createQuery(\"SELECT d FROM SensorData d\", SensorData.class).getResultList();\n }\n\n public List<SensorData> getAllDataFromSensor(Sensor sensor) {\n return entityManager.createQuery(\"SELECT d FROM SensorData d WHERE d.sensor = :sensor\", SensorData.class)\n .setParameter(\"sensor\", sensor)\n .getResultList();\n }\n}" }, { "identifier": "DataSocket", "path": "LuminAi/src/main/java/com/data/session/DataSocket.java", "snippet": "@ServerEndpoint(value = \"/subscribeUpdates\", encoders = { DataEncoder.class })\n@ApplicationScoped\npublic class DataSocket {\n Set<Session> sessions = new HashSet<>();\n\n @OnOpen\n public void onOpen(Session session) {\n sessions.add(session);\n }\n\n @OnError\n public void onError(Session session, Throwable throwable) {\n sessions.remove(session);\n throw new RuntimeException(\"error with user websocket\", throwable);\n }\n\n @OnClose\n public void onClose(Session session) {\n sessions.remove(session);\n }\n\n public void publish(SensorData data) {\n sessions.forEach(session -> session.getAsyncRemote().sendObject(data, result -> {\n if (result.getException() != null) {\n throw new RuntimeException(\"error with user websocket\", result.getException());\n }\n }));\n }\n}" } ]
import com.data.fetcher.DataFetcher; import com.data.model.SensorData; import com.data.repository.SensorDataRepository; import com.data.session.DataSocket; import io.quarkus.logging.Log; import jakarta.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; import java.util.List;
816
package com.data.fetcher.driver; public abstract class Driver implements DataFetcher { @Inject SensorDataRepository dataRepository; @Inject DataSocket dataSocket; @ConfigProperty(name = "apiUrl") public static String apiUrl; @Override public void invoke() { try {
package com.data.fetcher.driver; public abstract class Driver implements DataFetcher { @Inject SensorDataRepository dataRepository; @Inject DataSocket dataSocket; @ConfigProperty(name = "apiUrl") public static String apiUrl; @Override public void invoke() { try {
List<SensorData> data = runDriver();
1
2023-10-10 10:31:59+00:00
2k
1415181920/yamis-admin
cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/setting/service/impl/AdminSettingServiceImpl.java
[ { "identifier": "YamisBootstrap", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/bootstrap/base/YamisBootstrap.java", "snippet": "@Getter\n@Component\npublic class YamisBootstrap {\n\n //获取全局公共样式\n YamisAssetStyle yamisAssetStyle = new YamisAssetStyle();\n //Layout样式\n YamisLayout yamisLayout = new YamisLayout();\n\n @Value(\"${website.app_name}\")\n private String appName;\n\n\n\n public YamisBootstrap(@Value(\"${website.app_name}\") String appName) {\n yamisAssetStyle.setCss(new String[]{});\n yamisAssetStyle.setJs(new String[]{});\n yamisAssetStyle.setScripts(new String[]{});\n yamisAssetStyle.setStyles(new String[]{});\n yamisLayout.setFooter(appName);\n yamisLayout.setTitle(\"%title% | \"+appName);\n }\n}" }, { "identifier": "YamisAssetStyle", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/bootstrap/pojo/YamisAssetStyle.java", "snippet": "@Data\n@Repository\npublic class YamisAssetStyle {\n\n private String[] js;\n private String[] css;\n private String[] scripts;\n private String[] styles;\n private String appendNav;\n private String prependNav;\n\n}" }, { "identifier": "YamisLayout", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/bootstrap/pojo/YamisLayout.java", "snippet": "@Data\n@Repository\npublic class YamisLayout {\n\n\n private String footer;\n private Header header;\n private String title;\n private String[] keep_alive_exclude = new String[]{};\n\n public YamisLayout() {\n this.header = new Header();\n }\n @Data\n public static class Header {\n private boolean refresh = true; // 刷新\n private boolean dark = true; // 暗黑模式\n private boolean full_screen = true; // 全屏\n private boolean theme_config = true; // 主题配置\n }\n\n\n}" }, { "identifier": "CommonUrlUtil", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/util/CommonUrlUtil.java", "snippet": "@Component\npublic class CommonUrlUtil {\n\n\n @Value(\"${website.url}\")\n private String URL_PREFIX;\n\n /**\n * 根据绝对路径获取完整的图片url\n */\n public String get(String url) {\n if (url==null || url.isEmpty()){\n return null;\n }\n return URL_PREFIX + url;\n }\n\n\n}" }, { "identifier": "AdminSettingResponse", "path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/setting/resp/AdminSettingResponse.java", "snippet": "@Component\n@Data\npublic class AdminSettingResponse {\n\n @Value(\"${website.app_name}\")\n private String app_name;\n private Assets assets;\n private ArrayList<String> enabled_extensions = new ArrayList<>();\n private Layout layout;\n private String locale;\n private boolean login_captcha;\n private String logo;\n private Nav nav;\n private boolean show_development_tools;\n private Object system_theme_setting;\n\n @Data\n private static class Assets {\n private String[] js;\n private String[] css;\n private String[] scripts;\n private String[] styles;\n }\n\n @Data\n public static class Layout {\n\n private String footer;\n private Header header;\n private String title;\n private String[] keep_alive_exclude;\n\n\n @Data\n public static class Header {\n private boolean refresh; // 刷新\n private boolean dark; // 暗黑模式\n private boolean full_screen; // 全屏\n private boolean theme_config; // 主题配置\n }\n\n }\n\n //实例化Nav\n public AdminSettingResponse() {\n this.nav = new Nav();\n this.assets = new Assets();\n }\n\n @Data\n public static class Nav {\n private Object appendNav;\n private Object prependNav;\n }\n\n @Override\n public String toString() {\n return \"AdminSettingsResponse{\" +\n \"app_name='\" + app_name + '\\'' +\n \", assets=\" + assets +\n \", enabled_extensions=\" + enabled_extensions +\n \", layout=\" + layout +\n \", locale='\" + locale + '\\'' +\n \", login_captcha=\" + login_captcha +\n \", logo='\" + logo + '\\'' +\n \", nav=\" + nav +\n \", show_development_tools=\" + show_development_tools +\n \", system_theme_setting=\" + system_theme_setting +\n '}';\n }\n}" }, { "identifier": "AdminSettingService", "path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/setting/service/AdminSettingService.java", "snippet": "public interface AdminSettingService {\n\n public AdminSettingResponse getSetting();\n\n}" } ]
import cn.hutool.core.bean.BeanUtil; import io.xiaoyu.common.bootstrap.base.YamisBootstrap; import io.xiaoyu.common.bootstrap.pojo.YamisAssetStyle; import io.xiaoyu.common.bootstrap.pojo.YamisLayout; import io.xiaoyu.common.util.CommonUrlUtil; import io.xiaoyu.sys.modular.setting.resp.AdminSettingResponse; import io.xiaoyu.sys.modular.setting.service.AdminSettingService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap;
1,352
package io.xiaoyu.sys.modular.setting.service.impl; @Service public class AdminSettingServiceImpl implements AdminSettingService { @Resource private AdminSettingResponse adminSettingResponse; @Resource
package io.xiaoyu.sys.modular.setting.service.impl; @Service public class AdminSettingServiceImpl implements AdminSettingService { @Resource private AdminSettingResponse adminSettingResponse; @Resource
private CommonUrlUtil commonUrlUtil;
3
2023-10-09 06:04:30+00:00
2k
petrovviacheslav/myitmo
Программирование/Viacheslav/lab2/src/info/Pokemons/Claydol.java
[ { "identifier": "Scratch", "path": "Программирование/Viacheslav/lab2/src/info/Moves/PhysicalMoves/Scratch.java", "snippet": "public class Scratch extends PhysicalMove {\n public Scratch(){\n super(Type.NORMAL,40, 100);\n }\n\n // одно из самых распространенных и базовых движений,\n // которым обучается покемон. Он наносит урон без каких-либо дополнительных эффектов.\n\n\n @Override\n protected String describe(){\n return \"использует Scratch\";\n }\n}" }, { "identifier": "Aeroblast", "path": "Программирование/Viacheslav/lab2/src/info/Moves/SpecialMoves/Aeroblast.java", "snippet": "public class Aeroblast extends SpecialMove {\n public Aeroblast(){\n super(Type.FLYING, 100, 95);\n }\n \n\n // Aeroblast наносит урон и имеет увеличенный коэффициент критического удара (1/8 вместо 1/24).\n\n @Override\n protected double calcCriticalHit(Pokemon a, Pokemon d) {\n return 3.0 * super.calcCriticalHit(a, d);\n }\n\n\n @Override\n protected String describe(){\n return \"использует Aeroblast\";\n }\n}" }, { "identifier": "LightScreen", "path": "Программирование/Viacheslav/lab2/src/info/Moves/StatusMoves/LightScreen.java", "snippet": "public class LightScreen extends StatusMove {\n public LightScreen(){\n super(Type.PSYCHIC, 0, 0);\n }\n \n\n @Override\n public void applySelfEffects(Pokemon p) {\n Effect eff = new Effect();\n eff.stat(Stat.SPECIAL_ATTACK, (int)p.getStat(Stat.SPECIAL_ATTACK) / 2);\n eff.turns(5);\n\n p.addEffect(eff);\n // LightScreen уменьшает урон от специальных атак на 50% на 5 ходов. \n // Его эффекты распространяются на всех покемонов на стороне пользователя поля. ?????\n }\n\n @Override\n protected String describe(){\n return \"использует Light Screen\";\n }\n}" }, { "identifier": "Minimize", "path": "Программирование/Viacheslav/lab2/src/info/Moves/StatusMoves/Minimize.java", "snippet": "public class Minimize extends StatusMove {\n public Minimize(){\n super(Type.NORMAL, 0, 0);\n }\n \n \n @Override\n public void applySelfEffects(Pokemon p) {\n p.setMod(Stat.EVASION, 2);\n // Minimize увеличивает уклонение пользователя на две ступени, тем \n // самым затрудняя попадание в пользователя.\n }\n\n @Override\n protected String describe(){\n return \"использует Minimize \";\n }\n}" } ]
import info.Moves.PhysicalMoves.Scratch; import info.Moves.SpecialMoves.Aeroblast; import info.Moves.StatusMoves.LightScreen; import info.Moves.StatusMoves.Minimize; import ru.ifmo.se.pokemon.*;
869
package info.Pokemons; public class Claydol extends Pokemon { public Claydol(String name, int level){ super(name,level); setStats(50,60,95,120,70,70); setType(Type.GROUND);
package info.Pokemons; public class Claydol extends Pokemon { public Claydol(String name, int level){ super(name,level); setStats(50,60,95,120,70,70); setType(Type.GROUND);
setMove(new Aeroblast(), new LightScreen(), new Scratch(), new Minimize());
3
2023-10-13 08:29:38+00:00
2k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-nms/src/main/java/net/swofty/swm/nms/CraftCLSMBridge.java
[ { "identifier": "CLSMBridge", "path": "swoftyworldmanager-classmodifier/src/main/java/net/swofty/swm/clsm/CLSMBridge.java", "snippet": "public interface CLSMBridge {\n\n default Object getChunk(Object world, int x, int z) {\n return null;\n }\n\n default boolean saveChunk(Object world, Object chunkAccess) {\n return false;\n }\n\n // Array containing the normal world, the nether and the end\n Object[] getDefaultWorlds();\n\n boolean isCustomWorld(Object world);\n\n default boolean skipWorldAdd(Object world) {\n return false; // If true, the world won't be added to the bukkit world list\n }\n}" }, { "identifier": "ClassModifier", "path": "swoftyworldmanager-classmodifier/src/main/java/net/swofty/swm/clsm/ClassModifier.java", "snippet": "public class ClassModifier {\n\n private static CLSMBridge customLoader;\n\n public static CompletableFuture getFutureChunk(Object world, int x, int z) {\n if (customLoader == null) {\n return null;\n }\n\n Object chunk = customLoader.getChunk(world, x, z);\n return chunk != null ? CompletableFuture.supplyAsync(() -> Either.left(chunk)) : null;\n }\n\n public static boolean saveChunk(Object world, Object chunkAccess) {\n return customLoader != null && customLoader.saveChunk(world, chunkAccess);\n }\n\n public static boolean isCustomWorld(Object world) {\n return customLoader != null && customLoader.isCustomWorld(world);\n }\n\n public static boolean skipWorldAdd(Object world) {\n return customLoader != null && customLoader.skipWorldAdd(world);\n }\n\n public static void setLoader(CLSMBridge loader) {\n customLoader = loader;\n }\n\n public static Object[] getDefaultWorlds() {\n return customLoader != null ? customLoader.getDefaultWorlds() : null;\n }\n}" }, { "identifier": "CustomWorldServer", "path": "swoftyworldmanager-nms/src/main/java/net/swofty/swm/nms/custom/CustomWorldServer.java", "snippet": "public class CustomWorldServer extends WorldServer {\n\n private static final Logger LOGGER = LogManager.getLogger(\"SWM World\");\n private static final ExecutorService WORLD_SAVER_SERVICE = Executors.newFixedThreadPool(4, new ThreadFactoryBuilder()\n .setNameFormat(\"SWM Pool Thread #%1$d\").build());\n\n @Getter\n private final CraftSlimeWorld slimeWorld;\n private final Object saveLock = new Object();\n\n @Getter\n @Setter\n private boolean ready = false;\n\n public CustomWorldServer(CraftSlimeWorld world, IDataManager dataManager, int dimension) {\n super(MinecraftServer.getServer(), dataManager, dataManager.getWorldData(), dimension, MinecraftServer.getServer().methodProfiler,\n World.Environment.valueOf(world.getPropertyMap().getValue(SlimeProperties.ENVIRONMENT).toUpperCase()), null);\n\n b();\n this.slimeWorld = world;\n this.tracker = new EntityTracker(this);\n addIWorldAccess(new WorldManager(MinecraftServer.getServer(), this));\n\n // Set world properties\n SlimePropertyMap propertyMap = world.getPropertyMap();\n\n worldData.setDifficulty(EnumDifficulty.valueOf(propertyMap.getValue(SlimeProperties.DIFFICULTY).toUpperCase()));\n worldData.setSpawn(new BlockPosition(propertyMap.getValue(SlimeProperties.SPAWN_X), propertyMap.getValue(SlimeProperties.SPAWN_Y), propertyMap.getValue(SlimeProperties.SPAWN_Z)));\n super.setSpawnFlags(propertyMap.getValue(SlimeProperties.ALLOW_MONSTERS), propertyMap.getValue(SlimeProperties.ALLOW_ANIMALS));\n\n this.pvpMode = propertyMap.getValue(SlimeProperties.PVP);\n\n // Load all chunks\n CustomChunkLoader chunkLoader = ((CustomDataManager) this.getDataManager()).getChunkLoader();\n chunkLoader.loadAllChunks(this);\n }\n\n @Override\n public void save(boolean forceSave, IProgressUpdate progressUpdate) throws ExceptionWorldConflict {\n if (!slimeWorld.isReadOnly()) {\n super.save(forceSave, progressUpdate);\n\n if (MinecraftServer.getServer().isStopped()) { // Make sure the SlimeWorld gets saved before stopping the server by running it from the main thread\n save();\n\n // Have to manually unlock the world as well\n try {\n slimeWorld.getLoader().unlockWorld(slimeWorld.getName());\n } catch (IOException ex) {\n LOGGER.error(\"Failed to unlock the world \" + slimeWorld.getName() + \". Please unlock it manually by using the command /swm manualunlock. Stack trace:\");\n\n ex.printStackTrace();\n } catch (UnknownWorldException ignored) {\n\n }\n } else {\n WORLD_SAVER_SERVICE.execute(this::save);\n }\n }\n }\n\n private void save() {\n synchronized (saveLock) { // Don't want to save the slimeWorld from multiple threads simultaneously\n try {\n LOGGER.info(\"Saving world \" + slimeWorld.getName() + \"...\");\n long start = System.currentTimeMillis();\n byte[] serializedWorld = slimeWorld.serialize();\n slimeWorld.getLoader().saveWorld(slimeWorld.getName(), serializedWorld, false);\n LOGGER.info(\"World \" + slimeWorld.getName() + \" saved in \" + (System.currentTimeMillis() - start) + \"ms.\");\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n }\n}" } ]
import net.swofty.swm.clsm.CLSMBridge; import net.swofty.swm.clsm.ClassModifier; import lombok.RequiredArgsConstructor; import net.minecraft.server.v1_8_R3.WorldServer; import net.swofty.swm.nms.custom.CustomWorldServer;
1,564
package net.swofty.swm.nms; @RequiredArgsConstructor public class CraftCLSMBridge implements CLSMBridge { private final SlimeNMS nmsInstance; @Override public Object[] getDefaultWorlds() { WorldServer defaultWorld = nmsInstance.getDefaultWorld(); WorldServer netherWorld = nmsInstance.getDefaultNetherWorld(); WorldServer endWorld = nmsInstance.getDefaultEndWorld(); if (defaultWorld != null || netherWorld != null || endWorld != null) { return new WorldServer[] { defaultWorld, netherWorld, endWorld }; } // Returning null will just run the original load world method return null; } @Override public boolean isCustomWorld(Object world) { return world instanceof CustomWorldServer; } @Override public boolean skipWorldAdd(Object world) { if (!isCustomWorld(world) || nmsInstance.isLoadingDefaultWorlds()) { return false; } CustomWorldServer worldServer = (CustomWorldServer) world; return !worldServer.isReady(); } static void initialize(SlimeNMS instance) {
package net.swofty.swm.nms; @RequiredArgsConstructor public class CraftCLSMBridge implements CLSMBridge { private final SlimeNMS nmsInstance; @Override public Object[] getDefaultWorlds() { WorldServer defaultWorld = nmsInstance.getDefaultWorld(); WorldServer netherWorld = nmsInstance.getDefaultNetherWorld(); WorldServer endWorld = nmsInstance.getDefaultEndWorld(); if (defaultWorld != null || netherWorld != null || endWorld != null) { return new WorldServer[] { defaultWorld, netherWorld, endWorld }; } // Returning null will just run the original load world method return null; } @Override public boolean isCustomWorld(Object world) { return world instanceof CustomWorldServer; } @Override public boolean skipWorldAdd(Object world) { if (!isCustomWorld(world) || nmsInstance.isLoadingDefaultWorlds()) { return false; } CustomWorldServer worldServer = (CustomWorldServer) world; return !worldServer.isReady(); } static void initialize(SlimeNMS instance) {
ClassModifier.setLoader(new CraftCLSMBridge(instance));
1
2023-10-08 10:54:28+00:00
2k
marcushellberg/spring-boot-langchain-rag
src/main/java/com/example/application/services/CarRentalService.java
[ { "identifier": "Booking", "path": "src/main/java/com/example/application/data/Booking.java", "snippet": "public class Booking {\n\n private String bookingNumber;\n private LocalDate bookingFrom;\n private LocalDate bookingTo;\n private Customer customer;\n\n private BookingStatus bookingStatus;\n\n public Booking(String bookingNumber, LocalDate bookingFrom, LocalDate bookingTo, Customer customer, BookingStatus bookingStatus) {\n this.bookingNumber = bookingNumber;\n this.bookingFrom = bookingFrom;\n this.bookingTo = bookingTo;\n this.customer = customer;\n this.bookingStatus = bookingStatus;\n }\n\n\n public String getBookingNumber() {\n return bookingNumber;\n }\n\n public void setBookingNumber(String bookingNumber) {\n this.bookingNumber = bookingNumber;\n }\n\n public LocalDate getBookingFrom() {\n return bookingFrom;\n }\n\n public void setBookingFrom(LocalDate bookingFrom) {\n this.bookingFrom = bookingFrom;\n }\n\n public LocalDate getBookingTo() {\n return bookingTo;\n }\n\n public void setBookingTo(LocalDate bookingTo) {\n this.bookingTo = bookingTo;\n }\n\n public Customer getCustomer() {\n return customer;\n }\n\n public void setCustomer(Customer customer) {\n this.customer = customer;\n }\n\n public BookingStatus getBookingStatus() {\n return bookingStatus;\n }\n\n public void setBookingStatus(BookingStatus bookingStatus) {\n this.bookingStatus = bookingStatus;\n }\n}" }, { "identifier": "BookingStatus", "path": "src/main/java/com/example/application/data/BookingStatus.java", "snippet": "public enum BookingStatus {\n CONFIRMED, COMPLETED, CANCELLED\n}" }, { "identifier": "CarRentalData", "path": "src/main/java/com/example/application/data/CarRentalData.java", "snippet": "public class CarRentalData {\n\n private List<Customer> customers = new ArrayList<>();\n private List<Booking> bookings = new ArrayList<>();\n\n\n public List<Customer> getCustomers() {\n return customers;\n }\n\n public void setCustomers(List<Customer> customers) {\n this.customers = customers;\n }\n\n public List<Booking> getBookings() {\n return bookings;\n }\n\n public void setBookings(List<Booking> bookings) {\n this.bookings = bookings;\n }\n}" }, { "identifier": "Customer", "path": "src/main/java/com/example/application/data/Customer.java", "snippet": "public class Customer {\n\n private String firstName;\n private String lastName;\n\n private List<Booking> bookings = new ArrayList<>();\n\n public Customer() {\n }\n\n public Customer(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public List<Booking> getBookings() {\n return bookings;\n }\n\n public void setBookings(List<Booking> bookings) {\n this.bookings = bookings;\n }\n}" } ]
import com.example.application.data.Booking; import com.example.application.data.BookingStatus; import com.example.application.data.CarRentalData; import com.example.application.data.Customer; import org.eclipse.serializer.reflect.ClassLoaderProvider; import org.eclipse.store.storage.embedded.types.EmbeddedStorage; import org.eclipse.store.storage.embedded.types.EmbeddedStorageManager; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Random;
1,071
package com.example.application.services; @Service public class CarRentalService { private final CarRentalData db; private final EmbeddedStorageManager storeManager; public CarRentalService() { db = new CarRentalData(); storeManager = EmbeddedStorage.Foundation() //Ensure that always the same class loader is used. .onConnectionFoundation(cf -> cf.setClassLoaderProvider(ClassLoaderProvider.New(Thread.currentThread().getContextClassLoader())) ) .start(db); //Start storage, load data if not empty, set db as root if empty. initDemoData(); } private void initDemoData() { List<String> firstNames = List.of("John", "Jane", "Michael", "Sarah", "Robert"); List<String> lastNames = List.of("Doe", "Smith", "Johnson", "Williams", "Taylor"); Random random = new Random(); var customers = new ArrayList<Customer>();
package com.example.application.services; @Service public class CarRentalService { private final CarRentalData db; private final EmbeddedStorageManager storeManager; public CarRentalService() { db = new CarRentalData(); storeManager = EmbeddedStorage.Foundation() //Ensure that always the same class loader is used. .onConnectionFoundation(cf -> cf.setClassLoaderProvider(ClassLoaderProvider.New(Thread.currentThread().getContextClassLoader())) ) .start(db); //Start storage, load data if not empty, set db as root if empty. initDemoData(); } private void initDemoData() { List<String> firstNames = List.of("John", "Jane", "Michael", "Sarah", "Robert"); List<String> lastNames = List.of("Doe", "Smith", "Johnson", "Williams", "Taylor"); Random random = new Random(); var customers = new ArrayList<Customer>();
var bookings = new ArrayList<Booking>();
0
2023-10-11 21:13:42+00:00
2k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/client/NClient.java
[ { "identifier": "SitBypass", "path": "src/main/java/fifthcolumn/n/modules/SitBypass.java", "snippet": "public class SitBypass extends Module {\n public static final Identifier VERSION_CHECK = new Identifier(\"sit\", \"version_check\");\n public static final EntityType<EntityImpl> SIT_ENTITY_TYPE;\n private final SettingGroup sgGeneral;\n public final Setting<Integer> versionSetting;\n\n public SitBypass() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Sit compat\", \"The SIT plugin\");\n this.sgGeneral = this.settings.getDefaultGroup();\n this.versionSetting = this.sgGeneral.add((new IntSetting.Builder()).name(\"version\").description(\"version of sit\").defaultValue(20).max(100).build());\n }\n\n public static void init() {\n EntityRendererRegistry.register(SIT_ENTITY_TYPE, EmptyEntityRenderer::new);\n ClientLoginNetworking.registerGlobalReceiver(VERSION_CHECK, (client, handler, buf, listenerAdder) -> {\n SitBypass sit = Modules.get().get(SitBypass.class);\n PacketByteBuf responseBuf = PacketByteBufs.create();\n responseBuf.writeInt(sit.versionSetting.get());\n return CompletableFuture.completedFuture(responseBuf);\n });\n }\n\n static {\n SIT_ENTITY_TYPE = Registry.register(Registries.ENTITY_TYPE, new Identifier(\"sit\", \"entity_sit\"), FabricEntityTypeBuilder.create(SpawnGroup.MISC, EntityImpl::new).dimensions(EntityDimensions.fixed(0.001F, 0.001F)).build());\n }\n\n private static class EntityImpl extends Entity {\n public EntityImpl(EntityType<?> type, World world) {\n super(type, world);\n }\n\n protected void initDataTracker() {\n }\n\n protected void readCustomDataFromNbt(NbtCompound nbt) {\n }\n\n protected void writeCustomDataToNbt(NbtCompound nbt) {\n }\n }\n}" }, { "identifier": "ModPacketsC2S", "path": "src/main/java/fifthcolumn/n/origins/ModPacketsC2S.java", "snippet": "public class ModPacketsC2S {\n public static void register() {\n ServerLoginConnectionEvents.QUERY_START.register(ModPacketsC2S::handshake);\n }\n\n private static void handshake(ServerLoginNetworkHandler serverLoginNetworkHandler, MinecraftServer minecraftServer, PacketSender packetSender, ServerLoginNetworking.LoginSynchronizer loginSync) {\n if (Modules.get().isActive(OriginsModule.class)) {\n packetSender.sendPacket(ModPackets.HANDSHAKE, PacketByteBufs.empty());\n }\n\n }\n}" }, { "identifier": "ModPacketsS2C", "path": "src/main/java/fifthcolumn/n/origins/ModPacketsS2C.java", "snippet": "public class ModPacketsS2C {\n @Environment(EnvType.CLIENT)\n public static void register() {\n ClientLoginNetworking.registerGlobalReceiver(ModPackets.HANDSHAKE, ModPacketsS2C::handleHandshake);\n }\n\n @Environment(EnvType.CLIENT)\n private static CompletableFuture<PacketByteBuf> handleHandshake(MinecraftClient minecraftClient, ClientLoginNetworkHandler clientLoginNetworkHandler, PacketByteBuf packetByteBuf, Consumer<GenericFutureListener<? extends Future<? super Void>>> genericFutureListenerConsumer) {\n if (!Modules.get().isActive(OriginsModule.class)) {\n return CompletableFuture.failedFuture(new Throwable(\"Origins module needs to be enabled and version set\"));\n } else {\n OriginsModule originsModule = (OriginsModule)Modules.get().get(OriginsModule.class);\n int[] semVer = originsModule.getSemVer();\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeInt(semVer.length);\n\n for (int j : semVer) {\n buf.writeInt(j);\n }\n\n return CompletableFuture.completedFuture(buf);\n }\n }\n}" }, { "identifier": "TMOPacketsC2S", "path": "src/main/java/fifthcolumn/n/origins/TMOPacketsC2S.java", "snippet": "public class TMOPacketsC2S {\n public static void register() {\n ServerLoginConnectionEvents.QUERY_START.register(TMOPacketsC2S::handshake);\n ServerLoginNetworking.registerGlobalReceiver(TMOPackets.HANDSHAKE, (server, handler, understood, buf, synchronizer, responseSender) -> {\n });\n }\n\n private static void handshake(ServerLoginNetworkHandler serverLoginNetworkHandler, MinecraftServer minecraftServer, PacketSender packetSender, ServerLoginNetworking.LoginSynchronizer loginSynchronizer) {\n packetSender.sendPacket(TMOPackets.HANDSHAKE, PacketByteBufs.empty());\n }\n}" }, { "identifier": "TMOPacketsS2C", "path": "src/main/java/fifthcolumn/n/origins/TMOPacketsS2C.java", "snippet": "public class TMOPacketsS2C {\n @Environment(EnvType.CLIENT)\n public static void register() {\n ClientLoginNetworking.registerGlobalReceiver(TMOPackets.HANDSHAKE, TMOPacketsS2C::handleHandshake);\n }\n\n @Environment(EnvType.CLIENT)\n private static CompletableFuture<PacketByteBuf> handleHandshake(MinecraftClient minecraftClient, ClientLoginNetworkHandler clientLoginNetworkHandler, PacketByteBuf packetByteBuf, Consumer<GenericFutureListener<? extends Future<? super Void>>> genericFutureListenerConsumer) {\n if (minecraftClient.isIntegratedServerRunning()) {\n return CompletableFuture.completedFuture(PacketByteBufs.empty());\n } else if (!Modules.get().isActive(OriginsModule.class)) {\n return CompletableFuture.failedFuture(new Throwable(\"Origins module needs to be enabled and version set\"));\n } else {\n OriginsModule originsModule = Modules.get().get(OriginsModule.class);\n int[] semVer = originsModule.getSemVer();\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeInt(semVer.length);\n for (int j : semVer) {\n buf.writeInt(j);\n }\n\n return CompletableFuture.completedFuture(buf);\n }\n }\n}" } ]
import fifthcolumn.n.modules.SitBypass; import fifthcolumn.n.origins.ModPacketsC2S; import fifthcolumn.n.origins.ModPacketsS2C; import fifthcolumn.n.origins.TMOPacketsC2S; import fifthcolumn.n.origins.TMOPacketsS2C; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment;
1,467
package fifthcolumn.n.client; @Environment(EnvType.CLIENT) public class NClient implements ClientModInitializer { public void onInitializeClient() { ModPacketsC2S.register();
package fifthcolumn.n.client; @Environment(EnvType.CLIENT) public class NClient implements ClientModInitializer { public void onInitializeClient() { ModPacketsC2S.register();
ModPacketsS2C.register();
2
2023-10-14 19:18:35+00:00
2k
shenmejianghu/bili-downloader
src/main/java/com/bilibili/downloader/controller/MainController.java
[ { "identifier": "LiveConfig", "path": "src/main/java/com/bilibili/downloader/pojo/LiveConfig.java", "snippet": "public class LiveConfig {\n //推流地址\n private String url;\n private String secret;\n //循环次数,-1表示无限循环\n private Integer loop;\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public Integer getLoop() {\n return loop;\n }\n\n public void setLoop(Integer loop) {\n this.loop = loop;\n }\n\n public String getSecret() {\n return secret;\n }\n\n public void setSecret(String secret) {\n this.secret = secret;\n }\n}" }, { "identifier": "Result", "path": "src/main/java/com/bilibili/downloader/pojo/Result.java", "snippet": "public class Result<T> {\n private int code;\n private String message;\n private T data;\n\n public static <T> Result<T> success(T data){\n return new Result<>(200,\"操作成功\",data);\n }\n public static <T> Result<T> fail(T data,String message){\n return new Result<>(204,message,data);\n }\n\n public Result(int code, String message, T data) {\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public Result() {\n this.code = 200;\n }\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}" }, { "identifier": "HttpFile", "path": "src/main/java/com/bilibili/downloader/util/HttpFile.java", "snippet": "public class HttpFile {\n\n public static void downloadFile(String destFileName, String srcFilePath,\n HttpServletResponse response) {\n downloadFile(\"application/octet-stream\",destFileName,srcFilePath,response);\n }\n\n public static void downloadFile(String contentType,String destFileName, String srcFilePath,\n HttpServletResponse response){\n try {\n destFileName = new String(destFileName.getBytes(), \"ISO8859-1\");\n } catch (UnsupportedEncodingException e) {\n }\n response.addHeader(\"Content-Disposition\", \"attachment; filename=\" + destFileName);\n response.setContentType(contentType);\n try (FileInputStream fis = new FileInputStream(new File(srcFilePath));\n InputStream is = new BufferedInputStream(fis);\n BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {\n\n byte[] buffer = new byte[2048];\n int read = -1;\n while ((read = is.read(buffer)) != -1) {\n bos.write(buffer, 0, read);\n }\n bos.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" } ]
import cn.hutool.core.io.FileUtil; import cn.hutool.crypto.digest.MD5; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSON; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.bilibili.downloader.pojo.LiveConfig; import com.bilibili.downloader.pojo.Result; import com.bilibili.downloader.util.HttpFile; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,239
package com.bilibili.downloader.controller; @Controller public class MainController { private static Logger logger = LoggerFactory.getLogger(MainController.class); @Autowired private RestTemplate restTemplate; @Value("${server.tomcat.basedir}") private String baseDir; @Value("${application.ffmpeg-path}") private String ffmpegPath; @RequestMapping("/download") public void download(HttpServletResponse response, String file){ logger.info("下载视频文件:{}",file); if (StringUtils.isEmpty(file)){ return; } String[] arr = file.split("_"); if (arr.length != 2){ return; } String filePath = baseDir+File.separator+arr[0]+File.separator+arr[1]; if (!FileUtil.exist(filePath)){ return; } HttpFile.downloadFile(arr[1],filePath,response); FileUtil.del(baseDir+File.separator+arr[0]); } @RequestMapping("/parse") @ResponseBody
package com.bilibili.downloader.controller; @Controller public class MainController { private static Logger logger = LoggerFactory.getLogger(MainController.class); @Autowired private RestTemplate restTemplate; @Value("${server.tomcat.basedir}") private String baseDir; @Value("${application.ffmpeg-path}") private String ffmpegPath; @RequestMapping("/download") public void download(HttpServletResponse response, String file){ logger.info("下载视频文件:{}",file); if (StringUtils.isEmpty(file)){ return; } String[] arr = file.split("_"); if (arr.length != 2){ return; } String filePath = baseDir+File.separator+arr[0]+File.separator+arr[1]; if (!FileUtil.exist(filePath)){ return; } HttpFile.downloadFile(arr[1],filePath,response); FileUtil.del(baseDir+File.separator+arr[0]); } @RequestMapping("/parse") @ResponseBody
public Result<String> parse(String url){
1
2023-10-08 01:32:06+00:00
2k
dadegrande99/HikeMap
app/src/main/java/com/usi/hikemap/ui/viewmodel/UserViewModel.java
[ { "identifier": "AuthenticationResponse", "path": "app/src/main/java/com/usi/hikemap/model/AuthenticationResponse.java", "snippet": "public class AuthenticationResponse {\n\n private boolean success;\n private String message;\n\n public AuthenticationResponse() {\n\n }\n\n public boolean isSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @NonNull\n @Override\n public String toString() {\n return \"AuthenticationResponse{\" +\n \"success=\" + success +\n \", message='\" + message + '\\'' +\n '}';\n }\n\n}" }, { "identifier": "IUserRepository", "path": "app/src/main/java/com/usi/hikemap/repository/IUserRepository.java", "snippet": "public interface IUserRepository {\n\n MutableLiveData<AuthenticationResponse> sendSignInLinkToEmail(String auth, ActionCodeSettings actionCodeSettings);\n MutableLiveData<AuthenticationResponse> sendPasswordResetEmail(String auth);\n MutableLiveData<AuthenticationResponse> updatePassword(String password);\n\n}" }, { "identifier": "UserRepository", "path": "app/src/main/java/com/usi/hikemap/repository/UserRepository.java", "snippet": "public class UserRepository implements IUserRepository {\n\n private final FirebaseAuth fAuth;\n private static FirebaseDatabase fDatabase;\n private static DatabaseReference fReference;\n private final Application mApplication;\n\n private final MutableLiveData<AuthenticationResponse> mAuthenticationResponse;\n private static final String TAG = \"UserRepository\";\n private String userId;\n\n public UserRepository(Application application) {\n fAuth = FirebaseAuth.getInstance();\n fDatabase = FirebaseDatabase.getInstance(FIREBASE_DATABASE_URL);\n mApplication = application;\n mAuthenticationResponse = new MutableLiveData<>();\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> sendSignInLinkToEmail(String auth, ActionCodeSettings actionCodeSettings) {\n fAuth.sendSignInLinkToEmail(auth, actionCodeSettings).addOnCompleteListener(new OnCompleteListener<Void>() {\n @Override\n public void onComplete(@NonNull Task<Void> task) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n\n if (task.isSuccessful()) {\n authenticationResponse.setSuccess(true);\n Log.d(TAG, \"onComplete: Send email with links\");\n }\n else {\n authenticationResponse.setMessage(task.getException().getLocalizedMessage());\n Log.d(TAG, \"onComplete: \" + authenticationResponse.getMessage());\n authenticationResponse.setSuccess(false);\n Log.d(TAG, \"onComplete: Don't send email\");\n }\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> sendPasswordResetEmail(String auth) {\n fAuth.sendPasswordResetEmail(auth).addOnCompleteListener(new OnCompleteListener<Void>() {\n @Override\n public void onComplete(@NonNull Task<Void> task) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n\n if (task.isSuccessful()) {\n authenticationResponse.setSuccess(true);\n Log.d(TAG, \"onComplete: Send email with links\");\n }\n else {\n authenticationResponse.setMessage(task.getException().getLocalizedMessage());\n Log.d(TAG, \"onComplete: \" + authenticationResponse.getMessage());\n authenticationResponse.setSuccess(false);\n Log.d(TAG, \"onComplete: Don't send email\");\n }\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> updatePassword(String password) {\n fAuth.getCurrentUser().updatePassword(password).addOnCompleteListener(new OnCompleteListener<Void>() {\n @Override\n public void onComplete(@NonNull Task<Void> task) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n if(task.isSuccessful()){\n authenticationResponse.setSuccess(true);\n Log.d(TAG, \"onComplete: Password update\");\n }\n else {\n authenticationResponse.setSuccess(false);\n Log.d(TAG, \"onComplete: Error password not update\");\n }\n }\n });\n return mAuthenticationResponse;\n }\n\n}" } ]
import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import com.google.firebase.auth.ActionCodeSettings; import com.usi.hikemap.model.AuthenticationResponse; import com.usi.hikemap.repository.IUserRepository; import com.usi.hikemap.repository.UserRepository;
1,063
package com.usi.hikemap.ui.viewmodel; public class UserViewModel extends AndroidViewModel { private MutableLiveData<AuthenticationResponse> mAuthenticationResponse;
package com.usi.hikemap.ui.viewmodel; public class UserViewModel extends AndroidViewModel { private MutableLiveData<AuthenticationResponse> mAuthenticationResponse;
private final IUserRepository mUserRepository;
1
2023-10-09 14:23:22+00:00
2k
xiaoymin/LlmInAction
llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/compoents/VectorStorage.java
[ { "identifier": "EmbeddingResult", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/domain/llm/EmbeddingResult.java", "snippet": "@Getter\n@Setter\npublic class EmbeddingResult {\n\n /**\n * 原始文本内容\n */\n private String prompt;\n /**\n * embedding的处理结果,返回向量化表征的数组,数组长度为1024\n */\n private double[] embedding;\n /**\n * 用户在客户端请求时提交的任务编号或者平台生成的任务编号\n */\n private String requestId;\n /**\n * 智谱AI开放平台生成的任务订单号,调用请求结果接口时请使用此订单号\n */\n private String taskId;\n /**\n * 处理状态,PROCESSING(处理中),SUCCESS(成功),FAIL(失败)\n * 注:处理中状态需通过查询获取结果\n */\n private String taskStatus;\n}" }, { "identifier": "ElasticVectorData", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/domain/store/ElasticVectorData.java", "snippet": "@Data\npublic class ElasticVectorData {\n\n private String chunkId;\n private String content;\n private String docId;\n private double[] vector;\n\n}" } ]
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.map.MapUtil; import com.github.xiaoymin.llm.domain.llm.EmbeddingResult; import com.github.xiaoymin.llm.domain.store.ElasticVectorData; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.ScriptScoreQueryBuilder; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.*; import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.*;
910
package com.github.xiaoymin.llm.compoents; /** * @author <a href="[email protected]">[email protected]</a> * 2023/10/06 12:39 * @since llm_chat_java_hello */ @Slf4j @Component @AllArgsConstructor public class VectorStorage { final ElasticsearchRestTemplate elasticsearchRestTemplate; public String getCollectionName(){ //演示效果使用,固定前缀+日期 return "llm_action_rag_"+ DateUtil.format(Date.from(Instant.now()),"yyyyMMdd"); } /** * 初始化向量数据库index * @param collectionName 名称 * @param dim 维度 */ public boolean initCollection(String collectionName,int dim){ log.info("collection:{}", collectionName); // 查看向量索引是否存在,此方法为固定默认索引字段 IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(collectionName)); if (!indexOperations.exists()) { // 索引不存在,直接创建 log.info("index not exists,create"); //创建es的结构,简化处理 Document document = Document.from(this.elasticMapping(dim)); // 创建 indexOperations.create(new HashMap<>(), document); return true; } return true; } public void store(String collectionName,List<EmbeddingResult> embeddingResults){ //保存向量 log.info("save vector,collection:{},size:{}",collectionName, CollectionUtil.size(embeddingResults)); List<IndexQuery> results = new ArrayList<>(); for (EmbeddingResult embeddingResult : embeddingResults) {
package com.github.xiaoymin.llm.compoents; /** * @author <a href="[email protected]">[email protected]</a> * 2023/10/06 12:39 * @since llm_chat_java_hello */ @Slf4j @Component @AllArgsConstructor public class VectorStorage { final ElasticsearchRestTemplate elasticsearchRestTemplate; public String getCollectionName(){ //演示效果使用,固定前缀+日期 return "llm_action_rag_"+ DateUtil.format(Date.from(Instant.now()),"yyyyMMdd"); } /** * 初始化向量数据库index * @param collectionName 名称 * @param dim 维度 */ public boolean initCollection(String collectionName,int dim){ log.info("collection:{}", collectionName); // 查看向量索引是否存在,此方法为固定默认索引字段 IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(collectionName)); if (!indexOperations.exists()) { // 索引不存在,直接创建 log.info("index not exists,create"); //创建es的结构,简化处理 Document document = Document.from(this.elasticMapping(dim)); // 创建 indexOperations.create(new HashMap<>(), document); return true; } return true; } public void store(String collectionName,List<EmbeddingResult> embeddingResults){ //保存向量 log.info("save vector,collection:{},size:{}",collectionName, CollectionUtil.size(embeddingResults)); List<IndexQuery> results = new ArrayList<>(); for (EmbeddingResult embeddingResult : embeddingResults) {
ElasticVectorData ele = new ElasticVectorData();
1
2023-10-10 23:25:33+00:00
2k
zyyzyykk/kkTerminal
terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Utils/FileUtil.java
[ { "identifier": "FileBlockStateEnum", "path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Constants/Enum/FileBlockStateEnum.java", "snippet": "public enum FileBlockStateEnum {\n\n FILE_UPLOADING(202,\"文件后台上传中\"),\n\n CHUNK_UPLOAD_SUCCESS(203,\"文件片上传成功\"),\n\n UPLOAD_ERROR(502,\"文件片上传失败\"),\n\n UPLOAD_CHUNK_LOST(503,\"文件片缺失\"),\n\n UPLOAD_SIZE_DIFF(504,\"上传文件大小不一致\"),\n\n SSH_NOT_EXIST(602,\"ssh连接断开\");\n\n private Integer state;\n\n private String desc;\n\n FileBlockStateEnum(Integer state, String desc) {\n this.state = state;\n this.desc = desc;\n }\n\n public static FileBlockStateEnum getByState(Integer state) {\n for (FileBlockStateEnum item : FileBlockStateEnum.values()) {\n if (item.getState().equals(state)) {\n return item;\n }\n }\n return null;\n }\n\n public Integer getState() {\n return state;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n}" }, { "identifier": "MyException", "path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/GlobalExceptionHandler/MyException.java", "snippet": "@Data\npublic class MyException extends RuntimeException{\n\n private Result result;\n\n public MyException(String message){\n super(message);\n }\n}" }, { "identifier": "Result", "path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Result/Result.java", "snippet": "@Component\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n // 状态\n private String status;\n\n // 响应码\n private Integer code;\n\n // 状态信息\n private String info;\n\n // 返回数据\n private String data;\n\n // 失败返回\n public static Result setFail(Integer code, String info)\n {\n Result result = new Result();\n result.setStatus(\"warning\");\n result.setCode(code);\n result.setInfo(info);\n result.setData(null);\n\n return result;\n }\n\n // 成功返回\n public static Result setSuccess(Integer code, String info, Map<String,Object> data) {\n Result result = new Result();\n result.setStatus(\"success\");\n result.setCode(code);\n result.setInfo(info);\n try {\n if(null == data) result.setData(null);\n else result.setData(AesUtil.aesEncrypt(JSON.toJSONString(data)));\n } catch (Exception e) {\n System.out.println(\"加密异常\");\n result.setData(null);\n }\n\n return result;\n }\n\n // 错误返回\n public static Result setError(Integer code,String info)\n {\n Result result = new Result();\n result.setStatus(\"error\");\n result.setCode(code);\n result.setInfo(info);\n result.setData(null);\n\n return result;\n }\n\n\n public static Result setError(Integer code, String info, Map<String,Object> data) {\n Result result = new Result();\n result.setStatus(\"error\");\n result.setCode(code);\n result.setInfo(info);\n try {\n if(null == data) result.setData(null);\n else result.setData(AesUtil.aesEncrypt(JSON.toJSONString(data)));\n } catch (Exception e) {\n System.out.println(\"加密异常\");\n result.setData(null);\n }\n\n return result;\n }\n\n\n}" } ]
import com.kkbpro.terminal.Constants.Enum.FileBlockStateEnum; import com.kkbpro.terminal.GlobalExceptionHandler.MyException; import com.kkbpro.terminal.Result.Result; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
1,184
package com.kkbpro.terminal.Utils; public class FileUtil { public static final String folderBasePath = System.getProperty("user.dir") + "/src/main/resources/static/file"; /** * 文件片合并 */ public static void fileChunkMerge(String folderPath, String fileName, Integer chunks, Long totalSize) { File folder = new File(folderPath); // 获取暂存切片文件的文件夹中的所有文件 File[] files = folder.listFiles(); // 合并的文件 File finalFile = new File(folderPath + "/" + fileName); InputStream inputStream = null; OutputStream outputStream = null; try { outputStream = new FileOutputStream(finalFile, true); List<File> list = new ArrayList<>(); for (File file : files) { // 判断是否是文件对应的文件片 if (StringUtil.isFileChunk(file.getName(),chunks,fileName)) { list.add(file); } } // 如果服务器上的切片数量和前端给的数量不匹配 if (chunks != list.size()) { MyException myException = new MyException("文件片缺失");
package com.kkbpro.terminal.Utils; public class FileUtil { public static final String folderBasePath = System.getProperty("user.dir") + "/src/main/resources/static/file"; /** * 文件片合并 */ public static void fileChunkMerge(String folderPath, String fileName, Integer chunks, Long totalSize) { File folder = new File(folderPath); // 获取暂存切片文件的文件夹中的所有文件 File[] files = folder.listFiles(); // 合并的文件 File finalFile = new File(folderPath + "/" + fileName); InputStream inputStream = null; OutputStream outputStream = null; try { outputStream = new FileOutputStream(finalFile, true); List<File> list = new ArrayList<>(); for (File file : files) { // 判断是否是文件对应的文件片 if (StringUtil.isFileChunk(file.getName(),chunks,fileName)) { list.add(file); } } // 如果服务器上的切片数量和前端给的数量不匹配 if (chunks != list.size()) { MyException myException = new MyException("文件片缺失");
myException.setResult(Result.setError(FileBlockStateEnum.UPLOAD_CHUNK_LOST.getState(), "文件片缺失"));
2
2023-10-14 08:05:24+00:00
2k
f3n1b00t/car-design-patterns
src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/factory/manufacturer/FordFactory.java
[ { "identifier": "Coupe", "path": "src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/car/Coupe.java", "snippet": "public class Coupe extends Car {\n public Coupe(String chassis, String body, String paint, String interior) {\n super(chassis, body, paint, interior);\n }\n\n @Override\n public String toString() {\n return \"Coupe(\" +\n \"chassis=\" + getChassis() +\n \", body=\" + getBody() +\n \", paint=\" + getPaint() +\n \", interior=\" + getInterior() +\n ')';\n }\n}" }, { "identifier": "Sedan", "path": "src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/car/Sedan.java", "snippet": "public class Sedan extends Car {\n public Sedan(String chassis, String body, String paint, String interior) {\n super(chassis, body, paint, interior);\n }\n\n @Override\n public String toString() {\n return \"Sedan(\" +\n \"chassis=\" + getChassis() +\n \", body=\" + getBody() +\n \", paint=\" + getPaint() +\n \", interior=\" + getInterior() +\n ')';\n }\n}" }, { "identifier": "FordCoupe", "path": "src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/car/manufacturer/ford/FordCoupe.java", "snippet": "public class FordCoupe extends Coupe {\n public FordCoupe(String chassis, String body, String paint, String interior) {\n super(chassis, body, paint, interior);\n }\n\n @Override\n public String toString() {\n return \"FordCoupe(\" +\n \"chassis=\" + getChassis() +\n \", body=\" + getBody() +\n \", paint=\" + getPaint() +\n \", interior=\" + getInterior() +\n ')';\n }\n}" }, { "identifier": "FordSedan", "path": "src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/car/manufacturer/ford/FordSedan.java", "snippet": "public class FordSedan extends Sedan {\n public FordSedan(String chassis, String body, String paint, String interior) {\n super(chassis, body, paint, interior);\n }\n\n @Override\n public String toString() {\n return \"FordSedan(\" +\n \"chassis=\" + getChassis() +\n \", body=\" + getBody() +\n \", paint=\" + getPaint() +\n \", interior=\" + getInterior() +\n ')';\n }\n}" }, { "identifier": "CarFactory", "path": "src/main/java/ru/f3n1b00t/designpatterns/creational/abstractfactory/factory/CarFactory.java", "snippet": "public interface CarFactory {\n Sedan createSedan(String chassis, String body, String paint, String interior);\n Coupe createCoupe(String chassis, String body, String paint, String interior);\n}" } ]
import ru.f3n1b00t.designpatterns.creational.abstractfactory.car.Coupe; import ru.f3n1b00t.designpatterns.creational.abstractfactory.car.Sedan; import ru.f3n1b00t.designpatterns.creational.abstractfactory.car.manufacturer.ford.FordCoupe; import ru.f3n1b00t.designpatterns.creational.abstractfactory.car.manufacturer.ford.FordSedan; import ru.f3n1b00t.designpatterns.creational.abstractfactory.factory.CarFactory;
864
package ru.f3n1b00t.designpatterns.creational.abstractfactory.factory.manufacturer; public class FordFactory implements CarFactory { @Override public Sedan createSedan(String chassis, String body, String paint, String interior) {
package ru.f3n1b00t.designpatterns.creational.abstractfactory.factory.manufacturer; public class FordFactory implements CarFactory { @Override public Sedan createSedan(String chassis, String body, String paint, String interior) {
return new FordSedan(chassis, body, paint, interior);
3
2023-10-09 18:35:29+00:00
2k
howiefh/expression-engine-benchmark
src/main/java/io/github/howiefh/BaseBenchmark.java
[ { "identifier": "ExpressionEngine", "path": "src/main/java/io/github/howiefh/expression/ExpressionEngine.java", "snippet": "public interface ExpressionEngine {\n /**\n * 类型\n * @return {@link String}\n */\n String getType();\n\n /**\n * 执行表达式\n *\n * @param expressionString 表达式\n * @param param 数据\n * @return 表达式的值\n */\n Object execute(String expressionString, Map<String, Object> param);\n\n}" }, { "identifier": "ExpressionEngineFactory", "path": "src/main/java/io/github/howiefh/expression/ExpressionEngineFactory.java", "snippet": "public class ExpressionEngineFactory {\n public static final String MVEL = MVELExpressionEngine.MVEL_ENGINE;\n public static final String AVIATOR = AviatorExpressionEngine.AVIATOR_ENGINE;\n public static final String QL_EXPRESS = QLExpressExpressionEngine.QL_EXPRESS_ENGINE;\n public static final String SP_EL = SpElExpressionEngine.SP_EL_ENGINE;\n public static final String OGNL = OGNLExpressionEngine.OGNL_ENGINE;\n public static final String JEXL = JEXLExpressionEngine.JEXL_ENGINE;\n public static final String JUEL = JUELExpressionEngine.JUEL_ENGINE;\n public static final String JANINO = JaninoExpressionEngine.JANINO_ENGINE;\n\n public static final Set<String> ALL = new LinkedHashSet<>();\n static {\n ALL.add(MVEL);\n ALL.add(AVIATOR);\n ALL.add(QL_EXPRESS);\n ALL.add(SP_EL);\n ALL.add(OGNL);\n ALL.add(JEXL);\n ALL.add(JUEL);\n ALL.add(JANINO);\n }\n\n public static ExpressionEngine create(String type) {\n switch (type) {\n case MVEL:\n return new MVELExpressionEngine();\n case AVIATOR:\n return new AviatorExpressionEngine();\n case QL_EXPRESS:\n return new QLExpressExpressionEngine();\n case SP_EL:\n return new SpElExpressionEngine();\n case OGNL:\n return new OGNLExpressionEngine();\n case JEXL:\n return new JEXLExpressionEngine();\n case JUEL:\n return new JUELExpressionEngine();\n case JANINO:\n return new JaninoExpressionEngine();\n default:\n throw new IllegalArgumentException(\"不存在 \" + type);\n }\n }\n}" } ]
import io.github.howiefh.expression.ExpressionEngine; import io.github.howiefh.expression.ExpressionEngineFactory; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.ChainedOptionsBuilder; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit;
1,012
/* * @(#)BaseBenchmark 1.0 2023/9/12 * * Copyright 2023 Feng Hao. * * 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 * * https://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.howiefh; /** * @author fenghao * @version 1.0 * @since 1.0 */ @BenchmarkMode({Mode.AverageTime}) @Warmup(iterations = 1, time = 5) @Measurement(iterations = 10, time = 5) @Fork(1) @State(value = Scope.Benchmark) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class BaseBenchmark { public static void run(String filename, String...includes) throws RunnerException { ChainedOptionsBuilder optionsBuilder = new OptionsBuilder() .result(filename) .resultFormat(ResultFormatType.JSON); for (String reg : includes) { optionsBuilder.include(reg); } Options opt = optionsBuilder.build(); new Runner(opt).run(); } @State(Scope.Benchmark) public static class BenchmarkData {
/* * @(#)BaseBenchmark 1.0 2023/9/12 * * Copyright 2023 Feng Hao. * * 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 * * https://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.howiefh; /** * @author fenghao * @version 1.0 * @since 1.0 */ @BenchmarkMode({Mode.AverageTime}) @Warmup(iterations = 1, time = 5) @Measurement(iterations = 10, time = 5) @Fork(1) @State(value = Scope.Benchmark) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class BaseBenchmark { public static void run(String filename, String...includes) throws RunnerException { ChainedOptionsBuilder optionsBuilder = new OptionsBuilder() .result(filename) .resultFormat(ResultFormatType.JSON); for (String reg : includes) { optionsBuilder.include(reg); } Options opt = optionsBuilder.build(); new Runner(opt).run(); } @State(Scope.Benchmark) public static class BenchmarkData {
public ExpressionEngine mvel = ExpressionEngineFactory.create(ExpressionEngineFactory.MVEL);
1
2023-10-08 03:50:21+00:00
2k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/config/Config.java
[ { "identifier": "Project", "path": "src/main/java/zju/cst/aces/api/Project.java", "snippet": "public interface Project {\n Project getParent();\n File getBasedir();\n /**\n * Get the project packaging type.\n */\n String getPackaging();\n String getGroupId();\n String getArtifactId();\n List<String> getCompileSourceRoots();\n Path getArtifactPath();\n Path getBuildPath();\n\n}" }, { "identifier": "Validator", "path": "src/main/java/zju/cst/aces/api/Validator.java", "snippet": "public interface Validator {\n\n boolean syntacticValidate(String code);\n boolean semanticValidate(String code, String className, Path outputPath, PromptInfo promptInfo);\n boolean runtimeValidate(String fullTestName);\n public boolean compile(String className, Path outputPath, PromptInfo promptInfo);\n public TestExecutionSummary execute(String fullTestName);\n}" }, { "identifier": "LoggerImpl", "path": "src/main/java/zju/cst/aces/api/impl/LoggerImpl.java", "snippet": "public class LoggerImpl implements zju.cst.aces.api.Logger {\n\n java.util.logging.Logger log;\n\n public LoggerImpl() {\n this.log = java.util.logging.Logger.getLogger(\"ChatUniTest\");\n Handler consoleHandler = new ConsoleHandler();\n consoleHandler.setLevel(Level.ALL);\n consoleHandler.setFormatter(new LogFormatter());\n this.log.addHandler(consoleHandler);\n this.log.setUseParentHandlers(false);\n }\n\n @Override\n public void info(String msg) {\n log.info(msg);\n }\n\n @Override\n public void warn(String msg) {\n log.warning(msg);\n }\n\n @Override\n public void error(String msg) {\n log.severe(msg);\n }\n\n @Override\n public void debug(String msg) {\n log.config(msg);\n }\n}" }, { "identifier": "Logger", "path": "src/main/java/zju/cst/aces/api/Logger.java", "snippet": "public interface Logger {\n\n void info(String msg);\n void warn(String msg);\n void error(String msg);\n void debug(String msg);\n}" }, { "identifier": "ValidatorImpl", "path": "src/main/java/zju/cst/aces/api/impl/ValidatorImpl.java", "snippet": "@Data\npublic class ValidatorImpl implements Validator {\n\n TestCompiler compiler;\n\n public ValidatorImpl(Path testOutputPath, Path compileOutputPath, Path targetPath, List<String> classpathElements) {\n this.compiler = new TestCompiler(testOutputPath, compileOutputPath, targetPath, classpathElements);\n }\n\n @Override\n public boolean syntacticValidate(String code) {\n try {\n StaticJavaParser.parse(code);\n return true;\n } catch (ParseProblemException e) {\n return false;\n }\n }\n\n @Override\n public boolean semanticValidate(String code, String className, Path outputPath, PromptInfo promptInfo) {\n compiler.setCode(code);\n return compiler.compileTest(className, outputPath, promptInfo);\n }\n\n @Override\n public boolean runtimeValidate(String fullTestName) {\n return compiler.executeTest(fullTestName).getTestsFailedCount() == 0;\n }\n\n @Override\n public boolean compile(String className, Path outputPath, PromptInfo promptInfo) {\n return compiler.compileTest(className, outputPath, promptInfo);\n }\n\n @Override\n public TestExecutionSummary execute(String fullTestName) {\n return compiler.executeTest(fullTestName);\n }\n}" } ]
import zju.cst.aces.api.Project; import com.github.javaparser.JavaParser; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Getter; import lombok.Setter; import okhttp3.OkHttpClient; import zju.cst.aces.api.Validator; import zju.cst.aces.api.impl.LoggerImpl; import zju.cst.aces.api.Logger; import zju.cst.aces.api.impl.ValidatorImpl; import java.io.File; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
1,053
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys;
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys;
public Logger log;
3
2023-10-14 07:15:10+00:00
2k
Nyayurn/Yutori-QQ
src/main/java/io/github/nyayurn/yutori/qq/event/message/MessageEvent.java
[ { "identifier": "Channel", "path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Channel.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Channel {\n /**\n * 群聊: 群号\n * 私聊: QQ 号\n */\n private String id;\n\n /**\n * 群聊: 0\n * 私聊: 3\n */\n private Integer type;\n\n /**\n * 群聊: 群名称\n * 私聊: null\n */\n private String name;\n\n public static Channel parse(EventEntity event) {\n return new Channel(event.getChannel().getId(), event.getChannel().getType(), event.getChannel().getName());\n }\n}" }, { "identifier": "Message", "path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Message.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Message {\n /**\n * 消息 ID\n */\n private String id;\n\n /**\n * 消息内容\n */\n private String content;\n\n public static Message parse(EventEntity event) {\n return new Message(event.getMessage().getId(), event.getMessage().getContent());\n }\n}" }, { "identifier": "BaseMessageElement", "path": "src/main/java/io/github/nyayurn/yutori/qq/message/element/BaseMessageElement.java", "snippet": "public abstract class BaseMessageElement extends io.github.nyayurn.yutori.message.element.BaseMessageElement {}" }, { "identifier": "User", "path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/User.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class User {\n /**\n * QQ 号\n */\n private String id;\n\n /**\n * 昵称\n */\n private String name;\n\n /**\n * 头像\n */\n private String avatar;\n\n /**\n * 是否为机器人(null 表示未知)\n */\n private Boolean isBot;\n\n public static User parse(EventEntity event) {\n return new User(event.getUser().getId(), event.getUser().getName(), event.getUser().getAvatar(), event.getUser().getIsBot());\n }\n}" }, { "identifier": "UserEvent", "path": "src/main/java/io/github/nyayurn/yutori/qq/event/UserEvent.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class UserEvent extends Event {\n /**\n * 用户信息\n */\n private User user;\n\n public UserEvent(Integer id, Long timestamp, User user) {\n super(id, timestamp);\n this.user = user;\n }\n\n public void setUser(String name, String id, String avatar, Boolean isBot) {\n this.user = new User(name, id, avatar, isBot);\n }\n\n}" } ]
import io.github.nyayurn.yutori.qq.entity.event.Channel; import io.github.nyayurn.yutori.qq.entity.event.Message; import io.github.nyayurn.yutori.qq.message.element.BaseMessageElement; import io.github.nyayurn.yutori.qq.entity.event.User; import io.github.nyayurn.yutori.qq.event.UserEvent; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List;
965
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.event.message; /** * @author Yurn */ @EqualsAndHashCode(callSuper = true) @Data @NoArgsConstructor public class MessageEvent extends UserEvent { /** * 消息信息 */
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.event.message; /** * @author Yurn */ @EqualsAndHashCode(callSuper = true) @Data @NoArgsConstructor public class MessageEvent extends UserEvent { /** * 消息信息 */
protected Message message;
1
2023-10-12 09:58:07+00:00
2k
jmdevall/opencodeplan
src/test/java/jmdevall/opencodeplan/adapter/out/repository/RepositoryMulpleFoldersTest.java
[ { "identifier": "TestingUtil", "path": "src/test/java/jmdevall/opencodeplan/adapter/out/javaparser/util/TestingUtil.java", "snippet": "public class TestingUtil {\n\t\n\tpublic String readFileFromTestSource(String filepath) {\n\t\tFile file=getSrcTestFile(filepath);\n\t\tInputStream is;\n\t\ttry {\n\t\t\tis = new FileInputStream(file);\n\t\t\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(is));\n\t\treturn reader.lines().collect(Collectors.joining(System.lineSeparator()));\n\t\t} catch (FileNotFoundException e) {\n\t\t\tfail();\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic File getSrcTestFile(String filepath) {\n\t\treturn new File(this.getSrcRootTestFolder().getAbsolutePath()+filepath);\n\t}\n\t\n\tpublic File getSrcRootTestFolder() {\n\t\tFile srcTestRoot = new File(\"src/test/java\");\n\t\tif(!srcTestRoot.exists()) {\n\t\t\tthrow new IllegalStateException(\"testing folder of source test bench not exists!!!\");\n\t\t}\n\t\treturn srcTestRoot;\n\t}\n\t\n\tpublic SourceFolder getSrcTestSourceFolder() {\n\t\treturn new SourceFolder(getSrcRootTestFolder(),FiltersFactory.defaultJavaExtensionFilter(),true);\n\t}\n\n\tpublic Repository getTestingRepository(String startfolder) {\n\t\treturn\n\t\t\t\tRepositoryMulpleFolders.newFromSingleSourceRoot(getSrcRootTestFolder(),\n\t\t\t\t(int level, String path, File file)->path.startsWith(startfolder));\n\t}\n\t\n\tpublic JavaParser getTestingJavaParser() {\n\t\treturn JavaParserFactory.newDefaultJavaParser(Arrays.asList(getSrcTestSourceFolder()));\n\t}\n\t\n\n}" }, { "identifier": "CuSource", "path": "src/main/java/jmdevall/opencodeplan/application/port/out/repository/CuSource.java", "snippet": "public interface CuSource {\n\n\tString getSource(String path);\n\n\tCollection<String> getPaths();\n\n}" }, { "identifier": "SourceFolder", "path": "src/main/java/jmdevall/opencodeplan/application/port/out/repository/SourceFolder.java", "snippet": "@AllArgsConstructor\n@Getter\npublic class SourceFolder {\n\tprivate File sourceRoot;\n\tprivate Filter filter;\n\tboolean testSource;\n}" } ]
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import org.junit.jupiter.api.Test; import jmdevall.opencodeplan.adapter.out.javaparser.util.TestingUtil; import jmdevall.opencodeplan.application.port.out.repository.CuSource; import jmdevall.opencodeplan.application.port.out.repository.SourceFolder; import lombok.extern.slf4j.Slf4j;
1,033
package jmdevall.opencodeplan.adapter.out.repository; @Slf4j public class RepositoryMulpleFoldersTest { @Test public void canSaveContentOfFile() throws Exception{ File srcRoot = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir = srcRoot.getAbsolutePath(); log.debug("temp folder="+tmpdir); RepositoryMulpleFolders sut=RepositoryMulpleFolders.newFromSingleSourceRoot(srcRoot); String filepath = "/foo/bar/Foo.java"; sut.save(filepath, "content1"); String readcontent = new String(Files.readAllBytes(Paths.get(tmpdir+filepath))); assertEquals("content1",readcontent); sut.save(filepath, "content2"); String other = new String(Files.readAllBytes(Paths.get(tmpdir+filepath))); assertEquals("content2",other); } @Test public void multiplesFolders() throws Exception{ File srcRoot1 = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir1 = srcRoot1.getAbsolutePath(); log.debug("temp folder 1="+tmpdir1); File srcRoot2 = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir2 = srcRoot2.getAbsolutePath(); log.debug("temp folder 2="+tmpdir2); SourceFolder sf1=new SourceFolder(srcRoot1,FiltersFactory.defaultJavaExtensionFilter(),false); SourceFolder sf2=new SourceFolder(srcRoot2,FiltersFactory.defaultJavaExtensionFilter(),true); RepositorySingleFolder onlySf2=new RepositorySingleFolder(sf2); onlySf2.save("/test.java", "untest"); RepositoryMulpleFolders sut=RepositoryMulpleFolders.newRepositoryMultipleFolders( Arrays.asList(sf1,sf2)); String source=sut.getCuSource().getSource("/test.java"); assertNotNull(source); assertEquals("untest",source); }
package jmdevall.opencodeplan.adapter.out.repository; @Slf4j public class RepositoryMulpleFoldersTest { @Test public void canSaveContentOfFile() throws Exception{ File srcRoot = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir = srcRoot.getAbsolutePath(); log.debug("temp folder="+tmpdir); RepositoryMulpleFolders sut=RepositoryMulpleFolders.newFromSingleSourceRoot(srcRoot); String filepath = "/foo/bar/Foo.java"; sut.save(filepath, "content1"); String readcontent = new String(Files.readAllBytes(Paths.get(tmpdir+filepath))); assertEquals("content1",readcontent); sut.save(filepath, "content2"); String other = new String(Files.readAllBytes(Paths.get(tmpdir+filepath))); assertEquals("content2",other); } @Test public void multiplesFolders() throws Exception{ File srcRoot1 = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir1 = srcRoot1.getAbsolutePath(); log.debug("temp folder 1="+tmpdir1); File srcRoot2 = Files.createTempDirectory("openCodePlanTestFileRespository").toFile(); String tmpdir2 = srcRoot2.getAbsolutePath(); log.debug("temp folder 2="+tmpdir2); SourceFolder sf1=new SourceFolder(srcRoot1,FiltersFactory.defaultJavaExtensionFilter(),false); SourceFolder sf2=new SourceFolder(srcRoot2,FiltersFactory.defaultJavaExtensionFilter(),true); RepositorySingleFolder onlySf2=new RepositorySingleFolder(sf2); onlySf2.save("/test.java", "untest"); RepositoryMulpleFolders sut=RepositoryMulpleFolders.newRepositoryMultipleFolders( Arrays.asList(sf1,sf2)); String source=sut.getCuSource().getSource("/test.java"); assertNotNull(source); assertEquals("untest",source); }
TestingUtil testUtil=new TestingUtil();
0
2023-10-14 18:27:18+00:00
2k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/parser/JsonDocParser.java
[ { "identifier": "Ops", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenApiListApi.java", "snippet": "@Getter\nclass Ops {\n\n static final JsonObject empty = new JsonObject();\n\n private JsonElement insert = JsonNull.INSTANCE;\n private JsonObject attributes = empty;\n\n public String getId() {\n final JsonElement insert = this.insert;\n if (insert.isJsonPrimitive()) {\n final String id = insert.getAsString();\n if (StringUtils.isNotBlank(id)) {\n return id;\n }\n } else {\n final JsonElement idElement = insert.getAsJsonObject().get(\"id\");\n\n if (idElement != null) {\n final String id = idElement.getAsString();\n if (StringUtils.isNotBlank(id)) {\n return id;\n }\n }\n }\n\n return attributes.get(\"zoneId\").getAsString();\n }\n\n public boolean isBold() {\n final JsonObject attributes = this.attributes;\n return attributes.has(\"bold\") && attributes.get(\"bold\").getAsBoolean();\n }\n\n public boolean isHeading() {\n final JsonObject attributes = this.attributes;\n return attributes.has(\"heading\");\n }\n\n public boolean isList() {\n final JsonObject attributes = this.attributes;\n return attributes.has(\"list\");\n }\n\n public boolean isTable() {\n final JsonObject attributes = this.attributes;\n return attributes.has(\"aceTable\");\n }\n\n public String getDataId() {\n final JsonObject attributes = this.attributes;\n return !isTable() ? \"\" : attributes.get(\"aceTable\").getAsString().split(\" \")[0];\n }\n\n public String getColumnWidthId() {\n final JsonObject attributes = this.attributes;\n return !isTable() ? \"\" : attributes.get(\"aceTable\").getAsString().split(\" \")[1];\n }\n\n}" }, { "identifier": "OpsList", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenApiListApi.java", "snippet": "@Getter\nclass OpsList {\n private List<Ops> ops;\n\n private String zoneId;\n\n public String getColumnId() {\n final String zoneId = this.zoneId;\n final int index = zoneId.lastIndexOf('x');\n if (index == -1) {\n return zoneId;\n }\n\n return zoneId.substring(index + 1);\n }\n\n private String zoneType;\n}" } ]
import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenApiListApi.Ops; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenApiListApi.OpsList; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import j2html.TagCreator; import j2html.tags.DomContent; import j2html.tags.specialized.TableTag; import lombok.AllArgsConstructor; import org.apache.commons.collections4.map.DefaultedMap; import org.apache.commons.lang3.StringUtils; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List;
908
/* * Copyright 2023 [email protected] * * 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 com.github.eahau.openapi.douyin.generator.parser; @AllArgsConstructor public class JsonDocParser {
/* * Copyright 2023 [email protected] * * 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 com.github.eahau.openapi.douyin.generator.parser; @AllArgsConstructor public class JsonDocParser {
private final Map<String, OpsList> opsListMap;
1
2023-10-07 09:09:15+00:00
2k
knowledgefactory4u/registration-login-spring-boot-security6-thymeleaf
registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/service/impl/UserServiceImpl.java
[ { "identifier": "UserRegistrationDto", "path": "registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/dto/UserRegistrationDto.java", "snippet": "public class UserRegistrationDto {\r\n\r\n private String firstName;\r\n private String lastName;\r\n private String email;\r\n private String password;\r\n\r\n public UserRegistrationDto() {\r\n\r\n }\r\n\r\n public String getFirstName() {\r\n return firstName;\r\n }\r\n\r\n public void setFirstName(String firstName) {\r\n this.firstName = firstName;\r\n }\r\n\r\n public String getLastName() {\r\n return lastName;\r\n }\r\n\r\n public void setLastName(String lastName) {\r\n this.lastName = lastName;\r\n }\r\n\r\n public String getEmail() {\r\n return email;\r\n }\r\n\r\n public void setEmail(String email) {\r\n this.email = email;\r\n }\r\n\r\n public String getPassword() {\r\n return password;\r\n }\r\n\r\n public void setPassword(String password) {\r\n this.password = password;\r\n }\r\n}" }, { "identifier": "Role", "path": "registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/entity/Role.java", "snippet": "@Entity\r\n@Table(name = \"role\")\r\npublic class Role {\r\n\r\n @Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n private String name;\r\n\r\n public Role() {\r\n\r\n }\r\n\r\n public Role(String name) {\r\n super();\r\n this.name = name;\r\n }\r\n\r\n public Long getId() {\r\n return id;\r\n }\r\n\r\n public void setId(Long id) {\r\n this.id = id;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public void setName(String name) {\r\n this.name = name;\r\n }\r\n}" }, { "identifier": "User", "path": "registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/entity/User.java", "snippet": "@Entity\r\n@Table(name = \"my_user\", uniqueConstraints =\r\n @UniqueConstraint(columnNames = \"email\"))\r\npublic class User {\r\n\r\n @Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n\r\n @Column(name = \"first_name\")\r\n private String firstName;\r\n\r\n @Column(name = \"last_name\")\r\n private String lastName;\r\n\r\n private String email;\r\n\r\n private String password;\r\n\r\n @ManyToMany(fetch = FetchType.EAGER, \r\n cascade = CascadeType.ALL)\r\n @JoinTable(name = \"users_roles\", \r\n joinColumns = @JoinColumn(name = \"user_id\", \r\n referencedColumnName = \"id\"), \r\n inverseJoinColumns = @JoinColumn\r\n (name = \"role_id\", \r\n referencedColumnName = \"id\"))\r\n private Collection<Role> roles;\r\n\r\n public User() {\r\n\r\n }\r\n\r\n public User(String firstName, String lastName, \r\n String email, String password, \r\n Collection<Role> roles) {\r\n \r\n this.firstName = firstName;\r\n this.lastName = lastName;\r\n this.email = email;\r\n this.password = password;\r\n this.roles = roles;\r\n }\r\n\r\n public Long getId() {\r\n return id;\r\n }\r\n\r\n public void setId(Long id) {\r\n this.id = id;\r\n }\r\n\r\n public String getFirstName() {\r\n return firstName;\r\n }\r\n\r\n public void setFirstName(String firstName) {\r\n this.firstName = firstName;\r\n }\r\n\r\n public String getLastName() {\r\n return lastName;\r\n }\r\n\r\n public void setLastName(String lastName) {\r\n this.lastName = lastName;\r\n }\r\n\r\n public String getEmail() {\r\n return email;\r\n }\r\n\r\n public void setEmail(String email) {\r\n this.email = email;\r\n }\r\n\r\n public String getPassword() {\r\n return password;\r\n }\r\n\r\n public void setPassword(String password) {\r\n this.password = password;\r\n }\r\n\r\n public Collection<Role> getRoles() {\r\n return roles;\r\n }\r\n\r\n public void setRoles(Collection<Role> roles) {\r\n this.roles = roles;\r\n }\r\n}" }, { "identifier": "UserRepository", "path": "registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/repository/UserRepository.java", "snippet": "public interface UserRepository extends JpaRepository<User, Long> {\r\n \r\n User findByEmail(String email);\r\n}" }, { "identifier": "UserService", "path": "registration-login-spring-boot-security6-thymeleaf/src/main/java/com/knf/dev/demo/service/UserService.java", "snippet": "public interface UserService extends UserDetailsService {\r\n \r\n User save(UserRegistrationDto registrationDto);\r\n List<User> getAll();\r\n}" } ]
import com.knf.dev.demo.dto.UserRegistrationDto; import com.knf.dev.demo.entity.Role; import com.knf.dev.demo.entity.User; import com.knf.dev.demo.repository.UserRepository; import com.knf.dev.demo.service.UserService; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors;
1,246
package com.knf.dev.demo.service.impl; @Service public class UserServiceImpl implements UserService {
package com.knf.dev.demo.service.impl; @Service public class UserServiceImpl implements UserService {
private UserRepository userRepository;
3
2023-10-14 17:09:44+00:00
2k
rimmelasghar/Automation-Testing
src/main/java/org/example/SwagsLabsTesting/pages/Login.java
[ { "identifier": "Params", "path": "src/main/java/org/example/Labs/Params.java", "snippet": "public class Params {\n // Parameters for SwagsLab Website.\n public static WebDriver driver;\n public static int waitTime = 5;\n public static String projectPath = System.getProperty(\"user.dir\");\n public static String userName = \"standard_user\";\n public static String userPassword = \"secret_sauce\";\n public static String checkoutUserFirstName = \"Rimmel\";\n public static String checkoutUserLastName = \"Asghar\";\n public static String checkoutPostalCode = \"45372\";\n public static String urlPath = \"https://www.saucedemo.com/\";\n public static String expectedTitle = \"Swag Labs\";\n public static String userNameIdentifier = \"user-name\";\n public static String userPasswordIdentifier = \"password\";\n public static String loginBtnIdentifier = \"login-button\";\n public static String productIdentifier = \"//span[@class='title']\";\n public static String expectedProductResults = \"Products\";\n\n public static void waitForTime(int ms) throws Exception {\n Thread.sleep(ms);\n }\n\n public static void getDriverSession() {\n System.setProperty(\"webdriver.chrome.driver\", projectPath + \"/src/main/resources/chromedriver.exe\");\n driver = new ChromeDriver();\n driver.manage().window().maximize();\n }\n public static void navigateToUrl(String url) {\n driver.get(url);\n }\n public static void verifyTitle() {\n String actualTitle = driver.getTitle();\n try {\n if (actualTitle.equals(expectedTitle)) {\n System.out.println(\"Test Passed --> \");\n } else {\n System.out.println(\"Test Unsuccessfull -->\");\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n public static void enterText(String identifier,String testData) throws Exception{\n try {\n WebElement element = driver.findElement(By.name(identifier));\n element.sendKeys(testData);\n } catch (Exception ex){\n ex.printStackTrace();\n }\n }\n public static void clickElement(String identifier) throws Exception{\n try{\n WebElement element = driver.findElement(By.id(identifier));\n element.click();\n } catch (Exception e){\n e.printStackTrace();\n }\n }\n public static void closeAndQuitDriverSession(){\n driver.close();\n driver.quit();\n }\n public static void verifyElementExpectedText(String identifier,String expectedText) throws Exception{\n try{\n WebElement element = driver.findElement(By.xpath(identifier));\n String actualText = element.getText();\n if (actualText.equals(expectedText)){\n System.out.println(\"Test Passed -->\");\n } else {\n System.out.println(\"Test Failed\");\n }\n } catch (Exception e){\n e.printStackTrace();\n }\n }\n public static void main(String[] args) throws Exception {\n // <--- WorkFlow:: --->\n getDriverSession();\n navigateToUrl(urlPath);\n waitForTime(3);\n verifyTitle();\n enterText(userNameIdentifier,userName);\n enterText(userPasswordIdentifier,userPassword);\n clickElement(loginBtnIdentifier);\n waitForTime(3);\n verifyElementExpectedText(productIdentifier,expectedProductResults);\n closeAndQuitDriverSession();\n }\n}" }, { "identifier": "Method", "path": "src/main/java/org/example/Methods/Method.java", "snippet": "public class Method {\n public static WebDriver driver;\n public static WebDriverWait wait;\n public Method(WebDriver driver,WebDriverWait webDriverWait){\n this.driver = driver;\n this.wait = webDriverWait;\n }\n public static void navigateToUrl(String url){\n driver.get(url);\n }\n public static void verifyTitle(String expectedTitle){\n String actualTitle = driver.getTitle();\n assert expectedTitle.equals(actualTitle);\n System.out.println(\"Verified\");\n }\n public static void enterText(String identifier,String inputText){\n WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(identifier)));\n element.sendKeys(inputText);\n }\n public static void clickElement(String identifier){\n WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(identifier)));\n element.click();\n }\n public static void closeSession(){\n driver.quit();\n }\n public static void verifyExpectedText(String identifier,String expectedText){\n WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(identifier)));\n String actualText = element.getText();\n assert expectedText.equals(actualText);\n }\n}" }, { "identifier": "SwagsLabParams", "path": "src/main/java/org/example/SwagsLabsTesting/SwagsLabParams.java", "snippet": "public class SwagsLabParams {\n public static int waitTime = 5;\n public static String browser = \"FIREFOX\";\n public static String userName = \"standard_user\";\n public static String userPassword = \"secret_sauce\";\n public static String urlPath = \"https://www.saucedemo.com/\";\n public static String expectedTitle = \"Swag Labs\";\n public static String userNameIdentifier = \"//*[@name='user-name']\";\n public static String userPasswordIdentifier = \"//*[@name='password']\";\n public static String loginBtnIdentifier = \"//input[@id='login-button']\";\n public static String productIdentifier = \"//span[@class='title']\";\n public static String expectedProductResults = \"Products\";\n}" } ]
import org.example.Labs.Params; import org.example.Methods.Method; import org.example.SwagsLabsTesting.SwagsLabParams; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait;
1,304
package org.example.SwagsLabsTesting.pages; public class Login { public static SwagsLabParams params= new SwagsLabParams();
package org.example.SwagsLabsTesting.pages; public class Login { public static SwagsLabParams params= new SwagsLabParams();
public static Method method;
1
2023-10-11 10:39:25+00:00
2k
quarkiverse/quarkus-mailpit
deployment/src/main/java/io/quarkiverse/mailpit/deployment/devui/MailpitDevUIProcessor.java
[ { "identifier": "MailpitContainer", "path": "deployment/src/main/java/io/quarkiverse/mailpit/deployment/MailpitContainer.java", "snippet": "public final class MailpitContainer extends GenericContainer<MailpitContainer> {\n\n public static final String CONFIG_SMTP_PORT = MailpitProcessor.FEATURE + \".smtp.port\";\n public static final String CONFIG_HTTP_SERVER = MailpitProcessor.FEATURE + \".http.server\";\n\n /**\n * Logger which will be used to capture container STDOUT and STDERR.\n */\n private static final Logger log = Logger.getLogger(MailpitContainer.class);\n /**\n * Default Mailpit SMTP Port.\n */\n private static final Integer PORT_SMTP = 1025;\n /**\n * Default Mailpit HTTP Port for UI.\n */\n private static final Integer PORT_HTTP = 8025;\n /**\n * Runtime mail port from either \"quarkus.mailer.port\" or 1025 if not found\n */\n private final Integer runtimeMailPort;\n /**\n * Flag whether to use shared networking\n */\n private final boolean useSharedNetwork;\n /**\n * The dynamic host name determined from TestContainers.\n */\n private String hostName;\n\n MailpitContainer(MailpitConfig config, boolean useSharedNetwork) {\n super(DockerImageName.parse(config.imageName()).asCompatibleSubstituteFor(MailpitConfig.DEFAULT_IMAGE));\n this.runtimeMailPort = getMailPort();\n this.useSharedNetwork = useSharedNetwork;\n\n super.withLabel(MailpitProcessor.DEV_SERVICE_LABEL, MailpitProcessor.FEATURE);\n super.withNetwork(Network.SHARED);\n super.waitingFor(Wait.forHttp(\"/\").forPort(PORT_HTTP));\n\n // configure verbose container logging\n if (config.verbose()) {\n super.withEnv(\"MP_VERBOSE\", \"true\");\n }\n\n // forward the container logs\n super.withLogConsumer(new JbossContainerLogConsumer(log).withPrefix(MailpitProcessor.FEATURE));\n }\n\n @Override\n protected void configure() {\n super.configure();\n\n if (useSharedNetwork) {\n hostName = ConfigureUtil.configureSharedNetwork(this, MailpitProcessor.FEATURE);\n return;\n }\n\n // this forces the SMTP port to match what the user has configured for quarkus.mailer.port\n addFixedExposedPort(this.runtimeMailPort, PORT_SMTP);\n // this forces the HTTP port so the DevUI doesn't break on every change\n addFixedExposedPort(PORT_HTTP, PORT_HTTP);\n }\n\n /**\n * Info about the DevService used in the DevUI.\n *\n * @return the map of as running configuration of the dev service\n */\n public Map<String, String> getExposedConfig() {\n Map<String, String> exposed = new HashMap<>(2);\n exposed.put(CONFIG_SMTP_PORT, Objects.toString(getMailPort()));\n exposed.put(CONFIG_HTTP_SERVER, getMailpitHttpServer());\n exposed.putAll(super.getEnvMap());\n return exposed;\n }\n\n /**\n * Get the calculated Mailpit UI location for use in the DevUI.\n *\n * @return the calculated full URL to the Mailpit UI\n */\n public String getMailpitHttpServer() {\n return String.format(\"http://%s:%d\", getMailpitHost(), getMappedPort(PORT_HTTP));\n }\n\n /**\n * Get the calculated Mailpit host address.\n *\n * @return the host address\n */\n public String getMailpitHost() {\n if (hostName != null && !hostName.isEmpty()) {\n return hostName;\n } else {\n return getHost();\n }\n }\n\n /**\n * Use \"quarkus.mailer.port\" to configure Mailpit as its exposed SMTP port.\n *\n * @return the mailer port or -1 if not found which will cause this service not to start\n */\n public static Integer getMailPort() {\n // first try default port\n int port = ConfigProvider.getConfig().getOptionalValue(\"quarkus.mailer.port\",\n Integer.class).orElse(-1);\n\n // if not found search through named mailers until we find one\n if (port == -1) {\n // check for all configs\n for (String key : ConfigProvider.getConfig().getPropertyNames()) {\n if (key.contains(\"quarkus.mailer.\") && key.endsWith(\"port\")) {\n port = ConfigProvider.getConfig().getOptionalValue(key, Integer.class).orElse(-1);\n if (port >= 0) {\n break;\n }\n }\n }\n }\n return port;\n }\n}" }, { "identifier": "MailpitDevServicesConfigBuildItem", "path": "deployment/src/main/java/io/quarkiverse/mailpit/deployment/MailpitDevServicesConfigBuildItem.java", "snippet": "public final class MailpitDevServicesConfigBuildItem extends SimpleBuildItem {\n\n private final Map<String, String> config;\n\n public MailpitDevServicesConfigBuildItem(Map<String, String> config) {\n this.config = config;\n }\n\n public Map<String, String> getConfig() {\n return config;\n }\n\n}" } ]
import java.util.Map; import java.util.Optional; import io.quarkiverse.mailpit.deployment.MailpitContainer; import io.quarkiverse.mailpit.deployment.MailpitDevServicesConfigBuildItem; import io.quarkus.deployment.IsDevelopment; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.devui.spi.page.CardPageBuildItem; import io.quarkus.devui.spi.page.FooterPageBuildItem; import io.quarkus.devui.spi.page.Page; import io.quarkus.devui.spi.page.PageBuilder; import io.quarkus.devui.spi.page.WebComponentPageBuilder;
1,486
package io.quarkiverse.mailpit.deployment.devui; /** * Dev UI card for displaying important details such Mailpit embedded UI. */ public class MailpitDevUIProcessor { @BuildStep(onlyIf = IsDevelopment.class) void createVersion(BuildProducer<CardPageBuildItem> cardPageBuildItemBuildProducer, Optional<MailpitDevServicesConfigBuildItem> configProps, BuildProducer<FooterPageBuildItem> footerProducer) { if (configProps.isPresent()) { Map<String, String> config = configProps.get().getConfig(); final CardPageBuildItem card = new CardPageBuildItem(); // SMTP
package io.quarkiverse.mailpit.deployment.devui; /** * Dev UI card for displaying important details such Mailpit embedded UI. */ public class MailpitDevUIProcessor { @BuildStep(onlyIf = IsDevelopment.class) void createVersion(BuildProducer<CardPageBuildItem> cardPageBuildItemBuildProducer, Optional<MailpitDevServicesConfigBuildItem> configProps, BuildProducer<FooterPageBuildItem> footerProducer) { if (configProps.isPresent()) { Map<String, String> config = configProps.get().getConfig(); final CardPageBuildItem card = new CardPageBuildItem(); // SMTP
if (config.containsKey(MailpitContainer.CONFIG_SMTP_PORT)) {
0
2023-10-13 18:20:34+00:00
2k
QRXqrx/fuzz-mut-demos
mutest-demo/src/main/java/edu/nju/mutest/DemoSrcMutationEngine.java
[ { "identifier": "Mutator", "path": "mutest-demo/src/main/java/edu/nju/mutest/mutator/Mutator.java", "snippet": "public interface Mutator {\n\n /**\n * Find the positions that could be mutated by this mutator.\n */\n void locateMutationPoints();\n\n /**\n * Mutate the original program, which is represented with {@link CompilationUnit},\n * and get a list of mutated programs.\n *\n * @return a list of compilation units mutated from the original one.\n */\n List<CompilationUnit> mutate();\n\n}" }, { "identifier": "BinaryMutator", "path": "mutest-demo/src/main/java/edu/nju/mutest/mutator/BinaryMutator.java", "snippet": "public class BinaryMutator extends AbstractMutator {\n\n private List<BinaryExpr> mutPoints = null;\n private List<CompilationUnit> mutants = new NodeList<>();\n\n private BinaryExpr.Operator[] targetOps = {\n PLUS, MINUS, MULTIPLY, DIVIDE\n };\n\n public BinaryMutator(CompilationUnit cu) {\n super(cu);\n }\n\n @Override\n public void locateMutationPoints() {\n mutPoints = BinaryExprCollector.collect(this.origCU);\n }\n\n @Override\n public List<CompilationUnit> mutate() {\n\n // Sanity check.\n if (this.mutPoints == null)\n throw new RuntimeException(\"You must locate mutation points first!\");\n\n // Modify each mutation points.\n for (BinaryExpr mp : mutPoints) {\n // This is a polluted operation. So we preserve the original\n // operator for recovering.\n BinaryExpr.Operator origOp = mp.getOperator();\n\n // Generate simple mutation. Each mutant contains only one\n // mutated point.\n for (BinaryExpr.Operator targetOp : targetOps) {\n // Skip self\n if (origOp.equals(targetOp))\n continue;\n // Mutate\n mutants.add(mutateOnce(mp, targetOp));\n }\n\n // Recovering\n mp.setOperator(origOp);\n\n }\n\n return this.mutants;\n }\n\n /**\n * Replace the operator with a given one\n */\n private CompilationUnit mutateOnce(BinaryExpr mp, BinaryExpr.Operator op) {\n mp.setOperator(op);\n // Now the CU is a mutated one. Return its clone.\n return this.origCU.clone();\n }\n\n public List<CompilationUnit> getMutants() {\n if (mutants.isEmpty())\n System.out.println(\"Oops, seems no mutation has been conducted yet. Call mutate() first!\");\n return mutants;\n }\n}" } ]
import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.PackageDeclaration; import edu.nju.mutest.mutator.Mutator; import org.apache.commons.io.FileUtils; import edu.nju.mutest.mutator.BinaryMutator; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import java.util.Optional;
891
package edu.nju.mutest; /** * Demo source-level mutation engine using javaparser. */ public class DemoSrcMutationEngine { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("DemoSrcMutationEngine: <source_java_file> <mutant_pool_dir>"); System.exit(0); } // Read in original program(s). File srcFile = new File(args[0]); File outDir = new File(args[1]); System.out.println("[LOG] Source file: " + srcFile.getAbsolutePath()); System.out.println("[LOG] Output dir: " + outDir.getAbsolutePath()); // Initialize mutator(s). CompilationUnit cu = StaticJavaParser.parse(srcFile);
package edu.nju.mutest; /** * Demo source-level mutation engine using javaparser. */ public class DemoSrcMutationEngine { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("DemoSrcMutationEngine: <source_java_file> <mutant_pool_dir>"); System.exit(0); } // Read in original program(s). File srcFile = new File(args[0]); File outDir = new File(args[1]); System.out.println("[LOG] Source file: " + srcFile.getAbsolutePath()); System.out.println("[LOG] Output dir: " + outDir.getAbsolutePath()); // Initialize mutator(s). CompilationUnit cu = StaticJavaParser.parse(srcFile);
Mutator mutator = new BinaryMutator(cu);
0
2023-10-13 06:36:47+00:00
2k
Aywen1/wispy
src/fr/nicolas/wispy/Panels/MenuPanel.java
[ { "identifier": "MainFrame", "path": "src/fr/nicolas/wispy/Frames/MainFrame.java", "snippet": "public class MainFrame extends JFrame {\n\n\tprivate WPanel panel;\n\tpublic static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720;\n\n\tpublic MainFrame() {\n\t\tthis.setTitle(\"Wispy\");\n\t\tthis.setSize(INIT_WIDTH, INIT_HEIGHT);\n\t\tthis.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT));\n\t\tthis.setLocationRelativeTo(null);\n\t\tthis.setResizable(true);\n\t\tthis.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tpanel = new MenuPanel(this.getBounds(), this);\n\n\t\tthis.addComponentListener(new ComponentListener() {\n\t\t\tpublic void componentResized(ComponentEvent e) {\n\t\t\t\tpanel.setFrameBounds(getBounds());\n\t\t\t}\n\n\t\t\tpublic void componentHidden(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentMoved(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentShown(ComponentEvent e) {\n\t\t\t}\n\t\t});\n\n\t\tthis.setContentPane(panel);\n\n\t\tthis.setVisible(true);\n\t}\n\n\tpublic void newGame() {\n\t\tpanel = new GamePanel(this.getBounds(), true);\n\t\tthis.setContentPane(panel);\n\t\tthis.validate();\n\t\tpanel.requestFocus();\n\t}\n\n}" }, { "identifier": "WButton", "path": "src/fr/nicolas/wispy/Panels/Components/Menu/WButton.java", "snippet": "public class WButton extends JPanel {\n\tprivate BufferedImage icon, iconHovered;\n\tprivate Rectangle button;\n\tprivate boolean isHovered = false;\n\tprivate String text;\n\tprivate int size = 40;\n\n\tpublic WButton(String text, Rectangle bounds) {\n\t\tthis.text = text;\n\t\tbutton = bounds;\n\t\tloadImages(\"default\");\n\t}\n\n\tpublic WButton(String text, String iconName, Rectangle bounds) {\n\t\tbutton = bounds;\n\t\tloadImages(iconName);\n\t}\n\n\tprivate void loadImages(String iconName) {\n\t\ttry {\n\t\t\ticon = ImageIO.read(getClass().getResource(\"res/buttons/\" + iconName + \".png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\ticonHovered = ImageIO.read(getClass().getResource(\"res/buttons/\" + iconName + \"Hovered.png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic boolean mouseClick(Point mouseLocation) {\n\t\tif (button.contains(mouseLocation)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean mouseClick(Point mouseLocation, boolean isRightClick) {\n\t\tif (isRightClick) {\n\t\t\tif (button.contains(mouseLocation)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tif (button.contains(mouseLocation)) {\n\t\t\tisHovered = true;\n\t\t} else {\n\t\t\tisHovered = false;\n\t\t}\n\t}\n\n\tpublic void setHovered(boolean isHovered) {\n\t\tthis.isHovered = isHovered;\n\t}\n\n\tpublic void changeBounds(Rectangle bounds) {\n\t\tbutton = bounds;\n\t\tthis.setBounds(bounds);\n\t}\n\t\n\tpublic void reSize(int newSize) {\n\t\tthis.size = newSize;\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tif (isHovered) {\n\t\t\tg.drawImage(iconHovered, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\t} else {\n\t\t\tg.drawImage(icon, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\t}\n\t\t\n\t\tg.setColor(new Color(255, 255, 255, 180));\n\t\tg.setFont(new Font(\"Arial\", Font.PLAIN, size));\n\t\tg.drawString(text, this.getWidth() / 2 - g.getFontMetrics().stringWidth(text)/2, this.getHeight() / 2 +2*size/6);\n\t}\n}" }, { "identifier": "WPanel", "path": "src/fr/nicolas/wispy/Panels/Components/Menu/WPanel.java", "snippet": "public abstract class WPanel extends JPanel {\n\n\tprotected Rectangle frameBounds;\n\n\tpublic WPanel(Rectangle frameBounds) {\n\t\tthis.frameBounds = frameBounds;\n\t}\n\n\tpublic void setFrameBounds(Rectangle frameBounds) {\n\n\t}\n\n}" } ]
import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import fr.nicolas.wispy.Frames.MainFrame; import fr.nicolas.wispy.Panels.Components.Menu.WButton; import fr.nicolas.wispy.Panels.Components.Menu.WPanel;
1,213
package fr.nicolas.wispy.Panels; public class MenuPanel extends WPanel implements MouseListener, MouseMotionListener { private BufferedImage bg, title; private Point mouseLocation = new Point(0, 0);
package fr.nicolas.wispy.Panels; public class MenuPanel extends WPanel implements MouseListener, MouseMotionListener { private BufferedImage bg, title; private Point mouseLocation = new Point(0, 0);
private WButton buttonStart, buttonSettings, buttonQuit;
1
2023-10-13 13:10:56+00:00
2k
PfauMC/CyanWorld
cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/menus/coding/PlayerAction/PlayerActionSettings.java
[ { "identifier": "CustomMenu", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/api/CustomMenu.java", "snippet": "public abstract class CustomMenu implements InventoryHolder {\n public final Inventory inventory;\n public final ItemStack GLASS = new CustomItem(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 11), \"\", \"glass\");\n public final ItemStack AIR = new ItemStack(Material.AIR);\n\n public CustomMenu(Server server, int rows, String title) {\n this.inventory = server.createInventory(this, rows * 9, title);\n }\n\n public Inventory getInventory() {\n return this.inventory;\n }\n\n public abstract void onClick(InventoryClickEvent var1);\n}" }, { "identifier": "ItemBuilder", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/api/ItemBuilder.java", "snippet": "public class ItemBuilder {\n public ItemStack itemStack;\n public ItemMeta itemMeta;\n\n public ItemBuilder(ItemStack itemStack) {\n this.itemStack = itemStack;\n this.itemMeta = itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material) {\n this.itemStack = new ItemStack(material);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material, int amount) {\n this.itemStack = new ItemStack(material, amount);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material, int amount, int dura) {\n new ItemBuilder(material, amount, (short) dura);\n }\n\n public ItemBuilder(Material material, int amount, short dura) {\n this.itemStack = new ItemStack(material, amount, dura);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder name(String name) {\n this.itemMeta.setDisplayName(name != null ? \"\\u00a7f\" + name : null);\n return this;\n }\n\n public ItemBuilder locname(String locname) {\n this.itemMeta.setLocalizedName(locname);\n return this;\n }\n\n public ItemBuilder amount(int amount) {\n this.itemStack.setAmount(amount);\n return this;\n }\n\n public ItemBuilder dura(int dura) {\n return this.dura((short) dura);\n }\n\n public ItemBuilder dura(short dura) {\n this.itemStack.setDurability(dura);\n return this;\n }\n\n public ItemBuilder lore(List<String> lore) {\n this.itemMeta.setLore(lore);\n return this;\n }\n\n public ItemBuilder unbreakable(boolean unbreakable) {\n this.itemMeta.setUnbreakable(unbreakable);\n return this;\n }\n\n public ItemBuilder enchant(Enchantment enchant, int lvl) {\n this.itemStack.addUnsafeEnchantment(enchant, lvl);\n return this;\n }\n\n public /* varargs */ ItemBuilder itemflag(ItemFlag... itemFlags) {\n this.itemMeta.addItemFlags(itemFlags);\n return this;\n }\n\n public ItemStack build() {\n this.itemStack.setItemMeta(this.itemMeta);\n return this.itemStack;\n }\n}" }, { "identifier": "server", "path": "cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/CyanUniverse.java", "snippet": "public static Server server;" } ]
import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import ru.cyanworld.cyan1dex.api.CustomMenu; import ru.cyanworld.cyan1dex.api.ItemBuilder; import static ru.cyanworld.cyanuniverse.CyanUniverse.server;
948
package ru.cyanworld.cyanuniverse.menus.coding.PlayerAction; public class PlayerActionSettings extends CustomMenu { public Sign sign; public PlayerActionSettings(Sign sign) {
package ru.cyanworld.cyanuniverse.menus.coding.PlayerAction; public class PlayerActionSettings extends CustomMenu { public Sign sign; public PlayerActionSettings(Sign sign) {
super(server, 3, "Сделать игроку - Настройки");
2
2023-10-08 17:50:55+00:00
2k
Aywen1/improvident
src/fr/nicolas/main/panels/NLeftBar.java
[ { "identifier": "NCategory", "path": "src/fr/nicolas/main/components/NCategory.java", "snippet": "public class NCategory extends JPanel {\n\n\tprivate Rectangle category;\n\tprivate BufferedImage img;\n\tprivate boolean isHovered = false;\n\n\tpublic NCategory(String name, int y) {\n\t\tcategory = new Rectangle();\n\t\tcategory.setBounds(10, 38 + y * 40, 35, 28);\n\n\t\ttry {\n\t\t\timg = ImageIO.read(new File(\"res/categoriesIcons/\" + name.toLowerCase() + \".png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic boolean mouseClick(Point mouseLocation) {\n\t\tif (category.contains(mouseLocation)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tif (category.contains(mouseLocation)) {\n\t\t\tisHovered = true;\n\t\t} else {\n\t\t\tisHovered = false;\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.drawImage(img, 0, 0, getWidth() - 7, getHeight(), null);\n\n\t\tif (isHovered) {\n\t\t\tg.setColor(new Color(255, 255, 255, 150));\n\t\t\tg.drawLine(getWidth() - 1, 0, getWidth() - 1, getHeight());\n\t\t}\n\t}\n\n}" }, { "identifier": "MainFrame", "path": "src/fr/nicolas/main/frames/MainFrame.java", "snippet": "public class MainFrame extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n\tprivate NBackground bg;\n\tprivate NLeftBar leftBar;\n\tprivate NTitle titlePanel;\n\tprivate NBase base;\n\tprivate String[] categories = { \"Accueil\", \"Cours écrits\", \"Cours vidéos\", \"Compréhension écrite\",\n\t\t\t\"Compréhension orale\", \"Points\", \"Paramètres\" };\n\n\tprivate Point mouseLocation = new Point(0, 0);\n\n\tpublic MainFrame(Point location) {\n\t\tString path = \"Improvident/Categories/\";\n\t\tif (!(new File(path).exists())) {\n\t\t\tfor (int i = 1; i < categories.length; i++) {\n\t\t\t\tnew File(path + categories[i]).mkdirs();\n\t\t\t\tif (categories[i] != \"Points\" && categories[i] != \"Paramètres\") {\n\t\t\t\t\tnewFile(path + categories[i] + \"/À faire\", false);\n\t\t\t\t\tnewFile(path + categories[i] + \"/À revoir\", false);\n\t\t\t\t\tnewFile(path + categories[i] + \"/Archivés\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewFile(\"Improvident/Categories/Points/points\", true);\n\t\t}\n\n\t\tthis.setTitle(\"Improvident\");\n\t\tthis.setSize(800, 500);\n\t\tthis.setLocationRelativeTo(null);\n\t\tthis.setResizable(false);\n\t\tthis.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tthis.setIconImage(new ImageIcon(\"res/icon.png\").getImage());\n\t\tthis.setLocation(location);\n\n\t\tthis.addMouseListener(this);\n\t\tthis.addMouseMotionListener(this);\n\t\tthis.addMouseWheelListener(this);\n\t\tthis.setFocusable(true);\n\n\t\tinit();\n\n\t\tthis.setVisible(true);\n\t}\n\n\tprivate void newFile(String path, boolean valueTo0) {\n\t\ttry {\n\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(path)));\n\t\t\tif (valueTo0) {\n\t\t\t\tbufferedWriter.write(\"0\");\n\t\t\t} else {\n\t\t\t\tbufferedWriter.write(\"\");\n\t\t\t}\n\t\t\tbufferedWriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate void init() {\n\t\tbg = new NBackground(0);\n\t\tleftBar = new NLeftBar(categories, this);\n\t\ttitlePanel = new NTitle(this);\n\t\tbase = new NBase(this);\n\n\t\tthis.setContentPane(bg);\n\n\t\tbg.add(leftBar);\n\t\tbg.add(titlePanel);\n\t\tbg.add(base);\n\n\t\tleftBar.setBounds(0, 0, 42, getHeight());\n\t\ttitlePanel.setBounds(42, 0, getWidth(), 60);\n\t\tbase.setBounds(42, 60, getWidth(), getHeight());\n\t}\n\n\tpublic NTitle getTitlePanel() {\n\t\treturn titlePanel;\n\t}\n\n\tpublic NBase getBase() {\n\t\treturn base;\n\t}\n\n\t// MouseListener\n\n\tpublic void mouseClicked(MouseEvent e) {\n\t}\n\n\tpublic void mouseEntered(MouseEvent e) {\n\t}\n\n\tpublic void mouseExited(MouseEvent e) {\n\t}\n\n\tpublic void mousePressed(MouseEvent e) {\n\t}\n\n\tpublic void mouseReleased(MouseEvent e) {\n\t\tif (e.getButton() == MouseEvent.BUTTON1) {\n\n\t\t\tleftBar.mouseClick(mouseLocation);\n\t\t\tbase.mouseClick(mouseLocation, false);\n\t\t\ttitlePanel.mouseClick(mouseLocation);\n\n\t\t} else if (e.getButton() == MouseEvent.BUTTON2) {\n\t\t\tbase.mouseClick(mouseLocation, true);\n\t\t}\n\n\t\tbg.repaint();\n\t}\n\n\t// MouseMotionListener\n\n\tpublic void mouseDragged(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tleftBar.mouseMove(mouseLocation);\n\t\tbase.mouseMove(mouseLocation);\n\n\t\tbg.repaint();\n\t}\n\n\tpublic void mouseMoved(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tleftBar.mouseMove(mouseLocation);\n\t\tbase.mouseMove(mouseLocation);\n\t\ttitlePanel.mouseMove(mouseLocation);\n\n\t\tbg.repaint();\n\t}\n\n\t// MouseWheelListener\n\n\tpublic void mouseWheelMoved(MouseWheelEvent e) {\n\t\tleftBar.mouseWheelMoved(mouseLocation, e.getWheelRotation());\n\n\t\tbg.repaint();\n\t}\n\n}" } ]
import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JPanel; import fr.nicolas.main.components.NCategory; import fr.nicolas.main.frames.MainFrame;
1,470
package fr.nicolas.main.panels; public class NLeftBar extends JPanel { private MainFrame mainFrame; private String[] categoriesName;
package fr.nicolas.main.panels; public class NLeftBar extends JPanel { private MainFrame mainFrame; private String[] categoriesName;
private NCategory[] categories;
0
2023-10-13 10:30:31+00:00
2k
Mon-L/virtual-waiting-room
virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/mq/MqGatewayGatewayImpl.java
[ { "identifier": "WaitingRoomException", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/exception/WaitingRoomException.java", "snippet": "@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)\npublic class WaitingRoomException extends RuntimeException {\n\n public static Throwable getCause(Object[] argArray) {\n if (argArray == null || argArray.length == 0) {\n return null;\n }\n\n final Object lastEntry = argArray[argArray.length - 1];\n if (lastEntry instanceof Throwable) {\n return (Throwable) lastEntry;\n }\n\n return null;\n }\n\n public WaitingRoomException(String msg) {\n super(msg);\n }\n\n public WaitingRoomException(String msg, Throwable t) {\n super(msg, t);\n }\n\n public WaitingRoomException(String pattern, Object... args) {\n super(MessageFormatter.arrayFormat(pattern, args).getMessage(), getCause(args));\n }\n}" }, { "identifier": "MqGateway", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/gateway/mq/MqGateway.java", "snippet": "public interface MqGateway {\n String TOPIC_ASSIGN_POS = \"assign-pos\";\n\n void sendAssignRequest(AssignRequestIdEvent assignRequestIdEvent);\n}" }, { "identifier": "AssignRequestIdEvent", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/model/event/AssignRequestIdEvent.java", "snippet": "public class AssignRequestIdEvent {\n private String queueId;\n private String requestId;\n private Date sendTime;\n\n public AssignRequestIdEvent() {}\n\n public AssignRequestIdEvent(String queueId, String requestId, Date sendTime) {\n this.queueId = queueId;\n this.requestId = requestId;\n this.sendTime = sendTime;\n }\n\n public String getQueueId() {\n return queueId;\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n public Date getSendTime() {\n return sendTime;\n }\n}" } ]
import cn.zcn.virtual.waiting.room.domain.exception.WaitingRoomException; import cn.zcn.virtual.waiting.room.domain.gateway.mq.MqGateway; import cn.zcn.virtual.waiting.room.domain.model.event.AssignRequestIdEvent; import javax.annotation.Resource; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.stereotype.Component;
819
/* * 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 cn.zcn.virtual.waiting.room.infrastructure.mq; /** * @author zicung */ @Component public class MqGatewayGatewayImpl implements MqGateway { @Resource private RocketMQTemplate rocketMQTemplate; @Override
/* * 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 cn.zcn.virtual.waiting.room.infrastructure.mq; /** * @author zicung */ @Component public class MqGatewayGatewayImpl implements MqGateway { @Resource private RocketMQTemplate rocketMQTemplate; @Override
public void sendAssignRequest(AssignRequestIdEvent assignRequestIdEvent) {
2
2023-10-07 10:31:42+00:00
2k
ferderplays/ElypsaClient
src/main/java/net/elypsaclient/modules/combat/CrystalAura.java
[ { "identifier": "Module", "path": "src/main/java/net/elypsaclient/modules/Module.java", "snippet": "public class Module {\n public String name, description;\n public int keyChar;\n public ModuleCateg category;\n public boolean toggled;\n\n protected Minecraft mc = Minecraft.getMinecraft();\n public Module(String name, String description, ModuleCateg category) {\n super();\n this.name = name;\n this.description = description;\n this.category = category;\n this.toggled = false;\n }\n\n public String getName() {\n return name;\n }\n\n public ModuleCateg getCategory() {\n return category;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public int getKeyChar() {\n return keyChar;\n }\n\n public void setKeyChar(int keyChar) {\n this.keyChar = keyChar;\n }\n\n public boolean isToggled() {\n return toggled;\n }\n\n public void setToggled(boolean toggled) {\n this.toggled = toggled;\n }\n\n public void enable() {\n this.toggled = !this.toggled;\n if (this.toggled) onEnable();\n else onDisable();\n }\n\n public void onEnable() {\n MinecraftForge.EVENT_BUS.register(this);\n modAction();\n }\n\n public void modAction() {\n }\n\n public void onDisable() {\n MinecraftForge.EVENT_BUS.unregister(this);\n modActionEnd();\n }\n\n public void modActionEnd() {\n\n }\n}" }, { "identifier": "ModuleCateg", "path": "src/main/java/net/elypsaclient/modules/ModuleCateg.java", "snippet": "public enum ModuleCateg {\n MOVEMENT(\"Movement\"), PLAYER(\"Player\"), RENDER(\"Render\"), CLIENT(\"Client\"), COMBAT(\"Combat\");\n\n public String name;\n public int moduleIndex;\n ModuleCateg(String name) {\n this.name = name;\n }\n}" }, { "identifier": "TimerUtil", "path": "src/main/java/net/elypsaclient/utils/TimerUtil.java", "snippet": "public class TimerUtil {\n public long lastMilliSecond = System.currentTimeMillis();\n public void resetTimer() {\n lastMilliSecond = System.currentTimeMillis();\n }\n\n public boolean hasTimePassed(long time, boolean reset) {\n if (System.currentTimeMillis() - lastMilliSecond > time) {\n if (reset) resetTimer();\n return true;\n }\n return false;\n }\n}" } ]
import net.elypsaclient.modules.Module; import net.elypsaclient.modules.ModuleCateg; import net.elypsaclient.utils.TimerUtil; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.input.Keyboard;
724
package net.elypsaclient.modules.combat; public class CrystalAura extends Module { public TimerUtil timer = new TimerUtil(); public CrystalAura() {
package net.elypsaclient.modules.combat; public class CrystalAura extends Module { public TimerUtil timer = new TimerUtil(); public CrystalAura() {
super("Crystal Aura", "attacks end crystals", ModuleCateg.COMBAT);
1
2023-10-10 18:11:26+00:00
2k
openGemini/opengemini-client-java
opengemini-client-jdk/src/main/java/io/opengemini/client/jdk/OpenGeminiJdkClient.java
[ { "identifier": "Address", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/Address.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Address {\n /**\n * Host service ip or domain.\n */\n private String host;\n /**\n * Port exposed service port.\n */\n private int port;\n}" }, { "identifier": "OpenGeminiException", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/OpenGeminiException.java", "snippet": "public class OpenGeminiException extends Exception {\n private static final int DEFAULT_STATUS_CODE = 500;\n\n private final int statusCode;\n\n public OpenGeminiException(Throwable t) {\n super(t);\n statusCode = DEFAULT_STATUS_CODE;\n }\n\n public OpenGeminiException(String message) {\n this(message, DEFAULT_STATUS_CODE);\n }\n\n public OpenGeminiException(String message, int statusCode) {\n super(message);\n this.statusCode = statusCode;\n }\n}" }, { "identifier": "Query", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/Query.java", "snippet": "@AllArgsConstructor\n@Getter\n@Setter\npublic class Query {\n /*\n * the query command\n */\n private String command;\n\n /*\n * the database name of the query command using\n */\n private String database;\n\n /*\n * the rp name of the query command using\n */\n private String retentionPolicy;\n\n public Query(String command){\n this.command = command;\n };\n}" }, { "identifier": "QueryResult", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/QueryResult.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class QueryResult {\n private List<SeriesResult> results;\n\n private String error;\n}" }, { "identifier": "SslContextUtil", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/SslContextUtil.java", "snippet": "public class SslContextUtil {\n\n public static SSLContext buildSSLContextFromJks(String keyStorePath,\n String keyStorePassword,\n String trustStorePath,\n String trustStorePassword,\n boolean disableSslVerify) {\n try {\n // Load the key store\n KeyStore keyStore = KeyStore.getInstance(\"JKS\");\n try (FileInputStream keyStoreFile = new FileInputStream(keyStorePath)) {\n keyStore.load(keyStoreFile, keyStorePassword.toCharArray());\n }\n\n // Set up key manager factory to use our key store\n String defaultKeyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();\n KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultKeyAlgorithm);\n keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());\n\n // Load the trust store, if specified\n TrustManagerFactory trustManagerFactory = null;\n if (trustStorePath != null) {\n KeyStore trustStore = KeyStore.getInstance(\"JKS\");\n try (FileInputStream trustStoreFile = new FileInputStream(trustStorePath)) {\n trustStore.load(trustStoreFile, trustStorePassword.toCharArray());\n }\n\n // Set up trust manager factory to use our trust store\n trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n trustManagerFactory.init(trustStore);\n }\n\n // Set up SSL context\n SSLContext sslContext = SSLContext.getInstance(\"TLSv1.3\");\n\n TrustManager[] trustManagers;\n if (disableSslVerify) {\n trustManagers = new TrustManager[] { new InsecureTrustManager() };\n } else if (trustManagerFactory != null) {\n trustManagers = trustManagerFactory.getTrustManagers();\n } else {\n trustManagers = null;\n }\n\n // Set up SSL parameters\n sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());\n\n if (disableSslVerify) {\n sslContext.getDefaultSSLParameters().setEndpointIdentificationAlgorithm(null);\n }\n\n return sslContext;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }\n}" }, { "identifier": "TlsConfig", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/TlsConfig.java", "snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TlsConfig {\n public String keyStorePath;\n\n @ToString.Exclude\n public String keyStorePassword;\n\n public String trustStorePath;\n\n @ToString.Exclude\n public String trustStorePassword;\n\n public boolean tlsVerificationDisabled;\n}" }, { "identifier": "OpenGeminiCommon", "path": "opengemini-client-jdk/src/main/java/io/opengemini/client/jdk/common/OpenGeminiCommon.java", "snippet": "public class OpenGeminiCommon {\n private static final ObjectMapper objectMapper = new ObjectMapper();\n public static <T> T converJson2Bean(String json, Class<T> cls) throws JsonProcessingException {\n return objectMapper.readValue(json, cls);\n }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import io.opengemini.client.api.Address; import io.opengemini.client.api.OpenGeminiException; import io.opengemini.client.api.Query; import io.opengemini.client.api.QueryResult; import io.opengemini.client.api.SslContextUtil; import io.opengemini.client.api.TlsConfig; import io.opengemini.client.jdk.common.OpenGeminiCommon; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger;
1,462
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig();
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig();
builder = builder.sslContext(SslContextUtil.buildSSLContextFromJks(
4
2023-10-12 09:08:55+00:00
2k
lilmayu/java-discord-oauth2-api
src/test/java/dev/mayuna/discord/api/DiscordApiTest.java
[ { "identifier": "Utils", "path": "src/test/java/dev/mayuna/discord/Utils.java", "snippet": "public class Utils {\n\n public static void AssertStringArraysEquals(String[] a, String[] b) {\n if (a.length != b.length) {\n Assertions.fail(\"Arrays are not the same length (a.length != b.length: \" + a.length + \" != \" + b.length + \")\");\n }\n\n for (int i = 0; i < a.length; i++) {\n if (!a[i].equals(b[i])) {\n Assertions.fail(\"Arrays are not the same (a[i] != b[i]: \" + a[i] + \" != \" + b[i] + \")\");\n }\n }\n }\n\n public static void setField(Object object, String fieldName, Object value) {\n try {\n Field field = object.getClass().getDeclaredField(fieldName);\n field.setAccessible(true);\n field.set(object, value);\n } catch (NoSuchFieldException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "DiscordUser", "path": "src/main/java/dev/mayuna/discord/api/entities/DiscordUser.java", "snippet": "@Getter\npublic class DiscordUser extends DiscordApiResponse {\n\n private String id;\n private String username;\n private String discriminator;\n private @SerializedName(\"global_name\") String globalName;\n private @SerializedName(\"avatar\") String avatarHash;\n private @Nullable Boolean bot;\n private @Nullable Boolean system;\n private @Nullable @SerializedName(\"mfa_enabled\") Boolean mfaEnabled;\n private @Nullable @SerializedName(\"accent_color\") Integer accentColor;\n private @Nullable String locale;\n private @Nullable Boolean verified;\n private @Nullable String email;\n private @Nullable Integer flags;\n private @Nullable @SerializedName(\"premium_type\") Integer premiumType;\n private @Nullable @SerializedName(\"public_flags\") Integer publicFlags;\n private @Nullable @SerializedName(\"avatar_decoration\") String avatarDecorationHash;\n\n /**\n * Gets the user's ID as a long.\n *\n * @return The user's ID as a long.\n */\n public long getIdAsLong() {\n return Long.parseLong(id);\n }\n}" }, { "identifier": "DiscordApiMock", "path": "src/test/java/dev/mayuna/discord/api/server/DiscordApiMock.java", "snippet": "@Getter\npublic class DiscordApiMock {\n\n private final int port;\n private final Javalin javalin;\n\n private final String userAccessToken;\n private final DiscordUser discordUser;\n\n public DiscordApiMock(String userAccessToken, DiscordUser discordUser) {\n this.userAccessToken = userAccessToken;\n this.discordUser = discordUser;\n\n this.port = new Random().nextInt(65535 - 1024) + 1024;\n this.javalin = Javalin.create();\n }\n\n /**\n * Gets the URL of the server.\n *\n * @return The URL of the server.\n */\n public String getUrl() {\n return \"http://localhost:\" + port;\n }\n\n /**\n * Starts the server.\n */\n public void start() {\n prepareEndpoints();\n\n javalin.start(\"localhost\", port);\n }\n\n /**\n * Stops the server.\n */\n public void stop() {\n javalin.stop();\n }\n\n private void prepareEndpoints() {\n javalin.get(\"/users/@me\", this::handleGetUser);\n }\n\n private void handleGetUser(Context context) {\n // Check access token\n String authorization = context.header(\"Authorization\");\n\n if (authorization == null || !authorization.startsWith(\"Bearer \")) {\n processCtxAsError(context, \"invalid_request\", \"Missing or invalid Authorization header\");\n return;\n }\n\n String accessToken = authorization.substring(\"Bearer \".length());\n\n if (!accessToken.equals(userAccessToken)) {\n processCtxAsError(context, \"invalid_token\", \"Invalid access token\");\n return;\n }\n\n context.status(200);\n context.result(new Gson().toJsonTree(discordUser).toString());\n }\n\n private void processCtxAsError(Context ctx, String error, String errorDescription) {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"error\", error);\n jsonObject.addProperty(\"error_description\", errorDescription);\n\n ctx.status(400);\n ctx.contentType(\"application/json\");\n ctx.result(jsonObject.toString());\n }\n}" } ]
import dev.mayuna.discord.Utils; import dev.mayuna.discord.api.entities.DiscordUser; import dev.mayuna.discord.api.server.DiscordApiMock; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test;
1,167
package dev.mayuna.discord.api; public class DiscordApiTest { private final static String testAccessToken = "abcdefg"; private final static DiscordUser testUser = createTestUser(); private static DiscordApi discordApi;
package dev.mayuna.discord.api; public class DiscordApiTest { private final static String testAccessToken = "abcdefg"; private final static DiscordUser testUser = createTestUser(); private static DiscordApi discordApi;
private static DiscordApiMock discordApiMock;
2
2023-10-10 15:10:53+00:00
2k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/model/ImagineInRequest.java
[ { "identifier": "DiscordMjJavaException", "path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java", "snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n */\n private int errorCode;\n\n /**\n * 错误信息.\n */\n private String errorMsg;\n\n\n public DiscordMjJavaException(Throwable e){\n super(e);\n }\n\n public DiscordMjJavaException(int errorCode,String errorMsg){\n this.errorCode = errorCode;\n this.errorMsg = errorMsg;\n }\n\n public DiscordMjJavaException(int errorCode,String errorMsg,Object...params){\n this.errorCode = errorCode;\n this.errorMsg = StrUtil.format(errorMsg,params);\n }\n\n public DiscordMjJavaException(String errorMsg){\n this.errorCode = 400;\n this.errorMsg = errorMsg;\n }\n\n public DiscordMjJavaException(String errorMsg,Object...params){\n this.errorCode = 400;\n this.errorMsg = StrUtil.format(errorMsg,params);\n }\n\n}" }, { "identifier": "UniqueUtil", "path": "src/main/java/com/github/dmj/util/UniqueUtil.java", "snippet": "public class UniqueUtil {\n\n public static Integer generateUniqueId() {\n int digits = 9; // 指定生成的位数\n // 生成11位数的随机纯数字字符串\n String randomNumber = RandomUtil.randomNumbers(digits);\n if(randomNumber.charAt(0) == '0'){\n //如果第一位是0 随机切换到1-9\n Random random = new Random();\n int randomOne = random.nextInt(9) + 1;\n randomNumber = randomOne +randomNumber.substring(1);\n }\n return Integer.parseInt(randomNumber);\n }\n}" } ]
import cn.hutool.core.util.StrUtil; import com.github.dmj.error.DiscordMjJavaException; import com.github.dmj.util.UniqueUtil; import lombok.Data; import java.io.Serializable;
731
package com.github.dmj.model; /** * @author ljjy1 * @classname ImagineInRequest * @date 2023/10/12 11:04 */ @Data public class ImagineInRequest extends BaseRequest implements Serializable { /** * 文本 */ private String prompt; /** * 图片链接 * */ private String picurl; /** * 验证参数 */ public void check(){ if(StrUtil.isBlank(userKey)){ throw new DiscordMjJavaException("用户key不能为空 [The userKey cannot be empty]"); } if(StrUtil.isBlank(prompt) && prompt.trim().equals("")){ throw new DiscordMjJavaException("文本不能为空 [The prompt cannot be empty]"); } if (StrUtil.isBlank(picurl) && (prompt.startsWith("http://") || prompt.startsWith("https://"))) { String[] parts = prompt.split(" ", 2); if (parts.length >= 2) { picurl = parts[0]; prompt = parts[1]; } }
package com.github.dmj.model; /** * @author ljjy1 * @classname ImagineInRequest * @date 2023/10/12 11:04 */ @Data public class ImagineInRequest extends BaseRequest implements Serializable { /** * 文本 */ private String prompt; /** * 图片链接 * */ private String picurl; /** * 验证参数 */ public void check(){ if(StrUtil.isBlank(userKey)){ throw new DiscordMjJavaException("用户key不能为空 [The userKey cannot be empty]"); } if(StrUtil.isBlank(prompt) && prompt.trim().equals("")){ throw new DiscordMjJavaException("文本不能为空 [The prompt cannot be empty]"); } if (StrUtil.isBlank(picurl) && (prompt.startsWith("http://") || prompt.startsWith("https://"))) { String[] parts = prompt.split(" ", 2); if (parts.length >= 2) { picurl = parts[0]; prompt = parts[1]; } }
triggerId = UniqueUtil.generateUniqueId();
1
2023-10-11 01:12:39+00:00
2k
weizen-w/Educational-Management-System-BE
src/main/java/de/ait/ems/controllers/ModulesController.java
[ { "identifier": "ModulesApi", "path": "src/main/java/de/ait/ems/controllers/api/ModulesApi.java", "snippet": "@RequestMapping(\"/api/modules\")\n@Tags(value = {\n @Tag(name = \"Modules\")\n})\npublic interface ModulesApi {\n\n @Operation(summary = \"Create a module\", description = \"Available to administrator\")\n @ApiResponses(value = {\n @ApiResponse(responseCode = \"201\",\n description = \"The module was created successfully\",\n content = @Content(mediaType = \"application/json\",\n schema = @Schema(implementation = CourseDto.class))),\n @ApiResponse(responseCode = \"400\",\n description = \"Validation error\",\n content = @Content(mediaType = \"application/json\",\n schema = @Schema(implementation = ValidationErrorsDto.class)))\n })\n @PostMapping\n @ResponseStatus(code = HttpStatus.CREATED)\n @PreAuthorize(\"hasAuthority('ADMIN')\")\n ModuleDto addModule(\n @Parameter(description = \"Body with new module\", required = true) @RequestBody @Valid NewModuleDto newModule);\n\n @Operation(summary = \"Getting a list of modules\", description = \"Available to administrator\")\n @GetMapping\n @ResponseStatus(code = HttpStatus.OK)\n @PreAuthorize(\"hasAuthority('ADMIN')\")\n List<ModuleDto> getModules();\n\n @Operation(summary = \"Module update\", description = \"Available to administrator\")\n @ApiResponses(value = {\n @ApiResponse(responseCode = \"200\",\n description = \"Update processed successfully\",\n content = @Content(mediaType = \"application/json\",\n schema = @Schema(implementation = CourseDto.class))\n ),\n @ApiResponse(responseCode = \"400\",\n description = \"Validation error\",\n content = @Content(mediaType = \"application/json\",\n schema = @Schema(implementation = ValidationErrorsDto.class))\n ),\n @ApiResponse(responseCode = \"404\",\n description = \"Module not found\",\n content = @Content(mediaType = \"application/json\",\n schema = @Schema(implementation = StandardResponseDto.class)))\n })\n @PutMapping(\"/{module-id}\")\n @ResponseStatus(code = HttpStatus.OK)\n @PreAuthorize(\"hasAuthority('ADMIN')\")\n ModuleDto updateModule(\n @Parameter(description = \"Module ID\", example = \"1\", required = true) @Min(1) @PathVariable(\"module-id\") Long moduleId,\n @Parameter(description = \"Body with new module\", required = true) @Valid @RequestBody UpdateModuleDto updateModule);\n}" }, { "identifier": "ModuleDto", "path": "src/main/java/de/ait/ems/dto/ModuleDto.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Schema(name = \"Module\", description = \"Lesson module\")\npublic class ModuleDto {\n\n @Schema(description = \"Module ID\", example = \"1\")\n private Long id;\n @Schema(description = \"Module name\", example = \"Backend\")\n private String name;\n @Schema(description = \"Module is archived\", example = \"false\")\n private Boolean archived;\n\n public static ModuleDto from(Module module) {\n return ModuleDto.builder()\n .id(module.getId())\n .name(module.getName())\n .archived(module.getArchived())\n .build();\n }\n\n public static List<ModuleDto> from(List<Module> modules) {\n return modules\n .stream()\n .map(ModuleDto::from)\n .collect(Collectors.toList());\n }\n}" }, { "identifier": "NewModuleDto", "path": "src/main/java/de/ait/ems/dto/NewModuleDto.java", "snippet": "@Data\n@Schema(name = \"New module\")\npublic class NewModuleDto {\n\n @Schema(description = \"Module name\", example = \"Backend\")\n @NotNull(message = \"Must not be null\")\n @NotBlank(message = \"Must not be blank\")\n @NotEmpty(message = \"Must not be empty\")\n @Size(max = 50, message = \"Size must be in the range from 0 to 50\")\n private String name;\n}" }, { "identifier": "UpdateModuleDto", "path": "src/main/java/de/ait/ems/dto/UpdateModuleDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Schema(name = \"Update module\", description = \"Data for updating the module\")\npublic class UpdateModuleDto {\n\n @Pattern(regexp = \"^$|^(?!\\\\s+$).+\", message = \"Must not be blank or contain only spaces\")\n @Size(min = 1, max = 50, message = \"Size must be in the range from 1 to 50\")\n @Schema(description = \"Module name\", example = \"Backend\")\n private String name;\n @Schema(description = \"Module is archived\", example = \"true\")\n private Boolean archived;\n}" }, { "identifier": "ModulesService", "path": "src/main/java/de/ait/ems/services/ModulesService.java", "snippet": "@RequiredArgsConstructor\n@Service\npublic class ModulesService {\n\n private final ModulesRepository modulesRepository;\n\n public ModuleDto addModule(NewModuleDto newModule) {\n Module module = Module.builder()\n .name(newModule.getName())\n .archived(false)\n .build();\n modulesRepository.save(module);\n return from(module);\n }\n\n public List<ModuleDto> getModules() {\n List<Module> modules = modulesRepository.findAll();\n return from(modules);\n }\n\n public ModuleDto updateModule(Long moduleId, UpdateModuleDto updateModule) {\n Module moduleForUpdate = getModuleOrThrow(moduleId);\n if (updateModule.getName() != null) {\n moduleForUpdate.setName(updateModule.getName());\n }\n if (updateModule.getArchived() != null) {\n moduleForUpdate.setArchived(updateModule.getArchived());\n }\n modulesRepository.save(moduleForUpdate);\n return from(moduleForUpdate);\n }\n\n public Module getModuleOrThrow(Long moduleId) {\n return modulesRepository.findById(moduleId).orElseThrow(\n () -> new RestException(HttpStatus.NOT_FOUND,\n \"Module with id <\" + moduleId + \"> not found\"));\n }\n}" } ]
import de.ait.ems.controllers.api.ModulesApi; import de.ait.ems.dto.ModuleDto; import de.ait.ems.dto.NewModuleDto; import de.ait.ems.dto.UpdateModuleDto; import de.ait.ems.services.ModulesService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.RestController;
1,503
package de.ait.ems.controllers; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class ModulesController implements ModulesApi {
package de.ait.ems.controllers; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class ModulesController implements ModulesApi {
private final ModulesService modulesService;
4
2023-10-07 16:00:02+00:00
2k
hendisantika/saga-pattern-choreography
payment/src/main/java/com/hendisantika/payment/controller/PaymentController.java
[ { "identifier": "CustomerOrder", "path": "payment/src/main/java/com/hendisantika/payment/dto/CustomerOrder.java", "snippet": "@Data\npublic class CustomerOrder {\n private String item;\n\n private int quantity;\n\n private double amount;\n\n private String paymentMode;\n\n private Long orderId;\n\n private String address;\n}" }, { "identifier": "OrderEvent", "path": "payment/src/main/java/com/hendisantika/payment/dto/OrderEvent.java", "snippet": "@Data\npublic class OrderEvent {\n private String type;\n\n private CustomerOrder order;\n}" }, { "identifier": "PaymentEvent", "path": "payment/src/main/java/com/hendisantika/payment/dto/PaymentEvent.java", "snippet": "@Data\npublic class PaymentEvent {\n private String type;\n\n private CustomerOrder order;\n}" }, { "identifier": "Payment", "path": "payment/src/main/java/com/hendisantika/payment/entity/Payment.java", "snippet": "@Data\n@Entity\npublic class Payment {\n @Id\n @GeneratedValue\n private Long id;\n\n @Column\n private String mode;\n\n @Column\n private Long orderId;\n\n @Column\n private double amount;\n\n @Column\n private String status;\n}" }, { "identifier": "PaymentRepository", "path": "payment/src/main/java/com/hendisantika/payment/repository/PaymentRepository.java", "snippet": "public interface PaymentRepository extends CrudRepository<Payment, Long> {\n\n List<Payment> findByOrderId(long orderId);\n\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hendisantika.payment.dto.CustomerOrder; import com.hendisantika.payment.dto.OrderEvent; import com.hendisantika.payment.dto.PaymentEvent; import com.hendisantika.payment.entity.Payment; import com.hendisantika.payment.repository.PaymentRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Controller;
679
package com.hendisantika.payment.controller; /** * Created by IntelliJ IDEA. * Project : saga-pattern-choreography * User: hendi * Email: [email protected] * Telegram : @hendisantika34 * Link : s.id/hendisantika * Date: 10/13/2023 * Time: 8:03 AM * To change this template use File | Settings | File Templates. */ @Controller @RequiredArgsConstructor @Slf4j public class PaymentController { private final PaymentRepository paymentRepository; private final KafkaTemplate<String, PaymentEvent> kafkaTemplate; private final KafkaTemplate<String, OrderEvent> kafkaOrderTemplate; @KafkaListener(topics = "new-orders", groupId = "orders-group") public void processPayment(String event) throws JsonProcessingException { log.info("Recieved event" + event); OrderEvent orderEvent = new ObjectMapper().readValue(event, OrderEvent.class);
package com.hendisantika.payment.controller; /** * Created by IntelliJ IDEA. * Project : saga-pattern-choreography * User: hendi * Email: [email protected] * Telegram : @hendisantika34 * Link : s.id/hendisantika * Date: 10/13/2023 * Time: 8:03 AM * To change this template use File | Settings | File Templates. */ @Controller @RequiredArgsConstructor @Slf4j public class PaymentController { private final PaymentRepository paymentRepository; private final KafkaTemplate<String, PaymentEvent> kafkaTemplate; private final KafkaTemplate<String, OrderEvent> kafkaOrderTemplate; @KafkaListener(topics = "new-orders", groupId = "orders-group") public void processPayment(String event) throws JsonProcessingException { log.info("Recieved event" + event); OrderEvent orderEvent = new ObjectMapper().readValue(event, OrderEvent.class);
CustomerOrder order = orderEvent.getOrder();
0
2023-10-13 00:23:14+00:00
2k
wukong121/eights-reservation
src/main/java/com/bupt/eights/controller/LoginController.java
[ { "identifier": "LoginRequest", "path": "src/main/java/com/bupt/eights/dto/request/LoginRequest.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Data\npublic class LoginRequest {\n \n @NotBlank String userName;\n \n @NotBlank String password;\n \n @NotBlank boolean remember;\n}" }, { "identifier": "RegisterRequest", "path": "src/main/java/com/bupt/eights/dto/request/RegisterRequest.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Data\npublic class RegisterRequest {\n \n @NotBlank String email;\n \n @NotBlank String gender;\n \n String nickName;\n \n @NotBlank String password;\n \n @NotBlank String phone;\n \n @NotBlank String prefix;\n \n @NotBlank String userName;\n \n}" }, { "identifier": "LoginResponse", "path": "src/main/java/com/bupt/eights/dto/response/LoginResponse.java", "snippet": "@Data\npublic class LoginResponse implements Serializable {\n \n @Data\n @AllArgsConstructor\n public static class User {\n \n String userName;\n \n String password;\n \n }\n \n private User user;\n \n private String token;\n}" }, { "identifier": "AuthorityRole", "path": "src/main/java/com/bupt/eights/model/AuthorityRole.java", "snippet": "public enum AuthorityRole {\n ROLE_STUDENT,\n ROLE_ADMIN;\n}" }, { "identifier": "User", "path": "src/main/java/com/bupt/eights/model/User.java", "snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User {\n\n private String userId;\n \n private String userName;\n \n private String email;\n \n private String phoneNumber;\n \n private String gender;\n \n private String nickName;\n \n private String password;\n\n private String createTime;\n \n private AuthorityRole authority;\n}" }, { "identifier": "HttpResponse", "path": "src/main/java/com/bupt/eights/dto/response/HttpResponse.java", "snippet": "@Data\npublic class HttpResponse<T> implements Serializable {\n \n private String status; // success,failed\n \n private int code; // 0 success;-1 failed\n \n private String message;\n \n public T data;\n \n}" }, { "identifier": "AuthenticateService", "path": "src/main/java/com/bupt/eights/service/AuthenticateService.java", "snippet": "public interface AuthenticateService {\n \n User createUser(RegisterRequest registerRequest);\n \n HttpResponse<LoginResponse> authenticate(LoginRequest loginRequest);\n \n}" }, { "identifier": "JwtTokenUtils", "path": "src/main/java/com/bupt/eights/utils/JwtTokenUtils.java", "snippet": "public class JwtTokenUtils {\n \n // expiration time set to 3600s (1 hour)\n private static final long EXPIRATION = 3600L;\n \n // expiration time set to 7 days after select remember me\n private static final long EXPIRATION_REMEMBER = 604800L;\n \n private static final String SECRET = \"eightsjwtsecret\";\n \n private static final String ISSUER = \"com.bupt.eights\";\n \n private static final String ROLE_CLAIMS = \"role\";\n \n public static String createToken(String userName, AuthorityRole role, Boolean isRememberMe) {\n long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;\n Map<String, Object> claimMap = new HashMap<>();\n claimMap.put(ROLE_CLAIMS, role);\n return Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET).setClaims(claimMap).setIssuer(ISSUER)\n .setSubject(userName).setIssuedAt(new Date())\n .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)).compact();\n }\n \n public static String getUserName(String token) {\n return getTokenBody(token).getSubject();\n }\n \n public static AuthorityRole getUserRole(String token) {\n return (AuthorityRole) getTokenBody(token).get(ROLE_CLAIMS);\n }\n \n public static boolean isExpired(String token) {\n try {\n return getTokenBody(token).getExpiration().before(new Date());\n } catch (ExpiredJwtException e) {\n return true;\n }\n }\n \n private static Claims getTokenBody(String token) {\n return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();\n }\n}" }, { "identifier": "URLConstant", "path": "src/main/java/com/bupt/eights/utils/URLConstant.java", "snippet": "public class URLConstant {\n \n public static final String LOGIN_URL = \"/api/v1\";\n \n}" } ]
import com.bupt.eights.dto.request.LoginRequest; import com.bupt.eights.dto.request.RegisterRequest; import com.bupt.eights.dto.response.LoginResponse; import com.bupt.eights.model.AuthorityRole; import com.bupt.eights.model.User; import com.bupt.eights.dto.response.HttpResponse; import com.bupt.eights.service.AuthenticateService; import com.bupt.eights.utils.JwtTokenUtils; import com.bupt.eights.utils.URLConstant; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
1,532
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST)
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST)
public HttpResponse<String> createUser(@RequestBody @Valid RegisterRequest request) {
5
2023-10-11 09:34:23+00:00
2k
manhcntt21/design-pattern
factory-abstract/src/pizza/v2/PizzaDriven.java
[ { "identifier": "Pizza", "path": "factory-abstract/src/pizza/v2/product/Pizza.java", "snippet": "public abstract class Pizza {\n private String name;\n\n public abstract void prepare();\n\n public abstract void bake();\n\n public abstract void cut();\n\n public abstract void box();\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "identifier": "CaliforniaPizzaStore", "path": "factory-abstract/src/pizza/v2/store/CaliforniaPizzaStore.java", "snippet": "public class CaliforniaPizzaStore extends PizzaStore {\n @Override\n protected Pizza createPizza(String type) {\n return switch (type.toLowerCase(Locale.ROOT)) {\n case \"cheese\" -> new CaliforniaStyleCheesePizza();\n case \"pepperoni\" -> new CaliforniaStylePepperoniPizza();\n case \"greek\" -> new CaliforniaStyleGreekPizza();\n default -> throw new IllegalArgumentException(\"invalid type!\");\n };\n }\n}" }, { "identifier": "ChicagoPizzaStore", "path": "factory-abstract/src/pizza/v2/store/ChicagoPizzaStore.java", "snippet": "public class ChicagoPizzaStore extends PizzaStore {\n @Override\n protected Pizza createPizza(String type) {\n return switch (type.toLowerCase(Locale.ROOT)) {\n case \"cheese\" -> new ChicagoStyleCheesePizza();\n case \"pepperoni\" -> new ChicagoStylePepperoniPizza();\n case \"greek\" -> new ChicagoStyleGreekPizza();\n default -> throw new IllegalArgumentException(\"invalid type!\");\n };\n }\n}" }, { "identifier": "NewYorkStylePizza", "path": "factory-abstract/src/pizza/v2/store/NewYorkStylePizza.java", "snippet": "public class NewYorkStylePizza extends PizzaStore{\n @Override\n protected Pizza createPizza(String type) {\n return switch (type.toLowerCase(Locale.ROOT)) {\n case \"cheese\" -> new NewYorkStyleCheesePizza();\n case \"pepperoni\" -> new NewYorkStylePepperoniPizza();\n case \"greek\" -> new NewYorkStyleGreekPizza();\n default -> throw new IllegalArgumentException(\"invalid type!\");\n };\n }\n}" }, { "identifier": "PizzaStore", "path": "factory-abstract/src/pizza/v2/store/PizzaStore.java", "snippet": "public abstract class PizzaStore {\n public Pizza orderPizza(String type) {\n Pizza pizza = createPizza(type);\n // process for creating a pizza\n pizza.prepare();\n pizza.bake();\n pizza.cut();\n pizza.box();\n return pizza;\n }\n\n protected abstract Pizza createPizza(String type);\n}" } ]
import pizza.v2.product.Pizza; import pizza.v2.store.CaliforniaPizzaStore; import pizza.v2.store.ChicagoPizzaStore; import pizza.v2.store.NewYorkStylePizza; import pizza.v2.store.PizzaStore;
673
package pizza.v2; /** * @author manhdt14 * created in 10/8/2023 6:58 PM */ public class PizzaDriven { public static void main(String[] args) {
package pizza.v2; /** * @author manhdt14 * created in 10/8/2023 6:58 PM */ public class PizzaDriven { public static void main(String[] args) {
PizzaStore chicago = new ChicagoPizzaStore();
4
2023-10-09 06:56:26+00:00
2k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/main/GamePanel.java
[ { "identifier": "KeyboardInputs", "path": "src/inputs/KeyboardInputs.java", "snippet": "public class KeyboardInputs implements KeyListener {\n\n\tprivate GamePanel gamePanel;\n\n\tpublic KeyboardInputs(GamePanel gamePanel) {\n\t\tthis.gamePanel = gamePanel;\n\t}\n\n\t@Override\n\tpublic void keyTyped(KeyEvent e) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\t\n\t@Override\n\tpublic void keyReleased(KeyEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tgamePanel.getGame().getMenu().keyReleased(e);\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().keyReleased(e);\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void keyPressed(KeyEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tgamePanel.getGame().getMenu().keyPressed(e);\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().keyPressed(e);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgamePanel.getGame().getGameOptions().keyPressed(e);\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t}\n\n}" }, { "identifier": "MouseInputs", "path": "src/inputs/MouseInputs.java", "snippet": "public class MouseInputs implements MouseListener, MouseMotionListener {\n\n\tprivate GamePanel gamePanel;\n\n\tpublic MouseInputs(GamePanel gamePanel) {\n\t\tthis.gamePanel = gamePanel;\n\t}\n\n\t@Override\n\tpublic void mouseDragged(MouseEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().mouseDragged(e);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgamePanel.getGame().getGameOptions().mouseDragged(e);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mouseMoved(MouseEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tgamePanel.getGame().getMenu().mouseMoved(e);\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().mouseMoved(e);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgamePanel.getGame().getGameOptions().mouseMoved(e);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mouseClicked(MouseEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().mouseClicked(e);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mousePressed(MouseEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tgamePanel.getGame().getMenu().mousePressed(e);\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().mousePressed(e);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgamePanel.getGame().getGameOptions().mousePressed(e);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mouseReleased(MouseEvent e) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tgamePanel.getGame().getMenu().mouseReleased(e);\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tgamePanel.getGame().getPlaying().mouseReleased(e);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgamePanel.getGame().getGameOptions().mouseReleased(e);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void mouseEntered(MouseEvent e) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void mouseExited(MouseEvent e) {\n\t\t\n\n\t}\n\n}" }, { "identifier": "GAME_HEIGHT", "path": "src/main/Game.java", "snippet": "public final static int GAME_HEIGHT = TILES_SIZE * TILES_IN_HEIGHT;" }, { "identifier": "GAME_WIDTH", "path": "src/main/Game.java", "snippet": "public final static int GAME_WIDTH = TILES_SIZE * TILES_IN_WIDTH;" } ]
import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; import inputs.KeyboardInputs; import inputs.MouseInputs; import static main.Game.GAME_HEIGHT; import static main.Game.GAME_WIDTH;
1,079
package main; public class GamePanel extends JPanel { private MouseInputs mouseInputs; private Game game; public GamePanel(Game game) { mouseInputs = new MouseInputs(this); this.game = game; setPanelSize(); addKeyListener(new KeyboardInputs(this)); addMouseListener(mouseInputs); addMouseMotionListener(mouseInputs); } private void setPanelSize() {
package main; public class GamePanel extends JPanel { private MouseInputs mouseInputs; private Game game; public GamePanel(Game game) { mouseInputs = new MouseInputs(this); this.game = game; setPanelSize(); addKeyListener(new KeyboardInputs(this)); addMouseListener(mouseInputs); addMouseMotionListener(mouseInputs); } private void setPanelSize() {
Dimension size = new Dimension(GAME_WIDTH , GAME_HEIGHT );
3
2023-10-07 12:07:45+00:00
2k
whykang/Trajectory-extraction
app/src/main/java/com/wang/tracker/sensor/StepEventHandler.java
[ { "identifier": "StepPosition", "path": "app/src/main/java/com/wang/tracker/pojo/StepPosition.java", "snippet": "public class StepPosition {\n private Long time;\n private Float dx;\n private Float dy;\n\n public StepPosition(Long time, Float dx, Float dy) {\n this.time = time;\n this.dx = dx;\n this.dy = dy;\n }\n\n public Float getDx() {\n return dx;\n }\n\n public void setDx(float x) {\n\n this.dx=x;\n // return dx;\n }\n\n public void setDy(float y) {\n\n this.dy=y;\n // return dx;\n }\n\n public Float getDy() {\n return dy;\n }\n\n public long getTime() {\n return time;\n }\n\n @Override\n public String toString() {\n return \"StepPosition{\" +\n \"time=\" + time +\n \", dx=\" + dx +\n \", dy=\" + dy +\n '}';\n }\n}" }, { "identifier": "WaveRecorder", "path": "app/src/main/java/com/wang/tracker/tool/WaveRecorder.java", "snippet": "public class WaveRecorder {\n private static WaveRecorder instance;\n float maxWave = 0;\n float minWave = 0x7fffffff;\n\n public synchronized static WaveRecorder getInstance() {\n if (instance != null) return instance;\n instance = new WaveRecorder();\n return instance;\n }\n\n public boolean update(float wave) {\n if (wave > maxWave) {\n maxWave = wave;\n return true;\n }\n if (wave < minWave) {\n minWave = wave;\n return true;\n }\n return false;\n }\n\n public float calculate() {\n if(maxWave == 0 || minWave == 0x7fffffff) {\n reset();\n return 0;\n }\n return maxWave - minWave;\n }\n\n public void reset() {\n minWave = 0x7fffffff;\n maxWave = 0;\n }\n\n public float calculateAndReset() {\n if(maxWave == 0 || minWave == 0x7fffffff) {\n reset();\n return 0;\n }\n return maxWave - minWave;\n }\n}" } ]
import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import com.wang.tracker.pojo.StepPosition; import com.wang.tracker.tool.WaveRecorder; import java.util.ArrayList; import java.util.Date; import java.util.List;
913
package com.wang.tracker.sensor; /** * Handling step information * */ public class StepEventHandler { private final Handler activityHandler; private final Handler activityHandler1; private List<Float> angles=new ArrayList<Float>(); private Context context; public StepEventHandler(Handler activityHandler, Handler activityHandler1, Context con) { this.activityHandler = activityHandler; this.activityHandler1 = activityHandler1; this.context=con; } /** * Calculate the direction and distance of this step * Of course, the numbers are relative * */ public void onStep() { float angle = (float) OrientationData.getInstance().getAzimuth(); angles.add(angle); float ang=angle; SharedPreferences dataBase =context. getSharedPreferences("Sha", context.MODE_PRIVATE); SharedPreferences.Editor edit = dataBase.edit(); int phclnum=dataBase.getInt("phcl", 3); if(angles.size()>200) { angles.clear(); } if(angles.size()>phclnum) { ang=pro(angles,phclnum); } float distance = getStepSize(); //StepPosition stepPosition = new StepPosition(new Date().getTime(), (float) -Math.cos(angle) * distance, (float) -Math.sin(angle) * distance);
package com.wang.tracker.sensor; /** * Handling step information * */ public class StepEventHandler { private final Handler activityHandler; private final Handler activityHandler1; private List<Float> angles=new ArrayList<Float>(); private Context context; public StepEventHandler(Handler activityHandler, Handler activityHandler1, Context con) { this.activityHandler = activityHandler; this.activityHandler1 = activityHandler1; this.context=con; } /** * Calculate the direction and distance of this step * Of course, the numbers are relative * */ public void onStep() { float angle = (float) OrientationData.getInstance().getAzimuth(); angles.add(angle); float ang=angle; SharedPreferences dataBase =context. getSharedPreferences("Sha", context.MODE_PRIVATE); SharedPreferences.Editor edit = dataBase.edit(); int phclnum=dataBase.getInt("phcl", 3); if(angles.size()>200) { angles.clear(); } if(angles.size()>phclnum) { ang=pro(angles,phclnum); } float distance = getStepSize(); //StepPosition stepPosition = new StepPosition(new Date().getTime(), (float) -Math.cos(angle) * distance, (float) -Math.sin(angle) * distance);
StepPosition stepPosition = new StepPosition(new Date().getTime(), (float) Math.sin(ang) * distance, (float) Math.cos(ang) * distance);
0
2023-10-10 12:49:16+00:00
2k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/common/Result.java
[ { "identifier": "ShirBootContracts", "path": "src/main/java/io/github/reinershir/boot/contract/ShirBootContracts.java", "snippet": "public class ShirBootContracts {\n\n public static final String RESP_CODE_SUCCESS = \"00000\";\n public static final String RESP_CODE_SUCCESS_DESC = \"操作成功\";\n\n public static final String RESP_CODE_FAILE = \"00001\";\n public static final String RESP_CODE_FAILE_DESC = \"系统异常\";\n\n //参数为空错误码\n public static final String RESP_CODE_FAILE_NULLPARAM = \"00002\";\n //登陆失败\n public static final String RESP_CODE_FAILE_LOGIN_FAILE = \"00003\";\n //参数不合法\n public static final String RESP_CODE_FAILE_PARAM = \"00004\";\n //超出文件上传大小限制\n public static final String RESP_CODE_UPLOAD_MAX_FAILE = \"00010\";\n\n /**\n * Feign调用服务时出现异常\n */\n public static final String RESP_CODE_FEIGN_EXCEPTION = \"00010\";\n\n //查询出错\n public static final String RESP_CODE_QUERY_ERROR = \"00100\";\n /**\n * 修改数据时出错码\n */\n public static final String RESP_CODE_DATA_UPDATE_ERROR = \"00101\";\n\n //web端请求服务端时的token盐\n public static final String HTTP_ACCESS_TOKEN_SALT = \"httpWebSalt\";\n\n /**\n * 密码加密密钥\n */\n public static final String LOGIN_SALT = \"ShirBootloginSalt\";\n /**\n * 用户信息加密密钥\n */\n public static final String USER_INFO_SALT = \"ShirBootUserInfoSalt\";\n\n //禁用状态\n public static final int STATUS_DISABLE = 1;\n //启用状态\n public static final int STATUS_ENABLE = 0;\n\n //删除状态\n public static final int STATUS_DELETED = 1;\n //正常状态\n public static final int STATUS_NORMAL = 0;\n \n /**\n * token失效时间,默认30分钟 \n */\n public static final int LOGIN_TOKEN_EXPIRE_MINUTES=30;\n \n /**\n * 微信接口的交易类型:扫码\n */\n public static final String WECHAT_TRADE_TYPE_NATIVE=\"NATIVE\";\n /**\n * 微信交易类型:小程序\n */\n public static final String WECHAT_TRADE_TYPE_JSAPI=\"JSAPI\";\n /**\n * APP\n */\n public static final String WECHAT_TRADE_TYPE_APP=\"APP\";\n \n public static final int USER_GROUP_TYPE_STATION = 1;\n \n public static final int USER_GROUP_TYPE_SALE = 2;\n}" }, { "identifier": "IMessager", "path": "src/main/java/io/github/reinershir/boot/core/international/IMessager.java", "snippet": "@Slf4j\npublic class IMessager {\n\n\tprivate Properties properties;\n\tprivate static IMessager instance;\n\t\n\tpublic IMessager() throws IOException {\n\t\tString defaultPath = \"i18n/message.properties\";\n\t\tString path = \"i18n/message_\"+LocaleContextHolder.getLocale().getLanguage().toLowerCase()+\"_\"+LocaleContextHolder.getLocale().getCountry()+\".properties\";\n\t\t\n\t\tResource resource = new ClassPathResource(path);\n\t try {\n\t\t\tthis.properties = PropertiesLoaderUtils.loadProperties(resource);\n\t\t} catch (FileNotFoundException e) {\n\t\t\tthis.properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(defaultPath));\n\t\t\tlog.warn(\"Unable to retrieve internationalization configuration path :{}, will attempt to use default configuration path.\",path);\n\t \tif(properties==null) {\n\t \t\tthrow new BaseException(\"Can not find internationalization properties\");\n\t \t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized IMessager getInstance() {\n\t\t\tif(IMessager.instance==null) {\n\t\t\t\ttry {\n\t\t\t\t\tIMessager.instance = new IMessager();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\treturn IMessager.instance;\n\t\t\n\t}\n\t\n\tpublic static String getMessageByCode(String code) {\n\t\treturn IMessager.getInstance().getMessage(code);\n\t}\n\t\n\tpublic String getMessage(String code) {\n\t\treturn this.properties.getProperty(code);\n\t}\n}" } ]
import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import io.github.reinershir.boot.contract.ShirBootContracts; import io.github.reinershir.boot.core.international.IMessager; import io.swagger.v3.oas.annotations.media.Schema;
1,303
package io.github.reinershir.boot.common; @Schema(description = "Response DTO") @JsonInclude(value = JsonInclude.Include.ALWAYS)//Even if the returned object is null, it will still be returned when this annotation is added. public class Result<T> implements Serializable{ /** * */ private static final long serialVersionUID = -472604879542896258L; @Schema(description = "Response Message", nullable = false, example = "success!") private String message; @Schema(description = "The return result code, by default 00000 indicates a successful request.", required = true, example = "00000") private String code; @Schema(description = "Return Value", nullable = true) private T data = null; public Result(T value) { this.data=value; initSuccess(); } public Result(String message,T value) { this.data=value; initSuccess(); this.message=message; } public Result() { initSuccess(); } private void initSuccess() { this.message = IMessager.getInstance().getMessage("message.success");
package io.github.reinershir.boot.common; @Schema(description = "Response DTO") @JsonInclude(value = JsonInclude.Include.ALWAYS)//Even if the returned object is null, it will still be returned when this annotation is added. public class Result<T> implements Serializable{ /** * */ private static final long serialVersionUID = -472604879542896258L; @Schema(description = "Response Message", nullable = false, example = "success!") private String message; @Schema(description = "The return result code, by default 00000 indicates a successful request.", required = true, example = "00000") private String code; @Schema(description = "Return Value", nullable = true) private T data = null; public Result(T value) { this.data=value; initSuccess(); } public Result(String message,T value) { this.data=value; initSuccess(); this.message=message; } public Result() { initSuccess(); } private void initSuccess() { this.message = IMessager.getInstance().getMessage("message.success");
this.code = ShirBootContracts.RESP_CODE_SUCCESS;
0
2023-10-10 13:06:54+00:00
2k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/ActivitiesPanel.java
[ { "identifier": "PlayerInfo", "path": "src/main/java/net/wiseoldman/beans/PlayerInfo.java", "snippet": "@Value\npublic class PlayerInfo\n{\n int id;\n String username;\n String displayName;\n PlayerType type;\n PlayerBuild build;\n String country;\n boolean flagged;\n long exp;\n double ehp;\n double ehb;\n double ttm;\n double tt200m;\n String registeredAt;\n String updatedAt;\n String lastChangedAt;\n String lastImportedAt;\n int combatLevel;\n Snapshot latestSnapshot;\n}" }, { "identifier": "Snapshot", "path": "src/main/java/net/wiseoldman/beans/Snapshot.java", "snippet": "@Value\npublic class Snapshot\n{\n\tint id;\n\tint playerId;\n\tString createdAt;\n\tString importedAt;\n\tSnapshotData data;\n}" } ]
import com.google.common.collect.ImmutableList; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.Snapshot; import net.runelite.client.ui.ColorScheme; import net.runelite.client.hiscore.HiscoreSkill; import net.runelite.client.hiscore.HiscoreSkillType; import javax.inject.Inject; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import static net.runelite.client.hiscore.HiscoreSkill.*;
665
package net.wiseoldman.panel; public class ActivitiesPanel extends JPanel { /** * Activities, ordered in the way they should be displayed in the panel */ private static final List<HiscoreSkill> ACTIVITIES = ImmutableList.of( LEAGUE_POINTS, BOUNTY_HUNTER_HUNTER, BOUNTY_HUNTER_ROGUE, CLUE_SCROLL_ALL, CLUE_SCROLL_BEGINNER, CLUE_SCROLL_EASY, CLUE_SCROLL_MEDIUM, CLUE_SCROLL_HARD, CLUE_SCROLL_ELITE, CLUE_SCROLL_MASTER, LAST_MAN_STANDING, PVP_ARENA_RANK, SOUL_WARS_ZEAL, RIFTS_CLOSED ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; List<RowPair> tableRows = new ArrayList<>(); @Inject private ActivitiesPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("activities"); add(tableHeader); for (int i = 0; i < ACTIVITIES.size(); i++) { HiscoreSkill activity = ACTIVITIES.get(i); TableRow row = new TableRow( activity.name(), activity.getName(), HiscoreSkillType.ACTIVITY, "score", "rank" ); row.setBackground(ROW_COLORS[1-i%2]); tableRows.add(new RowPair(activity, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; }
package net.wiseoldman.panel; public class ActivitiesPanel extends JPanel { /** * Activities, ordered in the way they should be displayed in the panel */ private static final List<HiscoreSkill> ACTIVITIES = ImmutableList.of( LEAGUE_POINTS, BOUNTY_HUNTER_HUNTER, BOUNTY_HUNTER_ROGUE, CLUE_SCROLL_ALL, CLUE_SCROLL_BEGINNER, CLUE_SCROLL_EASY, CLUE_SCROLL_MEDIUM, CLUE_SCROLL_HARD, CLUE_SCROLL_ELITE, CLUE_SCROLL_MASTER, LAST_MAN_STANDING, PVP_ARENA_RANK, SOUL_WARS_ZEAL, RIFTS_CLOSED ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; List<RowPair> tableRows = new ArrayList<>(); @Inject private ActivitiesPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("activities"); add(tableHeader); for (int i = 0; i < ACTIVITIES.size(); i++) { HiscoreSkill activity = ACTIVITIES.get(i); TableRow row = new TableRow( activity.name(), activity.getName(), HiscoreSkillType.ACTIVITY, "score", "rank" ); row.setBackground(ROW_COLORS[1-i%2]); tableRows.add(new RowPair(activity, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; }
Snapshot latestSnapshot = info.getLatestSnapshot();
1
2023-10-09 14:23:06+00:00
2k
PinkGoosik/player-nametags
src/main/java/pinkgoosik/playernametags/command/PlayerNametagsCommands.java
[ { "identifier": "PlayerNametagsMod", "path": "src/main/java/pinkgoosik/playernametags/PlayerNametagsMod.java", "snippet": "public class PlayerNametagsMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"player-nametags\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\tpublic static LinkedHashMap<UUID, ElementHolder> holders = new LinkedHashMap<>();\n\n\tpublic static PlayerNametagsConfig config;\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tconfig = PlayerNametagsConfig.read();\n\t\tPlayerNametagsCommands.init();\n\n\t\tServerTickEvents.END_SERVER_TICK.register(server -> {\n\t\t\tif(config.enabled) {\n\t\t\t\tserver.getPlayerManager().getPlayerList().forEach(PlayerNametagsMod::updateHolder);\n\n\t\t\t\tif(config.updateRate >= 1 && server.getTicks() % config.updateRate == 0) {\n\t\t\t\t\tupdateNametags(server);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif(!holders.isEmpty()) {\n\t\t\t\t\tholders.forEach((uuid, holder) -> holder.destroy());\n\t\t\t\t\tholders.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static ElementHolder updateHolder(ServerPlayerEntity player) {\n\t\tElementHolder holder;\n\n\t\tif (!holders.containsKey(player.getUuid())) {\n\t\t\tholder = new ElementHolder();\n\n\t\t\tItemDisplayElement element = new ItemDisplayElement();\n\t\t\telement.setBillboardMode(DisplayEntity.BillboardMode.CENTER);\n\n\t\t\tText text = Placeholders.parseText(TextParserUtils.formatText(getFormat(player)), PlaceholderContext.of(player));\n\n\t\t\telement.setCustomName(text);\n\t\t\telement.setCustomNameVisible(!player.isInvisible());\n\n\t\t\tholder.addElement(element);\n\t\t\tholders.put(player.getUuid(), holder);\n\t\t}\n\t\telse {\n\t\t\tholder = holders.get(player.getUuid());\n\t\t}\n\n\t\tholder.getElements().forEach(virtualElement -> {\n\t\t\tif(virtualElement instanceof ItemDisplayElement element) {\n\t\t\t\tif(player.isSneaking()) {\n\t\t\t\t\tswitch (config.whenSneaking) {\n\t\t\t\t\t\tcase \"gray-out\" -> element.setSneaking(true);\n\t\t\t\t\t\tcase \"hide\" -> element.setCustomNameVisible(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\telement.setSneaking(false);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tEntityAttachment.of(holder, player);\n\t\tVirtualEntityUtils.addVirtualPassenger(player, holder.getEntityIds().getInt(0));\n\n\t\treturn holder;\n\t}\n\n\tpublic static void updateNametags(MinecraftServer server) {\n\t\tholders.forEach((uuid, holder) -> {\n\t\t\tvar player = server.getPlayerManager().getPlayer(uuid);\n\t\t\tif(player != null) {\n\t\t\t\tText text = Placeholders.parseText(TextParserUtils.formatText(getFormat(player)), PlaceholderContext.of(player));\n\t\t\t\tholder.getElements().forEach(virtualElement -> {\n\t\t\t\t\tif(virtualElement instanceof ItemDisplayElement element) {\n\t\t\t\t\t\telement.setCustomName(text);\n\t\t\t\t\t\telement.tick();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static String getFormat(ServerPlayerEntity player) {\n\n\t\tfor(Map.Entry<String, String> entry : config.formatPerPermission.entrySet()) {\n\t\t\tif(Permissions.check(player, entry.getKey())) return entry.getValue();\n\t\t}\n\n\t\treturn config.format;\n\t}\n}" }, { "identifier": "PlayerNametagsConfig", "path": "src/main/java/pinkgoosik/playernametags/config/PlayerNametagsConfig.java", "snippet": "public class PlayerNametagsConfig {\n\tpublic static final Gson GSON = new GsonBuilder().setLenient().setPrettyPrinting().disableHtmlEscaping().create();\n\n\tpublic boolean enabled = false;\n\tpublic String format = \"%player:name%\";\n\tpublic int updateRate = 20;\n\tpublic String whenSneaking = \"gray-out\";\n\n\tpublic LinkedHashMap<String, String> formatPerPermission = new LinkedHashMap<>(Map.of(\"example.admin\", \"<red>[Admin] %player:name%\"));\n\n\tpublic static PlayerNametagsConfig read() {\n\t\tString filePath = FabricLoader.getInstance().getConfigDir().resolve(\"player-nametags.json\").toString();\n\t\ttry {\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8));\n\t\t\tvar config = GSON.fromJson(reader, PlayerNametagsConfig.class);\n\t\t\tconfig.save();\n\t\t\treturn config;\n\t\t}\n\t\tcatch(FileNotFoundException e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"File \" + filePath + \" is not found! Setting to default.\");\n\t\t\tvar conf = new PlayerNametagsConfig();\n\t\t\tconf.save();\n\t\t\treturn conf;\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"Failed to read player-nametags config due to an exception. \" +\n\t\t\t\t\"Please delete player-nametags.json to regenerate config or fix the issue:\\n\" + e);\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(0);\n\t\t\treturn new PlayerNametagsConfig();\n\t\t}\n\t}\n\n\tpublic void save() {\n\t\ttry {\n\t\t\tString filePath = FabricLoader.getInstance().getConfigDir().resolve(\"player-nametags.json\").toString();\n\t\t\ttry(FileWriter writer = new FileWriter(filePath, StandardCharsets.UTF_8)) {\n\t\t\t\twriter.write(GSON.toJson(this));\n\t\t\t}\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"Failed to save player-nametags config due to an exception:\\n\" + e);\n\t\t}\n\t}\n}" } ]
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.BoolArgumentType; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.suggestion.SuggestionProvider; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.text.Text; import pinkgoosik.playernametags.PlayerNametagsMod; import pinkgoosik.playernametags.config.PlayerNametagsConfig; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal;
1,486
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining();
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining();
for(String permission : PlayerNametagsMod.config.formatPerPermission.keySet()) {
0
2023-10-10 10:12:09+00:00
2k
vaylor27/config
common/src/main/java/net/vakror/jamesconfig/config/manager/object/ConfigObjectManager.java
[ { "identifier": "ConfigObject", "path": "common/src/main/java/net/vakror/jamesconfig/config/config/object/ConfigObject.java", "snippet": "public interface ConfigObject {\n String getName();\n void setName(String name);\n ResourceLocation getType();\n JsonElement serialize();\n ConfigObject deserialize(@Nullable String name, JsonElement element, ConfigObject defaultValue, String configName);\n\n @Nullable\n static ConfigObject deserializeUnknown(JsonElement element, String configName) {\n if (element instanceof JsonObject object) {\n return deserializeFromObject(null, object, configName);\n } else if (element instanceof JsonPrimitive primitive) {\n return deserializePrimitive(null, primitive);\n } else {\n return null;\n }\n }\n\n @Nullable\n static ConfigObject deserializeUnknown(String name, JsonElement element, String configName) {\n if (element instanceof JsonObject object) {\n return deserializeFromObject(name, object, configName);\n } else if (element instanceof JsonPrimitive primitive) {\n return deserializePrimitive(name, primitive);\n } else {\n return null;\n }\n }\n\n static PrimitiveObject<?> deserializePrimitive(String name, JsonPrimitive element) {\n if (element.isNumber()) {\n return new NumberPrimitiveObject(name, element.getAsNumber());\n } else if (element.isString()) {\n return new StringPrimitiveObject(name, element.getAsString());\n } else if (element.isBoolean()) {\n return new BooleanPrimitiveObject(name, element.getAsBoolean());\n }\n return null;\n }\n\n private static ConfigObject deserializeFromObject(String name, JsonObject jsonObject, String configName) {\n ConfigObject object = JamesConfigMod.KNOWN_OBJECT_TYPES.get(new ResourceLocation(jsonObject.getAsJsonPrimitive(\"type\").getAsString()));\n if (object == null) {\n JamesConfigMod.LOGGER.error(\"Could not find config object object of type {}\", jsonObject.getAsJsonPrimitive(\"type\").getAsString());\n return null;\n }\n return object.deserialize(name, jsonObject, null, configName);\n }\n}" }, { "identifier": "ConfigEvents", "path": "common/src/main/java/net/vakror/jamesconfig/config/event/ConfigEvents.java", "snippet": "@SuppressWarnings(\"all\")\npublic class ConfigEvents {\n //@James usually in a fabric/architectury sense registries are static and non frozen anyways, so the registry wouldnt be event based\n //but instead be just a map you can add yourself to, i am keeping the event wrapper for now\n public static final Event<RegisterEvent> CONFIG_REGISTER_EVENT = EventFactory.createEventResult();\n public static final Event<ObjectRegisterEvent> OBJECT_REGISTER_EVENT = EventFactory.createEventResult();\n public static final Event<RegisterConfigManager> REGISTER_MANAGER = EventFactory.createEventResult();\n\n public interface RegisterEvent {\n EventResult post(ConfigRegisterEvent event);\n }\n\n public interface ObjectRegisterEvent {\n EventResult post(ConfigObjectRegisterEvent event);\n }\n\n public interface RegisterConfigManager{\n EventResult post(RegisterConfigManagersEvent event);\n }\n}" }, { "identifier": "Manager", "path": "common/src/main/java/net/vakror/jamesconfig/config/manager/Manager.java", "snippet": "public abstract class Manager<P> {\n public abstract void register();\n\n public abstract void register(P object);\n\n public abstract List<P> getAll();\n}" }, { "identifier": "SimpleManager", "path": "common/src/main/java/net/vakror/jamesconfig/config/manager/SimpleManager.java", "snippet": "public abstract class SimpleManager<P> extends Manager<P> {\n List<P> values = new ArrayList<>();\n\n @Override\n public void register(P object) {\n values.add(object);\n }\n\n @Override\n public List<P> getAll() {\n return values;\n }\n}" } ]
import dev.architectury.event.EventResult; import net.vakror.jamesconfig.config.config.object.ConfigObject; import net.vakror.jamesconfig.config.event.ConfigEvents; import net.vakror.jamesconfig.config.manager.Manager; import net.vakror.jamesconfig.config.manager.SimpleManager; import java.util.List;
985
package net.vakror.jamesconfig.config.manager.object; public abstract class ConfigObjectManager extends SimpleManager<ConfigObject> { @Override public void register() { new ModEvents(this); } public static class ModEvents { private ModEvents(ConfigObjectManager manager) {
package net.vakror.jamesconfig.config.manager.object; public abstract class ConfigObjectManager extends SimpleManager<ConfigObject> { @Override public void register() { new ModEvents(this); } public static class ModEvents { private ModEvents(ConfigObjectManager manager) {
ConfigEvents.OBJECT_REGISTER_EVENT.register(event -> {
1
2023-10-07 23:04:49+00:00
2k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/effect/MRPGCEffects.java
[ { "identifier": "MRPGCMod", "path": "src/main/java/net/more_rpg_classes/MRPGCMod.java", "snippet": "public class MRPGCMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"more_rpg_classes\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"more_rpg_classes\");\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tMRPGCItems.registerModItems();\n\t\tMRPGCGroup.registerItemGroups();\n\t\tMRPGCLootTableEntityModifiers.modifyLootEntityTables();\n\t\tMRPGCLootTableChestModifiers.modifyChestLootTables();\n\t\tMRPGCEffects.register();\n\t\tMRPGCBooks.register();\n\t\tCustomSpells.register();\n\t\tMRPGCEntityAttributes.registerAttributes();\n\t\tMoreParticles.register();\n\t\tModSounds.register();\n\t}\n}" }, { "identifier": "MRPGCEntityAttributes", "path": "src/main/java/net/more_rpg_classes/entity/attribute/MRPGCEntityAttributes.java", "snippet": "public class MRPGCEntityAttributes{\n\n public static final EntityAttribute INCOMING_DAMAGE_MODIFIER = createAttribute(\n \"incoming_damage_modifier\", 0.0f, -10.0f, 10.0f);\n\n\n\n public static EntityAttribute register(String id, EntityAttribute attribute){\n return Registry.register(Registries.ATTRIBUTE, new Identifier(MRPGCMod.MOD_ID, id), attribute);\n }\n private static EntityAttribute createAttribute(final String name, double base, double min, double max){\n return new ClampedEntityAttribute(\"attribute.name.generic.\" + MRPGCMod.MOD_ID + '.' +name, base, min, max).setTracked(true);\n }\n\n public static void registerAttributes(){\n register(\"incoming_damage_modifier\", INCOMING_DAMAGE_MODIFIER);\n }\n}" } ]
import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectCategory; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier; import net.more_rpg_classes.MRPGCMod; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.spell_engine.api.effect.ActionImpairing; import net.spell_engine.api.effect.EntityActionsAllowed; import net.spell_engine.api.effect.RemoveOnHit; import net.spell_engine.api.effect.Synchronized; import net.spell_power.api.MagicSchool; import net.spell_power.api.SpellPower;
792
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION)
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION)
.addAttributeModifier(MRPGCEntityAttributes.INCOMING_DAMAGE_MODIFIER, "0bf30a36-798a-450d-bd74-959910e6778e",
1
2023-10-14 12:44:07+00:00
2k
pasindusampath/Spring-Boot-Final
Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/service/impl/TravelPackageServiceIMPL.java
[ { "identifier": "TravelPackageDTO", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/dto/TravelPackageDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class TravelPackageDTO{\n private String id;\n private int hotelCount;\n private int areaCount;\n private double estimatedPrice;\n private String category;\n private int dayCount;\n}" }, { "identifier": "TravelPackage", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/entity/TravelPackage.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class TravelPackage extends SuperEntity{\n @Id\n private String id;\n private int hotelCount;\n private int areaCount;\n private double estimatedPrice;\n private String category;\n private int dayCount;\n}" }, { "identifier": "DeleteFailException", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/exception/DeleteFailException.java", "snippet": "public class DeleteFailException extends Exception{\n public DeleteFailException(String message){\n super(message);\n }\n\n public DeleteFailException(String message, Throwable cause){\n super(message,cause);\n }\n}" }, { "identifier": "NotFoundException", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/exception/NotFoundException.java", "snippet": "public class NotFoundException extends Exception{\n\n public NotFoundException(String message){\n super(message);\n }\n\n public NotFoundException(String message, Throwable cause){\n super(message,cause);\n }\n}" }, { "identifier": "SaveFailException", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/exception/SaveFailException.java", "snippet": "public class SaveFailException extends Exception{\n public SaveFailException(String message){\n super(message);\n }\n\n public SaveFailException(String message,Throwable cause){\n super(message,cause);\n }\n}" }, { "identifier": "UpdateFailException", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/exception/UpdateFailException.java", "snippet": "public class UpdateFailException extends Exception{\n public UpdateFailException(String message){\n super(message);\n }\n\n public UpdateFailException(String message, Throwable cause){\n super(message,cause);\n }\n}" }, { "identifier": "TravelPackageRepo", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/repo/TravelPackageRepo.java", "snippet": "public interface TravelPackageRepo extends CrudRepository<TravelPackage, String> {\n List<TravelPackage> findByCategory(String category);\n List<TravelPackage> findAll();\n\n}" }, { "identifier": "TravelPackageService", "path": "Travel Package Micro Service/src/main/java/lk/ijse/gdse63/spring_final/travel_package_micro_service/service/TravelPackageService.java", "snippet": "public interface TravelPackageService {\n\n public String save(TravelPackageDTO obj) throws SaveFailException;\n void update(TravelPackageDTO obj) throws UpdateFailException;\n void delete(String id) throws DeleteFailException;\n List<TravelPackageDTO> getPackagesByCategory(String category);\n TravelPackageDTO fidById(String id) throws NotFoundException;\n List<TravelPackageDTO> findByCategory(String category) throws NotFoundException;\n String generateNextId();\n\n List<TravelPackageDTO> getAll() throws NotFoundException;\n}" } ]
import lk.ijse.gdse63.spring_final.travel_package_micro_service.dto.TravelPackageDTO; import lk.ijse.gdse63.spring_final.travel_package_micro_service.entity.TravelPackage; import lk.ijse.gdse63.spring_final.travel_package_micro_service.exception.DeleteFailException; import lk.ijse.gdse63.spring_final.travel_package_micro_service.exception.NotFoundException; import lk.ijse.gdse63.spring_final.travel_package_micro_service.exception.SaveFailException; import lk.ijse.gdse63.spring_final.travel_package_micro_service.exception.UpdateFailException; import lk.ijse.gdse63.spring_final.travel_package_micro_service.repo.TravelPackageRepo; import lk.ijse.gdse63.spring_final.travel_package_micro_service.service.TravelPackageService; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.TreeSet;
1,132
package lk.ijse.gdse63.spring_final.travel_package_micro_service.service.impl; @Service public class TravelPackageServiceIMPL implements TravelPackageService { TravelPackageRepo travelPackageRepo; ModelMapper modelMapper; public TravelPackageServiceIMPL(TravelPackageRepo travelPackageRepo, ModelMapper modelMapper) { this.travelPackageRepo = travelPackageRepo; this.modelMapper = modelMapper; } @Override public String save(TravelPackageDTO obj) throws SaveFailException { try { String id = generateNextId(); obj.setId(id);
package lk.ijse.gdse63.spring_final.travel_package_micro_service.service.impl; @Service public class TravelPackageServiceIMPL implements TravelPackageService { TravelPackageRepo travelPackageRepo; ModelMapper modelMapper; public TravelPackageServiceIMPL(TravelPackageRepo travelPackageRepo, ModelMapper modelMapper) { this.travelPackageRepo = travelPackageRepo; this.modelMapper = modelMapper; } @Override public String save(TravelPackageDTO obj) throws SaveFailException { try { String id = generateNextId(); obj.setId(id);
TravelPackage map = modelMapper.map(obj, TravelPackage.class);
1
2023-10-15 06:40:35+00:00
2k
Nilan-Dinushka/IJSE-Employee-Management-System
IJSE-EAS/src/main/java/lk/ijse/dep11/EAS/controller/LoginFormController.java
[ { "identifier": "EmployeeDataAccess", "path": "IJSE-EAS/src/main/java/lk/ijse/dep11/EAS/db/EmployeeDataAccess.java", "snippet": "public class EmployeeDataAccess {\n private static final PreparedStatement STM_INSERT;\n private static final PreparedStatement STM_UPDATE;\n private static final PreparedStatement STM_DELETE;\n private static final PreparedStatement STM_GET_ROLE;\n private static final PreparedStatement STM_GET_NAME;\n private static final PreparedStatement STM_GET_ALL;\n private static final PreparedStatement STM_GET_LAST_ID;\n private static final PreparedStatement STM_GET_USER;\n\n static {\n\n try {\n Connection connection = SingleConnectionDataSource.getInstance().getConnection();\n STM_INSERT = connection.prepareStatement(\"INSERT INTO employee (id, password, name, nic, role, username, contact, branch_id, employment_status) VALUES (?,?,?,?,?,?,?,?,?,?)\");\n STM_UPDATE = connection.prepareStatement(\"UPDATE employee SET password=?,name=?,nic=?,role=?,username=?,contact=?,branch_id=?,employment_status=? WHERE id=?\");\n STM_DELETE = connection.prepareStatement(\"DELETE FROM employee WHERE id=?\");\n STM_GET_ROLE = connection.prepareStatement(\"SELECT role FROM employee WHERE username=?\");\n STM_GET_NAME = connection.prepareStatement(\"SELECT name FROM employee WHERE username=?\");\n STM_GET_ALL = connection.prepareStatement(\"SELECT * FROM employee ORDER BY id\");\n STM_GET_LAST_ID = connection.prepareStatement(\"SELECT id FROM employee ORDER BY id DESC FETCH FIRST ROW ONLY\");\n STM_GET_USER = connection.prepareStatement(\"SELECT * FROM employee WHERE id=? AND password=?\");\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static List<Employee> getAllEmployee() throws SQLException {\n ResultSet rst = STM_GET_ALL.executeQuery();\n ArrayList<Employee> employeeList = new ArrayList<>();\n while(rst.next()){\n String id = rst.getString(\"id\");\n String password = rst.getString(\"password\");\n String name = rst.getString(\"name\");\n String nic = rst.getString(\"nic\");\n String role = rst.getString(\"role\");\n String username = rst.getString(\"username\");\n String contact = rst.getString(\"contact\");\n int branch_id = rst.getInt(\"branch_id\");\n String employment_status = rst.getString(\"employment_status\");\n employeeList.add(new Employee(id,name,username,password,nic,role,contact,branch_id,employment_status));\n }\n return employeeList;\n\n }\n\n public static ResultSet getUser(String id,String password) throws SQLException {\n STM_GET_USER.setString(1,id);\n STM_GET_USER.setString(2,password);\n ResultSet rst = STM_GET_USER.executeQuery();\n return rst;\n }\n}" }, { "identifier": "SingleConnectionDataSource", "path": "IJSE-EAS/src/main/java/lk/ijse/dep11/EAS/db/SingleConnectionDataSource.java", "snippet": "public class SingleConnectionDataSource {\n private static SingleConnectionDataSource instance;\n private final Connection connection;\n private SingleConnectionDataSource(){\n\n try {\n Properties properties = new Properties();\n properties.load(getClass().getResourceAsStream(\"/application.properties\"));\n String url = properties.getProperty(\"app.datasource.url\");\n String username = properties.getProperty(\"app.datasource.username\");\n String password = properties.getProperty(\"app.datasource.password\");\n connection = DriverManager.getConnection(url,username,password);\n generateSchema();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private void generateSchema() throws Exception {\n URL url = getClass().getResource(\"/schema.sql\");\n Path path = Paths.get(url.toURI());\n String dbScript = Files.readAllLines(path).stream().reduce((prevLine, currentLine) -> prevLine + currentLine).get();\n //String[] dbScriptArray = dbScript.split(\";\");\n /* for (String script : dbScriptArray) {\n\n }*/\n connection.createStatement().execute(dbScript);\n\n }\n\n public static SingleConnectionDataSource getInstance() {\n return (instance == null) ? instance = new SingleConnectionDataSource() : instance;\n }\n\n public Connection getConnection(){\n return connection;\n }\n}" } ]
import com.jfoenix.controls.JFXButton; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Hyperlink; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import lk.ijse.dep11.EAS.db.EmployeeDataAccess; import lk.ijse.dep11.EAS.db.SingleConnectionDataSource; import org.apache.commons.codec.digest.DigestUtils; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
1,149
package lk.ijse.dep11.EAS.controller; public class LoginFormController { public AnchorPane root; public TextField txtId; public PasswordField txtPassword; public JFXButton btnLogin; public Hyperlink lnkForgotPassword; public ResultSet rst; public void initialize(){ } public void btnLoginOnAction(ActionEvent actionEvent) { String id = txtId.getText().strip(); String password = txtPassword.getText().strip(); try {
package lk.ijse.dep11.EAS.controller; public class LoginFormController { public AnchorPane root; public TextField txtId; public PasswordField txtPassword; public JFXButton btnLogin; public Hyperlink lnkForgotPassword; public ResultSet rst; public void initialize(){ } public void btnLoginOnAction(ActionEvent actionEvent) { String id = txtId.getText().strip(); String password = txtPassword.getText().strip(); try {
rst = EmployeeDataAccess.getUser(id, DigestUtils.sha256Hex(password));
0
2023-10-11 18:35:18+00:00
2k
XATUOS/ChatRobo
src/test/java/VersionTest.java
[ { "identifier": "IVersion", "path": "src/main/java/dev/xatuos/chatrobo/api/util/IVersion.java", "snippet": "public interface IVersion {\n int getMajor();\n int getMinor();\n int getPatch();\n int getPreRelease();\n int getBuild();\n}" }, { "identifier": "Version", "path": "src/main/java/dev/xatuos/chatrobo/util/Version.java", "snippet": "public class Version implements IVersion, Comparable<IVersion> {\n private final int major;\n private final int minor;\n private final int patch;\n private final int preRelease;\n private final int build;\n\n public Version(int major, int minor, int patch, int preRelease, int build) {\n this.major = major;\n this.minor = minor;\n this.patch = patch;\n this.preRelease = preRelease;\n this.build = build;\n }\n\n public Version(int major, int minor, int patch, int preRelease) {\n this(major, minor, patch, preRelease, 0);\n }\n\n public Version(int major, int minor, int patch) {\n this(major, minor, patch, 0, 0);\n }\n\n public Version(int major, int minor) {\n this(major, minor, 0, 0, 0);\n }\n\n public Version(int major) {\n this(major, 0, 0, 0, 0);\n }\n\n /**\n * 解析版本号\n * 示例: 1.0.0-release.0+build.0\n * 1.0.0+build.0\n * 1.0.0-release.0\n * 1.0.0\n *\n * @param version 版本号\n * @return 版本对象\n */\n public static Version parse(String version) {\n Pattern pattern = Pattern.compile(\"^(\\\\d+)(\\\\.(\\\\d+)(\\\\.(\\\\d+))?)?(-release\\\\.\\\\d+)?(\\\\+build\\\\.\\\\d+)?$\");\n if (!pattern.matcher(version).find())\n throw new IllegalArgumentException(\"Invalid version: %s\".formatted(version));\n String[] split = version.split(\"[+\\\\-]\");\n String[] versionSplit = split[0].split(\"\\\\.\");\n int major = Integer.parseInt(versionSplit[0]);\n int minor = versionSplit.length > 1 ? Integer.parseInt(versionSplit[1]) : 0;\n int patch = versionSplit.length > 2 ? Integer.parseInt(versionSplit[2]) : 0;\n int preRelease = split.length > 1 ? Integer.parseInt(split[1].split(\"\\\\.\")[1]) : 0;\n int build = split.length > 2 ? Integer.parseInt(split[2].split(\"\\\\.\")[1]) : 0;\n return new Version(major, minor, patch, preRelease, build);\n }\n\n public int getMajor() {\n return major;\n }\n\n public int getMinor() {\n return minor;\n }\n\n public int getPatch() {\n return patch;\n }\n\n public int getPreRelease() {\n return preRelease;\n }\n\n public int getBuild() {\n return build;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder(\"%d.%d.%d\".formatted(major, minor, patch));\n if (preRelease != 0)\n builder.append(\"-release.%d\".formatted(preRelease));\n if (build != 0)\n builder.append(\"+build.%d\".formatted(build));\n return builder.toString();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Version version) {\n return major == version.major && minor == version.minor && patch == version.patch && preRelease == version.preRelease && build == version.build;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return major ^ minor ^ patch ^ preRelease ^ build;\n }\n\n @Override\n public int compareTo(@NotNull IVersion o) {\n if (major != o.getMajor())\n return major - o.getMajor();\n if (minor != o.getMinor())\n return minor - o.getMinor();\n if (patch != o.getPatch())\n return patch - o.getPatch();\n if (preRelease != o.getPreRelease())\n return preRelease - o.getPreRelease();\n return build - o.getBuild();\n }\n}" } ]
import dev.xatuos.chatrobo.api.util.IVersion; import dev.xatuos.chatrobo.util.Version; import java.util.regex.Pattern;
1,378
public class VersionTest { public static void main(String[] args) { Pattern pattern = Pattern.compile("^(\\d+)(\\.(\\d+)(\\.(\\d+))?)?$"); System.out.println(pattern.matcher("1.0.0-release.1+build.10").find()); System.out.println(pattern.matcher("1.0.0-release.1").find()); System.out.println(pattern.matcher("1.0.0+build.10").find()); System.out.println(pattern.matcher("1.0.0").find()); System.out.println(pattern.matcher("1.0").find()); System.out.println(pattern.matcher("1").find()); pattern = Pattern.compile("^(\\d+)(\\.(\\d+)(\\.(\\d+))?)?(-release\\.\\d+)?(\\+build\\.\\d+)?$"); System.out.println(pattern.matcher("1.0.0-release.1+build.10").find()); System.out.println(pattern.matcher("1.0.0-release.1").find()); System.out.println(pattern.matcher("1.0.0+build.10").find()); System.out.println(pattern.matcher("1.0.0").find()); System.out.println(pattern.matcher("1.0").find()); System.out.println(pattern.matcher("1").find());
public class VersionTest { public static void main(String[] args) { Pattern pattern = Pattern.compile("^(\\d+)(\\.(\\d+)(\\.(\\d+))?)?$"); System.out.println(pattern.matcher("1.0.0-release.1+build.10").find()); System.out.println(pattern.matcher("1.0.0-release.1").find()); System.out.println(pattern.matcher("1.0.0+build.10").find()); System.out.println(pattern.matcher("1.0.0").find()); System.out.println(pattern.matcher("1.0").find()); System.out.println(pattern.matcher("1").find()); pattern = Pattern.compile("^(\\d+)(\\.(\\d+)(\\.(\\d+))?)?(-release\\.\\d+)?(\\+build\\.\\d+)?$"); System.out.println(pattern.matcher("1.0.0-release.1+build.10").find()); System.out.println(pattern.matcher("1.0.0-release.1").find()); System.out.println(pattern.matcher("1.0.0+build.10").find()); System.out.println(pattern.matcher("1.0.0").find()); System.out.println(pattern.matcher("1.0").find()); System.out.println(pattern.matcher("1").find());
System.out.println(Version.parse("1.0.0-release.1+build.10"));
1
2023-10-14 03:23:23+00:00
2k
juzi45/XianTech
src/main/java/com/qq/xiantech/world/feature/ModConfiguredFeatures.java
[ { "identifier": "XianTech", "path": "src/main/java/com/qq/xiantech/XianTech.java", "snippet": "@Slf4j\n@Mod(XianTech.MOD_ID)\npublic class XianTech {\n\n /**\n * 模组ID,必须和 META-INF/mods.toml中保持一致\n */\n public static final String MOD_ID = \"xiantech\";\n\n public XianTech() {\n // Forge事件总线\n MinecraftForge.EVENT_BUS.register(this);\n\n // Mod事件总线\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // 添加监听方法\n modEventBus.addListener(this::commonSetup);\n modEventBus.addListener(this::addCreative);\n\n BlockInit.BLOCKS.register(modEventBus);\n ItemInit.ITEMS.register(modEventBus);\n TabInit.TABS.register(modEventBus);\n\n // mod加载的上下文中,注册自定义配置类\n ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, XianTechConfiguration.SPEC);\n }\n\n /**\n * mod 加载时的监听\n *\n * @param event FMLCommonSetupEvent\n */\n private void commonSetup(final FMLCommonSetupEvent event) {\n // Some common setup code\n log.info(\"HELLO FROM COMMON SETUP\");\n log.info(\"DIRT BLOCK >> {}\", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));\n\n if (XianTechConfiguration.logDirtBlock) {\n log.info(\"DIRT BLOCK >> {}\", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));\n }\n\n log.info(XianTechConfiguration.magicNumberIntroduction + XianTechConfiguration.magicNumber);\n\n XianTechConfiguration.items.forEach((item) -> log.info(\"ITEM >> {}\", item.toString()));\n }\n\n /**\n * Add the example block item to the building blocks tab\n *\n * @param event BuildCreativeModeTabContentsEvent\n */\n private void addCreative(BuildCreativeModeTabContentsEvent event) {\n\n }\n\n\n /**\n * 订阅 EventBus 上的事件\n */\n @SubscribeEvent\n public void allEvent(Event event) {\n if (event instanceof RegisterEvent) {\n log.info(\"Event {}\", event);\n }\n }\n\n /**\n * 实例事件\n *\n * @param event ServerStartingEvent\n */\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event) {\n // Do something when the server starts\n log.info(\"HELLO from server starting\");\n }\n\n\n}" }, { "identifier": "BlockInit", "path": "src/main/java/com/qq/xiantech/block/BlockInit.java", "snippet": "public class BlockInit {\n\n /**\n * 延迟注册器(方块)\n */\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, XianTech.MOD_ID);\n\n /**\n * 延迟注册器(物品)\n */\n public static final DeferredRegister<Item> ITEMS = ItemInit.ITEMS;\n\n public static final RegistryObject<Block> STRING_CRYSTAL_ORE = register(\"string_crystal_ore\", StringCrystalOre::new,\n object -> () -> new StringCrystalOreItem(object.get()));\n\n public static final RegistryObject<Block> DEEP_SLATE_STRING_CRYSTAL_ORE = register(\"deep_slate_string_crystal_ore\", DeepSlateStringCrystalOre::new,\n object -> () -> new DeepSlateStringCrystalOreItem(object.get()));\n\n /**\n * 注册(方块+物品)\n *\n * @param name 注册 ID\n * @param block 方块 Supplier\n * @param item 物品 Supplier\n * @param <T> ? extends Block\n * @return 注册对象\n */\n private static <T extends Block> RegistryObject<T> register(final String name,\n final Supplier<? extends T> block,\n Function<RegistryObject<T>, Supplier<? extends Item>> item) {\n RegistryObject<T> obj = registerBlock(name, block);\n ITEMS.register(name, item.apply(obj));\n return obj;\n }\n\n\n /**\n * 注册(方块)\n *\n * @param name 注册 ID\n * @param block 方块 Supplier\n * @param <T> ? extends Block\n * @return 注册对象\n */\n private static <T extends Block> RegistryObject<T> registerBlock(final String name,\n final Supplier<? extends T> block) {\n return BLOCKS.register(name, block);\n }\n\n\n}" } ]
import com.qq.xiantech.XianTech; import com.qq.xiantech.block.BlockInit; import net.minecraft.core.registries.Registries; import net.minecraft.data.worldgen.BootstapContext; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.OreConfiguration; import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest; import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; import java.util.List;
1,562
package com.qq.xiantech.world.feature; /** * 注册-矿石生成类型 * * @author Pig-Gua * @date 2023-10-18 */ public class ModConfiguredFeatures { // 注意fantom_ore要和数据包名称保持一致 public static final ResourceKey<ConfiguredFeature<?, ?>> FANTOM_ORES = registerKey("string_crystal_ore"); public static void bootstrap(BootstapContext<ConfiguredFeature<?, ?>> context) { RuleTest stoneReplaceabeles = new TagMatchTest(BlockTags.STONE_ORE_REPLACEABLES); RuleTest deepslateReplaceabeles = new TagMatchTest(BlockTags.DEEPSLATE_ORE_REPLACEABLES); RuleTest netherrackReplaceabeles = new BlockMatchTest(Blocks.NETHERRACK); RuleTest endReplaceabeles = new BlockMatchTest(Blocks.END_STONE); //将我们第一步的两种矿石分别填入其中 List<OreConfiguration.TargetBlockState> overworldFantomOres = List.of(OreConfiguration.target(stoneReplaceabeles,
package com.qq.xiantech.world.feature; /** * 注册-矿石生成类型 * * @author Pig-Gua * @date 2023-10-18 */ public class ModConfiguredFeatures { // 注意fantom_ore要和数据包名称保持一致 public static final ResourceKey<ConfiguredFeature<?, ?>> FANTOM_ORES = registerKey("string_crystal_ore"); public static void bootstrap(BootstapContext<ConfiguredFeature<?, ?>> context) { RuleTest stoneReplaceabeles = new TagMatchTest(BlockTags.STONE_ORE_REPLACEABLES); RuleTest deepslateReplaceabeles = new TagMatchTest(BlockTags.DEEPSLATE_ORE_REPLACEABLES); RuleTest netherrackReplaceabeles = new BlockMatchTest(Blocks.NETHERRACK); RuleTest endReplaceabeles = new BlockMatchTest(Blocks.END_STONE); //将我们第一步的两种矿石分别填入其中 List<OreConfiguration.TargetBlockState> overworldFantomOres = List.of(OreConfiguration.target(stoneReplaceabeles,
BlockInit.STRING_CRYSTAL_ORE.get().defaultBlockState()),
1
2023-10-13 12:32:28+00:00
2k
uku3lig/ukuwayplus
src/main/java/net/uku3lig/ukuway/mixin/MixinEntityRenderer.java
[ { "identifier": "FriendListManager", "path": "src/main/java/net/uku3lig/ukuway/ui/FriendListManager.java", "snippet": "public class FriendListManager {\n @Getter\n private static final Set<String> friends = new HashSet<>();\n\n private static GenericContainerScreenHandler oldHandler = null;\n private static long ticksElapsed = 0;\n\n @Getter\n private static boolean init = false;\n\n public static void tick() {\n if (MinecraftClient.getInstance().currentScreen instanceof GenericContainerScreen containerScreen) {\n checkFriends(containerScreen);\n } else if (ticksElapsed >= 50 && !init && MinecraftClient.getInstance().player != null) {\n init = true;\n MinecraftClient.getInstance().player.networkHandler.sendChatCommand(\"friend\");\n }\n\n ticksElapsed++;\n }\n\n private static void checkFriends(GenericContainerScreen containerScreen) {\n long count = containerScreen.getScreenHandler().getStacks().stream().map(ItemStack::getItem).filter(Items.PLAYER_HEAD::equals).count();\n if (count == friends.size() || count <= 1) {\n return; // friend list didn't change, no need to check\n }\n\n init = true;\n\n GenericContainerScreenHandler handler = containerScreen.getScreenHandler();\n if (oldHandler != null && oldHandler == handler) return;\n oldHandler = handler;\n\n Optional<Slot> nextPageSlot = handler.slots.stream().filter(slot -> slot.getStack().isOf(Items.PAPER)\n && slot.getStack().getNbt() != null && slot.getStack().getNbt().asString().contains(\"→\"))\n .findFirst();\n\n CompletableFuture.runAsync(() -> {\n for (ItemStack itemStack : handler.getStacks()) {\n NbtCompound nbt = itemStack.getNbt();\n if (nbt == null || !itemStack.isOf(Items.PLAYER_HEAD) || nbt.toString().contains(\"Left click to Accept\")) {\n continue;\n }\n\n NbtCompound skullOwner = nbt.getCompound(\"SkullOwner\");\n String name = skullOwner.getString(\"Name\").toLowerCase(Locale.ROOT);\n if (!name.isBlank()) friends.add(name);\n }\n });\n\n nextPageSlot.ifPresentOrElse(slot -> containerScreen.onMouseClick(slot, 0, 0, SlotActionType.PICKUP),\n () -> MinecraftClient.getInstance().setScreen(null));\n }\n\n private FriendListManager() {\n }\n}" }, { "identifier": "Chars", "path": "src/main/java/net/uku3lig/ukuway/util/Chars.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum Chars {\n DISC(\"\\uE010\", null),\n FRIEND_BADGE(\"\\uE002\", \"tooltip.hp.friend\"),\n SETTINGS_ICON(\"\\uEF01\", null);\n\n private final String character;\n private final String translationKey;\n\n private static final Identifier FONT = new Identifier(\"ukuwayplus\", \"text\");\n\n public MutableText with(Text next) {\n MutableText text = Text.literal(character).styled(s -> s.withFont(FONT).withFormatting(Formatting.WHITE));\n\n if (translationKey != null) {\n Text hoverText = Text.translatable(translationKey).styled(s2 -> s2.withColor(Formatting.GOLD));\n text = text.styled(s -> s.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText)));\n }\n\n return Text.empty().append(text).append(next);\n }\n\n public MutableText formatted() {\n return with(Text.empty());\n }\n}" } ]
import net.minecraft.client.render.entity.EntityRenderer; import net.minecraft.entity.Entity; import net.minecraft.text.Text; import net.uku3lig.ukuway.ui.FriendListManager; import net.uku3lig.ukuway.util.Chars; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; import java.util.Locale;
1,071
package net.uku3lig.ukuway.mixin; @Mixin(EntityRenderer.class) public abstract class MixinEntityRenderer { @ModifyArgs(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/entity/EntityRenderer;renderLabelIfPresent(Lnet/minecraft/entity/Entity;Lnet/minecraft/text/Text;Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;I)V")) public void renderLabel(Args args) { Entity entity = args.get(0); Text text = args.get(1);
package net.uku3lig.ukuway.mixin; @Mixin(EntityRenderer.class) public abstract class MixinEntityRenderer { @ModifyArgs(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/entity/EntityRenderer;renderLabelIfPresent(Lnet/minecraft/entity/Entity;Lnet/minecraft/text/Text;Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;I)V")) public void renderLabel(Args args) { Entity entity = args.get(0); Text text = args.get(1);
if (FriendListManager.getFriends().contains(entity.getEntityName().toLowerCase(Locale.ROOT))) {
0
2023-10-07 00:02:04+00:00
2k
YumiProject/yumi-gradle-licenser
src/main/java/dev/yumi/gradle/licenser/task/JavaSourceBasedTask.java
[ { "identifier": "HeaderComment", "path": "src/main/java/dev/yumi/gradle/licenser/api/comment/HeaderComment.java", "snippet": "public interface HeaderComment {\n\t/**\n\t * Attempts to find the header comment and extract it from the given source.\n\t *\n\t * @param source the source\n\t * @return the read result\n\t */\n\t@Contract(pure = true)\n\t@NotNull Result readHeaderComment(@NotNull String source);\n\n\t/**\n\t * Extracts the line separator used for the given source string.\n\t *\n\t * @param source the source string\n\t * @return the line separator\n\t */\n\t@Contract(pure = true)\n\tdefault @NotNull String extractLineSeparator(@NotNull String source) {\n\t\tint firstNewLineIndex = source.indexOf('\\n');\n\n\t\tif (firstNewLineIndex == -1) {\n\t\t\treturn System.lineSeparator();\n\t\t} else {\n\t\t\tif (firstNewLineIndex != 0 && source.charAt(firstNewLineIndex - 1) == '\\r')\n\t\t\t\treturn \"\\r\\n\";\n\t\t\telse\n\t\t\t\treturn \"\\n\";\n\t\t}\n\t}\n\n\t/**\n\t * Formats the given header to the proper comment format.\n\t *\n\t * @param header the header comment to format\n\t * @param separator the line separator to use\n\t * @return the formatted header comment\n\t */\n\t@NotNull String writeHeaderComment(List<String> header, String separator);\n\n\t/**\n\t * Represents a header comment parsing result.\n\t *\n\t * @param start the start index of the parsed header comment\n\t * @param end the end index of the parsed header comment\n\t * @param existing the parsed header comment lines if found, or {@code null} otherwise\n\t * @param separator the line separator used in the parsed file\n\t */\n\trecord Result(int start, int end, @Nullable List<String> existing, @NotNull String separator) {\n\t}\n}" }, { "identifier": "HeaderCommentManager", "path": "src/main/java/dev/yumi/gradle/licenser/api/comment/HeaderCommentManager.java", "snippet": "public class HeaderCommentManager {\n\tprivate final Map<PatternSet, HeaderComment> headers = new HashMap<>();\n\n\tpublic HeaderCommentManager() {\n\t\tthis.register(new PatternSet()\n\t\t\t\t\t\t.include(\n\t\t\t\t\t\t\t\t\"**/*.c\",\n\t\t\t\t\t\t\t\t\"**/*.cpp\",\n\t\t\t\t\t\t\t\t\"**/*.cxx\",\n\t\t\t\t\t\t\t\t\"**/*.h\",\n\t\t\t\t\t\t\t\t\"**/*.hpp\",\n\t\t\t\t\t\t\t\t\"**/*.hxx\",\n\t\t\t\t\t\t\t\t\"**/*.java\",\n\t\t\t\t\t\t\t\t\"**/*.kt\",\n\t\t\t\t\t\t\t\t\"**/*.kts\",\n\t\t\t\t\t\t\t\t\"**/*.scala\"\n\t\t\t\t\t\t),\n\t\t\t\tCStyleHeaderComment.INSTANCE\n\t\t);\n\t}\n\n\t/**\n\t * Registers a header comment implementation for a given file pattern.\n\t *\n\t * @param filePattern the file pattern to match files for which the given header comment implementation applies\n\t * @param headerComment the header comment implementation\n\t */\n\tpublic void register(@NotNull PatternSet filePattern, @NotNull HeaderComment headerComment) {\n\t\tthis.headers.put(filePattern, headerComment);\n\t}\n\n\t/**\n\t * Finds the header comment implementation to use for the given file.\n\t *\n\t * @param file the file\n\t * @return the header comment implementation if a suitable one could be found, or {@code null} otherwise\n\t */\n\tpublic @Nullable HeaderComment findHeaderComment(@NotNull FileTreeElement file) {\n\t\tfor (var entry : this.headers.entrySet()) {\n\t\t\tif (entry.getKey().getAsSpec().isSatisfiedBy(file)) {\n\t\t\t\treturn entry.getValue();\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n}" } ]
import dev.yumi.gradle.licenser.api.comment.HeaderComment; import dev.yumi.gradle.licenser.api.comment.HeaderCommentManager; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.util.PatternFilterable; import org.jetbrains.annotations.ApiStatus; import java.io.IOException; import java.nio.file.Path;
1,204
/* * Copyright 2023 Yumi Project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package dev.yumi.gradle.licenser.task; /** * Represents a task that acts on a given Java project source set. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ @ApiStatus.Internal public abstract class JavaSourceBasedTask extends DefaultTask { protected final SourceSet sourceSet; protected final PatternFilterable patternFilterable; protected JavaSourceBasedTask(SourceSet sourceSet, PatternFilterable patternFilterable) { this.sourceSet = sourceSet; this.patternFilterable = patternFilterable; } /** * Executes the given action to all matched files. * * @param headerCommentManager the header comment manager to find out the header comments of files * @param consumer the action to execute on a given file */
/* * Copyright 2023 Yumi Project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package dev.yumi.gradle.licenser.task; /** * Represents a task that acts on a given Java project source set. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ @ApiStatus.Internal public abstract class JavaSourceBasedTask extends DefaultTask { protected final SourceSet sourceSet; protected final PatternFilterable patternFilterable; protected JavaSourceBasedTask(SourceSet sourceSet, PatternFilterable patternFilterable) { this.sourceSet = sourceSet; this.patternFilterable = patternFilterable; } /** * Executes the given action to all matched files. * * @param headerCommentManager the header comment manager to find out the header comments of files * @param consumer the action to execute on a given file */
void execute(HeaderCommentManager headerCommentManager, SourceConsumer consumer) {
1
2023-10-08 20:51:43+00:00
2k
Thenuka22/BakerySalesnOrdering_System
BakeryPosSystem/src/bakerypossystem/View/ManagePanel.java
[ { "identifier": "DatabaseConnector", "path": "BakeryPosSystem/src/bakerypossystem/Model/DatabaseConnector.java", "snippet": "public class DatabaseConnector {\n private Connection connection;\n\n public DatabaseConnector() {\n // database connection \n try {\n Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Load the MySQL driver\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/bakeryshop\", \"root\", \"\");\n } catch (ClassNotFoundException | SQLException e) {\n }\n }\n\n public ResultSet retrieveData(String query) {\n ResultSet resultSet = null;\n try {\n// String query = \"SELECT Name,Price FROM bakeryitem\";\n PreparedStatement statement = connection.prepareStatement(query);\n resultSet = statement.executeQuery();\n } catch (SQLException e) {\n }\n return resultSet;\n }\n public Connection getConnection() {\n return connection;\n }\n\n public void closeConnection() {\n try {\n if (connection != null) {\n connection.close();\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n}\n\n\n}" }, { "identifier": "PriceUpdater", "path": "BakeryPosSystem/src/bakerypossystem/Model/PriceUpdater.java", "snippet": "public class PriceUpdater {\n private final Connection connection;\n private JComboBox<String> IDnumDropdown;\n private JTextField OldPriceTextArea;\n private final DatabaseConnector databaseConnector;\n \n\n public PriceUpdater(Connection connection) {\n this.connection = connection;\n databaseConnector = new DatabaseConnector();\n }\n public void initializeComponents(JComboBox<String> comboBox, JTextField textArea) {\n IDnumDropdown = comboBox;\n OldPriceTextArea = textArea ;\n\n // dropdown \n populatIDNumbers();\n\n // Add an ActionListener to the dropdown to display order details when an order is selected\n IDnumDropdown.addActionListener(e -> {\n String selectedOrderNumber = (String) IDnumDropdown.getSelectedItem();\n \n displayOrderDetails(selectedOrderNumber);\n });\n }\n public void populatIDNumbers() {\n IDnumDropdown.removeAllItems(); // Clear existing items\n \n String query = \"SELECT itemID FROM bakeryitem\";\n ResultSet resultSet = databaseConnector.retrieveData(query);\n\n if (resultSet != null) {\n try {\n while (resultSet.next()) {\n String orderNumber = resultSet.getString(\"itemID\");\n IDnumDropdown.addItem(orderNumber);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n }\n public void displayOrderDetails(String idNumber) {\n OldPriceTextArea.setText(\"\"); // Clear existing text\n \n String query = \"SELECT Name,Price FROM bakeryitem WHERE itemID = '\" + idNumber + \"'\";\n ResultSet resultSet = databaseConnector.retrieveData(query);\n\n if (resultSet != null) {\n StringBuilder details = new StringBuilder();\n\n try {\n while (resultSet.next()) {\n String itemName = resultSet.getString(\"Name\");\n int quantity = resultSet.getInt(\"Price\");\n details.append(itemName).append(\": \").append(quantity).append(\"\\n\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n OldPriceTextArea.setText(details.toString());\n }\n }\n\n public void incrementPrices(double incrementValue) {\n try {\n String updateQuery = \"UPDATE bakeryitem SET Price = Price + ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuery);\n preparedStatement.setDouble(1, incrementValue);\n preparedStatement.executeUpdate();\n JOptionPane.showMessageDialog(null, \"Price Updated Succesfuly!\");\n } catch (SQLException e) {\n e.printStackTrace();\n JOptionPane.showMessageDialog(null, \"Price Update Failed!\");\n }\n }\n\n public void decrementPrices(double decrementValue) {\n try {\n String updateQuery = \"UPDATE bakeryitem SET Price = Price - ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuery);\n preparedStatement.setDouble(1, decrementValue);\n preparedStatement.executeUpdate();\n JOptionPane.showMessageDialog(null, \"Price Updated Succesfuly!\");\n } catch (SQLException e) {\n e.printStackTrace();\n JOptionPane.showMessageDialog(null, \"Price Update Failed!\");\n }\n }\n public void UpdatePrices(BigDecimal decrementValue,String id) {\n try {\n String updateQuery = \"UPDATE bakeryitem SET Price = ? Where ItemID = '\" + id + \"'\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuery);\n preparedStatement.setBigDecimal(1, decrementValue);\n preparedStatement.executeUpdate();\n JOptionPane.showMessageDialog(null, \"Price Updated Succesfuly!\");\n } catch (SQLException e) {\n e.printStackTrace();\n JOptionPane.showMessageDialog(null, \"Price Update Failed!\");\n }\n }\n}" } ]
import bakerypossystem.Model.DatabaseConnector; import bakerypossystem.Model.PriceUpdater; import com.formdev.flatlaf.FlatDarkLaf; import java.awt.event.KeyEvent; import java.math.BigDecimal; import java.sql.Connection; import javax.swing.JOptionPane;
1,264
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JPanel.java to edit this template */ package bakerypossystem.View; /** * * @author thenu */ public class ManagePanel extends javax.swing.JPanel { /** * Creates new form ManagePanel */ private final PriceUpdater pud; public ManagePanel() { try { FlatDarkLaf.setup(); } catch (Exception e) { printStackTrace(e); } initComponents(); showolddpricetxt.setEditable(false);
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JPanel.java to edit this template */ package bakerypossystem.View; /** * * @author thenu */ public class ManagePanel extends javax.swing.JPanel { /** * Creates new form ManagePanel */ private final PriceUpdater pud; public ManagePanel() { try { FlatDarkLaf.setup(); } catch (Exception e) { printStackTrace(e); } initComponents(); showolddpricetxt.setEditable(false);
DatabaseConnector dbConnector = new DatabaseConnector();
0
2023-10-11 16:55:32+00:00
2k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/handler/TardisHandlersManager.java
[ { "identifier": "TardisTickable", "path": "src/main/java/mdteam/ait/tardis/TardisTickable.java", "snippet": "public interface TardisTickable { // todo, actually use this class where its needed eg desktop, exterior, console, etc.\n void tick(MinecraftServer server);\n\n void tick(ServerWorld world);\n void tick(MinecraftClient client);\n void startTick(MinecraftServer server);\n}" }, { "identifier": "SequenceHandler", "path": "src/main/java/mdteam/ait/tardis/control/sequences/SequenceHandler.java", "snippet": "public class SequenceHandler extends TardisLink {\n private static final int REMOVE_CONTROL_TICK = FlightUtil.convertSecondsToTicks(2);\n\n private RecentControls recent;\n private int ticks = 0;\n\n public SequenceHandler(UUID tardisId) {\n super(tardisId);\n recent = new RecentControls(tardisId);\n }\n\n public void add(Control control) {\n recent.add(control);\n ticks = 0;\n this.compareToSequences();\n }\n\n private void compareToSequences() {\n for (Sequence sequence : SequenceRegistry.REGISTRY) {\n if (sequence.isFinished(this.recent))\n sequence.execute(this.tardis());\n }\n }\n\n @Override\n public void tick(MinecraftServer server) {\n super.tick(server);\n\n ticks++;\n if (ticks >= REMOVE_CONTROL_TICK) {\n recent.clear();\n ticks = 0;\n }\n }\n}" }, { "identifier": "LoyaltyHandler", "path": "src/main/java/mdteam/ait/tardis/handler/loyalty/LoyaltyHandler.java", "snippet": "public class LoyaltyHandler extends TardisLink { // todo currently will be useless as will only be finished when all features have been added.\n private HashMap<UUID, Loyalty> data;\n\n public LoyaltyHandler(UUID tardisId, HashMap<UUID, Loyalty> data) {\n super(tardisId);\n this.data = data;\n }\n\n public LoyaltyHandler(UUID tardis) {\n this(tardis, new HashMap<>());\n }\n\n public HashMap<UUID, Loyalty> data() {\n return this.data;\n }\n\n public void add(ServerPlayerEntity player) {\n this.add(player, Loyalty.NONE);\n }\n\n public void add(ServerPlayerEntity player, Loyalty loyalty) {\n this.data().put(player.getUuid(), loyalty);\n\n tardis().markDirty();\n }\n\n public Loyalty get(ServerPlayerEntity player) {\n return this.data().get(player.getUuid());\n }\n}" }, { "identifier": "PropertiesHolder", "path": "src/main/java/mdteam/ait/tardis/handler/properties/PropertiesHolder.java", "snippet": "public class PropertiesHolder extends TardisLink {\n private final HashMap<String, Object> data; // might replace the generic object with a property class that has impls eg Property.Boolean, etc\n\n public PropertiesHolder(UUID tardisId, HashMap<String, Object> data) {\n super(tardisId);\n this.data = data;\n }\n\n public PropertiesHolder(UUID tardis) {\n this(tardis, PropertiesHandler.createDefaultProperties());\n }\n\n public HashMap<String, Object> getData() {\n return this.data;\n }\n}" } ]
import mdteam.ait.tardis.Exclude; import mdteam.ait.tardis.TardisTickable; import mdteam.ait.tardis.control.sequences.SequenceHandler; import mdteam.ait.tardis.handler.loyalty.LoyaltyHandler; import mdteam.ait.tardis.handler.properties.PropertiesHolder; import net.minecraft.server.MinecraftServer; import java.util.ArrayList; import java.util.List; import java.util.UUID;
926
package mdteam.ait.tardis.handler; public class TardisHandlersManager extends TardisLink { @Exclude private List<TardisLink> tickables = new ArrayList<>(); // Yup private DoorHandler door; private PropertiesHolder properties; private WaypointHandler waypoints;
package mdteam.ait.tardis.handler; public class TardisHandlersManager extends TardisLink { @Exclude private List<TardisLink> tickables = new ArrayList<>(); // Yup private DoorHandler door; private PropertiesHolder properties; private WaypointHandler waypoints;
private LoyaltyHandler loyalties;
2
2023-10-08 00:38:53+00:00
2k
jianjian3219/044_bookmanage2-public
nhXJH-common/src/main/java/com/nhXJH/common/utils/PageUtils.java
[ { "identifier": "PageDomain", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/page/PageDomain.java", "snippet": "public class PageDomain {\n /** 当前记录起始索引 */\n private Integer pageNum;\n\n /** 每页显示记录数 */\n private Integer pageSize;\n\n /** 排序列 */\n private String orderByColumn;\n\n /** 排序的方向desc或者asc */\n private String isAsc = \"asc\";\n\n /** 分页参数合理化 */\n private Boolean reasonable = true;\n\n public String getOrderBy() {\n if (StringUtils.isEmpty(orderByColumn)) {\n return \"\";\n }\n return StringUtils.toUnderScoreCase(orderByColumn) + \" \" + isAsc;\n }\n\n public Integer getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(Integer pageNum) {\n this.pageNum = pageNum;\n }\n\n public Integer getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize) {\n this.pageSize = pageSize;\n }\n\n public String getOrderByColumn() {\n return orderByColumn;\n }\n\n public void setOrderByColumn(String orderByColumn) {\n this.orderByColumn = orderByColumn;\n }\n\n public String getIsAsc() {\n return isAsc;\n }\n\n public void setIsAsc(String isAsc) {\n if (StringUtils.isNotEmpty(isAsc)) {\n // 兼容前端排序类型\n if (\"ascending\".equals(isAsc)) {\n isAsc = \"asc\";\n }\n else if (\"descending\".equals(isAsc)) {\n isAsc = \"desc\";\n }\n this.isAsc = isAsc;\n }\n }\n\n public Boolean getReasonable() {\n if (StringUtils.isNull(reasonable)) {\n return Boolean.TRUE;\n }\n return reasonable;\n }\n\n public void setReasonable(Boolean reasonable) {\n this.reasonable = reasonable;\n }\n}" }, { "identifier": "TableSupport", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/page/TableSupport.java", "snippet": "public class TableSupport {\n /**\n * 当前记录起始索引\n */\n public static final String PAGE_NUM = \"pageNum\";\n\n /**\n * 每页显示记录数\n */\n public static final String PAGE_SIZE = \"pageSize\";\n\n /**\n * 排序列\n */\n public static final String ORDER_BY_COLUMN = \"orderByColumn\";\n\n /**\n * 排序的方向 \"desc\" 或者 \"asc\".\n */\n public static final String IS_ASC = \"isAsc\";\n\n /**\n * 分页参数合理化\n */\n public static final String REASONABLE = \"reasonable\";\n\n /**\n * 封装分页对象\n */\n public static PageDomain getPageDomain() {\n PageDomain pageDomain = new PageDomain();\n pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));\n pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));\n pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));\n pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));\n pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));\n return pageDomain;\n }\n\n public static PageDomain buildPageRequest() {\n return getPageDomain();\n }\n}" }, { "identifier": "SqlUtil", "path": "nhXJH-common/src/main/java/com/nhXJH/common/utils/sql/SqlUtil.java", "snippet": "public class SqlUtil {\n /**\n * 定义常用的 sql关键字\n */\n public static String SQL_REGEX = \"select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare \";\n\n /**\n * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)\n */\n public static String SQL_PATTERN = \"[a-zA-Z0-9_\\\\ \\\\,\\\\.]+\";\n\n /**\n * 检查字符,防止注入绕过\n */\n public static String escapeOrderBySql(String value) {\n if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {\n throw new UtilException(\"参数不符合规范,不能进行查询\");\n }\n return value;\n }\n\n /**\n * 验证 order by 语法是否符合规范\n */\n public static boolean isValidOrderBySql(String value) {\n return value.matches(SQL_PATTERN);\n }\n\n /**\n * SQL关键字检查\n */\n public static void filterKeyword(String value) {\n if (StringUtils.isEmpty(value)) {\n return;\n }\n String[] sqlKeywords = StringUtils.split(SQL_REGEX, \"\\\\|\");\n for (int i = 0; i < sqlKeywords.length; i++) {\n if (StringUtils.indexOfIgnoreCase(value, sqlKeywords[i]) > -1) {\n throw new UtilException(\"参数存在SQL注入风险\");\n }\n }\n }\n}" } ]
import com.github.pagehelper.PageHelper; import com.nhXJH.common.core.page.PageDomain; import com.nhXJH.common.core.page.TableSupport; import com.nhXJH.common.utils.sql.SqlUtil;
1,364
package com.nhXJH.common.utils; /** * 分页工具类 * * @author nhXJH */ public class PageUtils extends PageHelper { /** * 设置请求分页数据 */ public static void startPage() {
package com.nhXJH.common.utils; /** * 分页工具类 * * @author nhXJH */ public class PageUtils extends PageHelper { /** * 设置请求分页数据 */ public static void startPage() {
PageDomain pageDomain = TableSupport.buildPageRequest();
1
2023-10-14 04:57:42+00:00
2k
quan100/quan
quan-app/quan-app-mobile-bff/src/main/java/cn/javaquan/app/mobile/bff/tools/convert/OpenToolsAssembler.java
[ { "identifier": "OpenToolsQuery", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/tools/OpenToolsQuery.java", "snippet": "@Data\npublic class OpenToolsQuery extends BasePage implements Serializable {\n\n private static final long serialVersionUID = 3495832154878623290L;\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 数据类型\n */\n private Integer dataType;\n\n}" }, { "identifier": "OpenToolsVO", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/tools/OpenToolsVO.java", "snippet": "@Data\npublic class OpenToolsVO implements Serializable {\n\n private static final long serialVersionUID = 3495832154878623290L;\n\n private Long id;\n\n /**\n * 图标\n */\n private String avatar;\n\n /**\n * 封面图\n */\n private String cover;\n\n /**\n * 备注\n */\n private String remarks;\n\n /**\n * 内容\n */\n private String content;\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 数据类型\n */\n private Integer dataType;\n\n /**\n * 列表类型\n */\n private Integer listType;\n\n /**\n * 状态,0:正常,1:审核中,2:审核不通过\n */\n private Integer status;\n\n /**\n * 跳转链接\n */\n private String jumpUrl;\n\n /**\n * 跳转类型\n * 1:站内资源\n * 2:站外资源\n */\n private Integer jumpType;\n\n /**\n * 排序\n */\n private Integer sort;\n\n /**\n * 创建人\n */\n private String createUser;\n\n /**\n * 创建人\n */\n private String updateUser;\n\n}" }, { "identifier": "ToolsDTO", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/tools/ToolsDTO.java", "snippet": "@Data\npublic class ToolsDTO implements Serializable {\n\n private static final long serialVersionUID = -137770378920503836L;\n\n /**\n * 自增主键\n */\n private Long id;\n\n /**\n * 图标地址\n */\n private String avatar;\n\n /**\n * 封面图\n */\n private String cover;\n\n /**\n * 备注\n */\n private String remarks;\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 数据类型\n */\n private Integer dataType;\n\n /**\n * 列表类型\n */\n private Integer listType;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n /**\n *\n */\n private String createUser;\n\n /**\n *\n */\n private String updateUser;\n\n /**\n * 状态,0:正常,1:审核中,2:审核不通过\n */\n private Integer status;\n\n /**\n * 删除状态,false:未删除,true:已删除\n */\n private Boolean delFlag;\n\n /**\n * 内容\n */\n private String content;\n\n /**\n * 内容跳转链接\n */\n private String jumpUrl;\n\n /**\n * 跳转类型\n */\n private Integer jumpType;\n\n /**\n * 排序\n */\n private Integer sort;\n\n}" }, { "identifier": "ToolsQuery", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/tools/ToolsQuery.java", "snippet": "@Data\npublic class ToolsQuery extends BasePage implements Serializable {\n\n private static final long serialVersionUID = 742833405930788595L;\n\n /**\n * 自增主键\n */\n private Long id;\n\n /**\n * 图标地址\n */\n private String avatar;\n\n /**\n * 封面图\n */\n private String cover;\n\n /**\n * 备注\n */\n private String remarks;\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 数据类型\n */\n private Integer dataType;\n\n /**\n * 列表类型\n */\n private Integer listType;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n /**\n *\n */\n private String createUser;\n\n /**\n *\n */\n private String updateUser;\n\n /**\n * 状态,0:正常,1:审核中,2:审核不通过\n */\n private Integer status;\n\n /**\n * 删除状态,false:未删除,true:已删除\n */\n private Boolean delFlag;\n\n /**\n * 内容\n */\n private String content;\n\n /**\n * 内容跳转链接\n */\n private String jumpUrl;\n\n /**\n * 跳转类型\n */\n private Integer jumpType;\n\n /**\n * 排序\n */\n private Integer sort;\n\n}" } ]
import cn.javaquan.app.common.module.tools.OpenToolsQuery; import cn.javaquan.app.common.module.tools.OpenToolsVO; import cn.javaquan.app.common.module.tools.ToolsDTO; import cn.javaquan.app.common.module.tools.ToolsQuery; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import java.util.List;
1,510
package cn.javaquan.app.mobile.bff.tools.convert; /** * @author wangquan */ @Mapper public interface OpenToolsAssembler { OpenToolsAssembler INSTANCE = Mappers.getMapper(OpenToolsAssembler.class);
package cn.javaquan.app.mobile.bff.tools.convert; /** * @author wangquan */ @Mapper public interface OpenToolsAssembler { OpenToolsAssembler INSTANCE = Mappers.getMapper(OpenToolsAssembler.class);
ToolsQuery toToolsQuery(OpenToolsQuery query);
0
2023-10-08 06:48:41+00:00
2k
Hartie95/AnimeGamesLua
GILua/src/main/java/org/anime_game_servers/gi_lua/script_lib/ScriptLib.java
[ { "identifier": "ExhibitionPlayType", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/ExhibitionPlayType.java", "snippet": "@LuaStatic\npublic enum ExhibitionPlayType {\n Challenge,\n Gallery,\n}" }, { "identifier": "FlowSuiteOperatePolicy", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/FlowSuiteOperatePolicy.java", "snippet": "@LuaStatic\npublic enum FlowSuiteOperatePolicy {\n DEFAULT,\n COMPLETE\n}" }, { "identifier": "GalleryProgressScoreType", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/temporary/GalleryProgressScoreType.java", "snippet": "@LuaStatic\npublic enum GalleryProgressScoreType {\n GALLERY_PROGRESS_SCORE_NONE,\n GALLERY_PROGRESS_SCORE_NO_DEGRADE\n}" }, { "identifier": "GalleryProgressScoreUIType", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/temporary/GalleryProgressScoreUIType.java", "snippet": "@LuaStatic\npublic enum GalleryProgressScoreUIType {\n GALLERY_PROGRESS_SCORE_UI_TYPE_NONE,\n GALLERY_PROGRESS_SCORE_UI_TYPE_BUOYANT_COMBAT,\n GALLERY_PROGRESS_SCORE_UI_TYPE_SUMO_STAGE,\n GALLERY_PROGRESS_SCORE_UI_TYPE_DIG,\n GALLERY_PROGRESS_SCORE_UI_TYPE_CRYSTAL_LINK,\n GALLERY_PROGRESS_SCORE_UI_TYPE_TREASURE;\n}" }, { "identifier": "luaToPos", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/utils/ScriptUtils.java", "snippet": "public static Vector luaToPos(LuaTable position){\n val result = new PositionImpl();\n if(position != null){\n result.setX(position.optInt(\"x\", 0));\n result.setY(position.optInt(\"y\", 0));\n result.setZ(position.optInt(\"z\", 0));\n }\n\n return result;\n}" }, { "identifier": "posToLua", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/utils/ScriptUtils.java", "snippet": "public static LuaTable posToLua(Vector position, LuaEngine engine){\n var result = engine.createTable();\n if(position != null){\n result.set(\"x\", position.getX());\n result.set(\"y\", position.getY());\n result.set(\"z\", position.getZ());\n } else {\n result.set(\"x\", 0);\n result.set(\"y\", 0);\n result.set(\"z\", 0);\n }\n\n return result;\n}" } ]
import io.github.oshai.kotlinlogging.KLogger; import io.github.oshai.kotlinlogging.KotlinLogging; import lombok.val; import org.anime_game_servers.core.base.annotations.lua.LuaStatic; import org.anime_game_servers.gi_lua.models.constants.*; import org.anime_game_servers.gi_lua.models.constants.ExhibitionPlayType; import org.anime_game_servers.gi_lua.models.constants.FlowSuiteOperatePolicy; import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreType; import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreUIType; import org.anime_game_servers.gi_lua.script_lib.handler.ScriptLibStaticHandler; import org.anime_game_servers.gi_lua.script_lib.handler.parameter.KillByConfigIdParams; import org.anime_game_servers.lua.engine.LuaTable; import static org.anime_game_servers.gi_lua.utils.ScriptUtils.luaToPos; import static org.anime_game_servers.gi_lua.utils.ScriptUtils.posToLua; import static org.anime_game_servers.gi_lua.script_lib.ScriptLibErrors.*;
1,515
package org.anime_game_servers.gi_lua.script_lib; @LuaStatic public class ScriptLib { /** * Context free functions */ private static KLogger scriptLogger = KotlinLogging.INSTANCE.logger(ScriptLib.class.getName()); public static ScriptLibStaticHandler staticHandler; public static void PrintLog(String msg) { staticHandler.PrintLog(msg); } public static int GetEntityType(int entityId){ return staticHandler.GetEntityType(entityId); } /** * Context independent functions */ public static void PrintContextLog(LuaContext context, String msg) { staticHandler.PrintContextLog(context, msg); } /** * GroupEventLuaContext functions */ public static void PrintGroupWarning(GroupEventLuaContext context, String msg) { context.getScriptLibHandler().PrintGroupWarning(context, msg); } public static int SetGadgetStateByConfigId(GroupEventLuaContext context, int configId, int gadgetState) { return context.getScriptLibHandler().SetGadgetStateByConfigId(context, configId, gadgetState); } public static int SetGroupGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId, int gadgetState) { return context.getScriptLibHandler().SetGroupGadgetStateByConfigId(context, groupId, configId, gadgetState); } public static int SetWorktopOptionsByGroupId(GroupEventLuaContext context, int groupId, int configId, Object optionsTable) { val options = context.getEngine().getTable(optionsTable); return context.getScriptLibHandler().SetWorktopOptionsByGroupId(context, groupId, configId, options); } public static int SetWorktopOptions(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().SetWorktopOptions(context, table); } public static int DelWorktopOptionByGroupId(GroupEventLuaContext context, int groupId, int configId, int option) { return context.getScriptLibHandler().DelWorktopOptionByGroupId(context, groupId, configId, option); } public static int DelWorktopOption(GroupEventLuaContext context, int var1){ return context.getScriptLibHandler().DelWorktopOption(context, var1); } // Some fields are guessed public static int AutoMonsterTide(GroupEventLuaContext context, int challengeIndex, int groupId, Integer[] ordersConfigId, int tideCount, int sceneLimit, int param6) { return context.getScriptLibHandler().AutoMonsterTide(context, challengeIndex, groupId, ordersConfigId, tideCount, sceneLimit, param6); } public static int GoToGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().GoToGroupSuite(context, groupId, suite); } public static int AddExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().AddExtraGroupSuite(context, groupId, suite); } public static int RemoveExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().RemoveExtraGroupSuite(context, groupId, suite); } public static int KillExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().KillExtraGroupSuite(context, groupId, suite); } public static int AddExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){
package org.anime_game_servers.gi_lua.script_lib; @LuaStatic public class ScriptLib { /** * Context free functions */ private static KLogger scriptLogger = KotlinLogging.INSTANCE.logger(ScriptLib.class.getName()); public static ScriptLibStaticHandler staticHandler; public static void PrintLog(String msg) { staticHandler.PrintLog(msg); } public static int GetEntityType(int entityId){ return staticHandler.GetEntityType(entityId); } /** * Context independent functions */ public static void PrintContextLog(LuaContext context, String msg) { staticHandler.PrintContextLog(context, msg); } /** * GroupEventLuaContext functions */ public static void PrintGroupWarning(GroupEventLuaContext context, String msg) { context.getScriptLibHandler().PrintGroupWarning(context, msg); } public static int SetGadgetStateByConfigId(GroupEventLuaContext context, int configId, int gadgetState) { return context.getScriptLibHandler().SetGadgetStateByConfigId(context, configId, gadgetState); } public static int SetGroupGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId, int gadgetState) { return context.getScriptLibHandler().SetGroupGadgetStateByConfigId(context, groupId, configId, gadgetState); } public static int SetWorktopOptionsByGroupId(GroupEventLuaContext context, int groupId, int configId, Object optionsTable) { val options = context.getEngine().getTable(optionsTable); return context.getScriptLibHandler().SetWorktopOptionsByGroupId(context, groupId, configId, options); } public static int SetWorktopOptions(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().SetWorktopOptions(context, table); } public static int DelWorktopOptionByGroupId(GroupEventLuaContext context, int groupId, int configId, int option) { return context.getScriptLibHandler().DelWorktopOptionByGroupId(context, groupId, configId, option); } public static int DelWorktopOption(GroupEventLuaContext context, int var1){ return context.getScriptLibHandler().DelWorktopOption(context, var1); } // Some fields are guessed public static int AutoMonsterTide(GroupEventLuaContext context, int challengeIndex, int groupId, Integer[] ordersConfigId, int tideCount, int sceneLimit, int param6) { return context.getScriptLibHandler().AutoMonsterTide(context, challengeIndex, groupId, ordersConfigId, tideCount, sceneLimit, param6); } public static int GoToGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().GoToGroupSuite(context, groupId, suite); } public static int AddExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().AddExtraGroupSuite(context, groupId, suite); } public static int RemoveExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().RemoveExtraGroupSuite(context, groupId, suite); } public static int KillExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().KillExtraGroupSuite(context, groupId, suite); } public static int AddExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){
if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){
1
2023-10-07 16:45:54+00:00
2k
ruislan/korderbook
src/jmh/java/com/ruislan/korderbook/java/OrderBookJavaPerformance.java
[ { "identifier": "Order", "path": "src/main/java/com/ruislan/korderbook/Order.java", "snippet": "public class Order {\n private final boolean isBuy;\n private final long price;\n private final long originQty;\n private long openQty;\n private final long createdAt;\n private long updatedAt;\n\n /**\n * @param isBuy 是否是买单\n * @param price 请使用最小单位,整数形式,如8.88->888, 8.888 -> 8888\n * @param qty 请使用最小单位,以整数形式,同上\n */\n public Order(boolean isBuy, long price, long qty) {\n this.isBuy = isBuy;\n this.price = price;\n this.originQty = qty;\n this.openQty = qty;\n createdAt = Instant.now().getEpochSecond();\n updatedAt = Instant.now().getEpochSecond();\n }\n\n public void fill(long qty) {\n openQty -= qty;\n updatedAt = Instant.now().getEpochSecond();\n }\n\n /**\n * price 为 0 是市价单, price 大于0 是限价单\n */\n public boolean isLimit() {\n return price > 0;\n }\n\n public boolean isFullFilled() {\n return openQty == 0L;\n }\n\n public boolean isBuy() {\n return isBuy;\n }\n\n public long getPrice() {\n return price;\n }\n\n public long getOriginQty() {\n return originQty;\n }\n\n public long getOpenQty() {\n return openQty;\n }\n\n public long getCreatedAt() {\n return createdAt;\n }\n\n public long getUpdatedAt() {\n return updatedAt;\n }\n}" }, { "identifier": "OrderBook", "path": "src/main/java/com/ruislan/korderbook/OrderBook.java", "snippet": "public interface OrderBook {\n void open();\n\n void close();\n\n String getSymbol(); //账簿标记,它是识别账簿的唯一标识\n\n void place(Order order); // 下单,下单之后会立刻进行匹配,如果没有完全把订单填满则放入order book,等待后面的市价或者限价单进行匹配\n\n void cancel(Order order); //取消订单\n\n long getSpread(); // 最低卖价减去最高买价\n\n long getMarketPrice(); //市场价,通常是最后一次成交价格\n\n Depth getBidsDepth(); //买方深度\n\n Depth getAsksDepth(); //卖方深度\n}" }, { "identifier": "OrderBookListener", "path": "src/main/java/com/ruislan/korderbook/OrderBookListener.java", "snippet": "public abstract class OrderBookListener implements EventListener {\n public void onCanceled(Order order) {}\n public void onCancelRejected(Order order, String reason) {}\n public void onLastPriceChanged(long price) {}\n public void onMatched(Order o1, Order o2, long price, long qty) {}\n public void onAccepted(Order order) {}\n public void onFullFilled(Order order) {}\n public void onRejected(Order order, String reason) {}\n}" } ]
import com.ruislan.korderbook.Order; import com.ruislan.korderbook.OrderBook; import com.ruislan.korderbook.OrderBookListener; import org.openjdk.jmh.annotations.*; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
930
package com.ruislan.korderbook.java; @State(Scope.Benchmark) public class OrderBookJavaPerformance { private OrderBook orderBook; private Lock lock; private Random random; @Setup public void prepare() {
package com.ruislan.korderbook.java; @State(Scope.Benchmark) public class OrderBookJavaPerformance { private OrderBook orderBook; private Lock lock; private Random random; @Setup public void prepare() {
orderBook = new OrderBookJavaImpl("simple", new OrderBookListener() {
2
2023-10-07 05:22:59+00:00
2k
jmaes12345/lhasa-kata
examples/java2/src/main/java/org/katas/Assess.java
[ { "identifier": "catToOutputDir", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static String catToOutputDir(String category) {\n\tswitch (category) {\n\t\tcase \"I\":\n\t\t\treturn CAT1_DIR;\n\t\tcase \"II\":\n\t\t\treturn CAT2_DIR;\n\t\tcase \"III\":\n\t\t\treturn CAT3_DIR;\n\t\tcase \"Unclassified\":\n\t\tdefault:\n\t\t\treturn UNCLASSIFIED_DIR;\n\t}\n}" }, { "identifier": "countFiles", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static int countFiles(String dirName) {\n\treturn countFiles(dirName, null);\n}" }, { "identifier": "foundInFiles", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static boolean foundInFiles(File[] files, String filename) {\n\tif (files == null || files.length == 0) {\n\t\treturn false;\n\t}\n\treturn Arrays.stream(files).anyMatch(file -> file.getName().equals(filename));\n}" }, { "identifier": "getTestCases", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static List<List<String>> getTestCases(String inputLocation) {\n\tvar inputDir = new File(inputLocation);\n\tif (!inputDir.exists()) {\n\t\t//inputDir.mkdirs();\n\t\tthrow new IllegalStateException(\"Input directory does not exist: \" + inputDir);\n\t}\n\tvar files = inputDir.listFiles((dir, name) -> name.toLowerCase().endsWith(\".svg\"));\n\tif (files == null || files.length == 0) {\n\t\tthrow new IllegalStateException(\"Input directory is empty: \" + inputDir);\n\t}\n\n\tList<List<String>> testCases = Arrays.stream(files)\n\t\t\t.map(file -> {\n\t\t\t\tString filename = file.getName();\n\t\t\t\tvar chunks = filename.split(\"-\");\n\t\t\t\tString cat = chunks[chunks.length - 1].split(\"\\\\.\")[0].trim();\n\t\t\t\treturn List.of(filename, cat);\n\t\t\t}).toList();\n\n\tif (testCases.isEmpty()) {\n\t\tthrow new IllegalStateException(\"Input directory is empty: \" + inputDir);\n\t}\n\n\treturn testCases;\n}" }, { "identifier": "OUTPUT_DIRS_ALL", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final List<String> OUTPUT_DIRS_ALL = List.of(CAT1_DIR, CAT2_DIR, CAT3_DIR, UNCLASSIFIED_DIR);" }, { "identifier": "CAT1_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT1_DIR = OUTPUT_DIR + \"/\" + \"Cat1\";" }, { "identifier": "CAT2_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT2_DIR = OUTPUT_DIR + \"/\" + \"Cat2\";" }, { "identifier": "CAT3_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT3_DIR = OUTPUT_DIR + \"/\" + \"Cat3\";" }, { "identifier": "INPUT_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String INPUT_DIR = ROOT_DIR + \"/\" + \"input\";" }, { "identifier": "ROOT_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String ROOT_DIR = \"C:/kata-svg\";" }, { "identifier": "UNCLASSIFIED_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String UNCLASSIFIED_DIR = OUTPUT_DIR + \"/\" + \"Unclassified\";" } ]
import static org.katas.AssessUtils.catToOutputDir; import static org.katas.AssessUtils.countFiles; import static org.katas.AssessUtils.foundInFiles; import static org.katas.AssessUtils.getTestCases; import static org.katas.SvgLocations.OUTPUT_DIRS_ALL; import static org.katas.SvgLocations.CAT1_DIR; import static org.katas.SvgLocations.CAT2_DIR; import static org.katas.SvgLocations.CAT3_DIR; import static org.katas.SvgLocations.INPUT_DIR; import static org.katas.SvgLocations.ROOT_DIR; import static org.katas.SvgLocations.UNCLASSIFIED_DIR; import java.io.File;
1,399
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir);
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir);
int foundCat2 = countFiles(CAT2_DIR, rootDir);
6
2023-10-07 21:45:39+00:00
2k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java
[ { "identifier": "AdministrativeDivisionTmp", "path": "src/main/java/io/github/qmjy/mapbox/model/AdministrativeDivisionTmp.java", "snippet": "public class AdministrativeDivisionTmp {\n private final int id;\n private final int parentId;\n private final String name;\n private final String nameEn;\n private final int adminLevel;\n private List<AdministrativeDivisionTmp> children = new ArrayList<>();\n\n public AdministrativeDivisionTmp(SimpleFeature simpleFeature, int parentId) {\n this.id = (int) simpleFeature.getAttribute(\"osm_id\");\n this.name = (String) simpleFeature.getAttribute(\"local_name\");\n Object nameEnObj = simpleFeature.getAttribute(\"name_en\");\n this.nameEn = nameEnObj == null ? \"\" : String.valueOf(nameEnObj);\n this.parentId = parentId;\n this.adminLevel = simpleFeature.getAttribute(\"admin_level\") == null ? -1 : (int) simpleFeature.getAttribute(\"admin_level\");\n }\n\n public int getId() {\n return id;\n }\n\n public int getParentId() {\n return parentId;\n }\n\n public String getName() {\n return name;\n }\n\n public String getNameEn() {\n return nameEn;\n }\n\n public int getAdminLevel() {\n return adminLevel;\n }\n\n public List<AdministrativeDivisionTmp> getChildren() {\n return children;\n }\n\n public void setChildren(List<AdministrativeDivisionTmp> children) {\n this.children = children;\n }\n}" }, { "identifier": "FontsFileModel", "path": "src/main/java/io/github/qmjy/mapbox/model/FontsFileModel.java", "snippet": "public class FontsFileModel {\n private final File folder;\n\n public FontsFileModel(File fontFolder) {\n this.folder = fontFolder;\n }\n\n public File getFolder() {\n return folder;\n }\n}" }, { "identifier": "MetaData", "path": "src/main/java/io/github/qmjy/mapbox/model/MetaData.java", "snippet": "@Data\npublic class MetaData {\n private String name;\n private String type;\n private String version;\n private String description;\n private String format;\n private String crs;\n private long minzoom;\n private long maxzoom;\n private String bounds;\n private String center;\n private Map<String, String> others;\n}" }, { "identifier": "TilesFileModel", "path": "src/main/java/io/github/qmjy/mapbox/model/TilesFileModel.java", "snippet": "public class TilesFileModel {\n private final Logger logger = LoggerFactory.getLogger(TilesFileModel.class);\n private final String filePath;\n private JdbcTemplate jdbcTemplate;\n private final Map<String, String> metaDataMap = new HashMap<>();\n\n public TilesFileModel(File file, String className) {\n this.filePath = file.getAbsolutePath();\n\n initJdbc(className, file);\n loadMetaData();\n }\n\n private void initJdbc(String className, File file) {\n this.jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(className, file.getAbsolutePath());\n }\n\n private void loadMetaData() {\n try {\n List<Map<String, Object>> mapList = jdbcTemplate.queryForList(\"SELECT * FROM metadata\");\n for (Map<String, Object> map : mapList) {\n metaDataMap.put(String.valueOf(map.get(\"name\")), String.valueOf(map.get(\"value\")));\n }\n } catch (DataAccessException e) {\n logger.error(\"Load map meta data failed: {}\", filePath);\n }\n }\n\n public JdbcTemplate getJdbcTemplate() {\n return jdbcTemplate;\n }\n\n public Map<String, String> getMetaDataMap() {\n return metaDataMap;\n }\n}" } ]
import io.github.qmjy.mapbox.model.AdministrativeDivisionTmp; import io.github.qmjy.mapbox.model.FontsFileModel; import io.github.qmjy.mapbox.model.MetaData; import io.github.qmjy.mapbox.model.TilesFileModel; import lombok.Getter; import org.geotools.api.feature.simple.SimpleFeature; import org.geotools.data.geojson.GeoJSONReader; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.tpk.TPKFile; import org.geotools.tpk.TPKZoomLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*;
1,423
/* * Copyright (c) 2023 QMJY. * * 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 * * https://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.qmjy.mapbox; /** * 地图数据库服务工具 */ @Component public class MapServerDataCenter { private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class); /** * 瓦片数据库文件模型 */ private static final Map<String, TilesFileModel> tilesMap = new HashMap<>(); private static final Map<String, Map<Long, TPKZoomLevel>> tpkMap = new HashMap<>(); private static final Map<String, TPKFile> tpkFileMap = new HashMap<>(); /** * 字体文件模型 */ private static final Map<String, FontsFileModel> fontsMap = new HashMap<>(); /** * 行政区划数据。key:行政级别、value:区划对象列表 */ @Getter private static final Map<Integer, List<SimpleFeature>> administrativeDivisionLevel = new HashMap<>(); /** * 行政区划数据。key:区划ID、value:区划对象 */ @Getter private static final Map<Integer, SimpleFeature> administrativeDivision = new HashMap<>(); /** * 行政区划层级树 */ @Getter
/* * Copyright (c) 2023 QMJY. * * 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 * * https://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.qmjy.mapbox; /** * 地图数据库服务工具 */ @Component public class MapServerDataCenter { private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class); /** * 瓦片数据库文件模型 */ private static final Map<String, TilesFileModel> tilesMap = new HashMap<>(); private static final Map<String, Map<Long, TPKZoomLevel>> tpkMap = new HashMap<>(); private static final Map<String, TPKFile> tpkFileMap = new HashMap<>(); /** * 字体文件模型 */ private static final Map<String, FontsFileModel> fontsMap = new HashMap<>(); /** * 行政区划数据。key:行政级别、value:区划对象列表 */ @Getter private static final Map<Integer, List<SimpleFeature>> administrativeDivisionLevel = new HashMap<>(); /** * 行政区划数据。key:区划ID、value:区划对象 */ @Getter private static final Map<Integer, SimpleFeature> administrativeDivision = new HashMap<>(); /** * 行政区划层级树 */ @Getter
private static AdministrativeDivisionTmp simpleAdminDivision;
0
2023-10-09 03:18:52+00:00
2k
codegrits/CodeGRITS
src/main/java/trackers/IDETracker.java
[ { "identifier": "RelativePathGetter", "path": "src/main/java/utils/RelativePathGetter.java", "snippet": "public class RelativePathGetter {\n /**\n * Get the relative path of a file compared to the project path. If the project path is not a prefix of the file path, the absolute path of the file is returned.\n *\n * @param absolutePath The absolute path of the file.\n * @param projectPath The absolute path of the project.\n * @return The relative path of the file compared to the project path.\n */\n public static String getRelativePath(String absolutePath, String projectPath) {\n if (absolutePath.length() > projectPath.length() && absolutePath.startsWith(projectPath)) {\n return absolutePath.substring(projectPath.length());\n }\n return absolutePath;\n }\n}" }, { "identifier": "XMLWriter", "path": "src/main/java/utils/XMLWriter.java", "snippet": "public class XMLWriter {\n /**\n * Write the formatted XML document to the XML file.\n *\n * @param document The XML document.\n * @param filePath The path of the XML file.\n */\n public static void writeToXML(Document document, String filePath) throws TransformerException {\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n DOMSource source = new DOMSource(document);\n StreamResult result = new StreamResult(new File(filePath));\n transformer.transform(source, result);\n }\n}" } ]
import javax.xml.parsers.*; import javax.xml.transform.TransformerException; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.apache.commons.io.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.awt.*; import java.awt.event.MouseEvent; import java.io.*; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import java.util.function.Consumer; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import org.jetbrains.annotations.NotNull; import utils.RelativePathGetter; import utils.XMLWriter; import javax.xml.parsers.DocumentBuilderFactory;
1,557
package trackers; /** * This class is the IDE tracker. */ public final class IDETracker implements Disposable { boolean isTracking = false; /** * This variable is the XML document for storing the tracking data. */ Document iDETracking = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = iDETracking.createElement("ide_tracking"); Element environment = iDETracking.createElement("environment"); Element actions = iDETracking.createElement("actions"); Element archives = iDETracking.createElement("archives"); Element typings = iDETracking.createElement("typings"); Element files = iDETracking.createElement("files"); Element mouses = iDETracking.createElement("mouses"); Element carets = iDETracking.createElement("carets"); Element selections = iDETracking.createElement("selections"); Element visibleAreas = iDETracking.createElement("visible_areas"); String projectPath = ""; String dataOutputPath = ""; String lastSelectionInfo = ""; /** * This variable indicates whether the data is transmitted in real time. */ private static boolean isRealTimeDataTransmitting = false; /** * This variable is the handler for the IDE tracker data. */ private Consumer<Element> ideTrackerDataHandler; /** * This variable is the document listener for the IDE tracker. When the document is changed, if the {@code EditorKind} is {@code CONSOLE}, the console output is archived. Otherwise, the {@code changedFilepath} and {@code changedFileText} are updated. */ DocumentListener documentListener = new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent event) { if (!isTracking) return; if (event.getDocument().getText().length() == 0) return; if (EditorFactory.getInstance().getEditors(event.getDocument()).length == 0) return; Editor currentEditor = EditorFactory.getInstance().getEditors(event.getDocument())[0]; if (currentEditor != null && currentEditor.getEditorKind() == EditorKind.CONSOLE) { archiveFile("unknown", String.valueOf(System.currentTimeMillis()), "", event.getDocument().getText()); return; } VirtualFile changedFile = FileDocumentManager.getInstance().getFile(event.getDocument()); if (changedFile != null) { changedFilepath = changedFile.getPath(); changedFileText = event.getDocument().getText(); } } }; /** * This variable is the mouse listener for the IDE tracker. * When the mouse is pressed, clicked, or released, the mouse event is tracked. */ EditorMouseListener editorMouseListener = new EditorMouseListener() { @Override public void mousePressed(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mousePressed"); mouses.appendChild(mouseElement); } @Override public void mouseClicked(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseClicked"); mouses.appendChild(mouseElement); handleElement(mouseElement); } @Override public void mouseReleased(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseReleased"); mouses.appendChild(mouseElement); handleElement(mouseElement); } }; /** * This variable is the mouse motion listener for the IDE tracker. * When the mouse is moved or dragged, the mouse event is tracked. */ EditorMouseMotionListener editorMouseMotionListener = new EditorMouseMotionListener() { @Override public void mouseMoved(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseMoved"); mouses.appendChild(mouseElement); handleElement(mouseElement); } @Override public void mouseDragged(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseDragged"); mouses.appendChild(mouseElement); handleElement(mouseElement); } }; /** * This variable is the caret listener for the IDE tracker. * When the caret position is changed, the caret event is tracked. */ CaretListener caretListener = new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { if (!isTracking) return; Element caretElement = iDETracking.createElement("caret"); carets.appendChild(caretElement); caretElement.setAttribute("id", "caretPositionChanged"); caretElement.setAttribute("timestamp", String.valueOf(System.currentTimeMillis())); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(e.getEditor().getDocument()); caretElement.setAttribute("path", virtualFile != null ?
package trackers; /** * This class is the IDE tracker. */ public final class IDETracker implements Disposable { boolean isTracking = false; /** * This variable is the XML document for storing the tracking data. */ Document iDETracking = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = iDETracking.createElement("ide_tracking"); Element environment = iDETracking.createElement("environment"); Element actions = iDETracking.createElement("actions"); Element archives = iDETracking.createElement("archives"); Element typings = iDETracking.createElement("typings"); Element files = iDETracking.createElement("files"); Element mouses = iDETracking.createElement("mouses"); Element carets = iDETracking.createElement("carets"); Element selections = iDETracking.createElement("selections"); Element visibleAreas = iDETracking.createElement("visible_areas"); String projectPath = ""; String dataOutputPath = ""; String lastSelectionInfo = ""; /** * This variable indicates whether the data is transmitted in real time. */ private static boolean isRealTimeDataTransmitting = false; /** * This variable is the handler for the IDE tracker data. */ private Consumer<Element> ideTrackerDataHandler; /** * This variable is the document listener for the IDE tracker. When the document is changed, if the {@code EditorKind} is {@code CONSOLE}, the console output is archived. Otherwise, the {@code changedFilepath} and {@code changedFileText} are updated. */ DocumentListener documentListener = new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent event) { if (!isTracking) return; if (event.getDocument().getText().length() == 0) return; if (EditorFactory.getInstance().getEditors(event.getDocument()).length == 0) return; Editor currentEditor = EditorFactory.getInstance().getEditors(event.getDocument())[0]; if (currentEditor != null && currentEditor.getEditorKind() == EditorKind.CONSOLE) { archiveFile("unknown", String.valueOf(System.currentTimeMillis()), "", event.getDocument().getText()); return; } VirtualFile changedFile = FileDocumentManager.getInstance().getFile(event.getDocument()); if (changedFile != null) { changedFilepath = changedFile.getPath(); changedFileText = event.getDocument().getText(); } } }; /** * This variable is the mouse listener for the IDE tracker. * When the mouse is pressed, clicked, or released, the mouse event is tracked. */ EditorMouseListener editorMouseListener = new EditorMouseListener() { @Override public void mousePressed(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mousePressed"); mouses.appendChild(mouseElement); } @Override public void mouseClicked(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseClicked"); mouses.appendChild(mouseElement); handleElement(mouseElement); } @Override public void mouseReleased(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseReleased"); mouses.appendChild(mouseElement); handleElement(mouseElement); } }; /** * This variable is the mouse motion listener for the IDE tracker. * When the mouse is moved or dragged, the mouse event is tracked. */ EditorMouseMotionListener editorMouseMotionListener = new EditorMouseMotionListener() { @Override public void mouseMoved(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseMoved"); mouses.appendChild(mouseElement); handleElement(mouseElement); } @Override public void mouseDragged(@NotNull EditorMouseEvent e) { if (!isTracking) return; Element mouseElement = getMouseElement(e, "mouseDragged"); mouses.appendChild(mouseElement); handleElement(mouseElement); } }; /** * This variable is the caret listener for the IDE tracker. * When the caret position is changed, the caret event is tracked. */ CaretListener caretListener = new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { if (!isTracking) return; Element caretElement = iDETracking.createElement("caret"); carets.appendChild(caretElement); caretElement.setAttribute("id", "caretPositionChanged"); caretElement.setAttribute("timestamp", String.valueOf(System.currentTimeMillis())); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(e.getEditor().getDocument()); caretElement.setAttribute("path", virtualFile != null ?
RelativePathGetter.getRelativePath(virtualFile.getPath(), projectPath) : null);
0
2023-10-12 15:40:39+00:00
2k
soya-miyoshi/amazon-s3-encryption-client-cli
src/main/java/com/github/soyamiyoshi/App.java
[ { "identifier": "blockingDownload", "path": "src/main/java/com/github/soyamiyoshi/Act.java", "snippet": "public static void blockingDownload(final String bucketName, final String objectKey,\n final String privateKeyPath) {\n try (final CBlockingDownloader blockDownloadClient =\n new CBlockingDownloader(new CPrivateKeyProvider(privateKeyPath))) {\n blockDownloadClient.download(bucketName, objectKey);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "blockingDownloadKmsKey", "path": "src/main/java/com/github/soyamiyoshi/Act.java", "snippet": "public static void blockingDownloadKmsKey(final String bucketName, final String objectKey,\n final String kmsKeyArn) {\n try (final CKmsKeyBasedClient blockDownloadClient =\n new CKmsKeyBasedClient(kmsKeyArn)) {\n blockDownloadClient.blockingDownload(bucketName, objectKey);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "blockingDownloadMorethan64MBdata", "path": "src/main/java/com/github/soyamiyoshi/Act.java", "snippet": "public static void blockingDownloadMorethan64MBdata(final String bucketName,\n final String objectKey, final String privateKeyPath) {\n try (final CDelayedAuthenticationDownloader blockDownloadClient =\n new CDelayedAuthenticationDownloader(new CPrivateKeyProvider(privateKeyPath))) {\n blockDownloadClient.download(bucketName, objectKey);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "blockingUpload", "path": "src/main/java/com/github/soyamiyoshi/Act.java", "snippet": "public static void blockingUpload(final String bucketName, final String objectKey,\n final Path uploadFilePath, final String pulicKeyPath) {\n try (final CBlockingUploader blockUploadClient =\n new CBlockingUploader(new CPublicKeyProvider(pulicKeyPath))) {\n blockUploadClient.upload(bucketName, objectKey, uploadFilePath);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "blockingUploadKmsKey", "path": "src/main/java/com/github/soyamiyoshi/Act.java", "snippet": "public static void blockingUploadKmsKey(final String bucketName, final String objectKey,\n final Path uploadFilePath, final String kmsKeyArn) {\n try (final CKmsKeyBasedClient blockUploadClient =\n new CKmsKeyBasedClient(kmsKeyArn)) {\n blockUploadClient.blockingUpload(bucketName, objectKey, uploadFilePath);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "ArgsParser", "path": "src/main/java/com/github/soyamiyoshi/cli/ArgsParser.java", "snippet": "public class ArgsParser {\n public static CommandLineArgs parse(String[] args) {\n CommandLineArgs cliArgs = new CommandLineArgs();\n JCommander commander = JCommander.newBuilder().addObject(cliArgs).build();\n commander.parse(args);\n\n if (cliArgs.isHelp()) {\n commander.usage();\n System.exit(1);\n }\n\n try {\n ArgsValidater.validate(cliArgs);\n } catch (IllegalArgumentException e) {\n System.out.println(\"Error: \" + e.getMessage());\n commander.usage();\n System.exit(1);\n }\n\n return cliArgs;\n }\n\n}" }, { "identifier": "CommandLineArgs", "path": "src/main/java/com/github/soyamiyoshi/cli/CommandLineArgs.java", "snippet": "@Getter\n@Setter\npublic class CommandLineArgs {\n @Parameter(names = {\"-o\", \"--object-key\"}, description = \"Object key\")\n private String objectKey;\n\n @Parameter(names = {\"-l\", \"--local-file-path\"}, description = \"Local file path\")\n private String localFilePath;\n\n @Parameter(names = {\"-m\", \"--kms-key-id\"}, description = \"KMS key ID\")\n private String kmsKeyId;\n\n @Parameter(names = {\"-u\", \"--upload\"}, description = \"Upload action\")\n private boolean isUpload;\n\n @Parameter(names = {\"-d\", \"--download\"}, description = \"Download action\")\n private boolean isDownload;\n\n @Parameter(names = {\"--heavy\"}, description = \"Download more than 64MB data\")\n private boolean isDownloadMorethan64MBdata;\n\n @Parameter(names = {\"-h\", \"--help\"}, description = \"Display help/usage.\", help = true)\n private boolean help;\n\n @Parameter(names = {\"-p\", \"--public-key-path\"}, description = \"Path to public key\")\n private String publicKeyPath;\n\n @Parameter(names = {\"-k\", \"--private-key-path\"}, description = \"Path to private key\")\n private String privateKeyPath;\n\n @Parameter(names = {\"-b\", \"--bucket-name\"}, description = \"Bucket name\")\n private String bucketName;\n}" } ]
import static com.github.soyamiyoshi.Act.blockingDownload; import static com.github.soyamiyoshi.Act.blockingDownloadKmsKey; import static com.github.soyamiyoshi.Act.blockingDownloadMorethan64MBdata; import static com.github.soyamiyoshi.Act.blockingUpload; import static com.github.soyamiyoshi.Act.blockingUploadKmsKey; import java.nio.file.Path; import com.github.soyamiyoshi.cli.ArgsParser; import com.github.soyamiyoshi.cli.CommandLineArgs;
1,207
package com.github.soyamiyoshi; public class App { public static void main(String[] args) {
package com.github.soyamiyoshi; public class App { public static void main(String[] args) {
CommandLineArgs cliArgs = ArgsParser.parse(args);
5
2023-10-11 06:30:54+00:00
2k
Raniten/CaC-Spring-TP
src/main/java/com/cac/g6/tpfinal/mappers/AccountMapper.java
[ { "identifier": "AccountDto", "path": "src/main/java/com/cac/g6/tpfinal/entities/dto/AccountDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n\npublic class AccountDto {\n\n private Long idAccount;\n private String accountNumber;\n private float balance;\n private String cbu;\n private String alias;\n private String accountType;\n private float amount;\n private Long user;\n private Long currency;\n\n\n}" }, { "identifier": "CurrencyDto", "path": "src/main/java/com/cac/g6/tpfinal/entities/dto/CurrencyDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class CurrencyDto {\n private Long idCurrencyDto;\n private String name;\n private String code;\n}" }, { "identifier": "UserRepository", "path": "src/main/java/com/cac/g6/tpfinal/repositories/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository <User, Long> {\n}" }, { "identifier": "CurrencyService", "path": "src/main/java/com/cac/g6/tpfinal/services/CurrencyService.java", "snippet": "@Service\npublic class CurrencyService {\n\n private final CurrencyRepository currencyRepository;\n\n public CurrencyService(CurrencyRepository currencyRepository){\n this.currencyRepository = currencyRepository;\n }\n\n public List<Currency> getCurrencies() {\n return currencyRepository.findAll();\n }\n\n public Currency getCurrencyById(Long id) {\n return currencyRepository.findById(id).get();\n }\n\n public CurrencyDto createCurrency(CurrencyDto currencyDto) {\n Currency entity = CurrencyMapper.dtoToCurrency(currencyDto);\n Currency entitySaved = currencyRepository.save(entity);\n currencyDto = CurrencyMapper.currencyToDto(entitySaved);\n return currencyDto;\n }\n\n}" }, { "identifier": "UserService", "path": "src/main/java/com/cac/g6/tpfinal/services/UserService.java", "snippet": "@Service\npublic class UserService {\n\n @Autowired\n private final UserRepository userRepository;\n\n @Autowired\n private final AccountService accountService;\n\n @Autowired\n private final RandomCodeGeneratorService randomCodes;\n\n @Autowired\n private final CurrencyService currencyService;\n\n public UserService (UserRepository repository, AccountService accountService, RandomCodeGeneratorService randomCodes) {\n this.userRepository = repository;\n this.accountService = accountService;\n this.randomCodes = randomCodes;\n currencyService = null;\n }\n\n\n public List<User> getUsers() {\n\n return userRepository.findAll();\n }\n\n public User getUserById(Long id) {\n\n return userRepository.findById(id).get();\n\n }\n\n /*public User addUser (User user) {\n\n\n // Verifica si la cuenta existe\n //Account account = accountRepository.findById(user.getAccount().getIdAccount()).orElse(null);\n\n // Si la cuenta no existe, crea una nueva cuenta\n //if (account == null) {\n // account = accountService.createAccount(user);\n //}\n\n Account account = accountService.createAccount(user);\n\n // Asocia la cuenta al usuario\n account.setUser(user);\n //user.setAccount(account);\n\n // Guarda el usuario\n repository.save(user);\n\n // Guarda la cuenta\n //accountRepository.save(account);\n\n return user;\n }*/\n @Transactional\n public User addUser(UserDto requestUser) {\n User user = new User();\n\n user.setUserName(requestUser.getUserName());\n user.setEmail(requestUser.getEmail());\n user.setPassword(requestUser.getPassword());\n user.setDni(requestUser.getDni());\n user.setBirthDate(requestUser.getBirthDate());\n user.setAddress(requestUser.getAddress());\n\n List<Account> accounts = new ArrayList<>();\n\n Currency currency = new Currency();\n\n Account account = null;\n for (AccountDto accountRequest : requestUser.getAccounts()) {\n String actNbr = accountService.generateRandomDigits(10);\n String cbu = accountService.generateRandomDigits(15);\n\n if (accountRequest.getAccountType().equalsIgnoreCase(\"SAVINGS\")) {\n account = new AccountBuilder().buildSavingsAccount(null, actNbr, 0.0F, \"23650\"+actNbr+cbu, accountService.generateRandomAlias(), user, currencyService.getCurrencyById(accountRequest.getCurrency()), accountRequest.getAmount());\n\n } else if (accountRequest.getAccountType().equalsIgnoreCase(\"CURRENT\")) {\n account = new AccountBuilder().buildCurrentAccount(null, actNbr, 0.0F, \"23650\"+actNbr+cbu, accountService.generateRandomAlias(), user, currencyService.getCurrencyById(accountRequest.getCurrency()), accountRequest.getAmount());\n }\n accounts.add(account);\n }\n\n user.setAccounts(accounts);\n\n userRepository.save(user);\n return user;\n }\n\n public void deleteUserById (Long id) {\n\n userRepository.deleteById(id);\n }\n}" } ]
import com.cac.g6.tpfinal.entities.*; import com.cac.g6.tpfinal.entities.dto.AccountDto; import com.cac.g6.tpfinal.entities.dto.CurrencyDto; import com.cac.g6.tpfinal.repositories.UserRepository; import com.cac.g6.tpfinal.services.CurrencyService; import com.cac.g6.tpfinal.services.UserService; import org.springframework.beans.factory.annotation.Autowired;
1,457
package com.cac.g6.tpfinal.mappers; public class AccountMapper { @Autowired private UserRepository userRepository; @Autowired private static CurrencyService currencyService ; @Autowired private static UserService userService; public static Account dtoToAccount(AccountDto dto){ Account account; Currency currency = currencyService.getCurrencyById(dto.getCurrency()); if (dto.getAccountType().equalsIgnoreCase("SAVINGS")) { account = new AccountBuilder().buildSavingsAccount(dto.getIdAccount(), dto.getAccountNumber(), dto.getBalance(), dto.getCbu(), dto.getAlias(), userService.getUserById(dto.getUser()), currency, dto.getAmount()); } else if (dto.getAccountType().equalsIgnoreCase("CURRENT")) { account = new AccountBuilder().buildCurrentAccount(dto.getIdAccount(), dto.getAccountNumber(), dto.getBalance(), dto.getCbu(), dto.getAlias(), userService.getUserById(dto.getUser()), currency, dto.getAmount()); } else { account = new Account(); } return account; } public static AccountDto accountToDto(Account account){
package com.cac.g6.tpfinal.mappers; public class AccountMapper { @Autowired private UserRepository userRepository; @Autowired private static CurrencyService currencyService ; @Autowired private static UserService userService; public static Account dtoToAccount(AccountDto dto){ Account account; Currency currency = currencyService.getCurrencyById(dto.getCurrency()); if (dto.getAccountType().equalsIgnoreCase("SAVINGS")) { account = new AccountBuilder().buildSavingsAccount(dto.getIdAccount(), dto.getAccountNumber(), dto.getBalance(), dto.getCbu(), dto.getAlias(), userService.getUserById(dto.getUser()), currency, dto.getAmount()); } else if (dto.getAccountType().equalsIgnoreCase("CURRENT")) { account = new AccountBuilder().buildCurrentAccount(dto.getIdAccount(), dto.getAccountNumber(), dto.getBalance(), dto.getCbu(), dto.getAlias(), userService.getUserById(dto.getUser()), currency, dto.getAmount()); } else { account = new Account(); } return account; } public static AccountDto accountToDto(Account account){
CurrencyDto dto = new CurrencyDto();
1
2023-10-11 17:30:07+00:00
2k
eduardozamit/Projeto-Revisao-AvioesDoForro
Projeto-Revisao/src/main/java/main/java/Main.java
[ { "identifier": "ConsultarTrajetos", "path": "Projeto-Revisao/src/main/java/main/java/services/ConsultarTrajetos.java", "snippet": "public class ConsultarTrajetos extends Transporte {\n\n public static void consultarTrechosModalidades(){\n Scanner scanner = new Scanner(System.in);\n //Lista todas as cidades disponíveis.\n System.out.println(\"Listando cidades abaixo...\");\n listarCidades();\n\n //Calcula a distancia entre as cidades que o usuário digitou.\n System.out.print(\"Digite o nome da cidade de origem: \");\n String cidadeDeOrigem = scanner.nextLine().toUpperCase();\n while (!cidadeExiste(cidadeDeOrigem)) {\n System.out.println(\"A cidade digitada não existe. Por favor, digite uma cidade válida.\");\n cidadeDeOrigem = scanner.nextLine().toUpperCase();\n }\n System.out.print(\"Digite o nome da cidade de Destino: \");\n String cidadeDeDestino = scanner.nextLine().toUpperCase();\n while (!cidadeExiste(cidadeDeDestino)) {\n System.out.println(\"A cidade digitada não existe. Por favor, digite uma cidade válida.\");\n cidadeDeDestino = scanner.nextLine().toUpperCase();\n }\n double distancia = calcularDistancia(cidadeDeOrigem, cidadeDeDestino);\n\n //Seleciona o tipo de caminhão.\n String tipoDeCaminhao;\n do {\n System.out.print(\"Digite o tipo de caminhão (pequeno, médio ou grande): \");\n tipoDeCaminhao = scanner.nextLine().toLowerCase();\n if (!tipoDeCaminhao.equalsIgnoreCase(\"pequeno\") && !tipoDeCaminhao.equalsIgnoreCase(\"médio\") && !tipoDeCaminhao.equalsIgnoreCase(\"grande\")) {\n System.out.println(\"Opção de caminhão inválida. Por favor, digite uma opção válida.\");\n }\n }while (!tipoDeCaminhao.equalsIgnoreCase(\"pequeno\") && !tipoDeCaminhao.equalsIgnoreCase(\"médio\") && !tipoDeCaminhao.equalsIgnoreCase(\"grande\"));\n Caminhao caminhao = Caminhao.selecionarCaminhao(tipoDeCaminhao.toLowerCase());\n\n\n //Exibe o resultado para o usuário\n System.out.println(\"---------------------- Consulta de trajeto: -----------------------\");\n System.out.println(\"A distância percorrida entre \" + cidadeDeOrigem + \" e \" + cidadeDeDestino + \" foi de: \" + distancia + \" Km\");\n System.out.println(\"E o custo total utilizando o caminhão \" + caminhao.getTipo() + \" foi de: R$ \" + (distancia * caminhao.getPrecoPorKm()));\n System.out.println(\"-------------------------------------------------------------------\");\n\n //Pergunta se o usuário deseja fazer uma nova consulta\n System.out.println(\"Deseja fazer uma nova consulta? (S/N)\");\n String resposta = scanner.nextLine();\n\n if (resposta.equalsIgnoreCase(\"S\")) {\n //Reinicia o processo de consulta\n consultarTrechosModalidades();\n } else {\n //Retorna para o menu principal\n System.out.println(\"Retornando para o menu principal...\");\n }\n }\n}" }, { "identifier": "cadastrarTransportes", "path": "Projeto-Revisao/src/main/java/main/java/services/CadastroTransporte.java", "snippet": "public static void cadastrarTransportes() {\n Scanner scanner = new Scanner(System.in);\n System.out.println(\"\"\"\n |--------------------------------------------|\\s\n | Em construção, volte em breve! |\\s\n |--------------------------------------------|\\s\n (Tecle espaço para voltar ao menu...)\n \"\"\");\n scanner.nextLine();\n scanner.nextLine();\n}" }, { "identifier": "gerarRelatorio", "path": "Projeto-Revisao/src/main/java/main/java/services/RelatorioTransportes.java", "snippet": "public static void gerarRelatorio() {\n Scanner scanner = new Scanner(System.in);\n System.out.println(\"\"\"\n |--------------------------------------------|\\s\n | Em construção, volte em breve! |\\s\n |--------------------------------------------|\\s\n (Tecle espaço para voltar ao menu...)\n \"\"\");\n scanner.nextLine();\n scanner.nextLine();\n}" } ]
import main.java.services.ConsultarTrajetos; import java.util.Scanner; import static main.java.services.CadastroTransporte.cadastrarTransportes; import static main.java.services.RelatorioTransportes.gerarRelatorio;
1,258
package main.java; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int opcao = -1; while (opcao != 0) { System.out.println(""" |--------------------------------------------|\s | Menu do programa |\s |--------------------------------------------|\s |----------- Selecione uma opção: -----------|\s |Opção: 1 - Consultar Trechos e Modalidades |\s |Opção: 2 - Cadastrar transporte |\s |Opção: 3 - Consultar dados estatísticos |\s |Opção: 0 - Finalizar programa |\s |--------------------------------------------| """); opcao = scanner.nextInt(); switch (opcao) { case 1: System.out.println("|-------- Você Selecionou a opção 1 ---------|"); ConsultarTrajetos.consultarTrechosModalidades(); break; case 2: System.out.println("|-------- Você Selecionou a opção 2 ---------|");
package main.java; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int opcao = -1; while (opcao != 0) { System.out.println(""" |--------------------------------------------|\s | Menu do programa |\s |--------------------------------------------|\s |----------- Selecione uma opção: -----------|\s |Opção: 1 - Consultar Trechos e Modalidades |\s |Opção: 2 - Cadastrar transporte |\s |Opção: 3 - Consultar dados estatísticos |\s |Opção: 0 - Finalizar programa |\s |--------------------------------------------| """); opcao = scanner.nextInt(); switch (opcao) { case 1: System.out.println("|-------- Você Selecionou a opção 1 ---------|"); ConsultarTrajetos.consultarTrechosModalidades(); break; case 2: System.out.println("|-------- Você Selecionou a opção 2 ---------|");
cadastrarTransportes();
1
2023-10-13 13:25:40+00:00
2k
DSantosxTech/System-management-web-Events
src/main/java/com/eventosweb/controllers/EventoController.java
[ { "identifier": "Convidado", "path": "src/main/java/com/eventosweb/models/Convidado.java", "snippet": "@Entity\npublic class Convidado {\n\n\t@Id\n\t@NotEmpty\n\tprivate String rg;\n\n\t@NotEmpty\n\tprivate String nomeConvidado;\n\n\t@ManyToOne\n\tprivate Evento evento;\n\n\tpublic String getRg() {\n\t\treturn rg;\n\t}\n\n\tpublic void setRg(String rg) {\n\t\tthis.rg = rg;\n\t}\n\n\tpublic String getNomeConvidado() {\n\t\treturn nomeConvidado;\n\t}\n\n\tpublic void setNomeConvidado(String nomeConvidado) {\n\t\tthis.nomeConvidado = nomeConvidado;\n\t}\n\n\tpublic Evento getEvento() {\n\t\treturn evento;\n\t}\n\n\tpublic void setEvento(Evento evento) {\n\t\tthis.evento = evento;\n\t}\n\n\n}" }, { "identifier": "Evento", "path": "src/main/java/com/eventosweb/models/Evento.java", "snippet": "@Entity\npublic class Evento implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate long codigo;\n\n\t@NotEmpty\n\tprivate String nome;\n\n\t@NotEmpty\n\tprivate String local;\n\n\t@NotEmpty\n\tprivate String data;\n\n\t@NotEmpty\n\tprivate String horario;\n\n\t@OneToMany\n\tprivate List<Convidado> convidados;\n\n\tpublic long getCodigo() {\n\t\treturn codigo;\n\t}\n\n\tpublic void setCodigo(long codigo) {\n\t\tthis.codigo = codigo;\n\t}\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getLocal() {\n\t\treturn local;\n\t}\n\n\tpublic void setLocal(String local) {\n\t\tthis.local = local;\n\t}\n\n\tpublic String getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(String data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic String getHorario() {\n\t\treturn horario;\n\t}\n\n\tpublic void setHorario(String horario) {\n\t\tthis.horario = horario;\n\t}\n\n\n}" }, { "identifier": "ConvidadoRepository", "path": "src/main/java/com/eventosweb/repository/ConvidadoRepository.java", "snippet": "public interface ConvidadoRepository extends CrudRepository<Convidado, String> {\n\tIterable<Convidado> findByEvento(Evento evento);\n\n\tConvidado findByRg(String rg);\n}" }, { "identifier": "EventoRepository", "path": "src/main/java/com/eventosweb/repository/EventoRepository.java", "snippet": "public interface EventoRepository extends CrudRepository<Evento, String> {\n\tEvento findByCodigo(long codigo);\n}" } ]
import com.eventosweb.models.Convidado; import com.eventosweb.models.Evento; import com.eventosweb.repository.ConvidadoRepository; import com.eventosweb.repository.EventoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.validation.Valid;
855
package com.eventosweb.controllers; @Controller public class EventoController { @Autowired private EventoRepository er; @Autowired
package com.eventosweb.controllers; @Controller public class EventoController { @Autowired private EventoRepository er; @Autowired
private ConvidadoRepository cr;
2
2023-10-12 14:26:00+00:00
2k
rgrosa/comes-e-bebes
src/main/java/br/com/project/domain/service/UserService.java
[ { "identifier": "CreateUserDTO", "path": "src/main/java/br/com/project/domain/dto/CreateUserDTO.java", "snippet": "public class CreateUserDTO {\n\n private String username;\n private String password;\n private String address;\n private String registrationDocument;\n private RestaurantDTO restaurant;\n private Boolean status;\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getRegistrationDocument() {\n return registrationDocument;\n }\n\n public void setRegistrationDocument(String registrationDocument) {\n this.registrationDocument = registrationDocument;\n }\n\n public RestaurantDTO getRestaurant() {\n return restaurant;\n }\n\n public void setRestaurant(RestaurantDTO restaurant) {\n this.restaurant = restaurant;\n }\n\n public Boolean getStatus() {\n return status;\n }\n\n public void setStatus(Boolean status) {\n this.status = status;\n }\n}" }, { "identifier": "LoggedUserDTO", "path": "src/main/java/br/com/project/domain/dto/LoggedUserDTO.java", "snippet": "public class LoggedUserDTO {\n\n private Long id;\n private String username;\n private String password;\n private String jwtToken;\n private Integer userTypeId;\n private String address;\n private String registrationDocument;\n private LocalDateTime updatedAt;\n private LocalDateTime insertedAt;\n private Long restaurantId;\n private Boolean status;\n\n public LoggedUserDTO(Long id, String username, String password, String jwtToken, Integer userTypeId, String address, String registrationDocument, LocalDateTime updatedAt, LocalDateTime insertedAt, Long restaurantId, Boolean status) {\n this.id = id;\n this.username = username;\n this.password = password;\n this.jwtToken = jwtToken;\n this.userTypeId = userTypeId;\n this.address = address;\n this.registrationDocument = registrationDocument;\n this.updatedAt = updatedAt;\n this.insertedAt = insertedAt;\n this.restaurantId = restaurantId;\n this.status = status;\n }\n\n public Integer getUserTypeId() {\n return userTypeId;\n }\n\n public void setUserTypeId(Integer userTypeId) {\n this.userTypeId = userTypeId;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getRegistrationDocument() {\n return registrationDocument;\n }\n\n public void setRegistrationDocument(String registrationDocument) {\n this.registrationDocument = registrationDocument;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getInsertedAt() {\n return insertedAt;\n }\n\n public void setInsertedAt(LocalDateTime insertedAt) {\n this.insertedAt = insertedAt;\n }\n\n public Long getRestaurantId() {\n return restaurantId;\n }\n\n public void setRestaurantId(Long restaurantId) {\n this.restaurantId = restaurantId;\n }\n\n public Boolean getStatus() {\n return status;\n }\n\n public void setStatus(Boolean status) {\n this.status = status;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getJwtToken() {\n return jwtToken;\n }\n\n public void setJwtToken(String jwtToken) {\n this.jwtToken = jwtToken;\n }\n}" }, { "identifier": "UserLoginDTO", "path": "src/main/java/br/com/project/domain/dto/UserLoginDTO.java", "snippet": "public class UserLoginDTO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n private String userName;\n private String password;\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n\n}" }, { "identifier": "PasswordException", "path": "src/main/java/br/com/project/infrasctructure/exception/PasswordException.java", "snippet": "@ResponseStatus(value = HttpStatus.UNAUTHORIZED)\npublic class PasswordException extends Exception{\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public PasswordException(final String message) {\n super(message);\n }\n}" }, { "identifier": "ResourceNotFoundException", "path": "src/main/java/br/com/project/infrasctructure/exception/ResourceNotFoundException.java", "snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends Exception{\n\n\t@Serial\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic ResourceNotFoundException(final String message) {\n \tsuper(message);\n }\n}" } ]
import br.com.project.domain.dto.CreateUserDTO; import br.com.project.domain.dto.LoggedUserDTO; import br.com.project.domain.dto.UserLoginDTO; import br.com.project.infrasctructure.exception.PasswordException; import br.com.project.infrasctructure.exception.ResourceNotFoundException; import org.springframework.security.core.userdetails.UserDetails;
1,439
package br.com.project.domain.service; public interface UserService { LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException; UserDetails loadUserByUsername(String username) throws ResourceNotFoundException;
package br.com.project.domain.service; public interface UserService { LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException; UserDetails loadUserByUsername(String username) throws ResourceNotFoundException;
UserDetails createClient(CreateUserDTO createUserDTO) throws Exception;
0
2023-10-10 23:22:15+00:00
2k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/timer/recorder/files/CategoryFile.java
[ { "identifier": "ZombiesUtils", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/ZombiesUtils.java", "snippet": "@Mod(modid = \"zombiesutils\", useMetadata = true, clientSideOnly = true, guiFactory = \"com.github.stachelbeere1248.zombiesutils.config.GuiFactory\")\npublic class ZombiesUtils {\n private static ZombiesUtils instance;\n private final Hotkeys hotkeys;\n private Logger logger;\n\n public ZombiesUtils() {\n hotkeys = new Hotkeys();\n instance = this;\n }\n\n public static ZombiesUtils getInstance() {\n return instance;\n }\n\n @Mod.EventHandler\n public void preInit(@NotNull FMLPreInitializationEvent event) {\n logger = event.getModLog();\n ZombiesUtilsConfig.config = new Configuration(\n event.getSuggestedConfigurationFile(),\n \"1.2.4\"\n );\n ZombiesUtilsConfig.load();\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n HandlerRegistry.registerAll();\n CommandRegistry.registerAll();\n hotkeys.registerAll();\n }\n\n public Logger getLogger() {\n return logger;\n }\n\n public Hotkeys getHotkeys() {\n return hotkeys;\n }\n}" }, { "identifier": "GameMode", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/game/GameMode.java", "snippet": "public class GameMode {\n private final Map map;\n private Difficulty difficulty;\n\n public GameMode(@NotNull Map map) {\n this.map = map;\n this.difficulty = Difficulty.NORMAL;\n }\n\n public GameMode(@NotNull Map map, @NotNull Difficulty difficulty) {\n this.map = map;\n this.difficulty = difficulty;\n }\n\n public Map getMap() {\n return map;\n }\n\n public Difficulty getDifficulty() {\n return difficulty;\n }\n\n public void changeDifficulty(@NotNull Difficulty difficulty) {\n switch (map) {\n case DEAD_END:\n case BAD_BLOOD:\n this.difficulty = difficulty;\n break;\n case ALIEN_ARCADIUM:\n throw new RuntimeException(\"Achievement Get: Alien Arcadium Hard/RIP\" + Map.ALIEN_ARCADIUM);\n }\n }\n\n public boolean is(Map map, Difficulty difficulty) {\n return this.getDifficulty() == difficulty && this.getMap() == map;\n }\n}" }, { "identifier": "FileManager", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/timer/recorder/FileManager.java", "snippet": "public class FileManager {\n private static CategoryData readDataFromFile(@NotNull File file) throws FileNotFoundException, JsonSyntaxException {\n if (!file.exists()) throw new FileNotFoundException();\n\n String dataJson;\n Gson gson = new Gson();\n try {\n dataJson = FileUtils.readFileToString(file, StandardCharsets.UTF_16);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n if (dataJson == null || dataJson.trim().isEmpty()) throw new JsonSyntaxException(\"File empty\");\n\n return gson.fromJson(dataJson, CategoryData.class);\n }\n\n public static void createDataFile(@NotNull SplitsFile file, ISplitsData data) {\n try {\n //noinspection ResultOfMethodCallIgnored\n file.getParentFile().mkdirs();\n //noinspection ResultOfMethodCallIgnored\n file.createNewFile();\n writeDataToFile(file, data);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void writeDataToFile(SplitsFile file, @NotNull ISplitsData data) throws IOException {\n FileUtils.writeStringToFile(file, data.toJSON(), StandardCharsets.UTF_16);\n }\n\n @NotNull\n public static CategoryData categoryReadOrCreate(CategoryFile file) {\n CategoryData data;\n try {\n data = FileManager.readDataFromFile(file);\n } catch (FileNotFoundException | JsonSyntaxException ignored) {\n data = new CategoryData(file.getGameMode().getMap());\n FileManager.createDataFile(file, data);\n }\n return data;\n }\n}" }, { "identifier": "SplitsFile", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/timer/recorder/SplitsFile.java", "snippet": "public abstract class SplitsFile extends File {\n public SplitsFile(String parent, @NotNull String child) {\n super(parent, child);\n }\n\n public SplitsFile(File category, String child) {\n super(category, child);\n }\n\n}" }, { "identifier": "CategoryData", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/timer/recorder/data/CategoryData.java", "snippet": "public class CategoryData implements ISplitsData {\n private final short[] bestSegments; //in ticks, max ~27 min\n private final int[] personalBests; //in ticks,\n\n public CategoryData(@NotNull Map map) throws IllegalStateException {\n switch (map) {\n case ALIEN_ARCADIUM:\n bestSegments = new short[105];\n personalBests = new int[105];\n break;\n case DEAD_END:\n case BAD_BLOOD:\n bestSegments = new short[30];\n personalBests = new int[30];\n break;\n default:\n throw new IllegalStateException(\"Not a map: \" + map);\n }\n Arrays.fill(bestSegments, (short) 0);\n Arrays.fill(personalBests, 0);\n }\n\n @Override @NotNull\n public String toJSON() {\n Gson gson = new Gson();\n return gson.toJson(this, CategoryData.class);\n }\n\n public short getBestSegment(int index) {\n return bestSegments[index];\n }\n\n public int getPersonalBest(int index) {\n return personalBests[index];\n }\n\n public void setBestSegment(int index, short ticks) {\n bestSegments[index] = ticks;\n }\n\n public void setPersonalBest(int index, int ticks) {\n personalBests[index] = ticks;\n }\n}" } ]
import com.github.stachelbeere1248.zombiesutils.ZombiesUtils; import com.github.stachelbeere1248.zombiesutils.game.GameMode; import com.github.stachelbeere1248.zombiesutils.timer.recorder.FileManager; import com.github.stachelbeere1248.zombiesutils.timer.recorder.SplitsFile; import com.github.stachelbeere1248.zombiesutils.timer.recorder.data.CategoryData; import net.minecraft.client.Minecraft; import net.minecraft.util.ChatComponentText; import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import java.io.File;
1,586
package com.github.stachelbeere1248.zombiesutils.timer.recorder.files; public class CategoryFile extends SplitsFile { private final CategoryData data;
package com.github.stachelbeere1248.zombiesutils.timer.recorder.files; public class CategoryFile extends SplitsFile { private final CategoryData data;
private final GameMode gameMode;
1
2023-10-11 01:30:28+00:00
2k
gustavofg1pontes/Tickets-API
infrastructure/src/main/java/br/com/ifsp/tickets/api/infra/contexts/event/persistence/EventJpaEntity.java
[ { "identifier": "Event", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/entity/Event.java", "snippet": "@Getter\n@Setter\npublic class Event extends AggregateRoot<EventID> {\n private String name;\n private LocalDateTime dateTime;\n private Integer maxTickets;\n private Integer soldTickets;\n\n public Event(EventID eventID, String name, LocalDateTime dateTime, Integer maxQuantGuests, Integer soldTickets) {\n super(eventID);\n this.name = name;\n this.dateTime = dateTime;\n this.maxTickets = maxQuantGuests;\n this.soldTickets = soldTickets;\n }\n\n public static Event with(EventID eventID, String name, LocalDateTime dateTime, Integer maxQuantGuests, Integer soldTickets) {\n return new Event(eventID, name, dateTime, maxQuantGuests, soldTickets);\n }\n\n public void update(String name, LocalDateTime localDateTime, Integer maxQuantGuests, Integer soldTickets) {\n this.name = name;\n this.dateTime = localDateTime;\n this.maxTickets = maxQuantGuests;\n this.soldTickets = soldTickets;\n }\n\n public void addTicketSold() {\n this.soldTickets++;\n }\n\n public void removeTicketSold() {\n this.soldTickets--;\n }\n\n @Override\n public void validate(ValidationHandler handler) {\n new EventValidator(this, handler).validate();\n }\n}" }, { "identifier": "EventID", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/entity/EventID.java", "snippet": "public class EventID extends Identifier<UUID> {\n\n private final UUID uuid;\n\n public EventID(final UUID uuid) {\n this.uuid = uuid;\n }\n\n public static EventID from(final String anId) {\n if (anId == null || anId.isBlank()) return null;\n return new EventID(UUIDUtils.getFromString(anId));\n }\n\n public static EventID unique() {\n return EventID.from(UUIDUtils.uuid());\n }\n\n @Override\n public UUID getValue() {\n return this.uuid;\n }\n}" }, { "identifier": "GuestJpaEntity", "path": "infrastructure/src/main/java/br/com/ifsp/tickets/api/infra/contexts/guest/persistence/GuestJpaEntity.java", "snippet": "@Entity\n@Table(name = \"CV_GUESTS\")\n@Getter\n@NoArgsConstructor\npublic class GuestJpaEntity {\n\n @Id\n @Column(name = \"id\", updatable = false, nullable = false)\n private UUID id;\n @Column(name = \"event_id\", nullable = false)\n private UUID eventId;\n @Column(name=\"name\", nullable = false)\n private String name;\n @Column(name = \"age\", nullable = false)\n private Integer age;\n @Column(name = \"enter_id\", updatable = false, insertable = false, nullable = false)\n private Integer enterId;\n @Column(name = \"document\", nullable = false)\n private String document;\n @Column(name = \"is_blocked\", nullable = false)\n private boolean blocked;\n @Column(name = \"is_entered\", nullable = false)\n private boolean entered;\n @Column(name = \"is_left\", nullable = false)\n private boolean left;\n @Column(name = \"phone_number\", nullable = false)\n private String phoneNumber;\n @Column(name = \"email\", nullable = false)\n private String email;\n @Column(name = \"profile_id\", nullable = false)\n private Integer profileId;\n\n @Builder\n public GuestJpaEntity(UUID id, String eventId, Integer enterId, String name, Integer age, String document, boolean blocked, boolean entered, boolean left, String phoneNumber, String email, Integer profileId) {\n this.id = id;\n this.eventId = UUIDUtils.getFromString(eventId);\n this.name = name;\n this.enterId = enterId;\n this.age = age;\n this.document = document;\n this.blocked = blocked;\n this.phoneNumber = phoneNumber;\n this.email = email;\n this.profileId = profileId;\n this.entered = entered;\n this.left = left;\n }\n\n public static GuestJpaEntity from(final Guest guest){\n return GuestJpaEntity.builder()\n .id(guest.getId().getValue())\n .eventId(guest.getEventId().getValue().toString())\n .enterId(guest.getEnterId())\n .name(guest.getName())\n .age(guest.getAge())\n .document(guest.getDocument())\n .blocked(guest.isBlocked())\n .entered(guest.isEntered())\n .left(guest.isLeft())\n .phoneNumber(guest.getPhoneNumber())\n .email(guest.getEmail())\n .profileId(guest.getProfile().getId())\n .build();\n }\n\n public Guest toDomain(){\n return Guest.with(\n new GuestID(id),\n new EventID(eventId),\n enterId,\n name,\n age,\n document,\n blocked,\n entered,\n left,\n phoneNumber,\n email,\n Profile.get(profileId));\n }\n}" } ]
import br.com.ifsp.tickets.api.domain.event.entity.Event; import br.com.ifsp.tickets.api.domain.event.entity.EventID; import br.com.ifsp.tickets.api.infra.contexts.guest.persistence.GuestJpaEntity; import jakarta.persistence.*; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; import java.util.UUID;
1,593
package br.com.ifsp.tickets.api.infra.contexts.event.persistence; @Entity @Table(name = "CV_EVENTS") @Getter @NoArgsConstructor public class EventJpaEntity implements Serializable { @Id @Column(name = "id", updatable = false, nullable = false) private UUID id; @Column(name = "name", nullable = false) private String name; @Column(name = "date", nullable = false) private LocalDateTime dateTime; @Column(name = "max_guests", nullable = false) private Integer maxGuests; @Column(name = "sold_tickets", nullable = false) private Integer soldTickets; @Builder public EventJpaEntity(UUID id, String name, LocalDateTime dateTime, Integer maxGuests, Integer soldTickets) { this.id = id; this.name = name; this.dateTime = dateTime; this.maxGuests = maxGuests; this.soldTickets = soldTickets; } public static EventJpaEntity from(final Event event) { return EventJpaEntity.builder() .id(event.getId().getValue()) .name(event.getName()) .dateTime(event.getDateTime()) .maxGuests(event.getMaxTickets()) .soldTickets(event.getSoldTickets()) .build(); } public Event toDomain(){ return Event.with(
package br.com.ifsp.tickets.api.infra.contexts.event.persistence; @Entity @Table(name = "CV_EVENTS") @Getter @NoArgsConstructor public class EventJpaEntity implements Serializable { @Id @Column(name = "id", updatable = false, nullable = false) private UUID id; @Column(name = "name", nullable = false) private String name; @Column(name = "date", nullable = false) private LocalDateTime dateTime; @Column(name = "max_guests", nullable = false) private Integer maxGuests; @Column(name = "sold_tickets", nullable = false) private Integer soldTickets; @Builder public EventJpaEntity(UUID id, String name, LocalDateTime dateTime, Integer maxGuests, Integer soldTickets) { this.id = id; this.name = name; this.dateTime = dateTime; this.maxGuests = maxGuests; this.soldTickets = soldTickets; } public static EventJpaEntity from(final Event event) { return EventJpaEntity.builder() .id(event.getId().getValue()) .name(event.getName()) .dateTime(event.getDateTime()) .maxGuests(event.getMaxTickets()) .soldTickets(event.getSoldTickets()) .build(); } public Event toDomain(){ return Event.with(
new EventID(this.id),
1
2023-10-11 00:05:05+00:00
2k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/blocks/millstone/instance/TuffMillStoneCogInstance.java
[ { "identifier": "DecoPartialModels", "path": "src/main/java/com/mangomilk/design_decor/base/DecoPartialModels.java", "snippet": "public class DecoPartialModels {\n\n public static final PartialModel\n EMPTY = block(\"empty\"),\n\n SHAFTLESS_LARGE_COGWHEEL = block(\"industrial_gear_large\"),\n\n GRANITE_MILLSTONE_COG = block(\"granite_millstone/inner\"),\n DIORITE_MILLSTONE_COG = block(\"diorite_millstone/inner\"),\n LIMESTONE_MILLSTONE_COG = block(\"limestone_millstone/inner\"),\n SCORCHIA_MILLSTONE_COG = block(\"scorchia_millstone/inner\"),\n SCORIA_MILLSTONE_COG = block(\"scoria_millstone/inner\"),\n TUFF_MILLSTONE_COG = block(\"tuff_millstone/inner\"),\n VERIDIUM_MILLSTONE_COG = block(\"veridium_millstone/inner\"),\n DRIPSTONE_MILLSTONE_COG = block(\"dripstone_millstone/inner\"),\n DEEPSLATE_MILLSTONE_COG = block(\"deepslate_millstone/inner\"),\n CRIMSITE_MILLSTONE_COG = block(\"crimsite_millstone/inner\"),\n CALCITE_MILLSTONE_COG = block(\"calcite_millstone/inner\"),\n ASURINE_MILLSTONE_COG = block(\"asurine_millstone/inner\"),\n OCHRUM_MILLSTONE_COG = block(\"ochrum_millstone/inner\")\n\n\n ;\n\n\n\n\n private static PartialModel block(String path) {\n return new PartialModel(CreateMMBuilding.asResource(\"block/\" + path));\n }\n\n private static PartialModel entity(String path) {\n return new PartialModel(CreateMMBuilding.asResource(\"entity/\" + path));\n }\n\n public static void init() {\n }\n}" }, { "identifier": "DecoMillStoneBlockEntity", "path": "src/main/java/com/mangomilk/design_decor/blocks/millstone/DecoMillStoneBlockEntity.java", "snippet": "public class DecoMillStoneBlockEntity extends MillstoneBlockEntity {\n public DecoMillStoneBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n super(type, pos, state);\n capability = LazyOptional.of(DecoMillstoneInventoryHandler::new);\n }\n\n public MillingRecipe lastRecipe;\n\n @Override\n public void tick() {\n super.tick();\n\n if (getSpeed() == 0)\n return;\n for (int i = 0; i < outputInv.getSlots(); i++)\n if (outputInv.getStackInSlot(i)\n .getCount() == outputInv.getSlotLimit(i))\n return;\n\n if (timer > 0) {\n timer -= getProcessingSpeed();\n\n if (level.isClientSide) {\n spawnParticles();\n return;\n }\n if (timer <= 0)\n process();\n return;\n }\n\n if (inputInv.getStackInSlot(0)\n .isEmpty())\n return;\n\n RecipeWrapper inventoryIn = new RecipeWrapper(inputInv);\n if (lastRecipe == null || !lastRecipe.matches(inventoryIn, level)) {\n Optional<MillingRecipe> recipe = AllRecipeTypes.MILLING.find(inventoryIn, level);\n if (!recipe.isPresent()) {\n timer = 100;\n sendData();\n } else {\n lastRecipe = recipe.get();\n timer = lastRecipe.getProcessingDuration();\n sendData();\n }\n return;\n }\n\n timer = lastRecipe.getProcessingDuration();\n sendData();\n }\n\n public void process() {\n RecipeWrapper inventoryIn = new RecipeWrapper(inputInv);\n\n if (lastRecipe == null || !lastRecipe.matches(inventoryIn, level)) {\n Optional<MillingRecipe> recipe = AllRecipeTypes.MILLING.find(inventoryIn, level);\n if (!recipe.isPresent())\n return;\n lastRecipe = recipe.get();\n }\n\n ItemStack stackInSlot = inputInv.getStackInSlot(0);\n stackInSlot.shrink(1);\n inputInv.setStackInSlot(0, stackInSlot);\n lastRecipe.rollResults()\n .forEach(stack -> ItemHandlerHelper.insertItemStacked(outputInv, stack, false));\n award(AllAdvancements.MILLSTONE);\n\n sendData();\n setChanged();\n }\n\n public boolean canProcess(ItemStack stack) {\n ItemStackHandler tester = new ItemStackHandler(1);\n tester.setStackInSlot(0, stack);\n RecipeWrapper inventoryIn = new RecipeWrapper(tester);\n\n if (lastRecipe != null && lastRecipe.matches(inventoryIn, level))\n return true;\n return AllRecipeTypes.MILLING.find(inventoryIn, level)\n .isPresent();\n }\n\n public class DecoMillstoneInventoryHandler extends CombinedInvWrapper {\n\n public DecoMillstoneInventoryHandler() {\n super(inputInv, outputInv);\n }\n\n @Override\n public boolean isItemValid(int slot, ItemStack stack) {\n if (outputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return false;\n return canProcess(stack) && super.isItemValid(slot, stack);\n }\n\n @Override\n public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {\n if (outputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return stack;\n if (!isItemValid(slot, stack))\n return stack;\n return super.insertItem(slot, stack, simulate);\n }\n\n @Override\n public ItemStack extractItem(int slot, int amount, boolean simulate) {\n if (inputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return ItemStack.EMPTY;\n return super.extractItem(slot, amount, simulate);\n }\n\n }\n}" } ]
import com.mangomilk.design_decor.base.DecoPartialModels; import com.mangomilk.design_decor.blocks.millstone.DecoMillStoneBlockEntity; import com.simibubi.create.content.kinetics.base.SingleRotatingInstance;import com.jozufozu.flywheel.api.Instancer; import com.jozufozu.flywheel.api.MaterialManager; import com.simibubi.create.content.kinetics.base.flwdata.RotatingData;
1,590
package com.mangomilk.design_decor.blocks.millstone.instance; public class TuffMillStoneCogInstance extends SingleRotatingInstance<DecoMillStoneBlockEntity> { public TuffMillStoneCogInstance(MaterialManager materialManager, DecoMillStoneBlockEntity blockEntity) {super(materialManager, blockEntity);} @Override protected Instancer<RotatingData> getModel() {
package com.mangomilk.design_decor.blocks.millstone.instance; public class TuffMillStoneCogInstance extends SingleRotatingInstance<DecoMillStoneBlockEntity> { public TuffMillStoneCogInstance(MaterialManager materialManager, DecoMillStoneBlockEntity blockEntity) {super(materialManager, blockEntity);} @Override protected Instancer<RotatingData> getModel() {
return getRotatingMaterial().getModel(DecoPartialModels.TUFF_MILLSTONE_COG, blockEntity.getBlockState());
0
2023-10-14 21:51:49+00:00
2k
Konloch/InjectedCalculator
src/main/java/com/konloch/ic/InjectedCalculator.java
[ { "identifier": "Calculator", "path": "src/main/java/com/konloch/ic/calculator/Calculator.java", "snippet": "public abstract class Calculator\n{\n\tpublic abstract long add(long a, long b);\n\tpublic abstract long sub(long a, long b);\n\tpublic abstract long mul(long a, long b);\n\tpublic abstract long div(long a, long b);\n}" }, { "identifier": "CalculatorInjector", "path": "src/main/java/com/konloch/ic/calculator/injector/CalculatorInjector.java", "snippet": "public class CalculatorInjector implements CalculatorInjectorI\n{\n\t@Override\n\tpublic Calculator inject()\n\t{\n\t\t//create new calc instance based off of java ASM, implementing the functions as needed\n\t\tClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);\n\t\t\n\t\t//define class\n\t\tcw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, \"GeneratedCalculator\", null, \"com/konloch/ic/calculator/Calculator\", null);\n\t\t{\n\t\t\t//implement init method\n\t\t\tMethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"<init>\", \"()V\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.ALOAD, 0);\n\t\t\tmv.visitMethodInsn(Opcodes.INVOKESPECIAL, \"com/konloch/ic/calculator/Calculator\", \"<init>\", \"()V\", false);\n\t\t\tmv.visitInsn(Opcodes.RETURN);\n\t\t\tmv.visitMaxs(1, 1);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement add method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"add\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LADD);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement sub method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"sub\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LSUB);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement mul method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"mul\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LMUL);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement div method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"div\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LDIV);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t}\n\t\tcw.visitEnd();\n\t\t\n\t\ttry\n\t\t{\n\t\t\tbyte[] bytecode = cw.toByteArray();\n\t\t\t\n\t\t\t//define a custom class loader to load the generated class\n\t\t\tInjectedClassLoader classLoader = new InjectedClassLoader();\n\t\t\t\n\t\t\tClass<?> generatedClass = classLoader.defineClass(\"GeneratedCalculator\", bytecode);\n\t\t\treturn (Calculator) generatedClass.newInstance();\n\t\t}\n\t\tcatch (InstantiationException | IllegalAccessException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "ExpressionEvaluator", "path": "src/main/java/com/konloch/ic/calculator/expression/ExpressionEvaluator.java", "snippet": "public class ExpressionEvaluator\n{\n\tprivate final Calculator calculator;\n\t\n\tpublic ExpressionEvaluator(Calculator calculator)\n\t{\n\t\tthis.calculator = calculator;\n\t}\n\t\n\tpublic long evaluateExpression(String expression)\n\t{\n\t\tStack<Long> operands = new Stack<>();\n\t\tStack<Character> operators = new Stack<>();\n\t\tchar[] chars = expression.toCharArray();\n\t\t\n\t\tStringBuilder numBuffer = new StringBuilder();\n\t\t\n\t\tfor (char c : chars)\n\t\t{\n\t\t\tif (Character.isDigit(c))\n\t\t\t\tnumBuffer.append(c);\n\t\t\telse if (c == '+' || c == '-' || c == '*' || c == '/')\n\t\t\t{\n\t\t\t\tif(numBuffer.length() > 0)\n\t\t\t\t{\n\t\t\t\t\toperands.push(Long.parseLong(numBuffer.toString()));\n\t\t\t\t\tnumBuffer = new StringBuilder();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twhile (!operators.isEmpty() && hasPrecedence(c, operators.peek()))\n\t\t\t\t{\n\t\t\t\t\tevaluateStackTop(operands, operators);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\toperators.push(c);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(numBuffer.length() > 0)\n\t\t\toperands.push(Long.parseLong(numBuffer.toString()));\n\t\t\n\t\twhile (!operators.isEmpty())\n\t\t{\n\t\t\tevaluateStackTop(operands, operators);\n\t\t}\n\t\t\n\t\treturn operands.pop();\n\t}\n\t\n\tprivate void evaluateStackTop(Stack<Long> operands, Stack<Character> operators)\n\t{\n\t\tchar operator = operators.pop();\n\t\tlong operand2 = operands.pop();\n\t\tlong operand1 = operands.pop();\n\t\toperands.push(evaluateOperation(operator, operand1, operand2));\n\t}\n\t\n\tprivate long evaluateOperation(char operator, long operand1, long operand2)\n\t{\n\t\tlong result = 0;\n\t\t\n\t\tswitch (operator)\n\t\t{\n\t\t\tcase '+':\n\t\t\t\tresult = calculator.add(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '-':\n\t\t\t\tresult = calculator.sub(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '*':\n\t\t\t\tresult = calculator.mul(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '/':\n\t\t\t\tresult = calculator.div(operand1, operand2);\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tprivate boolean hasPrecedence(char op1, char op2)\n\t{\n\t\treturn (op2 == '*' || op2 == '/') && (op1 == '+' || op1 == '-');\n\t}\n}" } ]
import com.konloch.ic.calculator.Calculator; import com.konloch.ic.calculator.injector.CalculatorInjector; import com.konloch.ic.calculator.expression.ExpressionEvaluator;
1,577
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator {
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator {
private final ExpressionEvaluator evaluator;
2
2023-10-15 08:38:08+00:00
2k
DeeChael/dcg
src/main/java/net/deechael/dcg/source/variable/internal/ThisVariable.java
[ { "identifier": "DyStructure", "path": "src/main/java/net/deechael/dcg/source/structure/DyStructure.java", "snippet": "public interface DyStructure {\n\n /**\n * Get parents domains to which this structure object belongs\n *\n * @return parent domains\n */\n @NotNull\n DyStructure[] getParentDomains();\n\n default boolean isStaticStructure() {\n return false;\n }\n\n}" }, { "identifier": "DyType", "path": "src/main/java/net/deechael/dcg/source/type/DyType.java", "snippet": "public interface DyType extends DyExportable, Invoker {\n\n // Default provided JTypes\n DyType VOID = classType(void.class);\n DyType INT = classType(int.class);\n DyType BOOLEAN = classType(boolean.class);\n DyType DOUBLE = classType(double.class);\n DyType FLOAT = classType(float.class);\n DyType LONG = classType(long.class);\n DyType SHORT = classType(short.class);\n DyType BYTE = classType(byte.class);\n DyType CHAR = classType(char.class);\n DyType OBJECT = classType(Object.class);\n DyType STRING = classType(String.class);\n DyType CLASS = classType(Class.class);\n\n /**\n * Get type for normal class type\n *\n * @param clazz class type\n * @return type\n */\n @NotNull\n static DyType classType(@NotNull Class<?> clazz) {\n return new DyJvmType(clazz);\n }\n\n /**\n * Get type for a generic type </br>\n * Example: List<T>, Map<K, V> etc.\n *\n * @param clazz base type\n * @param types generic parameters\n * @return type\n */\n @NotNull\n static DyType genericClassType(@NotNull Class<?> clazz, @NotNull DyType... types) {\n return new DyJvmGenericType(clazz, types);\n }\n\n @NotNull\n static DyType unknownGenericType(@Nullable DyType extending) {\n return new UnknownGenericType(extending);\n }\n\n /**\n * To check if this type is primitive type\n *\n * @return if is primitive type\n */\n boolean isPrimitive();\n\n /**\n * Get the base type of this type </br>\n * Example: if this type is java.lang.String[][], this method will return java.lang.String\n *\n * @return base type of this type\n */\n @NotNull\n DyType getBaseType();\n\n /**\n * Generate compilable string\n *\n * @return compilable string\n */\n @NotNull\n String toTypeString();\n\n /**\n * To check if this type is array\n *\n * @return if this type self is an array\n */\n boolean isArray();\n\n @Override\n @NotNull\n default String toExportableString() {\n return this.toTypeString();\n }\n\n @Override\n @NotNull\n default String toInvokerString() {\n return this.toTypeString();\n }\n\n @Override\n default boolean isStaticExportable() {\n return false;\n }\n\n}" }, { "identifier": "Variable", "path": "src/main/java/net/deechael/dcg/source/variable/Variable.java", "snippet": "public interface Variable extends Invoker, Requirement {\n\n /**\n * Get the type of this variable\n *\n * @return variable type\n */\n @NotNull\n DyType getType();\n\n /**\n * Get the name of the variable, only exists if it's a defined variable\n *\n * @return name, exception when not exists\n */\n String getName();\n\n /**\n * Get the domain of this variable, defining the availability of the variable\n *\n * @return domain\n */\n @NotNull\n DyStructure getDomain();\n\n /**\n * Generate compilable string for compiling use\n *\n * @return compilable string\n */\n String toVariableString();\n\n @Override\n @NotNull\n default String toInvokerString() {\n return this.toVariableString();\n }\n\n @Override\n default String toRequirementString() {\n return this.toVariableString();\n }\n\n static JvmVariable nullVariable() {\n return NullVariable.INSTANCE;\n }\n\n static JvmVariable stringVariable(String value) {\n return new StringVariable(value);\n }\n\n static Variable invokeMethodVariable(@Nullable Invoker invoker, @NotNull String methodName, Variable... parameters) {\n return new InvokeMethodVariable(DyUndefinedStructure.INSTANCE, invoker, methodName, parameters);\n }\n\n static Variable superVariable(DyType type) {\n return new SuperVariable(DyUndefinedStructure.INSTANCE, type);\n }\n\n static Variable thisVariable(DyType type) {\n return new ThisVariable(DyUndefinedStructure.INSTANCE, type);\n }\n\n}" } ]
import net.deechael.dcg.source.structure.DyStructure; import net.deechael.dcg.source.type.DyType; import net.deechael.dcg.source.variable.Variable; import org.jetbrains.annotations.NotNull;
1,272
package net.deechael.dcg.source.variable.internal; public final class ThisVariable implements Variable, NonNameVariable { private final DyStructure structure;
package net.deechael.dcg.source.variable.internal; public final class ThisVariable implements Variable, NonNameVariable { private final DyStructure structure;
private final DyType type;
1
2023-10-15 13:45:11+00:00
2k
niket17590/java-springboot-tutorials
java-object-comparator/src/test/java/com/medium/agrawalniket/object/comparator/ObjectComparatorApplicationTest.java
[ { "identifier": "MobileCompany", "path": "java-object-comparator/src/main/java/com/medium/agrawalniket/object/comparator/dto/MobileCompany.java", "snippet": "@Data\n@Builder(setterPrefix = \"set\")\npublic class MobileCompany {\n\n\tprivate String companyName;\n\tprivate Integer startYear;\n\tprivate String founderName;\n}" }, { "identifier": "MobileModel", "path": "java-object-comparator/src/main/java/com/medium/agrawalniket/object/comparator/dto/MobileModel.java", "snippet": "@Data\n@Builder(setterPrefix = \"set\")\npublic class MobileModel {\n\n\tprivate String modelName;\n\tprivate Double version;\n\tprivate boolean availablity;\n\tprivate Long modelPrice;\n\tprivate OperatingSystem osSystem;\n\tprivate MobileApplications mobileApps;\n\n}" }, { "identifier": "MobileApplications", "path": "java-object-comparator/src/main/java/com/medium/agrawalniket/object/comparator/entity/MobileApplications.java", "snippet": "@Data\n@Builder(setterPrefix = \"set\")\npublic class MobileApplications {\n\n\tprivate List<String> appNameList;\n\tprivate Map<String, String> appFeatures;\n\tprivate MobileCompany mobileCompany;\n\n}" }, { "identifier": "ObjectComparatorUtil", "path": "java-object-comparator/src/main/java/com/medium/agrawalniket/object/comparator/util/ObjectComparatorUtil.java", "snippet": "public class ObjectComparatorUtil {\n\n\tprivate ObjectComparatorUtil() {\n\n\t}\n\n\tstatic final Logger logger = LoggerFactory.getLogger(ObjectComparatorUtil.class);\n\n\tstatic final Set<String> dtoPackages = new HashSet<>();\n\n\t// Add all packages which contains user defined pojo\n\tstatic {\n\t\tdtoPackages.add(\"com.medium.agrawalniket.object.comparator.dto\");\n\t\tdtoPackages.add(\"com.medium.agrawalniket.object.comparator.entity\");\n\t}\n\n\tpublic static List<String> compareAndGetDiff(Object firstObj, Object secondObj, String parentName) {\n\t\ttry {\n\n\t\t\t// Check if both comparison objects are of same type\n\t\t\tif (Objects.nonNull(firstObj) && Objects.nonNull(secondObj)\n\t\t\t\t\t&& !(firstObj.getClass().getName().equals(secondObj.getClass().getName()))) {\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\n\t\t\tList<String> diffValFieldList = new ArrayList<>();\n\t\t\tlogger.info(\"Comparison started for Object: {}\", firstObj.getClass().getSimpleName());\n\n\t\t\tfor (Field field : firstObj.getClass().getDeclaredFields()) {\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\tString fieldName = parentName + firstObj.getClass().getSimpleName() + \".\" + field.getName();\n\t\t\t\tObject value1 = field.get(firstObj);\n\t\t\t\tObject value2 = field.get(secondObj);\n\n\t\t\t\tif (Objects.isNull(value1) && Objects.isNull(value2)) {\n\t\t\t\t\t// If field is null in both object then move to next field for comparison\n\t\t\t\t\tlogger.info(\"{} is null for both objects\", fieldName);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (Objects.isNull(value1) || Objects.isNull(value2)) {\n\t\t\t\t\t// If one of the object is having null value then add it changed properties\n\t\t\t\t\tdiffValFieldList.add(fieldName);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Logic to check if field is user defined object , if yes call recursively to\n\t\t\t\t// compare fields of User Object\n\t\t\t\tString value1Class = value1.getClass().getName();\n\t\t\t\tString value2Class = value2.getClass().getName();\n\n\t\t\t\tif (value1Class.equals(value2Class) && validateUserDefinedObj(value1.getClass().getName())) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\"{} is a user defined object, so calling same function again to compare independent object\",\n\t\t\t\t\t\t\tvalue1.getClass().getName());\n\t\t\t\t\tdiffValFieldList.addAll(compareAndGetDiff(value1, value2,\n\t\t\t\t\t\t\tparentName.concat(firstObj.getClass().getSimpleName() + \".\")));\n\t\t\t\t} else if (!Objects.equals(value1, value2)) {\n\t\t\t\t\tlogger.info(\"{} field value is different in both objects\", fieldName);\n\t\t\t\t\tdiffValFieldList.add(fieldName);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn diffValFieldList;\n\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\tlogger.error(\"Error while comparing objects\");\n\t\t}\n\t\treturn Collections.emptyList();\n\t}\n\n\t/**\n\t * Method to check if comparison object is an User Object from DTO packages\n\t */\n\tprivate static boolean validateUserDefinedObj(String dtoPackageName) {\n\t\tfor (String packageName : dtoPackages) {\n\t\t\tif (dtoPackageName.startsWith(packageName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n}" }, { "identifier": "OperatingSystem", "path": "java-object-comparator/src/main/java/com/medium/agrawalniket/object/comparator/util/EnumConstants.java", "snippet": "public enum OperatingSystem {\n\tANDROID, APPLE\n}" } ]
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.medium.agrawalniket.object.comparator.dto.MobileCompany; import com.medium.agrawalniket.object.comparator.dto.MobileModel; import com.medium.agrawalniket.object.comparator.entity.MobileApplications; import com.medium.agrawalniket.object.comparator.util.ObjectComparatorUtil; import com.medium.agrawalniket.object.comparator.util.EnumConstants.OperatingSystem;
1,230
package com.medium.agrawalniket.object.comparator; public class ObjectComparatorApplicationTest { @Test public void testSuccessComparison() {
package com.medium.agrawalniket.object.comparator; public class ObjectComparatorApplicationTest { @Test public void testSuccessComparison() {
MobileCompany oneplusCompany = MobileCompany.builder().setCompanyName("Oneplus").setStartYear(2000).build();
0
2023-10-14 18:39:04+00:00
2k
giteecode/supermarket2Public
src/main/java/com/ruoyi/common/utils/PageUtils.java
[ { "identifier": "SqlUtil", "path": "src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java", "snippet": "public class SqlUtil\n{\n /**\n * 定义常用的 sql关键字\n */\n public static String SQL_REGEX = \"select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare \";\n\n /**\n * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)\n */\n public static String SQL_PATTERN = \"[a-zA-Z0-9_\\\\ \\\\,\\\\.]+\";\n\n /**\n * 检查字符,防止注入绕过\n */\n public static String escapeOrderBySql(String value)\n {\n if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))\n {\n throw new UtilException(\"参数不符合规范,不能进行查询\");\n }\n return value;\n }\n\n /**\n * 验证 order by 语法是否符合规范\n */\n public static boolean isValidOrderBySql(String value)\n {\n return value.matches(SQL_PATTERN);\n }\n\n /**\n * SQL关键字检查\n */\n public static void filterKeyword(String value)\n {\n if (StringUtils.isEmpty(value))\n {\n return;\n }\n String[] sqlKeywords = StringUtils.split(SQL_REGEX, \"\\\\|\");\n for (String sqlKeyword : sqlKeywords)\n {\n if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1)\n {\n throw new UtilException(\"参数存在SQL注入风险\");\n }\n }\n }\n}" }, { "identifier": "PageDomain", "path": "src/main/java/com/ruoyi/framework/web/page/PageDomain.java", "snippet": "public class PageDomain\n{\n /** 当前记录起始索引 */\n private Integer pageNum;\n\n /** 每页显示记录数 */\n private Integer pageSize;\n\n /** 排序列 */\n private String orderByColumn;\n\n /** 排序的方向desc或者asc */\n private String isAsc = \"asc\";\n\n /** 分页参数合理化 */\n private Boolean reasonable = true;\n\n public String getOrderBy()\n {\n if (StringUtils.isEmpty(orderByColumn))\n {\n return \"\";\n }\n return StringUtils.toUnderScoreCase(orderByColumn) + \" \" + isAsc;\n }\n\n public Integer getPageNum()\n {\n return pageNum;\n }\n\n public void setPageNum(Integer pageNum)\n {\n this.pageNum = pageNum;\n }\n\n public Integer getPageSize()\n {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize)\n {\n this.pageSize = pageSize;\n }\n\n public String getOrderByColumn()\n {\n return orderByColumn;\n }\n\n public void setOrderByColumn(String orderByColumn)\n {\n this.orderByColumn = orderByColumn;\n }\n\n public String getIsAsc()\n {\n return isAsc;\n }\n\n public void setIsAsc(String isAsc)\n {\n this.isAsc = isAsc;\n }\n\n public Boolean getReasonable()\n {\n if (StringUtils.isNull(reasonable))\n {\n return Boolean.TRUE;\n }\n return reasonable;\n }\n\n public void setReasonable(Boolean reasonable)\n {\n this.reasonable = reasonable;\n }\n}" }, { "identifier": "TableSupport", "path": "src/main/java/com/ruoyi/framework/web/page/TableSupport.java", "snippet": "public class TableSupport\n{\n /**\n * 当前记录起始索引\n */\n public static final String PAGE_NUM = \"pageNum\";\n\n /**\n * 每页显示记录数\n */\n public static final String PAGE_SIZE = \"pageSize\";\n\n /**\n * 排序列\n */\n public static final String ORDER_BY_COLUMN = \"orderByColumn\";\n\n /**\n * 排序的方向 \"desc\" 或者 \"asc\".\n */\n public static final String IS_ASC = \"isAsc\";\n\n /**\n * 分页参数合理化\n */\n public static final String REASONABLE = \"reasonable\";\n\n /**\n * 封装分页对象\n */\n public static PageDomain getPageDomain()\n {\n PageDomain pageDomain = new PageDomain();\n pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));\n pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));\n pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));\n pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));\n pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));\n return pageDomain;\n }\n\n public static PageDomain buildPageRequest()\n {\n return getPageDomain();\n }\n}" } ]
import com.github.pagehelper.PageHelper; import com.ruoyi.common.utils.sql.SqlUtil; import com.ruoyi.framework.web.page.PageDomain; import com.ruoyi.framework.web.page.TableSupport;
1,306
package com.ruoyi.common.utils; /** * 分页工具类 * * @author ruoyi */ public class PageUtils extends PageHelper { /** * 设置请求分页数据 */ public static void startPage() {
package com.ruoyi.common.utils; /** * 分页工具类 * * @author ruoyi */ public class PageUtils extends PageHelper { /** * 设置请求分页数据 */ public static void startPage() {
PageDomain pageDomain = TableSupport.buildPageRequest();
2
2023-10-14 02:27:47+00:00
2k
Kartbllansh/ShavermaTG
Client-Rest/src/main/java/com/shaverma/rest/controller/MenuController.java
[ { "identifier": "ApiResponse", "path": "Server-Interaction/src/main/java/com/chaverma/api/ApiResponse.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ApiResponse<T> {\n private T data;\n private String message;\n private HttpStatusCode httpStatus;\n\n @JsonProperty(\"data\")\n public void setData(T data) {\n this.data = data;\n }\n}" }, { "identifier": "ResponseHandler", "path": "Server-Interaction/src/main/java/com/chaverma/response/ResponseHandler.java", "snippet": "@Slf4j\npublic class ResponseHandler {\n /**\n * Response builder response entity.\n *\n * @param message the message\n * @param httpStatus the http status\n * @param responseData the response data\n * @return the response entity\n */\n public static <T> ResponseEntity<ApiResponse<T>> responseBuilder(String message, HttpStatus httpStatus, T responseData) {\n\n ApiResponse<T> response = new ApiResponse<>(responseData, message, httpStatus);\n log.info(\"Successfully response with message: {} and status: {}\", message, httpStatus);\n\n return new ResponseEntity<>(response, httpStatus);\n }\n}" }, { "identifier": "Menu", "path": "DataBase/src/main/java/com/shaverma/database/entity/Menu.java", "snippet": "@Getter\n@Setter\n@EqualsAndHashCode(exclude = \"id\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"AppUser\")\npublic class Menu {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String typeDish;\n private String nameDish;\n private Double price;\n private Long calories;\n\n public MenuDTO toDTO(){\n return MenuDTO.builder()\n .typeDish(typeDish)\n .nameDish(nameDish)\n .price(price)\n .calories(calories).build();\n\n }\n\n}" }, { "identifier": "MenuService", "path": "Client-Rest/src/main/java/com/shaverma/rest/service/MenuService.java", "snippet": "public interface MenuService {\n List<MenuDTO> getMenu();\n}" } ]
import com.chaverma.api.ApiResponse; import com.chaverma.dto.MenuDTO; import com.chaverma.response.ResponseHandler; import com.shaverma.database.entity.Menu; import com.shaverma.rest.service.MenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List;
664
package com.shaverma.rest.controller; @RestController @RequestMapping("/api/menu") public class MenuController { private final MenuService menuService; @Autowired public MenuController(MenuService menuService) { this.menuService = menuService; } @GetMapping public ResponseEntity<ApiResponse<List<MenuDTO>>> getMenu(){ List<MenuDTO> menus = menuService.getMenu();
package com.shaverma.rest.controller; @RestController @RequestMapping("/api/menu") public class MenuController { private final MenuService menuService; @Autowired public MenuController(MenuService menuService) { this.menuService = menuService; } @GetMapping public ResponseEntity<ApiResponse<List<MenuDTO>>> getMenu(){ List<MenuDTO> menus = menuService.getMenu();
return ResponseHandler.responseBuilder("All menu was sent", HttpStatus.OK, menus);
1
2023-10-12 19:41:14+00:00
2k
Yunzez/SubDependency_CodeLine_Analysis
java/Calculator-master/src/main/java/com/houarizegai/calculator/ui/CalculatorUI.java
[ { "identifier": "Theme", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/theme/properties/Theme.java", "snippet": "public class Theme {\n\n private String name;\n private String applicationBackground;\n private String textColor;\n private String btnEqualTextColor;\n private String operatorBackground;\n private String numbersBackground;\n private String btnEqualBackground;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getApplicationBackground() {\n return applicationBackground;\n }\n\n public void setApplicationBackground(String applicationBackground) {\n this.applicationBackground = applicationBackground;\n }\n\n public String getTextColor() {\n return textColor;\n }\n\n public void setTextColor(String textColor) {\n this.textColor = textColor;\n }\n\n public String getBtnEqualTextColor() {\n return btnEqualTextColor;\n }\n\n public void setBtnEqualTextColor(String btnEqualTextColor) {\n this.btnEqualTextColor = btnEqualTextColor;\n }\n\n public String getOperatorBackground() {\n return operatorBackground;\n }\n\n public void setOperatorBackground(String operatorBackground) {\n this.operatorBackground = operatorBackground;\n }\n\n public String getNumbersBackground() {\n return numbersBackground;\n }\n\n public void setNumbersBackground(String numbersBackground) {\n this.numbersBackground = numbersBackground;\n }\n\n public String getBtnEqualBackground() {\n return btnEqualBackground;\n }\n\n public void setBtnEqualBackground(String btnEqualBackground) {\n this.btnEqualBackground = btnEqualBackground;\n }\n}" }, { "identifier": "ThemeLoader", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/theme/ThemeLoader.java", "snippet": "public class ThemeLoader {\n\n private ThemeLoader() {\n throw new AssertionError(\"Constructor is not allowed\");\n }\n\n public static Map<String, Theme> loadThemes() {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n try {\n ThemeList themeList = mapper.readValue(new File(\"src/main/resources/application.yaml\"), ThemeList.class);\n return themeList.getThemesAsMap();\n } catch (IOException e) {\n return Collections.emptyMap();\n }\n }\n}" }, { "identifier": "hex2Color", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/util/ColorUtil.java", "snippet": "public static Color hex2Color(String colorHex) {\n return Optional.ofNullable(colorHex)\n .map(hex -> new Color(\n Integer.valueOf(colorHex.substring(0, 2), 16),\n Integer.valueOf(colorHex.substring(2, 4), 16),\n Integer.valueOf(colorHex.substring(4, 6), 16)))\n .orElse(null);\n}" } ]
import com.houarizegai.calculator.theme.properties.Theme; import com.houarizegai.calculator.theme.ThemeLoader; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ItemEvent; import java.util.Map; import java.util.regex.Pattern; import java.awt.Color; import javax.swing.*; import static com.houarizegai.calculator.util.ColorUtil.hex2Color;
1,118
package com.houarizegai.calculator.ui; public class CalculatorUI { private static final String FONT_NAME = "Comic Sans MS"; private static final String DOUBLE_OR_NUMBER_REGEX = "([-]?\\d+[.]\\d*)|(\\d+)|(-\\d+)"; private static final String APPLICATION_TITLE = "Calculator"; private static final int WINDOW_WIDTH = 410; private static final int WINDOW_HEIGHT = 600; private static final int BUTTON_WIDTH = 80; private static final int BUTTON_HEIGHT = 70; private static final int MARGIN_X = 20; private static final int MARGIN_Y = 60; private final JFrame window; private JComboBox<String> comboCalculatorType; private JComboBox<String> comboTheme; private JTextField inputScreen; private JButton btnC; private JButton btnBack; private JButton btnMod; private JButton btnDiv; private JButton btnMul; private JButton btnSub; private JButton btnAdd; private JButton btn0; private JButton btn1; private JButton btn2; private JButton btn3; private JButton btn4; private JButton btn5; private JButton btn6; private JButton btn7; private JButton btn8; private JButton btn9; private JButton btnPoint; private JButton btnEqual; private JButton btnRoot; private JButton btnPower; private JButton btnLog; private char selectedOperator = ' '; private boolean go = true; // For calculate with Opt != (=) private boolean addToDisplay = true; // Connect numbers in display private double typedValue = 0;
package com.houarizegai.calculator.ui; public class CalculatorUI { private static final String FONT_NAME = "Comic Sans MS"; private static final String DOUBLE_OR_NUMBER_REGEX = "([-]?\\d+[.]\\d*)|(\\d+)|(-\\d+)"; private static final String APPLICATION_TITLE = "Calculator"; private static final int WINDOW_WIDTH = 410; private static final int WINDOW_HEIGHT = 600; private static final int BUTTON_WIDTH = 80; private static final int BUTTON_HEIGHT = 70; private static final int MARGIN_X = 20; private static final int MARGIN_Y = 60; private final JFrame window; private JComboBox<String> comboCalculatorType; private JComboBox<String> comboTheme; private JTextField inputScreen; private JButton btnC; private JButton btnBack; private JButton btnMod; private JButton btnDiv; private JButton btnMul; private JButton btnSub; private JButton btnAdd; private JButton btn0; private JButton btn1; private JButton btn2; private JButton btn3; private JButton btn4; private JButton btn5; private JButton btn6; private JButton btn7; private JButton btn8; private JButton btn9; private JButton btnPoint; private JButton btnEqual; private JButton btnRoot; private JButton btnPower; private JButton btnLog; private char selectedOperator = ' '; private boolean go = true; // For calculate with Opt != (=) private boolean addToDisplay = true; // Connect numbers in display private double typedValue = 0;
private final Map<String, Theme> themesMap;
0
2023-10-14 20:31:35+00:00
2k
jocasilvalima/aulasimple-api
src/main/java/com/joaocarlos/aulasimple/services/UserService.java
[ { "identifier": "User", "path": "src/main/java/com/joaocarlos/aulasimple/model/User.java", "snippet": "@Entity \n@Table(name = \"user\")\npublic class User {\n\t\n\tpublic interface CreateUser {\n\t\t}\n\t\n\tpublic interface UpdateUser{\n\t\t}\n\t\n public static final String TABLE_NAME = \"user\";\n \n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\", unique = true)\n private Long id;\n \n @Column(name = \"username\", length = 100, nullable = false, unique = true)\n @NotNull(groups = CreateUser.class)\n @NotEmpty(groups = CreateUser.class)\n @Size(groups = CreateUser.class, min = 4, max = 100)\n private String username;\n \n \n @JsonProperty(access = Access.WRITE_ONLY)\n @Column(name = \"password\", length = 60, nullable =false )\n @NotNull(groups = {CreateUser.class, UpdateUser.class})\n @NotEmpty(groups = {CreateUser.class, UpdateUser.class})\n @Size(groups = {CreateUser.class, UpdateUser.class}, min = 8, max = 60)\n private String password;\n\n\n \n @OneToMany(mappedBy = \"user\")\n private List<Task> tasks = new ArrayList<Task>();\n \n \n \n \n \n public User() {\n\t\t\n }\n\n\npublic User(Long id,\n\t\t@NotNull(groups = CreateUser.class) @NotEmpty(groups = CreateUser.class) @Size(groups = CreateUser.class, min = 4, max = 100) String username,\n\t\t@NotNull(groups = { CreateUser.class, UpdateUser.class }) @NotEmpty(groups = { CreateUser.class,\n\t\t\t\tUpdateUser.class }) @Size(groups = { CreateUser.class,\n\t\t\t\t\t\tUpdateUser.class }, min = 8, max = 60) String password) {\n\tsuper();\n\tthis.id = id;\n\tthis.username = username;\n\tthis.password = password;\n}\n\n\npublic Long getId() {\n\treturn id;\n}\n\n\npublic void setId(Long id) {\n\tthis.id = id;\n}\n\n\npublic String getUsername() {\n\treturn username;\n}\n\n\npublic void setUsername(String username) {\n\tthis.username = username;\n}\n\n\npublic String getPassword() {\n\treturn password;\n}\n\n\npublic void setPassword(String password) {\n\tthis.password = password;\n}\n\n\npublic List<Task> getTasks() {\n\treturn tasks;\n}\n\n\npublic void setTasks(List<Task> tasks) {\n\tthis.tasks = tasks;\n}\n\n\n@Override\npublic int hashCode() {\n\tfinal int prime = 31;\n\tint result = 1;\n\tresult = prime * result + ((this.id == null) ? 0 : this.id.hashCode());\n\treturn result;\n}\n\n\n@Override\npublic boolean equals(Object obj) {\n\tif (this == obj)\n\t\treturn true;\n\tif (obj == null)\n\t\treturn false;\n\tif (getClass() != obj.getClass())\n\t\treturn false;\n\tUser other = (User) obj;\n\treturn Objects.equals(id, other.id) && Objects.equals(password, other.password)\n\t\t\t&& Objects.equals(username, other.username);\n}\n \n \n}" }, { "identifier": "TaskRepository", "path": "src/main/java/com/joaocarlos/aulasimple/repository/TaskRepository.java", "snippet": "@Repository\npublic interface TaskRepository extends JpaRepository<Task, Long>{\n\t\n\tList<Task>buscarPeloIdentificador(Long id);\n\n\tvoid saveAll(List<com.joaocarlos.aulasimple.model.Task> tasks);\n\t\n\n}" }, { "identifier": "UserRepository", "path": "src/main/java/com/joaocarlos/aulasimple/repository/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, Long> {\n\n}" } ]
import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.joaocarlos.aulasimple.model.User; import com.joaocarlos.aulasimple.repository.TaskRepository; import com.joaocarlos.aulasimple.repository.UserRepository;
1,009
package com.joaocarlos.aulasimple.services; @Service public class UserService { @Autowired
package com.joaocarlos.aulasimple.services; @Service public class UserService { @Autowired
private UserRepository userRepository;
2
2023-10-14 00:12:34+00:00
2k
notoriux/xshellmenu
xshellmenu-gui/src/main/java/it/xargon/xshellmenu/gui/XSMenuItemComponent.java
[ { "identifier": "XSMenuItem", "path": "xshellmenu-api/src/main/java/it/xargon/xshellmenu/api/XSMenuItem.java", "snippet": "public interface XSMenuItem {\n\tpublic enum MenuType {\n\t\tPRIMARY, AUXILIARY;\n\t}\n\t\n\tdefault boolean isSeparator() {return false;}\n\tpublic String getLabel();\n\tpublic Icon getIcon();\n\tpublic Runnable getAction();\n\tpublic int countChildren(MenuType menuType);\n\tpublic XSMenuItem getChild(MenuType menuType, int index);\n\tpublic boolean isEnabled();\n\tpublic String getTooltip();\n}" }, { "identifier": "XSPlatformResource", "path": "xshellmenu-api/src/main/java/it/xargon/xshellmenu/api/XSPlatformResource.java", "snippet": "public final class XSPlatformResource<T> {\n\tpublic final static XSPlatformResource<Icon> GENERIC_ICON = resourceOf(Icon.class);\n\tpublic final static XSPlatformResource<Icon> APPLICATION_ICON = resourceOf(Icon.class);\n\tpublic final static XSPlatformResource<ScheduledExecutorService> TASK_SCHEDULER = resourceOf(ScheduledExecutorService.class);\n\tpublic final static XSPlatformResource<ExecutorService> ICONFETCHER_SCHEDULER = resourceOf(ExecutorService.class);\n\t\n\tprivate Class<T> resourceClass;\n\t\n\tprivate static <T> XSPlatformResource<T> resourceOf(Class<T> resourceClass) {\n\t\treturn new XSPlatformResource<>(resourceClass);\n\t}\n\t\n\tprivate XSPlatformResource(Class<T> resourceClass) {\n\t\tthis.resourceClass = Objects.requireNonNull(resourceClass);\n\t}\n\t\n\tpublic T cast(Object obj) {return resourceClass.cast(obj);}\n}" }, { "identifier": "InMemoryMenuItem", "path": "xshellmenu-api/src/main/java/it/xargon/xshellmenu/api/base/InMemoryMenuItem.java", "snippet": "public class InMemoryMenuItem implements XSMenuItem {\n\tprivate String label;\n\tprivate String tooltip;\n\tprivate Icon icon;\n\tprivate Runnable action;\n\t\n\tprivate ArrayList<XSMenuItem> children;\n\t\n\tpublic InMemoryMenuItem(String label, Icon icon) {\n\t\tthis(label, icon, null, null);\n\t}\n\t\n\tpublic InMemoryMenuItem(String label, Icon icon, String tooltip, Runnable action) {\n\t\tthis.label = label;\n\t\tthis.icon = icon;\n\t\tthis.tooltip = tooltip;\n\t\tthis.action = action;\n\t\tthis.children = new ArrayList<>();\n\t}\n\t\n\tpublic InMemoryMenuItem addChild(String label, Icon icon) {\n\t\treturn addChild(label, icon, null, null);\n\t}\n\t\n\tpublic InMemoryMenuItem addChild(String label, Icon icon, String tooltip, Runnable action) {\n\t\tInMemoryMenuItem result = new InMemoryMenuItem(label, icon, tooltip, action);\n\t\tchildren.add(result);\n\t\treturn result;\n\t}\n\t\n\tpublic void addSeparator() {\n\t\tchildren.add(new SeparatorMenuItem());\n\t}\n\n\t@Override\n\tpublic String getLabel() {return label;}\n\n\t@Override\n\tpublic Icon getIcon() {return icon;}\n\t\n\t@Override\n\tpublic Runnable getAction() {return action;}\n\t\n\t@Override\n\tpublic int countChildren(MenuType menuType) {\n\t\tif (MenuType.PRIMARY.equals(menuType)) return children.size();\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic XSMenuItem getChild(MenuType menuType, int index) {\n\t\tif (MenuType.PRIMARY.equals(menuType)) return children.get(index);\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tpublic boolean isEnabled() {return true;}\n\t\n\t@Override\n\tpublic String getTooltip() {return tooltip;}\n}" }, { "identifier": "Resources", "path": "xshellmenu-gui/src/main/java/it/xargon/xshellmenu/res/Resources.java", "snippet": "public class Resources {\n\tprivate Resources() {}\n\t\n\tpublic final static XSPlatform xsGuiPlatform;\n\t\n\tpublic final static BaseMultiResolutionImage appIconImage;\n\tpublic final static ImageIcon appIcon;\n\tpublic final static ImageIcon quitIcon;\n\tpublic final static ImageIcon genericIcon;\n\tpublic final static ImageIcon expandIcon;\n\t\n\tstatic {\n\t\txsGuiPlatform = new XSGuiPlatform();\n\t\t\n\t\ttry {\n\t\t\tString prefix = xsGuiPlatform.isDarkModeSystemTheme() ? \"dark\" : \"light\";\n\t\t\t\n\t\t\tImage[] allSizesAppIcon = new Image[] {\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-16.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-32.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-48.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-64.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-128.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-256.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-512.png\"))\t\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\tappIconImage = new BaseMultiResolutionImage(0, allSizesAppIcon);\n\t\t\tappIcon = new ImageIcon(appIconImage);\n\t\t\t\n\t\t\tgenericIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"generic-icon.png\")));\n\t\t\texpandIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"expand-icon.png\")));\n\t\t\tquitIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"quit-icon.png\")));\n\t\t} catch (IOException ex) {\n\t\t\tthrow new IllegalStateException(\"Unable to initialize resources\", ex);\n\t\t}\n\t}\n}" } ]
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.MouseEvent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.event.MouseInputAdapter; import it.xargon.xshellmenu.api.XSMenuItem; import it.xargon.xshellmenu.api.XSPlatformResource; import it.xargon.xshellmenu.api.base.InMemoryMenuItem; import it.xargon.xshellmenu.res.Resources;
1,574
package it.xargon.xshellmenu.gui; public class XSMenuItemComponent extends JPanel { private static final long serialVersionUID = 2267459892158068804L; private JLabel lblMenuItemText; private JLabel lblExpandIcon; private XSMenuItem menuItem; private Color hoverBorderColor = UIManager.getColor("MenuItem.selectionBackground"); private Color itemDisabledColor = UIManager.getColor("MenuItem.disabledForeground"); private Border normalBorder = new EmptyBorder(5, 5, 5, 5); private Border hoverBorder = new XSRoundBorder(hoverBorderColor, 1, 5); private XSMenuItemListener itemListener = null; private MouseInputAdapter mouseInputHandler = new MouseInputAdapter() { public void mouseEntered(MouseEvent e) { setBorder(hoverBorder); itemListener.mouseEntered(menuItem); } public void mouseExited(MouseEvent e) { setBorder(normalBorder); itemListener.mouseExited(menuItem); } public void mouseClicked(MouseEvent e) { itemListener.mouseActionClicked(menuItem, e.getButton()); } }; public XSMenuItemComponent() {
package it.xargon.xshellmenu.gui; public class XSMenuItemComponent extends JPanel { private static final long serialVersionUID = 2267459892158068804L; private JLabel lblMenuItemText; private JLabel lblExpandIcon; private XSMenuItem menuItem; private Color hoverBorderColor = UIManager.getColor("MenuItem.selectionBackground"); private Color itemDisabledColor = UIManager.getColor("MenuItem.disabledForeground"); private Border normalBorder = new EmptyBorder(5, 5, 5, 5); private Border hoverBorder = new XSRoundBorder(hoverBorderColor, 1, 5); private XSMenuItemListener itemListener = null; private MouseInputAdapter mouseInputHandler = new MouseInputAdapter() { public void mouseEntered(MouseEvent e) { setBorder(hoverBorder); itemListener.mouseEntered(menuItem); } public void mouseExited(MouseEvent e) { setBorder(normalBorder); itemListener.mouseExited(menuItem); } public void mouseClicked(MouseEvent e) { itemListener.mouseActionClicked(menuItem, e.getButton()); } }; public XSMenuItemComponent() {
InMemoryMenuItem iMenuItem = new InMemoryMenuItem("Menu item text", Resources.genericIcon);
3
2023-10-14 16:43:45+00:00
2k
FOBshippingpoint/ncu-punch-clock
src/main/java/com/sdovan1/ncupunchclock/user/UserController.java
[ { "identifier": "PunchAgentFactory", "path": "src/main/java/com/sdovan1/ncupunchclock/schedule/PunchAgentFactory.java", "snippet": "@Component\npublic class PunchAgentFactory {\n @Value(\"${chrome-driver-binary-path}\")\n private String chromeDriverBinaryPath;\n\n @Value(\"${web-driver-headless}\")\n private boolean isWebDriverHeadless;\n public PunchAgent create(String username, String password) {\n var driver = createChromeDriver();\n return new PunchAgent(driver, null, username, password);\n }\n\n public PunchAgent create(String partTimeUsuallyId, String username, String password) {\n var driver = createChromeDriver();\n return new PunchAgent(driver, partTimeUsuallyId, username, password);\n }\n\n private WebDriver createChromeDriver() {\n var option = new ChromeOptions();\n if (isWebDriverHeadless) {\n option.addArguments(\"--headless\");\n }\n if (chromeDriverBinaryPath != null) {\n option.setBinary(chromeDriverBinaryPath);\n }\n return new ChromeDriver(option);\n }\n}" }, { "identifier": "PasscodeRepository", "path": "src/main/java/com/sdovan1/ncupunchclock/passcode/PasscodeRepository.java", "snippet": "public interface PasscodeRepository extends CrudRepository<Passcode, Long> {\n Optional<Passcode> findByPasscode(String passcode);\n\n void deleteByPasscode(String passcode);\n}" }, { "identifier": "PunchLoginFailedException", "path": "src/main/java/com/sdovan1/ncupunchclock/schedule/PunchLoginFailedException.java", "snippet": "public class PunchLoginFailedException extends RuntimeException {\n public static final String FAILED_TO_PASS_CAPTCHA = \"無法通過機器人檢查\";\n public static final String WRONG_USERNAME_OR_PASSWORD = \"Portal帳號或密碼錯誤\";\n public static final String TIMEOUT = \"逾時\";\n public PunchLoginFailedException(String message) {\n super(message);\n }\n}" } ]
import com.sdovan1.ncupunchclock.schedule.PunchAgentFactory; import com.sdovan1.ncupunchclock.passcode.PasscodeRepository; import com.sdovan1.ncupunchclock.schedule.PunchLoginFailedException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap;
1,429
package com.sdovan1.ncupunchclock.user; @Controller @Slf4j public class UserController { @Autowired private UserRepository userRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private UserPasswordEncryptor userPasswordEncryptor; private final SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); private final Map<String, CompletableFuture<Void>> verifyFutures = new ConcurrentHashMap<>(); @Autowired private PunchAgentFactory punchAgentFactory; @InitBinder public void setAllowedFields(WebDataBinder binder) { binder.setDisallowedFields("id"); } @ModelAttribute("user") public User user() { return new User(); } @InitBinder("changePasswordDTO") public void initChangePasswordDTOValidator(WebDataBinder binder) { binder.setValidator(new ChangePasswordDTOValidator()); } @GetMapping("/sign_up") public String signUp(Model model) { model.addAttribute("user", new User()); return "sign_up"; } @PostMapping("/sign_up") public String register(@Valid User user, Model model, BindingResult result) { if (userRepository.findByUsername(user.getUsername()).isPresent()) { result.rejectValue("password", "usernameAlreadyExists", "這個帳號已有人使用,請試試其他名稱。"); } if (!user.getPassword().equals(user.getConfirmPassword())) { result.rejectValue("password", "passwordsDoNotMatch", "您輸入的兩個密碼並不相符,請再試一次。"); } if (user.getUsername().equals(user.getPassword())) { result.rejectValue("password", "passwordSameAsUsername", "您的密碼不能和帳號相同,請再試一次。"); } if (passcodeRepository.findByPasscode(user.getPasscode()).isEmpty()) { result.rejectValue("passcode", "passcodeDoesNotExist", "邀請碼錯誤。"); } if (result.hasErrors()) { return "sign_up"; } var verifyId = UUID.randomUUID().toString(); var isPortalAccountValid = verifyPortalAccount(user); verifyFutures.put(verifyId, isPortalAccountValid); isPortalAccountValid.whenComplete((v, ex) -> { if (ex == null) { userPasswordEncryptor.setPassword(user, user.getPassword()); userRepository.save(user); passcodeRepository.deleteByPasscode(user.getPasscode()); log.info("User {} registered", user.getUsername()); log.info("Passcode {} consumed", user.getPasscode()); } }); model.addAttribute("verifyId", verifyId); return "verify_account"; } public CompletableFuture<Void> verifyPortalAccount(User user) { return CompletableFuture.runAsync(() -> { var agent = punchAgentFactory.create(user.getUsername(), user.getPassword()); try { agent.login(); } finally { agent.getDriver().quit(); } }); } @GetMapping("/sse/verify_account/{verifyId}") public SseEmitter getSseEmitter(@PathVariable String verifyId) { var emitter = new SseEmitter(); if (verifyFutures.containsKey(verifyId)) { var future = verifyFutures.get(verifyId); future.whenComplete((result, ex) -> { var event = SseEmitter.event().name("message"); if (ex != null) {
package com.sdovan1.ncupunchclock.user; @Controller @Slf4j public class UserController { @Autowired private UserRepository userRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private UserPasswordEncryptor userPasswordEncryptor; private final SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); private final Map<String, CompletableFuture<Void>> verifyFutures = new ConcurrentHashMap<>(); @Autowired private PunchAgentFactory punchAgentFactory; @InitBinder public void setAllowedFields(WebDataBinder binder) { binder.setDisallowedFields("id"); } @ModelAttribute("user") public User user() { return new User(); } @InitBinder("changePasswordDTO") public void initChangePasswordDTOValidator(WebDataBinder binder) { binder.setValidator(new ChangePasswordDTOValidator()); } @GetMapping("/sign_up") public String signUp(Model model) { model.addAttribute("user", new User()); return "sign_up"; } @PostMapping("/sign_up") public String register(@Valid User user, Model model, BindingResult result) { if (userRepository.findByUsername(user.getUsername()).isPresent()) { result.rejectValue("password", "usernameAlreadyExists", "這個帳號已有人使用,請試試其他名稱。"); } if (!user.getPassword().equals(user.getConfirmPassword())) { result.rejectValue("password", "passwordsDoNotMatch", "您輸入的兩個密碼並不相符,請再試一次。"); } if (user.getUsername().equals(user.getPassword())) { result.rejectValue("password", "passwordSameAsUsername", "您的密碼不能和帳號相同,請再試一次。"); } if (passcodeRepository.findByPasscode(user.getPasscode()).isEmpty()) { result.rejectValue("passcode", "passcodeDoesNotExist", "邀請碼錯誤。"); } if (result.hasErrors()) { return "sign_up"; } var verifyId = UUID.randomUUID().toString(); var isPortalAccountValid = verifyPortalAccount(user); verifyFutures.put(verifyId, isPortalAccountValid); isPortalAccountValid.whenComplete((v, ex) -> { if (ex == null) { userPasswordEncryptor.setPassword(user, user.getPassword()); userRepository.save(user); passcodeRepository.deleteByPasscode(user.getPasscode()); log.info("User {} registered", user.getUsername()); log.info("Passcode {} consumed", user.getPasscode()); } }); model.addAttribute("verifyId", verifyId); return "verify_account"; } public CompletableFuture<Void> verifyPortalAccount(User user) { return CompletableFuture.runAsync(() -> { var agent = punchAgentFactory.create(user.getUsername(), user.getPassword()); try { agent.login(); } finally { agent.getDriver().quit(); } }); } @GetMapping("/sse/verify_account/{verifyId}") public SseEmitter getSseEmitter(@PathVariable String verifyId) { var emitter = new SseEmitter(); if (verifyFutures.containsKey(verifyId)) { var future = verifyFutures.get(verifyId); future.whenComplete((result, ex) -> { var event = SseEmitter.event().name("message"); if (ex != null) {
if (ex.getCause() instanceof PunchLoginFailedException e) {
2
2023-10-12 15:41:58+00:00
2k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/module/modules/combat/AntiKnockback.java
[ { "identifier": "Event", "path": "src/main/java/net/shadowclient/main/event/Event.java", "snippet": "public abstract class Event {\n public boolean cancelled = false;\n public void cancel() {\n this.cancelled = true;\n }\n public void uncancel() {\n this.cancelled = false;\n }\n}" }, { "identifier": "KnockbackEvent", "path": "src/main/java/net/shadowclient/main/event/events/KnockbackEvent.java", "snippet": "public class KnockbackEvent extends Event {\n public double x, y, z;\n public KnockbackEvent(double x, double y, double z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n}" }, { "identifier": "Module", "path": "src/main/java/net/shadowclient/main/module/Module.java", "snippet": "public abstract class Module {\n\n public final ModuleCategory category;\n public final String moduleName;\n public final String friendlyName;\n public final String description;\n\n public KeyBinding keybinding;\n\n public ModuleButton moduleButton = null;\n\n public boolean enabled;\n\n public List<Setting> getSettings() {\n return settings;\n }\n\n public void addSetting(Setting setting) {\n settings.add(setting);\n }\n\n public void addSettings(Setting...settings) {\n for (Setting setting : settings) {\n addSetting(setting);\n }\n }\n\n public final List<Setting> settings = new ArrayList<>();\n\n public final MinecraftClient mc = MinecraftClient.getInstance();\n\n public Module(String name, String friendlyName, String description, ModuleCategory category) {\n moduleName = name;\n this.category = category;\n this.friendlyName = friendlyName;\n this.description = description;\n }\n\n public void setEnabled() {\n this.enabled = true;\n this.onEnable();\n if (this.getClass().isAnnotationPresent(OneClick.class)) {\n setDisabled();\n }\n }\n public void setDisabled() {\n this.enabled = false;\n this.onDisable();\n }\n\n public void setEnabled(boolean event) {\n if (event) {\n this.onEnable();\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event) {\n if (event) {\n this.onDisable();\n }\n this.enabled = false;\n }\n\n public boolean showMessage = true;\n\n public void setEnabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onEnable();\n showMessage = msgOld;\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onDisable();\n showMessage = msgOld;\n }\n this.enabled = false;\n }\n\n public void toggle() {\n if (enabled) {\n setDisabled();\n return;\n }\n setEnabled();\n }\n\n public void onEnable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onDisable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onEvent(Event event) {}\n\n public void postInit() {}\n\n}" }, { "identifier": "ModuleCategory", "path": "src/main/java/net/shadowclient/main/module/ModuleCategory.java", "snippet": "public enum ModuleCategory {\n COMBAT(\"Combat\"),\n PLAYER(\"Player\"),\n MOVEMENT(\"Movement\"),\n WORLD(\"World\"),\n RENDER(\"Render\"),\n FUN(\"Fun\"),\n OTHER(\"Other\"),\n MENUS(\"Menus\");\n\n public final String name;\n\n ModuleCategory(String name) {\n this.name = name;\n }\n}" }, { "identifier": "NumberSetting", "path": "src/main/java/net/shadowclient/main/setting/settings/NumberSetting.java", "snippet": "public class NumberSetting extends Setting {\n\n public final int decimalPlaces;\n\n public NumberSetting(String name, Number min, Number max, Number defaultValue, int decimalPlaces) {\n super(name, min, max, defaultValue);\n this.decimalPlaces = decimalPlaces;\n }\n}" } ]
import net.shadowclient.main.annotations.EventListener; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.event.Event; import net.shadowclient.main.event.events.KnockbackEvent; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleCategory; import net.shadowclient.main.setting.settings.NumberSetting;
1,191
package net.shadowclient.main.module.modules.combat; @SearchTags({"no knockback", "anti knockback"}) @EventListener({KnockbackEvent.class}) public class AntiKnockback extends Module { public final NumberSetting STRENGTH = new NumberSetting("Strength", 0.01f, 1f, 1f, 2); public AntiKnockback() {
package net.shadowclient.main.module.modules.combat; @SearchTags({"no knockback", "anti knockback"}) @EventListener({KnockbackEvent.class}) public class AntiKnockback extends Module { public final NumberSetting STRENGTH = new NumberSetting("Strength", 0.01f, 1f, 1f, 2); public AntiKnockback() {
super("antiknockback", "No Knockback", "Don't take any knockback from attacks.", ModuleCategory.COMBAT);
3
2023-10-07 06:55:12+00:00
2k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/client/gui/VoicePanels.java
[ { "identifier": "GuiMclibVoiceDashboard", "path": "src/main/java/mrkto/mvoice/client/gui/VoiceMclibPanel/GuiMclibVoiceDashboard.java", "snippet": "public class GuiMclibVoiceDashboard extends GuiDashboardPanel<GuiDashboard>\n{\n GuiPlayerListElement list;\n public GuiMclibVoiceDashboard(Minecraft mc, GuiDashboard dashboard)\n {\n super(mc, dashboard);\n\n this.list = new GuiPlayerListElement(mc, IKey.lang(\"mvoice.settings.playerlist\"), this::playerList);\n this.list.flex().relative(this.flex()).set(0, 0, 120, 0).h(1F).x(1F, -120);\n this.add(this.list);\n\n GuiIconElement reload = new GuiIconElement(mc, Icons.REFRESH, (b) -> this.list.reload(mc));\n reload.flex().set(0, 2, 24, 24).relative(this).x(1F, -28);\n\n this.add(reload);\n }\n\n private void playerList(Object o) {\n PlayerSettingsOverlay panel = new PlayerSettingsOverlay(this.mc, o.toString());\n\n GuiOverlay.addOverlay(GuiBase.getCurrent(), panel, 0.7F, 0.9F);\n }\n\n private void PlayerElement(GuiPlayerElement e) {\n ClientData data = ClientData.getInstance();\n data.getData().put(e.name, e.volume.value);\n data.save();\n }\n\n @Override\n public boolean isClientSideOnly()\n {\n return true;\n }\n}" }, { "identifier": "MVIcons", "path": "src/main/java/mrkto/mvoice/utils/other/mclib/MVIcons.java", "snippet": "public class MVIcons {\n public static final ResourceLocation TEXTURE = new ResourceLocation(MappetVoice.MOD_ID, \"textures/voice.png\");\n\n public static final Icon MutedD = new Icon(TEXTURE, 0, 0, 16, 16, 64, 64);\n public static final Icon MutedMicro = new Icon(TEXTURE, 16, 0, 16, 16, 64, 64);\n public static final Icon MutedSpeaker = new Icon(TEXTURE, 32, 0, 16, 16, 64, 64);\n public static final Icon MutedEarphones = new Icon(TEXTURE, 48, 0, 16, 16, 64, 64);\n public static final Icon D = new Icon(TEXTURE, 0, 16, 16, 16, 64, 64);\n public static final Icon Micro = new Icon(TEXTURE, 16, 16, 16, 16, 64, 64);\n public static final Icon Speaker = new Icon(TEXTURE, 32, 16, 16, 16, 64, 64);\n public static final Icon Earphones = new Icon(TEXTURE, 48, 16, 16, 16, 64, 64);\n\n public static void register()\n {\n IconRegistry.register(\"MutedDinamo\", MutedD);\n IconRegistry.register(\"MutedMicro\", MutedMicro);\n IconRegistry.register(\"MutedSpeaker\", MutedSpeaker);\n IconRegistry.register(\"MutedEarphones\", MutedEarphones);\n\n IconRegistry.register(\"Dinamo\", D);\n IconRegistry.register(\"Micro\", Micro);\n IconRegistry.register(\"Speaker\", Speaker);\n IconRegistry.register(\"Earphones\", Earphones);\n }\n}" } ]
import mchorse.mappet.client.gui.GuiMappetDashboard; import mchorse.mclib.client.gui.mclib.GuiAbstractDashboard; import mchorse.mclib.client.gui.mclib.GuiDashboard; import mchorse.mclib.client.gui.utils.keys.IKey; import mchorse.mclib.events.RegisterDashboardPanels; import mchorse.mclib.events.RemoveDashboardPanels; import mrkto.mvoice.client.gui.VoiceMclibPanel.GuiMclibVoiceDashboard; import mrkto.mvoice.utils.other.mclib.MVIcons; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
1,068
package mrkto.mvoice.client.gui; @SideOnly(Side.CLIENT) public class VoicePanels { GuiMclibVoiceDashboard voicePanel; @SubscribeEvent public void OnDashboardRegister(RegisterDashboardPanels event){ Minecraft mc = Minecraft.getMinecraft(); GuiAbstractDashboard dashboard = event.dashboard; if(dashboard instanceof GuiDashboard){ this.voicePanel = new GuiMclibVoiceDashboard(mc, (GuiDashboard) dashboard);
package mrkto.mvoice.client.gui; @SideOnly(Side.CLIENT) public class VoicePanels { GuiMclibVoiceDashboard voicePanel; @SubscribeEvent public void OnDashboardRegister(RegisterDashboardPanels event){ Minecraft mc = Minecraft.getMinecraft(); GuiAbstractDashboard dashboard = event.dashboard; if(dashboard instanceof GuiDashboard){ this.voicePanel = new GuiMclibVoiceDashboard(mc, (GuiDashboard) dashboard);
dashboard.panels.registerPanel(this.voicePanel, IKey.lang("mvoice.settings.dashboard"), MVIcons.Earphones);
1
2023-10-14 19:20:12+00:00
2k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/JoinCombiner.java
[ { "identifier": "Abap", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Abap.java", "snippet": "public final class Abap {\n\n\t// class to store keywords and stuff\n\t// --> easier to find use with 'where used list'\n\n\tpublic static final List<String> JOINS = Arrays.asList(\"INNER JOIN\", \"JOIN\", \"CROSS JOIN\", \"OUTER JOIN\",\n\t\t\t\"FULL OUTER JOIN\", \"LEFT OUTER JOIN\", \"RIGHT OUTER JOIN\", \"LEFT JOIN\", \"RIGHT JOIN\");\n\n\tpublic static final String ORDERBY = \"ORDER BY\";\n\tpublic static final String SELECT = \"SELECT\";\n\tpublic static final String UPTO = \"UP TO\";\n\tpublic static final String FROM = \"FROM\";\n\tpublic static final String SELECTFROM = \"SELECT FROM\";\n\tpublic static final String SELECT_SINGLE_FROM = \"SELECT SINGLE FROM\";\n\tpublic static final String INTO = \"INTO\";\n\tpublic static final String WHERE = \"WHERE\";\n\tpublic static final String GROUPBY = \"GROUP BY\";\n\tpublic static final String HAVING = \"HAVING\";\n\tpublic static final String FIELDS = \"FIELDS\";\n\tpublic static final String CONNECTION = \"CONNECTION\";\n\tpublic static final String FORALLENTRIES = \"FOR ALL ENTRIES\";\n\tpublic static final String APPENDING = \"APPENDING\";\n\tpublic static final String OFFSET = \"OFFSET\";\n\tpublic static final String COMMENT = \"COMMENT\";\n\tpublic static final String SINGLE = \"SINGLE\";\n\tpublic static final String INTO_COR_FI_OF = \"INTO CORRESPONDING FIELDS\";\n}" }, { "identifier": "Activator", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Activator.java", "snippet": "public class Activator extends AbstractUIPlugin {\n\n\t// The shared instance\n\tprivate static Activator plugin;\n\n\t// The plug-in ID\n\tpublic static final String PLUGIN_ID = \"com.abap.sql.beautifier\"; //$NON-NLS-1$\n\n\t/**\n\t * Returns the shared instance\n\t *\n\t * @return the shared instance\n\t */\n\tpublic static Activator getDefault() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The constructor\n\t */\n\tpublic Activator() {\n\t}\n\n\t@Override\n\tpublic void start(BundleContext context) throws Exception {\n\t\tsuper.start(context);\n\t\tplugin = this;\n\t}\n\n\t@Override\n\tpublic void stop(BundleContext context) throws Exception {\n\t\tplugin = null;\n\t\tsuper.stop(context);\n\t}\n\n}" }, { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"COMBINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_SELECT = \"COMBINE_SMALL_SELECT\";\n\n\tpublic static final String COMMAS = \"COMMAS\";\n\n\tpublic static final String ESCAPING = \"ESCAPING\";\n\n\tpublic static final String OPERSTYLE = \"OPERSTYLE\";\n\n\tpublic static final String ORDER_OLD_SYNTAX = \"ORDER_OLD_SYNTAX\";\n\t\n\tpublic static final String ORDER_NEW_SYNTAX = \"ORDER_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL = \"TAB_ALL\";\n\n\tpublic static final String TAB_CONDITIONS = \"TAB_CONDITIONS\";\n\n\tpublic static final String LINE_CHAR_LIMIT = \"LINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS_LIMIT = \"COMBINE_SMALL_JOINS_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS = \"COMBINE_SMALL_JOINS\";\n\n\tpublic static final String TAB_CONDITIONS_NEW_SYNTAX = \"TAB_CONDITIONS_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL_NEW_SYNTAX = \"TAB_ALL_NEW_SYNTAX\";\n\n\tpublic static final String COMMENTSTYLE = \"COMMENTSTYLE\";\n\n}" }, { "identifier": "AbapSqlPart", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/AbapSqlPart.java", "snippet": "public class AbapSqlPart {\n\n\tpublic String name = this.getClass().toString();\n\n\tpublic AbapSqlPart(List<String> lines) {\n\t\tsetLines(lines);\n\t}\n\n\tprotected List<String> lines;\n\n\tpublic List<String> getLines() {\n\t\treturn lines;\n\t}\n\n\tpublic void setLines(List<String> lines) {\n\t\tthis.lines = lines;\n\t}\n\n}" } ]
import java.util.ArrayList; import java.util.List; import com.abap.sql.beautifier.Abap; import com.abap.sql.beautifier.Activator; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.statement.AbapSqlPart;
1,250
package com.abap.sql.beautifier.settings; public class JoinCombiner extends AbstractSqlSetting { public JoinCombiner() { } @Override public void apply() { if (abapSql.isOldSyntax()) { // TODO enable also for new syntax if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMBINE_SMALL_JOINS)) { int limit = Activator.getDefault().getPreferenceStore() .getInt(PreferenceConstants.COMBINE_SMALL_JOINS_LIMIT);
package com.abap.sql.beautifier.settings; public class JoinCombiner extends AbstractSqlSetting { public JoinCombiner() { } @Override public void apply() { if (abapSql.isOldSyntax()) { // TODO enable also for new syntax if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMBINE_SMALL_JOINS)) { int limit = Activator.getDefault().getPreferenceStore() .getInt(PreferenceConstants.COMBINE_SMALL_JOINS_LIMIT);
AbapSqlPart fromPart = abapSql.getPart(Abap.FROM);
3
2023-10-10 18:56:27+00:00
2k
Milosz08/screen-sharing-system
client/src/main/java/pl/polsl/screensharing/client/view/dialog/LicenseDialogWindow.java
[ { "identifier": "ClientWindow", "path": "client/src/main/java/pl/polsl/screensharing/client/view/ClientWindow.java", "snippet": "@Getter\npublic class ClientWindow extends AbstractRootFrame {\n private final ClientState clientState;\n\n private final TopMenuBar topMenuBar;\n private final TopToolbar topToolbar;\n private final TabbedPaneWindow tabbedPaneWindow;\n private final BottomInfobar bottomInfobar;\n\n private final ConnectWindow connectWindow;\n private final LastConnectionsWindow lastConnectionsWindow;\n private final AboutDialogWindow aboutDialogWindow;\n private final LicenseDialogWindow licenseDialogWindow;\n private final SessionInfoDialogWindow sessionInfoDialogWindow;\n\n @Setter\n private ClientDatagramSocket clientDatagramSocket;\n @Setter\n private ClientTcpSocket clientTcpSocket;\n\n public ClientWindow(ClientState clientState) {\n super(AppType.CLIENT, clientState, ClientWindow.class);\n this.clientState = clientState;\n\n topMenuBar = new TopMenuBar(this);\n topToolbar = new TopToolbar(this);\n tabbedPaneWindow = new TabbedPaneWindow(this);\n bottomInfobar = new BottomInfobar(this);\n\n connectWindow = new ConnectWindow(this);\n lastConnectionsWindow = new LastConnectionsWindow(this);\n aboutDialogWindow = new AboutDialogWindow(this);\n licenseDialogWindow = new LicenseDialogWindow(this);\n sessionInfoDialogWindow = new SessionInfoDialogWindow(this);\n }\n\n @Override\n protected void extendsFrame(JFrame frame, JPanel rootPanel) {\n frame.setJMenuBar(topMenuBar);\n frame.add(topToolbar, BorderLayout.NORTH);\n frame.add(tabbedPaneWindow, BorderLayout.CENTER);\n frame.add(bottomInfobar, BorderLayout.SOUTH);\n }\n\n public BottomInfobarController getBottomInfobarController() {\n return bottomInfobar.getBottomInfobarController();\n }\n\n public VideoCanvas getVideoCanvas() {\n return tabbedPaneWindow.getTabbedVideoStreamPanel().getVideoCanvas();\n }\n}" }, { "identifier": "AppType", "path": "lib/src/main/java/pl/polsl/screensharing/lib/AppType.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum AppType {\n HOST(\"HOST\", \"HostIcon\", \"host.json\", new Dimension(1280, 720)),\n CLIENT(\"CLIENT\", \"ClientIcon\", \"client.json\", new Dimension(1280, 720));\n\n private final String rootWindowName;\n private final String iconName;\n private final String configFileName;\n private final Dimension rootWindowSize;\n\n public String getRootWindowTitle() {\n return String.format(\"%s - Screen Sharing\", rootWindowName);\n }\n\n public Optional<Image> getIconPath(Class<?> frameClazz) {\n return FileUtils.getRootWindowIconFromResources(frameClazz, this);\n }\n}" }, { "identifier": "AbstractPopupDialog", "path": "lib/src/main/java/pl/polsl/screensharing/lib/gui/AbstractPopupDialog.java", "snippet": "public abstract class AbstractPopupDialog extends JDialog {\n private final JFrame rootFrame;\n private final JPanel rootPanel;\n private final String title;\n private final Dimension size;\n private final Optional<Image> iconImageOptional;\n\n public AbstractPopupDialog(\n AppType appType,\n int width,\n int height,\n String title,\n AbstractRootFrame rootFrame,\n Class<?> frameClazz\n ) {\n rootPanel = new JPanel();\n size = new Dimension(width, height);\n this.rootFrame = rootFrame;\n this.title = title;\n iconImageOptional = appType.getIconPath(frameClazz);\n }\n\n protected void initDialogGui(boolean fixedToContent, boolean isModal) {\n iconImageOptional.ifPresent(this::setIconImage);\n rootPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n rootPanel.setLayout(new BorderLayout(10, 10));\n\n setModal(isModal);\n setSize(size);\n setMaximumSize(size);\n setMinimumSize(size);\n setLocationRelativeTo(rootFrame);\n setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n setResizable(false);\n setTitle(title);\n extendsDialog(this, rootPanel);\n add(rootPanel);\n if (fixedToContent) {\n pack();\n }\n }\n\n protected void initDialogGui(boolean fixedToContent) {\n initDialogGui(fixedToContent, true);\n }\n\n public void closeWindow() {\n setVisible(false);\n dispose();\n }\n\n protected abstract void extendsDialog(JDialog dialog, JPanel rootPanel);\n}" }, { "identifier": "JAppLicensePanel", "path": "lib/src/main/java/pl/polsl/screensharing/lib/gui/fragment/JAppLicensePanel.java", "snippet": "@Slf4j\npublic class JAppLicensePanel extends JPanel {\n @Getter\n private final JScrollPane scrollPane;\n private final JLabel label;\n\n public JAppLicensePanel() {\n scrollPane = new JScrollPane(this);\n label = new JLabel(loadHtmlLicenseContent());\n\n scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);\n scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);\n\n add(label);\n }\n\n private String loadHtmlLicenseContent() {\n try {\n return FileUtils\n .loadAndWrapAsHtmlContent(\"license.txt\", getClass(), Alignment.CENTER)\n .replace(\"[year]\", String.valueOf(LocalDate.now().getYear()));\n } catch (Exception ex) {\n log.error(\"Unable to load license.txt file from assets resource directory.\");\n System.exit(-1);\n }\n return StringUtils.EMPTY;\n }\n}" } ]
import pl.polsl.screensharing.client.view.ClientWindow; import pl.polsl.screensharing.lib.AppType; import pl.polsl.screensharing.lib.gui.AbstractPopupDialog; import pl.polsl.screensharing.lib.gui.fragment.JAppLicensePanel; import javax.swing.*;
1,412
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view.dialog; public class LicenseDialogWindow extends AbstractPopupDialog { private final JAppLicensePanel licensePanel;
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view.dialog; public class LicenseDialogWindow extends AbstractPopupDialog { private final JAppLicensePanel licensePanel;
public LicenseDialogWindow(ClientWindow clientWindow) {
0
2023-10-11 16:12:02+00:00
2k
cbfacademy-admin/java-rest-api-assessment-jenieb3
src/test/java/com/cbfacademy/apiassessment/utility/JsonUtilTest.java
[ { "identifier": "Bond", "path": "src/main/java/com/cbfacademy/apiassessment/model/Bond.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\n\npublic class Bond implements Investment {\n // Class properties for Bond.\n private Long id;\n private String name;\n private int quantity;\n private double purchasePrice;\n private double currentPrice;\n\n// Constructor\n public Bond(Long id , String name, int quantity, double purchasePrice, double currentPrice) {\n this.id = id;\n this.name = name;\n this.quantity = quantity;\n this.purchasePrice = purchasePrice;\n this.currentPrice = currentPrice;\n\n }\n\n public Bond() {\n\n }\n // Getters and Setters\n\n public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id =id;\n }\n public String getName() {\n return name;\n }\n public void setName (String name) {\n this.name = name;\n }\n public int getQuantity() {\n return quantity;\n }\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n public double getPurchasePrice() {\n return purchasePrice;\n }\n public void setPurchasePrice(double purchasePrice) {\n this.purchasePrice = purchasePrice;\n }\n public double getCurrentPrice() {\n return currentPrice;\n }\n public void setCurrentPrice(double currentPrice) {\n this.currentPrice = currentPrice;\n }\n\n @Override\n public double getReturns() {\n //Calculate returns for a Bond.\n return(currentPrice -purchasePrice) * quantity;\n }\n}" }, { "identifier": "Investment", "path": "src/main/java/com/cbfacademy/apiassessment/model/Investment.java", "snippet": "@JsonTypeInfo(\n use = JsonTypeInfo.Id.NAME,\n property = \"type\")\n@JsonSubTypes({\n @JsonSubTypes.Type(value = Bond.class, name = \"Bond\"),\n @JsonSubTypes.Type(value = Stock.class, name = \"Stock\")\n})\n\n\n// Investment interface to represent any kind of investment\npublic interface Investment {\n // Abstract methods for basic Investment properties.\n\n Long getId();\n void setId(Long id);\n String getName();\n void setName(String name);\n int getQuantity();\n void setQuantity(int quantity);\n double getPurchasePrice();\n void setPurchasePrice(double purchasePrice);\n double getCurrentPrice();\n void setCurrentPrice(double currentPrice);\n double getReturns();\n\n}" }, { "identifier": "InvestmentWrapper", "path": "src/main/java/com/cbfacademy/apiassessment/model/InvestmentWrapper.java", "snippet": "public class InvestmentWrapper {\n //List to hold the investments\n private List<Investment> investments;\n //Gets the list of investments\n\n public List<Investment> getInvestments() {\n return investments;\n }\n //Sets the list of investments\n\n public void setInvestments(List<Investment> investments) {\n this.investments = investments;\n }\n}" }, { "identifier": "Stock", "path": "src/main/java/com/cbfacademy/apiassessment/model/Stock.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\n\npublic class Stock implements Investment {\n // Class properties for a Stock\n private Long id;\n private String name;\n private int quantity;\n private double purchasePrice;\n private double currentPrice;\n// Constructor\n public Stock(Long id, String name, int quantity, double purchasePrice, double currentPrice) {\n this.id = id;\n this.name = name;\n this.quantity = quantity;\n this.purchasePrice = purchasePrice;\n this.currentPrice = currentPrice;\n }\n\n public Stock() {\n\n }\n // Getters and Setters\n public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getQuantity() {\n return quantity;\n }\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n public double getPurchasePrice() {\n return purchasePrice;\n }\n public void setPurchasePrice(double purchasePrice) {\n this.purchasePrice = purchasePrice;\n }\n public double getCurrentPrice() {\n return currentPrice;\n }\n public void setCurrentPrice(double currentPrice) {\n this.currentPrice = currentPrice;\n }\n @Override\n public double getReturns() {\n //Calculation for stock returns\n return (currentPrice - purchasePrice) * quantity;\n }\n}" } ]
import com.cbfacademy.apiassessment.model.Bond; import com.cbfacademy.apiassessment.model.Investment; import com.cbfacademy.apiassessment.model.InvestmentWrapper; import com.cbfacademy.apiassessment.model.Stock; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*;
1,521
package com.cbfacademy.apiassessment.utility; /** * Test for the JsonUtility class. * These tests ensure that JSON read and write operations are correctly handled, including the * accurate serialization and deserialization of investment data to and from jSON format. * The class uses mock objects to simulate file operations and interactions. */ @ExtendWith(MockitoExtension.class) public class JsonUtilTest { @Mock private ObjectMapper objectMapper; @Mock private ResourceLoader resourceLoader; @Mock private Resource resource; private JsonUtil jsonUtil; private final String filePath = "classpath:data/test-investment.json"; @BeforeEach void setup() { // Setting up necessary objects before each test jsonUtil = new JsonUtil(objectMapper, resourceLoader, filePath); } @Test void readInvestmentsFromJsonTest() throws Exception { // Testing the read functionality from JSON // Creating mock objects for Bond and Stock implementations Investment bond = mock(Bond.class);
package com.cbfacademy.apiassessment.utility; /** * Test for the JsonUtility class. * These tests ensure that JSON read and write operations are correctly handled, including the * accurate serialization and deserialization of investment data to and from jSON format. * The class uses mock objects to simulate file operations and interactions. */ @ExtendWith(MockitoExtension.class) public class JsonUtilTest { @Mock private ObjectMapper objectMapper; @Mock private ResourceLoader resourceLoader; @Mock private Resource resource; private JsonUtil jsonUtil; private final String filePath = "classpath:data/test-investment.json"; @BeforeEach void setup() { // Setting up necessary objects before each test jsonUtil = new JsonUtil(objectMapper, resourceLoader, filePath); } @Test void readInvestmentsFromJsonTest() throws Exception { // Testing the read functionality from JSON // Creating mock objects for Bond and Stock implementations Investment bond = mock(Bond.class);
Investment stock = mock(Stock.class);
3
2023-10-10 18:57:19+00:00
2k
Bawnorton/Potters
src/client/java/com/bawnorton/potters/client/render/PottersBlockEntityRenderers.java
[ { "identifier": "PottersBlockEntityType", "path": "src/main/java/com/bawnorton/potters/registry/PottersBlockEntityType.java", "snippet": "public class PottersBlockEntityType {\n public static final BlockEntityType<FiniteDecoratedPotBlockEntity> FINITE_DECORATED_POT;\n public static final BlockEntityType<BottomlessDecoratedPotBlockEntity> BOTTOMLESS_DECORATED_POT;\n private static final List<BlockEntityType<? extends PottersDecoratedPotBlockEntityBase>> ALL;\n\n static {\n ALL = new ArrayList<>();\n List<Block> blocks = new ArrayList<>();\n PottersBlocks.forEachFinite(blocks::add);\n FINITE_DECORATED_POT = register(\"finite\", FabricBlockEntityTypeBuilder.create((pos, state) -> {\n FiniteDecoratedPotBlock block = (FiniteDecoratedPotBlock) state.getBlock();\n return new FiniteDecoratedPotBlockEntity(pos, state, block.getStackCountSupplier());\n }, blocks.toArray(new Block[]{})).build());\n BOTTOMLESS_DECORATED_POT = register(\"bottomless\", FabricBlockEntityTypeBuilder.create(BottomlessDecoratedPotBlockEntity::new, PottersBlocks.BOTTOMLESS_DECORATED_POT)\n .build());\n }\n\n public static void forEach(Consumer<BlockEntityType<? extends PottersDecoratedPotBlockEntityBase>> blockEntityTypeConsumer) {\n ALL.forEach(blockEntityTypeConsumer);\n }\n\n public static void init() {\n ItemStorage.SIDED.registerForBlockEntities(((blockEntity, context) -> {\n if (blockEntity instanceof PottersDecoratedPotBlockEntityBase pottersBlockEntity) {\n return pottersBlockEntity.getStorage();\n }\n return null;\n }), ALL.toArray(new BlockEntityType[]{}));\n }\n\n private static <T extends PottersDecoratedPotBlockEntityBase> BlockEntityType<T> register(String name, BlockEntityType<T> type) {\n BlockEntityType<T> blockEntityType = Registry.register(Registries.BLOCK_ENTITY_TYPE, Potters.id(name + \"_decorated_pot\"), type);\n ALL.add(blockEntityType);\n return blockEntityType;\n }\n}" }, { "identifier": "PottersItems", "path": "src/main/java/com/bawnorton/potters/registry/PottersItems.java", "snippet": "public class PottersItems {\n public static final ItemGroup POTTERS_ITEM_GROUP;\n private static final List<Item> ALL;\n\n static {\n ALL = new ArrayList<>();\n PottersBlocks.forEach(PottersItems::register);\n\n POTTERS_ITEM_GROUP = Registry.register(Registries.ITEM_GROUP, Potters.id(\"item_group\"), FabricItemGroup.builder()\n .icon(() -> IRON_DECORATED_POT.asItem().getDefaultStack())\n .displayName(Text.translatable(\"itemGroup.potters\"))\n .entries(((displayContext, entries) -> entries.addAll(ALL.stream().map(Item::getDefaultStack).toList())))\n .build());\n }\n\n public static void init() {\n // no-op\n }\n\n public static void forEach(Consumer<Item> itemConsumer) {\n ALL.forEach(itemConsumer);\n }\n\n private static void register(Block block) {\n register(new BlockItem(block, new Item.Settings()));\n }\n\n private static void register(BlockItem item) {\n register(item.getBlock(), item);\n }\n\n private static void register(Block block, Item item) {\n register(Registries.BLOCK.getId(block), item);\n }\n\n private static void register(Identifier id, Item item) {\n register(RegistryKey.of(Registries.ITEM.getKey(), id), item);\n }\n\n private static void register(RegistryKey<Item> key, Item item) {\n if (item instanceof BlockItem blockItem) blockItem.appendBlocks(Item.BLOCK_ITEMS, item);\n ALL.add(item);\n Registry.register(Registries.ITEM, key, item);\n }\n}" } ]
import com.bawnorton.potters.registry.PottersBlockEntityType; import com.bawnorton.potters.registry.PottersItems; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.minecraft.client.render.block.entity.BlockEntityRendererFactories;
1,023
package com.bawnorton.potters.client.render; public class PottersBlockEntityRenderers { public static void init() { PottersBlockEntityType.forEach(blockEntityType -> BlockEntityRendererFactories.register(blockEntityType, PottersDecoratedPotBlockEntityRenderer::new));
package com.bawnorton.potters.client.render; public class PottersBlockEntityRenderers { public static void init() { PottersBlockEntityType.forEach(blockEntityType -> BlockEntityRendererFactories.register(blockEntityType, PottersDecoratedPotBlockEntityRenderer::new));
PottersItems.forEach(item -> BuiltinItemRendererRegistry.INSTANCE.register(item, PottersDecoratedPotBlockEntityRenderer::renderItemStack));
1
2023-10-13 19:14:56+00:00
2k
YinQin257/mqs-adapter
mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/CustomKafkaConsumer.java
[ { "identifier": "Constants", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/Constants.java", "snippet": "public interface Constants {\n int SUCCESS = 1;\n int ERROR = 0;\n String TRAN = \"TRAN\";\n String BATCH = \"BATCH\";\n String BROADCAST = \"BROADCAST\";\n String TRUE = \"true\";\n String EMPTY = \"\";\n String HYPHEN = \"-\";\n String UNDER_SCORE = \"_\";\n String BROADCAST_CONNECTOR = \"_BROADCAST_\";\n String BROADCAST_SUFFIX = \"_BROADCAST\";\n String BATCH_SUFFIX = \"_BATCH\";\n String WILDCARD =\"*\";\n}" }, { "identifier": "MessageConsumer", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/service/MessageConsumer.java", "snippet": "public interface MessageConsumer extends DisposableBean {\n\n /**\n * 消费组启动方法\n */\n void start();\n}" }, { "identifier": "PollWorker", "path": "mqs-starter/src/main/java/org/yinqin/mqs/kafka/PollWorker.java", "snippet": "public class PollWorker implements Runnable {\n\n private final Logger logger = LoggerFactory.getLogger(PollWorker.class);\n\n /**\n * 线程停止标记\n */\n private final AtomicBoolean closed = new AtomicBoolean(false);\n\n /**\n * kafka源生消费者\n */\n private final KafkaConsumer<String, byte[]> kafkaConsumer;\n\n /**\n * 消息处理器集合\n */\n private final Map<String, MessageHandler> messageHandlers;\n\n /**\n * 拉取消息间隔\n */\n private final int interval;\n\n public PollWorker(KafkaConsumer<String, byte[]> kafkaConsumer, Map<String, MessageHandler> messageHandlers, int interval) {\n this.kafkaConsumer = kafkaConsumer;\n this.messageHandlers = messageHandlers;\n this.interval = interval;\n }\n\n @Override\n public void run() {\n try {\n while (!closed.get()) {\n try {\n List<AdapterMessage> messages = fetchMessages();\n if (messages.isEmpty()) {\n ThreadUtil.sleep(interval);\n continue;\n }\n\n consumeMessage(messages);\n } catch (Exception e) {\n logger.error(\"拉取消息异常:\", e);\n }\n }\n } finally {\n // 关闭消费者,必须在当前线程关闭,否则会有线程安全问题\n kafkaConsumer.close();\n }\n\n }\n\n public void shutdown() {\n closed.set(true);\n }\n\n /**\n * 拉取消息\n *\n * @return 消息集合\n */\n private List<AdapterMessage> fetchMessages() {\n ConsumerRecords<String, byte[]> records = kafkaConsumer.poll(Duration.ofMillis(100));\n Iterator<ConsumerRecord<String, byte[]>> iterator = records.iterator();\n List<AdapterMessage> messages = new ArrayList<>(records.count());\n ConsumerRecord<String, byte[]> item;\n while (iterator.hasNext()) {\n item = iterator.next();\n AdapterMessage message = AdapterMessage.builder()\n .topic(item.topic())\n .body(item.value())\n .bizKey(item.key())\n .build();\n message.setOriginMessage(item);\n messages.add(message);\n }\n return messages;\n }\n\n /**\n * 按照topic分组批量消费消息\n *\n * @param messages 消息集合\n */\n private void consumeMessage(List<AdapterMessage> messages) {\n Map<String, List<AdapterMessage>> collect = messages.stream().collect(Collectors.groupingBy(AdapterMessage::getTopic, Collectors.toList()));\n try {\n for (Map.Entry<String, List<AdapterMessage>> entry : collect.entrySet()) {\n String topic = entry.getKey();\n List<AdapterMessage> messageObjectList = entry.getValue();\n logger.debug(\"kafka批量消息,topic:{},消息数量为:{}\", topic, messageObjectList.size());\n MessageAdapter messageAdapter = messageHandlers.get(messageObjectList.get(0).getTopic()).getClass().getAnnotation(MessageAdapter.class);\n if (messageAdapter.isBatch()) {\n messageHandlers.get(messageObjectList.get(0).getTopic()).process(messages);\n } else {\n for (AdapterMessage msg : messages)\n messageHandlers.get(messageObjectList.get(0).getTopic()).process(msg);\n }\n }\n } catch (Exception e) {\n logger.error(\"kafka消费异常:\", e);\n }\n }\n}" } ]
import cn.hutool.core.thread.ThreadUtil; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yinqin.mqs.common.Constants; import org.yinqin.mqs.common.service.MessageConsumer; import org.yinqin.mqs.kafka.PollWorker;
1,387
package org.yinqin.mqs.kafka.consumer; /** * 自定义kafka消费者 * * @author YinQin * @version 1.0.6 * @createDate 2023年10月13日 * @see org.yinqin.mqs.common.service.MessageConsumer * @since 1.0.0 */ public class CustomKafkaConsumer implements MessageConsumer { private final Logger logger = LoggerFactory.getLogger(CustomKafkaConsumer.class); /** * 实例ID */ private final String instanceId; /** * 消费类型 */ private final String consumerType; /** * 拉取消息工作线程 */ @Getter private final PollWorker pollWorker; public CustomKafkaConsumer(String instanceId, String consumerType, PollWorker pollWorker) { this.instanceId = instanceId; this.consumerType = consumerType; this.pollWorker = pollWorker; } /** * 异步启动拉取消息工作线程 */ @Override public void start() {
package org.yinqin.mqs.kafka.consumer; /** * 自定义kafka消费者 * * @author YinQin * @version 1.0.6 * @createDate 2023年10月13日 * @see org.yinqin.mqs.common.service.MessageConsumer * @since 1.0.0 */ public class CustomKafkaConsumer implements MessageConsumer { private final Logger logger = LoggerFactory.getLogger(CustomKafkaConsumer.class); /** * 实例ID */ private final String instanceId; /** * 消费类型 */ private final String consumerType; /** * 拉取消息工作线程 */ @Getter private final PollWorker pollWorker; public CustomKafkaConsumer(String instanceId, String consumerType, PollWorker pollWorker) { this.instanceId = instanceId; this.consumerType = consumerType; this.pollWorker = pollWorker; } /** * 异步启动拉取消息工作线程 */ @Override public void start() {
ThreadUtil.newThread(pollWorker, instanceId + Constants.HYPHEN + consumerType + "-poll-worker").start();
0
2023-10-11 03:23:43+00:00
2k