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
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/MeasurementUtilController.java
[ { "identifier": "MeasurementUtil", "path": "nhXJH-admin/src/main/java/com/nhXJH/web/domain/MeasurementUtil.java", "snippet": "@TableName(\"base_util\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MeasurementUtil extends BaseEntity {\n private static final long serialVersi...
import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.web.domain.MeasurementUtil; import com.nhXJH.web.service.IMeasurementUtilService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo;
13,024
package com.nhXJH.web.controller.appllication; /** * 物品单位信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/util") @Api(tags = {"物品单位信息"}) public class MeasurementUtilController extends BaseController { @Autowired private IMeasurementUtilService measurementUtilService; /** * 查询物品单位信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:util:list')") @GetMapping("/list") @ApiOperation(value ="查询物品单位信息列表",notes = "查询物品单位信息列表")
package com.nhXJH.web.controller.appllication; /** * 物品单位信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/util") @Api(tags = {"物品单位信息"}) public class MeasurementUtilController extends BaseController { @Autowired private IMeasurementUtilService measurementUtilService; /** * 查询物品单位信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:util:list')") @GetMapping("/list") @ApiOperation(value ="查询物品单位信息列表",notes = "查询物品单位信息列表")
public TableDataInfo list(MeasurementUtil measurementUtil) {
0
2023-10-13 07:19:20+00:00
16k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/core/commands/ToggleAlarmCommand.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; import mdteam.ait.AITMod; import mdteam.ait.tardis.Tardis; import mdteam.ait.tardis.handler.properties.PropertiesHandler; import mdteam.ait.tardis.wrapper.server.manager.ServerTardisManager; import net.minecraft.command.argument.UuidArgumentType; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; import static mdteam.ait.core.commands.TeleportInteriorCommand.TARDIS_SUGGESTION; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal;
10,984
package mdteam.ait.core.commands; // TEMPORARY - REMOVE LATER public class ToggleAlarmCommand { public static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal(AITMod.MOD_ID) .then(literal("toggle-alarm").requires(source -> source.hasPermissionLevel(2)) .then(argument("tardis", UuidArgumentType.uuid()).suggests(TARDIS_SUGGESTION) .executes(ToggleAlarmCommand::runCommand)))); } private static int runCommand(CommandContext<ServerCommandSource> context) { ServerPlayerEntity source = context.getSource().getPlayer();
package mdteam.ait.core.commands; // TEMPORARY - REMOVE LATER public class ToggleAlarmCommand { public static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal(AITMod.MOD_ID) .then(literal("toggle-alarm").requires(source -> source.hasPermissionLevel(2)) .then(argument("tardis", UuidArgumentType.uuid()).suggests(TARDIS_SUGGESTION) .executes(ToggleAlarmCommand::runCommand)))); } private static int runCommand(CommandContext<ServerCommandSource> context) { ServerPlayerEntity source = context.getSource().getPlayer();
Tardis tardis = ServerTardisManager.getInstance().getTardis(UuidArgumentType.getUuid(context, "tardis"));
3
2023-10-08 00:38:53+00:00
16k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/PurchaseTemplateController.java
[ { "identifier": "PurchaseTemplate", "path": "nhXJH-admin/src/main/java/com/nhXJH/web/domain/PurchaseTemplate.java", "snippet": "@TableName(\"base_purchase_template\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PurchaseTemplate extends BaseEntity {\n private static final ...
import java.io.File; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.web.domain.PurchaseTemplate; import com.nhXJH.web.domain.param.purchase.TemplateParam; import com.nhXJH.web.service.IPurchaseTemplateService; import com.nhXJH.web.util.TemplateUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo; import org.springframework.web.multipart.MultipartFile;
13,360
package com.nhXJH.web.controller.appllication; /** * 审批流程模板Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/template") @Api(tags = {"审批流程模板"}) public class PurchaseTemplateController extends BaseController { @Autowired private IPurchaseTemplateService purchaseTemplateService; /** * 查询审批流程模板列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:("@ss.hasPermi('userApplication:template:list')") @GetMapping("/list") @ApiOperation(value ="查询审批流程模板列表",notes = "查询审批流程模板列表") public TableDataInfo list(PurchaseTemplate purchaseTemplate) { startPage(); List<PurchaseTemplate> list = purchaseTemplateService.selectPurchaseTemplateList(purchaseTemplate); return getDataTable(list); } /** * 导出审批流程模板列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:("@ss.hasPermi('userApplication:template:export')")
package com.nhXJH.web.controller.appllication; /** * 审批流程模板Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/template") @Api(tags = {"审批流程模板"}) public class PurchaseTemplateController extends BaseController { @Autowired private IPurchaseTemplateService purchaseTemplateService; /** * 查询审批流程模板列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:("@ss.hasPermi('userApplication:template:list')") @GetMapping("/list") @ApiOperation(value ="查询审批流程模板列表",notes = "查询审批流程模板列表") public TableDataInfo list(PurchaseTemplate purchaseTemplate) { startPage(); List<PurchaseTemplate> list = purchaseTemplateService.selectPurchaseTemplateList(purchaseTemplate); return getDataTable(list); } /** * 导出审批流程模板列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:("@ss.hasPermi('userApplication:template:export')")
@Log(title = "审批流程模板", businessType = BusinessType.EXPORT)
4
2023-10-14 04:57:42+00:00
16k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlockEntities.java
[ { "identifier": "BlueContainerBlockEntity", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlockEntity.java", "snippet": "public class BlueContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptiona...
import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlockEntity; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlockEntity; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearInstance; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearRenderer; import com.mangomilk.design_decor.blocks.millstone.DecoMillStoneBlockEntity; import com.mangomilk.design_decor.blocks.millstone.instance.*; import com.mangomilk.design_decor.blocks.millstone.renderer.*; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.kinetics.base.CutoutRotatingInstance; import com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE;
14,074
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL) .renderer(() -> IndustrialGearRenderer::new) .register(); public static final BlockEntityEntry<GasTankBlockEntity> GAS_TANK = REGISTRATE .blockEntity("gas_tank", GasTankBlockEntity::new) .validBlocks(MmbBlocks.GAS_TANK,MmbBlocks.COPPER_GAS_TANK) .register(); public static final BlockEntityEntry<RedContainerBlockEntity> RED_CONTAINER = REGISTRATE .blockEntity("red_container", RedContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register(); public static final BlockEntityEntry<GreenContainerBlockEntity> GREEN_CONTAINER = REGISTRATE .blockEntity("green_container", GreenContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register(); public static final BlockEntityEntry<BlueContainerBlockEntity> BLUE_CONTAINER = REGISTRATE .blockEntity("blue_container", BlueContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register();
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL) .renderer(() -> IndustrialGearRenderer::new) .register(); public static final BlockEntityEntry<GasTankBlockEntity> GAS_TANK = REGISTRATE .blockEntity("gas_tank", GasTankBlockEntity::new) .validBlocks(MmbBlocks.GAS_TANK,MmbBlocks.COPPER_GAS_TANK) .register(); public static final BlockEntityEntry<RedContainerBlockEntity> RED_CONTAINER = REGISTRATE .blockEntity("red_container", RedContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register(); public static final BlockEntityEntry<GreenContainerBlockEntity> GREEN_CONTAINER = REGISTRATE .blockEntity("green_container", GreenContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register(); public static final BlockEntityEntry<BlueContainerBlockEntity> BLUE_CONTAINER = REGISTRATE .blockEntity("blue_container", BlueContainerBlockEntity::new) .validBlocks(MmbBlocks.RED_CONTAINER) .register();
public static final BlockEntityEntry<MmbCrushingWheelBlockEntity> MMB_CRUSHING_WHEEL = REGISTRATE
3
2023-10-14 21:51:49+00:00
16k
giteecode/supermarket2Public
src/main/java/com/ruoyi/framework/web/controller/BaseController.java
[ { "identifier": "DateUtils", "path": "src/main/java/com/ruoyi/common/utils/DateUtils.java", "snippet": "public class DateUtils extends org.apache.commons.lang3.time.DateUtils\n{\n public static String YYYY = \"yyyy\";\n\n public static String YYYY_MM = \"yyyy-MM\";\n\n public static String YYYY...
import java.beans.PropertyEditorSupport; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.PageUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.common.utils.sql.SqlUtil; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.domain.AjaxResult.Type; import com.ruoyi.framework.web.page.PageDomain; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.framework.web.page.TableSupport; import com.ruoyi.project.system.user.domain.User;
12,228
package com.ruoyi.framework.web.controller; /** * web层通用数据处理 * * @author ruoyi */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(0); rspData.setRows(list); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? success() : error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回成功数据 */ public static AjaxResult success(Object data) { return AjaxResult.success("操作成功", data); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 返回错误码消息 */ public AjaxResult error(Type type, String message) { return new AjaxResult(type, message); } /** * 页面跳转 */ public String redirect(String url) { return StringUtils.format("redirect:{}", url); } /** * 获取用户缓存信息 */ public User getSysUser() {
package com.ruoyi.framework.web.controller; /** * web层通用数据处理 * * @author ruoyi */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(0); rspData.setRows(list); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? success() : error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回成功数据 */ public static AjaxResult success(Object data) { return AjaxResult.success("操作成功", data); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 返回错误码消息 */ public AjaxResult error(Type type, String message) { return new AjaxResult(type, message); } /** * 页面跳转 */ public String redirect(String url) { return StringUtils.format("redirect:{}", url); } /** * 获取用户缓存信息 */ public User getSysUser() {
return ShiroUtils.getSysUser();
3
2023-10-14 02:27:47+00:00
16k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/SCMain.java
[ { "identifier": "CommandManager", "path": "src/main/java/net/shadowclient/main/command/CommandManager.java", "snippet": "public class CommandManager {\n public static final Map<String, Command> commands = new HashMap<>();\n\n public static void registerCommands() {\n registerCommand(new Hel...
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; import net.fabricmc.loader.api.metadata.ModMetadata; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.shadowclient.main.command.CommandManager; import net.shadowclient.main.config.Config; import net.shadowclient.main.config.SCSettings; import net.shadowclient.main.module.ModuleManager; import net.shadowclient.main.ui.clickgui.ClickGUI; import net.shadowclient.main.ui.clickgui.Frame; import net.shadowclient.main.ui.clickgui.MainClickGUI; import net.shadowclient.main.ui.clickgui.ModuleButton; import net.shadowclient.main.ui.clickgui.settings.scsettings.components.SCBoolSetting; import net.shadowclient.main.ui.clickgui.text.TextField; import net.shadowclient.main.ui.notifications.Notification; import net.shadowclient.main.ui.notifications.NotificationsManager; import net.shadowclient.main.util.ChatUtils; import net.shadowclient.main.util.JavaUtils; import net.shadowclient.mixin.KeyBindingAccessor; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.stream.Stream;
12,694
package net.shadowclient.main; public class SCMain { public static final String ClientModId = "shadowclient"; public static final String ClientName = "ShadowClient"; public static final String ClientVersion = "0.2.0"; public static final String ClientCommandPrefix = "sc/"; public static MainClickGUI clickGui; public static ClickGUI settingsGui; public static final MinecraftClient mc = MinecraftClient.getInstance(); public static final Logger logger = LoggerFactory.getLogger(ClientName); public static boolean configDeleted = false; public static List<KeyBinding> keyBindings = new ArrayList<>(); public static KeyBinding ToggleGUIKeyBinding; public static void init() { try { info("Starting " + ClientName + " " + ClientVersion); ToggleGUIKeyBinding = registerKeyBinding( new KeyBinding( "key." + ClientModId + ".togglegui", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_RIGHT_SHIFT, "category." + ClientModId + ".clientcategory" )); CommandManager.registerCommands(); ModuleManager.registerModules(); clickGui = new MainClickGUI(); settingsGui = new ClickGUI("Settings"); initSettingsScreen(settingsGui);
package net.shadowclient.main; public class SCMain { public static final String ClientModId = "shadowclient"; public static final String ClientName = "ShadowClient"; public static final String ClientVersion = "0.2.0"; public static final String ClientCommandPrefix = "sc/"; public static MainClickGUI clickGui; public static ClickGUI settingsGui; public static final MinecraftClient mc = MinecraftClient.getInstance(); public static final Logger logger = LoggerFactory.getLogger(ClientName); public static boolean configDeleted = false; public static List<KeyBinding> keyBindings = new ArrayList<>(); public static KeyBinding ToggleGUIKeyBinding; public static void init() { try { info("Starting " + ClientName + " " + ClientVersion); ToggleGUIKeyBinding = registerKeyBinding( new KeyBinding( "key." + ClientModId + ".togglegui", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_RIGHT_SHIFT, "category." + ClientModId + ".clientcategory" )); CommandManager.registerCommands(); ModuleManager.registerModules(); clickGui = new MainClickGUI(); settingsGui = new ClickGUI("Settings"); initSettingsScreen(settingsGui);
Config.loadConfig();
1
2023-10-07 06:55:12+00:00
16k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "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 = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
13,237
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode);
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode);
List<AbstractSqlSetting> settings = generateSettings();
1
2023-10-10 18:56:27+00:00
16k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/filelist/FileListUploadThread.java
[ { "identifier": "FcpHandler", "path": "src/main/java/frost/fcp/FcpHandler.java", "snippet": "public abstract class FcpHandler {\r\n\r\n public static final int TYPE_MESSAGE = 1;\r\n public static final int TYPE_FILE = 2;\r\n\r\n public static final int MAX_MESSAGE_SIZE_07 = (64 * 1024) + (16...
import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.fcp.FcpHandler; import frost.fcp.FcpResultPut; import frost.fileTransfer.SharedFilesCHKKeyManager; import frost.storage.perst.SharedFilesCHKKey; import frost.util.FileAccess; import frost.util.Mixed;
11,205
/* FileListThread.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.filelist; /** * Thread that uploads the CHK file lists. * Periodically checks if there are CHKs pending for send, collects and sends them. */ public class FileListUploadThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(FileListUploadThread.class); private final int minutes6 = 6 * 60 * 1000; private long nextStartTime = 0; // one and only instance private static FileListUploadThread instance = new FileListUploadThread(); private FileListUploadThread() { nextStartTime = System.currentTimeMillis() + (5L * 60L * 1000L); // wait 5 minutes until first start } public static FileListUploadThread getInstance() { return instance; } public boolean cancelThread() { return false; } /** * User changed data in shared files table, wait 10 minutes starting from now, * maybe he does more changes. */ public void userActionOccured() { synchronized(instance) { nextStartTime = System.currentTimeMillis() + getRandomWaittime(); } } private int getRandomWaittime() { // at least 6 minutes, or max. 12 minutes final int sleepTime = minutes6 + (int)(minutes6 * Math.random()); return sleepTime; } @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while( true ) { try { while(true) { // wait until we really reached nextStartTime, nextStartTime may be changed during our wait final int waitTimeDelta = (int)(nextStartTime - System.currentTimeMillis()); if( waitTimeDelta > 1000 ) {
/* FileListThread.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.filelist; /** * Thread that uploads the CHK file lists. * Periodically checks if there are CHKs pending for send, collects and sends them. */ public class FileListUploadThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(FileListUploadThread.class); private final int minutes6 = 6 * 60 * 1000; private long nextStartTime = 0; // one and only instance private static FileListUploadThread instance = new FileListUploadThread(); private FileListUploadThread() { nextStartTime = System.currentTimeMillis() + (5L * 60L * 1000L); // wait 5 minutes until first start } public static FileListUploadThread getInstance() { return instance; } public boolean cancelThread() { return false; } /** * User changed data in shared files table, wait 10 minutes starting from now, * maybe he does more changes. */ public void userActionOccured() { synchronized(instance) { nextStartTime = System.currentTimeMillis() + getRandomWaittime(); } } private int getRandomWaittime() { // at least 6 minutes, or max. 12 minutes final int sleepTime = minutes6 + (int)(minutes6 * Math.random()); return sleepTime; } @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while( true ) { try { while(true) { // wait until we really reached nextStartTime, nextStartTime may be changed during our wait final int waitTimeDelta = (int)(nextStartTime - System.currentTimeMillis()); if( waitTimeDelta > 1000 ) {
Mixed.wait( waitTimeDelta );
5
2023-10-07 22:25:20+00:00
16k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/actions/editor/popupmenu/PopupMenuEditorActionGroupUtil.java
[ { "identifier": "DevPilotNotification", "path": "src/main/java/com/zhongan/devpilot/actions/notifications/DevPilotNotification.java", "snippet": "public class DevPilotNotification {\n\n public static void info(String content) {\n var notification = new Notification(\n \"DevPilot Not...
import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.zhongan.devpilot.actions.notifications.DevPilotNotification; import com.zhongan.devpilot.constant.DefaultConst; import com.zhongan.devpilot.constant.PromptConst; import com.zhongan.devpilot.enums.EditorActionEnum; import com.zhongan.devpilot.enums.SessionTypeEnum; import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService; import com.zhongan.devpilot.gui.toolwindows.components.EditorInfo; import com.zhongan.devpilot.settings.actionconfiguration.EditorActionConfigurationState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.settings.state.LanguageSettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.DocumentUtil; import com.zhongan.devpilot.util.LanguageUtil; import com.zhongan.devpilot.util.PerformanceCheckUtils; import com.zhongan.devpilot.util.PromptTemplate; import com.zhongan.devpilot.util.PsiFileUtil; import com.zhongan.devpilot.webview.model.CodeReferenceModel; import com.zhongan.devpilot.webview.model.MessageModel; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import javax.swing.Icon; import static com.zhongan.devpilot.constant.PlaceholderConst.ADDITIONAL_MOCK_PROMPT; import static com.zhongan.devpilot.constant.PlaceholderConst.LANGUAGE; import static com.zhongan.devpilot.constant.PlaceholderConst.MOCK_FRAMEWORK; import static com.zhongan.devpilot.constant.PlaceholderConst.SELECTED_CODE; import static com.zhongan.devpilot.constant.PlaceholderConst.TEST_FRAMEWORK;
11,662
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) {
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) {
DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong"));
0
2023-11-29 06:37:51+00:00
16k
Gaia3D/mago-3d-tiler
tiler/src/test/java/com/gaia3d/converter/AssimpConverterTest.java
[ { "identifier": "Configurator", "path": "tiler/src/main/java/com/gaia3d/command/Configurator.java", "snippet": "public class Configurator {\n public static final Level LEVEL = Level.ALL;\n private static final String DEFAULT_PATTERN = \"%message%n\";\n\n public static void initConsoleLogger() {...
import com.gaia3d.command.Configurator; import com.gaia3d.converter.kml.FastKmlReader; import com.gaia3d.converter.kml.KmlInfo; import com.gaia3d.converter.assimp.AssimpConverter; import com.gaia3d.process.postprocess.batch.Batcher; import com.gaia3d.process.postprocess.batch.GaiaBatcher; import com.gaia3d.basic.structure.GaiaScene; import org.junit.jupiter.api.Test; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.LevelOfDetail; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull;
13,628
package com.gaia3d.converter; class AssimpConverterTest { private static final String INPUT_PATH = "../sample/"; private static final String OUTPUT_PATH = "../output/"; @Test void load() throws URISyntaxException {
package com.gaia3d.converter; class AssimpConverterTest { private static final String INPUT_PATH = "../sample/"; private static final String OUTPUT_PATH = "../output/"; @Test void load() throws URISyntaxException {
Converter converter = new AssimpConverter(null);
3
2023-11-30 01:59:44+00:00
16k
okx/OKBund
aa-task/src/main/java/com/okcoin/dapp/bundler/manager/BundlerServiceImpl.java
[ { "identifier": "BundleConfig", "path": "aa-task/src/main/java/com/okcoin/dapp/bundler/config/BundleConfig.java", "snippet": "@Configuration\n@ConfigurationProperties(prefix = \"bundler.bundle\")\n@Data\npublic class BundleConfig {\n\n private BigInteger maxBundleGas;\n\n private BigDecimal baseFe...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.okcoin.dapp.bundler.config.BundleConfig; import com.okcoin.dapp.bundler.config.OnChainConfig; import com.okcoin.dapp.bundler.domain.UopBundleDO; import com.okcoin.dapp.bundler.infra.chain.FieldUtil; import com.okcoin.dapp.bundler.infra.chain.IChain; import com.okcoin.dapp.bundler.infra.chain.ReceiptUtil; import com.okcoin.dapp.bundler.infra.chain.web3j.resp.TransactionReceiptCommon; import com.okcoin.dapp.bundler.pool.bundler.IBundleService; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.domain.TxAndOpHashMappingDO; import com.okcoin.dapp.bundler.pool.domain.UserOperationDO; import com.okcoin.dapp.bundler.pool.domain.debug.SimulateValidationResult; import com.okcoin.dapp.bundler.pool.domain.debug.SlotMap; import com.okcoin.dapp.bundler.pool.domain.pool.MempoolEntry; import com.okcoin.dapp.bundler.pool.domain.reputation.ReputationStatusEnum; import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint; import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo; import com.okcoin.dapp.bundler.pool.gasprice.GasService; import com.okcoin.dapp.bundler.pool.mem.MempoolService; import com.okcoin.dapp.bundler.pool.reputation.ReputationService; import com.okcoin.dapp.bundler.pool.result.OnChainTxFailedService; import com.okcoin.dapp.bundler.pool.simulation.EntryPointSimulationsFactory; import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations; import com.okcoin.dapp.bundler.pool.util.AddressUtil; import com.okcoin.dapp.bundler.pool.util.MathUtil; import com.okcoin.dapp.bundler.task.logevent.LogEventService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.web3j.crypto.Credentials; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors;
13,597
log.error("bundle simulateValidation error", e); mempoolService.removeUop(sender, uop.getNonce()); continue; } //validate storage sender for (String storageAddress : simulateValidationResult.getStorageMap().keySet()) { if (!storageAddress.equals(sender) && knownSenders.contains(storageAddress)) { continue mainLoop; } } BigInteger userOpGasCost = simulateValidationResult.getReturnInfo().getPreOpGas().add(uop.getCallGasLimit()); BigInteger newTotalGas = totalGas.add(userOpGasCost); if (newTotalGas.compareTo(bundleConfig.getMaxBundleGas()) > 0) { break; } if (!FieldUtil.isEmpty(paymaster)) { if (!paymasterDeposit.containsKey(paymaster)) { paymasterDeposit.put(paymaster, Entrypoint.balanceOf(chainConfig, poolConfig.getEntrypoint(), paymaster)); } if (paymasterDeposit.get(paymaster).compareTo(simulateValidationResult.getReturnInfo().getPrefund()) < 0) { continue; } stakedEntityCount.compute(paymaster, (k, v) -> { if (v == null) { return 1; } else { return v + 1; } }); paymasterDeposit.put(paymaster, paymasterDeposit.get(paymaster).subtract(simulateValidationResult.getReturnInfo().getPrefund())); } if (!FieldUtil.isEmpty(factory)) { stakedEntityCount.compute(factory, (k, v) -> { if (v == null) { return 1; } else { return v + 1; } }); } // TODO YUKINO 2023/10/31: hash root mergeStorageMap(storageMap, simulateValidationResult.getStorageMap()); senders.add(sender); totalGas = newTotalGas; //calculate gas gasComputer.add(uop); entryList.add(entry); } if (entryList.isEmpty()) { return UopBundleDO.NULL; } return new UopBundleDO(entryList, storageMap, gasComputer.toTransactionGas(gasService.getGasPriceInfoWithCache(chainConfig).getBaseFee())); } private boolean checkUopMaxFee(IChain chain, UserOperationDO uop) { BigInteger uopMaxPriorityFeePerGas = uop.getMaxPriorityFeePerGas(); BigInteger uopBaseFee = uop.getMaxFeePerGas().subtract(uopMaxPriorityFeePerGas); GasPriceInfo gasPriceInfo = gasService.getGasPriceInfoWithCache(chain); BigInteger clientBaseFee = gasPriceInfo.getBaseFee(); BigDecimal bundlerBaseFeeCoefficient = bundleConfig.getBaseFeeMinCoefficient(); if (uopBaseFee.compareTo(MathUtil.multiply(clientBaseFee, bundlerBaseFeeCoefficient)) < 0) { log.warn("skip to send onchain, chain {}, baseFee is to low, uopHash: {}, uopBaseFee: {}, clientBaseFee: " + "{}, coefficient: {}", chain, uop.getOpHash(), uopBaseFee, clientBaseFee, bundlerBaseFeeCoefficient); return false; } BigInteger clientMaxPriorityFeePerGas = gasPriceInfo.getMaxPriorityFeePerGas(); BigDecimal bundlerMaxFeePerGasCoefficient = bundleConfig.getMaxPriorityFeePerGasMinCoefficient(); if (uopMaxPriorityFeePerGas.compareTo(MathUtil.multiply(clientMaxPriorityFeePerGas, bundlerMaxFeePerGasCoefficient)) < 0) { log.warn("skip to send onchain, chain {}, maxPriorityFeePerGas is to low, uopHash: {}, " + "uopMaxPriorityFeePerGas: {}, clientMaxPriorityFeePerGas: {}, coefficient: {}", chain, uop.getOpHash(), uopMaxPriorityFeePerGas, clientMaxPriorityFeePerGas, bundlerMaxFeePerGasCoefficient); return false; } return true; } @Override public void handlePastEvents() { logEventService.handlePastEvents(); } @Override public TxAndOpHashMappingDO sendNextBundle() { handlePastEvents(); UopBundleDO bundle = createBundle(); if (bundle == UopBundleDO.NULL) { return null; } Credentials bundlerCredential = onChainConfig.getBundlerCredential(); List<MempoolEntry> entryList = bundle.getMempoolEntryList(); TransactionGas transactionGas = bundle.getTransactionGas(); return sendBundle(entryList, bundle.getStorageMap(), transactionGas, bundlerCredential); } private TxAndOpHashMappingDO sendBundle(List<MempoolEntry> entryList, Map<String, SlotMap> storageMap, TransactionGas transactionGas, Credentials bundlerCredential) { List<UserOperationDO> uopList = entryList.stream().map(MempoolEntry::getUop).collect(Collectors.toList()); // TODO YUKINO 2023/10/28: 给钱最少得Bundler String txHash = Entrypoint.handleOps(uopList, bundlerCredential.getAddress(), onChainConfig.getPrivateKey(), transactionGas.getGasLimit(), transactionGas.getMaxFeePerGas(), transactionGas.getMaxPriorityFeePerGas()); // sleep one block time try { Thread.sleep(chainConfig.getBlockTime()); } catch (InterruptedException e) { } // TODO YUKINO 2023/10/30: 优化
package com.okcoin.dapp.bundler.manager; /** * @ClassName BundlerServiceImpl * @Author qunqin * @Date 2023/10/25 **/ @Component @Slf4j public class BundlerServiceImpl implements IBundleService { @Resource private MempoolService mempoolService; @Resource private BundleConfig bundleConfig; @Resource private GasService gasService; @Resource private EntryPointSimulationsFactory entryPointSimulationsFactory; @Autowired private OnChainConfig onChainConfig; @Autowired private ChainConfig chainConfig; @Autowired private LogEventService logEventService; @Autowired private ReputationService reputationService; @Autowired private PoolConfig poolConfig; @Autowired private OnChainTxFailedService onChainTxFailedService; private static final Long THROTTLED_ENTITY_BUNDLE_COUNT = 4L; private UopBundleDO createBundle() { List<MempoolEntry> entryList = Lists.newArrayList(); GasComputer gasComputer = new GasComputer(chainConfig, bundleConfig.getMaxBundleGas()); Set<String> senders = Sets.newHashSet(); Map<String, Integer> stakedEntityCount = Maps.newHashMap(); Map<String, BigInteger> paymasterDeposit = Maps.newHashMap(); Set<String> knownSenders = mempoolService.getKnownSenders(); Map<String, SlotMap> storageMap = Maps.newHashMap(); List<MempoolEntry> priorityEntryList = mempoolService.getAllEntryWithPriority(); IEntryPointSimulations entryPointSimulations = entryPointSimulationsFactory.get(poolConfig.getEntrypoint()); BigInteger totalGas = BigInteger.ZERO; mainLoop: for (MempoolEntry entry : priorityEntryList) { UserOperationDO uop = entry.getUop(); String sender = uop.getSender(); String paymaster = entry.getUop().getPaymaster(); String factory = entry.getUop().getFactory(); ReputationStatusEnum paymasterStatus = reputationService.getStatus(paymaster); ReputationStatusEnum factoryStatus = reputationService.getStatus(factory); if (paymasterStatus == ReputationStatusEnum.BANNED || factoryStatus == ReputationStatusEnum.BANNED) { mempoolService.removeUop(sender, uop.getNonce()); continue; } if (!AddressUtil.isEmpty(paymaster) && (paymasterStatus == ReputationStatusEnum.THROTTLED || stakedEntityCount.getOrDefault(paymaster, 0) > THROTTLED_ENTITY_BUNDLE_COUNT)) { continue; } if (!AddressUtil.isEmpty(factory) && (factoryStatus == ReputationStatusEnum.THROTTLED || stakedEntityCount.getOrDefault(factory, 0) > THROTTLED_ENTITY_BUNDLE_COUNT)) { continue; } if (senders.contains(sender)) { continue; } SimulateValidationResult simulateValidationResult; try { simulateValidationResult = entryPointSimulations.simulateValidation(uop, entry.getReferencedContracts()); } catch (Exception e) { log.error("bundle simulateValidation error", e); mempoolService.removeUop(sender, uop.getNonce()); continue; } //validate storage sender for (String storageAddress : simulateValidationResult.getStorageMap().keySet()) { if (!storageAddress.equals(sender) && knownSenders.contains(storageAddress)) { continue mainLoop; } } BigInteger userOpGasCost = simulateValidationResult.getReturnInfo().getPreOpGas().add(uop.getCallGasLimit()); BigInteger newTotalGas = totalGas.add(userOpGasCost); if (newTotalGas.compareTo(bundleConfig.getMaxBundleGas()) > 0) { break; } if (!FieldUtil.isEmpty(paymaster)) { if (!paymasterDeposit.containsKey(paymaster)) { paymasterDeposit.put(paymaster, Entrypoint.balanceOf(chainConfig, poolConfig.getEntrypoint(), paymaster)); } if (paymasterDeposit.get(paymaster).compareTo(simulateValidationResult.getReturnInfo().getPrefund()) < 0) { continue; } stakedEntityCount.compute(paymaster, (k, v) -> { if (v == null) { return 1; } else { return v + 1; } }); paymasterDeposit.put(paymaster, paymasterDeposit.get(paymaster).subtract(simulateValidationResult.getReturnInfo().getPrefund())); } if (!FieldUtil.isEmpty(factory)) { stakedEntityCount.compute(factory, (k, v) -> { if (v == null) { return 1; } else { return v + 1; } }); } // TODO YUKINO 2023/10/31: hash root mergeStorageMap(storageMap, simulateValidationResult.getStorageMap()); senders.add(sender); totalGas = newTotalGas; //calculate gas gasComputer.add(uop); entryList.add(entry); } if (entryList.isEmpty()) { return UopBundleDO.NULL; } return new UopBundleDO(entryList, storageMap, gasComputer.toTransactionGas(gasService.getGasPriceInfoWithCache(chainConfig).getBaseFee())); } private boolean checkUopMaxFee(IChain chain, UserOperationDO uop) { BigInteger uopMaxPriorityFeePerGas = uop.getMaxPriorityFeePerGas(); BigInteger uopBaseFee = uop.getMaxFeePerGas().subtract(uopMaxPriorityFeePerGas); GasPriceInfo gasPriceInfo = gasService.getGasPriceInfoWithCache(chain); BigInteger clientBaseFee = gasPriceInfo.getBaseFee(); BigDecimal bundlerBaseFeeCoefficient = bundleConfig.getBaseFeeMinCoefficient(); if (uopBaseFee.compareTo(MathUtil.multiply(clientBaseFee, bundlerBaseFeeCoefficient)) < 0) { log.warn("skip to send onchain, chain {}, baseFee is to low, uopHash: {}, uopBaseFee: {}, clientBaseFee: " + "{}, coefficient: {}", chain, uop.getOpHash(), uopBaseFee, clientBaseFee, bundlerBaseFeeCoefficient); return false; } BigInteger clientMaxPriorityFeePerGas = gasPriceInfo.getMaxPriorityFeePerGas(); BigDecimal bundlerMaxFeePerGasCoefficient = bundleConfig.getMaxPriorityFeePerGasMinCoefficient(); if (uopMaxPriorityFeePerGas.compareTo(MathUtil.multiply(clientMaxPriorityFeePerGas, bundlerMaxFeePerGasCoefficient)) < 0) { log.warn("skip to send onchain, chain {}, maxPriorityFeePerGas is to low, uopHash: {}, " + "uopMaxPriorityFeePerGas: {}, clientMaxPriorityFeePerGas: {}, coefficient: {}", chain, uop.getOpHash(), uopMaxPriorityFeePerGas, clientMaxPriorityFeePerGas, bundlerMaxFeePerGasCoefficient); return false; } return true; } @Override public void handlePastEvents() { logEventService.handlePastEvents(); } @Override public TxAndOpHashMappingDO sendNextBundle() { handlePastEvents(); UopBundleDO bundle = createBundle(); if (bundle == UopBundleDO.NULL) { return null; } Credentials bundlerCredential = onChainConfig.getBundlerCredential(); List<MempoolEntry> entryList = bundle.getMempoolEntryList(); TransactionGas transactionGas = bundle.getTransactionGas(); return sendBundle(entryList, bundle.getStorageMap(), transactionGas, bundlerCredential); } private TxAndOpHashMappingDO sendBundle(List<MempoolEntry> entryList, Map<String, SlotMap> storageMap, TransactionGas transactionGas, Credentials bundlerCredential) { List<UserOperationDO> uopList = entryList.stream().map(MempoolEntry::getUop).collect(Collectors.toList()); // TODO YUKINO 2023/10/28: 给钱最少得Bundler String txHash = Entrypoint.handleOps(uopList, bundlerCredential.getAddress(), onChainConfig.getPrivateKey(), transactionGas.getGasLimit(), transactionGas.getMaxFeePerGas(), transactionGas.getMaxPriorityFeePerGas()); // sleep one block time try { Thread.sleep(chainConfig.getBlockTime()); } catch (InterruptedException e) { } // TODO YUKINO 2023/10/30: 优化
TransactionReceiptCommon receipt;
6
2023-11-27 10:54:49+00:00
16k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/external/ScoreDataImporter.java
[ { "identifier": "ScoreData", "path": "core/src/bms/player/beatoraja/ScoreData.java", "snippet": "public class ScoreData implements Validatable {\n\n\t// TODO 各OPでのクリア、各DPオプションでのクリア、増加型/減少型プレイゲージでの最大クリア\n\n\t/**\n\t * 譜面のハッシュ値\n\t */\n\tprivate String sha256 = \"\";\n\t/**\n\t * プレイヤー名。自身のスコアの場合は空白\n\t *...
import bms.player.beatoraja.ScoreData; import bms.player.beatoraja.ScoreDatabaseAccessor; import bms.player.beatoraja.song.SongData; import bms.player.beatoraja.song.SongDatabaseAccessor; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; import java.sql.Connection; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger;
13,053
package bms.player.beatoraja.external; public class ScoreDataImporter { private ScoreDatabaseAccessor scoredb; public ScoreDataImporter(ScoreDatabaseAccessor scoredb) { this.scoredb = scoredb; } public void importFromLR2ScoreDatabase(String path, SongDatabaseAccessor songdb) { final int[] clears = { 0, 1, 4, 5, 6, 8, 9 }; scoredb.createTable(); try (Connection con = DriverManager.getConnection("jdbc:sqlite:" + path)) { QueryRunner qr = new QueryRunner(); MapListHandler rh = new MapListHandler(); List<Map<String, Object>> scores = qr.query(con, "SELECT * FROM score", rh);
package bms.player.beatoraja.external; public class ScoreDataImporter { private ScoreDatabaseAccessor scoredb; public ScoreDataImporter(ScoreDatabaseAccessor scoredb) { this.scoredb = scoredb; } public void importFromLR2ScoreDatabase(String path, SongDatabaseAccessor songdb) { final int[] clears = { 0, 1, 4, 5, 6, 8, 9 }; scoredb.createTable(); try (Connection con = DriverManager.getConnection("jdbc:sqlite:" + path)) { QueryRunner qr = new QueryRunner(); MapListHandler rh = new MapListHandler(); List<Map<String, Object>> scores = qr.query(con, "SELECT * FROM score", rh);
List<ScoreData> result = new ArrayList<ScoreData>();
0
2023-12-02 23:41:17+00:00
16k
Elb1to/FFA
src/main/java/me/elb1to/ffa/FfaPlugin.java
[ { "identifier": "Assemble", "path": "src/main/java/io/github/thatkawaiisam/assemble/Assemble.java", "snippet": "@Getter\n@Setter\npublic class Assemble {\n\n\tprivate final JavaPlugin plugin;\n\tprivate final ChatColor[] chatColorCache = ChatColor.values();\n\tprivate AssembleAdapter adapter;\n\tprivate...
import io.github.thatkawaiisam.assemble.Assemble; import io.github.thatkawaiisam.assemble.AssembleStyle; import lombok.Getter; import me.elb1to.ffa.command.manager.CommandManager; import me.elb1to.ffa.database.MongoSrv; import me.elb1to.ffa.game.listener.FfaListener; import me.elb1to.ffa.game.manager.FfaManager; import me.elb1to.ffa.game.task.ItemRemovalTask; import me.elb1to.ffa.kit.manager.KitManager; import me.elb1to.ffa.layout.ScoreboardLayout; import me.elb1to.ffa.leaderboard.manager.LeaderboardManager; import me.elb1to.ffa.map.FfaMap; import me.elb1to.ffa.map.manager.MapManager; import me.elb1to.ffa.user.UserProfile; import me.elb1to.ffa.user.listener.UserProfileListener; import me.elb1to.ffa.user.manager.UserProfileManager; import me.elb1to.ffa.util.menu.listener.ButtonListener; import me.elb1to.ffa.util.world.Cuboid; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.plugin.java.JavaPlugin;
11,489
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv; private MapManager mapManager; private KitManager kitManager; private FfaManager ffaManager; private UserProfileManager userProfileManager; private LeaderboardManager leaderboardManager; private CommandManager commandManager; @Override public void onEnable() { saveDefaultConfig(); mongoSrv = new MongoSrv(this, getConfig().getConfigurationSection("mongo")); mapManager = new MapManager(this, getConfig().getConfigurationSection("maps")); kitManager = new KitManager(this, getConfig().getConfigurationSection("kits")); ffaManager = new FfaManager(this); userProfileManager = new UserProfileManager(this); leaderboardManager = new LeaderboardManager(this); commandManager = new CommandManager(this); getServer().getPluginManager().registerEvents(new FfaListener(this), this); getServer().getPluginManager().registerEvents(new ButtonListener(this), this); getServer().getPluginManager().registerEvents(new UserProfileListener(this), this); getServer().getScheduler().runTaskLater(this, () -> { for (FfaMap ffaMap : mapManager.getMaps()) { ffaMap.setWorld(Bukkit.getWorld(ffaMap.getName())); Cuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation()); ffaMap.setCuboid(cuboid); } leaderboardManager.updateLeaderboards(); }, 100L); getServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L); Assemble assemble = new Assemble(this, new ScoreboardLayout(this));
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv; private MapManager mapManager; private KitManager kitManager; private FfaManager ffaManager; private UserProfileManager userProfileManager; private LeaderboardManager leaderboardManager; private CommandManager commandManager; @Override public void onEnable() { saveDefaultConfig(); mongoSrv = new MongoSrv(this, getConfig().getConfigurationSection("mongo")); mapManager = new MapManager(this, getConfig().getConfigurationSection("maps")); kitManager = new KitManager(this, getConfig().getConfigurationSection("kits")); ffaManager = new FfaManager(this); userProfileManager = new UserProfileManager(this); leaderboardManager = new LeaderboardManager(this); commandManager = new CommandManager(this); getServer().getPluginManager().registerEvents(new FfaListener(this), this); getServer().getPluginManager().registerEvents(new ButtonListener(this), this); getServer().getPluginManager().registerEvents(new UserProfileListener(this), this); getServer().getScheduler().runTaskLater(this, () -> { for (FfaMap ffaMap : mapManager.getMaps()) { ffaMap.setWorld(Bukkit.getWorld(ffaMap.getName())); Cuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation()); ffaMap.setCuboid(cuboid); } leaderboardManager.updateLeaderboards(); }, 100L); getServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L); Assemble assemble = new Assemble(this, new ScoreboardLayout(this));
assemble.setAssembleStyle(AssembleStyle.CUSTOM);
1
2023-11-28 16:53:29+00:00
16k
WiIIiam278/HuskClaims
bukkit/src/main/java/net/william278/huskclaims/event/BukkitCreateChildClaimEvent.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import lombok.Getter; import lombok.Setter; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.user.OnlineUser; import org.bukkit.event.Cancellable; import org.jetbrains.annotations.NotNull;
10,949
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.event; @Getter public class BukkitCreateChildClaimEvent extends BukkitPlayerEvent implements CreateChildClaimEvent, Cancellable {
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.event; @Getter public class BukkitCreateChildClaimEvent extends BukkitPlayerEvent implements CreateChildClaimEvent, Cancellable {
private final Claim parentClaim;
1
2023-11-28 01:09:43+00:00
16k
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/xxljob/service/impl/XxlJobServiceImpl.java
[ { "identifier": "SecurityContextHolder", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/context/SecurityContextHolder.java", "snippet": "public class SecurityContextHolder\n{\n private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new Transmitt...
import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.metax.common.core.context.SecurityContextHolder; import com.metax.common.core.exception.ServiceException; import com.metax.common.core.web.domain.AjaxResult; import com.metax.web.domain.MessageTemplate; import com.metax.web.mapper.MessageTemplateMapper; import com.metax.web.util.DataUtil; import com.metax.web.xxljob.domain.CronTaskCords; import com.metax.web.xxljob.domain.XxlJobInfo; import com.metax.web.xxljob.enums.ExecutorRouteStrategyEnum; import com.metax.web.xxljob.enums.MisfireStrategyEnum; import com.metax.web.xxljob.enums.ScheduleTypeEnum; import com.metax.web.xxljob.service.XxlJobService; import com.metax.web.xxljob.util.XxlJobUtil; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.enums.ExecutorBlockStrategyEnum; import com.xxl.job.core.glue.GlueTypeEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.scheduling.support.CronExpression; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Date; import java.util.Objects; import static com.metax.common.core.constant.MetaxDataConstants.*; import static com.metax.common.core.web.domain.AjaxResult.DATA_TAG;
11,942
package com.metax.web.xxljob.service.impl; @Service @Slf4j public class XxlJobServiceImpl implements XxlJobService { @Autowired private XxlJobUtil xxlJobUtil; @Autowired private MessageTemplateMapper messageTemplateMapper; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private DataUtil dataUtil; @Value("${xxl.job.executor.jobHandlerName}") private String jobName; /** * 保存xxlJob任务 * * @param messageTemplate * @return */ @Override public AjaxResult save(MessageTemplate messageTemplate) {
package com.metax.web.xxljob.service.impl; @Service @Slf4j public class XxlJobServiceImpl implements XxlJobService { @Autowired private XxlJobUtil xxlJobUtil; @Autowired private MessageTemplateMapper messageTemplateMapper; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private DataUtil dataUtil; @Value("${xxl.job.executor.jobHandlerName}") private String jobName; /** * 保存xxlJob任务 * * @param messageTemplate * @return */ @Override public AjaxResult save(MessageTemplate messageTemplate) {
XxlJobInfo xxlJobInfo = buildXxlJobInfo(messageTemplate);
7
2023-12-04 05:10:13+00:00
16k
ydb-platform/yoj-project
repository-ydb-v1/src/test/java/tech/ydb/yoj/repository/ydb/yql/YqlTypeAllTypesTest.java
[ { "identifier": "FieldValueType", "path": "databind/src/main/java/tech/ydb/yoj/databind/FieldValueType.java", "snippet": "public enum FieldValueType {\n /**\n * Integer value.\n * Java-side <strong>must</strong> either be a numeric primitive, or extend {@link Number java.lang.Number} and\n ...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import tech.ydb.yoj.databind.FieldValueType; import tech.ydb.yoj.databind.schema.Column; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.repository.DbTypeQualifier; import tech.ydb.yoj.repository.test.sample.TestJsonConverter; import tech.ydb.yoj.repository.ydb.DbType; import java.lang.reflect.Type; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue;
11,615
@Column(dbType = DbType.FLOAT) private float fieldPrimitiveFloatFloat; @Column private Double fieldDouble; @Column(dbType = DbType.DOUBLE) private Double fieldDoubleDouble; @Column private double fieldPrimitiveDouble; @Column(dbType = DbType.DOUBLE) private double fieldPrimitiveDoubleDouble; @Column private String fieldString; @Column(dbType = DbType.STRING) private String fieldStringString; @Column(dbType = DbType.UTF8) private String fieldStringUtf8; @Column(dbType = DbType.JSON) private String fieldStringJson; @Column private byte[] fieldBytes; @Column(dbType = DbType.STRING) private byte[] fieldBytesString; @Column private Instant fieldInstant; @Column(dbType = DbType.INT64) private Instant fieldInstantInt64; @Column(dbType = DbType.UINT64) private Instant fieldInstantUint64; @Column(dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantSeconds; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantInt64Seconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantUint64Seconds; @Column(dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantMilliseconds; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantInt64Milliseconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantUint64Milliseconds; @Column(dbType = DbType.TIMESTAMP) private Instant fieldInstantTimestamp; private Duration fieldDuration; @Column(dbType = DbType.INTERVAL) private Duration fieldDurationInterval; @Column(dbType = DbType.INT64) private Duration fieldDurationInt64; @Column(dbType = DbType.UINT64) private Duration fieldDurationUint64; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Duration fieldDurationInt64Milliseconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Duration fieldDurationUint64Milliseconds; @Column(dbType = DbType.INT32) private Duration fieldDurationInt32; @Column(dbType = DbType.UINT32) private Duration fieldDurationUint32; @Column(dbType = DbType.UTF8) private Duration fieldDurationUtf8; @Column private TestEnum fieldEnum; @Column(dbType = DbType.STRING) private TestEnum fieldEnumString; @Column(dbType = DbType.UTF8) private TestEnum fieldEnumUtf8; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumWithNameQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumDbTypeStringWithNameQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumDbTypeUtf8WithNameQualifier; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumWithEnumToStringAndNameQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumDbTypeStringWithEnumToStringAndNameQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumDbTypeUtf8WithEnumToStringAndNameQualifier; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumWithToStringQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumDbTypeStringWithToStringQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumDbTypeUtf8WithToStringQualifier; @Column private Map<String, Object> fieldObject; @Column(dbType = DbType.UTF8) private Map<String, Object> fieldObjectUtf8; @Column(dbType = DbType.STRING) private Map<String, Object> fieldObjectString; @Column(dbType = DbType.JSON) private Map<String, Object> fieldObjectJson; @Column private JsonNode fieldJsonNode; @Column(dbType = DbType.UTF8) private JsonNode fieldJsonNodeUtf8; @Column(dbType = DbType.STRING) private JsonNode fieldJsonNodeString; @Column(dbType = DbType.JSON) private JsonNode fieldJsonNodeJson; @Column private UUID fieldUUID; @Column(dbType = DbType.UTF8) private UUID fieldUUIDUtf8; @Column(dbType = DbType.STRING) private UUID fieldUUIDString; }
package tech.ydb.yoj.repository.ydb.yql; @RunWith(Parameterized.class) public class YqlTypeAllTypesTest { static { FieldValueType.registerStringValueType(UUID.class); TestJsonConverter.register(); } private static final Map<String, Object> OBJECT_VALUE = Map.of("string", "Unnamed", "number", 11, "boolean", true); private static final String JSON_STRING = """ {"integer": 17, "boolean": true, "string": "Nothing", "null": null} """; private static final TestSchema SCHEMA = new TestSchema(TestFields.class); @Parameters public static Collection<Object[]> data() { ObjectNode objectNode = JsonNodeFactory.instance.objectNode(); objectNode.put("integer", 17).put("boolean", true).put("string", "Nothing").putNull("null"); objectNode.putArray("array").add(17).add(true).add("Not empty string.").addNull(); objectNode.putObject("object").put("integer", 17).put("boolean", true).put("string", "Nothing").putNull("null"); UUID uuid = UUID.fromString("faefa9bc-eabc-4b90-a973-f25e6cd91e63"); return List.of(new Object[][] { {"fieldBoolean", "Bool", true, true}, {"fieldBooleanBool", "Bool", true, false}, {"fieldPrimitiveBoolean", "Bool", true, false}, {"fieldPrimitiveBooleanBool", "Bool", true, false}, {"fieldByte", "Int32", (byte) 17, true}, {"fieldByteInt32", "Int32", (byte) 17, false}, {"fieldByteUint8", "Uint8", (byte) 17, false}, {"fieldPrimitiveByte", "Int32", (byte) 17, true}, {"fieldPrimitiveByteInt32", "Int32", (byte) 17, false}, {"fieldPrimitiveByteUint8", "Uint8", (byte) 17, false}, {"fieldShort", "Int32", (short) 1723, true}, {"fieldShortInt32", "Int32", (short) 1723, false}, {"fieldPrimitiveShort", "Int32", (short) 1723, true}, {"fieldPrimitiveShortInt32", "Int32", (short) 1723, false}, {"fieldInteger", "Int32", 42, true}, {"fieldIntegerInt32", "Int32", 42, false}, {"fieldIntegerUint32", "Uint32", 42, false}, {"fieldIntegerUint8", "Uint8", 42, false}, {"fieldPrimitiveInteger", "Int32", 42, true}, {"fieldPrimitiveIntegerInt32", "Int32", 42, false}, {"fieldPrimitiveIntegerUint32", "Uint32", 42, false}, {"fieldPrimitiveIntegerUint8", "Uint8", 42, false}, {"fieldLong", "Int64", 100500L, true}, {"fieldLongInt64", "Int64", 100500L, false}, {"fieldLongUint64", "Uint64", 100500L, false}, {"fieldPrimitiveLong", "Int64", 100500L, true}, {"fieldPrimitiveLongInt64", "Int64", 100500L, false}, {"fieldPrimitiveLongUint64", "Uint64", 100500L, false}, {"fieldFloat", "Float", 17.42f, true}, {"fieldFloatFloat", "Float", 17.42f, false}, {"fieldPrimitiveFloat", "Float", 17.42f, true}, {"fieldPrimitiveFloatFloat", "Float", 17.42f, false}, {"fieldDouble", "Double", 100500.23, true}, {"fieldDoubleDouble", "Double", 100500.23, false}, {"fieldPrimitiveDouble", "Double", 100500.23, true}, {"fieldPrimitiveDoubleDouble", "Double", 100500.23, false}, {"fieldString", "String", "There is nothing here.", true}, {"fieldStringString", "String", "There is nothing here.", false}, {"fieldStringUtf8", "Utf8", "There is nothing here.", false}, {"fieldStringJson", "Json", JSON_STRING, false}, {"fieldBytes", "String", new byte[]{17, 42, -23}, true}, {"fieldBytesString", "String", new byte[]{17, 42, -23}, false}, {"fieldInstant", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), true}, {"fieldInstantInt64", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantUint64", "Uint64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantSeconds", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantInt64Seconds", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantUint64Seconds", "Uint64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantMilliseconds", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantInt64Milliseconds", "Int64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantUint64Milliseconds", "Uint64", Instant.parse("2020-02-20T11:07:17.00Z"), false}, {"fieldInstantTimestamp", "Timestamp", Instant.parse("2020-02-20T11:07:17.516000Z"), false}, // XXX Temporarily require an explicit specification // of the database type for duration fields in order to find possible places of the old use // of duration in the DB model {"fieldDurationInterval", "Interval", Duration.parse("P1DT30M0.000001S"), false}, {"fieldDurationInt64", "Int64", Duration.parse("-P1DT30M0.000001S"), false}, {"fieldDurationUint64", "Uint64", Duration.parse("P1DT30M0.000001S"), false}, {"fieldDurationInt64Milliseconds", "Int64", Duration.parse("-P1DT30M0.001S"), false}, {"fieldDurationUint64Milliseconds", "Uint64", Duration.parse("P1DT30M0.001S"), false}, {"fieldDurationInt32", "Int32", Duration.parse("-P1DT30M7S"), false}, {"fieldDurationUint32", "Uint32", Duration.parse("P1DT30M7S"), false}, {"fieldDurationUtf8", "Utf8", Duration.parse("-P1DT17H30M7.123456S"), false}, {"fieldEnum", "String", TestEnum.BLUE, true}, {"fieldEnumString", "String", TestEnum.BLUE, false}, {"fieldEnumUtf8", "Utf8", TestEnum.BLUE, false}, {"fieldEnumWithNameQualifier", "String", TestEnum.BLUE, true}, {"fieldEnumDbTypeStringWithNameQualifier", "String", TestEnum.BLUE, false}, {"fieldEnumDbTypeUtf8WithNameQualifier", "Utf8", TestEnum.BLUE, false}, {"fieldEnumWithEnumToStringAndNameQualifier", "String", TestToStringValueEnum.BLUE, true}, {"fieldEnumDbTypeStringWithEnumToStringAndNameQualifier", "String", TestToStringValueEnum.BLUE, false}, {"fieldEnumDbTypeUtf8WithEnumToStringAndNameQualifier", "Utf8", TestToStringValueEnum.BLUE, false}, {"fieldEnumWithToStringQualifier", "String", TestToStringValueEnum.BLUE, true}, {"fieldEnumDbTypeStringWithToStringQualifier", "String", TestToStringValueEnum.BLUE, false}, {"fieldEnumDbTypeUtf8WithToStringQualifier", "Utf8", TestToStringValueEnum.BLUE, false}, {"fieldObject", "Json", OBJECT_VALUE, true}, {"fieldObjectUtf8", "Utf8", OBJECT_VALUE, false}, {"fieldObjectString", "String", OBJECT_VALUE, false}, {"fieldObjectJson", "Json", OBJECT_VALUE, false}, {"fieldJsonNode", "Json", objectNode, true}, {"fieldJsonNodeUtf8", "Utf8", objectNode, false}, {"fieldJsonNodeString", "String", objectNode, false}, {"fieldJsonNodeJson", "Json", objectNode, false}, {"fieldUUID", "String", uuid, false}, {"fieldUUIDUtf8", "Utf8", uuid, false}, {"fieldUUIDString", "String", uuid, false}, }); } @Parameter(0) public String fieldName; @Parameter(1) public String dbType; @Parameter(2) public Object value; @Parameter(3) public boolean testOfTypeMethod; @Test public void testOfJavaFiled() { var yqlType = YqlType.of(SCHEMA.getField(fieldName)); assertThat(yqlType.getJavaType()).isEqualTo(getTestFieldType(fieldName)); assertThat(yqlType.getYqlTypeName()).isEqualTo(dbType); } @Test public void testOfType() { assumeTrue(testOfTypeMethod); Type type = getTestFieldType(fieldName); var yqlType = YqlType.of(type); assertThat(yqlType.getJavaType()).isEqualTo(type); assertThat(yqlType.getYqlTypeName()).isEqualTo(dbType); } @Test public void testToFrom() { var yqlType = YqlType.of(SCHEMA.getField(fieldName)); var actual = yqlType.fromYql(yqlType.toYql(value).build()); assertThat(actual).isEqualTo(value); } @SneakyThrows(NoSuchFieldException.class) private static Type getTestFieldType(String fieldName) { return TestFields.class.getDeclaredField(fieldName).getGenericType(); } @AllArgsConstructor public static class TestFields { @Column private Boolean fieldBoolean; @Column(dbType = DbType.BOOL) private Boolean fieldBooleanBool; @Column private boolean fieldPrimitiveBoolean; @Column(dbType = DbType.BOOL) private boolean fieldPrimitiveBooleanBool; @Column private Byte fieldByte; @Column(dbType = DbType.INT32) private Byte fieldByteInt32; @Column(dbType = DbType.UINT8) private Byte fieldByteUint8; @Column private byte fieldPrimitiveByte; @Column(dbType = DbType.INT32) private byte fieldPrimitiveByteInt32; @Column(dbType = DbType.UINT8) private byte fieldPrimitiveByteUint8; @Column private Short fieldShort; @Column(dbType = DbType.INT32) private Short fieldShortInt32; @Column private short fieldPrimitiveShort; @Column(dbType = DbType.INT32) private short fieldPrimitiveShortInt32; @Column private Integer fieldInteger; @Column(dbType = DbType.INT32) private Integer fieldIntegerInt32; @Column(dbType = DbType.UINT32) private Integer fieldIntegerUint32; @Column(dbType = DbType.UINT8) private Integer fieldIntegerUint8; @Column private int fieldPrimitiveInteger; @Column(dbType = DbType.INT32) private int fieldPrimitiveIntegerInt32; @Column(dbType = DbType.UINT32) private int fieldPrimitiveIntegerUint32; @Column(dbType = DbType.UINT8) private int fieldPrimitiveIntegerUint8; @Column private Long fieldLong; @Column(dbType = DbType.INT64) private Long fieldLongInt64; @Column(dbType = DbType.UINT64) private Long fieldLongUint64; @Column private long fieldPrimitiveLong; @Column(dbType = DbType.INT64) private long fieldPrimitiveLongInt64; @Column(dbType = DbType.UINT64) private long fieldPrimitiveLongUint64; @Column private Float fieldFloat; @Column(dbType = DbType.FLOAT) private Float fieldFloatFloat; @Column private float fieldPrimitiveFloat; @Column(dbType = DbType.FLOAT) private float fieldPrimitiveFloatFloat; @Column private Double fieldDouble; @Column(dbType = DbType.DOUBLE) private Double fieldDoubleDouble; @Column private double fieldPrimitiveDouble; @Column(dbType = DbType.DOUBLE) private double fieldPrimitiveDoubleDouble; @Column private String fieldString; @Column(dbType = DbType.STRING) private String fieldStringString; @Column(dbType = DbType.UTF8) private String fieldStringUtf8; @Column(dbType = DbType.JSON) private String fieldStringJson; @Column private byte[] fieldBytes; @Column(dbType = DbType.STRING) private byte[] fieldBytesString; @Column private Instant fieldInstant; @Column(dbType = DbType.INT64) private Instant fieldInstantInt64; @Column(dbType = DbType.UINT64) private Instant fieldInstantUint64; @Column(dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantSeconds; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantInt64Seconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.SECONDS) private Instant fieldInstantUint64Seconds; @Column(dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantMilliseconds; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantInt64Milliseconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Instant fieldInstantUint64Milliseconds; @Column(dbType = DbType.TIMESTAMP) private Instant fieldInstantTimestamp; private Duration fieldDuration; @Column(dbType = DbType.INTERVAL) private Duration fieldDurationInterval; @Column(dbType = DbType.INT64) private Duration fieldDurationInt64; @Column(dbType = DbType.UINT64) private Duration fieldDurationUint64; @Column(dbType = DbType.INT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Duration fieldDurationInt64Milliseconds; @Column(dbType = DbType.UINT64, dbTypeQualifier = DbTypeQualifier.MILLISECONDS) private Duration fieldDurationUint64Milliseconds; @Column(dbType = DbType.INT32) private Duration fieldDurationInt32; @Column(dbType = DbType.UINT32) private Duration fieldDurationUint32; @Column(dbType = DbType.UTF8) private Duration fieldDurationUtf8; @Column private TestEnum fieldEnum; @Column(dbType = DbType.STRING) private TestEnum fieldEnumString; @Column(dbType = DbType.UTF8) private TestEnum fieldEnumUtf8; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumWithNameQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumDbTypeStringWithNameQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestEnum fieldEnumDbTypeUtf8WithNameQualifier; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumWithEnumToStringAndNameQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumDbTypeStringWithEnumToStringAndNameQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_NAME) private TestToStringValueEnum fieldEnumDbTypeUtf8WithEnumToStringAndNameQualifier; @Column(dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumWithToStringQualifier; @Column(dbType = DbType.STRING, dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumDbTypeStringWithToStringQualifier; @Column(dbType = DbType.UTF8, dbTypeQualifier = DbTypeQualifier.ENUM_TO_STRING) private TestToStringValueEnum fieldEnumDbTypeUtf8WithToStringQualifier; @Column private Map<String, Object> fieldObject; @Column(dbType = DbType.UTF8) private Map<String, Object> fieldObjectUtf8; @Column(dbType = DbType.STRING) private Map<String, Object> fieldObjectString; @Column(dbType = DbType.JSON) private Map<String, Object> fieldObjectJson; @Column private JsonNode fieldJsonNode; @Column(dbType = DbType.UTF8) private JsonNode fieldJsonNodeUtf8; @Column(dbType = DbType.STRING) private JsonNode fieldJsonNodeString; @Column(dbType = DbType.JSON) private JsonNode fieldJsonNodeJson; @Column private UUID fieldUUID; @Column(dbType = DbType.UTF8) private UUID fieldUUIDUtf8; @Column(dbType = DbType.STRING) private UUID fieldUUIDString; }
public static class TestSchema extends Schema<TestFields> {
1
2023-12-05 15:57:58+00:00
16k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/MCOptionUtils.java
[ { "identifier": "windowHeight", "path": "app_pojavlauncher/src/main/java/org/lwjgl/glfw/CallbackBridge.java", "snippet": "public static volatile int windowWidth, windowHeight;" }, { "identifier": "Tools", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Tools.java", "snippet"...
import static org.lwjgl.glfw.CallbackBridge.windowHeight; import static org.lwjgl.glfw.CallbackBridge.windowWidth; import android.os.Build; import android.os.FileObserver; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.Tools; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Objects;
12,665
package net.kdt.pojavlaunch.utils; public class MCOptionUtils { private static final HashMap<String,String> sParameterMap = new HashMap<>(); private static final ArrayList<WeakReference<MCOptionListener>> sOptionListeners = new ArrayList<>(); private static FileObserver sFileObserver; private static String sOptionFolderPath = null; public interface MCOptionListener { /** Called when an option is changed. Don't know which one though */ void onOptionChanged(); } public static void load(){ load(sOptionFolderPath == null ? Tools.DIR_GAME_NEW : sOptionFolderPath); } public static void load(@NonNull String folderPath) { File optionFile = new File(folderPath + "/options.txt"); if(!optionFile.exists()) { try { // Needed for new instances I guess :think: optionFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if(sFileObserver == null || !Objects.equals(sOptionFolderPath, folderPath)){ sOptionFolderPath = folderPath; setupFileObserver(); } sOptionFolderPath = folderPath; // Yeah I know, it may be redundant sParameterMap.clear(); try { BufferedReader reader = new BufferedReader(new FileReader(optionFile)); String line; while ((line = reader.readLine()) != null) { int firstColonIndex = line.indexOf(':'); if(firstColonIndex < 0) { Log.w(Tools.APP_NAME, "No colon on line \""+line+"\", skipping"); continue; } sParameterMap.put(line.substring(0,firstColonIndex), line.substring(firstColonIndex+1)); } reader.close(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not load options.txt", e); } } public static void set(String key, String value) { sParameterMap.put(key,value); } /** Set an array of String, instead of a simple value. Not supported on all options */ public static void set(String key, List<String> values){ sParameterMap.put(key, values.toString()); } public static String get(String key){ return sParameterMap.get(key); } /** @return A list of values from an array stored as a string */ public static List<String> getAsList(String key){ String value = get(key); // Fallback if the value doesn't exist if (value == null) return new ArrayList<>(); // Remove the edges value = value.replace("[", "").replace("]", ""); if (value.isEmpty()) return new ArrayList<>(); return Arrays.asList(value.split(",")); } public static void save() { StringBuilder result = new StringBuilder(); for(String key : sParameterMap.keySet()) result.append(key) .append(':') .append(sParameterMap.get(key)) .append('\n'); try { sFileObserver.stopWatching(); Tools.write(sOptionFolderPath + "/options.txt", result.toString()); sFileObserver.startWatching(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not save options.txt", e); } } /** @return The stored Minecraft GUI scale, also auto-computed if on auto-mode or improper setting */ public static int getMcScale() { String str = MCOptionUtils.get("guiScale"); int guiScale = (str == null ? 0 :Integer.parseInt(str));
package net.kdt.pojavlaunch.utils; public class MCOptionUtils { private static final HashMap<String,String> sParameterMap = new HashMap<>(); private static final ArrayList<WeakReference<MCOptionListener>> sOptionListeners = new ArrayList<>(); private static FileObserver sFileObserver; private static String sOptionFolderPath = null; public interface MCOptionListener { /** Called when an option is changed. Don't know which one though */ void onOptionChanged(); } public static void load(){ load(sOptionFolderPath == null ? Tools.DIR_GAME_NEW : sOptionFolderPath); } public static void load(@NonNull String folderPath) { File optionFile = new File(folderPath + "/options.txt"); if(!optionFile.exists()) { try { // Needed for new instances I guess :think: optionFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if(sFileObserver == null || !Objects.equals(sOptionFolderPath, folderPath)){ sOptionFolderPath = folderPath; setupFileObserver(); } sOptionFolderPath = folderPath; // Yeah I know, it may be redundant sParameterMap.clear(); try { BufferedReader reader = new BufferedReader(new FileReader(optionFile)); String line; while ((line = reader.readLine()) != null) { int firstColonIndex = line.indexOf(':'); if(firstColonIndex < 0) { Log.w(Tools.APP_NAME, "No colon on line \""+line+"\", skipping"); continue; } sParameterMap.put(line.substring(0,firstColonIndex), line.substring(firstColonIndex+1)); } reader.close(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not load options.txt", e); } } public static void set(String key, String value) { sParameterMap.put(key,value); } /** Set an array of String, instead of a simple value. Not supported on all options */ public static void set(String key, List<String> values){ sParameterMap.put(key, values.toString()); } public static String get(String key){ return sParameterMap.get(key); } /** @return A list of values from an array stored as a string */ public static List<String> getAsList(String key){ String value = get(key); // Fallback if the value doesn't exist if (value == null) return new ArrayList<>(); // Remove the edges value = value.replace("[", "").replace("]", ""); if (value.isEmpty()) return new ArrayList<>(); return Arrays.asList(value.split(",")); } public static void save() { StringBuilder result = new StringBuilder(); for(String key : sParameterMap.keySet()) result.append(key) .append(':') .append(sParameterMap.get(key)) .append('\n'); try { sFileObserver.stopWatching(); Tools.write(sOptionFolderPath + "/options.txt", result.toString()); sFileObserver.startWatching(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not save options.txt", e); } } /** @return The stored Minecraft GUI scale, also auto-computed if on auto-mode or improper setting */ public static int getMcScale() { String str = MCOptionUtils.get("guiScale"); int guiScale = (str == null ? 0 :Integer.parseInt(str));
int scale = Math.max(Math.min(windowWidth / 320, windowHeight / 240), 1);
0
2023-12-01 16:16:12+00:00
16k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/world/ServerLevelWrapper.java
[ { "identifier": "McObjectConverter", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/McObjectConverter.java", "snippet": "public class McObjectConverter\n{\n\tprivate static int bufferIndex(int x, int y)\n\t{\n\t\treturn y * 4 + x;\n\t}\n\t/** Taken from Minecraft's com.mojang.m...
import java.io.File; import java.util.concurrent.ConcurrentHashMap; import com.seibel.distanthorizons.api.enums.worldGeneration.EDhApiLevelType; import com.seibel.distanthorizons.common.wrappers.McObjectConverter; import com.seibel.distanthorizons.common.wrappers.block.BiomeWrapper; import com.seibel.distanthorizons.common.wrappers.block.BlockStateWrapper; import com.seibel.distanthorizons.common.wrappers.block.cache.ServerBlockDetailMap; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.minecraft.MinecraftClientWrapper; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.pos.DhBlockPos; import com.seibel.distanthorizons.core.pos.DhChunkPos; import com.seibel.distanthorizons.core.wrapperInterfaces.block.IBlockStateWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IBiomeWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IServerLevelWrapper; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.ChunkStatus; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable;
13,265
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level; ServerBlockDetailMap blockMap = new ServerBlockDetailMap(this); //==============// // constructors // //==============// public static ServerLevelWrapper getWrapper(ServerLevel level) { return LEVEL_WRAPPER_BY_SERVER_LEVEL.computeIfAbsent(level, ServerLevelWrapper::new); } public ServerLevelWrapper(ServerLevel level) { this.level = level; } //=========// // methods // //=========// @Nullable @Override public IClientLevelWrapper tryGetClientLevelWrapper() { MinecraftClientWrapper client = MinecraftClientWrapper.INSTANCE; if (client.mc.level == null) { return null; } return ClientLevelWrapper.getWrapper(client.mc.level); } @Override public File getSaveFolder() { return level.getChunkSource().getDataStorage().dataFolder; } @Override public DimensionTypeWrapper getDimensionType() { return DimensionTypeWrapper.getDimensionTypeWrapper(level.dimensionType()); } @Override public EDhApiLevelType getLevelType() { return EDhApiLevelType.SERVER_LEVEL; } public ServerLevel getLevel() { return level; } @Override public boolean hasCeiling() { return level.dimensionType().hasCeiling(); } @Override public boolean hasSkyLight() { return level.dimensionType().hasSkyLight(); } @Override public int getHeight() { return level.getHeight(); } @Override public int getMinHeight() { #if PRE_MC_1_17_1 return 0; #else return level.getMinBuildHeight(); #endif } @Override public IChunkWrapper tryGetChunk(DhChunkPos pos) { if (!level.hasChunk(pos.x, pos.z)) return null; ChunkAccess chunk = level.getChunk(pos.x, pos.z, ChunkStatus.FULL, false); if (chunk == null) return null; return new ChunkWrapper(chunk, level, this); } @Override public boolean hasChunkLoaded(int chunkX, int chunkZ) { // world.hasChunk(chunkX, chunkZ); THIS DOES NOT WORK FOR CLIENT LEVEL CAUSE MOJANG ALWAYS RETURN TRUE FOR THAT! ChunkSource source = level.getChunkSource(); return source.hasChunk(chunkX, chunkZ); } @Override public IBlockStateWrapper getBlockState(DhBlockPos pos) { return BlockStateWrapper.fromBlockState(level.getBlockState(McObjectConverter.Convert(pos)), this); } @Override public IBiomeWrapper getBiome(DhBlockPos pos) {
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level; ServerBlockDetailMap blockMap = new ServerBlockDetailMap(this); //==============// // constructors // //==============// public static ServerLevelWrapper getWrapper(ServerLevel level) { return LEVEL_WRAPPER_BY_SERVER_LEVEL.computeIfAbsent(level, ServerLevelWrapper::new); } public ServerLevelWrapper(ServerLevel level) { this.level = level; } //=========// // methods // //=========// @Nullable @Override public IClientLevelWrapper tryGetClientLevelWrapper() { MinecraftClientWrapper client = MinecraftClientWrapper.INSTANCE; if (client.mc.level == null) { return null; } return ClientLevelWrapper.getWrapper(client.mc.level); } @Override public File getSaveFolder() { return level.getChunkSource().getDataStorage().dataFolder; } @Override public DimensionTypeWrapper getDimensionType() { return DimensionTypeWrapper.getDimensionTypeWrapper(level.dimensionType()); } @Override public EDhApiLevelType getLevelType() { return EDhApiLevelType.SERVER_LEVEL; } public ServerLevel getLevel() { return level; } @Override public boolean hasCeiling() { return level.dimensionType().hasCeiling(); } @Override public boolean hasSkyLight() { return level.dimensionType().hasSkyLight(); } @Override public int getHeight() { return level.getHeight(); } @Override public int getMinHeight() { #if PRE_MC_1_17_1 return 0; #else return level.getMinBuildHeight(); #endif } @Override public IChunkWrapper tryGetChunk(DhChunkPos pos) { if (!level.hasChunk(pos.x, pos.z)) return null; ChunkAccess chunk = level.getChunk(pos.x, pos.z, ChunkStatus.FULL, false); if (chunk == null) return null; return new ChunkWrapper(chunk, level, this); } @Override public boolean hasChunkLoaded(int chunkX, int chunkZ) { // world.hasChunk(chunkX, chunkZ); THIS DOES NOT WORK FOR CLIENT LEVEL CAUSE MOJANG ALWAYS RETURN TRUE FOR THAT! ChunkSource source = level.getChunkSource(); return source.hasChunk(chunkX, chunkZ); } @Override public IBlockStateWrapper getBlockState(DhBlockPos pos) { return BlockStateWrapper.fromBlockState(level.getBlockState(McObjectConverter.Convert(pos)), this); } @Override public IBiomeWrapper getBiome(DhBlockPos pos) {
return BiomeWrapper.getBiomeWrapper(level.getBiome(McObjectConverter.Convert(pos)), this);
1
2023-12-04 11:41:46+00:00
16k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static f...
import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.generation.util.RandomGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.Util; import uk.gov.hmcts.juror.support.sql.dto.JurorAccountDetailsDto; import uk.gov.hmcts.juror.support.sql.entity.CourtLocation; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorPool; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.entity.PoolRequestGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponseGenerator; import uk.gov.hmcts.juror.support.sql.generators.DigitalResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorPoolGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PaperResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PoolRequestGeneratorUtil; import uk.gov.hmcts.juror.support.sql.repository.CourtLocationRepository; import uk.gov.hmcts.juror.support.sql.repository.DigitalResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorPoolRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorRepository; import uk.gov.hmcts.juror.support.sql.repository.PaperResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.PoolRequestRepository; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors;
12,663
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository;
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository;
private static final List<CourtLocation> courtLocations;
3
2023-12-01 11:38:42+00:00
16k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/RequestManager.java
[ { "identifier": "Request", "path": "src/main/java/net/superricky/tpaplusplus/util/Request.java", "snippet": "public class Request {\n private final ServerPlayer sender;\n private final ServerPlayer receiver;\n private final boolean hereRequest;\n private boolean accepted;\n private double...
import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.superricky.tpaplusplus.util.Request; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.util.configuration.formatters.MessageParser; import net.superricky.tpaplusplus.util.limitations.LimitationManager; import net.superricky.tpaplusplus.util.manager.saved.PlayerData; import net.superricky.tpaplusplus.util.manager.saved.SaveDataManager; import javax.annotation.Nullable; import java.util.*;
13,856
package net.superricky.tpaplusplus.util.manager; public class RequestManager { static final Set<Request> requestSet = new HashSet<>(); private RequestManager() { } public static boolean isPlayerIdentical(ServerPlayer player1, ServerPlayer player2) { return player1.getUUID().equals(player2.getUUID()); } public static void clearRequestSet() { requestSet.clear(); } public static boolean alreadySentTeleportRequest(Request request) { for (Request currentRequest : requestSet) { if (isPlayerIdentical(request.getSender(), currentRequest.getSender()) && isPlayerIdentical(request.getReceiver(), currentRequest.getReceiver())) { return true; } } return false; } // Deny command is run by the receiver, hence why it's in the receiver's point of view. private static void denyFunctionality(Request request, ServerPlayer receiver) { if (Objects.isNull(request)) { receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_DENIES_TPA.get(), request.getSender().getName().getString()))); request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_DENIED_TPA.get(), request.getReceiver().getName().getString()))); requestSet.remove(request); } public static void denyTeleportRequest(ServerPlayer receiver) { Request request = RequestGrabUtil.getReceiverRequest(receiver); denyFunctionality(request, receiver); } // Deny command is run by the receiver, hence why it's in the receiver's point of view. public static void denyTeleportRequest(ServerPlayer receiver, ServerPlayer sender) { Request request = RequestGrabUtil.getReceiverRequest(receiver, sender); denyFunctionality(request, receiver); } // Cancel command is run by the sender, hence why it's in the sender's point of view. private static void cancelFunctionality(Request request, ServerPlayer sender) { if (Objects.isNull(request)) { sender.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_CANCELS_TPA.get(), request.getReceiver().getName().getString()))); request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_CANCELLED_TPA.get(), request.getSender().getName().getString()))); requestSet.remove(request); } public static void cancelTeleportRequest(ServerPlayer sender) { Request request = RequestGrabUtil.getSenderRequest(sender); cancelFunctionality(request, sender); } public static void cancelTeleportRequest(ServerPlayer sender, ServerPlayer receiver) { Request request = RequestGrabUtil.getSenderRequest(sender, receiver); cancelFunctionality(request, sender); } // Send command is run by the sender, hence why its in the sender's point of view public static void sendTeleportRequest(ServerPlayer sender, ServerPlayer receiver, boolean isHereRequest) { if (isPlayerIdentical(sender, receiver)) { sender.sendSystemMessage(Component.literal(Messages.ERR_NO_SELF_TELEPORT.get())); return; } if (PlayerBlockingManager.isPlayerBlocked(sender, receiver)) return; // Return if one of the players has blocked the other player. PlayerData receiverData = SaveDataManager.getPlayerData(receiver); if (Boolean.FALSE.equals(Objects.isNull(receiverData)) && receiverData.getTPToggle()) { // receiverData is not null && receiver TP toggle is enabled. sender.sendSystemMessage(Component.literal(MessageParser.enhancedFormatter(Messages.ERR_RECEIVER_TP_DISABLED.get(), Map.of("receiverName", receiver.getName().getString())))); return; } if (Boolean.FALSE.equals(Config.ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS.get())) { // Allow TPToggled players to send requests is disabled in the config PlayerData senderData = SaveDataManager.getPlayerData(sender); if (Boolean.FALSE.equals(Objects.isNull(senderData)) && senderData.getTPToggle()) { // senderData is not null && sender TP toggle is enabled. sender.sendSystemMessage(Component.literal(Messages.ERR_SENDER_TP_DISABLED.get())); return; } } // run the notify function and return if it false, to stop the player from sending the request.
package net.superricky.tpaplusplus.util.manager; public class RequestManager { static final Set<Request> requestSet = new HashSet<>(); private RequestManager() { } public static boolean isPlayerIdentical(ServerPlayer player1, ServerPlayer player2) { return player1.getUUID().equals(player2.getUUID()); } public static void clearRequestSet() { requestSet.clear(); } public static boolean alreadySentTeleportRequest(Request request) { for (Request currentRequest : requestSet) { if (isPlayerIdentical(request.getSender(), currentRequest.getSender()) && isPlayerIdentical(request.getReceiver(), currentRequest.getReceiver())) { return true; } } return false; } // Deny command is run by the receiver, hence why it's in the receiver's point of view. private static void denyFunctionality(Request request, ServerPlayer receiver) { if (Objects.isNull(request)) { receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_DENIES_TPA.get(), request.getSender().getName().getString()))); request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_DENIED_TPA.get(), request.getReceiver().getName().getString()))); requestSet.remove(request); } public static void denyTeleportRequest(ServerPlayer receiver) { Request request = RequestGrabUtil.getReceiverRequest(receiver); denyFunctionality(request, receiver); } // Deny command is run by the receiver, hence why it's in the receiver's point of view. public static void denyTeleportRequest(ServerPlayer receiver, ServerPlayer sender) { Request request = RequestGrabUtil.getReceiverRequest(receiver, sender); denyFunctionality(request, receiver); } // Cancel command is run by the sender, hence why it's in the sender's point of view. private static void cancelFunctionality(Request request, ServerPlayer sender) { if (Objects.isNull(request)) { sender.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_CANCELS_TPA.get(), request.getReceiver().getName().getString()))); request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_CANCELLED_TPA.get(), request.getSender().getName().getString()))); requestSet.remove(request); } public static void cancelTeleportRequest(ServerPlayer sender) { Request request = RequestGrabUtil.getSenderRequest(sender); cancelFunctionality(request, sender); } public static void cancelTeleportRequest(ServerPlayer sender, ServerPlayer receiver) { Request request = RequestGrabUtil.getSenderRequest(sender, receiver); cancelFunctionality(request, sender); } // Send command is run by the sender, hence why its in the sender's point of view public static void sendTeleportRequest(ServerPlayer sender, ServerPlayer receiver, boolean isHereRequest) { if (isPlayerIdentical(sender, receiver)) { sender.sendSystemMessage(Component.literal(Messages.ERR_NO_SELF_TELEPORT.get())); return; } if (PlayerBlockingManager.isPlayerBlocked(sender, receiver)) return; // Return if one of the players has blocked the other player. PlayerData receiverData = SaveDataManager.getPlayerData(receiver); if (Boolean.FALSE.equals(Objects.isNull(receiverData)) && receiverData.getTPToggle()) { // receiverData is not null && receiver TP toggle is enabled. sender.sendSystemMessage(Component.literal(MessageParser.enhancedFormatter(Messages.ERR_RECEIVER_TP_DISABLED.get(), Map.of("receiverName", receiver.getName().getString())))); return; } if (Boolean.FALSE.equals(Config.ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS.get())) { // Allow TPToggled players to send requests is disabled in the config PlayerData senderData = SaveDataManager.getPlayerData(sender); if (Boolean.FALSE.equals(Objects.isNull(senderData)) && senderData.getTPToggle()) { // senderData is not null && sender TP toggle is enabled. sender.sendSystemMessage(Component.literal(Messages.ERR_SENDER_TP_DISABLED.get())); return; } } // run the notify function and return if it false, to stop the player from sending the request.
if (!LimitationManager.notifyAndCheckAllowedToTeleport(sender, receiver, false)) return;
4
2023-12-02 05:41:24+00:00
16k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/ui/statistics/StatisticsActivity.java
[ { "identifier": "ActivityDiaryContract", "path": "app/src/main/java/de/rampro/activitydiary/db/ActivityDiaryContract.java", "snippet": "public class ActivityDiaryContract {\n\n /* no instance of this class is allowed */\n private ActivityDiaryContract() {\n }\n\n public static final String A...
import android.app.DatePickerDialog; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import androidx.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.formatter.IValueFormatter; import com.github.mikephil.charting.utils.ViewPortHandler; import org.osmdroid.config.Configuration; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import de.rampro.activitydiary.R; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.helpers.DateHelper; import de.rampro.activitydiary.helpers.TimeSpanFormatter; import de.rampro.activitydiary.ui.generic.BaseActivity; import de.rampro.activitydiary.ui.history.HistoryDetailActivity;
13,028
} data.moveToNext(); } if(acc_po > 2.0f) { entries.add(new PieEntry(acc, getResources().getString(R.string.statistics_others))); colors.add(Color.GRAY); } } PieDataSet set = new PieDataSet(entries, getResources().getString(R.string.activities)); PieData dat = new PieData(set); set.setColors(colors); set.setValueFormatter(new IValueFormatter() { @Override public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { PieEntry e = (PieEntry)entry; return TimeSpanFormatter.format((long)e.getValue()); } }); chart.setData(dat); chart.setUsePercentValues(true); chart.setRotationAngle(180.0f); chart.invalidate(); // refresh } // Called when a previously created loader is reset, making the data unavailable public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. } @Override public void onResume() { mNavigationView.getMenu().findItem(R.id.nav_statistics).setChecked(true); super.onResume(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { currentDateTime = new Date().getTime(); Bundle bnd = new Bundle(); switch (position) { case 0: // all break; case 1: // last 7 days bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7)); bnd.putLong("end", currentDateTime); break; case 2: // last 30 days bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7 * 30)); bnd.putLong("end", currentDateTime); break; case 3: // Day currentOffset = 0; currentRange = Calendar.DAY_OF_YEAR; loadRange(currentRange, currentOffset); break; case 4: // week currentOffset = 0; currentRange = Calendar.WEEK_OF_YEAR; loadRange(currentRange, currentOffset); break; case 5: // month currentOffset = 0; currentRange = Calendar.MONTH; loadRange(currentRange, currentOffset); break; case 6: // year currentOffset = 0; currentRange = Calendar.YEAR; loadRange(currentRange, currentOffset); break; default: } if(position < 3){ rangeTextView.setVisibility(View.INVISIBLE); rangeEarlierImageView.setVisibility(View.INVISIBLE); rangeLaterImageView.setVisibility(View.INVISIBLE); }else{ rangeTextView.setVisibility(View.VISIBLE); rangeEarlierImageView.setVisibility(View.VISIBLE); rangeLaterImageView.setVisibility(View.VISIBLE); } if(position < 1) { getLoaderManager().restartLoader(LOADER_ID_TIME, bnd, this); }else if(position < 3){ getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this); } } /* field is the field of Calender, e.g. Calendar.WEEK_OF_YEAR */ private void loadRange(int field, int offset){ Bundle bnd = new Bundle(); Calendar calStart = DateHelper.startOf(field, currentDateTime); calStart.add(field, offset); Calendar calEnd = (Calendar) calStart.clone(); calEnd.add(field, 1); SimpleDateFormat sdf = DateHelper.dateFormat(field); String tt = sdf.format(calStart.getTime()); rangeTextView.setText(tt); bnd.putLong("start", calStart.getTimeInMillis()); bnd.putLong("end", calEnd.getTimeInMillis()); getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this); } @Override public void onNothingSelected(AdapterView<?> parent) { } public void showDatePickerDialog(View v) {
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.statistics; public class StatisticsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemSelectedListener { private static final int LOADER_ID_TIME = 0; private static final int LOADER_ID_RANGE = 1; private static final String[] PROJECTION = new String[] { ActivityDiaryContract.DiaryStats.NAME, ActivityDiaryContract.DiaryStats.COLOR, ActivityDiaryContract.DiaryStats.PORTION, ActivityDiaryContract.DiaryStats.DURATION }; private PieChart chart; private Spinner timeframeSpinner; private TextView rangeTextView; private ImageView rangeEarlierImageView; private ImageView rangeLaterImageView; private long currentDateTime; private int currentOffset = 0; private int currentRange = Calendar.WEEK_OF_YEAR; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context ctx = getApplicationContext(); Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View contentView = inflater.inflate(R.layout.activity_statistics, null, false); setContent(contentView); timeframeSpinner = (Spinner) findViewById(R.id.timeframeSpinner); timeframeSpinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.statistic_dropdown, android.R.layout.simple_spinner_item); timeframeSpinner.setAdapter(adapter); getLoaderManager().initLoader(LOADER_ID_TIME, null, this); chart = (PieChart) findViewById(R.id.piechart); chart.getLegend().setEnabled(false); chart.setDescription(null); chart.setHoleRadius(30.0f); chart.setTransparentCircleRadius(40.0f); rangeTextView = (TextView)findViewById(R.id.rangeTextView); rangeEarlierImageView = (ImageView)findViewById(R.id.img_earlier); rangeEarlierImageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentOffset = currentOffset - 1; loadRange(currentRange, currentOffset); } }); rangeLaterImageView = (ImageView) findViewById(R.id.img_later); rangeLaterImageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentOffset = currentOffset + 1; loadRange(currentRange, currentOffset); } }); currentDateTime = new Date().getTime(); mDrawerToggle.setDrawerIndicatorEnabled(false); } // Called when a new Loader needs to be created public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. if(id == LOADER_ID_TIME) { return new CursorLoader(this, ActivityDiaryContract.DiaryStats.CONTENT_URI, PROJECTION, null, null, ActivityDiaryContract.DiaryStats.SORT_ORDER_DEFAULT); }else if(id == LOADER_ID_RANGE) { long start = args.getLong("start"); long end = args.getLong("end"); Uri u = ActivityDiaryContract.DiaryStats.CONTENT_URI; u = Uri.withAppendedPath(u, Long.toString(start)); u = Uri.withAppendedPath(u, Long.toString(end)); return new CursorLoader(this, u, PROJECTION, null, null, ActivityDiaryContract.DiaryStats.PORTION + " DESC"); }else{ return null; } } // Called when a previously created loader has finished loading public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) List<PieEntry> entries = new ArrayList<>(); List<Integer> colors = new ArrayList<>(); int portion_idx = data.getColumnIndex(ActivityDiaryContract.DiaryStats.PORTION); int name_idx = data.getColumnIndex(ActivityDiaryContract.DiaryStats.NAME); int col_idx = data.getColumnIndex(ActivityDiaryContract.DiaryStats.COLOR); int dur_idx = data.getColumnIndex(ActivityDiaryContract.DiaryStats.DURATION); if ((data != null) && data.moveToFirst()) { float acc = 0.0f; float acc_po = 0.0f; while (!data.isAfterLast()) { float portion = data.getFloat(portion_idx); long duration = data.getLong(dur_idx); if(portion > 3.0f){ PieEntry ent = new PieEntry((float)duration, data.getString(name_idx)); entries.add(ent); colors.add(data.getInt(col_idx)); }else{ // accumulate the small, not shown entries acc += duration; acc_po += portion; } data.moveToNext(); } if(acc_po > 2.0f) { entries.add(new PieEntry(acc, getResources().getString(R.string.statistics_others))); colors.add(Color.GRAY); } } PieDataSet set = new PieDataSet(entries, getResources().getString(R.string.activities)); PieData dat = new PieData(set); set.setColors(colors); set.setValueFormatter(new IValueFormatter() { @Override public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { PieEntry e = (PieEntry)entry; return TimeSpanFormatter.format((long)e.getValue()); } }); chart.setData(dat); chart.setUsePercentValues(true); chart.setRotationAngle(180.0f); chart.invalidate(); // refresh } // Called when a previously created loader is reset, making the data unavailable public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. } @Override public void onResume() { mNavigationView.getMenu().findItem(R.id.nav_statistics).setChecked(true); super.onResume(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { currentDateTime = new Date().getTime(); Bundle bnd = new Bundle(); switch (position) { case 0: // all break; case 1: // last 7 days bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7)); bnd.putLong("end", currentDateTime); break; case 2: // last 30 days bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7 * 30)); bnd.putLong("end", currentDateTime); break; case 3: // Day currentOffset = 0; currentRange = Calendar.DAY_OF_YEAR; loadRange(currentRange, currentOffset); break; case 4: // week currentOffset = 0; currentRange = Calendar.WEEK_OF_YEAR; loadRange(currentRange, currentOffset); break; case 5: // month currentOffset = 0; currentRange = Calendar.MONTH; loadRange(currentRange, currentOffset); break; case 6: // year currentOffset = 0; currentRange = Calendar.YEAR; loadRange(currentRange, currentOffset); break; default: } if(position < 3){ rangeTextView.setVisibility(View.INVISIBLE); rangeEarlierImageView.setVisibility(View.INVISIBLE); rangeLaterImageView.setVisibility(View.INVISIBLE); }else{ rangeTextView.setVisibility(View.VISIBLE); rangeEarlierImageView.setVisibility(View.VISIBLE); rangeLaterImageView.setVisibility(View.VISIBLE); } if(position < 1) { getLoaderManager().restartLoader(LOADER_ID_TIME, bnd, this); }else if(position < 3){ getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this); } } /* field is the field of Calender, e.g. Calendar.WEEK_OF_YEAR */ private void loadRange(int field, int offset){ Bundle bnd = new Bundle(); Calendar calStart = DateHelper.startOf(field, currentDateTime); calStart.add(field, offset); Calendar calEnd = (Calendar) calStart.clone(); calEnd.add(field, 1); SimpleDateFormat sdf = DateHelper.dateFormat(field); String tt = sdf.format(calStart.getTime()); rangeTextView.setText(tt); bnd.putLong("start", calStart.getTimeInMillis()); bnd.putLong("end", calEnd.getTimeInMillis()); getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this); } @Override public void onNothingSelected(AdapterView<?> parent) { } public void showDatePickerDialog(View v) {
HistoryDetailActivity.DatePickerFragment newFragment = new HistoryDetailActivity.DatePickerFragment();
4
2023-12-02 12:36:40+00:00
16k
Ethylene9160/Chess
src/chess/panels/WebPanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender;
11,138
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread;
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread;
private OpponentEmoThread opponentEmoThread;
6
2023-12-01 02:33:32+00:00
16k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
10,959
words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> {
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>(); private AnswerItemProvider answerItemProvider; private String deviceId; private String local_name; private boolean isLocal; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> {
WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords());
7
2023-12-03 13:36:00+00:00
16k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
13,173
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine();
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine();
private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) {
11
2023-11-27 18:25:00+00:00
16k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/VoxEditClient.java
[ { "identifier": "Presets", "path": "src/main/java/me/andre111/voxedit/Presets.java", "snippet": "public class Presets {\n\tpublic static final ToolItem.Data andre111;\n\tpublic static final ItemStack andre111Stack;\n\tstatic {\n\t\tandre111 = new ToolItem.Data(Util.make(new ArrayList<>(), list -> {\n\t\...
import org.lwjgl.glfw.GLFW; import org.spongepowered.include.com.google.common.base.Objects; import me.andre111.voxedit.Presets; import me.andre111.voxedit.VoxEdit; import me.andre111.voxedit.client.gui.screen.ToolSelectionScreen; import me.andre111.voxedit.client.network.ClientNetworking; import me.andre111.voxedit.client.renderer.EditorRenderer; import me.andre111.voxedit.client.renderer.HudRenderer; import me.andre111.voxedit.client.renderer.SelectionRenderer; import me.andre111.voxedit.client.renderer.ToolRenderer; import me.andre111.voxedit.item.ToolItem; import me.andre111.voxedit.item.VoxEditItem; import me.andre111.voxedit.network.Command; import me.andre111.voxedit.tool.ConfiguredTool; import me.andre111.voxedit.tool.Tool; import me.andre111.voxedit.tool.config.ToolConfig; import me.andre111.voxedit.tool.data.Selection; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult;
12,061
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player; ToolItem.Data oldActive = ClientState.active; BlockHitResult oldTarget = ClientState.target; ClientState.active = null; ItemStack stack = ClientState.player.getMainHandStack(); if(stack.getItem() instanceof ToolItem toolItem) { ClientState.active = ToolItem.readToolData(stack); } if(ClientState.active != null) { if(oldActive == null || !ClientState.active.selected().equals(oldActive.selected())) { HudRenderer.getToolSettingsScreen().rebuild(); ClientState.positions = null; } if(MinecraftClient.getInstance().currentScreen != null) return; ClientState.target = Selection.getTargetOf(ClientState.player, ClientState.active.selected().config()); if(oldTarget == null || !Objects.equal(ClientState.target.getBlockPos(), oldTarget.getBlockPos()) || !Objects.equal(ClientState.target.getSide(), oldTarget.getSide())) { ClientState.positions = null; } if(INCREASE_RADIUS.wasPressed()) { ClientNetworking.setSelectedConfig(ClientState.active.selected().config().withRadius(Math.min(ClientState.active.selected().config().radius()+1, 16))); } if(DECREASE_RADIUS.wasPressed()) { ClientNetworking.setSelectedConfig(ClientState.active.selected().config().withRadius(Math.max(1, ClientState.active.selected().config().radius()-1))); } if(INCREASE_SPEED.wasPressed()) { ClientState.cameraSpeed = Math.min(ClientState.cameraSpeed+1, 10f); MinecraftClient.getInstance().getMessageHandler().onGameMessage(Text.translatable("voxedit.feedback.cameraSpeed", ClientState.cameraSpeed), true); } if(DECREASE_SPEED.wasPressed()) { ClientState.cameraSpeed = Math.max(1f, ClientState.cameraSpeed-1); MinecraftClient.getInstance().getMessageHandler().onGameMessage(Text.translatable("voxedit.feedback.cameraSpeed", ClientState.cameraSpeed), true); } if(OPEN_MENU.wasPressed()) {
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player; ToolItem.Data oldActive = ClientState.active; BlockHitResult oldTarget = ClientState.target; ClientState.active = null; ItemStack stack = ClientState.player.getMainHandStack(); if(stack.getItem() instanceof ToolItem toolItem) { ClientState.active = ToolItem.readToolData(stack); } if(ClientState.active != null) { if(oldActive == null || !ClientState.active.selected().equals(oldActive.selected())) { HudRenderer.getToolSettingsScreen().rebuild(); ClientState.positions = null; } if(MinecraftClient.getInstance().currentScreen != null) return; ClientState.target = Selection.getTargetOf(ClientState.player, ClientState.active.selected().config()); if(oldTarget == null || !Objects.equal(ClientState.target.getBlockPos(), oldTarget.getBlockPos()) || !Objects.equal(ClientState.target.getSide(), oldTarget.getSide())) { ClientState.positions = null; } if(INCREASE_RADIUS.wasPressed()) { ClientNetworking.setSelectedConfig(ClientState.active.selected().config().withRadius(Math.min(ClientState.active.selected().config().radius()+1, 16))); } if(DECREASE_RADIUS.wasPressed()) { ClientNetworking.setSelectedConfig(ClientState.active.selected().config().withRadius(Math.max(1, ClientState.active.selected().config().radius()-1))); } if(INCREASE_SPEED.wasPressed()) { ClientState.cameraSpeed = Math.min(ClientState.cameraSpeed+1, 10f); MinecraftClient.getInstance().getMessageHandler().onGameMessage(Text.translatable("voxedit.feedback.cameraSpeed", ClientState.cameraSpeed), true); } if(DECREASE_SPEED.wasPressed()) { ClientState.cameraSpeed = Math.max(1f, ClientState.cameraSpeed-1); MinecraftClient.getInstance().getMessageHandler().onGameMessage(Text.translatable("voxedit.feedback.cameraSpeed", ClientState.cameraSpeed), true); } if(OPEN_MENU.wasPressed()) {
if(Screen.hasControlDown()) MinecraftClient.getInstance().setScreen(new ToolSelectionScreen(ClientState.active));
2
2023-12-01 15:12:26+00:00
16k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/core/GTTweaker.java
[ { "identifier": "IMaterial", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterial.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterial\")\npublic interface IMaterial {\n\tOreDictMaterial getMaterial();\n\n\t@ZenOperator(OperatorType.MUL)\n\tIMaterialStack multiply(long...
import cpw.mods.fml.common.event.FMLInitializationEvent; import gregapi.recipes.Recipe; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.item.IIngredient; import minetweaker.util.IEventHandler; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipe; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeFactory; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeMap; import mods.bio.gttweaker.core.command.GTCommand; import mods.bio.gttweaker.core.json.OreDictMaterial_Serializable; import mods.bio.gttweaker.mods.gregtech.oredict.*; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipe; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipeMaps; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTMaterialBracketHandler; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTPrefixBracketHandler; import mods.bio.gttweaker.mods.gregtech.recipe.bracket.CTRecipeMapBracketHandler; import mods.bio.gttweaker.mods.minetweaker.CTIItemStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTILiquidStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTIOreDictExpansion; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import java.util.Objects;
11,410
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class); MineTweakerAPI.registerClass(IMaterialStack.class); MineTweakerAPI.registerClass(IPrefix.class); MineTweakerAPI.registerClass(IMaterialData.class); MineTweakerAPI.registerClass(CTRecipeMaps.class); MineTweakerAPI.registerClass(CTUnifier.class); MineTweakerAPI.registerClass(CTIOreDictExpansion.class); MineTweakerAPI.registerClass(CTIItemStackExpansion.class); MineTweakerAPI.registerClass(CTILiquidStackExpansion.class); MineTweakerAPI.registerBracketHandler(new CTRecipeMapBracketHandler());
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class); MineTweakerAPI.registerClass(IMaterialStack.class); MineTweakerAPI.registerClass(IPrefix.class); MineTweakerAPI.registerClass(IMaterialData.class); MineTweakerAPI.registerClass(CTRecipeMaps.class); MineTweakerAPI.registerClass(CTUnifier.class); MineTweakerAPI.registerClass(CTIOreDictExpansion.class); MineTweakerAPI.registerClass(CTIItemStackExpansion.class); MineTweakerAPI.registerClass(CTILiquidStackExpansion.class); MineTweakerAPI.registerBracketHandler(new CTRecipeMapBracketHandler());
MineTweakerAPI.registerBracketHandler(new CTPrefixBracketHandler());
12
2023-12-03 11:55:49+00:00
16k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/group/discussion/GroupDiscussionManager.java
[ { "identifier": "StatusFailException", "path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusFailException.java", "snippet": "public class StatusFailException extends Exception{\n public StatusFailException() {\n }\n\n public StatusFailException(String message) {\n super...
import org.springframework.util.StringUtils; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.dao.discussion.DiscussionEntityService; import top.hcode.hoj.dao.group.GroupEntityService; import top.hcode.hoj.dao.problem.ProblemEntityService; import top.hcode.hoj.dao.user.UserAcproblemEntityService; import top.hcode.hoj.pojo.entity.discussion.Discussion; import top.hcode.hoj.pojo.entity.group.Group; import top.hcode.hoj.pojo.entity.problem.Problem; import top.hcode.hoj.pojo.entity.user.UserAcproblem; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import top.hcode.hoj.validator.GroupValidator; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
12,036
package top.hcode.hoj.manager.group.discussion; /** * @Author: LengYun * @Date: 2022/3/11 13:36 * @Description: */ @Component public class GroupDiscussionManager { @Autowired private GroupEntityService groupEntityService; @Autowired private DiscussionEntityService discussionEntityService; @Autowired private GroupValidator groupValidator; @Autowired private ProblemEntityService problemEntityService; @Autowired private UserAcproblemEntityService userAcproblemEntityService; @Autowired private RedisUtils redisUtils; public IPage<Discussion> getDiscussionList(Integer limit, Integer currentPage, Long gid, String pid) throws StatusNotFoundException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!groupValidator.isGroupMember(userRolesVo.getUid(), gid) && !isRoot) { throw new StatusForbiddenException("对不起,您无权限操作!"); } QueryWrapper<Discussion> discussionQueryWrapper = new QueryWrapper<>(); if (!StringUtils.isEmpty(pid)) { discussionQueryWrapper.eq("pid", pid); } IPage<Discussion> iPage = new Page<>(currentPage, limit); discussionQueryWrapper .eq("status", 0) .eq("gid", gid) .orderByDesc("top_priority") .orderByDesc("gmt_create") .orderByDesc("like_num") .orderByDesc("view_num"); return discussionEntityService.page(iPage, discussionQueryWrapper); } public IPage<Discussion> getAdminDiscussionList(Integer limit, Integer currentPage, Long gid) throws StatusNotFoundException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!isRoot && !groupValidator.isGroupAdmin(userRolesVo.getUid(), gid)) { throw new StatusForbiddenException("对不起,您无权限操作!"); } QueryWrapper<Discussion> discussionQueryWrapper = new QueryWrapper<>(); IPage<Discussion> iPage = new Page<>(currentPage, limit); discussionQueryWrapper .eq("gid", gid) .orderByDesc("top_priority") .orderByDesc("gmt_create") .orderByDesc("like_num") .orderByDesc("view_num"); return discussionEntityService.page(iPage, discussionQueryWrapper); } public void addDiscussion(Discussion discussion) throws StatusForbiddenException, StatusNotFoundException, StatusFailException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); boolean isProblemAdmin = SecurityUtils.getSubject().hasRole("problem_admin"); boolean isAdmin = SecurityUtils.getSubject().hasRole("admin"); Long gid = discussion.getGid(); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!isRoot && !groupValidator.isGroupMember(userRolesVo.getUid(), gid)) { throw new StatusForbiddenException("对不起,您无权限操作!"); } String problemId = discussion.getPid(); if (problemId != null) {
package top.hcode.hoj.manager.group.discussion; /** * @Author: LengYun * @Date: 2022/3/11 13:36 * @Description: */ @Component public class GroupDiscussionManager { @Autowired private GroupEntityService groupEntityService; @Autowired private DiscussionEntityService discussionEntityService; @Autowired private GroupValidator groupValidator; @Autowired private ProblemEntityService problemEntityService; @Autowired private UserAcproblemEntityService userAcproblemEntityService; @Autowired private RedisUtils redisUtils; public IPage<Discussion> getDiscussionList(Integer limit, Integer currentPage, Long gid, String pid) throws StatusNotFoundException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!groupValidator.isGroupMember(userRolesVo.getUid(), gid) && !isRoot) { throw new StatusForbiddenException("对不起,您无权限操作!"); } QueryWrapper<Discussion> discussionQueryWrapper = new QueryWrapper<>(); if (!StringUtils.isEmpty(pid)) { discussionQueryWrapper.eq("pid", pid); } IPage<Discussion> iPage = new Page<>(currentPage, limit); discussionQueryWrapper .eq("status", 0) .eq("gid", gid) .orderByDesc("top_priority") .orderByDesc("gmt_create") .orderByDesc("like_num") .orderByDesc("view_num"); return discussionEntityService.page(iPage, discussionQueryWrapper); } public IPage<Discussion> getAdminDiscussionList(Integer limit, Integer currentPage, Long gid) throws StatusNotFoundException, StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!isRoot && !groupValidator.isGroupAdmin(userRolesVo.getUid(), gid)) { throw new StatusForbiddenException("对不起,您无权限操作!"); } QueryWrapper<Discussion> discussionQueryWrapper = new QueryWrapper<>(); IPage<Discussion> iPage = new Page<>(currentPage, limit); discussionQueryWrapper .eq("gid", gid) .orderByDesc("top_priority") .orderByDesc("gmt_create") .orderByDesc("like_num") .orderByDesc("view_num"); return discussionEntityService.page(iPage, discussionQueryWrapper); } public void addDiscussion(Discussion discussion) throws StatusForbiddenException, StatusNotFoundException, StatusFailException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); boolean isRoot = SecurityUtils.getSubject().hasRole("root"); boolean isProblemAdmin = SecurityUtils.getSubject().hasRole("problem_admin"); boolean isAdmin = SecurityUtils.getSubject().hasRole("admin"); Long gid = discussion.getGid(); Group group = groupEntityService.getById(gid); if (group == null || group.getStatus() == 1 && !isRoot) { throw new StatusNotFoundException("该团队不存在或已被封禁!"); } if (!isRoot && !groupValidator.isGroupMember(userRolesVo.getUid(), gid)) { throw new StatusForbiddenException("对不起,您无权限操作!"); } String problemId = discussion.getPid(); if (problemId != null) {
QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>();
9
2023-12-03 14:15:51+00:00
16k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/KitchenController.java
[ { "identifier": "App", "path": "src/main/java/nz/ac/auckland/se206/App.java", "snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController...
import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import nz.ac.auckland.se206.App; import nz.ac.auckland.se206.GameState; import nz.ac.auckland.se206.SceneManager.AppUi; import nz.ac.auckland.se206.TextToSpeechManager;
11,082
package nz.ac.auckland.se206.controllers; /** Controller class for the room view. */ public class KitchenController { public static KitchenController instance; @FXML private AnchorPane contentPane; @FXML private ImageView floor; @FXML private ImageView character; @FXML private ImageView running; @FXML private ImageView doorGlow; @FXML private ImageView toasterGlow; @FXML private ImageView fridgeClosedGlow; @FXML private ImageView fridgeOpenGlow; @FXML private ImageView fridgeClosed; @FXML private ImageView fridgeOpen; @FXML private HBox dialogueHorizontalBox; @FXML private VBox bottomVerticalBox; @FXML private VBox hintVerticalBox; @FXML private Pane inventoryPane; @FXML private Circle doorMarker; @FXML private Circle toasterMarker; @FXML private Circle fridgeMarker; @FXML private AnchorPane room; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Button muteButton; /** Initializes the room view, it is called when the room loads. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // get door marker position int doorMarkerX = (int) doorMarker.getLayoutX(); int doorMarkerY = (int) doorMarker.getLayoutY(); // move character to door marker position GameState.goToInstant(doorMarkerX, doorMarkerY, character, running); room.setOpacity(0); instance = this; } /** * Handles the key pressed event. * * @param event the key event */ @FXML public void onKeyPressed(KeyEvent event) { System.out.println("key " + event.getCode() + " pressed"); } /** * Handles the key released event. * * @param event the key event */ @FXML public void onKeyReleased(KeyEvent event) { System.out.println("key " + event.getCode() + " released"); } /** * 'Consumes' the mouse event, preventing it from being registered. * * @param event the mouse event */ @FXML public void consumeMouseEvent(MouseEvent event) { System.out.println("mouse event consumed"); System.out.println(event.getSource()); event.consume(); } /** * Handles the mouse click event on the room, moving the character to the clicked location. * * @param event the mouse event */ @FXML public void onMoveCharacter(MouseEvent event) { // create click indicator GameState.onCharacterMovementClick(event, room); // get mouse position double mouseX = event.getX(); double mouseY = event.getY(); // move character to mouse position GameState.goTo(mouseX, mouseY, character, running); GameState.startMoving(); } /** * Handles the click event on the door. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onDoorClicked(MouseEvent event) throws IOException { // move character to door marker position GameState.goTo(doorMarker.getLayoutX(), doorMarker.getLayoutY(), character, running); // load the control room scene after movement animation is finished Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadControlRoom = () -> { try {
package nz.ac.auckland.se206.controllers; /** Controller class for the room view. */ public class KitchenController { public static KitchenController instance; @FXML private AnchorPane contentPane; @FXML private ImageView floor; @FXML private ImageView character; @FXML private ImageView running; @FXML private ImageView doorGlow; @FXML private ImageView toasterGlow; @FXML private ImageView fridgeClosedGlow; @FXML private ImageView fridgeOpenGlow; @FXML private ImageView fridgeClosed; @FXML private ImageView fridgeOpen; @FXML private HBox dialogueHorizontalBox; @FXML private VBox bottomVerticalBox; @FXML private VBox hintVerticalBox; @FXML private Pane inventoryPane; @FXML private Circle doorMarker; @FXML private Circle toasterMarker; @FXML private Circle fridgeMarker; @FXML private AnchorPane room; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Button muteButton; /** Initializes the room view, it is called when the room loads. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // get door marker position int doorMarkerX = (int) doorMarker.getLayoutX(); int doorMarkerY = (int) doorMarker.getLayoutY(); // move character to door marker position GameState.goToInstant(doorMarkerX, doorMarkerY, character, running); room.setOpacity(0); instance = this; } /** * Handles the key pressed event. * * @param event the key event */ @FXML public void onKeyPressed(KeyEvent event) { System.out.println("key " + event.getCode() + " pressed"); } /** * Handles the key released event. * * @param event the key event */ @FXML public void onKeyReleased(KeyEvent event) { System.out.println("key " + event.getCode() + " released"); } /** * 'Consumes' the mouse event, preventing it from being registered. * * @param event the mouse event */ @FXML public void consumeMouseEvent(MouseEvent event) { System.out.println("mouse event consumed"); System.out.println(event.getSource()); event.consume(); } /** * Handles the mouse click event on the room, moving the character to the clicked location. * * @param event the mouse event */ @FXML public void onMoveCharacter(MouseEvent event) { // create click indicator GameState.onCharacterMovementClick(event, room); // get mouse position double mouseX = event.getX(); double mouseY = event.getY(); // move character to mouse position GameState.goTo(mouseX, mouseY, character, running); GameState.startMoving(); } /** * Handles the click event on the door. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onDoorClicked(MouseEvent event) throws IOException { // move character to door marker position GameState.goTo(doorMarker.getLayoutX(), doorMarker.getLayoutY(), character, running); // load the control room scene after movement animation is finished Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadControlRoom = () -> { try {
App.setRoot(AppUi.CONTROL_ROOM);
0
2023-12-02 04:57:43+00:00
16k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
12,251
.ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam); int deviceSum = listDeviceStatsByShortLink.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情 List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>();
/* * 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 com.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam); if (CollUtil.isEmpty(listStatsByShortLink)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByShortLink = linkAccessLogsMapper.findPvUvUidStatsByShortLink(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByShortLink.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam); int deviceSum = listDeviceStatsByShortLink.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情 List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>();
List<LinkNetworkStatsDO> listNetworkStatsByShortLink = linkNetworkStatsMapper.listNetworkStatsByShortLink(requestParam);
4
2023-11-19 16:04:32+00:00
16k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/ResultParser.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.model.compute.aggregation.bucket.Bucket; import com.ly.ckibana.model.compute.aggregation.bucket.BucketStatics; import com.ly.ckibana.model.compute.aggregation.bucket.BucketsResult; import com.ly.ckibana.model.compute.aggregation.bucket.FilterInnerBucket; import com.ly.ckibana.model.compute.aggregation.bucket.MathBucket; import com.ly.ckibana.model.compute.aggregation.bucket.PercentilesBucket; import com.ly.ckibana.model.compute.aggregation.bucket.PercentilesRankBucket; import com.ly.ckibana.model.compute.aggregation.bucket.RangeBucket; import com.ly.ckibana.model.enums.AggCategory; import com.ly.ckibana.model.enums.AggType; import com.ly.ckibana.model.enums.SortType; import com.ly.ckibana.model.enums.TermsAggOrderType; import com.ly.ckibana.model.response.Response; import com.ly.ckibana.strategy.aggs.Aggregation; import com.ly.ckibana.strategy.aggs.TermsAggStrategy; import com.ly.ckibana.util.JSONUtils; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
11,386
} /** * 为TermAgg补充otherDocCount. * * @param aggregation agg * @param currentBuckets currentBuckets * @param buckets buckets * @return otherDocCount */ private long buildOtherDocCountForTermAgg(Aggregation aggregation, List<Bucket> currentBuckets, List<Bucket> buckets) { long otherDocCount = 0; if (AggType.TERMS.equals(aggregation.getAggType())) { long totalDocCount = currentBuckets.stream().mapToLong(Bucket::getDocCount).sum(); long showDocCount = buckets.stream().mapToLong(Bucket::getDocCount).sum(); otherDocCount = totalDocCount - showDocCount; } return otherDocCount; } /** * 从statics中获取当前agg对应的buckets,包括sub Buckets,peer Buckets. * * @param aggregation aggregation * @param bucketStatics 所有行数据,包含当前agg/subAgg,peerAgg数据 * @return buckets */ private List<Bucket> buildAggBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics) { String staticsId = aggregation.getStaticsId(); List<Bucket> result = new ArrayList<>(); //按照agg的bucketKey的值分类(如DateHistogramAggsStrategy的DateHistogramBucket的Key为时间)。需要LinkedHashMap保持先后顺序 Map<String, List<Map<String, BucketStatics>>> staticsByAggKeys = bucketStatics.stream().collect(Collectors.groupingBy(each -> each.get(staticsId).getBucketKey(), LinkedHashMap::new, Collectors.toList())); staticsByAggKeys.forEach((key, value) -> { //获取当前agg对应的基本bucket Bucket bucket = value.get(0).get(staticsId).getBucket(); //计算当前bucket对应的总docCount buildDocCount(aggregation, value, bucket); //内存计算。基于sub agg size计算sub buckets(如items top 10)的结果 buildSubAggsBuckets(aggregation, value, bucket); //针对第一层有兄弟节点 buildPeerAggsBuckets(aggregation, value, bucket); result.add(bucket); }); return result; } private void buildPeerAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { bucket.getComputeData().setPeerBucketMap(new HashMap<>()); aggregation.getPeerAggs().forEach(each -> { bucket.getComputeData().getPeerBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics)); }); } } private void buildSubAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { bucket.getComputeData().setSubBucketMap(new HashMap<>()); aggregation.getSubAggs().forEach(each -> bucket.getComputeData().getSubBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics))); } } /** * 计算当前聚合的totalDocCount. * * @param aggregation aggregation * @param bucketStatics bucketStatics * @param bucket bucket */ private void buildDocCount(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { long totalDocCount = 0; for (Map<String, BucketStatics> each : bucketStatics) { totalDocCount = totalDocCount + each.get(aggregation.getStaticsId()).getBucket().getDocCount(); } bucket.setDocCount(totalDocCount); } /** * 对bucket结果数据增加排序处理-基于内存排序实现. * TermsAgg按照avg,max,min,sum等sub agg进行排序,或子查询为 DateHistogramAgg需要内存处理排序 * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortBuckets(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result; result = sortTermsAggBySubAgg(aggregation, buckets); result = sortChildDateHistogramAgg(aggregation, result); return result; } /** * TermsAgg按照avg,max,min,sum等sub agg进行排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortTermsAggBySubAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets; if (null == aggregation.getSubAggs() || !AggType.TERMS.equals(aggregation.getAggType())) { return result; } TermsAggStrategy termsAgg = (TermsAggStrategy) aggregation; if (TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType())) { Aggregation subAgg = termsAgg.getSubAggs().get(termsAgg.getOrderBySubAggIndex()); if (!TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType()) || !AggCategory.MATH.equals(subAgg.getAggCategory())) { return result; } String orderValue = termsAgg.getOrder().split(" ")[1]; result = buckets.stream().sorted((o1, o2) -> { BucketsResult s1 = o1.getComputeData().getSubBucketMap().get(subAgg.getAggName()); BucketsResult s2 = o2.getComputeData().getSubBucketMap().get(subAgg.getAggName()); //math类bucket只有一个bucket MathBucket m1 = (MathBucket) s1.getBuckets().get(0); MathBucket m2 = (MathBucket) s2.getBuckets().get(0); int compareValue = (int) (m1.getValue() - m2.getValue());
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.parser; /** * 从ck中解析聚合结果,转换为kibana需要的格式返回. * * @author quzhihao */ @Service public class ResultParser extends HitsResultParser { public static final String BUCKET_FIELD_COMPUTE_DATA = "computeData"; /** * 执行聚合请求,将ck数据转换为kibana需要的格式数据. * * @param aggregation aggregation * @param aggCkResult aggCkResult * @return Response */ public Response execute(Aggregation aggregation, List<JSONObject> aggCkResult) { Response result = new Response(); List<Bucket> buckets = computeBuckets(aggregation, aggCkResult); result.setAggregations(computeAggsResult(aggregation, buckets)); result.getHits().setTotal(buckets.stream().mapToLong(Bucket::getDocCount).sum()); return result; } private Map<String, Map<String, Object>> computeAggsResult(Aggregation aggregation, List<Bucket> buckets) { Map<String, Map<String, Object>> peerAggResult = new HashMap<>(); parseDeepAggData(aggregation, buckets, peerAggResult); Map<String, Map<String, Object>> aggsResult = formatResult(aggregation, buckets, 0); aggsResult.putAll(peerAggResult); return aggsResult; } /** * 将ck结果,经过处理,得到对应的buckets. * 1.内存计算主agg doc_count * 2.内存计算subAgg size * 3.内存计算排序by subAgg */ public List<Bucket> computeBuckets(Aggregation aggregation, List<JSONObject> ckResult) { //statics:每一行ck结果解析到的对应各个agg的bucket结果List<Map<聚合staticsId,BucketStatics{Bucket.key(),Bucket}> List<Map<String, BucketStatics>> statics = buildCkRowAndAggBucketMappingList(aggregation, ckResult); // 解析得到当前agg对应的buckets,包括subBuckets和peerBuckets return buildBucketsResult(aggregation, statics).getBuckets(); } private List<Map<String, BucketStatics>> buildCkRowAndAggBucketMappingList(Aggregation aggregation, List<JSONObject> ckResult) { List<Map<String, BucketStatics>> result = new ArrayList<>(); for (int i = 0; i < ckResult.size(); i++) { JSONObject obj = ckResult.get(i); result.add(buildCkRowAndAggsMapping(aggregation, obj)); } return result; } /** * statics:约定统计数据存放规则(key:每个depth的每个agg,value=bucket,count). */ private Map<String, BucketStatics> buildCkRowAndAggsMapping(Aggregation aggregation, JSONObject ckResult) { Map<String, BucketStatics> result = new HashMap<>(); if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { aggregation.getSubAggs().forEach(each -> result.putAll(buildCkRowAndAggsMapping(each, ckResult))); } if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { aggregation.getPeerAggs().forEach(each -> result.putAll(buildCkRowAndAggsMapping(each, ckResult))); } result.put(aggregation.getStaticsId(), buildBucketStatics(aggregation, ckResult)); return result; } private BucketStatics buildBucketStatics(Aggregation aggregation, JSONObject ckResult) { Bucket bucket = aggregation.buildResultBucket(ckResult); return new BucketStatics(null == bucket.getKey() ? "unknownKey" : bucket.getKey().toString(), bucket); } private void parseDeepAggData(Aggregation aggregation, List<Bucket> buckets, Map<String, Map<String, Object>> peerAggDatas) { buckets.forEach(bucket -> { //注意目前仅第一层有peer agg if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { aggregation.getPeerAggs().forEach(each -> { BucketsResult bucketsResult = bucket.getComputeData().getPeerBucketMap().get(each.getAggName()); List<Bucket> tempBuckets = bucketsResult.getBuckets(); parseDeepAggData(each, tempBuckets, peerAggDatas); peerAggDatas.putAll(formatResult(each, tempBuckets, bucketsResult.getOtherDocCount())); }); } //任意层可能有child agg if (CollectionUtils.isNotEmpty(aggregation.getSubAggs())) { Map<String, Map<String, Object>> aggsData = new HashMap<>(); if (!aggregation.isIgnoreSubAggCondition()) { aggregation.getSubAggs().forEach(each -> { BucketsResult bucketsResult = bucket.getComputeData().getSubBucketMap().get(each.getAggName()); List<Bucket> tempBuckets = bucketsResult.getBuckets(); parseDeepAggData(each, tempBuckets, peerAggDatas); aggsData.putAll(formatResult(each, tempBuckets, bucketsResult.getOtherDocCount())); }); bucket.setComputeSubAggData(aggsData); } } }); } /** * 解析得到当前agg对应的buckets. * 1.内存计算后,内存处理排序和size截取 */ private BucketsResult buildBucketsResult(Aggregation aggsStrategy, List<Map<String, BucketStatics>> bucketStatics) { List<Bucket> currentBuckets = buildAggBuckets(aggsStrategy, bucketStatics); //内存处理排序和size截取 List<Bucket> sortedAndSizedBuckets = subSizeBuckets(aggsStrategy, sortBuckets(aggsStrategy, currentBuckets)); BucketsResult bucketsResult = new BucketsResult(sortedAndSizedBuckets); //构建返回结果:sum_other_doc_count,buckets bucketsResult.setOtherDocCount(buildOtherDocCountForTermAgg(aggsStrategy, currentBuckets, bucketsResult.getBuckets())); return bucketsResult; } /** * 内存截取size. * 由于需要整体内存计算后,才能得到排序后数据。因此需要内存处理size * * @param aggregation agg * @param currentBuckets currentBuckets * @return buckets */ private List<Bucket> subSizeBuckets(Aggregation aggregation, List<Bucket> currentBuckets) { List<Bucket> result = currentBuckets; if (aggregation.getSize() != null && aggregation.getSize() > 0) { result = currentBuckets.subList(0, Math.min(currentBuckets.size(), aggregation.getSize())); } return result; } /** * 为TermAgg补充otherDocCount. * * @param aggregation agg * @param currentBuckets currentBuckets * @param buckets buckets * @return otherDocCount */ private long buildOtherDocCountForTermAgg(Aggregation aggregation, List<Bucket> currentBuckets, List<Bucket> buckets) { long otherDocCount = 0; if (AggType.TERMS.equals(aggregation.getAggType())) { long totalDocCount = currentBuckets.stream().mapToLong(Bucket::getDocCount).sum(); long showDocCount = buckets.stream().mapToLong(Bucket::getDocCount).sum(); otherDocCount = totalDocCount - showDocCount; } return otherDocCount; } /** * 从statics中获取当前agg对应的buckets,包括sub Buckets,peer Buckets. * * @param aggregation aggregation * @param bucketStatics 所有行数据,包含当前agg/subAgg,peerAgg数据 * @return buckets */ private List<Bucket> buildAggBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics) { String staticsId = aggregation.getStaticsId(); List<Bucket> result = new ArrayList<>(); //按照agg的bucketKey的值分类(如DateHistogramAggsStrategy的DateHistogramBucket的Key为时间)。需要LinkedHashMap保持先后顺序 Map<String, List<Map<String, BucketStatics>>> staticsByAggKeys = bucketStatics.stream().collect(Collectors.groupingBy(each -> each.get(staticsId).getBucketKey(), LinkedHashMap::new, Collectors.toList())); staticsByAggKeys.forEach((key, value) -> { //获取当前agg对应的基本bucket Bucket bucket = value.get(0).get(staticsId).getBucket(); //计算当前bucket对应的总docCount buildDocCount(aggregation, value, bucket); //内存计算。基于sub agg size计算sub buckets(如items top 10)的结果 buildSubAggsBuckets(aggregation, value, bucket); //针对第一层有兄弟节点 buildPeerAggsBuckets(aggregation, value, bucket); result.add(bucket); }); return result; } private void buildPeerAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { bucket.getComputeData().setPeerBucketMap(new HashMap<>()); aggregation.getPeerAggs().forEach(each -> { bucket.getComputeData().getPeerBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics)); }); } } private void buildSubAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { bucket.getComputeData().setSubBucketMap(new HashMap<>()); aggregation.getSubAggs().forEach(each -> bucket.getComputeData().getSubBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics))); } } /** * 计算当前聚合的totalDocCount. * * @param aggregation aggregation * @param bucketStatics bucketStatics * @param bucket bucket */ private void buildDocCount(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { long totalDocCount = 0; for (Map<String, BucketStatics> each : bucketStatics) { totalDocCount = totalDocCount + each.get(aggregation.getStaticsId()).getBucket().getDocCount(); } bucket.setDocCount(totalDocCount); } /** * 对bucket结果数据增加排序处理-基于内存排序实现. * TermsAgg按照avg,max,min,sum等sub agg进行排序,或子查询为 DateHistogramAgg需要内存处理排序 * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortBuckets(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result; result = sortTermsAggBySubAgg(aggregation, buckets); result = sortChildDateHistogramAgg(aggregation, result); return result; } /** * TermsAgg按照avg,max,min,sum等sub agg进行排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortTermsAggBySubAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets; if (null == aggregation.getSubAggs() || !AggType.TERMS.equals(aggregation.getAggType())) { return result; } TermsAggStrategy termsAgg = (TermsAggStrategy) aggregation; if (TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType())) { Aggregation subAgg = termsAgg.getSubAggs().get(termsAgg.getOrderBySubAggIndex()); if (!TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType()) || !AggCategory.MATH.equals(subAgg.getAggCategory())) { return result; } String orderValue = termsAgg.getOrder().split(" ")[1]; result = buckets.stream().sorted((o1, o2) -> { BucketsResult s1 = o1.getComputeData().getSubBucketMap().get(subAgg.getAggName()); BucketsResult s2 = o2.getComputeData().getSubBucketMap().get(subAgg.getAggName()); //math类bucket只有一个bucket MathBucket m1 = (MathBucket) s1.getBuckets().get(0); MathBucket m2 = (MathBucket) s2.getBuckets().get(0); int compareValue = (int) (m1.getValue() - m2.getValue());
return orderValue.equalsIgnoreCase(SortType.ASC.name()) ? compareValue : (-compareValue);
11
2023-11-21 09:12:07+00:00
16k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/subpanels/ImagesSubPanel.java
[ { "identifier": "UndoManager", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/undo/UndoManager.java", "snippet": "public class UndoManager {\n public final static Array<Undoable> undoables = new Array<>();\n public static int undoIndex = -1;\n\n public static void add(Undoable undoable...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g2d.ParticleEmitter.SpriteMode; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.undo.undoables.ImagesAddUndoable; import com.ray3k.gdxparticleeditor.undo.undoables.ImagesMoveUndoable; import com.ray3k.gdxparticleeditor.undo.undoables.ImagesRemoveUndoable; import com.ray3k.gdxparticleeditor.undo.undoables.ImagesSpriteModeUndoable; import com.ray3k.gdxparticleeditor.widgets.Panel; import com.ray3k.stripe.DraggableTextList; import com.ray3k.stripe.DraggableTextList.DraggableTextListListener; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Listeners.*; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.draggableTextListNoBgStyle; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.tooltipBottomArrowStyle;
13,881
package com.ray3k.gdxparticleeditor.widgets.subpanels; /** * A widget that allows the user to add images to the particle emitter. Default image options are available. Also allows * the user to specify the sprite mode. */ public class ImagesSubPanel extends Panel { public static ImagesSubPanel imagesSubPanel; private DraggableTextList list; private Button removeButton; private Button moveUpButton; private Button moveDownButton; public ImagesSubPanel() { imagesSubPanel = this; var listWidth = 210; var listHeight = 100; for (int i = 0; i < selectedEmitter.getImagePaths().size; i++) { var path = selectedEmitter.getImagePaths().get(i); var sprite = selectedEmitter.getSprites().get(i); sprites.put(path, sprite); } setTouchable(Touchable.enabled); tabTable.left(); var label = new Label("Images", skin, "header"); tabTable.add(label); bodyTable.defaults().space(15); bodyTable.left(); var table = new Table(); bodyTable.add(table); //Add table.defaults().space(5).fillX(); var textButton = new TextButton("Add", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Add an image to be used as the texture for the particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, imagesRunnable); //Default table.row(); textButton = new TextButton("Default", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Set the image to the default round-faded image", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, () -> { var selectedFileHandles = new Array<FileHandle>(); selectedFileHandles.add(Gdx.files.internal("particle.png")); UndoManager.add(new ImagesAddUndoable(selectedEmitter, selectedFileHandles, "Add Default Image")); updateList(); updateDisabled(); }); //Default PMA table.row(); textButton = new TextButton("Default PMA", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Set the image to the default for premultiplied alpha", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, () -> { var selectedFileHandles = new Array<FileHandle>(); selectedFileHandles.add(Gdx.files.internal("pre_particle.png")); UndoManager.add(new ImagesAddUndoable(selectedEmitter, selectedFileHandles, "Add Default Image")); updateList(); updateDisabled(); }); table = new Table(); bodyTable.add(table); //Sprite Mode label = new Label("Sprite mode:", skin); table.add(label); var selectedSpriteMode = selectedEmitter.getSpriteMode(); table.row(); table.defaults().left(); var buttonGroup = new ButtonGroup<>(); var checkBoxSingle = new CheckBox("Single", skin, "radio"); checkBoxSingle.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.single) checkBoxSingle.setChecked(true); table.add(checkBoxSingle).spaceTop(5); buttonGroup.add(checkBoxSingle); addHandListener(checkBoxSingle); addTooltip(checkBoxSingle, "Only the selected image will be drawn", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxSingle, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.single, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); table.row(); var checkBoxRandom = new CheckBox("Random", skin, "radio"); checkBoxRandom.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.random) checkBoxRandom.setChecked(true); table.add(checkBoxRandom); buttonGroup.add(checkBoxRandom); addHandListener(checkBoxRandom); addTooltip(checkBoxRandom, "A randomly selected image will be chosen for each particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxRandom, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.random, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); table.row(); var checkBoxAnimated = new CheckBox("Animated", skin, "radio"); checkBoxAnimated.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.animated) checkBoxAnimated.setChecked(true); table.add(checkBoxAnimated); buttonGroup.add(checkBoxAnimated); addHandListener(checkBoxAnimated); addTooltip(checkBoxAnimated, "All images will be displayed in sequence over the life of each particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxAnimated, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.animated, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); //draggable text list list = new DraggableTextList(true, draggableTextListNoBgStyle); list.setProgrammaticChangeEvents(false); list.setTextAlignment(Align.left); list.align(Align.top); addHandListener(list); list.addListener(new DraggableTextListListener() { @Override public void removed(String path, int index) { list.setAllowRemoval(list.getTexts().size > 1); removeButton.setDisabled(!list.isAllowRemoval());
package com.ray3k.gdxparticleeditor.widgets.subpanels; /** * A widget that allows the user to add images to the particle emitter. Default image options are available. Also allows * the user to specify the sprite mode. */ public class ImagesSubPanel extends Panel { public static ImagesSubPanel imagesSubPanel; private DraggableTextList list; private Button removeButton; private Button moveUpButton; private Button moveDownButton; public ImagesSubPanel() { imagesSubPanel = this; var listWidth = 210; var listHeight = 100; for (int i = 0; i < selectedEmitter.getImagePaths().size; i++) { var path = selectedEmitter.getImagePaths().get(i); var sprite = selectedEmitter.getSprites().get(i); sprites.put(path, sprite); } setTouchable(Touchable.enabled); tabTable.left(); var label = new Label("Images", skin, "header"); tabTable.add(label); bodyTable.defaults().space(15); bodyTable.left(); var table = new Table(); bodyTable.add(table); //Add table.defaults().space(5).fillX(); var textButton = new TextButton("Add", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Add an image to be used as the texture for the particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, imagesRunnable); //Default table.row(); textButton = new TextButton("Default", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Set the image to the default round-faded image", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, () -> { var selectedFileHandles = new Array<FileHandle>(); selectedFileHandles.add(Gdx.files.internal("particle.png")); UndoManager.add(new ImagesAddUndoable(selectedEmitter, selectedFileHandles, "Add Default Image")); updateList(); updateDisabled(); }); //Default PMA table.row(); textButton = new TextButton("Default PMA", skin, "small"); table.add(textButton); addHandListener(textButton); addTooltip(textButton, "Set the image to the default for premultiplied alpha", Align.top, Align.top, tooltipBottomArrowStyle); onChange(textButton, () -> { var selectedFileHandles = new Array<FileHandle>(); selectedFileHandles.add(Gdx.files.internal("pre_particle.png")); UndoManager.add(new ImagesAddUndoable(selectedEmitter, selectedFileHandles, "Add Default Image")); updateList(); updateDisabled(); }); table = new Table(); bodyTable.add(table); //Sprite Mode label = new Label("Sprite mode:", skin); table.add(label); var selectedSpriteMode = selectedEmitter.getSpriteMode(); table.row(); table.defaults().left(); var buttonGroup = new ButtonGroup<>(); var checkBoxSingle = new CheckBox("Single", skin, "radio"); checkBoxSingle.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.single) checkBoxSingle.setChecked(true); table.add(checkBoxSingle).spaceTop(5); buttonGroup.add(checkBoxSingle); addHandListener(checkBoxSingle); addTooltip(checkBoxSingle, "Only the selected image will be drawn", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxSingle, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.single, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); table.row(); var checkBoxRandom = new CheckBox("Random", skin, "radio"); checkBoxRandom.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.random) checkBoxRandom.setChecked(true); table.add(checkBoxRandom); buttonGroup.add(checkBoxRandom); addHandListener(checkBoxRandom); addTooltip(checkBoxRandom, "A randomly selected image will be chosen for each particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxRandom, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.random, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); table.row(); var checkBoxAnimated = new CheckBox("Animated", skin, "radio"); checkBoxAnimated.setProgrammaticChangeEvents(false); if (selectedSpriteMode == SpriteMode.animated) checkBoxAnimated.setChecked(true); table.add(checkBoxAnimated); buttonGroup.add(checkBoxAnimated); addHandListener(checkBoxAnimated); addTooltip(checkBoxAnimated, "All images will be displayed in sequence over the life of each particle", Align.top, Align.top, tooltipBottomArrowStyle); onChange(checkBoxAnimated, () -> { UndoManager.add(new ImagesSpriteModeUndoable(selectedEmitter, SpriteMode.animated, selectedEmitter.getSpriteMode(), "change Image Sprite Mode")); particleEffect.reset(); }); //draggable text list list = new DraggableTextList(true, draggableTextListNoBgStyle); list.setProgrammaticChangeEvents(false); list.setTextAlignment(Align.left); list.align(Align.top); addHandListener(list); list.addListener(new DraggableTextListListener() { @Override public void removed(String path, int index) { list.setAllowRemoval(list.getTexts().size > 1); removeButton.setDisabled(!list.isAllowRemoval());
UndoManager.add(new ImagesRemoveUndoable(selectedEmitter, path, fileHandles.get(path), sprites.get(path), "Remove Image"));
3
2023-11-24 15:58:20+00:00
16k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/service_impl/SystemUsageRecordServiceImpl.java
[ { "identifier": "SystemUsageRecord", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/entity/SystemUsageRecord.java", "snippet": "@Data\n@TableName(\"tb_system_usage_record\")\npublic class SystemUsageRecord {\n\n @TableId(type = IdType.AUTO)\n private Integer id...
import com.siam.system.modular.package_goods.entity.SystemUsageRecord; import com.siam.system.modular.package_goods.mapper.SystemUsageRecordMapper; import com.siam.system.modular.package_goods.model.example.SystemUsageRecordExample; import com.siam.system.modular.package_goods.service.SystemUsageRecordService; import com.siam.system.modular.package_goods.mapper.SystemUsageRecordMapper; import com.siam.system.modular.package_goods.service.SystemUsageRecordService; import com.siam.system.modular.package_goods.entity.SystemUsageRecord; import com.siam.system.modular.package_goods.model.example.SystemUsageRecordExample; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List;
11,716
package com.siam.system.modular.package_goods.service_impl; @Slf4j @Service public class SystemUsageRecordServiceImpl implements SystemUsageRecordService { @Autowired
package com.siam.system.modular.package_goods.service_impl; @Slf4j @Service public class SystemUsageRecordServiceImpl implements SystemUsageRecordService { @Autowired
private SystemUsageRecordMapper systemUsageRecordMapper;
4
2023-11-26 12:41:06+00:00
16k
3dcitydb/citydb-tool
citydb-operation/src/main/java/org/citydb/operation/exporter/hierarchy/HierarchyBuilder.java
[ { "identifier": "Feature", "path": "citydb-model/src/main/java/org/citydb/model/feature/Feature.java", "snippet": "public class Feature extends ModelObject<Feature> implements Describable<FeatureDescriptor> {\n private final Name featureType;\n private Envelope envelope;\n private OffsetDateTim...
import org.citydb.operation.exporter.geometry.GeometryExporter; import org.citydb.operation.exporter.geometry.ImplicitGeometryExporter; import org.citydb.operation.exporter.property.PropertyExporter; import org.citydb.operation.exporter.property.PropertyStub; import org.citydb.operation.exporter.util.TableHelper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import org.citydb.model.feature.Feature; import org.citydb.model.property.Attribute; import org.citydb.model.property.Property; import org.citydb.model.property.PropertyDescriptor; import org.citydb.operation.exporter.ExportException; import org.citydb.operation.exporter.ExportHelper; import org.citydb.operation.exporter.address.AddressExporter; import org.citydb.operation.exporter.appearance.AppearanceExporter; import org.citydb.operation.exporter.feature.FeatureExporter;
11,316
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.operation.exporter.hierarchy; public class HierarchyBuilder { private final long rootId; private final ExportHelper helper; private final TableHelper tableHelper; private final PropertyBuilder propertyBuilder; private final Hierarchy hierarchy = new Hierarchy(); private final List<PropertyStub> propertyStubs = new ArrayList<>(); private HierarchyBuilder(long rootId, ExportHelper helper) { this.rootId = rootId; this.helper = helper; tableHelper = helper.getTableHelper(); propertyBuilder = new PropertyBuilder(helper); } public static HierarchyBuilder newInstance(long rootId, ExportHelper helper) { return new HierarchyBuilder(rootId, helper); } public HierarchyBuilder initialize(ResultSet rs) throws ExportException, SQLException { Set<Long> appearanceIds = new HashSet<>(); Set<Long> implicitGeometryIds = new HashSet<>(); while (rs.next()) { long nestedFeatureId = rs.getLong("val_feature_id"); if (!rs.wasNull() && hierarchy.getFeature(nestedFeatureId) == null) {
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.operation.exporter.hierarchy; public class HierarchyBuilder { private final long rootId; private final ExportHelper helper; private final TableHelper tableHelper; private final PropertyBuilder propertyBuilder; private final Hierarchy hierarchy = new Hierarchy(); private final List<PropertyStub> propertyStubs = new ArrayList<>(); private HierarchyBuilder(long rootId, ExportHelper helper) { this.rootId = rootId; this.helper = helper; tableHelper = helper.getTableHelper(); propertyBuilder = new PropertyBuilder(helper); } public static HierarchyBuilder newInstance(long rootId, ExportHelper helper) { return new HierarchyBuilder(rootId, helper); } public HierarchyBuilder initialize(ResultSet rs) throws ExportException, SQLException { Set<Long> appearanceIds = new HashSet<>(); Set<Long> implicitGeometryIds = new HashSet<>(); while (rs.next()) { long nestedFeatureId = rs.getLong("val_feature_id"); if (!rs.wasNull() && hierarchy.getFeature(nestedFeatureId) == null) {
hierarchy.addFeature(nestedFeatureId, tableHelper.getOrCreateExporter(FeatureExporter.class)
8
2023-11-19 12:29:54+00:00
16k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/craftbukkit/v1_12_R1/command/ProxiedNativeCommandSender.java
[ { "identifier": "Server", "path": "src/main/java/org/bukkit/Server.java", "snippet": "public interface Server extends PluginMessageRecipient {\n\n /**\n * Used for all administrative messages, such as an operator using a\n * command.\n * <p>\n * For use in {@link #broadcast(String, St...
import java.util.Set; import net.minecraft.command.ICommandSender; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.ProxiedCommandSender; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin;
14,152
package org.bukkit.craftbukkit.v1_12_R1.command; public class ProxiedNativeCommandSender implements ProxiedCommandSender { private final ICommandSender orig; private final CommandSender caller; private final CommandSender callee; public ProxiedNativeCommandSender(ICommandSender orig, CommandSender caller, CommandSender callee) { this.orig = orig; this.caller = caller; this.callee = callee; } public ICommandSender getHandle() { return orig; } @Override public CommandSender getCaller() { return caller; } @Override public CommandSender getCallee() { return callee; } @Override public void sendMessage(String message) { getCaller().sendMessage(message); } @Override public void sendMessage(String[] messages) { getCaller().sendMessage(messages); } @Override public Server getServer() { return getCallee().getServer(); } @Override public String getName() { return getCallee().getName(); } @Override public boolean isPermissionSet(String name) { return getCaller().isPermissionSet(name); } @Override public boolean isPermissionSet(Permission perm) { return getCaller().isPermissionSet(perm); } @Override public boolean hasPermission(String name) { return getCaller().hasPermission(name); } @Override public boolean hasPermission(Permission perm) { return getCaller().hasPermission(perm); } @Override
package org.bukkit.craftbukkit.v1_12_R1.command; public class ProxiedNativeCommandSender implements ProxiedCommandSender { private final ICommandSender orig; private final CommandSender caller; private final CommandSender callee; public ProxiedNativeCommandSender(ICommandSender orig, CommandSender caller, CommandSender callee) { this.orig = orig; this.caller = caller; this.callee = callee; } public ICommandSender getHandle() { return orig; } @Override public CommandSender getCaller() { return caller; } @Override public CommandSender getCallee() { return callee; } @Override public void sendMessage(String message) { getCaller().sendMessage(message); } @Override public void sendMessage(String[] messages) { getCaller().sendMessage(messages); } @Override public Server getServer() { return getCallee().getServer(); } @Override public String getName() { return getCallee().getName(); } @Override public boolean isPermissionSet(String name) { return getCaller().isPermissionSet(name); } @Override public boolean isPermissionSet(Permission perm) { return getCaller().isPermissionSet(perm); } @Override public boolean hasPermission(String name) { return getCaller().hasPermission(name); } @Override public boolean hasPermission(Permission perm) { return getCaller().hasPermission(perm); } @Override
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
6
2023-11-22 11:25:51+00:00
16k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/retrieval/KnowledgeRetrievalAssistant.java
[ { "identifier": "AssistantApi", "path": "src/main/java/com/logaritex/ai/api/AssistantApi.java", "snippet": "public class AssistantApi {\n\n\t/**\n\t * OpenAI assistant api beta marker.\n\t */\n\tpublic static final String OPEN_AI_BETA = \"OpenAI-Beta\";\n\n\t/**\n\t * OpenAI assistant api version.\n\t *...
import java.util.List; import java.util.Map; import com.logaritex.ai.api.AssistantApi; import com.logaritex.ai.api.Data; import com.logaritex.ai.api.Data.Message; import com.logaritex.ai.api.Data.Run; import com.logaritex.ai.api.FileApi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.DefaultResourceLoader;
13,768
/* * Copyright 2023-2023 the original author or authors. * * 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 com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY"));
/* * Copyright 2023-2023 the original author or authors. * * 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 com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY"));
AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY"));
0
2023-11-25 18:52:37+00:00
16k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityCompactCyclotron.java
[ { "identifier": "EPRecipeMaps", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/EPRecipeMaps.java", "snippet": "@ZenClass(\"mods.epimorphism.recipe.RecipeMaps\")\n@ZenRegister\npublic class EPRecipeMaps {\n\n // Singleblock Machine Recipemap\n @ZenProperty\n public static final Re...
import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import cn.gtcommunity.epimorphism.client.renderer.texture.EPTextures; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasingB; import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IEnergyContainer; import gregtech.api.metatileentity.IFastRenderMetaTileEntity; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.util.interpolate.Eases; import gregtech.client.renderer.ICubeRenderer; import gregtech.client.shader.postprocessing.BloomEffect; import gregtech.client.utils.BloomEffectUtil; import gregtech.client.utils.RenderBufferHelper; import gregtech.client.utils.RenderUtil; import gregtech.common.ConfigHolder; import gregtech.common.blocks.BlockGlassCasing; import gregtech.common.blocks.MetaBlocks; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects;
12,730
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCompactCyclotron extends RecipeMapMultiblockController implements IFastRenderMetaTileEntity { private Integer color; static BloomEffectUtil.IBloomRenderFast RENDER_HANDLER = new BloomEffectUtil.IBloomRenderFast() { float lastBrightnessX; float lastBrightnessY; public int customBloomStyle() { return ConfigHolder.client.shader.fusionBloom.useShader ? ConfigHolder.client.shader.fusionBloom.bloomStyle : -1; } @SideOnly(Side.CLIENT) public void preDraw(BufferBuilder buffer) { BloomEffect.strength = (float)ConfigHolder.client.shader.fusionBloom.strength; BloomEffect.baseBrightness = (float)ConfigHolder.client.shader.fusionBloom.baseBrightness; BloomEffect.highBrightnessThreshold = (float)ConfigHolder.client.shader.fusionBloom.highBrightnessThreshold; BloomEffect.lowBrightnessThreshold = (float)ConfigHolder.client.shader.fusionBloom.lowBrightnessThreshold; BloomEffect.step = 1.0F; this.lastBrightnessX = OpenGlHelper.lastBrightnessX; this.lastBrightnessY = OpenGlHelper.lastBrightnessY; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0F, 240.0F); GlStateManager.disableTexture2D(); } @SideOnly(Side.CLIENT) public void postDraw(BufferBuilder buffer) { GlStateManager.enableTexture2D(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, this.lastBrightnessX, this.lastBrightnessY); } }; public EPMetaTileEntityCompactCyclotron(ResourceLocation metaTileEntityId) {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCompactCyclotron extends RecipeMapMultiblockController implements IFastRenderMetaTileEntity { private Integer color; static BloomEffectUtil.IBloomRenderFast RENDER_HANDLER = new BloomEffectUtil.IBloomRenderFast() { float lastBrightnessX; float lastBrightnessY; public int customBloomStyle() { return ConfigHolder.client.shader.fusionBloom.useShader ? ConfigHolder.client.shader.fusionBloom.bloomStyle : -1; } @SideOnly(Side.CLIENT) public void preDraw(BufferBuilder buffer) { BloomEffect.strength = (float)ConfigHolder.client.shader.fusionBloom.strength; BloomEffect.baseBrightness = (float)ConfigHolder.client.shader.fusionBloom.baseBrightness; BloomEffect.highBrightnessThreshold = (float)ConfigHolder.client.shader.fusionBloom.highBrightnessThreshold; BloomEffect.lowBrightnessThreshold = (float)ConfigHolder.client.shader.fusionBloom.lowBrightnessThreshold; BloomEffect.step = 1.0F; this.lastBrightnessX = OpenGlHelper.lastBrightnessX; this.lastBrightnessY = OpenGlHelper.lastBrightnessY; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0F, 240.0F); GlStateManager.disableTexture2D(); } @SideOnly(Side.CLIENT) public void postDraw(BufferBuilder buffer) { GlStateManager.enableTexture2D(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, this.lastBrightnessX, this.lastBrightnessY); } }; public EPMetaTileEntityCompactCyclotron(ResourceLocation metaTileEntityId) {
super(metaTileEntityId, EPRecipeMaps.CYCLOTRON_RECIPES);
0
2023-11-26 01:56:35+00:00
16k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/Main.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONWriter; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.stage.StageStyle; import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.ui.controller.InspectController; import xyz.zcraft.zpixiv.ui.controller.MainController; import xyz.zcraft.zpixiv.util.CachedImage; import xyz.zcraft.zpixiv.util.Config; import xyz.zcraft.zpixiv.util.ResourceLoader; import xyz.zcraft.zpixiv.util.SSLUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.LinkedList; import java.util.Timer; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor;
11,326
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter
public static final LinkedList<CachedImage> loginBackground = new LinkedList<>();
3
2023-11-23 15:08:16+00:00
16k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/CommandHandler/CmdExecutorHandler.java
[ { "identifier": "ConfigSetup", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigSetup.java", "snippet": "public class ConfigSetup {\n\n private static File configFile;\n private static File sampleConfigFile;\n private static FileConfiguration configFileConfiguration;\n pri...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigSetup; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus.FoundShopsMenu; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.WarpUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.maxgamer.quickshop.api.shop.Shop; import java.util.List;
12,335
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) {
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) {
LoggerUtils.logInfo("This command can only be run from in game");
6
2023-11-22 11:36:01+00:00
16k
DIDA-lJ/qiyao-12306
services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/service/impl/OrderServiceImpl.java
[ { "identifier": "OrderCanalErrorCodeEnum", "path": "services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/common/enums/OrderCanalErrorCodeEnum.java", "snippet": "@AllArgsConstructor\npublic enum OrderCanalErrorCodeEnum implements IErrorCode {\n\n ORDER_CANAL_UNKNOWN_ERROR(\"B...
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.text.StrBuilder; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderCanalErrorCodeEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderItemStatusEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderStatusEnum; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemPassengerDO; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderItemMapper; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderMapper; import org.opengoofy.index12306.biz.orderservice.dto.domain.OrderStatusReversalDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.CancelTicketOrderReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderItemCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderSelfPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailSelfRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderPassengerDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.mq.event.DelayCloseOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.event.PayResultCallbackOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.produce.DelayCloseOrderSendProduce; import org.opengoofy.index12306.biz.orderservice.remote.UserRemoteService; import org.opengoofy.index12306.biz.orderservice.remote.dto.UserQueryActualRespDTO; import org.opengoofy.index12306.biz.orderservice.service.OrderItemService; import org.opengoofy.index12306.biz.orderservice.service.OrderPassengerRelationService; import org.opengoofy.index12306.biz.orderservice.service.OrderService; import org.opengoofy.index12306.biz.orderservice.service.orderid.OrderIdGeneratorManager; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ClientException; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.convention.page.PageResponse; import org.opengoofy.index12306.framework.starter.convention.result.Result; import org.opengoofy.index12306.framework.starter.database.toolkit.PageUtil; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Objects;
11,563
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper); TicketOrderDetailRespDTO result = BeanUtil.convert(orderDO, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, orderSn); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper); result.setPassengerDetails(BeanUtil.convert(orderItemDOList, TicketOrderPassengerDetailRespDTO.class)); return result; } @Override public PageResponse<TicketOrderDetailRespDTO> pageTicketOrder(TicketOrderPageQueryReqDTO requestParam) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getUserId, requestParam.getUserId()) .in(OrderDO::getStatus, buildOrderStatusList(requestParam)) .orderByDesc(OrderDO::getOrderTime); IPage<OrderDO> orderPage = orderMapper.selectPage(PageUtil.convert(requestParam), queryWrapper); return PageUtil.convert(orderPage, each -> { TicketOrderDetailRespDTO result = BeanUtil.convert(each, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, each.getOrderSn()); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper); result.setPassengerDetails(BeanUtil.convert(orderItemDOList, TicketOrderPassengerDetailRespDTO.class)); return result; }); } @Transactional(rollbackFor = Exception.class) @Override public String createTicketOrder(TicketOrderCreateReqDTO requestParam) { // 通过基因法将用户 ID 融入到订单号 String orderSn = OrderIdGeneratorManager.generateId(requestParam.getUserId()); OrderDO orderDO = OrderDO.builder().orderSn(orderSn) .orderTime(requestParam.getOrderTime()) .departure(requestParam.getDeparture()) .departureTime(requestParam.getDepartureTime()) .ridingDate(requestParam.getRidingDate()) .arrivalTime(requestParam.getArrivalTime()) .trainNumber(requestParam.getTrainNumber()) .arrival(requestParam.getArrival()) .trainId(requestParam.getTrainId()) .source(requestParam.getSource()) .status(OrderStatusEnum.PENDING_PAYMENT.getStatus()) .username(requestParam.getUsername()) .userId(String.valueOf(requestParam.getUserId())) .build(); orderMapper.insert(orderDO); List<TicketOrderItemCreateReqDTO> ticketOrderItems = requestParam.getTicketOrderItems(); List<OrderItemDO> orderItemDOList = new ArrayList<>();
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper); TicketOrderDetailRespDTO result = BeanUtil.convert(orderDO, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, orderSn); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper); result.setPassengerDetails(BeanUtil.convert(orderItemDOList, TicketOrderPassengerDetailRespDTO.class)); return result; } @Override public PageResponse<TicketOrderDetailRespDTO> pageTicketOrder(TicketOrderPageQueryReqDTO requestParam) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getUserId, requestParam.getUserId()) .in(OrderDO::getStatus, buildOrderStatusList(requestParam)) .orderByDesc(OrderDO::getOrderTime); IPage<OrderDO> orderPage = orderMapper.selectPage(PageUtil.convert(requestParam), queryWrapper); return PageUtil.convert(orderPage, each -> { TicketOrderDetailRespDTO result = BeanUtil.convert(each, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, each.getOrderSn()); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper); result.setPassengerDetails(BeanUtil.convert(orderItemDOList, TicketOrderPassengerDetailRespDTO.class)); return result; }); } @Transactional(rollbackFor = Exception.class) @Override public String createTicketOrder(TicketOrderCreateReqDTO requestParam) { // 通过基因法将用户 ID 融入到订单号 String orderSn = OrderIdGeneratorManager.generateId(requestParam.getUserId()); OrderDO orderDO = OrderDO.builder().orderSn(orderSn) .orderTime(requestParam.getOrderTime()) .departure(requestParam.getDeparture()) .departureTime(requestParam.getDepartureTime()) .ridingDate(requestParam.getRidingDate()) .arrivalTime(requestParam.getArrivalTime()) .trainNumber(requestParam.getTrainNumber()) .arrival(requestParam.getArrival()) .trainId(requestParam.getTrainId()) .source(requestParam.getSource()) .status(OrderStatusEnum.PENDING_PAYMENT.getStatus()) .username(requestParam.getUsername()) .userId(String.valueOf(requestParam.getUserId())) .build(); orderMapper.insert(orderDO); List<TicketOrderItemCreateReqDTO> ticketOrderItems = requestParam.getTicketOrderItems(); List<OrderItemDO> orderItemDOList = new ArrayList<>();
List<OrderItemPassengerDO> orderPassengerRelationDOList = new ArrayList<>();
5
2023-11-23 07:59:11+00:00
16k
estkme-group/infineon-lpa-mirror
core/src/main/java/com/infineon/esim/lpa/core/worker/local/ListProfilesWorker.java
[ { "identifier": "ProfileInfo", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/ProfileInfo.java", "snippet": "public class ProfileInfo implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static class NotificationConfigurationInfo impl...
import java.util.List; import com.gsma.sgp.messages.rspdefinitions.ProfileInfo; import com.gsma.sgp.messages.rspdefinitions.ProfileInfoListResponse; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.es10.Es10Interface; import com.infineon.esim.util.Log; import java.util.ArrayList;
13,424
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.local; public class ListProfilesWorker { private static final String TAG = ListProfilesWorker.class.getName();
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.local; public class ListProfilesWorker { private static final String TAG = ListProfilesWorker.class.getName();
private final Es10Interface es10Interface;
3
2023-11-22 07:46:30+00:00
16k
phamdung2209/FAP
src/main/java/com/func/GradeHandler/Add.java
[ { "identifier": "Course", "path": "src/main/java/com/course/Course.java", "snippet": "public class Course {\n private String id;\n private String courseName;\n private String description;\n private long cost;\n private Student student;\n private Lecturer lecturer;\n private List<Sch...
import java.util.Scanner; import com.course.Course; import com.func.Grade; import com.persons.Administrator; import com.persons.Lecturer; import com.persons.Student;
13,072
package com.func.GradeHandler; public class Add { public Scanner scanner = new Scanner(System.in); public void addGrade(Administrator admin) { System.out.println("Enter grade's information:"); System.out.print("Student ID: "); String sid = scanner.next(); scanner.nextLine(); System.out.print("Lecturer ID: "); String lid = scanner.next(); scanner.nextLine(); System.out.print("Course ID: "); String cid = scanner.next(); scanner.nextLine(); System.out.print("Grade: "); int grade = scanner.nextInt(); if (!admin.checkStudent(sid)) { System.out.println("Student does not exist."); } else if (!admin.checkLecture(lid)) { System.out.println("Lecturer does not exist."); } else if (!admin.checkCourse(cid)) { System.out.println("Course does not exist."); } else { Student student = admin.getStudentById(sid);
package com.func.GradeHandler; public class Add { public Scanner scanner = new Scanner(System.in); public void addGrade(Administrator admin) { System.out.println("Enter grade's information:"); System.out.print("Student ID: "); String sid = scanner.next(); scanner.nextLine(); System.out.print("Lecturer ID: "); String lid = scanner.next(); scanner.nextLine(); System.out.print("Course ID: "); String cid = scanner.next(); scanner.nextLine(); System.out.print("Grade: "); int grade = scanner.nextInt(); if (!admin.checkStudent(sid)) { System.out.println("Student does not exist."); } else if (!admin.checkLecture(lid)) { System.out.println("Lecturer does not exist."); } else if (!admin.checkCourse(cid)) { System.out.println("Course does not exist."); } else { Student student = admin.getStudentById(sid);
Lecturer lecturer = admin.getLectureById(lid);
3
2023-11-23 18:42:19+00:00
16k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/RevokeCertEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.security.SignatureCheck; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.database.objects.ACMEAccount; import de.morihofi.acmeserver.database.objects.ACMEIdentifier; import de.morihofi.acmeserver.exception.exceptions.*; import de.morihofi.acmeserver.tools.crypto.Crypto; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.math.BigInteger; import java.security.PublicKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.Date;
14,025
package de.morihofi.acmeserver.certificate.acme.api.endpoints; public class RevokeCertEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); /** * Constructs a new RevokeCertEndpoint instance. * This constructor initializes the endpoint with a specific Provisioner instance. * It sets up the necessary components for handling certificate revocation requests, * including creating a new Gson instance for JSON processing. * * @param provisioner The {@link Provisioner} instance used for managing certificate operations. */ @SuppressFBWarnings("EI_EXPOSE_REP2") public RevokeCertEndpoint(Provisioner provisioner) { super(provisioner); } @Override
package de.morihofi.acmeserver.certificate.acme.api.endpoints; public class RevokeCertEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); /** * Constructs a new RevokeCertEndpoint instance. * This constructor initializes the endpoint with a specific Provisioner instance. * It sets up the necessary components for handling certificate revocation requests, * including creating a new Gson instance for JSON processing. * * @param provisioner The {@link Provisioner} instance used for managing certificate operations. */ @SuppressFBWarnings("EI_EXPOSE_REP2") public RevokeCertEndpoint(Provisioner provisioner) { super(provisioner); } @Override
public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception {
3
2023-11-22 15:54:36+00:00
16k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/JsonDataGenerator.java
[ { "identifier": "JSONConfigReader", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/JSONConfigReader.java", "snippet": "public class JSONConfigReader {\n private static final Logger log = LogManager.getLogger(JSONConfigReader.class);\n \n public static String getJsonC...
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.pulsar.client.api.PulsarClientException; import org.eclipse.paho.client.mqttv3.MqttException; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import net.acesinc.data.json.generator.config.JSONConfigReader; import net.acesinc.data.json.generator.config.SimulationConfig; import net.acesinc.data.json.generator.log.AzureIoTHubLogger; import net.acesinc.data.json.generator.log.EventLogger; import net.acesinc.data.json.generator.log.FileLogger; import net.acesinc.data.json.generator.log.HttpPostLogger; import net.acesinc.data.json.generator.log.KafkaLogger; import net.acesinc.data.json.generator.log.KinesisLogger; import net.acesinc.data.json.generator.log.Log4JLogger; import net.acesinc.data.json.generator.log.MqttLogger; import net.acesinc.data.json.generator.log.NatsLogger; import net.acesinc.data.json.generator.log.PulsarLogger; import net.acesinc.data.json.generator.log.TranquilityLogger; import net.acesinc.data.json.generator.log.WampLogger;
11,220
break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try { loggers.add(new PulsarLogger(elProps)); } catch (final PulsarClientException ex) { log.error("Pulsar Logger unable to initialize", ex); } break; } case "wamp": { log.info("Adding Wamp Logger with properties: " + elProps); try { loggers.add(new WampLogger(queue, elProps)); } catch (final Exception ex) { log.error("Wamp Logger unable to initialize", ex); } break; } } } if (loggers.isEmpty()) { throw new IllegalArgumentException("You must configure at least one Producer in the Simulation Config"); } simRunner = new SimulationRunner(simConfig, loggers, getSimulationContentPath(), queue); } catch (IOException ex) { log.error("Error getting Simulation Config [ " + simConfigString + " ]", ex); } return this; } private FireGreetings r = new FireGreetings(this); private Thread t; @MessageMapping("/output") @SendTo("/topic/output") public String validate(String message) {// @Payload if (t != null && t.isAlive()) { t.interrupt(); // interupt vedere } t = new Thread(r); t.start(); return message; } @Autowired private SimpMessagingTemplate template; public void fireGreeting(String lastEvent) { System.out.println(); this.template.convertAndSend("/topic/output", lastEvent); } public void startRunning() { simRunner.startSimulation(); } public void stopRunning() { simRunner.stopSimulation(); } private SimulationConfig getSimConfig() throws IOException { File f = new File(getFilePath(simConfigFile));
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ @RestController public class JsonDataGenerator { @Autowired Environment environment; private static final Logger log = LogManager.getLogger(JsonDataGenerator.class); private SimulationRunner simRunner; private String simConfigFile; public JsonDataGenerator() { } public String getFilePath(String file) { String filePath = getSimulationContentPath() + "/" + file; return filePath; } public String getSimulationContentPath() { String folder = null; if (environment != null) environment.getProperty("myApp.folder", "conf"); else folder = System.getProperty("myApp.folder", "conf"); return folder; } public JsonDataGenerator setUpSimulation(String simConfigString) { simConfigFile = simConfigString; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); try { log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]"); SimulationConfig simConfig = getSimConfig(); List<EventLogger> loggers = new ArrayList<>(); for (Map<String, Object> elProps : simConfig.getProducers()) { String elType = (String) elProps.get("type"); switch (elType) { case "logger": { log.info("Adding Log4JLogger Producer"); loggers.add(new Log4JLogger()); break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try { loggers.add(new PulsarLogger(elProps)); } catch (final PulsarClientException ex) { log.error("Pulsar Logger unable to initialize", ex); } break; } case "wamp": { log.info("Adding Wamp Logger with properties: " + elProps); try { loggers.add(new WampLogger(queue, elProps)); } catch (final Exception ex) { log.error("Wamp Logger unable to initialize", ex); } break; } } } if (loggers.isEmpty()) { throw new IllegalArgumentException("You must configure at least one Producer in the Simulation Config"); } simRunner = new SimulationRunner(simConfig, loggers, getSimulationContentPath(), queue); } catch (IOException ex) { log.error("Error getting Simulation Config [ " + simConfigString + " ]", ex); } return this; } private FireGreetings r = new FireGreetings(this); private Thread t; @MessageMapping("/output") @SendTo("/topic/output") public String validate(String message) {// @Payload if (t != null && t.isAlive()) { t.interrupt(); // interupt vedere } t = new Thread(r); t.start(); return message; } @Autowired private SimpMessagingTemplate template; public void fireGreeting(String lastEvent) { System.out.println(); this.template.convertAndSend("/topic/output", lastEvent); } public void startRunning() { simRunner.startSimulation(); } public void stopRunning() { simRunner.stopSimulation(); } private SimulationConfig getSimConfig() throws IOException { File f = new File(getFilePath(simConfigFile));
return JSONConfigReader.readConfig(f, SimulationConfig.class);
0
2023-11-26 10:57:17+00:00
16k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERErebus.java
[ { "identifier": "JERRenderGlowWorm", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/render/entity/mods/erebus/JERRenderGlowWorm.java", "snippet": "public class JERRenderGlowWorm extends RenderGlowWorm {\n private static final ResourceLocation TEXTURE_ON = new ResourceLocation(\"...
import com.google.common.collect.Sets; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.erebus.JERRenderGlowWorm; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.erebus.JERRenderMagmaCrawler; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigErebus; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.plant.CustomPlantEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.integrations.jer.conditionals.JEMConditional; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.LogHelper; import com.invadermonky.justenoughmagiculture.util.ModIds; import com.invadermonky.justenoughmagiculture.util.StringHelper; import erebus.ModBiomes; import erebus.ModBlocks; import erebus.ModItems; import erebus.blocks.EnumWood; import erebus.entity.*; import erebus.items.ItemErebusFood.EnumFoodType; import erebus.items.ItemMaterials.EnumErebusMaterialsType; import erebus.world.biomes.BiomeBaseErebus; import erebus.world.biomes.decorators.BiomeDecoratorFungalForest; import erebus.world.feature.plant.WorldGenRottenTreeStump; import erebus.world.feature.structure.*; import erebus.world.feature.tree.WorldGenGiantEucalyptus; import erebus.world.loot.WeightedLootList; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; import jeresources.api.conditionals.Conditional; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.api.drop.PlantDrop; import net.minecraft.block.Block; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.biome.Biome; import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraft.world.storage.loot.functions.SetCount; import net.minecraft.world.storage.loot.functions.SetMetadata; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.client.registry.RenderingRegistry; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
13,913
EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), ModBlocks.DARK_FRUIT_VINE.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), 0, 1), new PlantDrop(EnumFoodType.DARK_FRUIT.createStack(), 0, 1) ); darkFruit.setSoil(Blocks.AIR.getDefaultState()); registerCustomPlant(darkFruit); } if(jerConfig.JER_PLANTS.enableHeartBerry) { CustomPlantEntry heartBerry = new CustomPlantEntry( new ItemStack(ModBlocks.HEART_BERRY_BUSH), ModBlocks.HEART_BERRY_BUSH.getDefaultState(), new PlantDrop(new ItemStack(ModItems.HEART_BERRIES), 1, 1) ); heartBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(heartBerry); } if(jerConfig.JER_PLANTS.enableJadeBerry) { CustomPlantEntry jadeBerry = new CustomPlantEntry( new ItemStack(ModBlocks.JADE_BERRY_BUSH), ModBlocks.JADE_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.JADE_BERRIES.createStack(), 1, 1) ); jadeBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(jadeBerry); } if(jerConfig.JER_PLANTS.enableMandrake) { registerPlant((Item & IPlantable) ModItems.MANDRAKE_ROOT, new PlantDrop(new ItemStack(ModItems.MANDRAKE_ROOT), 1, 3) ); } if(jerConfig.JER_PLANTS.enableSwampBerry) { CustomPlantEntry swampBerry = new CustomPlantEntry( new ItemStack(ModBlocks.SWAMP_BERRY_BUSH), ModBlocks.SWAMP_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumFoodType.SWAMP_BERRIES.createStack(), 1, 1) ); swampBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(swampBerry); } if(jerConfig.JER_PLANTS.enableTurnip) { registerPlant((Item & IPlantable) ModItems.TURNIP, new PlantDrop(new ItemStack(ModItems.TURNIP), 1, 3) ); } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityGlowWorm.class, JERRenderGlowWorm::new); RenderingRegistry.registerEntityRenderingHandler(EntityMagmaCrawler.class, JERRenderMagmaCrawler::new); } private void adjustBugRenderHookUp(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, 0.4, 0); return renderInfo; })); } private void adjustBugRenderHookDown(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, -0.4, 0); return renderInfo; })); } private String[] getSpawnBiomes(Class<? extends EntityLiving> entityClass) { THashSet<Biome> spawnBiomes = new THashSet<>(); mobSpawns.forEach((biome, mobList) -> { if(mobList.contains(entityClass)) spawnBiomes.add(biome); }); return !spawnBiomes.isEmpty() ? BiomeHelper.getBiomeNamesForBiomes(spawnBiomes.toArray(new Biome[0])) : new String[] {"Check Spawns"}; } private void registerErebusDungeon(String name, WeightedLootList lootList, int minRolls, int maxRolls) { JERDungeonStrings dungeon = new JERDungeonStrings(name, lootList, minRolls, maxRolls); registerDungeonLoot(dungeon.category, dungeon.unlocName, dungeon.lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public final LootTable lootTable; public JERDungeonStrings(String name, WeightedLootList lootList, int minRolls, int maxRolls) { this.category = String.format("%s:%s", ModIds.EREBUS.MOD_ID, name); this.unlocName = StringHelper.getDungeonTranslationKey(ModIds.EREBUS.MOD_ID, name); this.lootTable = getLootTable(lootList, minRolls, maxRolls); } private LootTable getLootTable(WeightedLootList lootList, int minRolls, int maxRolls) { List<LootEntry> lootEntries = new ArrayList<>(); lootList.forEach((lootItemStack -> { try { Item item = (Item) getFieldValue(lootItemStack, "item"); if(item != null) { List<LootFunction> lootFunctions = new ArrayList<>(); String name = item.getRegistryName().toString(); short minDamage = (short) getFieldValue(lootItemStack, "minDamage"); short maxDamage = (short) getFieldValue(lootItemStack, "maxDamage"); byte minAmount = (byte) getFieldValue(lootItemStack, "minAmount"); byte maxAmount = (byte) getFieldValue(lootItemStack, "maxAmount"); short weight = (short) getFieldValue(lootItemStack, "weight"); lootFunctions.add(new SetCount(new LootCondition[0], new RandomValueRange(minAmount, maxAmount))); if((minDamage > 0 && maxDamage > 0)) { lootFunctions.add(new SetMetadata(new LootCondition[0], new RandomValueRange(minDamage, maxDamage))); } lootEntries.add(new LootEntryItem(item, weight, 0, lootFunctions.toArray(new LootFunction[0]), new LootCondition[0], name)); } } catch (Exception e) {
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERErebus extends JERBase implements IJERIntegration { private static JERErebus instance; private final JEMConfigErebus.JER jerConfig = JEMConfig.EREBUS.JUST_ENOUGH_RESOURCES; private static THashMap<BiomeBaseErebus, THashSet<Class<? extends EntityLiving>>> mobSpawns; private JERErebus() {} public JERErebus(boolean enableJERDungeons, boolean enableJERMobs, boolean enableJERPlants) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); if(enableJERPlants) registerModPlants(); getInstance(); } public static JERErebus getInstance() { return instance != null ? instance : (instance = new JERErebus()); } @Override public void registerModDungeons() { registerErebusDungeon("antlion_dungeon", WorldGenAntlionDungeon.chestLoot, 3, 10); registerErebusDungeon("antlion_lair", WorldGenAntlionLair.chestLoot, 10, 14); registerErebusDungeon("dragonfly_dungeon", WorldGenDragonflyDungeon.CHEST_LOOT, 5, 15); registerErebusDungeon("dung_pile", WorldGenDungPile.CHEST_LOOT, 8, 14); registerErebusDungeon("giant_eucalyptus", WorldGenGiantEucalyptus.chestLoot, 3, 10); registerErebusDungeon("locust_shrine", WorldGenLocustShrine.CHEST_LOOT,2, 3); registerErebusDungeon("rotten_tree_stump", WorldGenRottenTreeStump.chestLoot, 3, 10); registerErebusDungeon("spider_dungeon", WorldGenSpiderDungeons.chestLoot, 3, 10); } @Override public void registerModEntities() { populateMobSpawns(); String[] allBiomes = BiomeHelper.getBiomeNamesForBiomes(mobSpawns.keySet().toArray(new Biome[0])); LootDrop exoPlateDrop = new LootDrop(EnumErebusMaterialsType.PLATE_EXO.createStack(), 0, 3, Conditional.affectedByLooting); if(jerConfig.JER_MOBS.enableAntlion) { registerMob(new EntityAntlion(world), LightLevel.hostile, getSpawnBiomes(EntityAntlion.class), exoPlateDrop); } if(jerConfig.JER_MOBS.enableAntlionGuardian) { registerMob(new EntityAntlionMiniBoss(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), exoPlateDrop); registerRenderHook(EntityAntlionMiniBoss.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableAntlionOverlord) { LootDrop[] drops = new LootDrop[] { new LootDrop(new ItemStack(ModBlocks.ANTLION_EGG)), new LootDrop(EnumErebusMaterialsType.SOUL_CRYSTAL.createStack()), new LootDrop(new ItemStack(ModItems.WAR_HAMMER)) }; registerMob(new EntityAntlionBoss(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), drops); registerRenderHook(EntityAntlionBoss.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableBedBug) { registerMob(new EntityBedBug(world), LightLevel.hostile, allBiomes, new LootDrop(new ItemStack(Blocks.WOOL, 1, 0))); registerRenderHook(EntityBedBug.class, ((renderInfo, e) -> { GlStateManager.translate(0,-0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableBeetle) { registerMob(new EntityBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityBeetle.class), exoPlateDrop); adjustBugRenderHookUp(EntityBeetle.class); } if(jerConfig.JER_MOBS.enableBeetleLarva) { List<LootDrop> larvaDrops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(new ItemStack(ModItems.EREBUS_FOOD, 1, 0), 1, 1, JEMConditional.isNotSquashed); foodDrop.smeltedItem = new ItemStack(ModItems.EREBUS_FOOD, 1, 1); larvaDrops.add(foodDrop); larvaDrops.add(new LootDrop(Items.SLIME_BALL, 1, 1, ((float)199/200), JEMConditional.isSquashed)); larvaDrops.add(new LootDrop(Items.DIAMOND, 0, 1, ((float)1/200), JEMConditional.isSquashed, Conditional.rareDrop)); registerMob(new EntityBeetleLarva(world), LightLevel.hostile, getSpawnBiomes(EntityBeetleLarva.class), larvaDrops); adjustBugRenderHookUp(EntityBeetleLarva.class); } if(jerConfig.JER_MOBS.enableBlackWidow) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.STRING, 0, 1, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 1, (float)1/3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack()) }; registerMob(new EntityBlackWidow(world), LightLevel.hostile, getSpawnBiomes(EntityBlackWidow.class), drops); } if(jerConfig.JER_MOBS.enableBogMaw) { registerMob(new EntityBogMaw(world), LightLevel.hostile, getSpawnBiomes(EntityBogMaw.class), new LootDrop(EnumErebusMaterialsType.BOGMAW_ROOT.createStack(), 0, 2, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableBombardierBeetle) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.GUNPOWDER, 1, 1), new LootDrop(Items.BLAZE_POWDER, 1, 1), exoPlateDrop }; registerMob(new EntityBombardierBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityBombardierBeetle.class), drops); } if(jerConfig.JER_MOBS.enableBombardierBeetleLarva) { List<LootDrop> larvaDrops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(new ItemStack(ModItems.EREBUS_FOOD, 1, 0), 1, 1, JEMConditional.isNotSquashed); foodDrop.smeltedItem = new ItemStack(ModItems.EREBUS_FOOD, 1, 1); larvaDrops.add(foodDrop); larvaDrops.add(new LootDrop(Items.SLIME_BALL, 1, 1, ((float)199/200), JEMConditional.isSquashed)); larvaDrops.add(new LootDrop(Items.DIAMOND, 0, 1, ((float)1/200), JEMConditional.isSquashed)); registerMob(new EntityBombardierBeetleLarva(world), LightLevel.hostile, getSpawnBiomes(EntityBombardierBeetleLarva.class), larvaDrops); } if(jerConfig.JER_MOBS.enableBotFly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 3, 0.25f, Conditional.affectedByLooting) }; registerMob(new EntityBotFly(world), LightLevel.hostile, getSpawnBiomes(EntityBotFly.class), drops); } if(jerConfig.JER_MOBS.enableCentipede) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.BIO_VELOCITY.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SUPERNATURAL_VELOCITY.createStack(), 0, 1, 0.02f, Conditional.rareDrop) }; registerMob(new EntityCentipede(world), LightLevel.hostile, getSpawnBiomes(EntityCentipede.class), drops); } if(jerConfig.JER_MOBS.enableChameleonTick) { registerMob(new EntityChameleonTick(world), LightLevel.hostile, getSpawnBiomes(EntityChameleonTick.class), new LootDrop(EnumErebusMaterialsType.CAMO_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableCicada) { registerMob(new EntityCicada(world), LightLevel.hostile, getSpawnBiomes(EntityCicada.class), new LootDrop(EnumErebusMaterialsType.REPELLENT.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableCropWeevil) { LootDrop[] drops = new LootDrop[]{ new LootDrop(new ItemStack(ModBlocks.GIANT_FLOWER_STIGMA), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.PUMPKIN_SEEDS), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.MELON_SEEDS), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.DYE, 1, 3), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(ModItems.TURNIP), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.NETHER_WART), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.WHEAT), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.REEDS), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(EnumWood.BAMBOO.getSapling()), 1, 1, 0.01425f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.CARROT), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.POTATO), 1, 1, 0.015f, Conditional.affectedByLooting) }; registerMob(new EntityCropWeevil(world), LightLevel.hostile, getSpawnBiomes(EntityCropWeevil.class), drops); registerRenderHook(EntityCropWeevil.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableCrushroom) { registerMob(new EntityCrushroom(world), LightLevel.hostile, getSpawnBiomes(EntityCrushroom.class), new LootDrop(EnumErebusMaterialsType.HIDE_SHROOM.createStack(), 0, 2, Conditional.affectedByLooting)); registerRenderHook(EntityCrushroom.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDragonfly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.DRAGONFLY_WING.createStack()), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 1, 0.20f, Conditional.affectedByLooting), new LootDrop(Items.ENDER_PEARL, 0, 1, 0.15f, Conditional.affectedByLooting) }; registerMob(new EntityDragonfly(world), LightLevel.hostile, getSpawnBiomes(EntityDragonfly.class), drops); registerRenderHook(EntityDragonfly.class, ((renderInfo, e) -> { GlStateManager.scale(1.5,1.5,1.5); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFireAnt) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.MAGMA_CREAM, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.FIRE_CHARGE, 0, 1, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityFireAnt(world), LightLevel.hostile, getSpawnBiomes(EntityFireAnt.class), drops); registerRenderHook(EntityFireAnt.class, ((renderInfo, e) -> { GlStateManager.scale(1.1,1.1,1.1); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFireAntSoldier) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.BLAZE_POWDER, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.BLAZE_ROD, 0, 1, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityFireAntSoldier(world), LightLevel.hostile, getSpawnBiomes(EntityFireAntSoldier.class), drops); } if(jerConfig.JER_MOBS.enableFly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 1, 0.10f), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 1, 0.05f, Conditional.rareDrop) }; registerMob(new EntityFly(world), LightLevel.hostile, getSpawnBiomes(EntityFly.class), drops); registerRenderHook(EntityFly.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFungalWeevil) { List<LootDrop> drops = new ArrayList<>(); drops.add(new LootDrop(new ItemStack(Blocks.BROWN_MUSHROOM), 0.1667f)); drops.add(new LootDrop(new ItemStack(Blocks.RED_MUSHROOM), 0.1667f)); float chance = (float) 2/3 * 1 / BiomeDecoratorFungalForest.MUSHROOMS.length; for(Block block : BiomeDecoratorFungalForest.MUSHROOMS) { drops.add(new LootDrop(new ItemStack(block), chance)); } registerMob(new EntityFungalWeevil(world), LightLevel.hostile, getSpawnBiomes(EntityFungalWeevil.class), drops); registerRenderHook(EntitySolifuge.class, ((renderInfo, e) -> { GlStateManager.scale(1.6,1.6,1.6); return renderInfo; })); } if(jerConfig.JER_MOBS.enableGlowWorm) { registerMob(new EntityGlowWorm(world), LightLevel.hostile, getSpawnBiomes(EntityGlowWorm.class), new LootDrop(EnumErebusMaterialsType.BIO_LUMINESCENCE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableGrasshopper) { LootDrop foodDrop = new LootDrop(EnumFoodType.GRASSHOPPER_LEG_RAW.createStack(), 0, 3, Conditional.affectedByLooting); foodDrop.smeltedItem = EnumFoodType.GRASSHOPPER_LEG_COOKED.createStack(); registerMob(new EntityGrasshopper(world), LightLevel.hostile, getSpawnBiomes(EntityGrasshopper.class), foodDrop); } if(jerConfig.JER_MOBS.enableHoneyPotAnt) { registerMob(new EntityHoneyPotAnt(world), LightLevel.hostile, getSpawnBiomes(EntityHoneyPotAnt.class), new LootDrop(EnumErebusMaterialsType.NECTAR.createStack(), 1, 8, 1f)); adjustBugRenderHookUp(EntityHoneyPotAnt.class); registerRenderHook(EntityHoneyPotAnt.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableJumpingSpider) { registerMob(new EntityJumpingSpider(world), LightLevel.hostile, getSpawnBiomes(EntityJumpingSpider.class), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableLavaWebSpider) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.FIRE_CHARGE, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 2, Conditional.affectedByLooting) }; registerMob(new EntityLavaWebSpider(world), LightLevel.hostile, getSpawnBiomes(EntityLavaWebSpider.class), drops); registerRenderHook(EntityLavaWebSpider.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableLocust) { registerMob(new EntityLocust(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.SUBTERRANEAN_SAVANNAH), new LootDrop(EnumErebusMaterialsType.ELASTIC_FIBRE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableMagmaCrawler) { registerMob(new EntityMagmaCrawler(world), LightLevel.hostile, getSpawnBiomes(EntityMagmaCrawler.class), new LootDrop(EnumErebusMaterialsType.MAGMA_CRAWLER_EYE.createStack())); } if(jerConfig.JER_MOBS.enableMidgeSwarm) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 3, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityMidgeSwarm(world), LightLevel.hostile, getSpawnBiomes(EntityMidgeSwarm.class), drops); } if(jerConfig.JER_MOBS.enableMoneySpider) { List<String> spawnBiomes = new ArrayList<>(); spawnBiomes.addAll(Arrays.asList(getSpawnBiomes(EntityLavaWebSpider.class))); spawnBiomes.addAll(Arrays.asList(getSpawnBiomes(EntityTarantula.class))); registerMob(new EntityMoneySpider(world), LightLevel.hostile, spawnBiomes.isEmpty() ? new String[] {"jer.any"} : spawnBiomes.toArray(new String[0]), new LootDrop(Items.GOLD_INGOT, 0, 1, 0.10f, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableMosquito) { registerMob(new EntityMosquito(world), LightLevel.hostile, getSpawnBiomes(EntityMosquito.class), new LootDrop(ModItems.LIFE_BLOOD, 1, 5)); registerRenderHook(EntityMosquito.class, ((renderInfo, e) -> { GlStateManager.translate(0,-0.5,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableMoth) { registerMob(new EntityMoth(world), LightLevel.hostile, getSpawnBiomes(EntityMoth.class), new LootDrop(Items.GLOWSTONE_DUST, 0.20f)); } if(jerConfig.JER_MOBS.enablePondSkater) { registerMob(new EntityPondSkater(world), LightLevel.hostile, getSpawnBiomes(EntityPondSkater.class), new LootDrop(EnumErebusMaterialsType.HYDROFUGE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enablePrayingMantis) { EntityPrayingMantis mantis = new EntityPrayingMantis(world); mantis.setAlpha(1.0f); registerMob(mantis, LightLevel.hostile, getSpawnBiomes(EntityPrayingMantis.class), new LootDrop(EnumErebusMaterialsType.CAMO_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); adjustBugRenderHookDown(EntityPrayingMantis.class); } if(jerConfig.JER_MOBS.enablePunchroom) { registerMob(new EntityPunchroom(world), LightLevel.hostile, getSpawnBiomes(EntityPunchroom.class), new LootDrop(EnumErebusMaterialsType.ELASTIC_FIBRE.createStack(), 1, 1, 0.20f, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableRhinoBeetle) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_EXO_RHINO.createStack(), 1, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.RHINO_BEETLE_HORN.createStack(), 0, 1, 0.05f, Conditional.rareDrop) }; registerMob(new EntityRhinoBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityRhinoBeetle.class), drops); registerRenderHook(EntityRhinoBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); GlStateManager.translate(0,1.0,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableScorpion) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SCORPION_PINCER.createStack(), 0, 3, 0.0333f, Conditional.affectedByLooting, Conditional.rareDrop) }; registerMob(new EntityScorpion(world), LightLevel.hostile, getSpawnBiomes(EntityScorpion.class), drops); adjustBugRenderHookDown(EntityScorpion.class); } if(jerConfig.JER_MOBS.enableScytodes) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.STRING, 0, 3, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 2, Conditional.affectedByLooting) }; registerMob(new EntityScytodes(world), LightLevel.hostile, getSpawnBiomes(EntityScytodes.class), drops); registerRenderHook(EntityScytodes.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableSolifuge) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.BIO_VELOCITY.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SUPERNATURAL_VELOCITY.createStack(), 0, 1, 0.02f, Conditional.rareDrop) }; registerMob(new EntitySolifuge(world), LightLevel.hostile, getSpawnBiomes(EntitySolifuge.class), drops); registerRenderHook(EntitySolifuge.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableStagBeetle) { List<LootDrop> drops = new ArrayList<>(); drops.add(exoPlateDrop); LootDrop foodDrop = new LootDrop(ModItems.STAG_HEART_RAW, 0.1333f); foodDrop.smeltedItem = new ItemStack(ModItems.STAG_HEART_COOKED); drops.add(foodDrop); drops.add(new LootDrop(EnumErebusMaterialsType.STAG_BEETLE_MANDIBLES.createStack(), 0, 1, 0.0333f, Conditional.rareDrop)); registerMob(new EntityStagBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityStagBeetle.class), drops); registerRenderHook(EntityStagBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); GlStateManager.translate(0, 1.0, 0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTarantula) { List<LootDrop> drops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(EnumFoodType.TARANTULA_LEG_RAW.createStack(), 1, 1, Conditional.affectedByLooting); foodDrop.smeltedItem = EnumFoodType.TARANTULA_LEG_COOKED.createStack(); drops.add(foodDrop); drops.add(new LootDrop(Items.SPIDER_EYE, 0, 1, Conditional.affectedByLooting)); registerMob(new EntityTarantula(world), LightLevel.hostile, getSpawnBiomes(EntityTarantula.class), drops); } if(jerConfig.JER_MOBS.enableTarantulaBroodMother) { registerMob(new EntityTarantulaMiniboss(world), LightLevel.hostile, allBiomes, new LootDrop(new ItemStack(ModItems.SPIDER_T_SHIRT))); registerRenderHook(EntityTarantulaMiniboss.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTitanBeetle) { List<LootDrop> drops = new ArrayList<>(); drops.add(exoPlateDrop); LootDrop foodDrop = new LootDrop(EnumFoodType.TITAN_CHOP_RAW.createStack()); foodDrop.smeltedItem = EnumFoodType.TITAN_CHOP_COOKED.createStack(); drops.add(foodDrop); registerMob(new EntityTitanBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityTitanBeetle.class), drops); registerRenderHook(EntityTitanBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); GlStateManager.translate(0, 1.0, 0); return renderInfo; })); } boolean isUmberGolemRegistered = false; if(jerConfig.JER_MOBS.enableUmberGolemMud) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 0); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemIron) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 1); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemGold) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 2); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemJade) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 3); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(isUmberGolemRegistered) { registerRenderHook(EntityUmberGolemDungeonTypes.class, ((renderInfo, e) -> { GlStateManager.translate(-0.025, -0.4, 0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableVelvetWorm) { registerMob(new EntityVelvetWorm(world), LightLevel.hostile, getSpawnBiomes(EntityVelvetWorm.class), new LootDrop(Items.SLIME_BALL, 1, 2, Conditional.affectedByLooting)); registerRenderHook(EntityVelvetWorm.class, ((renderInfo, e) -> { GlStateManager.scale(1.6,1.6,1.6); return renderInfo; })); } if(jerConfig.JER_MOBS.enableWasp) { registerMob(new EntityWasp(world), LightLevel.hostile, getSpawnBiomes(EntityWasp.class), new LootDrop(EnumErebusMaterialsType.WASP_STING.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableWaspBoss) { EntityWasp waspBoss = new EntityWasp(world); waspBoss.setIsBoss((byte) 1); LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.WASP_STING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(new ItemStack(ModItems.ANTI_VENOM_BOTTLE)) }; registerMob(waspBoss, LightLevel.hostile, getSpawnBiomes(EntityWasp.class), drops); } if(jerConfig.JER_MOBS.enableWoodlouse) { registerMob(new EntityWoodlouse(world), LightLevel.hostile, allBiomes, new LootDrop(EnumErebusMaterialsType.WHETSTONE_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); registerRenderHook(EntityWoodlouse.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableWorkerBee) { registerMob(new EntityWorkerBee(world), LightLevel.hostile, getSpawnBiomes(EntityWorkerBee.class), new LootDrop(EnumErebusMaterialsType.NECTAR.createStack(2))); adjustBugRenderHookUp(EntityWorkerBee.class); } if(jerConfig.JER_MOBS.enableZombieAnt) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.20f) }; registerMob(new EntityZombieAnt(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAnt.class), drops); } if(jerConfig.JER_MOBS.enableZombieAntSoldier) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.10f), new LootDrop(EnumErebusMaterialsType.TERPSISHROOM.createStack(), 0.10f) }; registerMob(new EntityZombieAntSoldier(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAntSoldier.class), drops); } } @Override public void registerModPlants() { if(jerConfig.JER_PLANTS.enableCabbage) { registerPlant((Item & IPlantable) ModItems.CABBAGE_SEEDS, new PlantDrop(new ItemStack(ModItems.CABBAGE_SEEDS), 0, 2), new PlantDrop(EnumFoodType.CABBAGE.createStack(), 1, 1) ); } if(jerConfig.JER_PLANTS.enableDarkFruit) { CustomPlantEntry darkFruit = new CustomPlantEntry( EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), ModBlocks.DARK_FRUIT_VINE.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), 0, 1), new PlantDrop(EnumFoodType.DARK_FRUIT.createStack(), 0, 1) ); darkFruit.setSoil(Blocks.AIR.getDefaultState()); registerCustomPlant(darkFruit); } if(jerConfig.JER_PLANTS.enableHeartBerry) { CustomPlantEntry heartBerry = new CustomPlantEntry( new ItemStack(ModBlocks.HEART_BERRY_BUSH), ModBlocks.HEART_BERRY_BUSH.getDefaultState(), new PlantDrop(new ItemStack(ModItems.HEART_BERRIES), 1, 1) ); heartBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(heartBerry); } if(jerConfig.JER_PLANTS.enableJadeBerry) { CustomPlantEntry jadeBerry = new CustomPlantEntry( new ItemStack(ModBlocks.JADE_BERRY_BUSH), ModBlocks.JADE_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.JADE_BERRIES.createStack(), 1, 1) ); jadeBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(jadeBerry); } if(jerConfig.JER_PLANTS.enableMandrake) { registerPlant((Item & IPlantable) ModItems.MANDRAKE_ROOT, new PlantDrop(new ItemStack(ModItems.MANDRAKE_ROOT), 1, 3) ); } if(jerConfig.JER_PLANTS.enableSwampBerry) { CustomPlantEntry swampBerry = new CustomPlantEntry( new ItemStack(ModBlocks.SWAMP_BERRY_BUSH), ModBlocks.SWAMP_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumFoodType.SWAMP_BERRIES.createStack(), 1, 1) ); swampBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(swampBerry); } if(jerConfig.JER_PLANTS.enableTurnip) { registerPlant((Item & IPlantable) ModItems.TURNIP, new PlantDrop(new ItemStack(ModItems.TURNIP), 1, 3) ); } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityGlowWorm.class, JERRenderGlowWorm::new); RenderingRegistry.registerEntityRenderingHandler(EntityMagmaCrawler.class, JERRenderMagmaCrawler::new); } private void adjustBugRenderHookUp(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, 0.4, 0); return renderInfo; })); } private void adjustBugRenderHookDown(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, -0.4, 0); return renderInfo; })); } private String[] getSpawnBiomes(Class<? extends EntityLiving> entityClass) { THashSet<Biome> spawnBiomes = new THashSet<>(); mobSpawns.forEach((biome, mobList) -> { if(mobList.contains(entityClass)) spawnBiomes.add(biome); }); return !spawnBiomes.isEmpty() ? BiomeHelper.getBiomeNamesForBiomes(spawnBiomes.toArray(new Biome[0])) : new String[] {"Check Spawns"}; } private void registerErebusDungeon(String name, WeightedLootList lootList, int minRolls, int maxRolls) { JERDungeonStrings dungeon = new JERDungeonStrings(name, lootList, minRolls, maxRolls); registerDungeonLoot(dungeon.category, dungeon.unlocName, dungeon.lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public final LootTable lootTable; public JERDungeonStrings(String name, WeightedLootList lootList, int minRolls, int maxRolls) { this.category = String.format("%s:%s", ModIds.EREBUS.MOD_ID, name); this.unlocName = StringHelper.getDungeonTranslationKey(ModIds.EREBUS.MOD_ID, name); this.lootTable = getLootTable(lootList, minRolls, maxRolls); } private LootTable getLootTable(WeightedLootList lootList, int minRolls, int maxRolls) { List<LootEntry> lootEntries = new ArrayList<>(); lootList.forEach((lootItemStack -> { try { Item item = (Item) getFieldValue(lootItemStack, "item"); if(item != null) { List<LootFunction> lootFunctions = new ArrayList<>(); String name = item.getRegistryName().toString(); short minDamage = (short) getFieldValue(lootItemStack, "minDamage"); short maxDamage = (short) getFieldValue(lootItemStack, "maxDamage"); byte minAmount = (byte) getFieldValue(lootItemStack, "minAmount"); byte maxAmount = (byte) getFieldValue(lootItemStack, "maxAmount"); short weight = (short) getFieldValue(lootItemStack, "weight"); lootFunctions.add(new SetCount(new LootCondition[0], new RandomValueRange(minAmount, maxAmount))); if((minDamage > 0 && maxDamage > 0)) { lootFunctions.add(new SetMetadata(new LootCondition[0], new RandomValueRange(minDamage, maxDamage))); } lootEntries.add(new LootEntryItem(item, weight, 0, lootFunctions.toArray(new LootFunction[0]), new LootCondition[0], name)); } } catch (Exception e) {
LogHelper.warn("Failed to get loot item for " + this.category);
9
2023-11-19 23:09:14+00:00
16k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/ProviHealthClient.java
[ { "identifier": "ProviHealthApi", "path": "src/main/java/com/provismet/provihealth/api/ProviHealthApi.java", "snippet": "public interface ProviHealthApi {\n public void onInitialize ();\n\n /**\n * Registers an icon that will display on top of the health bar in the HUD for a specific entity gr...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.provismet.provihealth.api.ProviHealthApi; import com.provismet.provihealth.config.Options; import com.provismet.provihealth.hud.TargetHealthBar; import com.provismet.provihealth.particle.Particles; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier;
11,705
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () { HudRenderCallback.EVENT.register(new TargetHealthBar());
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () { HudRenderCallback.EVENT.register(new TargetHealthBar());
FabricLoader.getInstance().getEntrypointContainers(MODID, ProviHealthApi.class).forEach(
0
2023-11-26 02:46:37+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
build/sources/main/java/io/github/quantizr/core/Waypoints.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.github.quantizr.DungeonRooms; import io.github.quantizr.events.PacketEvent; import io.github.quantizr.utils.Utils; import io.github.quantizr.utils.WaypointUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S0DPacketCollectItem; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import java.awt.*; import java.util.*; import java.util.List;
13,456
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks; BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt())); if (pos == null) continue; double x = pos.getX() - viewerX; double y = pos.getY() - viewerY; double z = pos.getZ() - viewerZ; double distSq = x*x + y*y + z*z; GlStateManager.disableDepth(); GlStateManager.disableCull();
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks; BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt())); if (pos == null) continue; double x = pos.getX() - viewerX; double y = pos.getY() - viewerY; double z = pos.getZ() - viewerZ; double distSq = x*x + y*y + z*z; GlStateManager.disableDepth(); GlStateManager.disableCull();
if (showBoundingBox) WaypointUtils.drawFilledBoundingBox(new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1), color, 0.4f);
3
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/LauncherWindow2.java
[ { "identifier": "GenericWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/generics/GenericWindow.java", "snippet": "public class GenericWindow {\n private static final String TAG = \"GenericWindow\";\n\n private static final int FADE_DURATION = 500;\n\n private static WindowMana...
import android.annotation.SuppressLint; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.icu.util.Calendar; import android.media.tv.TvContract; import android.media.tv.TvInputInfo; import android.media.tv.TvInputManager; import android.media.tv.TvView; import android.net.Uri; import android.provider.Settings; import android.util.Log; import android.view.KeyEvent; import android.view.View; import androidx.leanback.widget.ArrayObjectAdapter; import androidx.tvprovider.media.tv.PreviewChannel; import androidx.tvprovider.media.tv.PreviewProgram; import androidx.tvprovider.media.tv.TvContractCompat; import androidx.tvprovider.media.tv.WatchNextProgram; import net.lonelytransistor.commonlib.OutlinedTextView; import net.lonelytransistor.launcher.generics.GenericWindow; import net.lonelytransistor.launcher.repos.ApkRepo; import net.lonelytransistor.launcher.repos.JustWatch; import net.lonelytransistor.launcher.repos.MovieTitle; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor;
13,556
package net.lonelytransistor.launcher; @SuppressLint("RestrictedApi") public class LauncherWindow2 extends GenericWindow { private static final String TAG = "LauncherWindow"; private final Drawable newIcon; private final Drawable pausedIcon; private final Drawable nextIcon; private final Drawable listIcon; private final Drawable androidIcon; private final Executor executor; private final List<ArrayObjectAdapter> rows = new ArrayList<>(); private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; };
package net.lonelytransistor.launcher; @SuppressLint("RestrictedApi") public class LauncherWindow2 extends GenericWindow { private static final String TAG = "LauncherWindow"; private final Drawable newIcon; private final Drawable pausedIcon; private final Drawable nextIcon; private final Drawable listIcon; private final Drawable androidIcon; private final Executor executor; private final List<ArrayObjectAdapter> rows = new ArrayList<>(); private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; };
private void appendRecommendedPlatformPriv(ArrayObjectAdapter row, JustWatch.Type type, ApkRepo.Platform platform, JustWatch.Callback cb, boolean separator) {
2
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/GameController.java
[ { "identifier": "ChessBackup", "path": "CS109_2022_Fall/Chess/model/ChessBackup.java", "snippet": "public class ChessBackup {\n String nowColor;\n String[][] type, color;\n boolean[][] reversal;\n String records = \"--\", redEatenList, blackEatenList;\n int redScore, blackScore;\n\n pu...
import Chess.chessComponent.*; import Chess.model.ChessBackup; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.view.Chessboard; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import static Chess.utils.FileUtils.getCorrectSlash; import static Chess.view.Chessboard.COL_SIZE; import static Chess.view.Chessboard.ROW_SIZE; import static Chess.view.StartFrame.checkRecords;
12,293
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame();
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame();
String[][] reversalString = new String[ROW_SIZE][COL_SIZE];
5
2023-12-31 05:50:13+00:00
16k
psobiech/opengr8on
tftp/src/test/java/pl/psobiech/opengr8on/tftp/TFTPTest.java
[ { "identifier": "ServerMode", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPServer.java", "snippet": "public enum ServerMode {\n GET_ONLY,\n PUT_ONLY,\n GET_AND_PUT,\n GET_AND_REPLACE\n //\n ;\n}" }, { "identifier": "TFTPException", "path": "tftp/src/main/java/...
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Inet4Address; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import pl.psobiech.opengr8on.tftp.TFTPServer.ServerMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPException; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.tftp.packets.TFTPPacket; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.SocketUtil; import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
11,411
temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(expectedString, Files.readString(expectedPath)); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void uploadDownloadTextAsciiCRLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + CR + LF + "and a second line" + CR + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { Files.writeString(temporaryPathFrom, inputString); final String fileName = "uploadTextAsciiCRLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.NETASCII, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(expectedString, Files.readString(expectedPath)); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadTextAsciiLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + LF + "and a second line" + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "downloadTextAsciiLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); Files.writeString(expectedPath, inputString); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadTextAsciiCRLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + CR + LF + "and a second line" + CR + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "downloadTextAsciiCRLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); Files.writeString(expectedPath, inputString); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadNotFound() throws Exception { final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "notexisting.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); try { client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); } catch (TFTPException e) {
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp; @Execution(ExecutionMode.CONCURRENT) class TFTPTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private static ExecutorService executor = Executors.newCachedThreadPool(); private static Path rootDirectory; private static UDPSocket socket; private static TFTPServer server; private static Future<Void> serverFuture; private static TFTPClient client; private String LF = Character.toString(0x0A); private String CR = Character.toString(0x0D); @BeforeAll static void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); FileUtil.mkdir(rootDirectory); socket = new UDPSocket(LOCALHOST, 0, false); server = new TFTPServer(LOCALHOST, ServerMode.GET_AND_PUT, rootDirectory, socket); serverFuture = server.start(); server.awaitInitialized(); client = new TFTPClient(SocketUtil.udpRandomPort(LOCALHOST), socket.getLocalPort()); client.open(); } @AfterAll static void tearDown() throws Exception { FileUtil.closeQuietly(client); serverFuture.cancel(true); try { serverFuture.get(); } catch (Exception e) { // } FileUtil.closeQuietly(server); executor.shutdownNow(); FileUtil.deleteRecursively(rootDirectory); } @ParameterizedTest @ValueSource( ints = { 0, 1, 1023, 1024, 1025, // multiple blocks 0xFFFF * TFTPPacket.SEGMENT_SIZE + 1025 // block number rollover } ) void uploadBinary(int fileSize) throws Exception { final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { fillWithRandomBytes(fileSize, temporaryPathFrom); final String fileName = "file_" + fileSize + ".bin"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.OCTET, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.OCTET, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(fileSize, Files.size(expectedPath)); assertEquals(fileSize, Files.size(temporaryPathTo)); assertFilesSame(temporaryPathFrom, expectedPath); assertFilesSame(temporaryPathFrom, temporaryPathTo); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } private static void fillWithRandomBytes(int bufferSize, Path temporaryPathFrom) throws IOException { int left = bufferSize; try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(temporaryPathFrom))) { while (left > 0) { final byte[] randomBuffer = RandomUtil.bytes(Math.min(left, 4096)); outputStream.write(randomBuffer); left -= randomBuffer.length; } } } private static void assertFilesSame(Path expectedPath, Path actualPath) throws IOException { assertEquals(Files.size(expectedPath), Files.size(expectedPath)); int offset = 0; final byte[] expectedBuffer = new byte[1024]; final byte[] actualBuffer = new byte[1024]; try ( InputStream expectedInputStream = new BufferedInputStream(Files.newInputStream(expectedPath)); InputStream actualInputStream = new BufferedInputStream(Files.newInputStream(actualPath)); ) { int expectedRead; int actualRead; do { expectedRead = expectedInputStream.readNBytes(expectedBuffer, 0, expectedBuffer.length); actualRead = actualInputStream.readNBytes(actualBuffer, 0, actualBuffer.length); assertArrayEquals( Arrays.copyOf(expectedBuffer, expectedRead), Arrays.copyOf(actualBuffer, actualRead), "Files differ after offset: " + offset ); offset += expectedRead; } while (expectedRead > 0 && actualRead > 0); } } @Test void uploadDownloadTextAsciiLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + LF + "and a second line" + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { Files.writeString(temporaryPathFrom, inputString); final String fileName = "uploadDownloadTextAsciiLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.NETASCII, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(expectedString, Files.readString(expectedPath)); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void uploadDownloadTextAsciiCRLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + CR + LF + "and a second line" + CR + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { Files.writeString(temporaryPathFrom, inputString); final String fileName = "uploadTextAsciiCRLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.NETASCII, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(expectedString, Files.readString(expectedPath)); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadTextAsciiLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + LF + "and a second line" + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "downloadTextAsciiLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); Files.writeString(expectedPath, inputString); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadTextAsciiCRLF() throws Exception { final String expectedString = "Some test string" + System.lineSeparator() + "and a second line" + System.lineSeparator() + " ;-)"; final String inputString = "Some test string" + CR + LF + "and a second line" + CR + LF + " ;-)"; final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "downloadTextAsciiCRLF.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); Files.writeString(expectedPath, inputString); client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); assertEquals(expectedString, Files.readString(temporaryPathTo)); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } @Test void downloadNotFound() throws Exception { final Path temporaryPathTo = FileUtil.temporaryFile(); try { final String fileName = "notexisting.lua"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); try { client.download( LOCALHOST, TFTPTransferMode.NETASCII, fileName, temporaryPathTo ); } catch (TFTPException e) {
assertEquals(TFTPErrorType.FILE_NOT_FOUND, e.getError());
2
2023-12-23 09:56:14+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/combat/ShortbowAura.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.util.*; import com.github.may2beez.mayobees.util.helper.Rotation; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import com.github.may2beez.mayobees.util.helper.Target; import lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Tuple; import net.minecraft.util.Vec3; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList;
13,800
package com.github.may2beez.mayobees.module.impl.combat; public class ShortbowAura implements IModuleActive { private final Minecraft mc = Minecraft.getMinecraft(); private static ShortbowAura instance; public static ShortbowAura getInstance() { if (instance == null) { instance = new ShortbowAura(); } return instance; } @Override public String getName() { return "Shortbow Aura"; } @Getter private boolean enabled = false; private Optional<EntityLivingBase> currentTarget = Optional.empty(); private final CopyOnWriteArrayList<EntityLivingBase> possibleTargets = new CopyOnWriteArrayList<>(); private final List<Tuple<Entity, Long>> hitTargets = new ArrayList<>(); @Override public boolean isRunning() { return enabled; } @Override public void onEnable() { enabled = true; nextRotationSpeed = MayOBeesConfig.getRandomizedRotationSpeed(); LogUtils.info("Shortbow Aura enabled!"); } @Override public void onDisable() { enabled = false; currentTarget = Optional.empty(); hitTargets.clear(); possibleTargets.clear(); lastHit = 0; currentRandomDelay = MayOBeesConfig.getRandomizedCooldown(); if (!MayOBeesConfig.shortBowAuraRotationType)
package com.github.may2beez.mayobees.module.impl.combat; public class ShortbowAura implements IModuleActive { private final Minecraft mc = Minecraft.getMinecraft(); private static ShortbowAura instance; public static ShortbowAura getInstance() { if (instance == null) { instance = new ShortbowAura(); } return instance; } @Override public String getName() { return "Shortbow Aura"; } @Getter private boolean enabled = false; private Optional<EntityLivingBase> currentTarget = Optional.empty(); private final CopyOnWriteArrayList<EntityLivingBase> possibleTargets = new CopyOnWriteArrayList<>(); private final List<Tuple<Entity, Long>> hitTargets = new ArrayList<>(); @Override public boolean isRunning() { return enabled; } @Override public void onEnable() { enabled = true; nextRotationSpeed = MayOBeesConfig.getRandomizedRotationSpeed(); LogUtils.info("Shortbow Aura enabled!"); } @Override public void onDisable() { enabled = false; currentTarget = Optional.empty(); hitTargets.clear(); possibleTargets.clear(); lastHit = 0; currentRandomDelay = MayOBeesConfig.getRandomizedCooldown(); if (!MayOBeesConfig.shortBowAuraRotationType)
RotationHandler.getInstance().easeBackFromServerRotation();
1
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,606
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() { startActivity(new Intent(getContext(), SmsActivity.class)); } private void goto_product() { startActivity(new Intent(getContext(), ProductQrActivity.class)); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_home, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.images_item_scan) {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() { startActivity(new Intent(getContext(), SmsActivity.class)); } private void goto_product() { startActivity(new Intent(getContext(), ProductQrActivity.class)); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_home, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.images_item_scan) {
Intent intent = new Intent(getContext(), ScannerActivity.class);
4
2023-12-26 05:10:38+00:00
16k
piovas-lu/condominio
src/main/java/app/condominio/service/RelatorioServiceImpl.java
[ { "identifier": "Categoria", "path": "src/main/java/app/condominio/domain/Categoria.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"categorias\")\r\npublic class Categoria implements Serializable, Comparable<Categoria> {\r\n\r\n\tpublic static final int NIVEL_MAX = 4;\r\n\...
import java.math.BigDecimal; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import app.condominio.domain.Categoria; import app.condominio.domain.Cobranca; import app.condominio.domain.Conta; import app.condominio.domain.Moradia; import app.condominio.domain.Movimento; import app.condominio.domain.Orcamento; import app.condominio.domain.Periodo; import app.condominio.domain.Subcategoria; import app.condominio.domain.enums.TipoCategoria;
11,752
return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada() { SortedMap<Moradia, List<Cobranca>> map = new TreeMap<>(); List<Cobranca> inadimplencia = cobrancaService.listarInadimplencia(); for (Cobranca cobranca : inadimplencia) { List<Cobranca> lista; if (map.containsKey(cobranca.getMoradia())) { lista = map.get(cobranca.getMoradia()); } else { lista = new ArrayList<>(); } lista.add(cobranca); map.put(cobranca.getMoradia(), lista); } return map; } @Override public Map<Moradia, BigDecimal> somaCobrancas(Map<Moradia, List<Cobranca>> map) { Map<Moradia, BigDecimal> mapa = new HashMap<>(); if (!map.isEmpty()) { for (Map.Entry<Moradia, List<Cobranca>> entrada : map.entrySet()) { BigDecimal soma = BigDecimal.ZERO; for (Cobranca cobranca : entrada.getValue()) { soma = soma.add(cobranca.getTotal()); } mapa.put(entrada.getKey(), soma); } } return mapa; } @Override public Map<Subcategoria, BigDecimal[]> somaOrcadoRealizadoSubcategorias(Periodo periodo) { Map<Subcategoria, BigDecimal[]> mapa = new HashMap<>(); List<Conta> contas = contaService.listar(); if (periodo != null && !contas.isEmpty()) { for (Subcategoria subcategoria : subcategoriaService.listar()) { Orcamento orcamento = orcamentoService.ler(periodo, subcategoria); BigDecimal realizado = movimentoService.somaLancamentosPeriodo(contas, periodo, subcategoria); BigDecimal[] valores = new BigDecimal[2]; if (orcamento != null) { valores[0] = orcamento.getOrcado(); } else { valores[0] = BigDecimal.ZERO.setScale(2); } if (realizado != null) { valores[1] = realizado; } else { valores[1] = BigDecimal.ZERO.setScale(2); } if (valores[0].compareTo(BigDecimal.ZERO) != 0 || valores[1].compareTo(BigDecimal.ZERO) != 0) { mapa.put(subcategoria, valores); } } } return mapa; } @Override
package app.condominio.service; @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class RelatorioServiceImpl implements RelatorioService { @Autowired ContaService contaService; @Autowired MovimentoService movimentoService; @Autowired CobrancaService cobrancaService; @Autowired OrcamentoService orcamentoService; @Autowired PeriodoService periodoService; @Autowired SubcategoriaService subcategoriaService; @Autowired CategoriaService categoriaService; @Override public BigDecimal saldoAtualTodasContas() { return contaService.saldoAtual(); } @Override public BigDecimal saldoInicialTodasContasEm(LocalDate data) { BigDecimal saldo = contaService.saldoAtual(); BigDecimal[] lancamentos = receitaDespesaDesde(contaService.listar(), data); return saldo.subtract(lancamentos[0]).add(lancamentos[1]); } @Override public BigDecimal saldoFinalTodasContasEm(LocalDate data) { return saldoInicialTodasContasEm(data.plusDays(1)); } @Override public BigDecimal inadimplenciaAtual() { return cobrancaService.inadimplencia(); } private BigDecimal[] receitaDespesaEntre(Collection<Conta> contas, LocalDate inicio, LocalDate fim) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } private BigDecimal[] receitaDespesaDesde(Collection<Conta> contas, LocalDate inicio) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada() { SortedMap<Moradia, List<Cobranca>> map = new TreeMap<>(); List<Cobranca> inadimplencia = cobrancaService.listarInadimplencia(); for (Cobranca cobranca : inadimplencia) { List<Cobranca> lista; if (map.containsKey(cobranca.getMoradia())) { lista = map.get(cobranca.getMoradia()); } else { lista = new ArrayList<>(); } lista.add(cobranca); map.put(cobranca.getMoradia(), lista); } return map; } @Override public Map<Moradia, BigDecimal> somaCobrancas(Map<Moradia, List<Cobranca>> map) { Map<Moradia, BigDecimal> mapa = new HashMap<>(); if (!map.isEmpty()) { for (Map.Entry<Moradia, List<Cobranca>> entrada : map.entrySet()) { BigDecimal soma = BigDecimal.ZERO; for (Cobranca cobranca : entrada.getValue()) { soma = soma.add(cobranca.getTotal()); } mapa.put(entrada.getKey(), soma); } } return mapa; } @Override public Map<Subcategoria, BigDecimal[]> somaOrcadoRealizadoSubcategorias(Periodo periodo) { Map<Subcategoria, BigDecimal[]> mapa = new HashMap<>(); List<Conta> contas = contaService.listar(); if (periodo != null && !contas.isEmpty()) { for (Subcategoria subcategoria : subcategoriaService.listar()) { Orcamento orcamento = orcamentoService.ler(periodo, subcategoria); BigDecimal realizado = movimentoService.somaLancamentosPeriodo(contas, periodo, subcategoria); BigDecimal[] valores = new BigDecimal[2]; if (orcamento != null) { valores[0] = orcamento.getOrcado(); } else { valores[0] = BigDecimal.ZERO.setScale(2); } if (realizado != null) { valores[1] = realizado; } else { valores[1] = BigDecimal.ZERO.setScale(2); } if (valores[0].compareTo(BigDecimal.ZERO) != 0 || valores[1].compareTo(BigDecimal.ZERO) != 0) { mapa.put(subcategoria, valores); } } } return mapa; } @Override
public Map<Categoria, BigDecimal[]> somaOrcadoRealizadoCategorias(Periodo periodo) {
0
2023-12-29 22:19:42+00:00
16k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/order/order/entity/dos/Order.java
[ { "identifier": "ClientTypeEnum", "path": "framework/src/main/java/cn/lili/common/enums/ClientTypeEnum.java", "snippet": "public enum ClientTypeEnum {\n\n /**\n * \"移动端\"\n */\n H5(\"移动端\"),\n /**\n * \"PC端\"\n */\n PC(\"PC端\"),\n /**\n * \"小程序端\"\n */\n WECHAT_...
import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.json.JSONUtil; import cn.lili.common.enums.ClientTypeEnum; import cn.lili.common.enums.PromotionTypeEnum; import cn.lili.common.security.sensitive.Sensitive; import cn.lili.common.security.sensitive.enums.SensitiveStrategy; import cn.lili.common.utils.BeanUtil; import cn.lili.modules.goods.entity.enums.GoodsTypeEnum; import cn.lili.modules.order.cart.entity.dto.MemberCouponDTO; import cn.lili.modules.order.cart.entity.dto.TradeDTO; import cn.lili.modules.order.cart.entity.enums.CartTypeEnum; import cn.lili.modules.order.cart.entity.enums.DeliveryMethodEnum; import cn.lili.modules.order.cart.entity.vo.CartVO; import cn.lili.modules.order.order.entity.dto.PriceDetailDTO; import cn.lili.modules.order.order.entity.enums.*; import cn.lili.modules.payment.entity.enums.PaymentMethodEnum; import cn.lili.mybatis.BaseEntity; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.Optional;
11,254
@ApiModelProperty(value = "是否为某订单类型的订单,如果是则为订单类型的id,否则为空") private String promotionId; /** * @see OrderTypeEnum */ @ApiModelProperty(value = "订单类型") private String orderType; /** * @see OrderPromotionTypeEnum */ @ApiModelProperty(value = "订单促销类型") private String orderPromotionType; @ApiModelProperty(value = "价格价格详情") private String priceDetail; @ApiModelProperty(value = "订单是否支持原路退回") private Boolean canReturn; @ApiModelProperty(value = "提货码") private String verificationCode; @ApiModelProperty(value = "分销员ID") private String distributionId; @ApiModelProperty(value = "使用的店铺会员优惠券id(,区分)") private String useStoreMemberCouponIds; @ApiModelProperty(value = "使用的平台会员优惠券id") private String usePlatformMemberCouponId; @ApiModelProperty(value = "qrCode 实物为提货码 虚拟货物为账号") private String qrCode; @ApiModelProperty(value = "自提点地址") private String storeAddressPath; @ApiModelProperty(value = "自提点电话") private String storeAddressMobile; @ApiModelProperty(value = "自提点地址经纬度") private String storeAddressCenter; /** * 构建订单 * * @param cartVO 购物车VO * @param tradeDTO 交易DTO */ public Order(CartVO cartVO, TradeDTO tradeDTO) { String oldId = this.getId(); BeanUtil.copyProperties(tradeDTO, this); BeanUtil.copyProperties(cartVO.getPriceDetailDTO(), this); BeanUtil.copyProperties(cartVO, this); //填写订单类型 this.setTradeType(cartVO, tradeDTO); setId(oldId); //设置默认支付状态 this.setOrderStatus(OrderStatusEnum.UNPAID.name()); this.setPayStatus(PayStatusEnum.UNPAID.name()); this.setDeliverStatus(DeliverStatusEnum.UNDELIVERED.name()); this.setTradeSn(tradeDTO.getSn()); this.setRemark(cartVO.getRemark()); this.setFreightPrice(tradeDTO.getPriceDetailDTO().getFreightPrice()); //会员收件信息 if (tradeDTO.getMemberAddress() != null && DeliveryMethodEnum.LOGISTICS.name().equals(cartVO.getDeliveryMethod())) { this.setConsigneeAddressIdPath(tradeDTO.getMemberAddress().getConsigneeAddressIdPath()); this.setConsigneeAddressPath(tradeDTO.getMemberAddress().getConsigneeAddressPath()); this.setConsigneeDetail(tradeDTO.getMemberAddress().getDetail()); this.setConsigneeMobile(tradeDTO.getMemberAddress().getMobile()); this.setConsigneeName(tradeDTO.getMemberAddress().getName()); } //自提点信息 if (tradeDTO.getStoreAddress() != null && DeliveryMethodEnum.SELF_PICK_UP.name().equals(cartVO.getDeliveryMethod())) { this.setStoreAddressPath(tradeDTO.getStoreAddress().getAddress()); this.setStoreAddressMobile(tradeDTO.getStoreAddress().getMobile()); this.setStoreAddressCenter(tradeDTO.getStoreAddress().getCenter()); } //平台优惠券判定 if (tradeDTO.getPlatformCoupon() != null) { this.setUsePlatformMemberCouponId(tradeDTO.getPlatformCoupon().getMemberCoupon().getId()); } //店铺优惠券判定 if (tradeDTO.getStoreCoupons() != null && !tradeDTO.getStoreCoupons().isEmpty()) { StringBuilder storeCouponIds = new StringBuilder(); for (MemberCouponDTO value : tradeDTO.getStoreCoupons().values()) { storeCouponIds.append(value.getMemberCoupon().getId()).append(","); } this.setUseStoreMemberCouponIds(storeCouponIds.toString()); } } /** * 填写交易(订单)类型 * 1.判断是普通、促销订单 * 2.普通订单进行区分:实物订单、虚拟订单 * 3.促销订单判断货物进行区分实物、虚拟商品。 * 4.拼团订单需要填写父订单ID * * @param cartVO 购物车VO * @param tradeDTO 交易DTO */ private void setTradeType(CartVO cartVO, TradeDTO tradeDTO) { //判断是否为普通订单、促销订单 if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.CART) || tradeDTO.getCartTypeEnum().equals(CartTypeEnum.BUY_NOW)) { this.setOrderType(OrderTypeEnum.NORMAL.name()); this.setOrderPromotionType(OrderPromotionTypeEnum.NORMAL.name()); } else if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.VIRTUAL)) { this.setOrderType(OrderTypeEnum.VIRTUAL.name()); this.setOrderPromotionType(OrderPromotionTypeEnum.NORMAL.name()); } else { //促销订单(拼团、积分)-判断购买的是虚拟商品还是实物商品 String goodsType = cartVO.getCheckedSkuList().get(0).getGoodsSku().getGoodsType();
package cn.lili.modules.order.order.entity.dos; /** * 订单 * * @author Chopper * @since 2020/11/17 7:30 下午 */ @EqualsAndHashCode(callSuper = true) @Data @TableName("li_order") @ApiModel(value = "订单") @NoArgsConstructor public class Order extends BaseEntity { private static final long serialVersionUID = 2233811628066468683L; @ApiModelProperty("订单编号") private String sn; @ApiModelProperty("交易编号 关联Trade") private String tradeSn; @ApiModelProperty(value = "店铺ID") private String storeId; @ApiModelProperty(value = "店铺名称") private String storeName; @ApiModelProperty(value = "会员ID") private String memberId; @ApiModelProperty(value = "用户名") @Sensitive(strategy = SensitiveStrategy.PHONE) private String memberName; /** * @see OrderStatusEnum */ @ApiModelProperty(value = "订单状态") private String orderStatus; /** * @see PayStatusEnum */ @ApiModelProperty(value = "付款状态") private String payStatus; /** * @see DeliverStatusEnum */ @ApiModelProperty(value = "货运状态") private String deliverStatus; @ApiModelProperty(value = "第三方付款流水号") private String receivableNo; /** * @see PaymentMethodEnum */ @ApiModelProperty(value = "支付方式") private String paymentMethod; @ApiModelProperty(value = "支付时间") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date paymentTime; @ApiModelProperty(value = "收件人姓名") private String consigneeName; @ApiModelProperty(value = "收件人手机") private String consigneeMobile; /** * @see DeliveryMethodEnum */ @ApiModelProperty(value = "配送方式") private String deliveryMethod; @ApiModelProperty(value = "地址名称, ','分割") private String consigneeAddressPath; @ApiModelProperty(value = "地址id,','分割 ") private String consigneeAddressIdPath; @ApiModelProperty(value = "详细地址") private String consigneeDetail; @ApiModelProperty(value = "总价格") private Double flowPrice; @ApiModelProperty(value = "商品价格") private Double goodsPrice; @ApiModelProperty(value = "运费") private Double freightPrice; @ApiModelProperty(value = "优惠的金额") private Double discountPrice; @ApiModelProperty(value = "修改价格") private Double updatePrice; @ApiModelProperty(value = "发货单号") private String logisticsNo; @ApiModelProperty(value = "物流公司CODE") private String logisticsCode; @ApiModelProperty(value = "物流公司名称") private String logisticsName; @ApiModelProperty(value = "订单商品总重量") private Double weight; @ApiModelProperty(value = "商品数量") private Integer goodsNum; @ApiModelProperty(value = "买家订单备注") private String remark; @ApiModelProperty(value = "订单取消原因") private String cancelReason; @ApiModelProperty(value = "完成时间") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date completeTime; @ApiModelProperty(value = "送货时间") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date logisticsTime; @ApiModelProperty(value = "支付方式返回的交易号") private String payOrderNo; /** * @see ClientTypeEnum */ @ApiModelProperty(value = "订单来源") private String clientType; @ApiModelProperty(value = "是否需要发票") private Boolean needReceipt; @ApiModelProperty(value = "是否为其他订单下的订单,如果是则为依赖订单的sn,否则为空") private String parentOrderSn = ""; @ApiModelProperty(value = "是否为某订单类型的订单,如果是则为订单类型的id,否则为空") private String promotionId; /** * @see OrderTypeEnum */ @ApiModelProperty(value = "订单类型") private String orderType; /** * @see OrderPromotionTypeEnum */ @ApiModelProperty(value = "订单促销类型") private String orderPromotionType; @ApiModelProperty(value = "价格价格详情") private String priceDetail; @ApiModelProperty(value = "订单是否支持原路退回") private Boolean canReturn; @ApiModelProperty(value = "提货码") private String verificationCode; @ApiModelProperty(value = "分销员ID") private String distributionId; @ApiModelProperty(value = "使用的店铺会员优惠券id(,区分)") private String useStoreMemberCouponIds; @ApiModelProperty(value = "使用的平台会员优惠券id") private String usePlatformMemberCouponId; @ApiModelProperty(value = "qrCode 实物为提货码 虚拟货物为账号") private String qrCode; @ApiModelProperty(value = "自提点地址") private String storeAddressPath; @ApiModelProperty(value = "自提点电话") private String storeAddressMobile; @ApiModelProperty(value = "自提点地址经纬度") private String storeAddressCenter; /** * 构建订单 * * @param cartVO 购物车VO * @param tradeDTO 交易DTO */ public Order(CartVO cartVO, TradeDTO tradeDTO) { String oldId = this.getId(); BeanUtil.copyProperties(tradeDTO, this); BeanUtil.copyProperties(cartVO.getPriceDetailDTO(), this); BeanUtil.copyProperties(cartVO, this); //填写订单类型 this.setTradeType(cartVO, tradeDTO); setId(oldId); //设置默认支付状态 this.setOrderStatus(OrderStatusEnum.UNPAID.name()); this.setPayStatus(PayStatusEnum.UNPAID.name()); this.setDeliverStatus(DeliverStatusEnum.UNDELIVERED.name()); this.setTradeSn(tradeDTO.getSn()); this.setRemark(cartVO.getRemark()); this.setFreightPrice(tradeDTO.getPriceDetailDTO().getFreightPrice()); //会员收件信息 if (tradeDTO.getMemberAddress() != null && DeliveryMethodEnum.LOGISTICS.name().equals(cartVO.getDeliveryMethod())) { this.setConsigneeAddressIdPath(tradeDTO.getMemberAddress().getConsigneeAddressIdPath()); this.setConsigneeAddressPath(tradeDTO.getMemberAddress().getConsigneeAddressPath()); this.setConsigneeDetail(tradeDTO.getMemberAddress().getDetail()); this.setConsigneeMobile(tradeDTO.getMemberAddress().getMobile()); this.setConsigneeName(tradeDTO.getMemberAddress().getName()); } //自提点信息 if (tradeDTO.getStoreAddress() != null && DeliveryMethodEnum.SELF_PICK_UP.name().equals(cartVO.getDeliveryMethod())) { this.setStoreAddressPath(tradeDTO.getStoreAddress().getAddress()); this.setStoreAddressMobile(tradeDTO.getStoreAddress().getMobile()); this.setStoreAddressCenter(tradeDTO.getStoreAddress().getCenter()); } //平台优惠券判定 if (tradeDTO.getPlatformCoupon() != null) { this.setUsePlatformMemberCouponId(tradeDTO.getPlatformCoupon().getMemberCoupon().getId()); } //店铺优惠券判定 if (tradeDTO.getStoreCoupons() != null && !tradeDTO.getStoreCoupons().isEmpty()) { StringBuilder storeCouponIds = new StringBuilder(); for (MemberCouponDTO value : tradeDTO.getStoreCoupons().values()) { storeCouponIds.append(value.getMemberCoupon().getId()).append(","); } this.setUseStoreMemberCouponIds(storeCouponIds.toString()); } } /** * 填写交易(订单)类型 * 1.判断是普通、促销订单 * 2.普通订单进行区分:实物订单、虚拟订单 * 3.促销订单判断货物进行区分实物、虚拟商品。 * 4.拼团订单需要填写父订单ID * * @param cartVO 购物车VO * @param tradeDTO 交易DTO */ private void setTradeType(CartVO cartVO, TradeDTO tradeDTO) { //判断是否为普通订单、促销订单 if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.CART) || tradeDTO.getCartTypeEnum().equals(CartTypeEnum.BUY_NOW)) { this.setOrderType(OrderTypeEnum.NORMAL.name()); this.setOrderPromotionType(OrderPromotionTypeEnum.NORMAL.name()); } else if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.VIRTUAL)) { this.setOrderType(OrderTypeEnum.VIRTUAL.name()); this.setOrderPromotionType(OrderPromotionTypeEnum.NORMAL.name()); } else { //促销订单(拼团、积分)-判断购买的是虚拟商品还是实物商品 String goodsType = cartVO.getCheckedSkuList().get(0).getGoodsSku().getGoodsType();
if (CharSequenceUtil.isEmpty(goodsType) || goodsType.equals(GoodsTypeEnum.PHYSICAL_GOODS.name())) {
4
2023-12-24 19:45:18+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/autoTokenController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n...
import com.tokensTool.pandoraNext.anno.Log; import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.impl.poolServiceImpl; import com.tokensTool.pandoraNext.service.impl.shareServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import java.util.List;
13,677
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired
private poolServiceImpl poolService;
2
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/AiServicesProcessor.java
[ { "identifier": "illegalConfigurationForMethod", "path": "core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/ExceptionUtil.java", "snippet": "static IllegalConfigurationException illegalConfigurationForMethod(String message, MethodInfo offendingMethod) {\n String effectiveMessage = m...
import static dev.langchain4j.exception.IllegalConfigurationException.illegalConfiguration; import static dev.langchain4j.service.ServiceOutputParser.outputFormatInstructions; import static io.quarkiverse.langchain4j.deployment.ExceptionUtil.illegalConfigurationForMethod; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.ClassType; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.jandex.ParameterizedType; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.AnalyzerException; import dev.langchain4j.exception.IllegalConfigurationException; import dev.langchain4j.service.V; import io.quarkiverse.langchain4j.deployment.items.SelectedChatModelProviderBuildItem; import io.quarkiverse.langchain4j.runtime.AiServicesRecorder; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceClassCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodImplementationSupport; import io.quarkiverse.langchain4j.runtime.aiservice.ChatMemoryRemovable; import io.quarkiverse.langchain4j.runtime.aiservice.DeclarativeAiServiceCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsCountedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsTimedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.QuarkusAiServiceContext; import io.quarkiverse.langchain4j.runtime.aiservice.SpanWrapper; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.InstanceHandle; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor; import io.quarkus.arc.deployment.SyntheticBeanBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.ScopeInfo; import io.quarkus.builder.item.MultiBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.GeneratedClassGizmoAdaptor; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.GeneratedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.metrics.MetricsCapabilityBuildItem; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.ClassOutput; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.Gizmo; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import io.quarkus.runtime.metrics.MetricsFactory;
12,865
containerHandle, mc.loadClassFromTCCL(className), mc.newArray(Annotation.class, 0)); return mc.invokeInterfaceMethod(MethodDescriptor.ofMethod(InstanceHandle.class, "get", Object.class), instanceHandle); } private String createMethodId(MethodInfo methodInfo) { return methodInfo.name() + '(' + Arrays.toString(methodInfo.parameters().stream().map(mp -> mp.type().name().toString()).toArray()) + ')'; } private void addIfacesWithMessageAnns(IndexView index, Set<String> detectedForCreate) { List<DotName> annotations = List.of(Langchain4jDotNames.SYSTEM_MESSAGE, Langchain4jDotNames.USER_MESSAGE, Langchain4jDotNames.MODERATE); for (DotName annotation : annotations) { Collection<AnnotationInstance> instances = index.getAnnotations(annotation); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.METHOD) { continue; } ClassInfo declaringClass = instance.target().asMethod().declaringClass(); if (declaringClass.isInterface()) { detectedForCreate.add(declaringClass.name().toString()); } } } } private static void addCreatedAware(IndexView index, Set<String> detectedForCreate) { Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.CREATED_AWARE); for (var instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; } detectedForCreate.add(instance.target().asClass().name().toString()); } } private AiServiceMethodCreateInfo gatherMethodMetadata(MethodInfo method, boolean addMicrometerMetrics, boolean addOpenTelemetrySpans) { if (method.returnType().kind() == Type.Kind.VOID) { throw illegalConfiguration("Return type of method '%s' cannot be void", method); } boolean requiresModeration = method.hasAnnotation(Langchain4jDotNames.MODERATE); List<MethodParameterInfo> params = method.parameters(); List<TemplateParameterInfo> templateParams = gatherTemplateParamInfo(params); Optional<AiServiceMethodCreateInfo.TemplateInfo> systemMessageInfo = gatherSystemMessageInfo(method, templateParams); Class<?> returnType = JandexUtil.load(method.returnType(), Thread.currentThread().getContextClassLoader()); AiServiceMethodCreateInfo.UserMessageInfo userMessageInfo = gatherUserMessageInfo(method, templateParams, returnType); Optional<Integer> memoryIdParamPosition = gatherMemoryIdParamName(method); Optional<AiServiceMethodCreateInfo.MetricsTimedInfo> metricsTimedInfo = gatherMetricsTimedInfo(method, addMicrometerMetrics); Optional<AiServiceMethodCreateInfo.MetricsCountedInfo> metricsCountedInfo = gatherMetricsCountedInfo(method, addMicrometerMetrics); Optional<AiServiceMethodCreateInfo.SpanInfo> spanInfo = gatherSpanInfo(method, addOpenTelemetrySpans); return new AiServiceMethodCreateInfo(method.declaringClass().name().toString(), method.name(), systemMessageInfo, userMessageInfo, memoryIdParamPosition, requiresModeration, returnType, metricsTimedInfo, metricsCountedInfo, spanInfo); } private List<TemplateParameterInfo> gatherTemplateParamInfo(List<MethodParameterInfo> params) { if (params.isEmpty()) { return Collections.emptyList(); } List<TemplateParameterInfo> templateParams = new ArrayList<>(); for (MethodParameterInfo param : params) { if (effectiveParamAnnotations(param).isEmpty()) { // if a parameter has no annotations it is considered a template variable templateParams.add(new TemplateParameterInfo(param.position(), param.name())); } else { AnnotationInstance vInstance = param.annotation(V); if (vInstance != null) { AnnotationValue value = vInstance.value(); if (value != null) { templateParams.add(new TemplateParameterInfo(param.position(), value.asString())); } } } } if ((templateParams.size() == 1) && (params.size() == 1)) { // the special 'it' param is supported when the method only has one parameter templateParams.add(new TemplateParameterInfo(0, "it")); } return templateParams; } private List<AnnotationInstance> effectiveParamAnnotations(MethodParameterInfo param) { return param.annotations().stream().filter(ai -> { String name = ai.name().toString(); if (name.startsWith("kotlin") || name.startsWith("jakarta.validation.constraints")) { return false; } if (name.endsWith("NotNull")) { return false; } if (name.startsWith("io.opentelemetry")) { return false; } return true; }).collect(Collectors.toList()); } private Optional<AiServiceMethodCreateInfo.TemplateInfo> gatherSystemMessageInfo(MethodInfo method, List<TemplateParameterInfo> templateParams) { AnnotationInstance instance = method.annotation(Langchain4jDotNames.SYSTEM_MESSAGE); if (instance != null) { String systemMessageTemplate = ""; AnnotationValue delimiterValue = instance.value("delimiter"); String delimiter = delimiterValue != null ? delimiterValue.asString() : DEFAULT_DELIMITER; AnnotationValue value = instance.value(); if (value != null) { systemMessageTemplate = String.join(delimiter, value.asStringArray()); } if (systemMessageTemplate.isEmpty()) {
package io.quarkiverse.langchain4j.deployment; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class AiServicesProcessor { private static final Logger log = Logger.getLogger(AiServicesProcessor.class); private static final DotName V = DotName.createSimple(V.class); public static final DotName MICROMETER_TIMED = DotName.createSimple("io.micrometer.core.annotation.Timed"); public static final DotName MICROMETER_COUNTED = DotName.createSimple("io.micrometer.core.annotation.Counted"); private static final String DEFAULT_DELIMITER = "\n"; private static final Predicate<AnnotationInstance> IS_METHOD_PARAMETER_ANNOTATION = ai -> ai.target() .kind() == AnnotationTarget.Kind.METHOD_PARAMETER; private static final Function<AnnotationInstance, Integer> METHOD_PARAMETER_POSITION_FUNCTION = ai -> Integer .valueOf(ai.target() .asMethodParameter().position()); public static final MethodDescriptor OBJECT_CONSTRUCTOR = MethodDescriptor.ofConstructor(Object.class); private static final MethodDescriptor RECORDER_METHOD_CREATE_INFO = MethodDescriptor.ofMethod(AiServicesRecorder.class, "getAiServiceMethodCreateInfo", AiServiceMethodCreateInfo.class, String.class, String.class); private static final MethodDescriptor SUPPORT_IMPLEMENT = MethodDescriptor.ofMethod( AiServiceMethodImplementationSupport.class, "implement", Object.class, AiServiceMethodImplementationSupport.Input.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_CLOSE = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "close", void.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_REMOVE_CHAT_MEMORY_IDS = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "removeChatMemoryIds", void.class, Object[].class); public static final DotName CDI_INSTANCE = DotName.createSimple(Instance.class); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String METRICS_DEFAULT_NAME = "langchain4j.aiservices"; @BuildStep public void nativeSupport(CombinedIndexBuildItem indexBuildItem, List<AiServicesMethodBuildItem> aiServicesMethodBuildItems, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.DESCRIPTION); Set<ClassInfo> classesUsingDescription = new HashSet<>(); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.FIELD) { continue; } classesUsingDescription.add(instance.target().asField().declaringClass()); } if (!classesUsingDescription.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(classesUsingDescription.stream().map(i -> i.name().toString()).toArray(String[]::new)).fields(true) .build()); } Set<DotName> returnTypesToRegister = new HashSet<>(); for (AiServicesMethodBuildItem aiServicesMethodBuildItem : aiServicesMethodBuildItems) { Type type = aiServicesMethodBuildItem.methodInfo.returnType(); if (type.kind() == Type.Kind.PRIMITIVE) { continue; } DotName returnTypeName = type.name(); if (returnTypeName.toString().startsWith("java.")) { continue; } returnTypesToRegister.add(returnTypeName); } if (!returnTypesToRegister.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(returnTypesToRegister.stream().map(DotName::toString).toArray(String[]::new)) .constructors(false) .build()); } } @BuildStep public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem, BuildProducer<RequestChatModelBeanBuildItem> requestChatModelBeanProducer, BuildProducer<RequestModerationModelBeanBuildItem> requestModerationModelBeanProducer, BuildProducer<DeclarativeAiServiceBuildItem> declarativeAiServiceProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); boolean needChatModelBean = false; boolean needModerationModelBean = false; for (AnnotationInstance instance : index.getAnnotations(Langchain4jDotNames.REGISTER_AI_SERVICES)) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; // should never happen } ClassInfo declarativeAiServiceClassInfo = instance.target().asClass(); DotName chatLanguageModelSupplierClassDotName = null; AnnotationValue chatLanguageModelSupplierValue = instance.value("chatLanguageModelSupplier"); if (chatLanguageModelSupplierValue != null) { chatLanguageModelSupplierClassDotName = chatLanguageModelSupplierValue.asClass().name(); if (chatLanguageModelSupplierClassDotName.equals(Langchain4jDotNames.BEAN_CHAT_MODEL_SUPPLIER)) { // this is the case where the default was set, so we just ignore it chatLanguageModelSupplierClassDotName = null; } else { validateSupplierAndRegisterForReflection(chatLanguageModelSupplierClassDotName, index, reflectiveClassProducer); } } if (chatLanguageModelSupplierClassDotName == null) { needChatModelBean = true; } List<DotName> toolDotNames = Collections.emptyList(); AnnotationValue toolsInstance = instance.value("tools"); if (toolsInstance != null) { toolDotNames = Arrays.stream(toolsInstance.asClassArray()).map(Type::name) .collect(Collectors.toList()); } // the default value depends on whether tools exists or not - if they do, then we require a ChatMemoryProvider bean DotName chatMemoryProviderSupplierClassDotName = Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER; AnnotationValue chatMemoryProviderSupplierValue = instance.value("chatMemoryProviderSupplier"); if (chatMemoryProviderSupplierValue != null) { chatMemoryProviderSupplierClassDotName = chatMemoryProviderSupplierValue.asClass().name(); if (!chatMemoryProviderSupplierClassDotName .equals(Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER)) { validateSupplierAndRegisterForReflection(chatMemoryProviderSupplierClassDotName, index, reflectiveClassProducer); } } DotName retrieverSupplierClassDotName = Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER; AnnotationValue retrieverSupplierValue = instance.value("retrieverSupplier"); if (retrieverSupplierValue != null) { retrieverSupplierClassDotName = retrieverSupplierValue.asClass().name(); if (!retrieverSupplierClassDotName.equals(Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER)) { validateSupplierAndRegisterForReflection(retrieverSupplierClassDotName, index, reflectiveClassProducer); } } DotName auditServiceSupplierClassName = Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER; AnnotationValue auditServiceSupplierValue = instance.value("auditServiceSupplier"); if (auditServiceSupplierValue != null) { auditServiceSupplierClassName = auditServiceSupplierValue.asClass().name(); validateSupplierAndRegisterForReflection(auditServiceSupplierClassName, index, reflectiveClassProducer); } DotName moderationModelSupplierClassName = null; AnnotationValue moderationModelSupplierValue = instance.value("moderationModelSupplier"); if (moderationModelSupplierValue != null) { moderationModelSupplierClassName = moderationModelSupplierValue.asClass().name(); if (Langchain4jDotNames.NO_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { moderationModelSupplierClassName = null; } else if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { needModerationModelBean = true; } else { validateSupplierAndRegisterForReflection(moderationModelSupplierClassName, index, reflectiveClassProducer); } } BuiltinScope declaredScope = BuiltinScope.from(declarativeAiServiceClassInfo); ScopeInfo cdiScope = declaredScope != null ? declaredScope.getInfo() : BuiltinScope.REQUEST.getInfo(); declarativeAiServiceProducer.produce( new DeclarativeAiServiceBuildItem( declarativeAiServiceClassInfo, chatLanguageModelSupplierClassDotName, toolDotNames, chatMemoryProviderSupplierClassDotName, retrieverSupplierClassDotName, auditServiceSupplierClassName, moderationModelSupplierClassName, cdiScope)); } if (needChatModelBean) { requestChatModelBeanProducer.produce(new RequestChatModelBeanBuildItem()); } if (needModerationModelBean) { requestModerationModelBeanProducer.produce(new RequestModerationModelBeanBuildItem()); } } private void validateSupplierAndRegisterForReflection(DotName supplierDotName, IndexView index, BuildProducer<ReflectiveClassBuildItem> producer) { ClassInfo classInfo = index.getClassByName(supplierDotName); if (classInfo == null) { log.warn("'" + supplierDotName.toString() + "' cannot be indexed"); // TODO: maybe this should be an error return; } if (!classInfo.hasNoArgsConstructor()) { throw new IllegalConfigurationException( "Class '" + supplierDotName.toString() + "' which must contain a no-args constructor."); } producer.produce(ReflectiveClassBuildItem.builder(supplierDotName.toString()).constructors(true).build()); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleDeclarativeServices(AiServicesRecorder recorder, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, Optional<SelectedChatModelProviderBuildItem> selectedChatModelProvider, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer, BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) { boolean needsChatModelBean = false; boolean needsChatMemoryProviderBean = false; boolean needsRetrieverBean = false; boolean needsAuditServiceBean = false; boolean needsModerationModelBean = false; Set<DotName> allToolNames = new HashSet<>(); for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) { ClassInfo declarativeAiServiceClassInfo = bi.getServiceClassInfo(); String serviceClassName = declarativeAiServiceClassInfo.name().toString(); String chatLanguageModelSupplierClassName = (bi.getLanguageModelSupplierClassDotName() != null ? bi.getLanguageModelSupplierClassDotName().toString() : null); List<String> toolClassNames = bi.getToolDotNames().stream().map(DotName::toString).collect(Collectors.toList()); String chatMemoryProviderSupplierClassName = bi.getChatMemoryProviderSupplierClassDotName() != null ? bi.getChatMemoryProviderSupplierClassDotName().toString() : null; String retrieverSupplierClassName = bi.getRetrieverSupplierClassDotName() != null ? bi.getRetrieverSupplierClassDotName().toString() : null; String auditServiceClassSupplierName = bi.getAuditServiceClassSupplierDotName() != null ? bi.getAuditServiceClassSupplierDotName().toString() : null; String moderationModelSupplierClassName = (bi.getModerationModelSupplierDotName() != null ? bi.getModerationModelSupplierDotName().toString() : null); SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem .configure(QuarkusAiServiceContext.class) .createWith(recorder.createDeclarativeAiService( new DeclarativeAiServiceCreateInfo(serviceClassName, chatLanguageModelSupplierClassName, toolClassNames, chatMemoryProviderSupplierClassName, retrieverSupplierClassName, auditServiceClassSupplierName, moderationModelSupplierClassName))) .setRuntimeInit() .addQualifier() .annotation(Langchain4jDotNames.QUARKUS_AI_SERVICE_CONTEXT_QUALIFIER).addValue("value", serviceClassName) .done() .scope(Dependent.class); if ((chatLanguageModelSupplierClassName == null) && selectedChatModelProvider.isPresent()) { // TODO: is second condition needed? configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MODEL)); needsChatModelBean = true; } if (!toolClassNames.isEmpty()) { for (String toolClassName : toolClassNames) { DotName dotName = DotName.createSimple(toolClassName); configurator.addInjectionPoint(ClassType.create(dotName)); allToolNames.add(dotName); } } if (Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER.toString().equals(chatMemoryProviderSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); needsChatMemoryProviderBean = true; } if (Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER.toString().equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null)); needsRetrieverBean = true; } else if (Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER.toString() .equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null) }, null)); needsRetrieverBean = true; } if (Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER.toString().equals(auditServiceClassSupplierName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ClassType.create(Langchain4jDotNames.AUDIT_SERVICE) }, null)); needsAuditServiceBean = true; } if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.toString().equals(moderationModelSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.MODERATION_MODEL)); needsModerationModelBean = true; } syntheticBeanProducer.produce(configurator.done()); } if (needsChatModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MODEL)); } if (needsChatMemoryProviderBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); } if (needsRetrieverBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.RETRIEVER)); } if (needsAuditServiceBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.AUDIT_SERVICE)); } if (needsModerationModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.MODERATION_MODEL)); } if (!allToolNames.isEmpty()) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames)); } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleAiServices(AiServicesRecorder recorder, CombinedIndexBuildItem indexBuildItem, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, BuildProducer<GeneratedClassBuildItem> generatedClassProducer, BuildProducer<GeneratedBeanBuildItem> generatedBeanProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, BuildProducer<AiServicesMethodBuildItem> aiServicesMethodProducer, BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer, Optional<MetricsCapabilityBuildItem> metricsCapability, Capabilities capabilities) { IndexView index = indexBuildItem.getIndex(); List<AiServicesUseAnalyzer.Result.Entry> aiServicesAnalysisResults = new ArrayList<>(); for (ClassInfo classInfo : index.getKnownUsers(Langchain4jDotNames.AI_SERVICES)) { String className = classInfo.name().toString(); if (className.startsWith("io.quarkiverse.langchain4j") || className.startsWith("dev.langchain4j")) { // TODO: this can be made smarter if needed continue; } try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( className.replace('.', '/') + ".class")) { if (is == null) { return; } var cn = new ClassNode(Gizmo.ASM_API_VERSION); var cr = new ClassReader(is); cr.accept(cn, 0); for (MethodNode method : cn.methods) { aiServicesAnalysisResults.addAll(AiServicesUseAnalyzer.analyze(cn, method).entries); } } catch (IOException e) { throw new UncheckedIOException("Reading bytecode of class '" + className + "' failed", e); } catch (AnalyzerException e) { log.debug("Unable to analyze bytecode of class '" + className + "'", e); } } Map<String, Boolean> nameToUsed = aiServicesAnalysisResults.stream() .collect(Collectors.toMap(e -> e.createdClassName, e -> e.chatMemoryProviderUsed, (u1, u2) -> u1 || u2)); for (var entry : nameToUsed.entrySet()) { String className = entry.getKey(); ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { continue; } if (!classInfo.annotations(Langchain4jDotNames.MEMORY_ID).isEmpty() && !entry.getValue()) { log.warn("Class '" + className + "' is used in AiServices and while it leverages @MemoryId, a ChatMemoryProvider has not been configured. This will likely result in an exception being thrown when the service is used."); } } Set<String> detectedForCreate = new HashSet<>(nameToUsed.keySet()); addCreatedAware(index, detectedForCreate); addIfacesWithMessageAnns(index, detectedForCreate); Set<String> registeredAiServiceClassNames = declarativeAiServiceItems.stream() .map(bi -> bi.getServiceClassInfo().name().toString()).collect( Collectors.toUnmodifiableSet()); detectedForCreate.addAll(registeredAiServiceClassNames); Set<ClassInfo> ifacesForCreate = new HashSet<>(); for (String className : detectedForCreate) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { log.warn("'" + className + "' used for creating an AiService was not found in the Quarkus index. Attempting to create " + "an AiService using this class will fail"); continue; } if (!classInfo.isInterface()) { log.warn("'" + className + "' used for creating an AiService is not an interface. Attempting to create an AiService " + "using this class will fail"); } ifacesForCreate.add(classInfo); } var addMicrometerMetrics = metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER); if (addMicrometerMetrics) { additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsTimedWrapper.class).build()); additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsCountedWrapper.class).build()); } var addOpenTelemetrySpan = capabilities.isPresent(Capability.OPENTELEMETRY_TRACER); if (addOpenTelemetrySpan) { additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(SpanWrapper.class).build()); } Map<String, AiServiceClassCreateInfo> perClassMetadata = new HashMap<>(); if (!ifacesForCreate.isEmpty()) { ClassOutput generatedClassOutput = new GeneratedClassGizmoAdaptor(generatedClassProducer, true); ClassOutput generatedBeanOutput = new GeneratedBeanGizmoAdaptor(generatedBeanProducer); for (ClassInfo iface : ifacesForCreate) { Set<MethodInfo> allMethods = new HashSet<>(iface.methods()); JandexUtil.getAllSuperinterfaces(iface, index).forEach(ci -> allMethods.addAll(ci.methods())); List<MethodInfo> methodsToImplement = new ArrayList<>(); Map<String, AiServiceMethodCreateInfo> perMethodMetadata = new HashMap<>(); for (MethodInfo method : allMethods) { short modifiers = method.flags(); if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers) || JandexUtil.isDefault( modifiers)) { continue; } methodsToImplement.add(method); } String ifaceName = iface.name().toString(); String implClassName = ifaceName + "$$QuarkusImpl"; boolean isRegisteredService = registeredAiServiceClassNames.contains(ifaceName); ClassCreator.Builder classCreatorBuilder = ClassCreator.builder() .classOutput(isRegisteredService ? generatedBeanOutput : generatedClassOutput) .className(implClassName) .interfaces(ifaceName, ChatMemoryRemovable.class.getName()); if (isRegisteredService) { classCreatorBuilder.interfaces(AutoCloseable.class); } try (ClassCreator classCreator = classCreatorBuilder.build()) { if (isRegisteredService) { // we need to make this a bean, so we need to add the proper scope annotation ScopeInfo scopeInfo = declarativeAiServiceItems.stream() .filter(bi -> bi.getServiceClassInfo().equals(iface)) .findFirst().orElseThrow(() -> new IllegalStateException( "Unable to determine the CDI scope of " + iface)) .getCdiScope(); classCreator.addAnnotation(scopeInfo.getDotName().toString()); } FieldDescriptor contextField = classCreator.getFieldCreator("context", QuarkusAiServiceContext.class) .setModifiers(Modifier.PRIVATE | Modifier.FINAL) .getFieldDescriptor(); for (MethodInfo methodInfo : methodsToImplement) { // The implementation essentially gets the context and delegates to // MethodImplementationSupport#implement String methodId = createMethodId(methodInfo); perMethodMetadata.put(methodId, gatherMethodMetadata(methodInfo, addMicrometerMetrics, addOpenTelemetrySpan)); { MethodCreator ctor = classCreator.getMethodCreator(MethodDescriptor.INIT, "V", QuarkusAiServiceContext.class); ctor.setModifiers(Modifier.PUBLIC); ctor.addAnnotation(Inject.class); ctor.getParameterAnnotations(0) .addAnnotation(Langchain4jDotNames.QUARKUS_AI_SERVICE_CONTEXT_QUALIFIER.toString()) .add("value", ifaceName); ctor.invokeSpecialMethod(OBJECT_CONSTRUCTOR, ctor.getThis()); ctor.writeInstanceField(contextField, ctor.getThis(), ctor.getMethodParam(0)); ctor.returnValue(null); } { MethodCreator noArgsCtor = classCreator.getMethodCreator(MethodDescriptor.INIT, "V"); noArgsCtor.setModifiers(Modifier.PUBLIC); noArgsCtor.invokeSpecialMethod(OBJECT_CONSTRUCTOR, noArgsCtor.getThis()); noArgsCtor.writeInstanceField(contextField, noArgsCtor.getThis(), noArgsCtor.loadNull()); noArgsCtor.returnValue(null); } { // actual method we need to implement MethodCreator mc = classCreator.getMethodCreator(MethodDescriptor.of(methodInfo)); // copy annotations for (AnnotationInstance annotationInstance : methodInfo.declaredAnnotations()) { // TODO: we need to review this if (annotationInstance.name().toString() .startsWith("org.eclipse.microprofile.faulttolerance")) { mc.addAnnotation(annotationInstance); } } ResultHandle contextHandle = mc.readInstanceField(contextField, mc.getThis()); ResultHandle methodCreateInfoHandle = mc.invokeStaticMethod(RECORDER_METHOD_CREATE_INFO, mc.load(ifaceName), mc.load(methodId)); ResultHandle paramsHandle = mc.newArray(Object.class, methodInfo.parametersCount()); for (int i = 0; i < methodInfo.parametersCount(); i++) { mc.writeArrayValue(paramsHandle, i, mc.getMethodParam(i)); } ResultHandle supportHandle = getFromCDI(mc, AiServiceMethodImplementationSupport.class.getName()); ResultHandle inputHandle = mc.newInstance( MethodDescriptor.ofConstructor(AiServiceMethodImplementationSupport.Input.class, QuarkusAiServiceContext.class, AiServiceMethodCreateInfo.class, Object[].class), contextHandle, methodCreateInfoHandle, paramsHandle); ResultHandle resultHandle = mc.invokeVirtualMethod(SUPPORT_IMPLEMENT, supportHandle, inputHandle); mc.returnValue(resultHandle); aiServicesMethodProducer.produce(new AiServicesMethodBuildItem(methodInfo)); } } if (isRegisteredService) { MethodCreator mc = classCreator.getMethodCreator( MethodDescriptor.ofMethod(implClassName, "close", void.class)); mc.addAnnotation(PreDestroy.class); ResultHandle contextHandle = mc.readInstanceField(contextField, mc.getThis()); mc.invokeVirtualMethod(QUARKUS_AI_SERVICES_CONTEXT_CLOSE, contextHandle); mc.returnVoid(); } { MethodCreator mc = classCreator.getMethodCreator( MethodDescriptor.ofMethod(implClassName, "remove", void.class, Object[].class)); ResultHandle contextHandle = mc.readInstanceField(contextField, mc.getThis()); mc.invokeVirtualMethod(QUARKUS_AI_SERVICES_CONTEXT_REMOVE_CHAT_MEMORY_IDS, contextHandle, mc.getMethodParam(0)); mc.returnVoid(); } } perClassMetadata.put(ifaceName, new AiServiceClassCreateInfo(perMethodMetadata, implClassName)); // make the constructor accessible reflectively since that is how we create the instance reflectiveClassProducer.produce(ReflectiveClassBuildItem.builder(implClassName).build()); } } recorder.setMetadata(perClassMetadata); } private ResultHandle getFromCDI(MethodCreator mc, String className) { ResultHandle containerHandle = mc .invokeStaticMethod(MethodDescriptor.ofMethod(Arc.class, "container", ArcContainer.class)); ResultHandle instanceHandle = mc.invokeInterfaceMethod( MethodDescriptor.ofMethod(ArcContainer.class, "instance", InstanceHandle.class, Class.class, Annotation[].class), containerHandle, mc.loadClassFromTCCL(className), mc.newArray(Annotation.class, 0)); return mc.invokeInterfaceMethod(MethodDescriptor.ofMethod(InstanceHandle.class, "get", Object.class), instanceHandle); } private String createMethodId(MethodInfo methodInfo) { return methodInfo.name() + '(' + Arrays.toString(methodInfo.parameters().stream().map(mp -> mp.type().name().toString()).toArray()) + ')'; } private void addIfacesWithMessageAnns(IndexView index, Set<String> detectedForCreate) { List<DotName> annotations = List.of(Langchain4jDotNames.SYSTEM_MESSAGE, Langchain4jDotNames.USER_MESSAGE, Langchain4jDotNames.MODERATE); for (DotName annotation : annotations) { Collection<AnnotationInstance> instances = index.getAnnotations(annotation); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.METHOD) { continue; } ClassInfo declaringClass = instance.target().asMethod().declaringClass(); if (declaringClass.isInterface()) { detectedForCreate.add(declaringClass.name().toString()); } } } } private static void addCreatedAware(IndexView index, Set<String> detectedForCreate) { Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.CREATED_AWARE); for (var instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; } detectedForCreate.add(instance.target().asClass().name().toString()); } } private AiServiceMethodCreateInfo gatherMethodMetadata(MethodInfo method, boolean addMicrometerMetrics, boolean addOpenTelemetrySpans) { if (method.returnType().kind() == Type.Kind.VOID) { throw illegalConfiguration("Return type of method '%s' cannot be void", method); } boolean requiresModeration = method.hasAnnotation(Langchain4jDotNames.MODERATE); List<MethodParameterInfo> params = method.parameters(); List<TemplateParameterInfo> templateParams = gatherTemplateParamInfo(params); Optional<AiServiceMethodCreateInfo.TemplateInfo> systemMessageInfo = gatherSystemMessageInfo(method, templateParams); Class<?> returnType = JandexUtil.load(method.returnType(), Thread.currentThread().getContextClassLoader()); AiServiceMethodCreateInfo.UserMessageInfo userMessageInfo = gatherUserMessageInfo(method, templateParams, returnType); Optional<Integer> memoryIdParamPosition = gatherMemoryIdParamName(method); Optional<AiServiceMethodCreateInfo.MetricsTimedInfo> metricsTimedInfo = gatherMetricsTimedInfo(method, addMicrometerMetrics); Optional<AiServiceMethodCreateInfo.MetricsCountedInfo> metricsCountedInfo = gatherMetricsCountedInfo(method, addMicrometerMetrics); Optional<AiServiceMethodCreateInfo.SpanInfo> spanInfo = gatherSpanInfo(method, addOpenTelemetrySpans); return new AiServiceMethodCreateInfo(method.declaringClass().name().toString(), method.name(), systemMessageInfo, userMessageInfo, memoryIdParamPosition, requiresModeration, returnType, metricsTimedInfo, metricsCountedInfo, spanInfo); } private List<TemplateParameterInfo> gatherTemplateParamInfo(List<MethodParameterInfo> params) { if (params.isEmpty()) { return Collections.emptyList(); } List<TemplateParameterInfo> templateParams = new ArrayList<>(); for (MethodParameterInfo param : params) { if (effectiveParamAnnotations(param).isEmpty()) { // if a parameter has no annotations it is considered a template variable templateParams.add(new TemplateParameterInfo(param.position(), param.name())); } else { AnnotationInstance vInstance = param.annotation(V); if (vInstance != null) { AnnotationValue value = vInstance.value(); if (value != null) { templateParams.add(new TemplateParameterInfo(param.position(), value.asString())); } } } } if ((templateParams.size() == 1) && (params.size() == 1)) { // the special 'it' param is supported when the method only has one parameter templateParams.add(new TemplateParameterInfo(0, "it")); } return templateParams; } private List<AnnotationInstance> effectiveParamAnnotations(MethodParameterInfo param) { return param.annotations().stream().filter(ai -> { String name = ai.name().toString(); if (name.startsWith("kotlin") || name.startsWith("jakarta.validation.constraints")) { return false; } if (name.endsWith("NotNull")) { return false; } if (name.startsWith("io.opentelemetry")) { return false; } return true; }).collect(Collectors.toList()); } private Optional<AiServiceMethodCreateInfo.TemplateInfo> gatherSystemMessageInfo(MethodInfo method, List<TemplateParameterInfo> templateParams) { AnnotationInstance instance = method.annotation(Langchain4jDotNames.SYSTEM_MESSAGE); if (instance != null) { String systemMessageTemplate = ""; AnnotationValue delimiterValue = instance.value("delimiter"); String delimiter = delimiterValue != null ? delimiterValue.asString() : DEFAULT_DELIMITER; AnnotationValue value = instance.value(); if (value != null) { systemMessageTemplate = String.join(delimiter, value.asStringArray()); } if (systemMessageTemplate.isEmpty()) {
throw illegalConfigurationForMethod("@SystemMessage's template parameter cannot be empty", method);
0
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/com/qingfeng/clinglibrary/service/manager/ClingManager.java
[ { "identifier": "ClingControlPoint", "path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/entity/ClingControlPoint.java", "snippet": "public class ClingControlPoint implements IControlPoint<ControlPoint> {\n\n private static ClingControlPoint INSTANCE = null;\n private ControlPoint mContr...
import android.content.Context; import androidx.annotation.Nullable; import com.qingfeng.clinglibrary.entity.ClingControlPoint; import com.qingfeng.clinglibrary.entity.ClingDevice; import com.qingfeng.clinglibrary.entity.IControlPoint; import com.qingfeng.clinglibrary.entity.IDevice; import com.qingfeng.clinglibrary.service.ClingUpnpService; import com.qingfeng.clinglibrary.util.ListUtils; import com.qingfeng.clinglibrary.util.Utils; import org.fourthline.cling.model.meta.Device; import org.fourthline.cling.model.types.DeviceType; import org.fourthline.cling.model.types.ServiceType; import org.fourthline.cling.model.types.UDADeviceType; import org.fourthline.cling.model.types.UDAServiceType; import org.fourthline.cling.registry.Registry; import java.util.ArrayList; import java.util.Collection;
12,564
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null; private ClingUpnpService mUpnpService; public IDeviceManager getDeviceManager() { return mDeviceManager; } private IDeviceManager mDeviceManager; // private SystemService mSystemService; private ClingManager() { } public static ClingManager getInstance() { if (Utils.isNull(INSTANCE)) { INSTANCE = new ClingManager(); } return INSTANCE; } @Override public void searchDevices() { if (!Utils.isNull(mUpnpService)) { mUpnpService.getControlPoint().search(); } } @Override @Nullable public Collection<ClingDevice> getDmrDevices() { if (Utils.isNull(mUpnpService)) { return null; } Collection<Device> devices = mUpnpService.getRegistry().getDevices(DMR_DEVICE_TYPE); if (ListUtils.isEmpty(devices)) { return null; } Collection<ClingDevice> clingDevices = new ArrayList<>(); for (Device device : devices) { ClingDevice clingDevice = new ClingDevice(device); clingDevices.add(clingDevice); } return clingDevices; } @Override @Nullable public IControlPoint getControlPoint() { if (Utils.isNull(mUpnpService)) { return null; } ClingControlPoint.getInstance().setControlPoint(mUpnpService.getControlPoint()); return ClingControlPoint.getInstance(); } @Override
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null; private ClingUpnpService mUpnpService; public IDeviceManager getDeviceManager() { return mDeviceManager; } private IDeviceManager mDeviceManager; // private SystemService mSystemService; private ClingManager() { } public static ClingManager getInstance() { if (Utils.isNull(INSTANCE)) { INSTANCE = new ClingManager(); } return INSTANCE; } @Override public void searchDevices() { if (!Utils.isNull(mUpnpService)) { mUpnpService.getControlPoint().search(); } } @Override @Nullable public Collection<ClingDevice> getDmrDevices() { if (Utils.isNull(mUpnpService)) { return null; } Collection<Device> devices = mUpnpService.getRegistry().getDevices(DMR_DEVICE_TYPE); if (ListUtils.isEmpty(devices)) { return null; } Collection<ClingDevice> clingDevices = new ArrayList<>(); for (Device device : devices) { ClingDevice clingDevice = new ClingDevice(device); clingDevices.add(clingDevice); } return clingDevices; } @Override @Nullable public IControlPoint getControlPoint() { if (Utils.isNull(mUpnpService)) { return null; } ClingControlPoint.getInstance().setControlPoint(mUpnpService.getControlPoint()); return ClingControlPoint.getInstance(); } @Override
public Registry getRegistry() {
12
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/FavorManager.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import lombok.Getter; import lombok.Setter; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.storage.DevotionStorage; import me.xidentified.devotions.util.FavorUtils; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID;
11,493
package me.xidentified.devotions.managers; // Point system for tracking favor with each deity public class FavorManager { // Basic details @Getter private final Devotions plugin; @Getter private final UUID uuid;
package me.xidentified.devotions.managers; // Point system for tracking favor with each deity public class FavorManager { // Basic details @Getter private final Devotions plugin; @Getter private final UUID uuid;
@Getter @Setter private Deity deity;
0
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/JobService.java
[ { "identifier": "JOB_STATUS_STOP", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java", "snippet": "public static final int JOB_STATUS_STOP = 5;" }, { "identifier": "JOB_STATUS_SYNC", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constant...
import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_STOP; import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_SYNC; import static com.datalinkx.common.utils.IdUtils.genKey; import static com.datalinkx.common.utils.JsonUtils.toJson; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Resource; import com.datalinkx.common.constants.MessageHubConstants; import com.datalinkx.common.constants.MetaConstants; import com.datalinkx.driver.dsdriver.DsDriverFactory; import com.datalinkx.driver.dsdriver.IDsReader; import com.datalinkx.driver.dsdriver.base.model.TableField; import com.datalinkx.driver.model.DataTransJobDetail; import com.datalinkx.common.result.StatusCode; import com.datalinkx.common.utils.JsonUtils; import com.datalinkx.dataserver.bean.domain.DsBean; import com.datalinkx.dataserver.bean.domain.DsTbBean; import com.datalinkx.dataserver.bean.domain.JobBean; import com.datalinkx.dataserver.bean.domain.JobLogBean; import com.datalinkx.dataserver.bean.dto.JobDto; import com.datalinkx.dataserver.bean.vo.JobVo; import com.datalinkx.dataserver.bean.vo.PageVo; import com.datalinkx.dataserver.client.xxljob.JobClientApi; import com.datalinkx.dataserver.client.xxljob.request.DataTransJobParam; import com.datalinkx.dataserver.controller.form.JobForm; import com.datalinkx.dataserver.controller.form.JobStateForm; import com.datalinkx.common.exception.DatalinkXServerException; import com.datalinkx.dataserver.repository.DsRepository; import com.datalinkx.dataserver.repository.DsTbRepository; import com.datalinkx.dataserver.repository.JobLogRepository; import com.datalinkx.dataserver.repository.JobRepository; import com.datalinkx.dataserver.service.DtsJobService; import com.datalinkx.messagehub.bean.form.ProducerAdapterForm; import com.datalinkx.messagehub.service.MessageHubService; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils;
12,113
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired JobClientApi jobClientApi; @Resource(name = "messageHubServiceImpl") MessageHubService messageHubService; @Transactional(rollbackFor = Exception.class) public String jobCreate(JobForm.JobCreateForm form) { this.validJobForm(form); String jobId = genKey("job"); JobBean jobBean = new JobBean(); jobBean.setJobId(jobId); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setStatus(MetaConstants.JobStatus.JOB_TABLE_CREATE); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); // 创建 xxljob String xxlJobId = jobClientApi.add(jobId, form.getSchedulerConf(), DataTransJobParam.builder().jobId(jobId).build()); jobBean.setXxlId(xxlJobId); jobRepository.save(jobBean); return jobId; } public String jobModify(JobForm.JobModifyForm form) { this.validJobForm(form); JobBean jobBean = jobRepository.findByJobId(form.getJobId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); jobRepository.save(jobBean); return form.getJobId(); } private void validJobForm(JobForm.JobCreateForm form) { DsBean fromDsBean = dsRepository.findByDsId(form.getFromDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "来源数据源不存在")); DsBean toBean = dsRepository.findByDsId(form.getToDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "目标数据源不存在")); if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode()) && ObjectUtils.isEmpty(form.getSyncMode().getIncreateField())) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, "增量模式必须指定增量字段"); } if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode())) { try {
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired JobClientApi jobClientApi; @Resource(name = "messageHubServiceImpl") MessageHubService messageHubService; @Transactional(rollbackFor = Exception.class) public String jobCreate(JobForm.JobCreateForm form) { this.validJobForm(form); String jobId = genKey("job"); JobBean jobBean = new JobBean(); jobBean.setJobId(jobId); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setStatus(MetaConstants.JobStatus.JOB_TABLE_CREATE); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); // 创建 xxljob String xxlJobId = jobClientApi.add(jobId, form.getSchedulerConf(), DataTransJobParam.builder().jobId(jobId).build()); jobBean.setXxlId(xxlJobId); jobRepository.save(jobBean); return jobId; } public String jobModify(JobForm.JobModifyForm form) { this.validJobForm(form); JobBean jobBean = jobRepository.findByJobId(form.getJobId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); jobRepository.save(jobBean); return form.getJobId(); } private void validJobForm(JobForm.JobCreateForm form) { DsBean fromDsBean = dsRepository.findByDsId(form.getFromDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "来源数据源不存在")); DsBean toBean = dsRepository.findByDsId(form.getToDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "目标数据源不存在")); if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode()) && ObjectUtils.isEmpty(form.getSyncMode().getIncreateField())) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, "增量模式必须指定增量字段"); } if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode())) { try {
IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(fromDsBean));
6
2023-11-16 02:22:52+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/runner/DiffRunner.java
[ { "identifier": "Constants", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/Constants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Constants {\n\n public static final String ROOT_PACKAGE = \"com.exadel.etoolbox.anydiff\";\n\n public static final int DE...
import com.exadel.etoolbox.anydiff.Constants; import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.comparison.DiffTask; import com.exadel.etoolbox.anydiff.comparison.Marker; import com.exadel.etoolbox.anydiff.comparison.TaskParameters; import com.exadel.etoolbox.anydiff.diff.Diff; import com.exadel.etoolbox.anydiff.diff.DiffEntry; import com.exadel.etoolbox.anydiff.diff.DiffState; import com.exadel.etoolbox.anydiff.filter.Filter; import com.exadel.etoolbox.anydiff.util.ContentUtil; import lombok.AccessLevel; import lombok.Getter; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors;
11,815
.leftId(left) .leftLabel(getLeftLabel()) .leftContent(Marker.PLACEHOLDER.wrap(left)) .rightId(right.getPath()) .rightLabel(getRightLabel()) .rightContent(right) .taskParameters(getTaskParameters()) .anticipatedState(DiffState.CHANGE) .build() .run(); } /* --------------- Factory methods --------------- */ /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled string arrays * @param left An array of strings that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right An array of strings that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ public static DiffRunner forValues(String[] left, String leftLabel, String[] right, String rightLabel) { if (ArrayUtils.isEmpty(left) || ArrayUtils.isEmpty(right)) { return EMPTY; } DiffRunner result = new StringListRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled strings * @param left A string that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right A string that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ static DiffRunner forValues(String left, String leftLabel, String right, String rightLabel) { if (StringUtils.isAnyBlank(left, right)) { return EMPTY; } DiffRunner result; if (isHttpEndpoint(left) && isHttpEndpoint(right)) { result = new HttpRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; } else if (isFile(left) && isFile(right)) { Path currentFolder = Paths.get(StringUtils.EMPTY); result = forValues( currentFolder.resolve(left).toFile().toPath(), leftLabel, currentFolder.resolve(right).toFile().toPath(), rightLabel); } else { result = new SimpleRunner(left, right); result.contentType = ContentType.TEXT; result.leftLabel = leftLabel; result.rightLabel = rightLabel; } return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled {@link Path} arrays * @param left An array of {@code Path} objects that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right An array of {@code Path} objects that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ public static DiffRunner forValues(Path[] left, String leftLabel, Path[] right, String rightLabel) { if (ArrayUtils.isEmpty(left) || ArrayUtils.isEmpty(right)) { return EMPTY; } DiffRunner result = new PathListRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled {@link Path} objects * @param left A {@code Path} object that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right A {@code Path} object that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ static DiffRunner forValues(Path left, String leftLabel, Path right, String rightLabel) { if (left == null || right == null) { return EMPTY; } DiffRunner result = null; if (Files.isDirectory(left) && Files.isDirectory(right)) { result = new DirectoryRunner(left, right); } else if (Files.isRegularFile(left) && Files.isRegularFile(right)) { if (StringUtils.endsWithAny(left.toString().toLowerCase(), ".list", ".lst") && StringUtils.endsWithAny(right.toString().toLowerCase(), ".list", ".lst")) { result = new FileListingRunner(left, right); } else if (StringUtils.endsWithAny(left.toString().toLowerCase(), ".zip", ".jar") && StringUtils.endsWithAny(right.toString().toLowerCase(), ".zip", ".jar")) { result = new ArchiveRunner(left, right); } else { result = new FileRunner(left, right); } } if (result != null) { result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } return EMPTY; } private static boolean isHttpEndpoint(String value) {
/* * 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.exadel.etoolbox.anydiff.runner; /** * Extracts the data from the given sources and invokes the comparison routine * <u>Note</u>: This class is not a part of public API and is subject to change. You should not use it directly * @see DiffTask */ public abstract class DiffRunner { private static final DiffRunner EMPTY = new DiffRunner() { @Override public List<Diff> runInternal() { return Collections.emptyList(); } }; private String leftLabel; private String rightLabel; private Predicate<Diff> diffFilter; /** * Gets the {@code Predicate} instance that represents the aggregate filter for the results of the comparison */ @Getter(value = AccessLevel.PACKAGE) private Predicate<DiffEntry> entryFilter; private ContentType contentType; /** * Gets the parameters that control the execution of a {@link DiffTask} */ @Getter(value = AccessLevel.PACKAGE) private TaskParameters taskParameters; /* ---------- Properties ---------- */ /** * Gets the {@code ContentType} instance that represents the content type of the data to be compared * @return {@code ContentType} object */ public ContentType getContentType() { return contentType != null ? contentType : ContentType.UNDEFINED; } /** * Gets the label for the left side of the comparison * @return A non-blank {@code String} value */ String getLeftLabel() { return StringUtils.defaultIfBlank(leftLabel, Constants.LABEL_LEFT); } /** * Gets the label for the right side of the comparison * @return A non-blank {@code String} value */ String getRightLabel() { return StringUtils.defaultIfBlank(rightLabel, Constants.LABEL_RIGHT); } /** * Assigns a collection of {@link Filter} instances that are used to produce the aggregate filter for the results * of the comparison. One can use either this method or {@link #withEntryFilter(Predicate)} to set the filter * @param filters {@code List} of {@code Filter} objects. A non-null value is expected * @return Current instance */ public DiffRunner withFilters(List<Filter> filters) { diffFilter = FilterHelper.getDiffFilter(filters); entryFilter = FilterHelper.getEntryFilter(filters); return this; } /** * Assigns a {@link Predicate} instance that is used to filter the results of the comparison. One can use either * this method or {@link #withFilters(List)} to set the filter * @param entryFilter {@code Predicate} object. A non-null value is expected * @return Current instance */ DiffRunner withEntryFilter(Predicate<DiffEntry> entryFilter) { this.entryFilter = entryFilter; return this; } /** * Assigns a {@link ContentType} instance that represents the content type of the data to be compared * @param contentType {@code ContentType} object. A non-null value is expected * @return Current instance */ public DiffRunner withContentType(ContentType contentType) { this.contentType = contentType; return this; } /** * Assigns a {@link com.exadel.etoolbox.anydiff.comparison.TaskParameters} instance that represents the * conversion/formatting rules for the comparison * @param parameters {@code TaskParameters} object. A non-null value is expected * @return Current instance */ public DiffRunner withTaskParameters(TaskParameters parameters) { this.taskParameters = parameters; return this; } /* --------- Execution --------- */ /** * Runs the data collection and subsequently invokes the comparison routine. The results are filtered according to * the previously assigned {@code Predicate} * @return A non-null list of {@link Diff} objects. Can be empty */ public List<Diff> run() { return runInternal().stream().filter(diffFilter != null ? diffFilter : e -> true).collect(Collectors.toList()); } /** * When overridden in a derived class, runs the data collection and invokes the comparison routine * @return An unfiltered list of {@link Diff} objects that are then passed to the {@link #run()} method */ abstract List<Diff> runInternal(); /** * Shortcuts the comparison for the case when the left part of the comparison is missing * @param left An identifier of the left side of the comparison * @param right An identifier of the right side of the comparison * @return A {@link Diff} object representing the result of the comparison */ Diff reportLeftMissing(String left, String right) { return DiffTask .builder() .leftId(left) .leftLabel(getLeftLabel()) .rightId(right) .rightLabel(getRightLabel()) .rightContent(right) .taskParameters(getTaskParameters()) .anticipatedState(DiffState.LEFT_MISSING) .build() .run(); } /** * Shortcuts the comparison for the case when the right part of the comparison is missing * @param left An identifier of the left side of the comparison * @param right An identifier of the right side of the comparison * @return A {@link Diff} object representing the result of the comparison */ Diff reportRightMissing(String left, String right) { return DiffTask .builder() .leftId(left) .leftLabel(getLeftLabel()) .leftContent(left) .rightId(right) .rightLabel(getRightLabel()) .taskParameters(getTaskParameters()) .anticipatedState(DiffState.RIGHT_MISSING) .build() .run(); } /** * Shortcuts the comparison for the case when the left and right parts of the comparison represent the content of a * file that has been moved * @param left An identifier of the left side of the comparison * @param right An identifier of the right side of the comparison * @return A {@link Diff} object representing the result of the comparison */ Diff reportMoved(String left, FileMoveInfo right) { return DiffTask .builder() .leftId(left) .leftLabel(getLeftLabel()) .leftContent(Marker.PLACEHOLDER.wrap(left)) .rightId(right.getPath()) .rightLabel(getRightLabel()) .rightContent(right) .taskParameters(getTaskParameters()) .anticipatedState(DiffState.CHANGE) .build() .run(); } /* --------------- Factory methods --------------- */ /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled string arrays * @param left An array of strings that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right An array of strings that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ public static DiffRunner forValues(String[] left, String leftLabel, String[] right, String rightLabel) { if (ArrayUtils.isEmpty(left) || ArrayUtils.isEmpty(right)) { return EMPTY; } DiffRunner result = new StringListRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled strings * @param left A string that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right A string that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ static DiffRunner forValues(String left, String leftLabel, String right, String rightLabel) { if (StringUtils.isAnyBlank(left, right)) { return EMPTY; } DiffRunner result; if (isHttpEndpoint(left) && isHttpEndpoint(right)) { result = new HttpRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; } else if (isFile(left) && isFile(right)) { Path currentFolder = Paths.get(StringUtils.EMPTY); result = forValues( currentFolder.resolve(left).toFile().toPath(), leftLabel, currentFolder.resolve(right).toFile().toPath(), rightLabel); } else { result = new SimpleRunner(left, right); result.contentType = ContentType.TEXT; result.leftLabel = leftLabel; result.rightLabel = rightLabel; } return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled {@link Path} arrays * @param left An array of {@code Path} objects that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right An array of {@code Path} objects that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ public static DiffRunner forValues(Path[] left, String leftLabel, Path[] right, String rightLabel) { if (ArrayUtils.isEmpty(left) || ArrayUtils.isEmpty(right)) { return EMPTY; } DiffRunner result = new PathListRunner(left, right); result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } /** * Creates a {@link DiffRunner} instance that corresponds to the specified labeled {@link Path} objects * @param left A {@code Path} object that represents the left side of the comparison * @param leftLabel The label for the left side of the comparison * @param right A {@code Path} object that represents the right side of the comparison * @param rightLabel The label for the right side of the comparison * @return A {@code DiffRunner} instance */ static DiffRunner forValues(Path left, String leftLabel, Path right, String rightLabel) { if (left == null || right == null) { return EMPTY; } DiffRunner result = null; if (Files.isDirectory(left) && Files.isDirectory(right)) { result = new DirectoryRunner(left, right); } else if (Files.isRegularFile(left) && Files.isRegularFile(right)) { if (StringUtils.endsWithAny(left.toString().toLowerCase(), ".list", ".lst") && StringUtils.endsWithAny(right.toString().toLowerCase(), ".list", ".lst")) { result = new FileListingRunner(left, right); } else if (StringUtils.endsWithAny(left.toString().toLowerCase(), ".zip", ".jar") && StringUtils.endsWithAny(right.toString().toLowerCase(), ".zip", ".jar")) { result = new ArchiveRunner(left, right); } else { result = new FileRunner(left, right); } } if (result != null) { result.leftLabel = leftLabel; result.rightLabel = rightLabel; return result; } return EMPTY; } private static boolean isHttpEndpoint(String value) {
if (!ContentUtil.isPathLike(value, true)) {
9
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/screen/AttachmentScreen.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.gui.screen.inventory.InventoryScreen; import net.minecraft.client.network.play.ClientPlayNetHandler; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Inventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Quaternion; import net.minecraft.util.math.vector.Vector3f; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import org.lwjgl.opengl.GL11; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.container.AttachmentContainer; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.IGenericAttachment; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.network.PacketHandler; import sheridan.gunscraft.network.packets.GiveBackItemPacket; import sheridan.gunscraft.network.packets.SetAttachmentPacket; import java.util.List;
13,616
package sheridan.gunscraft.screen; public class AttachmentScreen extends ContainerScreen<AttachmentContainer> { public static final ResourceLocation BACK_GROUND = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/attachment_screen.png"); private static final ResourceLocation DRAG_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/drag_button.png"); private static final ResourceLocation RESET_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/reset_button.png"); private final TranslationTextComponent title = new TranslationTextComponent("container.gunscraft.attachments"); private ItemStack heldStack; @Override public void onClose() { if (attachmentInventory != null) { ItemStack attachment = attachmentInventory.getStackInSlot(0); if (!attachment.isEmpty()) { PacketHandler.CommonChannel.sendToServer(new GiveBackItemPacket(Item.getIdFromItem(attachment.getItem()), attachment.getCount())); } } super.onClose(); } private IInventory inventory; private IInventory attachmentInventory; private List<GunAttachmentSlot> slots; private int selectedIndex = 0; private GunAttachmentSlot selectedSlot; private IGenericGun gun; private int maxIndex; private AttachmentContainer container; private boolean isMouseDruggingModel = false; private float modelRX; private float modelRY; private float tempModelRX; private float tempModelRY; private float dragStartX; private float dragStartY; private float dragX; private float dragY; private float tempDragX; private float tempDragY; private float scaleZoom; private float zoomMax = 50f; private float zoomMin = -50f; private boolean isResetBtnDown = false; private boolean isDragBtnDown = false; public AttachmentScreen(AttachmentContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); this.inventory = screenContainer.playerInventory; this.attachmentInventory = screenContainer.attachmentInventory; this.container = screenContainer; } @Override public boolean mouseScrolled(double mouseX, double mouseY, double delta) { if (isMouseInModelArea(mouseX, mouseY)) { scaleZoom += delta; if (scaleZoom > zoomMax) { scaleZoom = zoomMax; } if (scaleZoom < zoomMin) { scaleZoom = zoomMin; } return false; } return super.mouseScrolled(mouseX, mouseY, delta); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (slots != null && slots.size() >= 1) { switch (keyCode) { case 263: selectedIndex = selectedIndex - 1 < 0 ? maxIndex : selectedIndex - 1; break; case 262: selectedIndex ++; break; case 265: handleAttachmentChange(true); break; case 264: handleAttachmentChange(false); break; } } return super.keyPressed(keyCode, scanCode, modifiers); } private void handleAttachmentChange(boolean install) { if (install) { ItemStack stack = attachmentInventory.getStackInSlot(0); System.out.println("000"); if (stack.getItem() instanceof IGenericAttachment) { System.out.println("111"); IGenericAttachment attachment = (IGenericAttachment) stack.getItem(); String slotName = selectedSlot.name; ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem();
package sheridan.gunscraft.screen; public class AttachmentScreen extends ContainerScreen<AttachmentContainer> { public static final ResourceLocation BACK_GROUND = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/attachment_screen.png"); private static final ResourceLocation DRAG_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/drag_button.png"); private static final ResourceLocation RESET_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/reset_button.png"); private final TranslationTextComponent title = new TranslationTextComponent("container.gunscraft.attachments"); private ItemStack heldStack; @Override public void onClose() { if (attachmentInventory != null) { ItemStack attachment = attachmentInventory.getStackInSlot(0); if (!attachment.isEmpty()) { PacketHandler.CommonChannel.sendToServer(new GiveBackItemPacket(Item.getIdFromItem(attachment.getItem()), attachment.getCount())); } } super.onClose(); } private IInventory inventory; private IInventory attachmentInventory; private List<GunAttachmentSlot> slots; private int selectedIndex = 0; private GunAttachmentSlot selectedSlot; private IGenericGun gun; private int maxIndex; private AttachmentContainer container; private boolean isMouseDruggingModel = false; private float modelRX; private float modelRY; private float tempModelRX; private float tempModelRY; private float dragStartX; private float dragStartY; private float dragX; private float dragY; private float tempDragX; private float tempDragY; private float scaleZoom; private float zoomMax = 50f; private float zoomMin = -50f; private boolean isResetBtnDown = false; private boolean isDragBtnDown = false; public AttachmentScreen(AttachmentContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); this.inventory = screenContainer.playerInventory; this.attachmentInventory = screenContainer.attachmentInventory; this.container = screenContainer; } @Override public boolean mouseScrolled(double mouseX, double mouseY, double delta) { if (isMouseInModelArea(mouseX, mouseY)) { scaleZoom += delta; if (scaleZoom > zoomMax) { scaleZoom = zoomMax; } if (scaleZoom < zoomMin) { scaleZoom = zoomMin; } return false; } return super.mouseScrolled(mouseX, mouseY, delta); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (slots != null && slots.size() >= 1) { switch (keyCode) { case 263: selectedIndex = selectedIndex - 1 < 0 ? maxIndex : selectedIndex - 1; break; case 262: selectedIndex ++; break; case 265: handleAttachmentChange(true); break; case 264: handleAttachmentChange(false); break; } } return super.keyPressed(keyCode, scanCode, modifiers); } private void handleAttachmentChange(boolean install) { if (install) { ItemStack stack = attachmentInventory.getStackInSlot(0); System.out.println("000"); if (stack.getItem() instanceof IGenericAttachment) { System.out.println("111"); IGenericAttachment attachment = (IGenericAttachment) stack.getItem(); String slotName = selectedSlot.name; ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem();
if (NBTAttachmentsMap.set(slotName, attachment.getID(), gunStack, gun) != null) {
6
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKExplorerFragment.java
[ { "identifier": "TextEditorActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/TextEditorActivity.java", "snippet": "public class TextEditorActivity extends AppCompatActivity {\n\n private static final String find0 = \"android:extractNativeLibs=\\\"false\\\"\";\n private st...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.TextEditorActivity; import com.threethan.questpatcher.adapters.APKExplorerAdapter; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.DeleteFile; import com.threethan.questpatcher.utils.tasks.DeleteProject; import com.threethan.questpatcher.utils.tasks.ExportToStorage; import com.threethan.questpatcher.utils.tasks.SignAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textview.MaterialTextView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PermissionUtils.sPermissionUtils;
11,334
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 05, 2021 */ public class APKExplorerFragment extends androidx.fragment.app.Fragment { private MaterialTextView mTitle; private LinearLayoutCompat mProgressLayout; private RecyclerView mRecyclerView; private APKExplorerAdapter mRecycleViewAdapter; private AppCompatImageButton saveBtn; public static APKExplorerFragment current; public void fail() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.already_patched)); alertDialog.show(); } public void failManifest() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.no_manifest)); alertDialog.show(); } public void succeed() { saveBtn.callOnClick(); } @SuppressLint("StringFormatInvalid") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); } mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), APKExplorer.getSpanCount(requireActivity()))); // CHANGED: AUTOMATE current = this; Intent amintent; boolean hasOpened = false; amintent = new Intent(requireActivity(), TextEditorActivity.class); for (String file : APKExplorer.getData(getFilesList(), true, requireActivity())) { if (file != null && file.endsWith("AndroidManifest.xml")) { amintent.putExtra(TextEditorActivity.PATH_INTENT, file); startActivity(amintent); hasOpened = true; break; } } // succeed(); if (!hasOpened) failManifest(); mSortButton.setOnClickListener(v -> { PopupMenu popupMenu = new PopupMenu(requireActivity(), mSortButton); Menu menu = popupMenu.getMenu(); menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true) .setChecked(sCommonUtils.getBoolean("az_order", true, requireActivity())); if (Common.getFiles() != null && Common.getFiles().size() > 0) { menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.export_selected_files)); if (APKEditorUtils.isFullVersion(requireActivity())) { menu.add(Menu.NONE, 2, Menu.NONE, getString(R.string.delete_selected_files)); } } if (APKEditorUtils.isFullVersion(requireActivity()) && !Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { menu.add(Menu.NONE, 3, Menu.NONE, getString(R.string.delete_folder)); } popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == 0) { sCommonUtils.saveBoolean("az_order", !sCommonUtils.getBoolean("az_order", true, requireActivity()), requireActivity()); reload(requireActivity()); } else if (item.getItemId() == 1) { if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, v.getContext())) { sPermissionUtils.requestPermission( new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, (Activity) v.getContext()); } else { new ExportToStorage(null, Common.getFiles(), Common.getAppID(), requireActivity()).execute(); } } else if (item.getItemId() == 2) { for (File file : Common.getFiles()) { if (file.exists()) {
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 05, 2021 */ public class APKExplorerFragment extends androidx.fragment.app.Fragment { private MaterialTextView mTitle; private LinearLayoutCompat mProgressLayout; private RecyclerView mRecyclerView; private APKExplorerAdapter mRecycleViewAdapter; private AppCompatImageButton saveBtn; public static APKExplorerFragment current; public void fail() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.already_patched)); alertDialog.show(); } public void failManifest() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.no_manifest)); alertDialog.show(); } public void succeed() { saveBtn.callOnClick(); } @SuppressLint("StringFormatInvalid") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); } mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), APKExplorer.getSpanCount(requireActivity()))); // CHANGED: AUTOMATE current = this; Intent amintent; boolean hasOpened = false; amintent = new Intent(requireActivity(), TextEditorActivity.class); for (String file : APKExplorer.getData(getFilesList(), true, requireActivity())) { if (file != null && file.endsWith("AndroidManifest.xml")) { amintent.putExtra(TextEditorActivity.PATH_INTENT, file); startActivity(amintent); hasOpened = true; break; } } // succeed(); if (!hasOpened) failManifest(); mSortButton.setOnClickListener(v -> { PopupMenu popupMenu = new PopupMenu(requireActivity(), mSortButton); Menu menu = popupMenu.getMenu(); menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true) .setChecked(sCommonUtils.getBoolean("az_order", true, requireActivity())); if (Common.getFiles() != null && Common.getFiles().size() > 0) { menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.export_selected_files)); if (APKEditorUtils.isFullVersion(requireActivity())) { menu.add(Menu.NONE, 2, Menu.NONE, getString(R.string.delete_selected_files)); } } if (APKEditorUtils.isFullVersion(requireActivity()) && !Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { menu.add(Menu.NONE, 3, Menu.NONE, getString(R.string.delete_folder)); } popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == 0) { sCommonUtils.saveBoolean("az_order", !sCommonUtils.getBoolean("az_order", true, requireActivity()), requireActivity()); reload(requireActivity()); } else if (item.getItemId() == 1) { if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, v.getContext())) { sPermissionUtils.requestPermission( new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, (Activity) v.getContext()); } else { new ExportToStorage(null, Common.getFiles(), Common.getAppID(), requireActivity()).execute(); } } else if (item.getItemId() == 2) { for (File file : Common.getFiles()) { if (file.exists()) {
new DeleteFile(file, v.getContext()) {
5
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/security/service/OnlineUserService.java
[ { "identifier": "SecurityProperties", "path": "dimple-system/src/main/java/com/dimple/modules/security/config/bean/SecurityProperties.java", "snippet": "@Data\npublic class SecurityProperties {\n\n /**\n * Request Headers : Authorization\n */\n private String header;\n\n /**\n * 令牌前...
import com.dimple.modules.security.config.bean.SecurityProperties; import com.dimple.modules.security.service.dto.JwtUserDTO; import com.dimple.modules.security.service.dto.OnlineUserDTO; import com.dimple.utils.EncryptUtils; import com.dimple.utils.FileUtil; import com.dimple.utils.IpUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.RedisUtils; import com.dimple.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
11,702
package com.dimple.modules.security.service; /** * @className: OnlineUserService * @description: * @author: Dimple * @date: 06/17/20 */ @Service @Slf4j public class OnlineUserService {
package com.dimple.modules.security.service; /** * @className: OnlineUserService * @description: * @author: Dimple * @date: 06/17/20 */ @Service @Slf4j public class OnlineUserService {
private final SecurityProperties properties;
0
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/inputmeta/pane/general/deserializer/ControlLableElementListDeserializer.java
[ { "identifier": "ElementName", "path": "database/src/main/java/com/lazycoder/database/common/ElementName.java", "snippet": "public class ElementName {\n\n\t/**\n\t * 标签元素\n\t */\n\tpublic static final String LABEL_ELEMENT = \"labelElement\";\n\n\t/**\n\t * 文本元素\n\t */\n\tpublic static final String STRIN...
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.lazycoder.database.common.ElementName; import com.lazycoder.database.common.LabelElementName; import com.lazycoder.service.vo.base.BaseElement; import com.lazycoder.service.vo.base.BaseElementInterface; import com.lazycoder.service.vo.element.lable.BaseLableElement; import com.lazycoder.service.vo.element.lable.control.CodeInputControl; import com.lazycoder.service.vo.element.lable.control.ConstantControl; import com.lazycoder.service.vo.element.lable.control.ContentChooseControl; import com.lazycoder.service.vo.element.lable.control.CustomMethodNameControl; import com.lazycoder.service.vo.element.lable.control.CustomVariableControl; import com.lazycoder.service.vo.element.lable.control.FileSelectorControl; import com.lazycoder.service.vo.element.lable.control.FunctionAddControl; import com.lazycoder.service.vo.element.lable.control.InfrequentlyUsedSettingControl; import com.lazycoder.service.vo.element.lable.control.MethodChooseControl; import com.lazycoder.service.vo.element.lable.control.NoteControl; import com.lazycoder.service.vo.element.lable.control.PictureControl; import com.lazycoder.service.vo.element.lable.control.TextInputControl; import com.lazycoder.service.vo.element.lable.control.VariableControl; import com.lazycoder.utils.JsonUtil; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List;
10,872
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.general.deserializer; public class ControlLableElementListDeserializer implements ObjectDeserializer { protected static void deserializeControlLable(ArrayList<BaseElementInterface> list, String labelType, JSONObject labelJSONObject) { ContentChooseControl contentChooseControlTemp; BaseLableElement temp = null; if (LabelElementName.TEXT_INPUT.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, TextInputControl.class); } else if (LabelElementName.CONTENT_CHOOSE.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, ContentChooseControl.class); } else if (LabelElementName.FUNCTION_ADD.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, FunctionAddControl.class); } else if (LabelElementName.CUSTOM_VARIABLE.equals(labelType)) {
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.general.deserializer; public class ControlLableElementListDeserializer implements ObjectDeserializer { protected static void deserializeControlLable(ArrayList<BaseElementInterface> list, String labelType, JSONObject labelJSONObject) { ContentChooseControl contentChooseControlTemp; BaseLableElement temp = null; if (LabelElementName.TEXT_INPUT.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, TextInputControl.class); } else if (LabelElementName.CONTENT_CHOOSE.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, ContentChooseControl.class); } else if (LabelElementName.FUNCTION_ADD.equals(labelType)) { temp = JsonUtil.restoreByJSONObject(labelJSONObject, FunctionAddControl.class); } else if (LabelElementName.CUSTOM_VARIABLE.equals(labelType)) {
temp = JsonUtil.restoreByJSONObject(labelJSONObject, CustomVariableControl.class);
9
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506_ex/KSVentilation2.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import android.util.Log; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.Ventilation; import kr.or.kashi.hde.ksx4506.KSPacket; import kr.or.kashi.hde.ksx4506.KSVentilation; import java.util.Map;
13,811
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * 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 kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the ventilation */ public class KSVentilation2 extends KSVentilation { private static final String TAG = "KSVentilation2"; private static final boolean DBG = true; public static final int CMD_FILTER_CHANGE_ALARM_OFF_REQ = 0x51; public static final int CMD_FILTER_CHANGE_ALARM_OFF_RSP = 0xD1; private int mModeVersion = 0; private int mVendorCode = 0;
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * 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 kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the ventilation */ public class KSVentilation2 extends KSVentilation { private static final String TAG = "KSVentilation2"; private static final boolean DBG = true; public static final int CMD_FILTER_CHANGE_ALARM_OFF_REQ = 0x51; public static final int CMD_FILTER_CHANGE_ALARM_OFF_RSP = 0xD1; private int mModeVersion = 0; private int mVendorCode = 0;
public KSVentilation2(MainContext mainContext, Map defaultProps) {
2
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/core/StateManager.java
[ { "identifier": "FluxLogoState", "path": "src/main/java/io/xlorey/FluxLoader/client/states/FluxLogoState.java", "snippet": "public class FluxLogoState extends GameState {\n\n /**\n * Current transparency value\n */\n private float alpha = 0.0f;\n\n /**\n * Logo display time\n */...
import io.xlorey.FluxLoader.client.states.FluxLogoState; import io.xlorey.FluxLoader.utils.Logger; import zombie.GameWindow; import zombie.gameStates.GameState; import zombie.gameStates.TISLogoState; import java.util.List;
13,030
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() { List<GameState> states = GameWindow.states.States; GameState tisLogoState = states.get(0); if (tisLogoState instanceof TISLogoState) {
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() { List<GameState> states = GameWindow.states.States; GameState tisLogoState = states.get(0); if (tisLogoState instanceof TISLogoState) {
GameWindow.states.States.add(1, new FluxLogoState());
0
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
11,301
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup(
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup(
new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP),
1
2023-11-18 14:02:20+00:00
16k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/slayers/zombie/RevenantHorror.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.core.helpers.EntityHelper; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.types.slayer.zombie.items.BeheadedHorror; import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.MobAttributes; import com.sweattypalms.skyblock.core.mobs.builder.NameAttributes; import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.slayers.ISlayerMob; import com.sweattypalms.skyblock.slayers.Slayer; import com.sweattypalms.skyblock.slayers.SlayerTimer; import com.sweattypalms.skyblock.slayers.events.SlayerFailEvent; import net.minecraft.server.v1_8_R3.EntityLiving; import net.minecraft.server.v1_8_R3.EntityZombie; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.inventory.ItemStack;
12,603
package com.sweattypalms.skyblock.slayers.zombie; public abstract class RevenantHorror extends EntityZombie implements ISkyblockMob, ISlayerMob { protected final SkyblockMob skyblockMob; protected final SlayerTimer slayerTimer; protected final long startTime; protected SkyblockPlayer ownerPlayer; public RevenantHorror(Location location, SkyblockMob skyblockMob) { super(((CraftWorld) location.getWorld()).getHandle()); this.skyblockMob = skyblockMob; equipArmor(); setStats(); this.getSkyblockMob() .setNameAttribute(NameAttributes.FORMATTED, true) .setNameAttribute(NameAttributes.SHOW_LEVEL, false) .setAttribute(MobAttributes.SPEED, 200); this.slayerTimer = new SlayerTimer(this.skyblockMob); this.startTime = System.currentTimeMillis(); } public void equipArmor() { SkyblockItem beheadedHorror = SkyblockItem.get(BeheadedHorror.ID); EntityHelper.equipItem(this, SkyblockItemType.HELMET, beheadedHorror.toItemStack()); ItemStack chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE); chestplate.addUnsafeEnchantment(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 7); EntityHelper.equipItem(this, SkyblockItemType.CHESTPLATE, chestplate); ItemStack leggings = new ItemStack(Material.CHAINMAIL_LEGGINGS); leggings.addUnsafeEnchantment(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 7); EntityHelper.equipItem(this, SkyblockItemType.LEGGINGS, leggings); ItemStack boots = new ItemStack(Material.DIAMOND_BOOTS); EntityHelper.equipItem(this, SkyblockItemType.BOOTS, boots); } long ticks = 0; @Override public void t_() { super.t_(); ticks++; if (!valid()) return; if (ticks % 20 == 0) { long timeLeft = Slayer.MAX_TIME - (System.currentTimeMillis() - getStartTime()) / 1000; if (timeLeft <= 0) { Bukkit.getScheduler().runTask(SkyBlock.getInstance(), () -> { if (valid()) { this.getSkyblockMob().getEntityInstance().setHealth(0);
package com.sweattypalms.skyblock.slayers.zombie; public abstract class RevenantHorror extends EntityZombie implements ISkyblockMob, ISlayerMob { protected final SkyblockMob skyblockMob; protected final SlayerTimer slayerTimer; protected final long startTime; protected SkyblockPlayer ownerPlayer; public RevenantHorror(Location location, SkyblockMob skyblockMob) { super(((CraftWorld) location.getWorld()).getHandle()); this.skyblockMob = skyblockMob; equipArmor(); setStats(); this.getSkyblockMob() .setNameAttribute(NameAttributes.FORMATTED, true) .setNameAttribute(NameAttributes.SHOW_LEVEL, false) .setAttribute(MobAttributes.SPEED, 200); this.slayerTimer = new SlayerTimer(this.skyblockMob); this.startTime = System.currentTimeMillis(); } public void equipArmor() { SkyblockItem beheadedHorror = SkyblockItem.get(BeheadedHorror.ID); EntityHelper.equipItem(this, SkyblockItemType.HELMET, beheadedHorror.toItemStack()); ItemStack chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE); chestplate.addUnsafeEnchantment(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 7); EntityHelper.equipItem(this, SkyblockItemType.CHESTPLATE, chestplate); ItemStack leggings = new ItemStack(Material.CHAINMAIL_LEGGINGS); leggings.addUnsafeEnchantment(org.bukkit.enchantments.Enchantment.PROTECTION_ENVIRONMENTAL, 7); EntityHelper.equipItem(this, SkyblockItemType.LEGGINGS, leggings); ItemStack boots = new ItemStack(Material.DIAMOND_BOOTS); EntityHelper.equipItem(this, SkyblockItemType.BOOTS, boots); } long ticks = 0; @Override public void t_() { super.t_(); ticks++; if (!valid()) return; if (ticks % 20 == 0) { long timeLeft = Slayer.MAX_TIME - (System.currentTimeMillis() - getStartTime()) / 1000; if (timeLeft <= 0) { Bukkit.getScheduler().runTask(SkyBlock.getInstance(), () -> { if (valid()) { this.getSkyblockMob().getEntityInstance().setHealth(0);
SlayerFailEvent failEvent = new SlayerFailEvent(
12
2023-11-15 15:05:58+00:00
16k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFTableTest.java
[ { "identifier": "PDFGridLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java", "snippet": "public class PDFGridLayout extends PDFLayout{\n int rows, columns;\n\n ArrayList<Integer> span;\n\n final int[] gaps;\n final Rect childMargi...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFGridLayout; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFImage; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Fit; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.InputStream;
11,071
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE)
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE)
.addChild(PDFImage.build(b)
3
2023-11-15 08:05:28+00:00
16k
Hikaito/Fox-Engine
src/system/gui/editorPane/GuiFieldControls.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import system.Program; import system.gui.GuiOperations; import system.layerTree.data.LayerManager; import system.layerTree.data.SelectionManager; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.LayerCore; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
13,370
package system.gui.editorPane; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // field controls for Layer objects public class GuiFieldControls { //region core unit manipulation ======================================== //region clone and delete-------------------------------------- //add delete button: adds deletion button to field public static JButton makeDelete(LayerCore layer){ //add button JButton button = new JButton("delete"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, false); } }); return button; } //add delete all button: adds deletion of children button to field public static JButton makeDeleteAll(LayerCore layer){ //add button JButton button = new JButton("delete (deep)"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, true); } }); return button; } //add duplicate button public static JButton makeDuplicate(LayerCore layer){ //add button JButton button = new JButton("clone"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.duplicateTreeUnit(layer); } }); return button; } //endregion //region movement control --------------------------- //function for adding location controls to panel [adds buttons to field] public static void addLocationControls(JPanel innerField, LayerCore layer){ //generate panel for holding buttons JPanel buttonBox = new JPanel(); innerField.add(buttonBox); //add buttons for location movement----------- buttonBox.add(makeButtonOut(layer)); //register button buttonBox.add(makeButtonUp(layer)); //label for level //JLabel levelLabel = new JLabel("level " + 0); //fixme 0 was level //buttonBox.add(levelLabel); buttonBox.add(makeButtonDown(layer)); buttonBox.add(makeButtonIn(layer)); } //get button for in public static JButton makeButtonIn(LayerCore layer){ //in: button to signal moving deeper in hierarchy JButton buttonIn = new JButton("->"); buttonIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.IN); } }); return buttonIn; } //get button for down public static JButton makeButtonDown(LayerCore layer){ //down: button to signal moving down in hierarchy JButton buttonDown = new JButton("v"); buttonDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.DOWN); } }); return buttonDown; } //get button for up public static JButton makeButtonUp(LayerCore layer){ //up: button to signal moving up in hierarchy JButton buttonUp = new JButton("^"); buttonUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.UP); } }); return buttonUp; } ///get button for out public static JButton makeButtonOut(LayerCore layer){ //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton("<-"); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.OUT); } }); return buttonOut; } //endregion //region selection --------------------------- // function for selection public static JButton makeSelectionButton(LayerCore layer){ // pick text String text = "Deselect"; // test for selection: selection type is select if not selected
package system.gui.editorPane; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // field controls for Layer objects public class GuiFieldControls { //region core unit manipulation ======================================== //region clone and delete-------------------------------------- //add delete button: adds deletion button to field public static JButton makeDelete(LayerCore layer){ //add button JButton button = new JButton("delete"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, false); } }); return button; } //add delete all button: adds deletion of children button to field public static JButton makeDeleteAll(LayerCore layer){ //add button JButton button = new JButton("delete (deep)"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, true); } }); return button; } //add duplicate button public static JButton makeDuplicate(LayerCore layer){ //add button JButton button = new JButton("clone"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.duplicateTreeUnit(layer); } }); return button; } //endregion //region movement control --------------------------- //function for adding location controls to panel [adds buttons to field] public static void addLocationControls(JPanel innerField, LayerCore layer){ //generate panel for holding buttons JPanel buttonBox = new JPanel(); innerField.add(buttonBox); //add buttons for location movement----------- buttonBox.add(makeButtonOut(layer)); //register button buttonBox.add(makeButtonUp(layer)); //label for level //JLabel levelLabel = new JLabel("level " + 0); //fixme 0 was level //buttonBox.add(levelLabel); buttonBox.add(makeButtonDown(layer)); buttonBox.add(makeButtonIn(layer)); } //get button for in public static JButton makeButtonIn(LayerCore layer){ //in: button to signal moving deeper in hierarchy JButton buttonIn = new JButton("->"); buttonIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.IN); } }); return buttonIn; } //get button for down public static JButton makeButtonDown(LayerCore layer){ //down: button to signal moving down in hierarchy JButton buttonDown = new JButton("v"); buttonDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.DOWN); } }); return buttonDown; } //get button for up public static JButton makeButtonUp(LayerCore layer){ //up: button to signal moving up in hierarchy JButton buttonUp = new JButton("^"); buttonUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.UP); } }); return buttonUp; } ///get button for out public static JButton makeButtonOut(LayerCore layer){ //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton("<-"); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.OUT); } }); return buttonOut; } //endregion //region selection --------------------------- // function for selection public static JButton makeSelectionButton(LayerCore layer){ // pick text String text = "Deselect"; // test for selection: selection type is select if not selected
if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE)
3
2023-11-12 21:12:21+00:00
16k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/events/packets/PacketBlockAction.java
[ { "identifier": "GrimAPI", "path": "src/main/java/ac/grim/grimac/GrimAPI.java", "snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final...
import ac.grim.grimac.GrimAPI; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.data.ShulkerData; import ac.grim.grimac.utils.nmsutil.Materials; import io.github.retrooper.packetevents.event.PacketListenerAbstract; import io.github.retrooper.packetevents.event.PacketListenerPriority; import io.github.retrooper.packetevents.event.impl.PacketPlaySendEvent; import io.github.retrooper.packetevents.packettype.PacketType; import io.github.retrooper.packetevents.packetwrappers.play.out.blockaction.WrappedPacketOutBlockAction; import io.github.retrooper.packetevents.utils.vector.Vector3i;
13,551
package ac.grim.grimac.events.packets; // If a player doesn't get this packet, then they don't know the shulker box is currently opened // Meaning if a player enters a chunk with an opened shulker box, they see the shulker box as closed. // // Exempting the player on shulker boxes is an option... but then you have people creating PvP arenas // on shulker boxes to get high lenience. // // Due to the difficulty of cross version shulker box public class PacketBlockAction extends PacketListenerAbstract { public PacketBlockAction() { super(PacketListenerPriority.MONITOR); } @Override public void onPacketPlaySend(PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.BLOCK_ACTION) {
package ac.grim.grimac.events.packets; // If a player doesn't get this packet, then they don't know the shulker box is currently opened // Meaning if a player enters a chunk with an opened shulker box, they see the shulker box as closed. // // Exempting the player on shulker boxes is an option... but then you have people creating PvP arenas // on shulker boxes to get high lenience. // // Due to the difficulty of cross version shulker box public class PacketBlockAction extends PacketListenerAbstract { public PacketBlockAction() { super(PacketListenerPriority.MONITOR); } @Override public void onPacketPlaySend(PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.BLOCK_ACTION) {
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getPlayer());
0
2023-11-11 05:14:12+00:00
16k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/dialog/SafeDialog.java
[ { "identifier": "BaseDialog", "path": "library/base/src/main/java/com/hjq/base/BaseDialog.java", "snippet": "public class BaseDialog extends AppCompatDialog implements LifecycleOwner,\n ActivityAction, ResourcesAction, HandlerAction, ClickAction, AnimAction, KeyboardAction,\n DialogInterfa...
import android.content.Context; import android.view.View; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.Nullable; import com.hjq.base.BaseDialog; import com.buaa.food.R; import com.buaa.food.aop.SingleClick; import com.buaa.food.http.api.GetCodeApi; import com.buaa.food.http.api.VerifyCodeApi; import com.buaa.food.http.model.HttpData; import com.hjq.http.EasyHttp; import com.hjq.http.listener.OnHttpListener; import com.hjq.toast.ToastUtils; import com.hjq.widget.view.CountdownView;
11,475
package com.buaa.food.ui.dialog; public final class SafeDialog { public static final class Builder extends CommonDialog.Builder<Builder> { private final TextView mPhoneView; private final EditText mCodeView; private final CountdownView mCountdownView; @Nullable private OnListener mListener; /** 当前手机号 */ private final String mPhoneNumber; public Builder(Context context) { super(context); setTitle(R.string.safe_title); setCustomView(R.layout.safe_dialog); mPhoneView = findViewById(R.id.tv_safe_phone); mCodeView = findViewById(R.id.et_safe_code); mCountdownView = findViewById(R.id.cv_safe_countdown); setOnClickListener(mCountdownView); mPhoneNumber = "18100001413"; // 为了保护用户的隐私,不明文显示中间四个数字 mPhoneView.setText(String.format("%s****%s", mPhoneNumber.substring(0, 3), mPhoneNumber.substring(mPhoneNumber.length() - 4))); } public Builder setCode(String code) { mCodeView.setText(code); return this; } public Builder setListener(OnListener listener) { mListener = listener; return this; } @SingleClick @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == R.id.cv_safe_countdown) { if (true) { ToastUtils.show(R.string.common_code_send_hint); mCountdownView.start(); setCancelable(false); return; } // 获取验证码 EasyHttp.post(getDialog()) .api(new GetCodeApi() .setPhone(mPhoneNumber))
package com.buaa.food.ui.dialog; public final class SafeDialog { public static final class Builder extends CommonDialog.Builder<Builder> { private final TextView mPhoneView; private final EditText mCodeView; private final CountdownView mCountdownView; @Nullable private OnListener mListener; /** 当前手机号 */ private final String mPhoneNumber; public Builder(Context context) { super(context); setTitle(R.string.safe_title); setCustomView(R.layout.safe_dialog); mPhoneView = findViewById(R.id.tv_safe_phone); mCodeView = findViewById(R.id.et_safe_code); mCountdownView = findViewById(R.id.cv_safe_countdown); setOnClickListener(mCountdownView); mPhoneNumber = "18100001413"; // 为了保护用户的隐私,不明文显示中间四个数字 mPhoneView.setText(String.format("%s****%s", mPhoneNumber.substring(0, 3), mPhoneNumber.substring(mPhoneNumber.length() - 4))); } public Builder setCode(String code) { mCodeView.setText(code); return this; } public Builder setListener(OnListener listener) { mListener = listener; return this; } @SingleClick @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == R.id.cv_safe_countdown) { if (true) { ToastUtils.show(R.string.common_code_send_hint); mCountdownView.start(); setCancelable(false); return; } // 获取验证码 EasyHttp.post(getDialog()) .api(new GetCodeApi() .setPhone(mPhoneNumber))
.request(new OnHttpListener<HttpData<Void>>() {
3
2023-11-14 10:04:26+00:00
16k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/entity/BenchEntityModel.java
[ { "identifier": "AnimationHelper", "path": "src/main/java/useless/dragonfly/helper/AnimationHelper.java", "snippet": "public class AnimationHelper {\n\tpublic static final Map<String, Animation> registeredAnimations = new HashMap<>();\n\n\tpublic static Animation getOrCreateEntityAnimation(String modID,...
import com.google.gson.annotations.SerializedName; import net.minecraft.client.render.model.ModelBase; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import useless.dragonfly.helper.AnimationHelper; import useless.dragonfly.model.entity.animation.AnimationData; import useless.dragonfly.model.entity.processor.BenchEntityBones; import useless.dragonfly.model.entity.processor.BenchEntityCube; import useless.dragonfly.model.entity.processor.BenchEntityGeometry; import useless.dragonfly.utilities.vector.Vector3f; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional;
12,231
List<Float> rotation = bones.getRotation(); //parent time before rotate it self if (bones.getParent() != null) { BenchEntityBones parentBone = this.getIndexBones().get(bones.getParent()); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } } private void convertWithMoreParent(BenchEntityBones parentBone, float scale) { //don't forget some parent has more parent if (parentBone.getParent() != null) { convertWithMoreParent(this.getIndexBones().get(parentBone.getParent()), scale); } GL11.glTranslatef(convertPivot(parentBone, 0) * scale, convertPivot(parentBone, 1) * scale, convertPivot(parentBone, 2) * scale); if (parentBone.rotationPointX != 0.0f || parentBone.rotationPointY != 0.0f || parentBone.rotationPointZ != 0.0f) { GL11.glTranslatef(parentBone.rotationPointX * scale, parentBone.rotationPointY * scale, parentBone.rotationPointZ * scale); } if (parentBone.getRotation() != null) { GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(2)), 1.0f, 0.0f, 0.0f); } if (parentBone.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (parentBone.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (parentBone.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (parentBone.scaleX != 0.0f || parentBone.scaleY != 0.0f || parentBone.scaleZ != 0.0f) { GL11.glScalef(parentBone.scaleX, parentBone.scaleY, parentBone.scaleZ); } } public float convertPivot(BenchEntityBones bones, int index) { if (bones.getParent() != null) { if (index == 1) { return getIndexBones().get(bones.getParent()).getPivot().get(index) - bones.getPivot().get(index); } else { return bones.getPivot().get(index) - getIndexBones().get(bones.getParent()).getPivot().get(index); } } else { if (index == 1) { return 24 - bones.getPivot().get(index); } else { return bones.getPivot().get(index); } } } public float convertPivot(BenchEntityBones parent, BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return parent.getPivot().get(index) - cube.getPivot().get(index); } else { return cube.getPivot().get(index) - parent.getPivot().get(index); } } public float convertOrigin(BenchEntityBones bone, BenchEntityCube cube, int index) { if (index == 1) { return bone.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - bone.getPivot().get(index); } } public float convertOrigin(BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return cube.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - cube.getPivot().get(index); } } public Optional<BenchEntityBones> getAnyDescendantWithName(String key) { Optional<Map.Entry<String, BenchEntityBones>> bones = this.getIndexBones().entrySet().stream().filter((benchBone) -> benchBone.getKey().equals(key)).findFirst(); if (bones.isPresent()) { return Optional.of(bones.get().getValue()); } else { return Optional.empty(); } } protected void animateWalk(AnimationData animationData, float p_268057_, float p_268347_, float p_268138_, float p_268165_) { long time = (long) (p_268057_ * 50.0F * p_268138_); float scale = Math.min(p_268347_ * p_268165_, 1.0F);
package useless.dragonfly.model.entity; /* * Credit by 0999312! Thanks! * https://github.com/0999312/MMLib/blob/3e87210c9305a5724e06c492be503533a1ebcd59/src/main/java/cn/mcmod_mmf/mmlib/client/model/bedrock/BedrockModel.java */ public class BenchEntityModel extends ModelBase { public Vector3f VEC_ANIMATION = new Vector3f(); private final HashMap<String, BenchEntityBones> indexBones = new HashMap<>(); @SerializedName("format_version") private String formatVersion; @SerializedName("minecraft:geometry") private List<BenchEntityGeometry> benchEntityGeometry; public HashMap<String, BenchEntityBones> getIndexBones() { return indexBones; } @Override public void render(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { super.render(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); this.renderModel(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); } public void renderModel(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { BenchEntityGeometry entityGeometry = this.benchEntityGeometry.get(0); int texWidth = entityGeometry.getWidth(); int texHeight = entityGeometry.getHeight(); for (BenchEntityBones bones : entityGeometry.getBones()) { if (!this.getIndexBones().containsKey(bones.getName())) { this.getIndexBones().put(bones.getName(), bones); } } if (!this.getIndexBones().isEmpty()) { //DON'T MOVE IT! because the rotation and rotation position of entities of the same model being mixed. this.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); } for (BenchEntityBones bones : entityGeometry.getBones()) { String name = bones.getName(); @Nullable List<Float> rotation = bones.getRotation(); @Nullable String parent = bones.getParent(); if (parent != null) { if (!this.getIndexBones().get(parent).getChildren().contains(bones)) { this.getIndexBones().get(parent).addChild(bones); } } if (bones.getCubes() == null) { continue; } for (BenchEntityCube cube : bones.getCubes()) { List<Float> uv = cube.getUv(); List<Float> size = cube.getSize(); @Nullable List<Float> cubeRotation = cube.getRotation(); boolean mirror = cube.isMirror(); float inflate = cube.getInflate(); cube.addBox(texWidth, texHeight, convertOrigin(bones, cube, 0), convertOrigin(bones, cube, 1), convertOrigin(bones, cube, 2), false); if (!cube.isCompiled()) { cube.compileDisplayList(scale); } GL11.glPushMatrix(); //parent time before rotate it self if (parent != null) { BenchEntityBones parentBone = this.getIndexBones().get(parent); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } GL11.glCallList(cube.getDisplayList()); GL11.glPopMatrix(); } } } /* * This method used Translate for item render */ public void postRender(BenchEntityBones bones, float scale) { List<Float> rotation = bones.getRotation(); //parent time before rotate it self if (bones.getParent() != null) { BenchEntityBones parentBone = this.getIndexBones().get(bones.getParent()); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } } private void convertWithMoreParent(BenchEntityBones parentBone, float scale) { //don't forget some parent has more parent if (parentBone.getParent() != null) { convertWithMoreParent(this.getIndexBones().get(parentBone.getParent()), scale); } GL11.glTranslatef(convertPivot(parentBone, 0) * scale, convertPivot(parentBone, 1) * scale, convertPivot(parentBone, 2) * scale); if (parentBone.rotationPointX != 0.0f || parentBone.rotationPointY != 0.0f || parentBone.rotationPointZ != 0.0f) { GL11.glTranslatef(parentBone.rotationPointX * scale, parentBone.rotationPointY * scale, parentBone.rotationPointZ * scale); } if (parentBone.getRotation() != null) { GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(2)), 1.0f, 0.0f, 0.0f); } if (parentBone.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (parentBone.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (parentBone.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (parentBone.scaleX != 0.0f || parentBone.scaleY != 0.0f || parentBone.scaleZ != 0.0f) { GL11.glScalef(parentBone.scaleX, parentBone.scaleY, parentBone.scaleZ); } } public float convertPivot(BenchEntityBones bones, int index) { if (bones.getParent() != null) { if (index == 1) { return getIndexBones().get(bones.getParent()).getPivot().get(index) - bones.getPivot().get(index); } else { return bones.getPivot().get(index) - getIndexBones().get(bones.getParent()).getPivot().get(index); } } else { if (index == 1) { return 24 - bones.getPivot().get(index); } else { return bones.getPivot().get(index); } } } public float convertPivot(BenchEntityBones parent, BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return parent.getPivot().get(index) - cube.getPivot().get(index); } else { return cube.getPivot().get(index) - parent.getPivot().get(index); } } public float convertOrigin(BenchEntityBones bone, BenchEntityCube cube, int index) { if (index == 1) { return bone.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - bone.getPivot().get(index); } } public float convertOrigin(BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return cube.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - cube.getPivot().get(index); } } public Optional<BenchEntityBones> getAnyDescendantWithName(String key) { Optional<Map.Entry<String, BenchEntityBones>> bones = this.getIndexBones().entrySet().stream().filter((benchBone) -> benchBone.getKey().equals(key)).findFirst(); if (bones.isPresent()) { return Optional.of(bones.get().getValue()); } else { return Optional.empty(); } } protected void animateWalk(AnimationData animationData, float p_268057_, float p_268347_, float p_268138_, float p_268165_) { long time = (long) (p_268057_ * 50.0F * p_268138_); float scale = Math.min(p_268347_ * p_268165_, 1.0F);
AnimationHelper.animate(this, animationData, time, scale, VEC_ANIMATION);
0
2023-11-16 01:10:52+00:00
16k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/impl/CaptchaServiceImpl.java
[ { "identifier": "CaptchaCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/condition/CaptchaCondition.java", "snippet": "public class CaptchaCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata m...
import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.ReflectUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Service; import top.sharehome.springbootinittemplate.config.captcha.condition.CaptchaCondition; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.properties.CaptchaProperties; import top.sharehome.springbootinittemplate.config.captcha.properties.enums.CaptchaType; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource; import java.util.UUID;
13,837
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service
@Conditional(CaptchaCondition.class)
0
2023-11-12 07:49:59+00:00
16k
WuKongOpenSource/Wukong_HRM
common/common-web/src/main/java/com/kakarote/core/utils/BiParamsUtil.java
[ { "identifier": "CrmCacheKey", "path": "common/common-web/src/main/java/com/kakarote/core/common/cache/CrmCacheKey.java", "snippet": "public interface CrmCacheKey {\n /**\n * 打印模板缓存key\n */\n String CRM_PRINT_TEMPLATE_CACHE_KEY = \"CRM:PRINT:TEMPLATE:\";\n\n /**\n * crm待办事项数量缓存key\n...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.CalendarUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; import cn.hutool.core.text.StrPool; import cn.hutool.core.util.ObjectUtil; import com.kakarote.common.entity.UserInfo; import com.kakarote.common.utils.UserUtil; import com.kakarote.core.common.cache.CrmCacheKey; import com.kakarote.core.common.enums.DateFilterEnum; import com.kakarote.core.common.enums.SystemCodeEnum; import com.kakarote.core.exception.CrmException; import com.kakarote.core.feign.admin.service.AdminService; import com.kakarote.core.feign.crm.entity.BiEntityParams; import com.kakarote.core.redis.Redis; import com.kakarote.core.servlet.ApplicationContextHolder; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import java.util.*;
13,303
} } /** * 用户数据处理 * * @param biTimeEntity timeEntity * @param biParams biParams * @param menuId 菜单ID */ public static void analyzeUser(BiTimeEntity biTimeEntity, BiEntityParams biParams, Long menuId) { Set<Long> userList = getAllUserList(biParams); biTimeEntity.setUserIds(filterUser(userList, menuId)); } /** * 用户数据处理 * * @param userIds 当前用户列表 * @param menuId 菜单ID */ public static List<Long> filterUser(Collection<Long> userIds, Long menuId) { if (UserUtil.isAdmin()) { if (userIds.isEmpty()) { //如果无权访问任何数据,则添加一个不存在的用户,0L userIds.add(0L); } return new ArrayList<>(userIds); } List<Long> authUserList = queryAuthUserList(menuId); ArrayList<Long> list = new ArrayList<>(userIds); list.retainAll(authUserList); if (list.isEmpty()) { //如果无权访问任何数据,则添加一个不存在的用户,0L list.add(0L); } return list; } /** * 用户数据处理,根据数据权限,查询用户列表,未做权限拦截 * * @param biParams biParams */ public static Set<Long> getAllUserList(BiEntityParams biParams) { if (biParams.getDataType() == null) { throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID); } Set<Long> userIdList = new HashSet<>(); UserInfo userInfo = UserUtil.getUser(); AdminService adminService = ApplicationContextHolder.getBean(AdminService.class); switch (biParams.getDataType()) { case MYSELF: userIdList.add(userInfo.getUserId()); break; case MYSELF_AND_SUBORDINATE: userIdList.add(userInfo.getUserId()); userIdList.addAll(adminService.queryChildUserId(userInfo.getUserId()).getData()); break; case THIS_DEPARTMENT: userIdList.addAll(adminService.queryUserByDeptIds(Collections.singleton(userInfo.getDeptId())).getData()); break; case THIS_DEPARTMENT_AND_SUBORDINATE: List<Long> data = adminService.queryChildDeptId(userInfo.getDeptId()).getData(); data.add(userInfo.getDeptId()); userIdList.addAll(adminService.queryUserByDeptIds(data).getData()); break; case ALL: userIdList.addAll(adminService.queryUserList(1).getData()); break; case CUSTOM: //员工列表 if (CollUtil.isNotEmpty(biParams.getUserList())) { userIdList.addAll(biParams.getUserList()); } //部门列表 if (CollUtil.isNotEmpty(biParams.getDeptList())) { if (ObjectUtil.equals(1, biParams.getIsNeedChild())) { //需要查询部门和子级部门中员工 userIdList.addAll(adminService.queryUserListByDeptIds(biParams.getDeptList()).getData()); } else { userIdList.addAll(adminService.queryUserByDeptIds(biParams.getDeptList()).getData()); } } break; default: break; } return userIdList; } /** * 根据用户进行数据权限过滤,不会破坏原有数据 */ public List<Long> filterUserIdList(List<Long> allUserList, List<Long> userList) { List<Long> arrayList = new ArrayList<>(userList); arrayList.retainAll(allUserList); return arrayList; } /** * 根据菜单ID进行数据权限过滤 */ public List<Long> filterUserIdList(List<Long> allUserList, Long menuId) { List<Long> authUserList = queryAuthUserList(menuId); return filterUserIdList(allUserList, authUserList); } /** * 查询权限内用户ID * * @param menuId 菜单ID * @return userIds */ @SuppressWarnings("unchecked") public static List<Long> queryAuthUserList(Long menuId) { Long userId = UserUtil.getUserId();
package com.kakarote.core.utils; /** * @author zhangzhiwei */ public class BiParamsUtil { /** * 获取查询时间,用户等参数 * * @param biParams 查询参数 * @return timeEntity */ public static BiTimeEntity analyzeType(BiEntityParams biParams, Long menuId) { BiTimeEntity biTimeEntity = new BiTimeEntity(); //日期数据处理 analyzeDate(biTimeEntity, biParams); //员工信息处理 analyzeUser(biTimeEntity, biParams, menuId); return biTimeEntity; } /** * 根据当前用户的部门及下属部门取交集 * * @param deptIds dept列表 * @return data */ public static List<Long> filterDeptId(List<Long> deptIds) { if (UserUtil.isAdmin()) { return deptIds; } Long deptId = UserUtil.getUser().getDeptId(); List<Long> subDeptIdList = ApplicationContextHolder.getBean(AdminService.class).queryChildDeptId(deptId).getData(); subDeptIdList.add(deptId); subDeptIdList.retainAll(deptIds); return subDeptIdList; } /** * 日期时间处理,根据biParams的dateFilterEnum,计算出真实的开始时间和结束时间 * * @param biTimeEntity timeEntity * @param biParams biParams */ public static void analyzeDate(BiTimeEntity biTimeEntity, BiEntityParams biParams) { if (biParams.getDateFilter() == null) { return; } Calendar calendar = CalendarUtil.calendar(); Calendar startCalendar, endCalendar; switch (biParams.getDateFilter()) { case CUSTOM: { //自定义时间筛选,开始时间和结束时间都不可为空 Assert.notNull(biParams.getStartDate(), CrmException::new); Assert.notNull(biParams.getEndDate(), CrmException::new); //自定义时间筛选,最多90天 long betweenDay = DateUtil.betweenDay(biParams.getStartDate(), biParams.getEndDate(), true); Assert.checkBetween(betweenDay, 0, 90, CrmException::new); //最多筛选90天的数据,开始时间默认为当天00:00:00,结束时间默认为23:59:59 biTimeEntity.setBeginDate(DateUtil.beginOfDay(biParams.getStartDate())); biTimeEntity.setEndDate(DateUtil.endOfDay(biParams.getEndDate())); return; } case YESTERDAY: //时间往前推一天 calendar.add(Calendar.DAY_OF_YEAR, -1); case TOMORROW: if (biParams.getDateFilter() == DateFilterEnum.TOMORROW) { //时间往前推一天 calendar.add(Calendar.DAY_OF_YEAR, 1); } case TODAY: startCalendar = CalendarUtil.beginOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case LAST_WEEK: //时间往前推一周 calendar.add(Calendar.WEEK_OF_YEAR, -1); case NEXT_WEEK: if (biParams.getDateFilter() == DateFilterEnum.NEXT_WEEK) { //时间往后推一周 calendar.add(Calendar.WEEK_OF_YEAR, 1); } case WEEK: startCalendar = CalendarUtil.beginOfWeek(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfWeek(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case LAST_MONTH: calendar.add(Calendar.MONTH, -1); case NEXT_MONTH: if (biParams.getDateFilter() == DateFilterEnum.NEXT_MONTH) { calendar.add(Calendar.MONTH, 1); } case MONTH: startCalendar = CalendarUtil.beginOfMonth(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfMonth(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case LAST_QUARTER: calendar.add(Calendar.MONTH, -3); case NEXT_QUARTER: if (biParams.getDateFilter() == DateFilterEnum.NEXT_QUARTER) { calendar.add(Calendar.MONTH, 3); } case QUARTER: startCalendar = CalendarUtil.beginOfQuarter(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfQuarter(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case NEXT_YEAR: calendar.add(Calendar.MONTH, 12); case LAST_YEAR: if (biParams.getDateFilter() == DateFilterEnum.LAST_YEAR) { calendar.add(Calendar.MONTH, -12); } case YEAR: startCalendar = CalendarUtil.beginOfYear(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfYear(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case FIRST_HALF_YEAR: startCalendar = CalendarUtil.beginOfYear(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.calendar(); //每年上半年是到 6月30号,23:59:59 endCalendar.set(startCalendar.get(Calendar.YEAR), Calendar.JULY, 30, 23, 59, 59); break; case NEXT_HALF_YEAR: startCalendar = CalendarUtil.calendar(); startCalendar.set(startCalendar.get(Calendar.YEAR), Calendar.AUGUST, 1, 0, 0, 0); endCalendar = CalendarUtil.endOfYear(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case previous7day: startCalendar = CalendarUtil.beginOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); startCalendar.add(Calendar.DAY_OF_YEAR, -7); endCalendar = CalendarUtil.endOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case previous30day: startCalendar = CalendarUtil.beginOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); startCalendar.add(Calendar.DAY_OF_YEAR, -30); endCalendar = CalendarUtil.endOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); break; case future7day: startCalendar = CalendarUtil.beginOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); startCalendar.add(Calendar.DAY_OF_YEAR, 7); break; case future30day: startCalendar = CalendarUtil.beginOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); endCalendar = CalendarUtil.endOfDay(CalendarUtil.calendar(calendar.getTimeInMillis())); startCalendar.add(Calendar.DAY_OF_YEAR, 30); break; default: throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID); } if (biParams.getDateFilter() != DateFilterEnum.CUSTOM) { biTimeEntity.setBeginDate(startCalendar.getTime()); biTimeEntity.setEndDate(endCalendar.getTime()); } } /** * 用户数据处理 * * @param biTimeEntity timeEntity * @param biParams biParams * @param menuId 菜单ID */ public static void analyzeUser(BiTimeEntity biTimeEntity, BiEntityParams biParams, Long menuId) { Set<Long> userList = getAllUserList(biParams); biTimeEntity.setUserIds(filterUser(userList, menuId)); } /** * 用户数据处理 * * @param userIds 当前用户列表 * @param menuId 菜单ID */ public static List<Long> filterUser(Collection<Long> userIds, Long menuId) { if (UserUtil.isAdmin()) { if (userIds.isEmpty()) { //如果无权访问任何数据,则添加一个不存在的用户,0L userIds.add(0L); } return new ArrayList<>(userIds); } List<Long> authUserList = queryAuthUserList(menuId); ArrayList<Long> list = new ArrayList<>(userIds); list.retainAll(authUserList); if (list.isEmpty()) { //如果无权访问任何数据,则添加一个不存在的用户,0L list.add(0L); } return list; } /** * 用户数据处理,根据数据权限,查询用户列表,未做权限拦截 * * @param biParams biParams */ public static Set<Long> getAllUserList(BiEntityParams biParams) { if (biParams.getDataType() == null) { throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID); } Set<Long> userIdList = new HashSet<>(); UserInfo userInfo = UserUtil.getUser(); AdminService adminService = ApplicationContextHolder.getBean(AdminService.class); switch (biParams.getDataType()) { case MYSELF: userIdList.add(userInfo.getUserId()); break; case MYSELF_AND_SUBORDINATE: userIdList.add(userInfo.getUserId()); userIdList.addAll(adminService.queryChildUserId(userInfo.getUserId()).getData()); break; case THIS_DEPARTMENT: userIdList.addAll(adminService.queryUserByDeptIds(Collections.singleton(userInfo.getDeptId())).getData()); break; case THIS_DEPARTMENT_AND_SUBORDINATE: List<Long> data = adminService.queryChildDeptId(userInfo.getDeptId()).getData(); data.add(userInfo.getDeptId()); userIdList.addAll(adminService.queryUserByDeptIds(data).getData()); break; case ALL: userIdList.addAll(adminService.queryUserList(1).getData()); break; case CUSTOM: //员工列表 if (CollUtil.isNotEmpty(biParams.getUserList())) { userIdList.addAll(biParams.getUserList()); } //部门列表 if (CollUtil.isNotEmpty(biParams.getDeptList())) { if (ObjectUtil.equals(1, biParams.getIsNeedChild())) { //需要查询部门和子级部门中员工 userIdList.addAll(adminService.queryUserListByDeptIds(biParams.getDeptList()).getData()); } else { userIdList.addAll(adminService.queryUserByDeptIds(biParams.getDeptList()).getData()); } } break; default: break; } return userIdList; } /** * 根据用户进行数据权限过滤,不会破坏原有数据 */ public List<Long> filterUserIdList(List<Long> allUserList, List<Long> userList) { List<Long> arrayList = new ArrayList<>(userList); arrayList.retainAll(allUserList); return arrayList; } /** * 根据菜单ID进行数据权限过滤 */ public List<Long> filterUserIdList(List<Long> allUserList, Long menuId) { List<Long> authUserList = queryAuthUserList(menuId); return filterUserIdList(allUserList, authUserList); } /** * 查询权限内用户ID * * @param menuId 菜单ID * @return userIds */ @SuppressWarnings("unchecked") public static List<Long> queryAuthUserList(Long menuId) { Long userId = UserUtil.getUserId();
Redis redis = BaseUtil.getRedis();
6
2023-10-17 05:49:52+00:00
16k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/mobileqq/profilecard/processor/AbsProfileBusinessProcessor.java
[ { "identifier": "Card", "path": "qqinterface/src/main/java/com/tencent/mobileqq/data/Card.java", "snippet": "public class Card {\n public static final long BIRTHDAY_INVALID = 0;\n public static final int CONSTELLATION_INVALID = 0;\n public static final short FEMALE = 1;\n public static final...
import android.os.Bundle; import android.util.SparseArray; import com.tencent.mobileqq.data.Card; import com.tencent.mobileqq.profilecard.entity.BusinessReqBuffer; import com.tencent.mobileqq.profilecard.entity.BusinessRespBuffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import SummaryCard.RespHead; import SummaryCard.RespSummaryCard; import mqq.app.AppRuntime; import tencent.im.oidb.cmd0x5eb.oidb_0x5eb;
12,368
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
public void onProcessProfileService(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, SparseArray<BusinessRespBuffer> sparseArray) {
2
2023-10-20 10:43:47+00:00
16k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/core/RouteCenter.java
[ { "identifier": "ROUTER_CURRENT_PATH", "path": "GoRouter-Api/src/main/java/com/wyjson/router/core/Constants.java", "snippet": "static final String ROUTER_CURRENT_PATH = \"go_router_current_path\";" }, { "identifier": "ROUTER_RAW_URI", "path": "GoRouter-Api/src/main/java/com/wyjson/router/cor...
import static com.wyjson.router.core.Constants.ROUTER_CURRENT_PATH; import static com.wyjson.router.core.Constants.ROUTER_RAW_URI; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.wyjson.router.GoRouter; import com.wyjson.router.enums.ParamType; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IJsonService; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import com.wyjson.router.model.ParamMeta; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.utils.MapUtils; import com.wyjson.router.utils.TextUtils; import java.lang.reflect.Field; import java.util.Map;
10,836
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
public static CardMeta getCardMeta(Card card) throws NoFoundRouteException {
9
2023-10-18 13:52:07+00:00
16k
trpc-group/trpc-java
trpc-registry/trpc-registry-consul/src/main/java/com/tencent/trpc/registry/consul/ConsulRegistryCenter.java
[ { "identifier": "PluginConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/PluginConfig.java", "snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic class PluginConfig {\n\n /**\n * Plugin name (under a plugin type, the name is a unique identifier for a sp...
import com.ecwid.consul.v1.Response; import com.ecwid.consul.v1.health.model.HealthService; import com.tencent.trpc.core.common.config.PluginConfig; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.extension.Extension; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.registry.center.AbstractFailedRetryRegistryCenter; import com.tencent.trpc.registry.center.NotifyListener; import com.tencent.trpc.core.exception.TRpcExtensionException; import com.tencent.trpc.core.registry.RegisterInfo; import com.tencent.trpc.support.ConsulInstanceManager; import static com.tencent.trpc.support.util.NotifiersServiceUtils.stopAndClearAllNotifiersTask; import static com.tencent.trpc.support.util.NotifiersServiceUtils.unWatchServiceRegisterInfoUpdate; import static com.tencent.trpc.support.util.NotifiersServiceUtils.watchServiceRegisterInfoUpdate; import static com.tencent.trpc.support.util.ConsulServiceUtils.getWatchTimeout; import static com.tencent.trpc.support.util.ConsulServiceUtils.convert; import static com.tencent.trpc.support.util.TtlSchedulerInstanceUtils.stopAndClearAllTtlTask; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.commons.collections4.MapUtils; import static com.tencent.trpc.support.constant.ConsulConstant.CONSUL_SERVICE_INDEX; import static com.tencent.trpc.support.constant.ConsulConstant.ANY_VALUE;
12,882
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.consul; /** * Consul registry. */ @Extension("consul") public class ConsulRegistryCenter extends AbstractFailedRetryRegistryCenter { private static final Logger logger = LoggerFactory.getLogger(ConsulRegistryCenter.class); /** * Consul instance management class. */
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.consul; /** * Consul registry. */ @Extension("consul") public class ConsulRegistryCenter extends AbstractFailedRetryRegistryCenter { private static final Logger logger = LoggerFactory.getLogger(ConsulRegistryCenter.class); /** * Consul instance management class. */
private ConsulInstanceManager consulInstanceManager;
8
2023-10-19 10:54:11+00:00
16k
eclipse-jgit/jgit
org.eclipse.jgit.pgm/src/org/eclipse/jgit/console/ConsoleCredentialsProvider.java
[ { "identifier": "UnsupportedCredentialItem", "path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/UnsupportedCredentialItem.java", "snippet": "public class UnsupportedCredentialItem extends RuntimeException {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Constructs an UnsupportedCr...
import java.io.Console; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.pgm.internal.CLIText; import org.eclipse.jgit.transport.ChainingCredentialsProvider; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.NetRCCredentialsProvider; import org.eclipse.jgit.transport.URIish;
13,839
/* * Copyright (C) 2010, Google Inc. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.console; /** * Interacts with the user during authentication by using the text console. * * @since 4.0 */ public class ConsoleCredentialsProvider extends CredentialsProvider { /** * Install this implementation as the default. */ public static void install() { final ConsoleCredentialsProvider c = new ConsoleCredentialsProvider(); if (c.cons == null) throw new NoClassDefFoundError( CLIText.get().noSystemConsoleAvailable); CredentialsProvider cp = new ChainingCredentialsProvider( new NetRCCredentialsProvider(), c); CredentialsProvider.setDefault(cp); } private final Console cons = System.console(); @Override public boolean isInteractive() { return true; } @Override public boolean supports(CredentialItem... items) { for (CredentialItem i : items) { if (i instanceof CredentialItem.StringType) continue; else if (i instanceof CredentialItem.CharArrayType) continue; else if (i instanceof CredentialItem.YesNoType) continue; else if (i instanceof CredentialItem.InformationalMessage) continue; else return false; } return true; } @Override public boolean get(URIish uri, CredentialItem... items)
/* * Copyright (C) 2010, Google Inc. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.console; /** * Interacts with the user during authentication by using the text console. * * @since 4.0 */ public class ConsoleCredentialsProvider extends CredentialsProvider { /** * Install this implementation as the default. */ public static void install() { final ConsoleCredentialsProvider c = new ConsoleCredentialsProvider(); if (c.cons == null) throw new NoClassDefFoundError( CLIText.get().noSystemConsoleAvailable); CredentialsProvider cp = new ChainingCredentialsProvider( new NetRCCredentialsProvider(), c); CredentialsProvider.setDefault(cp); } private final Console cons = System.console(); @Override public boolean isInteractive() { return true; } @Override public boolean supports(CredentialItem... items) { for (CredentialItem i : items) { if (i instanceof CredentialItem.StringType) continue; else if (i instanceof CredentialItem.CharArrayType) continue; else if (i instanceof CredentialItem.YesNoType) continue; else if (i instanceof CredentialItem.InformationalMessage) continue; else return false; } return true; } @Override public boolean get(URIish uri, CredentialItem... items)
throws UnsupportedCredentialItem {
0
2023-10-20 15:09:17+00:00
16k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/block/TortoiseEggBlock.java
[ { "identifier": "Alligator", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Alligator.java", "snippet": "public class Alligator extends NaturalistAnimal implements IAnimatable, EggLayingAnimal {\n private static final Ingredient FOOD_ITEMS = Ingredient.of(NaturalistTags.I...
import com.starfish_studios.naturalist.common.entity.Alligator; import com.starfish_studios.naturalist.common.entity.Tortoise; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.TurtleEggBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent;
12,400
package com.starfish_studios.naturalist.common.block; public class TortoiseEggBlock extends TurtleEggBlock { public TortoiseEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, (BlockState)state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
package com.starfish_studios.naturalist.common.block; public class TortoiseEggBlock extends TurtleEggBlock { public TortoiseEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, (BlockState)state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
Tortoise tortoise = NaturalistEntityTypes.TORTOISE.get().create(level);
1
2023-10-16 21:54:32+00:00
16k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/UidFragment.java
[ { "identifier": "Utils", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/Utils.java", "snippet": "public class Utils {\n private static final String TAG = \"Utils\";\n //\tpublic final static String ACTION_RECEIVER_CHANGED=\"cn.wq.myandroidtoolspro.receiver_changed\";\n//\tprivate final ...
import android.content.Context; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.recyclerview.toolbar.SearchWithToolbarRecyclerFragment;
12,490
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class UidFragment extends SearchWithToolbarRecyclerFragment { private Pattern pattern=Pattern.compile("[\\d,]+,i,uid,(\\d+),([\\w\\.]+)"); private PackageManager pm; private LoadBatteryTask mTask; private UidAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); pm=getActivity().getPackageManager(); mAdapter=new UidAdapter(getActivity()); setAdapter(mAdapter); mTask=new LoadBatteryTask(); mTask.execute(); initActionbar(0, getString(R.string.uid)); } class LoadBatteryTask extends AsyncTask<Void, Void, List<UidEntry> >{ @Override protected List<UidEntry> doInBackground(Void... arg0) { String sCommand; if(Build.VERSION.SDK_INT>=19){ sCommand="dumpsys batterystats --checkin\n"; }else { sCommand="dumpsys batteryinfo --checkin\n"; } //方法2 // try { // Shell shell=Shell.startRootShell(); // final SparseArray<List<UidEntry>> result=new SparseArray<List<UidEntry>>(); // Command command=new Command(sCommand) { // private int lastUid=-1; // private List<UidEntry> list; // // @Override // public void output(int id, String line) { // Matcher matcher=pattern.matcher(line); // if(matcher.matches()){ // int uid=Integer.valueOf(matcher.group(1)); // UidEntry entry=new UidEntry(); // entry.packageName=matcher.group(2); // try { // entry.icon=pm.getApplicationIcon(entry.packageName); // } catch (NameNotFoundException e) { // e.printStackTrace(); // } // // if(lastUid!=uid){ // if(lastUid==-1){ // list=new ArrayList<UidEntry>(); // }else { // result.put(lastUid, list); // list=new ArrayList<UidEntry>(); // } // } // lastUid=uid; // list.add(entry); // // }else { // if(list!=null){ // result.put(lastUid, list); // list=null; // } // } // } // // @Override // public void afterExecution(int id, int exitCode) { // // } // }; // shell.add(command).waitForFinish(); // shell.close(); // return result; // } catch (Exception e) { // e.printStackTrace(); // }
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class UidFragment extends SearchWithToolbarRecyclerFragment { private Pattern pattern=Pattern.compile("[\\d,]+,i,uid,(\\d+),([\\w\\.]+)"); private PackageManager pm; private LoadBatteryTask mTask; private UidAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); pm=getActivity().getPackageManager(); mAdapter=new UidAdapter(getActivity()); setAdapter(mAdapter); mTask=new LoadBatteryTask(); mTask.execute(); initActionbar(0, getString(R.string.uid)); } class LoadBatteryTask extends AsyncTask<Void, Void, List<UidEntry> >{ @Override protected List<UidEntry> doInBackground(Void... arg0) { String sCommand; if(Build.VERSION.SDK_INT>=19){ sCommand="dumpsys batterystats --checkin\n"; }else { sCommand="dumpsys batteryinfo --checkin\n"; } //方法2 // try { // Shell shell=Shell.startRootShell(); // final SparseArray<List<UidEntry>> result=new SparseArray<List<UidEntry>>(); // Command command=new Command(sCommand) { // private int lastUid=-1; // private List<UidEntry> list; // // @Override // public void output(int id, String line) { // Matcher matcher=pattern.matcher(line); // if(matcher.matches()){ // int uid=Integer.valueOf(matcher.group(1)); // UidEntry entry=new UidEntry(); // entry.packageName=matcher.group(2); // try { // entry.icon=pm.getApplicationIcon(entry.packageName); // } catch (NameNotFoundException e) { // e.printStackTrace(); // } // // if(lastUid!=uid){ // if(lastUid==-1){ // list=new ArrayList<UidEntry>(); // }else { // result.put(lastUid, list); // list=new ArrayList<UidEntry>(); // } // } // lastUid=uid; // list.add(entry); // // }else { // if(list!=null){ // result.put(lastUid, list); // list=null; // } // } // } // // @Override // public void afterExecution(int id, int exitCode) { // // } // }; // shell.add(command).waitForFinish(); // shell.close(); // return result; // } catch (Exception e) { // e.printStackTrace(); // }
List<String> suResult= Utils.runRootCommandForResult(sCommand);
0
2023-10-18 14:32:49+00:00
16k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/impl/DamengDc.java
[ { "identifier": "CalculationMode", "path": "internal/otel-dc/src/main/java/com/instana/dc/CalculationMode.java", "snippet": "public enum CalculationMode {\n DIRECT,\n RATE\n}" }, { "identifier": "DcUtil", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet...
import com.instana.dc.CalculationMode; import com.instana.dc.DcUtil; import com.instana.dc.rdb.AbstractDbDc; import com.instana.dc.rdb.DbDcUtil; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.agent.sensorsdk.semconv.SemanticAttributes.*; import static com.instana.dc.rdb.DbDcUtil.*; import static com.instana.dc.rdb.impl.DamengUtil.*;
11,550
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class DamengDc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(DamengDc.class.getName()); public DamengDc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); findDbNameAndVersion(); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } } private void findDbNameAndVersion() throws SQLException { try (Connection connection = getConnection()) {
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class DamengDc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(DamengDc.class.getName()); public DamengDc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); findDbNameAndVersion(); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } } private void findDbNameAndVersion() throws SQLException { try (Connection connection = getConnection()) {
ResultSet rs = DbDcUtil.executeQuery(connection, DB_NAME_VERSION_SQL);
5
2023-10-23 01:16:38+00:00
16k
histevehu/12306
business/src/main/java/com/steve/train/business/service/TrainService.java
[ { "identifier": "Train", "path": "business/src/main/java/com/steve/train/business/domain/Train.java", "snippet": "public class Train {\n private Long id;\n\n private String code;\n\n private String type;\n\n private String start;\n\n private String startPinyin;\n\n private Date startTi...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.Train; import com.steve.train.business.domain.TrainExample; import com.steve.train.business.mapper.TrainMapper; import com.steve.train.business.req.TrainQueryReq; import com.steve.train.business.req.TrainSaveReq; import com.steve.train.business.resp.TrainQueryResp; import com.steve.train.common.exception.BusinessException; import com.steve.train.common.exception.BusinessExceptionEnum; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List;
11,520
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-29 09:38:38 * @description: 车次服务(FreeMarker生成) */ @Service public class TrainService { private static final Logger LOG = LoggerFactory.getLogger(TrainService.class); @Resource private TrainMapper trainMapper; public void save(TrainSaveReq req) { DateTime now = DateTime.now(); Train train = BeanUtil.copyProperties(req, Train.class); if (ObjectUtil.isNull(train.getId())) { Train trainDB = selectByUnique(req.getCode()); if (ObjectUtil.isNotEmpty(trainDB)) {
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-29 09:38:38 * @description: 车次服务(FreeMarker生成) */ @Service public class TrainService { private static final Logger LOG = LoggerFactory.getLogger(TrainService.class); @Resource private TrainMapper trainMapper; public void save(TrainSaveReq req) { DateTime now = DateTime.now(); Train train = BeanUtil.copyProperties(req, Train.class); if (ObjectUtil.isNull(train.getId())) { Train trainDB = selectByUnique(req.getCode()); if (ObjectUtil.isNotEmpty(trainDB)) {
throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CODE_UNIQUE_ERROR);
7
2023-10-23 01:20:56+00:00
16k
team-moabam/moabam-BE
src/test/java/com/moabam/api/application/notification/NotificationServiceTest.java
[ { "identifier": "MemberService", "path": "src/main/java/com/moabam/api/application/member/MemberService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class MemberService {\n\n\tprivate final RankingService rankingService;\n\tprivate final FcmService fcmSe...
import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.RoomService; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.notification.repository.NotificationRepository; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.infrastructure.fcm.FcmService; import com.moabam.global.auth.model.AuthMember; import com.moabam.global.auth.model.AuthorizationThreadLocal; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ConflictException; import com.moabam.global.error.exception.NotFoundException; import com.moabam.global.error.model.ErrorMessage; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.FilterProcessExtension; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.RoomFixture;
12,354
package com.moabam.api.application.notification; @ExtendWith({MockitoExtension.class, FilterProcessExtension.class}) class NotificationServiceTest { @InjectMocks NotificationService notificationService; @Mock MemberService memberService; @Mock RoomService roomService; @Mock FcmService fcmService; @Mock NotificationRepository notificationRepository; @Mock ParticipantSearchRepository participantSearchRepository; @Mock ClockHolder clockHolder; String successIssueResult = "%s 쿠폰 발행을 성공했습니다. 축하드립니다!"; @DisplayName("상대에게 콕 알림을 성공적으로 보낸다. - Void") @Test void sendKnock_success() { // Given Room room = RoomFixture.room();
package com.moabam.api.application.notification; @ExtendWith({MockitoExtension.class, FilterProcessExtension.class}) class NotificationServiceTest { @InjectMocks NotificationService notificationService; @Mock MemberService memberService; @Mock RoomService roomService; @Mock FcmService fcmService; @Mock NotificationRepository notificationRepository; @Mock ParticipantSearchRepository participantSearchRepository; @Mock ClockHolder clockHolder; String successIssueResult = "%s 쿠폰 발행을 성공했습니다. 축하드립니다!"; @DisplayName("상대에게 콕 알림을 성공적으로 보낸다. - Void") @Test void sendKnock_success() { // Given Room room = RoomFixture.room();
Member member = MemberFixture.member();
2
2023-10-20 06:15:43+00:00
16k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/textfield/XmSimpleTextFieldSkin.java
[ { "identifier": "FxKit", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java", "snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050...
import javafx.geometry.Insets; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.skin.TextFieldSkin; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import java.util.HashMap; import java.util.Map; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.SkinInfo; import com.xm2013.jfx.control.icon.XmSVGIcon; import javafx.application.Platform; import javafx.beans.value.ChangeListener;
12,967
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.textfield; public class XmSimpleTextFieldSkin extends TextFieldSkin { private Map<Integer, SkinInfo> skins = new HashMap<Integer, SkinInfo>(); private XmSimpleTextField control; private XmSVGIcon clearIcon = null; private boolean isSetedPadding = false; public XmSimpleTextFieldSkin(XmSimpleTextField control) { super(control); this.control = control; if(control.isCleanable()){ setCleanable(); } if (this.control.getSuffixIcon() != null) { setSuffixIcon(control.getSuffixIcon()); } updateSkin(1); control.suffixIconProperty().addListener(suffixIconListener); control.colorTypeProperty().addListener(skinListener); control.roundTypeProperty().addListener(skinListener); control.hoverProperty().addListener(statusListener); control.focusedProperty().addListener(statusListener); control.cleanableProperty().addListener(clearIconListener); } /** * 更新组件外观 * * @param status status: 1 : 默认状态下的颜色 * status: 2: hover, out focus * status: 3 : hover,focus状态下的颜色 * status: 4 : out hover, focus状态的颜色 */ private void updateSkin(int status) { if(control.isEnableSkin()){ return; } SkinInfo skin = getSkinInfo(status); Paint outColor = skin.getBorderOutColor(), innerColor = skin.getInnerBorderColor(); BorderWidths innWidths = new BorderWidths(skin.getInnerBorderWidth()), outWidths = new BorderWidths(skin.getOuterBorderWidth()); CornerRadii radiusWidth = new CornerRadii(skin.getRadiusWidth()); if (status == 1) { innerColor = Color.web("#888888"); } Border innBorder = new Border( new BorderStroke(outColor, BorderStrokeStyle.SOLID, radiusWidth, outWidths, skin.getOuterBorderInsets()), new BorderStroke(innerColor, BorderStrokeStyle.SOLID, radiusWidth, innWidths, skin.getInnerBorderInsets()) ); control.setBorder(innBorder); } private SkinInfo getSkinInfo(int status) { SkinInfo info = skins.get(status); if (info == null) { info = new SkinInfo(control.getColorType(), control.getSizeType(), control.getRoundType(), HueType.LIGHT, control.getBorderType()); info.compute(status); skins.put(status, info); } return info; } private void setSuffixIcon(Node nv) { getChildren().add(nv); nv.setManaged(false); Platform.runLater(()->{ Insets padding = control.getPadding(); double w = this.control.prefWidth(-1), h = this.control.prefHeight(-1), sw = nv.prefWidth(-1), sh = nv.prefHeight(-1), x = isSetedPadding?(w - sw):(w + 4), y = (h - sh) / 2 + sh/2 ; if(!isSetedPadding){ padding = new Insets(padding.getTop(), padding.getLeft() + sw, padding.getBottom(), padding.getRight()); control.setPadding(padding); isSetedPadding = true; } nv.setLayoutX(x); nv.setLayoutY(y); }); } /** * 是否可以清除 */ private void setCleanable() { if(clearIcon == null){
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.textfield; public class XmSimpleTextFieldSkin extends TextFieldSkin { private Map<Integer, SkinInfo> skins = new HashMap<Integer, SkinInfo>(); private XmSimpleTextField control; private XmSVGIcon clearIcon = null; private boolean isSetedPadding = false; public XmSimpleTextFieldSkin(XmSimpleTextField control) { super(control); this.control = control; if(control.isCleanable()){ setCleanable(); } if (this.control.getSuffixIcon() != null) { setSuffixIcon(control.getSuffixIcon()); } updateSkin(1); control.suffixIconProperty().addListener(suffixIconListener); control.colorTypeProperty().addListener(skinListener); control.roundTypeProperty().addListener(skinListener); control.hoverProperty().addListener(statusListener); control.focusedProperty().addListener(statusListener); control.cleanableProperty().addListener(clearIconListener); } /** * 更新组件外观 * * @param status status: 1 : 默认状态下的颜色 * status: 2: hover, out focus * status: 3 : hover,focus状态下的颜色 * status: 4 : out hover, focus状态的颜色 */ private void updateSkin(int status) { if(control.isEnableSkin()){ return; } SkinInfo skin = getSkinInfo(status); Paint outColor = skin.getBorderOutColor(), innerColor = skin.getInnerBorderColor(); BorderWidths innWidths = new BorderWidths(skin.getInnerBorderWidth()), outWidths = new BorderWidths(skin.getOuterBorderWidth()); CornerRadii radiusWidth = new CornerRadii(skin.getRadiusWidth()); if (status == 1) { innerColor = Color.web("#888888"); } Border innBorder = new Border( new BorderStroke(outColor, BorderStrokeStyle.SOLID, radiusWidth, outWidths, skin.getOuterBorderInsets()), new BorderStroke(innerColor, BorderStrokeStyle.SOLID, radiusWidth, innWidths, skin.getInnerBorderInsets()) ); control.setBorder(innBorder); } private SkinInfo getSkinInfo(int status) { SkinInfo info = skins.get(status); if (info == null) { info = new SkinInfo(control.getColorType(), control.getSizeType(), control.getRoundType(), HueType.LIGHT, control.getBorderType()); info.compute(status); skins.put(status, info); } return info; } private void setSuffixIcon(Node nv) { getChildren().add(nv); nv.setManaged(false); Platform.runLater(()->{ Insets padding = control.getPadding(); double w = this.control.prefWidth(-1), h = this.control.prefHeight(-1), sw = nv.prefWidth(-1), sh = nv.prefHeight(-1), x = isSetedPadding?(w - sw):(w + 4), y = (h - sh) / 2 + sh/2 ; if(!isSetedPadding){ padding = new Insets(padding.getTop(), padding.getLeft() + sw, padding.getBottom(), padding.getRight()); control.setPadding(padding); isSetedPadding = true; } nv.setLayoutX(x); nv.setLayoutY(y); }); } /** * 是否可以清除 */ private void setCleanable() { if(clearIcon == null){
clearIcon = new XmSVGIcon(FxKit.CLEAN_PATH);
0
2023-10-17 08:57:08+00:00
16k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/BerkeleyParser.java
[ { "identifier": "PTBLineLexer", "path": "src/berkeley_parser/edu/berkeley/nlp/io/PTBLineLexer.java", "snippet": "public class PTBLineLexer extends PTBLexer {\n\n\tpublic PTBLineLexer() {\n\t\tsuper((java.io.Reader) null);\n\t}\n\n\tpublic List<String> tokenizeLine(String line) throws IOException {\n\t\t...
import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.io.FileNotFoundException; import java.util.NoSuchElementException; import javax.imageio.ImageIO; import javax.swing.JFrame; import edu.berkeley.nlp.io.PTBLineLexer; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.ui.TreeJPanel; import edu.berkeley.nlp.util.Numberer;
13,243
} private static class State { short tag; short substate; public State(short tag, short substate) { this.tag = tag; this.substate = substate; } } public static State parseState(String lhs, Grammar grammar) { String lhs_state = lhs.split("_")[0].replace("AT", "@").replace("TICK", "``").replace("DOT", ".").replace("COMMA", ",").replace("HASH", "#").replace("LRB", "-LRB-").replace("RRB", "-RRB-").replace("APOSTROPHE", "''").replace("DOLLAR", "$").replace("COLON", ":").replace("COMMA", ",").replace("PRTADVP", "PRT|ADVP"); int lhs_tag = parseTag(lhs_state, grammar); int lhs_substate = Integer.parseInt(lhs.split("_")[1]); return new State((short) lhs_tag, (short) lhs_substate); } public static double parseProdProb(String str_prob) { return Double.parseDouble(str_prob.substring(1, str_prob.length() - 1)); } public static int parseTag(String lhs_state, Grammar grammar) { try { return grammar.tagNumberer.number(lhs_state); } catch (NoSuchElementException e) { return grammar.tagNumberer.number(lhs_state + "^g"); } } @SuppressWarnings("unchecked") public static void main(String[] args) { OptionParser optParser = new OptionParser(Options.class); Options opts = (Options) optParser.parse(args, true); double threshold = 1.0; if (opts.chinese) Corpus.myTreebank = Corpus.TreeBankType.CHINESE; CoarseToFineMaxRuleParser parser = null; if (opts.nGrammars != 1) { Grammar[] grammars = new Grammar[opts.nGrammars]; Lexicon[] lexicons = new Lexicon[opts.nGrammars]; Binarization bin = null; for (int nGr = 0; nGr < opts.nGrammars; nGr++) { String inFileName = opts.grFileName + "." + nGr; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } grammars[nGr] = pData.getGrammar(); lexicons[nGr] = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); bin = pData.getBinarization(); } parser = new CoarseToFineMaxRuleProductParser(grammars, lexicons, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, true, true); parser.binarization = bin; } else { String inFileName = opts.grFileName; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } Grammar grammar = pData.getGrammar(); if (opts.sub_pcfg != null) { filterGrammarRules(opts.sub_pcfg, grammar); } if (!opts.allRootNodes) { for (UnaryRule item : grammar.unaryRulesWithParent[0]) { if (item.childState != 1) { for (double[] row : item.scores) { Arrays.fill(row, (double)0.0); } } } } Lexicon lexicon = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); if (opts.kbest == 1) parser = new CoarseToFineMaxRuleParser(grammar, lexicon, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, true, true); else parser = new CoarseToFineNBestParser(grammar, lexicon, opts.kbest, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, false, true); parser.binarization = pData.getBinarization(); } MultiThreadedParserWrapper m_parser = null; if (opts.nThreads > 1) { System.err.println("Parsing with " + opts.nThreads + " threads in parallel."); m_parser = new MultiThreadedParserWrapper(parser, opts.nThreads); } try { BufferedReader inputData = (opts.inputFile == null) ? new BufferedReader( new InputStreamReader(System.in)) : new BufferedReader( new InputStreamReader(new FileInputStream(opts.inputFile), "UTF-8")); PrintWriter outputData = (opts.outputFile == null) ? new PrintWriter( new OutputStreamWriter(System.out)) : new PrintWriter( new OutputStreamWriter( new FileOutputStream(opts.outputFile), "UTF-8"), true);
package edu.berkeley.nlp.PCFGLA; /** * Reads in the Penn Treebank and generates N_GRAMMARS different grammars. * * @author Slav Petrov */ public class BerkeleyParser { static TreeJPanel tjp; static JFrame frame; public static class Options { @Option(name = "-gr", required = true, usage = "Grammarfile (Required)\n") public String grFileName; @Option(name = "-tokenize", usage = "Tokenize input first. (Default: false=text is already tokenized)") public boolean tokenize = false; @Option(name = "-viterbi", usage = "Compute viterbi derivation instead of max-rule tree (Default: max-rule)") public boolean viterbi; @Option(name = "-binarize", usage = "Output binarized trees. (Default: false)") public boolean binarize; @Option(name = "-scores", usage = "Output inside scores (only for binarized viterbi trees). (Default: false)") public boolean scores; @Option(name = "-keepFunctionLabels", usage = "Retain predicted function labels. Model must have been trained with function labels. (Default: false)") public boolean keepFunctionLabels; @Option(name = "-substates", usage = "Output subcategories (only for binarized viterbi trees). (Default: false)") public boolean substates; @Option(name = "-accurate", usage = "Set thresholds for accuracy. (Default: set thresholds for efficiency)") public boolean accurate; @Option(name = "-modelScore", usage = "Output effective model score (max rule score for max rule parser) (Default: false)") public boolean modelScore; @Option(name = "-confidence", usage = "Output confidence measure, i.e. likelihood of tree given words: P(T|w) (Default: false)") public boolean confidence; @Option(name = "-sentence_likelihood", usage = "Output sentence likelihood, i.e. summing out all parse trees: P(w) (Default: false)") public boolean sentence_likelihood; @Option(name = "-tree_likelihood", usage = "Output joint likelihood of tree and words: P(t,w) (Default: false)") public boolean tree_likelihood; @Option(name = "-variational", usage = "Use variational rule score approximation instead of max-rule (Default: false)") public boolean variational; @Option(name = "-render", usage = "Write rendered tree to image file. (Default: false)") public boolean render; @Option(name = "-chinese", usage = "Enable some Chinese specific features in the lexicon.") public boolean chinese; @Option(name = "-inputFile", usage = "Read input from this file instead of reading it from STDIN.") public String inputFile; @Option(name = "-maxLength", usage = "Maximum sentence length (Default = 200).") public int maxLength = 200; @Option(name = "-nThreads", usage = "Parse in parallel using n threads (Default: 1).") public int nThreads = 1; @Option(name = "-kbest", usage = "Output the k best parse max-rule trees (Default: 1).") public int kbest = 1; @Option(name = "-outputFile", usage = "Store output in this file instead of printing it to STDOUT.") public String outputFile; @Option(name = "-useGoldPOS", usage = "Read data in CoNLL format, including gold part of speech tags.") public boolean goldPOS; @Option(name = "-dumpPosteriors", usage = "Dump max-rule posteriors to disk.") public boolean dumpPosteriors; @Option(name = "-ec_format", usage = "Use Eugene Charniak's input and output format.") public boolean ec_format; @Option(name = "-nGrammars", usage = "Use a product model based on that many grammars") public int nGrammars = 1; @Option(name = "-allRootNodes", usage = "Use all possible root productions, else only ROOT -> S") public boolean allRootNodes; @Option(name = "-noOutput", usage = "Do not print the trees to stdout") public boolean noOutput; @Option(name = "-sub_pcfg", usage = "PCFG to filter current rules, overwrites original scores") public String sub_pcfg = null; } public static void filterGrammarRules(String file_name, Grammar grammar) { for (int state = 1; state < grammar.numStates; state++) { for (BinaryRule rule : grammar.splitRulesWithP(state)) { for (double[][] rows : rule.scores){ for (double[] row: rows) { if (row == null) { continue; } Arrays.fill(row, 0.0); } } } for (UnaryRule rule : grammar.closedViterbiRulesWithParent[state]) { for (double[] row : rule.scores){ if (row == null) { continue; } Arrays.fill(row, 0.0); } } } try { Scanner scanner = new Scanner(new File(file_name)); grammar.tagNumberer.lock(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] split_line = line.split(" "); if (split_line.length == 5) { // Binary Rules String lhs_str = split_line[0]; String lc_str = split_line[2]; String rc_str = split_line[3]; State lhs = parseState(lhs_str, grammar); State lc = parseState(lc_str, grammar); State rc = parseState(rc_str, grammar); double prob = parseProdProb(split_line[4]); BinaryRule rule = grammar.getBinaryRule(lhs.tag, lc.tag, rc.tag); rule.scores[lc.substate][rc.substate][lhs.substate] = prob; } else if (split_line.length == 4) { // Unary Rules String lhs_str = split_line[0]; String c_str = split_line[2]; if (c_str.startsWith("'")) { continue; } State lhs = parseState(lhs_str, grammar); State c = parseState(c_str, grammar); double prob = parseProdProb(split_line[3]); // But what about UnaryRules outside the Viterbi rules? D: for (UnaryRule rule : grammar.closedViterbiRulesWithParent[lhs.tag]) { if (rule.childState == c.tag) { rule.scores[c.substate][lhs.substate] = prob; break; } } } else { System.err.println(line); } } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } private static class State { short tag; short substate; public State(short tag, short substate) { this.tag = tag; this.substate = substate; } } public static State parseState(String lhs, Grammar grammar) { String lhs_state = lhs.split("_")[0].replace("AT", "@").replace("TICK", "``").replace("DOT", ".").replace("COMMA", ",").replace("HASH", "#").replace("LRB", "-LRB-").replace("RRB", "-RRB-").replace("APOSTROPHE", "''").replace("DOLLAR", "$").replace("COLON", ":").replace("COMMA", ",").replace("PRTADVP", "PRT|ADVP"); int lhs_tag = parseTag(lhs_state, grammar); int lhs_substate = Integer.parseInt(lhs.split("_")[1]); return new State((short) lhs_tag, (short) lhs_substate); } public static double parseProdProb(String str_prob) { return Double.parseDouble(str_prob.substring(1, str_prob.length() - 1)); } public static int parseTag(String lhs_state, Grammar grammar) { try { return grammar.tagNumberer.number(lhs_state); } catch (NoSuchElementException e) { return grammar.tagNumberer.number(lhs_state + "^g"); } } @SuppressWarnings("unchecked") public static void main(String[] args) { OptionParser optParser = new OptionParser(Options.class); Options opts = (Options) optParser.parse(args, true); double threshold = 1.0; if (opts.chinese) Corpus.myTreebank = Corpus.TreeBankType.CHINESE; CoarseToFineMaxRuleParser parser = null; if (opts.nGrammars != 1) { Grammar[] grammars = new Grammar[opts.nGrammars]; Lexicon[] lexicons = new Lexicon[opts.nGrammars]; Binarization bin = null; for (int nGr = 0; nGr < opts.nGrammars; nGr++) { String inFileName = opts.grFileName + "." + nGr; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } grammars[nGr] = pData.getGrammar(); lexicons[nGr] = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); bin = pData.getBinarization(); } parser = new CoarseToFineMaxRuleProductParser(grammars, lexicons, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, true, true); parser.binarization = bin; } else { String inFileName = opts.grFileName; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } Grammar grammar = pData.getGrammar(); if (opts.sub_pcfg != null) { filterGrammarRules(opts.sub_pcfg, grammar); } if (!opts.allRootNodes) { for (UnaryRule item : grammar.unaryRulesWithParent[0]) { if (item.childState != 1) { for (double[] row : item.scores) { Arrays.fill(row, (double)0.0); } } } } Lexicon lexicon = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); if (opts.kbest == 1) parser = new CoarseToFineMaxRuleParser(grammar, lexicon, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, true, true); else parser = new CoarseToFineNBestParser(grammar, lexicon, opts.kbest, threshold, -1, opts.viterbi, opts.substates, opts.scores, opts.accurate, opts.variational, false, true); parser.binarization = pData.getBinarization(); } MultiThreadedParserWrapper m_parser = null; if (opts.nThreads > 1) { System.err.println("Parsing with " + opts.nThreads + " threads in parallel."); m_parser = new MultiThreadedParserWrapper(parser, opts.nThreads); } try { BufferedReader inputData = (opts.inputFile == null) ? new BufferedReader( new InputStreamReader(System.in)) : new BufferedReader( new InputStreamReader(new FileInputStream(opts.inputFile), "UTF-8")); PrintWriter outputData = (opts.outputFile == null) ? new PrintWriter( new OutputStreamWriter(System.out)) : new PrintWriter( new OutputStreamWriter( new FileOutputStream(opts.outputFile), "UTF-8"), true);
PTBLineLexer tokenizer = null;
0
2023-10-22 13:13:22+00:00
16k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/entity/ai/RandomPositionGenerator.java
[ { "identifier": "EntityCreature", "path": "src/minecraft/net/minecraft/entity/EntityCreature.java", "snippet": "public abstract class EntityCreature extends EntityLiving {\n public static final UUID FLEEING_SPEED_MODIFIER_UUID = UUID.fromString(\"E199AD21-BA8A-4C53-8D13-6182D5C69D3A\");\n public sta...
import java.util.Random; import net.minecraft.entity.EntityCreature; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3;
11,530
package net.minecraft.entity.ai; public class RandomPositionGenerator { private static Vec3 staticVector = new Vec3(0.0, 0.0, 0.0);
package net.minecraft.entity.ai; public class RandomPositionGenerator { private static Vec3 staticVector = new Vec3(0.0, 0.0, 0.0);
public static Vec3 findRandomTarget(EntityCreature entitycreatureIn, int xz, int y) {
0
2023-10-15 00:21:15+00:00
16k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/formats/scripts/field/FieldScriptEditor.java
[ { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetE...
import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.ScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.LevelScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.antlr4.ScriptDataProducer; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.*; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditor; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel; import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.*; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.ScriptDocument; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import net.miginfocom.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List;
12,644
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() { addButton.setIcon(PokeditorManager.rowInsertIcon); removeButton.setIcon(PokeditorManager.rowRemoveIcon); confirmButton.setIcon(ThemeUtils.validIcon); discardButton.setIcon(ThemeUtils.reloadIcon); } @Override public void selectedIndexedChanged(int idx, ActionEvent e) { super.selectedIndexedChanged(idx, e); EditorDataModel<FieldScriptContents> model = getModel(); GenericScriptData data = (GenericScriptData) model.getValueFor(idx, null); // errorsList.removeAll(); if (data instanceof ScriptData scriptData) { remove(levelScriptPanel); add(fieldScriptPanel, "cell 1 0"); ScriptDocument document = new ScriptDocument(textPane1); textPane1.setScriptDocument(document); resetDisplayedFieldScriptData(scriptData); try { document.insertString(0, scriptData.toString(), document.getStyle("regular")); } catch (BadLocationException ble) { System.err.println("Couldn't insert initial text into text pane."); } scrollPane1.getVerticalScrollBar().setValue(0); } else if (data instanceof LevelScriptData) { remove(fieldScriptPanel); add(levelScriptPanel, "cell 1 0"); levelScriptDataListModel = new DefaultListModel<>(); levelScriptDataListModel.addAll(data); levelScriptList.setModel(levelScriptDataListModel); } updateUI(); // errorsList.setModel(listModel); } @Override public void addNewEntry() { ResourceBundle bundle = ResourceBundle.getBundle("pokeditor.sheet_panel"); String message = bundle.getString("FieldScriptEditor.newEntryDialog.text"); String fieldScript = bundle.getString("FieldScriptEditor.newEntryDialog.option1.text"); String levelScript = bundle.getString("FieldScriptEditor.newEntryDialog.option2.text"); Object selection = JOptionPane.showInputDialog(this, message, "PokEditor", JOptionPane.INFORMATION_MESSAGE, null, new Object[] {fieldScript, levelScript}, fieldScript); EditorDataModel<FieldScriptContents> model = getModel();
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() { addButton.setIcon(PokeditorManager.rowInsertIcon); removeButton.setIcon(PokeditorManager.rowRemoveIcon); confirmButton.setIcon(ThemeUtils.validIcon); discardButton.setIcon(ThemeUtils.reloadIcon); } @Override public void selectedIndexedChanged(int idx, ActionEvent e) { super.selectedIndexedChanged(idx, e); EditorDataModel<FieldScriptContents> model = getModel(); GenericScriptData data = (GenericScriptData) model.getValueFor(idx, null); // errorsList.removeAll(); if (data instanceof ScriptData scriptData) { remove(levelScriptPanel); add(fieldScriptPanel, "cell 1 0"); ScriptDocument document = new ScriptDocument(textPane1); textPane1.setScriptDocument(document); resetDisplayedFieldScriptData(scriptData); try { document.insertString(0, scriptData.toString(), document.getStyle("regular")); } catch (BadLocationException ble) { System.err.println("Couldn't insert initial text into text pane."); } scrollPane1.getVerticalScrollBar().setValue(0); } else if (data instanceof LevelScriptData) { remove(fieldScriptPanel); add(levelScriptPanel, "cell 1 0"); levelScriptDataListModel = new DefaultListModel<>(); levelScriptDataListModel.addAll(data); levelScriptList.setModel(levelScriptDataListModel); } updateUI(); // errorsList.setModel(listModel); } @Override public void addNewEntry() { ResourceBundle bundle = ResourceBundle.getBundle("pokeditor.sheet_panel"); String message = bundle.getString("FieldScriptEditor.newEntryDialog.text"); String fieldScript = bundle.getString("FieldScriptEditor.newEntryDialog.option1.text"); String levelScript = bundle.getString("FieldScriptEditor.newEntryDialog.option2.text"); Object selection = JOptionPane.showInputDialog(this, message, "PokEditor", JOptionPane.INFORMATION_MESSAGE, null, new Object[] {fieldScript, levelScript}, fieldScript); EditorDataModel<FieldScriptContents> model = getModel();
if (model instanceof FormatModel<?, ?> formatModel)
5
2023-10-15 05:00:57+00:00
16k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q20.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE;
14,190
package benchmark.olap.query; public class Q20 extends baseQuery { private static Logger log = Logger.getLogger(Q20.class); public double k; public double b; private int dbType; public Q20(int dbType) throws ParseException { super();
package benchmark.olap.query; public class Q20 extends baseQuery { private static Logger log = Logger.getLogger(Q20.class); public double k; public double b; private int dbType; public Q20(int dbType) throws ParseException { super();
this.k = OLTPClient.k2;
1
2023-10-22 11:22:32+00:00
16k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/entities/factories/ShipFactory.java
[ { "identifier": "ParticleEffectComponent", "path": "source/core/src/main/com/csse3200/game/components/ParticleEffectComponent.java", "snippet": "public class ParticleEffectComponent extends Component {\n\n\t/**\n\t * Store of all the particle effects that will be rendered on an entity at the one time. T...
import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.csse3200.game.components.ParticleEffectComponent; import com.csse3200.game.components.ship.*; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityType; import com.csse3200.game.physics.components.ColliderComponent; import com.csse3200.game.physics.components.HitboxComponent; import com.csse3200.game.physics.components.PhysicsComponent; import com.csse3200.game.physics.components.PhysicsMovementComponent; import com.csse3200.game.rendering.AnimationRenderComponent; import com.csse3200.game.services.ServiceLocator;
14,209
package com.csse3200.game.entities.factories; public class ShipFactory { public enum events { ADD_PART, REMOVE_PART, PROGRESS_UPDATED } /** * Creates a ship entity * * @return ship entity */ public static Entity createShip() { AnimationRenderComponent animator = setupShipAnimations(); Entity ship = new Entity(EntityType.SHIP)
package com.csse3200.game.entities.factories; public class ShipFactory { public enum events { ADD_PART, REMOVE_PART, PROGRESS_UPDATED } /** * Creates a ship entity * * @return ship entity */ public static Entity createShip() { AnimationRenderComponent animator = setupShipAnimations(); Entity ship = new Entity(EntityType.SHIP)
.addComponent(new PhysicsComponent())
5
2023-10-17 22:34:04+00:00
16k
moeinfatehi/PassiveDigger
src/PassiveDigger/reqRespForm.java
[ { "identifier": "BurpExtender", "path": "src/burp/BurpExtender.java", "snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public ...
import burp.BurpExtender; import burp.IBurpExtenderCallbacks; import burp.IHttpRequestResponse; import burp.IHttpService; import burp.IMessageEditor; import burp.IMessageEditorController; import burp.IRequestInfo; import javax.swing.table.DefaultTableModel;
12,587
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package PassiveDigger; /** * * @author moein */ public class reqRespForm extends javax.swing.JFrame implements IMessageEditorController{ DefaultTableModel model;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package PassiveDigger; /** * * @author moein */ public class reqRespForm extends javax.swing.JFrame implements IMessageEditorController{ DefaultTableModel model;
private static IHttpRequestResponse thisReqResp;
2
2023-10-23 12:13:00+00:00
16k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/UserController.java
[ { "identifier": "ErrorCode", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/ErrorCode.java", "snippet": "public class ErrorCode {\n\tpublic static final String AUTH_TOKEN_NOT_FOUND = \"AUTH_TOKEN_NOT_FOUND\";\n\tpublic static final String AUTH_TOKEN_INVALID = \"AUTH_TOKEN_INVAL...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.rrd.senseeact.client.exception.ErrorCode; import nl.rrd.senseeact.client.exception.HttpError; import nl.rrd.senseeact.client.exception.HttpFieldError; import nl.rrd.senseeact.client.model.ListUser; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.compat.*; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.service.*; import nl.rrd.senseeact.service.exception.BadRequestException; import nl.rrd.senseeact.service.exception.ForbiddenException; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.exception.NotFoundException; import nl.rrd.senseeact.service.mail.EmailSender; import nl.rrd.senseeact.service.mail.EmailTemplate; import nl.rrd.senseeact.service.mail.EmailTemplateCollection; import nl.rrd.senseeact.service.mail.EmailTemplateRepository; import nl.rrd.senseeact.service.model.UserTable; import nl.rrd.senseeact.service.model.*; import nl.rrd.senseeact.service.validation.ModelValidation; import nl.rrd.utils.AppComponents; import nl.rrd.utils.beans.PropertyReader; import nl.rrd.utils.beans.PropertyWriter; import nl.rrd.utils.datetime.DateTimeUtils; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.exception.ParseException; import nl.rrd.utils.validation.TypeConversion; import org.slf4j.Logger; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.*;
11,747
final String email) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doGetUser(version, authDb, user, userId, email), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.PUT) @RequestBody( content = { @Content( mediaType = "application/json", schema = @Schema(type = "string") ) } ) public DatabaseObject setUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail, @RequestParam(value="emailTemplate", required=false, defaultValue="") String emailTemplate) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doSetUser(version, authDb, user, userId, compatEmail, emailTemplate, request), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.DELETE) public void deleteUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, user) -> doDeleteUser(version, authDb, user, userId, compatEmail), versionName, request, response); } @RequestMapping(value="/role", method=RequestMethod.PUT) public void setRole( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="role") final String role) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetRole(version, authDb, currUser, user, role), versionName, request, response); } @RequestMapping(value="/active", method=RequestMethod.PUT) public void setActive( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="active") final String active) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetActive(version, authDb, currUser, user, active), versionName, request, response); } @RequestMapping(value="/groups", method=RequestMethod.GET) public List<String> getGroups( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String user) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, currUser) -> doGetGroups(version, authDb, currUser, user), versionName, request, response); } private Object doSetRole(ProtocolVersion version, Database authDb, User currUser, String setUserId, String role) throws HttpException, Exception { if (currUser.getRole() != Role.ADMIN) throw new ForbiddenException(); UserCache userCache = UserCache.getInstance(); User setUser = userCache.find(version, setUserId); if (setUser == null) { throw new NotFoundException(String.format("User %s not found", setUserId)); } if (setUser.getUserid().equals(currUser.getUserid())) throw new ForbiddenException("Can't set role of yourself"); Role roleEnum; try { roleEnum = TypeConversion.getEnum(role, Role.class); } catch (ParseException ex) { String msg = "Invalid role: " + role;
package nl.rrd.senseeact.service.controller; @RestController @RequestMapping("/v{version}/user") public class UserController { public static final List<String> CHANGE_FORBIDDEN_FIELDS = List.of( "userid", "emailVerified", "emailPendingVerification", "hasTemporaryEmail", "hasTemporaryPassword", "role", "active", "created", "lastActive" ); @RequestMapping(value="/list", method=RequestMethod.GET) public List<ListUser> getUserList( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName) throws HttpException, Exception { return QueryRunner.runAuthQuery((version, authDb, user) -> doGetUserList(version, user), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.GET) public DatabaseObject getUser( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @RequestParam(value="email", required=false, defaultValue="") final String email) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doGetUser(version, authDb, user, userId, email), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.PUT) @RequestBody( content = { @Content( mediaType = "application/json", schema = @Schema(type = "string") ) } ) public DatabaseObject setUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail, @RequestParam(value="emailTemplate", required=false, defaultValue="") String emailTemplate) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doSetUser(version, authDb, user, userId, compatEmail, emailTemplate, request), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.DELETE) public void deleteUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, user) -> doDeleteUser(version, authDb, user, userId, compatEmail), versionName, request, response); } @RequestMapping(value="/role", method=RequestMethod.PUT) public void setRole( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="role") final String role) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetRole(version, authDb, currUser, user, role), versionName, request, response); } @RequestMapping(value="/active", method=RequestMethod.PUT) public void setActive( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="active") final String active) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetActive(version, authDb, currUser, user, active), versionName, request, response); } @RequestMapping(value="/groups", method=RequestMethod.GET) public List<String> getGroups( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String user) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, currUser) -> doGetGroups(version, authDb, currUser, user), versionName, request, response); } private Object doSetRole(ProtocolVersion version, Database authDb, User currUser, String setUserId, String role) throws HttpException, Exception { if (currUser.getRole() != Role.ADMIN) throw new ForbiddenException(); UserCache userCache = UserCache.getInstance(); User setUser = userCache.find(version, setUserId); if (setUser == null) { throw new NotFoundException(String.format("User %s not found", setUserId)); } if (setUser.getUserid().equals(currUser.getUserid())) throw new ForbiddenException("Can't set role of yourself"); Role roleEnum; try { roleEnum = TypeConversion.getEnum(role, Role.class); } catch (ParseException ex) { String msg = "Invalid role: " + role;
HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg);
1
2023-10-24 09:36:50+00:00
16k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/swerve/Swerve.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train...
import edu.wpi.first.math.Matrix; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N3; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Subsystem; import frc.robot.Robot; import frc.robot.RobotTelemetry; import frc.robot.swerve.configs.MUSICDISC2023; import frc.robot.swerve.configs.NOTEBLOCK2023; import frc.spectrumLib.swerve.Drivetrain; import frc.spectrumLib.swerve.Drivetrain.DriveState; import frc.spectrumLib.swerve.Request; import frc.spectrumLib.swerve.config.SwerveConfig; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Supplier; import org.littletonrobotics.junction.Logger;
11,529
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() {
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() {
RobotTelemetry.print("Swerve Subsystem Starting: ");
1
2023-10-23 17:01:53+00:00
16k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/admin/tags/TagServiceImpl.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static fi...
import org.hibernate.exception.SQLGrammarException; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.SynchronizableItem; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.EntityServiceContext; import org.msh.etbm.commons.entities.EntityServiceImpl; import org.msh.etbm.commons.entities.ServiceResult; import org.msh.etbm.commons.entities.query.QueryBuilder; import org.msh.etbm.db.entities.Tag; import org.msh.etbm.services.cases.tag.AutoGenTagsCasesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.Errors; import javax.persistence.PersistenceException;
11,669
package org.msh.etbm.services.admin.tags; /** * Created by rmemoria on 6/1/16. */ @Service public class TagServiceImpl extends EntityServiceImpl<Tag, TagQueryParams> implements TagService { @Autowired AutoGenTagsCasesService autoGenTagsCasesService; @Override protected void buildQuery(QueryBuilder<Tag> builder, TagQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(TagQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(TagQueryParams.ORDERBY_TYPE, "classification, name"); // profiles builder.addDefaultProfile(TagQueryParams.PROFILE_DEFAULT, TagData.class); builder.addProfile(TagQueryParams.PROFILE_ITEM, SynchronizableItem.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } } @Override
package org.msh.etbm.services.admin.tags; /** * Created by rmemoria on 6/1/16. */ @Service public class TagServiceImpl extends EntityServiceImpl<Tag, TagQueryParams> implements TagService { @Autowired AutoGenTagsCasesService autoGenTagsCasesService; @Override protected void buildQuery(QueryBuilder<Tag> builder, TagQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(TagQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(TagQueryParams.ORDERBY_TYPE, "classification, name"); // profiles builder.addDefaultProfile(TagQueryParams.PROFILE_DEFAULT, TagData.class); builder.addProfile(TagQueryParams.PROFILE_ITEM, SynchronizableItem.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } } @Override
protected void afterSave(EntityServiceContext<Tag> context, ServiceResult res) {
5
2023-10-23 13:47:54+00:00
16k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/config/OlympiceneFacade.java
[ { "identifier": "TaskCategory", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/task/TaskCategory.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum TaskCategory {\n // 调用函数服务的Task\n FUNCTION(\"function\", 0),\n\n // 流程控制Task,执行分支语句\n ...
import com.google.common.collect.Maps; import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory; import com.weibo.rill.flow.olympicene.core.event.Callback; import com.weibo.rill.flow.olympicene.core.result.DAGResultHandler; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.storage.redis.api.RedisClient; import com.weibo.rill.flow.olympicene.traversal.DAGOperations; import com.weibo.rill.flow.olympicene.traversal.DAGTraversal; import com.weibo.rill.flow.olympicene.traversal.Olympicene; import com.weibo.rill.flow.olympicene.traversal.callback.DAGCallbackInfo; import com.weibo.rill.flow.olympicene.traversal.checker.TimeChecker; import com.weibo.rill.flow.olympicene.traversal.dispatcher.DAGDispatcher; import com.weibo.rill.flow.olympicene.traversal.helper.DefaultStasher; import com.weibo.rill.flow.olympicene.traversal.helper.SameThreadExecutorService; import com.weibo.rill.flow.olympicene.traversal.helper.Stasher; import com.weibo.rill.flow.olympicene.traversal.mappings.InputOutputMapping; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPath; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.olympicene.traversal.runners.*; import java.util.Map; import java.util.concurrent.ExecutorService;
13,145
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.olympicene.traversal.config; public class OlympiceneFacade { public static Olympicene build(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, Callback<DAGCallbackInfo> callback, DAGDispatcher dagDispatcher, DAGStorageProcedure dagStorageProcedure, TimeChecker timeChecker, SwitcherManager switcherManager) { ExecutorService executor = SameThreadExecutorService.INSTANCE; return build(dagInfoStorage, dagContextStorage, dagStorageProcedure, callback, null, dagDispatcher, timeChecker, executor, switcherManager); } public static Olympicene build(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGStorageProcedure dagStorageProcedure, Callback<DAGCallbackInfo> callback, DAGResultHandler dagResultHandler, DAGDispatcher dagDispatcher, TimeChecker timeChecker, ExecutorService executor, SwitcherManager switcherManager) { JSONPathInputOutputMapping jsonPathInputOutputMapping = new JSONPathInputOutputMapping(); DefaultStasher stasher = new DefaultStasher(); DAGRunner dagRunner = new DAGRunner(dagContextStorage, dagInfoStorage, dagStorageProcedure); dagRunner.setStasher(stasher); TimeCheckRunner timeCheckRunner = new TimeCheckRunner(timeChecker, dagInfoStorage, dagContextStorage, dagStorageProcedure); Map<String, TaskRunner> taskRunners = buildTaskRunners(dagInfoStorage, dagContextStorage, dagDispatcher, jsonPathInputOutputMapping, jsonPathInputOutputMapping, dagStorageProcedure, stasher, switcherManager); DAGTraversal dagTraversal = new DAGTraversal(dagContextStorage, dagInfoStorage, dagStorageProcedure, executor); DAGOperations dagOperations = new DAGOperations(executor, taskRunners, dagRunner, timeCheckRunner, dagTraversal, callback, dagResultHandler); dagTraversal.setDagOperations(dagOperations); dagTraversal.setStasher(stasher); timeCheckRunner.setDagOperations(dagOperations); return new Olympicene(dagInfoStorage, dagOperations, executor, dagResultHandler); } public static Map<String, TaskRunner> buildTaskRunners(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGDispatcher dagDispatcher, InputOutputMapping mapping, JSONPath jsonPath, DAGStorageProcedure dagStorageProcedure, Stasher stasher, SwitcherManager switcherManager) { PassTaskRunner passTaskRunner = new PassTaskRunner(mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); FunctionTaskRunner functionTaskRunner = new FunctionTaskRunner(dagDispatcher, mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); SuspenseTaskRunner suspenseTaskRunner = new SuspenseTaskRunner(mapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); ReturnTaskRunner returnTaskRunner = new ReturnTaskRunner(mapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); ForeachTaskRunner foreachTaskRunner = new ForeachTaskRunner(mapping, jsonPath, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); foreachTaskRunner.setStasher(stasher); ChoiceTaskRunner choiceTaskRunner = new ChoiceTaskRunner(mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); Map<String, TaskRunner> runners = Maps.newConcurrentMap();
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.olympicene.traversal.config; public class OlympiceneFacade { public static Olympicene build(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, Callback<DAGCallbackInfo> callback, DAGDispatcher dagDispatcher, DAGStorageProcedure dagStorageProcedure, TimeChecker timeChecker, SwitcherManager switcherManager) { ExecutorService executor = SameThreadExecutorService.INSTANCE; return build(dagInfoStorage, dagContextStorage, dagStorageProcedure, callback, null, dagDispatcher, timeChecker, executor, switcherManager); } public static Olympicene build(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGStorageProcedure dagStorageProcedure, Callback<DAGCallbackInfo> callback, DAGResultHandler dagResultHandler, DAGDispatcher dagDispatcher, TimeChecker timeChecker, ExecutorService executor, SwitcherManager switcherManager) { JSONPathInputOutputMapping jsonPathInputOutputMapping = new JSONPathInputOutputMapping(); DefaultStasher stasher = new DefaultStasher(); DAGRunner dagRunner = new DAGRunner(dagContextStorage, dagInfoStorage, dagStorageProcedure); dagRunner.setStasher(stasher); TimeCheckRunner timeCheckRunner = new TimeCheckRunner(timeChecker, dagInfoStorage, dagContextStorage, dagStorageProcedure); Map<String, TaskRunner> taskRunners = buildTaskRunners(dagInfoStorage, dagContextStorage, dagDispatcher, jsonPathInputOutputMapping, jsonPathInputOutputMapping, dagStorageProcedure, stasher, switcherManager); DAGTraversal dagTraversal = new DAGTraversal(dagContextStorage, dagInfoStorage, dagStorageProcedure, executor); DAGOperations dagOperations = new DAGOperations(executor, taskRunners, dagRunner, timeCheckRunner, dagTraversal, callback, dagResultHandler); dagTraversal.setDagOperations(dagOperations); dagTraversal.setStasher(stasher); timeCheckRunner.setDagOperations(dagOperations); return new Olympicene(dagInfoStorage, dagOperations, executor, dagResultHandler); } public static Map<String, TaskRunner> buildTaskRunners(DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGDispatcher dagDispatcher, InputOutputMapping mapping, JSONPath jsonPath, DAGStorageProcedure dagStorageProcedure, Stasher stasher, SwitcherManager switcherManager) { PassTaskRunner passTaskRunner = new PassTaskRunner(mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); FunctionTaskRunner functionTaskRunner = new FunctionTaskRunner(dagDispatcher, mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); SuspenseTaskRunner suspenseTaskRunner = new SuspenseTaskRunner(mapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); ReturnTaskRunner returnTaskRunner = new ReturnTaskRunner(mapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); ForeachTaskRunner foreachTaskRunner = new ForeachTaskRunner(mapping, jsonPath, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); foreachTaskRunner.setStasher(stasher); ChoiceTaskRunner choiceTaskRunner = new ChoiceTaskRunner(mapping, dagContextStorage, dagInfoStorage, dagStorageProcedure, switcherManager); Map<String, TaskRunner> runners = Maps.newConcurrentMap();
runners.put(TaskCategory.FUNCTION.getValue(), functionTaskRunner);
0
2023-11-03 03:46:01+00:00
16k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/main/java/org/example/service/impl/OrderServiceImpl.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alicloud.openservices.tablestore.model.search.sort.FieldSort; import com.alicloud.openservices.tablestore.model.search.sort.Sort.Sorter; import com.alicloud.openservices.tablestore.model.search.sort.SortOrder; import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.ComputeNestConstants; import org.example.common.constant.OrderOtsConstant; import org.example.common.constant.PayPeriodUnit; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.helper.BaseOtsHelper.OtsFilter; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.ServiceMetadataModel; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.GetServiceMetadataParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.common.param.UpdateServiceInstanceAttributeParam; import org.example.common.utils.BeanUtil; import org.example.common.utils.DateUtil; import org.example.common.utils.JsonUtil; import org.example.common.utils.UuidUtil; import org.example.service.AlipayService; import org.example.service.OrderService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD_UNIT;
12,805
/* *Copyright (c) Alibaba Group; *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 org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue();
/* *Copyright (c) Alibaba Group; *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 org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue();
PayPeriodUnit payPeriodUnit = PayPeriodUnit.valueOf(String.valueOf(nestParameters.remove(PAY_PERIOD_UNIT)));
4
2023-11-01 08:19:34+00:00
16k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/adapter/flashcard/SetAllAdapter.java
[ { "identifier": "CardDAO", "path": "app/src/main/java/com/daominh/quickmem/data/dao/CardDAO.java", "snippet": "public class CardDAO {\n QMDatabaseHelper qmDatabaseHelper;\n SQLiteDatabase sqLiteDatabase;\n\n public CardDAO(Context context) {\n qmDatabaseHelper = new QMDatabaseHelper(cont...
import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.data.dao.CardDAO; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.User; import com.daominh.quickmem.databinding.ItemSetAllBinding; import com.daominh.quickmem.ui.activities.set.ViewSetActivity; import com.squareup.picasso.Picasso; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
11,988
package com.daominh.quickmem.adapter.flashcard; public class SetAllAdapter extends RecyclerView.Adapter<SetAllAdapter.SetsViewHolder> { private final Context context; private final ArrayList<FlashCard> sets; public SetAllAdapter(Context context, ArrayList<FlashCard> sets) { this.context = context; this.sets = sets; } @NonNull @NotNull @Override public SetAllAdapter.SetsViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); ItemSetAllBinding binding = ItemSetAllBinding.inflate(inflater, parent, false); return new SetsViewHolder(binding.getRoot()); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull @NotNull SetAllAdapter.SetsViewHolder holder, int position) { FlashCard set = sets.get(position); CardDAO cardDAO = new CardDAO(context); int count = cardDAO.countCardByFlashCardId(set.getId()); UserDAO userDAO = new UserDAO(context);
package com.daominh.quickmem.adapter.flashcard; public class SetAllAdapter extends RecyclerView.Adapter<SetAllAdapter.SetsViewHolder> { private final Context context; private final ArrayList<FlashCard> sets; public SetAllAdapter(Context context, ArrayList<FlashCard> sets) { this.context = context; this.sets = sets; } @NonNull @NotNull @Override public SetAllAdapter.SetsViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); ItemSetAllBinding binding = ItemSetAllBinding.inflate(inflater, parent, false); return new SetsViewHolder(binding.getRoot()); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull @NotNull SetAllAdapter.SetsViewHolder holder, int position) { FlashCard set = sets.get(position); CardDAO cardDAO = new CardDAO(context); int count = cardDAO.countCardByFlashCardId(set.getId()); UserDAO userDAO = new UserDAO(context);
User user = userDAO.getUserById(set.getUser_id());
3
2023-11-07 16:56:39+00:00
16k
estkme-group/InfiLPA
app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java
[ { "identifier": "LocalProfileAssistantCoreImpl", "path": "core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java", "snippet": "public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore {\n private static final String TAG = LocalProfileAssistantCoreImpl....
import androidx.lifecycle.MutableLiveData; import com.infineon.esim.lpa.core.LocalProfileAssistantCoreImpl; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.data.StatusAndEventHandler; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.euicc.base.EuiccConnection; import com.infineon.esim.lpa.euicc.base.EuiccConnectionConsumer; import com.infineon.esim.lpa.lpa.task.AuthenticateTask; import com.infineon.esim.lpa.lpa.task.CancelSessionTask; import com.infineon.esim.lpa.lpa.task.DownloadTask; import com.infineon.esim.lpa.lpa.task.GetEuiccInfoTask; import com.infineon.esim.lpa.lpa.task.GetProfileListTask; import com.infineon.esim.lpa.lpa.task.HandleAndClearAllNotificationsTask; import com.infineon.esim.lpa.lpa.task.ProfileActionTask; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.InternetConnectionConsumer; import com.infineon.esim.lpa.util.threading.TaskRunner; import com.infineon.esim.util.Log;
14,306
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver;
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver;
private EuiccConnection euiccConnection;
11
2023-11-06 02:41:13+00:00
16k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
12,065
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service
public class VodServiceImpl implements VodService {
26
2023-11-03 10:05:02+00:00
16k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
12,793
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired
private InformDao informDao;
5
2023-11-03 02:29:57+00:00
16k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/d...
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,958
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) {
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) {
super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER);
10
2023-11-06 21:25:54+00:00
16k