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
By1337/BAuction
Core/src/main/java/org/by1337/bauction/menu/impl/ItemsForSaleMenu.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.entity.Player; import org.by1337.api.chat.Placeholderable; import org.by1337.api.command.Command; import org.by1337.api.command.CommandException; import org.by1337.api.command.argument.ArgumentSetList; import org.by1337.api.command.argument.ArgumentString; import org.by1337.bauction.Main; import org.by1337.bauction.action.TakeItemProcess; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.menu.CustomItemStack; import org.by1337.bauction.menu.Menu; import org.by1337.bauction.menu.command.DefaultMenuCommand; import org.by1337.bauction.util.CUniqueName; import org.by1337.api.util.Pair; import org.by1337.bauction.util.UniqueName; import javax.annotation.Nullable; import java.util.*;
13,107
package org.by1337.bauction.menu.impl; public class ItemsForSaleMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public ItemsForSaleMenu(Player player, User user) { this(player, user, null); } public ItemsForSaleMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getItemsForSaleMenu(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getItemsForSaleSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { sellItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS);
package org.by1337.bauction.menu.impl; public class ItemsForSaleMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public ItemsForSaleMenu(Player player, User user) { this(player, user, null); } public ItemsForSaleMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getItemsForSaleMenu(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getItemsForSaleSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { sellItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS);
UniqueName uuid = new CUniqueName(uuidS);
8
2023-11-08 18:25:18+00:00
16k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/item/ItemFactory.java
[ { "identifier": "CrypticLib", "path": "common/src/main/java/crypticlib/CrypticLib.java", "snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ...
import crypticlib.CrypticLib; import crypticlib.function.TernaryFunction; import crypticlib.nms.item.v1_12_R1.V1_12_R1NbtItem; import crypticlib.nms.item.v1_13_R1.V1_13_R1NbtItem; import crypticlib.nms.item.v1_13_R2.V1_13_R2NbtItem; import crypticlib.nms.item.v1_14_R1.V1_14_R1NbtItem; import crypticlib.nms.item.v1_15_R1.V1_15_R1NbtItem; import crypticlib.nms.item.v1_16_R1.V1_16_R1NbtItem; import crypticlib.nms.item.v1_16_R2.V1_16_R2NbtItem; import crypticlib.nms.item.v1_16_R3.V1_16_R3NbtItem; import crypticlib.nms.item.v1_17_R1.V1_17_R1NbtItem; import crypticlib.nms.item.v1_18_R1.V1_18_R1NbtItem; import crypticlib.nms.item.v1_18_R2.V1_18_R2NbtItem; import crypticlib.nms.item.v1_19_R1.V1_19_R1NbtItem; import crypticlib.nms.item.v1_19_R2.V1_19_R2NbtItem; import crypticlib.nms.item.v1_19_R3.V1_19_R3NbtItem; import crypticlib.nms.item.v1_20_R1.V1_20_R1NbtItem; import crypticlib.nms.item.v1_20_R2.V1_20_R2NbtItem; import crypticlib.nms.item.v1_20_R3.V1_20_R3NbtItem; import crypticlib.nms.nbt.NbtFactory; import crypticlib.nms.nbt.NbtTagCompound; import crypticlib.util.MaterialUtil; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Function;
12,845
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new); regNbtItemProvider("v1_15_R1", V1_15_R1NbtItem::new, V1_15_R1NbtItem::new, V1_15_R1NbtItem::new); regNbtItemProvider("v1_16_R1", V1_16_R1NbtItem::new, V1_16_R1NbtItem::new, V1_16_R1NbtItem::new); regNbtItemProvider("v1_16_R2", V1_16_R2NbtItem::new, V1_16_R2NbtItem::new, V1_16_R2NbtItem::new);
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new); regNbtItemProvider("v1_15_R1", V1_15_R1NbtItem::new, V1_15_R1NbtItem::new, V1_15_R1NbtItem::new); regNbtItemProvider("v1_16_R1", V1_16_R1NbtItem::new, V1_16_R1NbtItem::new, V1_16_R1NbtItem::new); regNbtItemProvider("v1_16_R2", V1_16_R2NbtItem::new, V1_16_R2NbtItem::new, V1_16_R2NbtItem::new);
regNbtItemProvider("v1_16_R3", V1_16_R3NbtItem::new, V1_16_R3NbtItem::new, V1_16_R3NbtItem::new);
9
2023-11-07 12:39:20+00:00
16k
ynwynw/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;
13,974
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; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId");
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; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId");
List<SystemTypeList> typeList = typeDao.findByTypeModel("inform");
16
2023-11-03 02:08:22+00:00
16k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
13,325
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension
getArchiveBaseName().set(modFusionerExtension.getMergedJarName());
6
2023-11-03 23:19:08+00:00
16k
data-harness-cloud/data_harness-be
common/common-log/src/main/java/supie/common/log/aop/OperationLogAspect.java
[ { "identifier": "ApplicationConstant", "path": "common/common-core/src/main/java/supie/common/core/constant/ApplicationConstant.java", "snippet": "public final class ApplicationConstant {\n\n /**\n * 适用于所有类型的字典格式数据。该常量为字典的键字段。\n */\n public static final String DICT_ID = \"id\";\n /**\n ...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.BooleanUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import supie.common.core.constant.ApplicationConstant; import supie.common.core.object.ResponseResult; import supie.common.core.object.TokenData; import supie.common.core.util.ContextUtil; import supie.common.core.util.IpUtil; import supie.common.core.util.MyCommonUtil; import supie.common.log.annotation.IgnoreResponseLog; import supie.common.log.annotation.OperationLog; import supie.common.log.config.OperationLogProperties; import supie.common.log.model.SysOperationLog; import supie.common.log.model.constant.SysOperationLogType; import supie.common.log.service.SysOperationLogService; import supie.common.sequence.wrapper.IdGeneratorWrapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*;
13,955
package supie.common.log.aop; /** * 操作日志记录处理AOP对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Aspect @Component @Order(1) @Slf4j public class OperationLogAspect { @Value("${spring.application.name}") private String serviceName; @Autowired private SysOperationLogService operationLogService; @Autowired
package supie.common.log.aop; /** * 操作日志记录处理AOP对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Aspect @Component @Order(1) @Slf4j public class OperationLogAspect { @Value("${spring.application.name}") private String serviceName; @Autowired private SysOperationLogService operationLogService; @Autowired
private OperationLogProperties properties;
6
2023-11-04 12:36:44+00:00
16k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
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.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
11,229
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; 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); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); }
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; 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); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); }
if (RUN_USING_ENCODER) {
9
2023-11-03 13:32:48+00:00
16k
beminder/BeautyMinder
java/src/test/java/app/beautyminder/controller/elasticsearch/DataViewApiControllerTest.java
[ { "identifier": "TokenProvider", "path": "java/src/main/java/app/beautyminder/config/jwt/TokenProvider.java", "snippet": "@Slf4j\n@RequiredArgsConstructor\n@Service\npublic class TokenProvider {\n\n private final JwtProperties jwtProperties;\n private final UserRepository userRepository;\n\n pu...
import app.beautyminder.config.jwt.TokenProvider; import app.beautyminder.domain.User; import app.beautyminder.dto.CosmeticMetricData; import app.beautyminder.dto.user.AddUserRequest; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.service.cosmetic.CosmeticSearchService; import app.beautyminder.service.cosmetic.ReviewSearchService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.time.Duration; import java.util.List; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
11,422
package app.beautyminder.controller.elasticsearch; @Slf4j @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ActiveProfiles({"awsBasic", "test"}) public class DataViewApiControllerTest { private static final Duration ACCESS_TOKEN_DURATION = Duration.ofMinutes(3); private static final String TEST_ADMIN_EMAIL = "dataviewadmin@test.com"; private static final String TEST_ADMIN_PASSWORD = "test"; @Autowired protected MockMvc mockMvc; @MockBean private ReviewSearchService reviewSearchService; @MockBean private CosmeticRankService cosmeticRankService; @MockBean private CosmeticSearchService cosmeticSearchService; @Autowired private WebApplicationContext context; @Autowired private UserService userService; @Autowired private TokenProvider tokenProvider; private String accessToken; private String userId; @BeforeEach public void mockMvcSetUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @BeforeAll public void initialize() {
package app.beautyminder.controller.elasticsearch; @Slf4j @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ActiveProfiles({"awsBasic", "test"}) public class DataViewApiControllerTest { private static final Duration ACCESS_TOKEN_DURATION = Duration.ofMinutes(3); private static final String TEST_ADMIN_EMAIL = "dataviewadmin@test.com"; private static final String TEST_ADMIN_PASSWORD = "test"; @Autowired protected MockMvc mockMvc; @MockBean private ReviewSearchService reviewSearchService; @MockBean private CosmeticRankService cosmeticRankService; @MockBean private CosmeticSearchService cosmeticSearchService; @Autowired private WebApplicationContext context; @Autowired private UserService userService; @Autowired private TokenProvider tokenProvider; private String accessToken; private String userId; @BeforeEach public void mockMvcSetUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @BeforeAll public void initialize() {
AddUserRequest addUserRequest = new AddUserRequest();
3
2023-11-01 12:37:16+00:00
16k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/MouseControls.java
[ { "identifier": "PropertiesWindow", "path": "src/main/java/engine/editor/PropertiesWindow.java", "snippet": "public class PropertiesWindow {\n\tprivate final List<Vector4f> objectColors;\n\tprivate final List<GameObject> gameObjects;\n\tprivate final Picker picker;\n\n\tpublic PropertiesWindow(Picker pi...
import engine.editor.PropertiesWindow; import engine.renderer.DebugDraw; import engine.renderer.Picker; import engine.ruby.ImGuiLayer; import engine.ruby.KeyListener; import engine.ruby.MouseListener; import engine.ruby.Window; import engine.scenes.LevelEditorScene; import engine.util.CONSTANTS; import org.joml.Vector2f; import org.joml.Vector2i; import org.joml.Vector4f; import java.util.HashSet; import java.util.Set; import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT;
13,451
package engine.components; public class MouseControls extends Component { private static boolean holding = false; private final Vector2f boxSelectStart = new Vector2f(), boxSelectEnd = new Vector2f(); private GameObject activeGameObject = null; private float debounce = 0.0f; private boolean boxSelect = false; public static boolean isHolding() { return holding; } public void setActiveGameObject(GameObject activeGameObject) { if (this.activeGameObject != null) { this.activeGameObject.destroy(); } this.activeGameObject = activeGameObject; this.activeGameObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0.8f, 0.8f, 0.8f, 0.5f)); this.activeGameObject.addComponent(new NonPickable()); Window.getScene().addGameObjectToScene(activeGameObject); } public void placeObject() { GameObject obj = activeGameObject.copy(); if (obj.getComponent(StateMachine.class) != null) { obj.getComponent(StateMachine.class).refresh(); } obj.getComponent(SpriteRenderer.class).setColor(new Vector4f(1, 1, 1, 1)); obj.removeComponent(NonPickable.class); Window.getScene().addGameObjectToScene(obj); } @Override public void update(float dt) { } @Override public void editorUpdate(float dt) { debounce -= dt; Picker picker = Window.getImGuiLayer().getPropertiesWindow().getPicker(); LevelEditorScene currentScene = (LevelEditorScene) Window.getScene(); if (activeGameObject != null) { holding = true; Vector2f pos = MouseListener.getWorld(); float width = CONSTANTS.GRID_WIDTH.getIntValue(), height = CONSTANTS.GRID_HEIGHT.getIntValue(); float firstX = (((int) Math.floor(pos.x / width)) * width) + width / 2.0f; float firstY = (((int) Math.floor(pos.y / height)) * height) + height / 2.0f; activeGameObject.transform.setPosition(new Vector2f(firstX, firstY)); if (MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT) && ImGuiLayer.getWantCaptureMouse()) { float halfWidth = width / 2.0f, halfHeight = height / 2.0f; if (MouseListener.isDragging() && blockInSquare(activeGameObject.transform.getPosition().x - halfWidth, activeGameObject.transform.getPosition().y - halfHeight)) { placeObject(); } else if (!MouseListener.isDragging() && debounce <= 0 && blockInSquare(activeGameObject.transform.getPosition().x - halfWidth, activeGameObject.transform.getPosition().y - halfHeight)) { placeObject(); debounce = 0.2f; } }
package engine.components; public class MouseControls extends Component { private static boolean holding = false; private final Vector2f boxSelectStart = new Vector2f(), boxSelectEnd = new Vector2f(); private GameObject activeGameObject = null; private float debounce = 0.0f; private boolean boxSelect = false; public static boolean isHolding() { return holding; } public void setActiveGameObject(GameObject activeGameObject) { if (this.activeGameObject != null) { this.activeGameObject.destroy(); } this.activeGameObject = activeGameObject; this.activeGameObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0.8f, 0.8f, 0.8f, 0.5f)); this.activeGameObject.addComponent(new NonPickable()); Window.getScene().addGameObjectToScene(activeGameObject); } public void placeObject() { GameObject obj = activeGameObject.copy(); if (obj.getComponent(StateMachine.class) != null) { obj.getComponent(StateMachine.class).refresh(); } obj.getComponent(SpriteRenderer.class).setColor(new Vector4f(1, 1, 1, 1)); obj.removeComponent(NonPickable.class); Window.getScene().addGameObjectToScene(obj); } @Override public void update(float dt) { } @Override public void editorUpdate(float dt) { debounce -= dt; Picker picker = Window.getImGuiLayer().getPropertiesWindow().getPicker(); LevelEditorScene currentScene = (LevelEditorScene) Window.getScene(); if (activeGameObject != null) { holding = true; Vector2f pos = MouseListener.getWorld(); float width = CONSTANTS.GRID_WIDTH.getIntValue(), height = CONSTANTS.GRID_HEIGHT.getIntValue(); float firstX = (((int) Math.floor(pos.x / width)) * width) + width / 2.0f; float firstY = (((int) Math.floor(pos.y / height)) * height) + height / 2.0f; activeGameObject.transform.setPosition(new Vector2f(firstX, firstY)); if (MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT) && ImGuiLayer.getWantCaptureMouse()) { float halfWidth = width / 2.0f, halfHeight = height / 2.0f; if (MouseListener.isDragging() && blockInSquare(activeGameObject.transform.getPosition().x - halfWidth, activeGameObject.transform.getPosition().y - halfHeight)) { placeObject(); } else if (!MouseListener.isDragging() && debounce <= 0 && blockInSquare(activeGameObject.transform.getPosition().x - halfWidth, activeGameObject.transform.getPosition().y - halfHeight)) { placeObject(); debounce = 0.2f; } }
if (KeyListener.keyBeginPress(GLFW_KEY_ESCAPE)) {
4
2023-11-04 13:19:21+00:00
16k
RezaGooner/University-food-ordering
Frames/Admin/Managment/DataBaseManagment.java
[ { "identifier": "FilesPath", "path": "Classes/Pathes/FilesPath.java", "snippet": "public class FilesPath {\r\n\r\n public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r\n public static String iconPath = \"Source/icon.png\";\r\n\r\n public static String UserPassPath = \"userpass.t...
import javax.swing.*; import javax.swing.tree.*; import java.awt.event.*; import java.io.*; import java.nio.file.Files; import static Classes.Pathes.FilesPath.*; import static Classes.Theme.SoundEffect.errorSound; import static Frames.Admin.ProfileManagment.UserEditor.deletedFilePath; import static Frames.Order.UniversitySelfRestaurant.*;
12,442
package Frames.Admin.Managment; /* این کد جاوا یک درخت JTree با سه گره اصلی "کاربران"، "مالی" و "سفارش" ایجاد می کند. هر گره اصلی دارای چندین گره فرزند است که می توان آنها را در JTree باز یا بسته کرد. وقتی یک گره کلیک می شود، کد بررسی می کند کدام گره کلیک شده است و بر اساس گره کلیک شده عملی خاصی انجام می دهد. و فایل مربوظ به همان مورد بررسی قرار میگیرد به عنوان مثال، اگر گره "ادمین ها" کلیک شود، یک جعبه گفتگو با سه گزینه "مشاهده"، "جایگزینی فایل" و "لغو" نمایش داده می شود. اگر کاربر گزینه "مشاهده" را انتخاب کند، کد محتوای فایل "AdminsPath" را می خواند و آن را در یک جعبه گفتگو نمایش می دهد. اگر کاربر گزینه "جایگزینی فایل" را انتخاب کند، یک جعبه انتخاب فایل نمایش داده می شود تا به کاربر اجازه دهد فایل جدیدی را انتخاب کند و جایگزین فایل موجود شود. */ public class DataBaseManagment { public DataBaseManagment () { JFrame frame = new JFrame("مدیریت پایگاه های داده"); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode admins = new DefaultMutableTreeNode("ادمین ها"); DefaultMutableTreeNode balances = new DefaultMutableTreeNode("موجودی ها"); DefaultMutableTreeNode chargeHistory = new DefaultMutableTreeNode("سوابق شارژ"); DefaultMutableTreeNode deletedUsers = new DefaultMutableTreeNode("کاربران حذف شده"); DefaultMutableTreeNode dinners = new DefaultMutableTreeNode("شام"); DefaultMutableTreeNode lunches = new DefaultMutableTreeNode("ناهار"); DefaultMutableTreeNode discounts = new DefaultMutableTreeNode("تخفیفات"); DefaultMutableTreeNode log = new DefaultMutableTreeNode("سوابق ورود"); DefaultMutableTreeNode orders = new DefaultMutableTreeNode("سفارشات"); DefaultMutableTreeNode userpass = new DefaultMutableTreeNode("کاربران"); DefaultMutableTreeNode usersRoot = new DefaultMutableTreeNode("کاربران"); usersRoot.add(admins); usersRoot.add(userpass); usersRoot.add(log); usersRoot.add(deletedUsers); DefaultMutableTreeNode financialRoot = new DefaultMutableTreeNode("مالی"); financialRoot.add(balances); financialRoot.add(chargeHistory); financialRoot.add(discounts); DefaultMutableTreeNode ordersRoot = new DefaultMutableTreeNode("سفارش"); ordersRoot.add(orders); ordersRoot.add(lunches); ordersRoot.add(dinners); root.add(usersRoot); root.add(financialRoot); root.add(ordersRoot); JTree tree = new JTree(root); tree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int selectedRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selectedPath = tree.getPathForLocation(e.getX(), e.getY()); if (selectedRow != -1) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); if (selectedNode.equals(admins)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "ادمین ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(AdminsPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try {
package Frames.Admin.Managment; /* این کد جاوا یک درخت JTree با سه گره اصلی "کاربران"، "مالی" و "سفارش" ایجاد می کند. هر گره اصلی دارای چندین گره فرزند است که می توان آنها را در JTree باز یا بسته کرد. وقتی یک گره کلیک می شود، کد بررسی می کند کدام گره کلیک شده است و بر اساس گره کلیک شده عملی خاصی انجام می دهد. و فایل مربوظ به همان مورد بررسی قرار میگیرد به عنوان مثال، اگر گره "ادمین ها" کلیک شود، یک جعبه گفتگو با سه گزینه "مشاهده"، "جایگزینی فایل" و "لغو" نمایش داده می شود. اگر کاربر گزینه "مشاهده" را انتخاب کند، کد محتوای فایل "AdminsPath" را می خواند و آن را در یک جعبه گفتگو نمایش می دهد. اگر کاربر گزینه "جایگزینی فایل" را انتخاب کند، یک جعبه انتخاب فایل نمایش داده می شود تا به کاربر اجازه دهد فایل جدیدی را انتخاب کند و جایگزین فایل موجود شود. */ public class DataBaseManagment { public DataBaseManagment () { JFrame frame = new JFrame("مدیریت پایگاه های داده"); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode admins = new DefaultMutableTreeNode("ادمین ها"); DefaultMutableTreeNode balances = new DefaultMutableTreeNode("موجودی ها"); DefaultMutableTreeNode chargeHistory = new DefaultMutableTreeNode("سوابق شارژ"); DefaultMutableTreeNode deletedUsers = new DefaultMutableTreeNode("کاربران حذف شده"); DefaultMutableTreeNode dinners = new DefaultMutableTreeNode("شام"); DefaultMutableTreeNode lunches = new DefaultMutableTreeNode("ناهار"); DefaultMutableTreeNode discounts = new DefaultMutableTreeNode("تخفیفات"); DefaultMutableTreeNode log = new DefaultMutableTreeNode("سوابق ورود"); DefaultMutableTreeNode orders = new DefaultMutableTreeNode("سفارشات"); DefaultMutableTreeNode userpass = new DefaultMutableTreeNode("کاربران"); DefaultMutableTreeNode usersRoot = new DefaultMutableTreeNode("کاربران"); usersRoot.add(admins); usersRoot.add(userpass); usersRoot.add(log); usersRoot.add(deletedUsers); DefaultMutableTreeNode financialRoot = new DefaultMutableTreeNode("مالی"); financialRoot.add(balances); financialRoot.add(chargeHistory); financialRoot.add(discounts); DefaultMutableTreeNode ordersRoot = new DefaultMutableTreeNode("سفارش"); ordersRoot.add(orders); ordersRoot.add(lunches); ordersRoot.add(dinners); root.add(usersRoot); root.add(financialRoot); root.add(ordersRoot); JTree tree = new JTree(root); tree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int selectedRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selectedPath = tree.getPathForLocation(e.getX(), e.getY()); if (selectedRow != -1) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); if (selectedNode.equals(admins)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "ادمین ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(AdminsPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try {
errorSound();
1
2023-11-03 08:35:22+00:00
16k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/FileServiceImpl.java
[ { "identifier": "FileAdapt", "path": "talktime-minio/src/main/java/com/qingmeng/adapt/FileAdapt.java", "snippet": "public class FileAdapt {\n\n\n /**\n * 构建 minio vo\n *\n * @param uploadUrl 上传网址\n * @param downloadUrl 下载网址\n * @return {@link MinioVO }\n * @author qingmeng\n...
import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.qingmeng.adapt.FileAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.SysUserDao; import com.qingmeng.dto.file.MinioDTO; import com.qingmeng.dto.file.ScanQrcodeDTO; import com.qingmeng.dto.file.UploadUrlDTO; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.system.ScanQrcodeEnum; import com.qingmeng.enums.system.UploadSceneEnum; import com.qingmeng.service.FileService; import com.qingmeng.service.MinioService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.ScanQrcodeInfoVO; import com.qingmeng.vo.file.MinioVO; import com.qingmeng.vo.user.CheckFriendVO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.util.ArrayList; import java.util.Objects;
13,336
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) {
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) {
MinioDTO minioDTO = FileAdapt.buildMinioDTO(userId, uploadUrlDTO);
6
2023-11-07 16:04:55+00:00
16k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/DeviceController.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final L...
import io.github.mmm.MMM; import io.github.mmm.measurement.device.objects.imu.IMU; import io.github.mmm.measurement.device.objects.imu.IMUController; import io.github.mmm.measurement.device.objects.lidar.LiDAR; import io.github.mmm.measurement.device.objects.lidar.LiDARController; import io.github.mmm.measurement.device.scans.ImuScan; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import java.awt.*; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static io.github.mmm.MMM.MMM_ROOT_PATH; import static io.github.mmm.Utils.saveStringToFile;
13,419
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3; private IMUController imuController; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans(); for (int i = 0; i < scans.length; i++) { DEVICE_CONTROLLER.saveLiDARScansToFile(scans[i], "lidar" + (i + 1) + ".csv"); } DEVICE_CONTROLLER.getLidarController().clearScans();
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3; private IMUController imuController; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans(); for (int i = 0; i < scans.length; i++) { DEVICE_CONTROLLER.saveLiDARScansToFile(scans[i], "lidar" + (i + 1) + ".csv"); } DEVICE_CONTROLLER.getLidarController().clearScans();
ArrayList<ImuScan> imuScans = DEVICE_CONTROLLER.getImuController().getScans();
5
2023-11-06 16:56:46+00:00
16k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/Dr...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.drive.DriveSignal; 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.eventloop.opmode.TeleOp; 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.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,918
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config //@TeleOp(name="sample mechna drive ", group="Linear OpMode") 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 = .4; 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.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config //@TeleOp(name="sample mechna drive ", group="Linear OpMode") 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 = .4; 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);
9
2023-11-04 04:11:26+00:00
16k
conductor-oss/conductor
es6-persistence/src/test/java/com/netflix/conductor/es6/dao/index/TestElasticSearchDAOV6.java
[ { "identifier": "EventExecution", "path": "common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java", "snippet": "@ProtoMessage\npublic class EventExecution {\n\n @ProtoEnum\n public enum Status {\n IN_PROGRESS,\n COMPLETED,\n FAILED,\n SKIP...
import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.junit.Test; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.common.run.Workflow.WorkflowStatus; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.es6.utils.TestUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.ImmutableMap; import static org.junit.Assert.*; import static org.junit.Assert.assertFalse;
12,838
indexDAO.indexTask(taskSummary); List<TaskSummary> tasks = tryFindResults(() -> searchTaskSummary(taskSummary)); assertEquals(1, tasks.size()); assertEquals(taskSummary, tasks.get(0)); } private long tryGetCount(Supplier<Long> countFunction, int resultsCount) { long result = 0; for (int i = 0; i < 20; i++) { result = countFunction.get(); if (result == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } // Get total workflow counts given the name and status private long getWorkflowCount(String workflowName, String status) { return indexDAO.getWorkflowCount( "status=\"" + status + "\" AND workflowType=\"" + workflowName + "\"", "*"); } private void assertWorkflowSummary(String workflowId, WorkflowSummary summary) throws JsonProcessingException { assertEquals(summary.getWorkflowType(), indexDAO.get(workflowId, "workflowType")); assertEquals(String.valueOf(summary.getVersion()), indexDAO.get(workflowId, "version")); assertEquals(summary.getWorkflowId(), indexDAO.get(workflowId, "workflowId")); assertEquals(summary.getCorrelationId(), indexDAO.get(workflowId, "correlationId")); assertEquals(summary.getStartTime(), indexDAO.get(workflowId, "startTime")); assertEquals(summary.getUpdateTime(), indexDAO.get(workflowId, "updateTime")); assertEquals(summary.getEndTime(), indexDAO.get(workflowId, "endTime")); assertEquals(summary.getStatus().name(), indexDAO.get(workflowId, "status")); assertEquals(summary.getInput(), indexDAO.get(workflowId, "input")); assertEquals(summary.getOutput(), indexDAO.get(workflowId, "output")); assertEquals( summary.getReasonForIncompletion(), indexDAO.get(workflowId, "reasonForIncompletion")); assertEquals( String.valueOf(summary.getExecutionTime()), indexDAO.get(workflowId, "executionTime")); assertEquals(summary.getEvent(), indexDAO.get(workflowId, "event")); assertEquals( summary.getFailedReferenceTaskNames(), indexDAO.get(workflowId, "failedReferenceTaskNames")); assertEquals( summary.getFailedTaskNames(), objectMapper.readValue(indexDAO.get(workflowId, "failedTaskNames"), Set.class)); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction) { return tryFindResults(searchFunction, 1); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction, int resultsCount) { List<T> result = Collections.emptyList(); for (int i = 0; i < 20; i++) { result = searchFunction.get(); if (result.size() == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } private List<String> searchWorkflows(String workflowId) { return indexDAO.searchWorkflows( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<WorkflowSummary> searchWorkflowSummary(String workflowId) { return indexDAO.searchWorkflowSummary( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<String> searchTasks(TaskSummary taskSummary) { return indexDAO.searchTasks( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<TaskSummary> searchTaskSummary(TaskSummary taskSummary) { return indexDAO.searchTaskSummary( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private TaskExecLog createLog(String taskId, String log) { TaskExecLog taskExecLog = new TaskExecLog(log); taskExecLog.setTaskId(taskId); return taskExecLog; } private EventExecution createEventExecution(String event) { EventExecution execution = new EventExecution(uuid(), uuid()); execution.setName("name"); execution.setEvent(event); execution.setCreated(System.currentTimeMillis()); execution.setStatus(EventExecution.Status.COMPLETED);
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.es6.dao.index; public class TestElasticSearchDAOV6 extends ElasticSearchDaoBaseTest { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMWW"); private static final String INDEX_PREFIX = "conductor"; private static final String WORKFLOW_DOC_TYPE = "workflow"; private static final String TASK_DOC_TYPE = "task"; private static final String MSG_DOC_TYPE = "message"; private static final String EVENT_DOC_TYPE = "event"; private static final String LOG_INDEX_PREFIX = "task_log"; @Test public void assertInitialSetup() { SIMPLE_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); String workflowIndex = INDEX_PREFIX + "_" + WORKFLOW_DOC_TYPE; String taskIndex = INDEX_PREFIX + "_" + TASK_DOC_TYPE; String taskLogIndex = INDEX_PREFIX + "_" + LOG_INDEX_PREFIX + "_" + SIMPLE_DATE_FORMAT.format(new Date()); String messageIndex = INDEX_PREFIX + "_" + MSG_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date()); String eventIndex = INDEX_PREFIX + "_" + EVENT_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date()); assertTrue("Index 'conductor_workflow' should exist", indexExists("conductor_workflow")); assertTrue("Index 'conductor_task' should exist", indexExists("conductor_task")); assertTrue("Index '" + taskLogIndex + "' should exist", indexExists(taskLogIndex)); assertTrue("Index '" + messageIndex + "' should exist", indexExists(messageIndex)); assertTrue("Index '" + eventIndex + "' should exist", indexExists(eventIndex)); assertTrue( "Mapping 'workflow' for index 'conductor' should exist", doesMappingExist(workflowIndex, WORKFLOW_DOC_TYPE)); assertTrue( "Mapping 'task' for index 'conductor' should exist", doesMappingExist(taskIndex, TASK_DOC_TYPE)); } private boolean indexExists(final String index) { IndicesExistsRequest request = new IndicesExistsRequest(index); try { return elasticSearchClient.admin().indices().exists(request).get().isExists(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private boolean doesMappingExist(final String index, final String mappingName) { GetMappingsRequest request = new GetMappingsRequest().indices(index); try { GetMappingsResponse response = elasticSearchClient.admin().indices().getMappings(request).get(); return response.getMappings().get(index).containsKey(mappingName); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Test public void shouldIndexWorkflow() throws JsonProcessingException { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); assertWorkflowSummary(workflow.getWorkflowId(), workflow); } @Test public void shouldIndexWorkflowAsync() throws Exception { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.asyncIndexWorkflow(workflow).get(); assertWorkflowSummary(workflow.getWorkflowId(), workflow); } @Test public void shouldRemoveWorkflow() { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); // wait for workflow to be indexed List<String> workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 1); assertEquals(1, workflows.size()); indexDAO.removeWorkflow(workflow.getWorkflowId()); workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 0); assertTrue("Workflow was not removed.", workflows.isEmpty()); } @Test public void shouldAsyncRemoveWorkflow() throws Exception { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); // wait for workflow to be indexed List<String> workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 1); assertEquals(1, workflows.size()); indexDAO.asyncRemoveWorkflow(workflow.getWorkflowId()).get(); workflows = tryFindResults(() -> searchWorkflows(workflow.getWorkflowId()), 0); assertTrue("Workflow was not removed.", workflows.isEmpty()); } @Test public void shouldUpdateWorkflow() throws JsonProcessingException { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); indexDAO.updateWorkflow( workflow.getWorkflowId(), new String[] {"status"}, new Object[] {WorkflowStatus.COMPLETED}); workflow.setStatus(WorkflowStatus.COMPLETED); assertWorkflowSummary(workflow.getWorkflowId(), workflow); } @Test public void shouldAsyncUpdateWorkflow() throws Exception { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); indexDAO.asyncUpdateWorkflow( workflow.getWorkflowId(), new String[] {"status"}, new Object[] {WorkflowStatus.FAILED}) .get(); workflow.setStatus(WorkflowStatus.FAILED); assertWorkflowSummary(workflow.getWorkflowId(), workflow); } @Test public void shouldIndexTask() { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); List<String> tasks = tryFindResults(() -> searchTasks(taskSummary)); assertEquals(taskSummary.getTaskId(), tasks.get(0)); } @Test public void shouldIndexTaskAsync() throws Exception { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.asyncIndexTask(taskSummary).get(); List<String> tasks = tryFindResults(() -> searchTasks(taskSummary)); assertEquals(taskSummary.getTaskId(), tasks.get(0)); } @Test public void shouldRemoveTask() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); TaskSummary taskSummary = TestUtils.loadTaskSnapshot( objectMapper, "task_summary", workflowSummary.getWorkflowId()); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.removeTask(workflowSummary.getWorkflowId(), taskSummary.getTaskId()); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertTrue("Task was not removed.", tasks.isEmpty()); } @Test public void shouldAsyncRemoveTask() throws Exception { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); TaskSummary taskSummary = TestUtils.loadTaskSnapshot( objectMapper, "task_summary", workflowSummary.getWorkflowId()); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.asyncRemoveTask(workflowSummary.getWorkflowId(), taskSummary.getTaskId()).get(); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertTrue("Task was not removed.", tasks.isEmpty()); } @Test public void shouldNotRemoveTaskWhenNotAssociatedWithWorkflow() { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.removeTask("InvalidWorkflow", taskSummary.getTaskId()); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertFalse("Task was removed.", tasks.isEmpty()); } @Test public void shouldNotAsyncRemoveTaskWhenNotAssociatedWithWorkflow() throws Exception { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.asyncRemoveTask("InvalidWorkflow", taskSummary.getTaskId()).get(); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertFalse("Task was removed.", tasks.isEmpty()); } @Test public void shouldAddTaskExecutionLogs() { List<TaskExecLog> logs = new ArrayList<>(); String taskId = uuid(); logs.add(createLog(taskId, "log1")); logs.add(createLog(taskId, "log2")); logs.add(createLog(taskId, "log3")); indexDAO.addTaskExecutionLogs(logs); List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3); assertEquals(3, indexedLogs.size()); assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs)); } @Test public void shouldAddTaskExecutionLogsAsync() throws Exception { List<TaskExecLog> logs = new ArrayList<>(); String taskId = uuid(); logs.add(createLog(taskId, "log1")); logs.add(createLog(taskId, "log2")); logs.add(createLog(taskId, "log3")); indexDAO.asyncAddTaskExecutionLogs(logs).get(); List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3); assertEquals(3, indexedLogs.size()); assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs)); } @Test public void shouldAddMessage() { String queue = "queue"; Message message1 = new Message(uuid(), "payload1", null); Message message2 = new Message(uuid(), "payload2", null); indexDAO.addMessage(queue, message1); indexDAO.addMessage(queue, message2); List<Message> indexedMessages = tryFindResults(() -> indexDAO.getMessages(queue), 2); assertEquals(2, indexedMessages.size()); assertTrue( "Not all messages was indexed", indexedMessages.containsAll(Arrays.asList(message1, message2))); } @Test public void shouldAddEventExecution() { String event = "event"; EventExecution execution1 = createEventExecution(event); EventExecution execution2 = createEventExecution(event); indexDAO.addEventExecution(execution1); indexDAO.addEventExecution(execution2); List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2); assertEquals(2, indexedExecutions.size()); assertTrue( "Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2))); } @Test public void shouldAsyncAddEventExecution() throws Exception { String event = "event2"; EventExecution execution1 = createEventExecution(event); EventExecution execution2 = createEventExecution(event); indexDAO.asyncAddEventExecution(execution1).get(); indexDAO.asyncAddEventExecution(execution2).get(); List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2); assertEquals(2, indexedExecutions.size()); assertTrue( "Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2))); } @Test public void shouldAddIndexPrefixToIndexTemplate() throws Exception { String json = TestUtils.loadJsonResource("expected_template_task_log"); String content = indexDAO.loadTypeMappingSource("/template_task_log.json"); assertEquals(json, content); } @Test public void shouldCountWorkflows() { int counts = 1100; for (int i = 0; i < counts; i++) { WorkflowSummary workflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflow); } // wait for workflow to be indexed long result = tryGetCount(() -> getWorkflowCount("template_workflow", "RUNNING"), counts); assertEquals(counts, result); } @Test public void shouldFindWorkflow() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed List<WorkflowSummary> workflows = tryFindResults(() -> searchWorkflowSummary(workflowSummary.getWorkflowId()), 1); assertEquals(1, workflows.size()); assertEquals(workflowSummary, workflows.get(0)); } @Test public void shouldFindTask() { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); List<TaskSummary> tasks = tryFindResults(() -> searchTaskSummary(taskSummary)); assertEquals(1, tasks.size()); assertEquals(taskSummary, tasks.get(0)); } private long tryGetCount(Supplier<Long> countFunction, int resultsCount) { long result = 0; for (int i = 0; i < 20; i++) { result = countFunction.get(); if (result == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } // Get total workflow counts given the name and status private long getWorkflowCount(String workflowName, String status) { return indexDAO.getWorkflowCount( "status=\"" + status + "\" AND workflowType=\"" + workflowName + "\"", "*"); } private void assertWorkflowSummary(String workflowId, WorkflowSummary summary) throws JsonProcessingException { assertEquals(summary.getWorkflowType(), indexDAO.get(workflowId, "workflowType")); assertEquals(String.valueOf(summary.getVersion()), indexDAO.get(workflowId, "version")); assertEquals(summary.getWorkflowId(), indexDAO.get(workflowId, "workflowId")); assertEquals(summary.getCorrelationId(), indexDAO.get(workflowId, "correlationId")); assertEquals(summary.getStartTime(), indexDAO.get(workflowId, "startTime")); assertEquals(summary.getUpdateTime(), indexDAO.get(workflowId, "updateTime")); assertEquals(summary.getEndTime(), indexDAO.get(workflowId, "endTime")); assertEquals(summary.getStatus().name(), indexDAO.get(workflowId, "status")); assertEquals(summary.getInput(), indexDAO.get(workflowId, "input")); assertEquals(summary.getOutput(), indexDAO.get(workflowId, "output")); assertEquals( summary.getReasonForIncompletion(), indexDAO.get(workflowId, "reasonForIncompletion")); assertEquals( String.valueOf(summary.getExecutionTime()), indexDAO.get(workflowId, "executionTime")); assertEquals(summary.getEvent(), indexDAO.get(workflowId, "event")); assertEquals( summary.getFailedReferenceTaskNames(), indexDAO.get(workflowId, "failedReferenceTaskNames")); assertEquals( summary.getFailedTaskNames(), objectMapper.readValue(indexDAO.get(workflowId, "failedTaskNames"), Set.class)); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction) { return tryFindResults(searchFunction, 1); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction, int resultsCount) { List<T> result = Collections.emptyList(); for (int i = 0; i < 20; i++) { result = searchFunction.get(); if (result.size() == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } private List<String> searchWorkflows(String workflowId) { return indexDAO.searchWorkflows( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<WorkflowSummary> searchWorkflowSummary(String workflowId) { return indexDAO.searchWorkflowSummary( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<String> searchTasks(TaskSummary taskSummary) { return indexDAO.searchTasks( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<TaskSummary> searchTaskSummary(TaskSummary taskSummary) { return indexDAO.searchTaskSummary( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private TaskExecLog createLog(String taskId, String log) { TaskExecLog taskExecLog = new TaskExecLog(log); taskExecLog.setTaskId(taskId); return taskExecLog; } private EventExecution createEventExecution(String event) { EventExecution execution = new EventExecution(uuid(), uuid()); execution.setName("name"); execution.setEvent(event); execution.setCreated(System.currentTimeMillis()); execution.setStatus(EventExecution.Status.COMPLETED);
execution.setAction(EventHandler.Action.Type.start_workflow);
1
2023-12-08 06:06:09+00:00
16k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
13,371
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired
private CalculatePositionService calculatePositionService ;
8
2023-12-14 06:53:32+00:00
16k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/utils/FragmentUtil.java
[ { "identifier": "AboutFragment", "path": "app/src/main/java/com/drdisagree/colorblendr/ui/fragments/AboutFragment.java", "snippet": "public class AboutFragment extends Fragment {\n\n private FragmentAboutBinding binding;\n\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater,...
import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.ui.fragments.AboutFragment; import com.drdisagree.colorblendr.ui.fragments.ColorsFragment; import com.drdisagree.colorblendr.ui.fragments.PerAppThemeFragment; import com.drdisagree.colorblendr.ui.fragments.SettingsFragment; import com.drdisagree.colorblendr.ui.fragments.StylesFragment; import com.drdisagree.colorblendr.ui.fragments.ThemeFragment;
12,427
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) {
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) {
return fragment instanceof ColorsFragment || fragment instanceof PerAppThemeFragment;
2
2023-12-06 13:20:16+00:00
16k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/menu/MenuItem.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.hooks.ItemHook; import com.extendedclip.deluxemenus.nbt.NbtProvider; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.ItemUtils; import com.extendedclip.deluxemenus.utils.StringUtils; import com.extendedclip.deluxemenus.utils.VersionHelper; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.block.Banner; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BannerMeta; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.FireworkEffectMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; import static com.extendedclip.deluxemenus.utils.Constants.INVENTORY_ITEM_ACCESSORS; import static com.extendedclip.deluxemenus.utils.Constants.ITEMSADDER_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.MMOITEMS_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.ORAXEN_PREFIX; import static com.extendedclip.deluxemenus.utils.Constants.PLACEHOLDER_PREFIX;
11,617
} catch (final NumberFormatException ignored) { } } if (amount > 64) { amount = 64; } itemStack.setAmount(amount); final ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta == null) { return itemStack; } if (this.options.customModelData().isPresent() && VersionHelper.IS_CUSTOM_MODEL_DATA) { try { final int modelData = Integer.parseInt(holder.setPlaceholders(this.options.customModelData().get())); itemMeta.setCustomModelData(modelData); } catch (final Exception ignored) { } } if (this.options.displayName().isPresent()) { final String displayName = holder.setPlaceholders(this.options.displayName().get()); itemMeta.setDisplayName(StringUtils.color(displayName)); } if (!this.options.lore().isEmpty()) { final List<String> lore = this.options.lore().stream() .map(holder::setPlaceholders) .map(StringUtils::color) .map(line -> line.split("\n")) .flatMap(Arrays::stream) .map(line -> line.split("\\\\n")) .flatMap(Arrays::stream) .collect(Collectors.toList()); itemMeta.setLore(lore); } if (!this.options.itemFlags().isEmpty()) { for (final ItemFlag flag : this.options.itemFlags()) { itemMeta.addItemFlags(flag); } } if (this.options.hideAttributes()) { itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); } if (this.options.hideEnchants()) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (this.options.hidePotionEffects()) { itemMeta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } if (this.options.unbreakable()) { itemMeta.setUnbreakable(true); } if (this.options.hideUnbreakable()) { itemMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); } if (itemMeta instanceof LeatherArmorMeta && this.options.rgb().isPresent()) { final String rgbString = holder.setPlaceholders(this.options.rgb().get()); final String[] parts = rgbString.split(","); final LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; try { leatherArmorMeta.setColor(Color.fromRGB(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), Integer.parseInt(parts[2].trim()))); itemStack.setItemMeta(leatherArmorMeta); } catch (final Exception exception) { DeluxeMenus.printStacktrace( "Invalid rgb colors found for leather armor: " + parts[0].trim() + ", " + parts[1].trim() + ", " + parts[2].trim(), exception ); } } else if (itemMeta instanceof FireworkEffectMeta && this.options.rgb().isPresent()) { final String rgbString = holder.setPlaceholders(this.options.rgb().get()); final String[] parts = rgbString.split(","); final FireworkEffectMeta fireworkEffectMeta = (FireworkEffectMeta) itemMeta; try { fireworkEffectMeta.setEffect(FireworkEffect.builder().withColor(Color.fromRGB(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), Integer.parseInt(parts[2].trim()))).build()); itemStack.setItemMeta(fireworkEffectMeta); } catch (final Exception exception) { DeluxeMenus.printStacktrace( "Invalid rgb colors found for firework or firework star: " + parts[0].trim() + ", " + parts[1].trim() + ", " + parts[2].trim(), exception ); } } else if (itemMeta instanceof EnchantmentStorageMeta && !this.options.enchantments().isEmpty()) { final EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) itemMeta; for (final Map.Entry<Enchantment, Integer> entry : this.options.enchantments().entrySet()) { final boolean result = enchantmentStorageMeta.addStoredEnchant(entry.getKey(), entry.getValue(), true); if (!result) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.INFO, "Failed to add enchantment " + entry.getKey().getName() + " to item " + itemStack.getType() ); } } itemStack.setItemMeta(enchantmentStorageMeta); } else { itemStack.setItemMeta(itemMeta); } if (!(itemMeta instanceof EnchantmentStorageMeta) && !this.options.enchantments().isEmpty()) { itemStack.addUnsafeEnchantments(this.options.enchantments()); }
package com.extendedclip.deluxemenus.menu; public class MenuItem { private final @NotNull MenuItemOptions options; public MenuItem(@NotNull final MenuItemOptions options) { this.options = options; } public ItemStack getItemStack(@NotNull final MenuHolder holder) { final Player viewer = holder.getViewer(); ItemStack itemStack = null; int amount = 1; String stringMaterial = this.options.material(); String lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ROOT); if (ItemUtils.isPlaceholderMaterial(lowercaseStringMaterial)) { stringMaterial = holder.setPlaceholders(stringMaterial.substring(PLACEHOLDER_PREFIX.length())); lowercaseStringMaterial = stringMaterial.toLowerCase(Locale.ENGLISH); } if (ItemUtils.isPlayerItem(lowercaseStringMaterial)) { final ItemStack playerItem = INVENTORY_ITEM_ACCESSORS.get(lowercaseStringMaterial).apply(viewer.getInventory()); if (playerItem == null || playerItem.getType() == Material.AIR) { return new ItemStack(Material.AIR); } itemStack = playerItem.clone(); amount = playerItem.getAmount(); } final int temporaryAmount = amount; final String finalMaterial = lowercaseStringMaterial; final ItemHook pluginHook = DeluxeMenus.getInstance().getItemHooks().values() .stream() .filter(x -> finalMaterial.startsWith(x.getPrefix())) .findFirst() .orElse(null); if (pluginHook != null) { itemStack = pluginHook.getItem(stringMaterial.substring(pluginHook.getPrefix().length())); } if (ItemUtils.isWaterBottle(stringMaterial)) { itemStack = ItemUtils.createWaterBottles(amount); } // The item is neither a water bottle nor plugin hook item if (itemStack == null) { final Material material = Material.getMaterial(stringMaterial.toUpperCase(Locale.ROOT)); if (material == null) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, "Material: " + stringMaterial + " is not valid! Setting to Stone." ); itemStack = new ItemStack(Material.STONE, temporaryAmount); } else { itemStack = new ItemStack(material, temporaryAmount); } } if (ItemUtils.isBanner(itemStack.getType())) { final BannerMeta meta = (BannerMeta) itemStack.getItemMeta(); if (meta != null) { if (this.options.baseColor().isPresent()) { meta.setBaseColor(this.options.baseColor().get()); } if (!this.options.bannerMeta().isEmpty()) { meta.setPatterns(this.options.bannerMeta()); } itemStack.setItemMeta(meta); } } if (ItemUtils.isShield(itemStack.getType())) { final BlockStateMeta blockStateMeta = (BlockStateMeta) itemStack.getItemMeta(); if (blockStateMeta != null) { final Banner banner = (Banner) blockStateMeta.getBlockState(); if (this.options.baseColor().isPresent()) { banner.setBaseColor(this.options.baseColor().get()); banner.update(); blockStateMeta.setBlockState(banner); } if (!this.options.bannerMeta().isEmpty()) { banner.setPatterns(this.options.bannerMeta()); banner.update(); blockStateMeta.setBlockState(banner); } itemStack.setItemMeta(blockStateMeta); } } if (ItemUtils.hasPotionMeta(itemStack)) { final PotionMeta meta = (PotionMeta) itemStack.getItemMeta(); if (meta != null) { if (this.options.rgb().isPresent()) { final String rgbString = holder.setPlaceholders(this.options.rgb().get()); final String[] parts = rgbString.split(","); try { meta.setColor(Color.fromRGB(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), Integer.parseInt(parts[2].trim()))); } catch (Exception ignored) { } } if (!this.options.potionEffects().isEmpty()) { for (PotionEffect effect : this.options.potionEffects()) { meta.addCustomEffect(effect, true); } } itemStack.setItemMeta(meta); } } if (itemStack.getType() == Material.AIR) { return itemStack; } short data = this.options.data(); if (this.options.placeholderData().isPresent()) { final String parsedData = holder.setPlaceholders(this.options.placeholderData().get()); try { data = Short.parseShort(parsedData); } catch (final NumberFormatException exception) { DeluxeMenus.printStacktrace( "Invalid placeholder data found: " + parsedData + ".", exception ); } } if (data > 0) { itemStack.setDurability(data); } if (this.options.amount() != -1) { amount = this.options.amount(); } if (this.options.dynamicAmount().isPresent()) { try { final int dynamicAmount = (int) Double.parseDouble(holder.setPlaceholders(this.options.dynamicAmount().get())); amount = Math.max(dynamicAmount, 1); } catch (final NumberFormatException ignored) { } } if (amount > 64) { amount = 64; } itemStack.setAmount(amount); final ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta == null) { return itemStack; } if (this.options.customModelData().isPresent() && VersionHelper.IS_CUSTOM_MODEL_DATA) { try { final int modelData = Integer.parseInt(holder.setPlaceholders(this.options.customModelData().get())); itemMeta.setCustomModelData(modelData); } catch (final Exception ignored) { } } if (this.options.displayName().isPresent()) { final String displayName = holder.setPlaceholders(this.options.displayName().get()); itemMeta.setDisplayName(StringUtils.color(displayName)); } if (!this.options.lore().isEmpty()) { final List<String> lore = this.options.lore().stream() .map(holder::setPlaceholders) .map(StringUtils::color) .map(line -> line.split("\n")) .flatMap(Arrays::stream) .map(line -> line.split("\\\\n")) .flatMap(Arrays::stream) .collect(Collectors.toList()); itemMeta.setLore(lore); } if (!this.options.itemFlags().isEmpty()) { for (final ItemFlag flag : this.options.itemFlags()) { itemMeta.addItemFlags(flag); } } if (this.options.hideAttributes()) { itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); } if (this.options.hideEnchants()) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (this.options.hidePotionEffects()) { itemMeta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } if (this.options.unbreakable()) { itemMeta.setUnbreakable(true); } if (this.options.hideUnbreakable()) { itemMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); } if (itemMeta instanceof LeatherArmorMeta && this.options.rgb().isPresent()) { final String rgbString = holder.setPlaceholders(this.options.rgb().get()); final String[] parts = rgbString.split(","); final LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; try { leatherArmorMeta.setColor(Color.fromRGB(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), Integer.parseInt(parts[2].trim()))); itemStack.setItemMeta(leatherArmorMeta); } catch (final Exception exception) { DeluxeMenus.printStacktrace( "Invalid rgb colors found for leather armor: " + parts[0].trim() + ", " + parts[1].trim() + ", " + parts[2].trim(), exception ); } } else if (itemMeta instanceof FireworkEffectMeta && this.options.rgb().isPresent()) { final String rgbString = holder.setPlaceholders(this.options.rgb().get()); final String[] parts = rgbString.split(","); final FireworkEffectMeta fireworkEffectMeta = (FireworkEffectMeta) itemMeta; try { fireworkEffectMeta.setEffect(FireworkEffect.builder().withColor(Color.fromRGB(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), Integer.parseInt(parts[2].trim()))).build()); itemStack.setItemMeta(fireworkEffectMeta); } catch (final Exception exception) { DeluxeMenus.printStacktrace( "Invalid rgb colors found for firework or firework star: " + parts[0].trim() + ", " + parts[1].trim() + ", " + parts[2].trim(), exception ); } } else if (itemMeta instanceof EnchantmentStorageMeta && !this.options.enchantments().isEmpty()) { final EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) itemMeta; for (final Map.Entry<Enchantment, Integer> entry : this.options.enchantments().entrySet()) { final boolean result = enchantmentStorageMeta.addStoredEnchant(entry.getKey(), entry.getValue(), true); if (!result) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.INFO, "Failed to add enchantment " + entry.getKey().getName() + " to item " + itemStack.getType() ); } } itemStack.setItemMeta(enchantmentStorageMeta); } else { itemStack.setItemMeta(itemMeta); } if (!(itemMeta instanceof EnchantmentStorageMeta) && !this.options.enchantments().isEmpty()) { itemStack.addUnsafeEnchantments(this.options.enchantments()); }
if (NbtProvider.isAvailable()) {
2
2023-12-14 23:41:07+00:00
16k
lxs2601055687/contextAdminRuoYi
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java
[ { "identifier": "CacheNames", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheNames.java", "snippet": "public interface CacheNames {\n\n /**\n * 演示案例\n */\n String DEMO_CACHE = \"demo:cache#60s#10m#20\";\n\n /**\n * 系统配置\n */\n String SYS_CONFIG = \"sys_con...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.constant.CacheNames; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.core.service.UserService; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.DataBaseHelper; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysPost; import com.ruoyi.system.domain.SysUserPost; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.mapper.*; import com.ruoyi.system.service.ISysUserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; import java.util.Map;
13,954
package com.ruoyi.system.service.impl; /** * 用户 业务层处理 * * @author Lion Li */ @Slf4j @RequiredArgsConstructor @Service
package com.ruoyi.system.service.impl; /** * 用户 业务层处理 * * @author Lion Li */ @Slf4j @RequiredArgsConstructor @Service
public class SysUserServiceImpl implements ISysUserService, UserService {
16
2023-12-07 12:06:21+00:00
16k
DantSu/studio
driver/src/main/java/studio/driver/fs/FsStoryTellerAsyncDriver.java
[ { "identifier": "transformUuid", "path": "core/src/main/java/studio/core/v1/writer/fs/FsStoryPackWriter.java", "snippet": "public static String transformUuid(String uuid) {\n String uuidStr = uuid.replace(\"-\", \"\");\n return uuidStr.substring(uuidStr.length()-8).toUpperCase();\n}" }, { ...
import static studio.core.v1.writer.fs.FsStoryPackWriter.transformUuid; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import studio.core.v1.utils.AESCBCCipher; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.XXTEACipher; import studio.core.v1.utils.exception.StoryTellerException; import studio.core.v1.utils.stream.ThrowingConsumer; import studio.core.v1.writer.fs.FsStoryPackWriter; import studio.core.v1.writer.fs.FsStoryPackWriterV3; import studio.driver.DeviceVersion; import studio.driver.LibUsbDetectionHelper; import studio.driver.StoryTellerAsyncDriver; import studio.driver.event.DevicePluggedListener; import studio.driver.event.DeviceUnpluggedListener; import studio.driver.event.TransferProgressListener; import studio.driver.model.TransferStatus; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos;
11,746
this.pluggedlisteners.add(pluggedlistener); this.unpluggedlisteners.add(unpluggedlistener); if (this.device != null) { pluggedlistener.onDevicePlugged(this.device); } } public CompletionStage<FsDeviceInfos> getDeviceInfos() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } FsDeviceInfos infos = new FsDeviceInfos(); Path mdFile = this.partitionMountPoint.resolve(DEVICE_METADATA_FILENAME); LOGGER.trace("Reading device infos from file: {}", mdFile); try (DataInputStream is = new DataInputStream(new BufferedInputStream(Files.newInputStream(mdFile)))) { // SD card size and used space FileStore mdFd = Files.getFileStore(mdFile); long sdCardTotalSpace = mdFd.getTotalSpace(); long sdCardUsedSpace = mdFd.getTotalSpace() - mdFd.getUnallocatedSpace(); double percent = Math.round(100d * 100d * sdCardUsedSpace / sdCardTotalSpace) / 100d; infos.setSdCardSizeInBytes(sdCardTotalSpace); infos.setUsedSpaceInBytes(sdCardUsedSpace); if (LOGGER.isDebugEnabled()) { LOGGER.debug("SD card used : {}% ({} / {})", percent, FileUtils.readableByteSize(sdCardUsedSpace), FileUtils.readableByteSize(sdCardTotalSpace)); } // MD file format version short mdVersion = DeviceUtils.readLittleEndianShort(is); LOGGER.trace("Device metadata format version: {}", mdVersion); if (mdVersion >= 1 && mdVersion <= 4) { return this.getDeviceInfosMeta1to4(infos, is); } else if (mdVersion == 6) { return this.getDeviceInfosMeta6(infos, is); } else { return CompletableFuture.failedFuture(new StoryTellerException("Unsupported device metadata format version: " + mdVersion)); } } catch (IOException e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to read device metadata on partition", e)); } } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta1to4(FsDeviceInfos infos, DataInputStream is) throws IOException { // Firmware version is.skipBytes(4); short major = DeviceUtils.readLittleEndianShort(is); short minor = DeviceUtils.readLittleEndianShort(is); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: {}.{}", major, minor); // Serial number String serialNumber = null; long sn = DeviceUtils.readBigEndianLong(is); if (sn != 0L && sn != -1L && sn != -4294967296L) { serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: {}", serialNumber); } else { LOGGER.warn("No serial number in SPI"); } infos.setSerialNumber(serialNumber); // UUID is.skipBytes(238); byte[] deviceId = is.readNBytes(256); infos.setDeviceKey(deviceId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("UUID: {}", SecurityUtils.encodeHex(deviceId)); } return CompletableFuture.completedFuture(infos); } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta6(FsDeviceInfos infos, DataInputStream is) throws IOException { short major = DeviceUtils.readAsciiToShort(is, 1); is.skipBytes(1); short minor = DeviceUtils.readAsciiToShort(is, 1); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: " + major + "." + minor); // Serial number is.skipBytes(21); long sn = DeviceUtils.readAsciiToLong(is, 14); String serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: " + serialNumber); infos.setSerialNumber(serialNumber); // UUID byte[] snb = String.valueOf(sn).getBytes(StandardCharsets.UTF_8); is.skipBytes(24); byte[] key = is.readNBytes(32); byte[] deviceKey = new byte[64]; System.arraycopy(snb, 0, deviceKey, 0 , 14); System.arraycopy(snb, 0, deviceKey, 24 , 8); System.arraycopy(key, 0, deviceKey, 32 , 32); infos.setDeviceKey(deviceKey); is.close(); return CompletableFuture.completedFuture(infos); } public CompletionStage<List<FsStoryPackInfos>> getPacksList() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenApply(packUUIDs -> { try { LOGGER.debug("Number of packs in index: {}", packUUIDs.size()); List<FsStoryPackInfos> packs = new ArrayList<>(); for (UUID packUUID : packUUIDs) { FsStoryPackInfos packInfos = new FsStoryPackInfos(); packInfos.setUuid(packUUID); LOGGER.debug("Pack UUID: {}", packUUID); // Compute .content folder (last 4 bytes of UUID)
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.fs; public class FsStoryTellerAsyncDriver implements StoryTellerAsyncDriver<FsDeviceInfos, FsStoryPackInfos> { private static final Logger LOGGER = LogManager.getLogger(FsStoryTellerAsyncDriver.class); private static final String DEVICE_METADATA_FILENAME = ".md"; private static final String PACK_INDEX_FILENAME = ".pi"; private static final String CONTENT_FOLDER = ".content"; private static final String NODE_INDEX_FILENAME = "ni"; private static final String NIGHT_MODE_FILENAME = "nm"; private static final long FS_MOUNTPOINT_POLL_DELAY = 1000L; private static final long FS_MOUNTPOINT_RETRY = 10; private Device device = null; private Path partitionMountPoint = null; private List<DevicePluggedListener> pluggedlisteners = new ArrayList<>(); private List<DeviceUnpluggedListener> unpluggedlisteners = new ArrayList<>(); public FsStoryTellerAsyncDriver() { // Initialize libusb, handle and propagate hotplug events LOGGER.debug("Registering hotplug listener"); LibUsbDetectionHelper.initializeLibUsb(DeviceVersion.DEVICE_VERSION_2, // device2 -> { // Wait for a partition to be mounted which contains the .md file LOGGER.debug("Waiting for device partition..."); for (int i = 0; i < FS_MOUNTPOINT_RETRY && partitionMountPoint == null; i++) { try { Thread.sleep(FS_MOUNTPOINT_POLL_DELAY); DeviceUtils.listMountPoints().forEach(path -> { LOGGER.trace("Looking for .md in {}", path); if (Files.exists(path.resolve(DEVICE_METADATA_FILENAME))) { partitionMountPoint = path; LOGGER.info("FS device partition located: {}", partitionMountPoint); } }); } catch (InterruptedException e) { LOGGER.error("Failed to locate device partition", e); Thread.currentThread().interrupt(); } } if (partitionMountPoint == null) { throw new StoryTellerException("Could not locate device partition"); } // Update device reference FsStoryTellerAsyncDriver.this.device = device2; // Notify listeners FsStoryTellerAsyncDriver.this.pluggedlisteners.forEach(l -> l.onDevicePlugged(device2)); }, // device2 -> { // Update device reference FsStoryTellerAsyncDriver.this.device = null; FsStoryTellerAsyncDriver.this.partitionMountPoint = null; // Notify listeners FsStoryTellerAsyncDriver.this.unpluggedlisteners.forEach(l -> l.onDeviceUnplugged(device2)); }); } public void registerDeviceListener(DevicePluggedListener pluggedlistener, DeviceUnpluggedListener unpluggedlistener) { this.pluggedlisteners.add(pluggedlistener); this.unpluggedlisteners.add(unpluggedlistener); if (this.device != null) { pluggedlistener.onDevicePlugged(this.device); } } public CompletionStage<FsDeviceInfos> getDeviceInfos() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } FsDeviceInfos infos = new FsDeviceInfos(); Path mdFile = this.partitionMountPoint.resolve(DEVICE_METADATA_FILENAME); LOGGER.trace("Reading device infos from file: {}", mdFile); try (DataInputStream is = new DataInputStream(new BufferedInputStream(Files.newInputStream(mdFile)))) { // SD card size and used space FileStore mdFd = Files.getFileStore(mdFile); long sdCardTotalSpace = mdFd.getTotalSpace(); long sdCardUsedSpace = mdFd.getTotalSpace() - mdFd.getUnallocatedSpace(); double percent = Math.round(100d * 100d * sdCardUsedSpace / sdCardTotalSpace) / 100d; infos.setSdCardSizeInBytes(sdCardTotalSpace); infos.setUsedSpaceInBytes(sdCardUsedSpace); if (LOGGER.isDebugEnabled()) { LOGGER.debug("SD card used : {}% ({} / {})", percent, FileUtils.readableByteSize(sdCardUsedSpace), FileUtils.readableByteSize(sdCardTotalSpace)); } // MD file format version short mdVersion = DeviceUtils.readLittleEndianShort(is); LOGGER.trace("Device metadata format version: {}", mdVersion); if (mdVersion >= 1 && mdVersion <= 4) { return this.getDeviceInfosMeta1to4(infos, is); } else if (mdVersion == 6) { return this.getDeviceInfosMeta6(infos, is); } else { return CompletableFuture.failedFuture(new StoryTellerException("Unsupported device metadata format version: " + mdVersion)); } } catch (IOException e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to read device metadata on partition", e)); } } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta1to4(FsDeviceInfos infos, DataInputStream is) throws IOException { // Firmware version is.skipBytes(4); short major = DeviceUtils.readLittleEndianShort(is); short minor = DeviceUtils.readLittleEndianShort(is); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: {}.{}", major, minor); // Serial number String serialNumber = null; long sn = DeviceUtils.readBigEndianLong(is); if (sn != 0L && sn != -1L && sn != -4294967296L) { serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: {}", serialNumber); } else { LOGGER.warn("No serial number in SPI"); } infos.setSerialNumber(serialNumber); // UUID is.skipBytes(238); byte[] deviceId = is.readNBytes(256); infos.setDeviceKey(deviceId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("UUID: {}", SecurityUtils.encodeHex(deviceId)); } return CompletableFuture.completedFuture(infos); } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta6(FsDeviceInfos infos, DataInputStream is) throws IOException { short major = DeviceUtils.readAsciiToShort(is, 1); is.skipBytes(1); short minor = DeviceUtils.readAsciiToShort(is, 1); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: " + major + "." + minor); // Serial number is.skipBytes(21); long sn = DeviceUtils.readAsciiToLong(is, 14); String serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: " + serialNumber); infos.setSerialNumber(serialNumber); // UUID byte[] snb = String.valueOf(sn).getBytes(StandardCharsets.UTF_8); is.skipBytes(24); byte[] key = is.readNBytes(32); byte[] deviceKey = new byte[64]; System.arraycopy(snb, 0, deviceKey, 0 , 14); System.arraycopy(snb, 0, deviceKey, 24 , 8); System.arraycopy(key, 0, deviceKey, 32 , 32); infos.setDeviceKey(deviceKey); is.close(); return CompletableFuture.completedFuture(infos); } public CompletionStage<List<FsStoryPackInfos>> getPacksList() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenApply(packUUIDs -> { try { LOGGER.debug("Number of packs in index: {}", packUUIDs.size()); List<FsStoryPackInfos> packs = new ArrayList<>(); for (UUID packUUID : packUUIDs) { FsStoryPackInfos packInfos = new FsStoryPackInfos(); packInfos.setUuid(packUUID); LOGGER.debug("Pack UUID: {}", packUUID); // Compute .content folder (last 4 bytes of UUID)
String folderName = transformUuid(packUUID.toString());
0
2023-12-14 15:08:35+00:00
16k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java
[ { "identifier": "ModInit", "path": "src/main/java/eu/pb4/polydecorations/ModInit.java", "snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"polydecorations\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMet...
import eu.pb4.polydecorations.ModInit; import eu.pb4.polydecorations.block.furniture.BenchBlock; import eu.pb4.polydecorations.block.furniture.LargeFlowerPotBlock; import eu.pb4.polydecorations.block.item.DisplayCaseBlock; import eu.pb4.polydecorations.block.item.ShelfBlock; import eu.pb4.polydecorations.block.furniture.BrazierBlock; import eu.pb4.polydecorations.block.item.GlobeBlock; import eu.pb4.polydecorations.block.extension.SignPostBlock; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; import eu.pb4.polydecorations.util.WoodUtil; import eu.pb4.polymer.core.api.block.PolymerBlock; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.registry.RegistryEntryAddedCallback; import net.minecraft.block.*; import net.minecraft.block.enums.Instrument; import net.minecraft.loot.LootTable; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.server.MinecraftServer; import net.minecraft.util.DyeColor; import net.minecraft.util.Identifier; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import static eu.pb4.polydecorations.ModInit.id;
12,189
package eu.pb4.polydecorations.block; public class DecorationsBlocks { private static final List<Block> BLOCKS = new ArrayList<>(); public static final WallAttachedLanternBlock WALL_LANTERN = register("wall_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.LANTERN)); public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = register("wall_soul_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.SOUL_LANTERN)); public static final BrazierBlock BRAZIER = register("brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final BrazierBlock SOUL_BRAZIER = register("soul_brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.SOUL_LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.SOUL_CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final GlobeBlock GLOBE = register("globe", new GlobeBlock(AbstractBlock.Settings.copy(Blocks.OAK_PLANKS).nonOpaque())); public static final DisplayCaseBlock DISPLAY_CASE = register("display_case", new DisplayCaseBlock(AbstractBlock.Settings.copy(Blocks.GLASS).nonOpaque())); public static final LargeFlowerPotBlock LARGE_FLOWER_POT = register("large_flower_pot", new LargeFlowerPotBlock( AbstractBlock.Settings.create().mapColor(MapColor.ORANGE).instrument(Instrument.BASEDRUM).strength(1.25F).nonOpaque())); public static final Map<WoodType, ShelfBlock> SHELF = registerWood("shelf", (x) -> { var planks = new Identifier(x.name() + "_planks"); if (Registries.BLOCK.containsId(planks)) { return new ShelfBlock( AbstractBlock.Settings.copy(Registries.BLOCK.get(planks)).nonOpaque() .solidBlock(Blocks::never), Registries.BLOCK.get(planks) ); } return null; }); public static final Map<WoodType, BenchBlock> BENCH = registerWood("bench", (x) -> { var planks = new Identifier(x.name() + "_planks"); if (Registries.BLOCK.containsId(planks)) {
package eu.pb4.polydecorations.block; public class DecorationsBlocks { private static final List<Block> BLOCKS = new ArrayList<>(); public static final WallAttachedLanternBlock WALL_LANTERN = register("wall_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.LANTERN)); public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = register("wall_soul_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.SOUL_LANTERN)); public static final BrazierBlock BRAZIER = register("brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final BrazierBlock SOUL_BRAZIER = register("soul_brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.SOUL_LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.SOUL_CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final GlobeBlock GLOBE = register("globe", new GlobeBlock(AbstractBlock.Settings.copy(Blocks.OAK_PLANKS).nonOpaque())); public static final DisplayCaseBlock DISPLAY_CASE = register("display_case", new DisplayCaseBlock(AbstractBlock.Settings.copy(Blocks.GLASS).nonOpaque())); public static final LargeFlowerPotBlock LARGE_FLOWER_POT = register("large_flower_pot", new LargeFlowerPotBlock( AbstractBlock.Settings.create().mapColor(MapColor.ORANGE).instrument(Instrument.BASEDRUM).strength(1.25F).nonOpaque())); public static final Map<WoodType, ShelfBlock> SHELF = registerWood("shelf", (x) -> { var planks = new Identifier(x.name() + "_planks"); if (Registries.BLOCK.containsId(planks)) { return new ShelfBlock( AbstractBlock.Settings.copy(Registries.BLOCK.get(planks)).nonOpaque() .solidBlock(Blocks::never), Registries.BLOCK.get(planks) ); } return null; }); public static final Map<WoodType, BenchBlock> BENCH = registerWood("bench", (x) -> { var planks = new Identifier(x.name() + "_planks"); if (Registries.BLOCK.containsId(planks)) {
return new BenchBlock(id(x.name() + "_bench"),
10
2023-12-10 16:20:36+00:00
16k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/controllers/ProjectWidgetController.java
[ { "identifier": "USER_NOT_ALLOWED_PROJECT", "path": "src/main/java/com/michelin/suricate/utils/exceptions/constants/ErrorMessage.java", "snippet": "public static final String USER_NOT_ALLOWED_PROJECT = \"The user is not allowed to modify this project\";" }, { "identifier": "ApiErrorDto", "pa...
import static com.michelin.suricate.utils.exceptions.constants.ErrorMessage.USER_NOT_ALLOWED_PROJECT; import com.michelin.suricate.model.dto.api.error.ApiErrorDto; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetRequestDto; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetResponseDto; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.ProjectGrid; import com.michelin.suricate.model.entities.ProjectWidget; import com.michelin.suricate.model.enums.ApiErrorEnum; import com.michelin.suricate.security.LocalUser; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.mapper.ProjectWidgetMapper; import com.michelin.suricate.utils.exceptions.ApiException; import com.michelin.suricate.utils.exceptions.GridNotFoundException; import com.michelin.suricate.utils.exceptions.ObjectNotFoundException; import io.swagger.v3.oas.annotations.Operation; 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.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.security.PermitAll; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
12,513
* Get the list of project widgets for a project. */ @Operation(summary = "Get the full list of projectWidgets for a project") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @GetMapping(value = "/v1/projectWidgets/{projectToken}/projectWidgets") @PermitAll public ResponseEntity<List<ProjectWidgetResponseDto>> getByProject( @Parameter(name = "projectToken", description = "The project token", required = true) @PathVariable("projectToken") String projectToken) { Optional<Project> projectOptional = projectService.getOneByToken(projectToken); if (projectOptional.isEmpty()) { throw new ObjectNotFoundException(Project.class, projectToken); } Project project = projectOptional.get(); List<ProjectWidget> allWidgets = project.getGrids().stream().map(ProjectGrid::getWidgets).flatMap(Collection::stream) .toList(); if (allWidgets.isEmpty()) { return ResponseEntity.noContent().build(); } return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(projectWidgetMapper.toProjectWidgetsDtos(allWidgets)); } /** * Edit a project widget for a project. * * @param connectedUser The connected user * @param projectWidgetId The project widget id * @param projectWidgetRequestDto The project widget updated */ @Operation(summary = "Edit a project widget") @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "Project widget updated"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project widget not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @PutMapping(value = "/v1/projectWidgets/{projectWidgetId}") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<ProjectWidgetResponseDto> editByProject( @Parameter(hidden = true) @AuthenticationPrincipal LocalUser connectedUser, @Parameter(name = "projectWidgetId", description = "The project widget id", required = true, example = "1") @PathVariable("projectWidgetId") Long projectWidgetId, @Parameter(name = "projectWidgetResponseDto", description = "The project widget information to update", required = true) @RequestBody ProjectWidgetRequestDto projectWidgetRequestDto) { Optional<ProjectWidget> projectWidgetOptional = projectWidgetService.getOne(projectWidgetId); if (projectWidgetOptional.isEmpty()) { throw new ObjectNotFoundException(ProjectWidget.class, projectWidgetId); } if (!projectService.isConnectedUserCanAccessToProject(projectWidgetOptional.get().getProjectGrid().getProject(), connectedUser)) { throw new ApiException(USER_NOT_ALLOWED_PROJECT, ApiErrorEnum.NOT_AUTHORIZED); } projectWidgetService.updateProjectWidget(projectWidgetOptional.get(), projectWidgetRequestDto.getCustomStyle(), projectWidgetRequestDto.getBackendConfig()); return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(projectWidgetMapper.toProjectWidgetDto(projectWidgetOptional.get())); } /** * Add widget into the dashboard. * * @param connectedUser The connected user * @param projectToken The project token * @param projectWidgetRequestDto The projectWidget to add * @return The project */ @Operation(summary = "Add a new widget to a project") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @PostMapping(value = "/v1/projectWidgets/{projectToken}/{gridId}/projectWidgets") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<ProjectWidgetResponseDto> addProjectWidgetToProject( @Parameter(hidden = true) @AuthenticationPrincipal LocalUser connectedUser, @Parameter(name = "projectToken", description = "The project token", required = true) @PathVariable("projectToken") String projectToken, @Parameter(name = "gridId", description = "The grid id", required = true, example = "1") @PathVariable("gridId") Long gridId, @Parameter(name = "projectWidgetDto", description = "The project widget info's", required = true) @RequestBody ProjectWidgetRequestDto projectWidgetRequestDto) { Optional<Project> projectOptional = projectService.getOneByToken(projectToken); if (projectOptional.isEmpty()) { throw new ObjectNotFoundException(Project.class, projectToken); } Project project = projectOptional.get(); if (!projectService.isConnectedUserCanAccessToProject(project, connectedUser)) { throw new ApiException(USER_NOT_ALLOWED_PROJECT, ApiErrorEnum.NOT_AUTHORIZED); } if (project.getGrids().stream().noneMatch(grid -> grid.getId().equals(gridId))) {
/* * * * Copyright 2012-2021 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 * * * * 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.michelin.suricate.controllers; /** * Project widget controller. */ @RestController @RequestMapping("/api") @Tag(name = "Project Widget", description = "Project Widget Controller") public class ProjectWidgetController { @Autowired private ProjectWidgetService projectWidgetService; @Autowired private ProjectWidgetMapper projectWidgetMapper; @Autowired private ProjectService projectService; /** * Get a project widget. * * @param projectWidgetId The project widget id * @return The project updated */ @Operation(summary = "Retrieve a project widget") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project widget not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @GetMapping(value = "/v1/projectWidgets/{projectWidgetId}") @PermitAll public ResponseEntity<ProjectWidgetResponseDto> getById( @Parameter(name = "projectWidgetId", description = "The project widget id", required = true, example = "1") @PathVariable("projectWidgetId") Long projectWidgetId) { Optional<ProjectWidget> projectWidgetOptional = projectWidgetService.getOne(projectWidgetId); if (projectWidgetOptional.isEmpty()) { throw new ObjectNotFoundException(ProjectWidget.class, projectWidgetId); } return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(projectWidgetMapper.toProjectWidgetDto(projectWidgetOptional.get())); } /** * Get the list of project widgets for a project. */ @Operation(summary = "Get the full list of projectWidgets for a project") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @GetMapping(value = "/v1/projectWidgets/{projectToken}/projectWidgets") @PermitAll public ResponseEntity<List<ProjectWidgetResponseDto>> getByProject( @Parameter(name = "projectToken", description = "The project token", required = true) @PathVariable("projectToken") String projectToken) { Optional<Project> projectOptional = projectService.getOneByToken(projectToken); if (projectOptional.isEmpty()) { throw new ObjectNotFoundException(Project.class, projectToken); } Project project = projectOptional.get(); List<ProjectWidget> allWidgets = project.getGrids().stream().map(ProjectGrid::getWidgets).flatMap(Collection::stream) .toList(); if (allWidgets.isEmpty()) { return ResponseEntity.noContent().build(); } return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(projectWidgetMapper.toProjectWidgetsDtos(allWidgets)); } /** * Edit a project widget for a project. * * @param connectedUser The connected user * @param projectWidgetId The project widget id * @param projectWidgetRequestDto The project widget updated */ @Operation(summary = "Edit a project widget") @ApiResponses(value = { @ApiResponse(responseCode = "204", description = "Project widget updated"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project widget not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @PutMapping(value = "/v1/projectWidgets/{projectWidgetId}") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<ProjectWidgetResponseDto> editByProject( @Parameter(hidden = true) @AuthenticationPrincipal LocalUser connectedUser, @Parameter(name = "projectWidgetId", description = "The project widget id", required = true, example = "1") @PathVariable("projectWidgetId") Long projectWidgetId, @Parameter(name = "projectWidgetResponseDto", description = "The project widget information to update", required = true) @RequestBody ProjectWidgetRequestDto projectWidgetRequestDto) { Optional<ProjectWidget> projectWidgetOptional = projectWidgetService.getOne(projectWidgetId); if (projectWidgetOptional.isEmpty()) { throw new ObjectNotFoundException(ProjectWidget.class, projectWidgetId); } if (!projectService.isConnectedUserCanAccessToProject(projectWidgetOptional.get().getProjectGrid().getProject(), connectedUser)) { throw new ApiException(USER_NOT_ALLOWED_PROJECT, ApiErrorEnum.NOT_AUTHORIZED); } projectWidgetService.updateProjectWidget(projectWidgetOptional.get(), projectWidgetRequestDto.getCustomStyle(), projectWidgetRequestDto.getBackendConfig()); return ResponseEntity .ok() .contentType(MediaType.APPLICATION_JSON) .body(projectWidgetMapper.toProjectWidgetDto(projectWidgetOptional.get())); } /** * Add widget into the dashboard. * * @param connectedUser The connected user * @param projectToken The project token * @param projectWidgetRequestDto The projectWidget to add * @return The project */ @Operation(summary = "Add a new widget to a project") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Authentication error, token expired or invalid", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "403", description = "You don't have permission to access to this resource", content = {@Content(schema = @Schema(implementation = ApiErrorDto.class))}), @ApiResponse(responseCode = "404", description = "Project not found", content = { @Content(schema = @Schema(implementation = ApiErrorDto.class))}) }) @PostMapping(value = "/v1/projectWidgets/{projectToken}/{gridId}/projectWidgets") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<ProjectWidgetResponseDto> addProjectWidgetToProject( @Parameter(hidden = true) @AuthenticationPrincipal LocalUser connectedUser, @Parameter(name = "projectToken", description = "The project token", required = true) @PathVariable("projectToken") String projectToken, @Parameter(name = "gridId", description = "The grid id", required = true, example = "1") @PathVariable("gridId") Long gridId, @Parameter(name = "projectWidgetDto", description = "The project widget info's", required = true) @RequestBody ProjectWidgetRequestDto projectWidgetRequestDto) { Optional<Project> projectOptional = projectService.getOneByToken(projectToken); if (projectOptional.isEmpty()) { throw new ObjectNotFoundException(Project.class, projectToken); } Project project = projectOptional.get(); if (!projectService.isConnectedUserCanAccessToProject(project, connectedUser)) { throw new ApiException(USER_NOT_ALLOWED_PROJECT, ApiErrorEnum.NOT_AUTHORIZED); } if (project.getGrids().stream().noneMatch(grid -> grid.getId().equals(gridId))) {
throw new GridNotFoundException(gridId, projectToken);
13
2023-12-11 11:28:37+00:00
16k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/OpenskyService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.config.FeederMapping; import com.amnesica.belugaproject.config.StaticValues; import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft; import com.amnesica.belugaproject.entities.data.AirportData; import com.amnesica.belugaproject.repositories.aircraft.OpenskyAircraftRepository; import com.amnesica.belugaproject.services.data.AircraftDataService; import com.amnesica.belugaproject.services.data.AirportDataService; import com.amnesica.belugaproject.services.helper.HelperService; import com.amnesica.belugaproject.services.helper.NetworkHandlerService; import com.amnesica.belugaproject.services.helper.Request; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
11,068
conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(innerArray.getDouble(9)); conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble); innerObject.put("speed", conversionValueDouble); } else { innerObject.put("speed", innerArray.get(9)); } if (innerArray.get(11) instanceof Integer) { conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(((int) innerArray.get(11))); innerObject.put("verticalRate", conversionValueDouble); } else if (innerArray.get(11) instanceof Double || innerArray.get(11) instanceof BigDecimal) { conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(innerArray.getDouble(11)); innerObject.put("verticalRate", conversionValueDouble); } else { innerObject.put("verticalRate", innerArray.get(11)); } // Füge innerObject zu arrayWithObjects hinzu arrayWithObjects.put(innerObject); } } return arrayWithObjects; } /** * Erstellt einen Feeder für das Opensky-Network * * @return Feeder */ public Feeder createOpenskyFeeder() { // Erstelle Feeder Opensky Feeder feeder = new Feeder("Opensky", null, "Opensky", "yellow"); // Erstelle Mapping FeederMapping mapping = new FeederMapping(); mapping.setHex("hex"); mapping.setLatitude("latitude"); mapping.setLongitude("longitude"); mapping.setAltitude("altitude"); mapping.setTrack("track"); mapping.setOnGround("onGround"); mapping.setSpeed("speed"); mapping.setSquawk("squawk"); mapping.setFlightId("flightId"); mapping.setVerticalRate("verticalRate"); mapping.setAutopilotEngaged("autopilotEngaged"); mapping.setElipsoidalAltitude("elipsoidalAltitude"); mapping.setFeeder("feeder"); mapping.setSource("source"); // Setze Mapping feeder.setMapping(mapping); return feeder; } /** * Methode ruft Flugzeuge innerhalb des Extents in arrayOpenskyExtent vom * Opensky-Network ab und speichert Flugzeuge in der Tabelle opensky_aircraft. * Methode wird alle INTERVAL_UPDATE_OPENSKY Sekunden abgerufen. Abruf wird * jedoch nur durchgeführt, wenn das arrayOpenskyExtent-Array mit Werten gefüllt * ist (dieses wird nur bei einer Anfrage vom Frontend gefüllt). Hinweis: Das * Abruf-Intervall ist auf 10 Sekunden gesetzt, da für nicht-registrierte Nutzer * nur alle 10 Sekunden die Daten von Opensky aktualisiert werden können */ @Scheduled(fixedRate = StaticValues.INTERVAL_UPDATE_OPENSKY) private void getPlanesFromOpensky() { // Hole Request aus queue. Wenn kein Request vorhanden ist, wird null zurückgegeben Request request = requestQueueOpensky.poll(); if (request == null) { return; } // Suche und extrahiere den neuesten Request der IP-Addresse final Request copyRequest = request; Optional<Request> requestNewest = requestQueueOpensky.stream() .filter(r -> r.getIpAddressClient().equals(copyRequest.getIpAddressClient()) && r.getTimestamp() > copyRequest.getTimestamp()).max(Comparator.comparing(Request::getTimestamp)); if (requestNewest.isPresent()) { // Ersetze ursprünglich gepollten Request durch neueren Request request = requestNewest.get(); // Lösche alle bisherigen Requests derjenigen Ip-Adressse, welche älter sind als der herausgenommene Request requestQueueOpensky.removeIf(r -> r.getTimestamp() < requestNewest.get().getTimestamp() && r.getIpAddressClient().equals(copyRequest.getIpAddressClient())); } // Validiere Request if (request.getLomin() == null || request.getLamin() == null || request.getLomax() == null || request.getLamax() == null) { log.error("Opensky: Request " + request + " is is not valid. Nothing to do"); return; } JSONArray jsonArrayFromOpensky; // Hole Flugzeuge als JSONArray vom Opensky-Network jsonArrayFromOpensky = getDataFromOpensky(request.getLomin(), request.getLamin(), request.getLomax(), request.getLamax()); // Initialisiere Feeder, wenn nötig if (openskyFeeder == null) { openskyFeeder = createOpenskyFeeder(); } if (jsonArrayFromOpensky != null) { for (int i = 0; i < jsonArrayFromOpensky.length(); i++) { // Extrahiere element aus JSONArray JSONObject element = jsonArrayFromOpensky.getJSONObject(i); // Prüfe, ob element alle Basis-Eigenschaften erfüllt (bspw. 'lat','lon' sind // vorhanden) if (element != null && element.has("hex") && element.has("lat") && element.has("lon") && !element.isNull("lat") && !element.isNull("lon") && element.getDouble("lat") != 0 && element.getDouble("lon") != 0) { // Erstelle aus Daten des Feeders ein neues Flugzeug
package com.amnesica.belugaproject.services.aircraft; @Slf4j @EnableScheduling @Service public class OpenskyService { @Autowired private AircraftService aircraftService; @Autowired private NetworkHandlerService networkHandler; @Autowired private AircraftDataService aircraftDataService; @Autowired private AirportDataService airportDataService; @Autowired private OpenskyAircraftRepository openskyAircraftRepository; @Autowired private Configuration configuration; // Feeder für das Opensky-Network private Feeder openskyFeeder; // Queue mit Anfragen an Opensky private final BlockingQueue<Request> requestQueueOpensky = new LinkedBlockingQueue<>(); // Url zum Fetchen der Daten von Opensky private static final String URL_OPENSKY_LIVE_API = "https://opensky-network.org/api/states/all?"; /** * Ruft die Rohdaten als JSONArray vom Opensky-Network ab * * @param lomin lower bound for the longitude in decimal degrees * @param lamin lower bound for the latitude in decimal degrees * @param lomax upper bound for the longitude in decimal degrees * @param lamax upper bound for the latitude in decimal degrees * @return JSONArray */ public JSONArray getDataFromOpensky(double lomin, double lamin, double lomax, double lamax) { // Array mit konvertierten Daten von Opensky JSONArray jsonArray = null; // Genriere URL mit Daten der Bounding-Box vom Frontend final String url = URL_OPENSKY_LIVE_API + "lamin=" + lamin + "&lomin=" + lomin + "&lamax=" + lamax + "&lomax=" + lomax; // Anfrage an Opensky mit url und Credentials String jsonStr = networkHandler.makeOpenskyServiceCall(url, configuration.getOpenskyUsername(), configuration.getOpenskyPassword()); try { if (jsonStr != null) { JSONObject jsonObject = new JSONObject(jsonStr); // Hinweis: jsonArray ist ein Array aus Arrays // und muss daher für weitere Bearbeitung konvertiert werden JSONArray jsonArrayStates = jsonObject.getJSONArray("states"); if (jsonArrayStates != null) { jsonArray = convertJsonArrayToArrayOfObjects(jsonArrayStates); } else { throw new Exception(); } } } catch (Exception e) { log.error( "Server: Data from Opensky-Network could not get fetched or there are no planes in this area. Url: " + url); } return jsonArray; } /** * Konvertiert ein JSONArray aus Arrays in ein JSONArray aus JSONObjects * * @param jsonArray JSONArray * @return JSONArray */ private JSONArray convertJsonArrayToArrayOfObjects(JSONArray jsonArray) { JSONArray arrayWithObjects = new JSONArray(); Double conversionValueDouble; if (jsonArray == null) { return null; } for (int i = 0; i < jsonArray.length(); i++) { JSONArray innerArray = jsonArray.getJSONArray(i); if (innerArray != null) { JSONObject innerObject = new JSONObject(); innerObject.put("hex", innerArray.get(0)); innerObject.put("flightId", innerArray.get(1)); innerObject.put("onGround", innerArray.get(8)); innerObject.put("squawk", innerArray.get(14)); innerObject.put("source", innerArray.get(16)); if (innerArray.get(5) instanceof BigDecimal) { innerObject.put("lon", innerArray.getDouble(5)); } else { innerObject.put("lon", innerArray.get(5)); } if (innerArray.get(6) instanceof BigDecimal) { innerObject.put("lat", innerArray.getDouble(6)); } else { innerObject.put("lat", innerArray.get(6)); } if (innerArray.get(10) instanceof BigDecimal) { innerObject.put("track", innerArray.getDouble(10)); } else { innerObject.put("track", innerArray.get(10)); } // OpenSky liefert metrische Werte, deshalb Konvertierung in nautical erforderlich if (innerArray.get(7) instanceof Integer) { conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(7))); innerObject.put("elipsoidalAltitude", conversionValueDouble); } else if (innerArray.get(7) instanceof Double || innerArray.get(7) instanceof BigDecimal) { conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(7)); innerObject.put("elipsoidalAltitude", conversionValueDouble); } else { innerObject.put("elipsoidalAltitude", innerArray.get(7)); } if (innerArray.get(13) instanceof Integer) { conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(13))); innerObject.put("altitude", conversionValueDouble); } else if (innerArray.get(13) instanceof Double || innerArray.get(13) instanceof BigDecimal) { conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(13)); innerObject.put("altitude", conversionValueDouble); } else { innerObject.put("altitude", innerArray.get(13)); } if (innerArray.get(9) instanceof Integer) { conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(((int) innerArray.get(9))); conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble); innerObject.put("speed", conversionValueDouble); } else if (innerArray.get(9) instanceof Double || innerArray.get(9) instanceof BigDecimal) { conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(innerArray.getDouble(9)); conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble); innerObject.put("speed", conversionValueDouble); } else { innerObject.put("speed", innerArray.get(9)); } if (innerArray.get(11) instanceof Integer) { conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(((int) innerArray.get(11))); innerObject.put("verticalRate", conversionValueDouble); } else if (innerArray.get(11) instanceof Double || innerArray.get(11) instanceof BigDecimal) { conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(innerArray.getDouble(11)); innerObject.put("verticalRate", conversionValueDouble); } else { innerObject.put("verticalRate", innerArray.get(11)); } // Füge innerObject zu arrayWithObjects hinzu arrayWithObjects.put(innerObject); } } return arrayWithObjects; } /** * Erstellt einen Feeder für das Opensky-Network * * @return Feeder */ public Feeder createOpenskyFeeder() { // Erstelle Feeder Opensky Feeder feeder = new Feeder("Opensky", null, "Opensky", "yellow"); // Erstelle Mapping FeederMapping mapping = new FeederMapping(); mapping.setHex("hex"); mapping.setLatitude("latitude"); mapping.setLongitude("longitude"); mapping.setAltitude("altitude"); mapping.setTrack("track"); mapping.setOnGround("onGround"); mapping.setSpeed("speed"); mapping.setSquawk("squawk"); mapping.setFlightId("flightId"); mapping.setVerticalRate("verticalRate"); mapping.setAutopilotEngaged("autopilotEngaged"); mapping.setElipsoidalAltitude("elipsoidalAltitude"); mapping.setFeeder("feeder"); mapping.setSource("source"); // Setze Mapping feeder.setMapping(mapping); return feeder; } /** * Methode ruft Flugzeuge innerhalb des Extents in arrayOpenskyExtent vom * Opensky-Network ab und speichert Flugzeuge in der Tabelle opensky_aircraft. * Methode wird alle INTERVAL_UPDATE_OPENSKY Sekunden abgerufen. Abruf wird * jedoch nur durchgeführt, wenn das arrayOpenskyExtent-Array mit Werten gefüllt * ist (dieses wird nur bei einer Anfrage vom Frontend gefüllt). Hinweis: Das * Abruf-Intervall ist auf 10 Sekunden gesetzt, da für nicht-registrierte Nutzer * nur alle 10 Sekunden die Daten von Opensky aktualisiert werden können */ @Scheduled(fixedRate = StaticValues.INTERVAL_UPDATE_OPENSKY) private void getPlanesFromOpensky() { // Hole Request aus queue. Wenn kein Request vorhanden ist, wird null zurückgegeben Request request = requestQueueOpensky.poll(); if (request == null) { return; } // Suche und extrahiere den neuesten Request der IP-Addresse final Request copyRequest = request; Optional<Request> requestNewest = requestQueueOpensky.stream() .filter(r -> r.getIpAddressClient().equals(copyRequest.getIpAddressClient()) && r.getTimestamp() > copyRequest.getTimestamp()).max(Comparator.comparing(Request::getTimestamp)); if (requestNewest.isPresent()) { // Ersetze ursprünglich gepollten Request durch neueren Request request = requestNewest.get(); // Lösche alle bisherigen Requests derjenigen Ip-Adressse, welche älter sind als der herausgenommene Request requestQueueOpensky.removeIf(r -> r.getTimestamp() < requestNewest.get().getTimestamp() && r.getIpAddressClient().equals(copyRequest.getIpAddressClient())); } // Validiere Request if (request.getLomin() == null || request.getLamin() == null || request.getLomax() == null || request.getLamax() == null) { log.error("Opensky: Request " + request + " is is not valid. Nothing to do"); return; } JSONArray jsonArrayFromOpensky; // Hole Flugzeuge als JSONArray vom Opensky-Network jsonArrayFromOpensky = getDataFromOpensky(request.getLomin(), request.getLamin(), request.getLomax(), request.getLamax()); // Initialisiere Feeder, wenn nötig if (openskyFeeder == null) { openskyFeeder = createOpenskyFeeder(); } if (jsonArrayFromOpensky != null) { for (int i = 0; i < jsonArrayFromOpensky.length(); i++) { // Extrahiere element aus JSONArray JSONObject element = jsonArrayFromOpensky.getJSONObject(i); // Prüfe, ob element alle Basis-Eigenschaften erfüllt (bspw. 'lat','lon' sind // vorhanden) if (element != null && element.has("hex") && element.has("lat") && element.has("lon") && !element.isNull("lat") && !element.isNull("lon") && element.getDouble("lat") != 0 && element.getDouble("lon") != 0) { // Erstelle aus Daten des Feeders ein neues Flugzeug
OpenskyAircraft aircraftNew = aircraftService.createNewOpenskyAircraft(element, openskyFeeder);
4
2023-12-11 11:37:46+00:00
16k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCodecsTest.java
[ { "identifier": "BinaryHttpRequest", "path": "codec-bhttp/src/main/java/io/netty/incubator/codec/bhttp/BinaryHttpRequest.java", "snippet": "public interface BinaryHttpRequest extends HttpRequest {\n\n /**\n * Returns the scheme used.\n *\n * @return scheme.\n */\n String scheme();\...
import io.netty.incubator.codec.bhttp.BinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpResponse; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpResponse; import io.netty.incubator.codec.bhttp.FullBinaryHttpRequest; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LoggingHandler; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.util.ReferenceCountUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
12,849
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); } public static ChannelPair createChannelPair(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { AsymmetricCipherKeyPair kpR = OHttpCryptoTest.createX25519KeyPair(serverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); byte keyId = 0x66; OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList(
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); } public static ChannelPair createChannelPair(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { AsymmetricCipherKeyPair kpR = OHttpCryptoTest.createX25519KeyPair(serverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); byte keyId = 0x66; OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList(
OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.AES_GCM128),
6
2023-12-06 09:14:09+00:00
16k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/audio/mp3/MP3FileWriter.java
[ { "identifier": "AudioFile", "path": "android/src/main/java/org/jaudiotagger/audio/AudioFile.java", "snippet": "public class AudioFile\n{\n //Logger\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio\");\n\n /**\n *\n * The physical file that this instance represe...
import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.exceptions.CannotReadException; import org.jaudiotagger.audio.exceptions.CannotWriteException; import org.jaudiotagger.audio.generic.AudioFileWriter; import org.jaudiotagger.tag.Tag; import java.io.IOException; import java.io.RandomAccessFile;
13,053
package org.jaudiotagger.audio.mp3; /** * Write Mp3 Info (retrofitted to entagged ,done differently to entagged which is why some methods throw RuntimeException) * because done elsewhere */ public class MP3FileWriter extends AudioFileWriter { public void deleteTag(AudioFile f) throws CannotWriteException { //Because audio file is an instanceof MP3File this directs it to save //taking into account if the tag has been sent to null in which case it will be deleted f.commit(); } public void writeFile(AudioFile f) throws CannotWriteException { //Because audio file is an instanceof MP3File this directs it to save f.commit(); } /** * Delete the Id3v1 and ID3v2 tags from file * * @param af * @throws CannotReadException * @throws CannotWriteException */ @Override
package org.jaudiotagger.audio.mp3; /** * Write Mp3 Info (retrofitted to entagged ,done differently to entagged which is why some methods throw RuntimeException) * because done elsewhere */ public class MP3FileWriter extends AudioFileWriter { public void deleteTag(AudioFile f) throws CannotWriteException { //Because audio file is an instanceof MP3File this directs it to save //taking into account if the tag has been sent to null in which case it will be deleted f.commit(); } public void writeFile(AudioFile f) throws CannotWriteException { //Because audio file is an instanceof MP3File this directs it to save f.commit(); } /** * Delete the Id3v1 and ID3v2 tags from file * * @param af * @throws CannotReadException * @throws CannotWriteException */ @Override
public synchronized void delete(AudioFile af) throws CannotReadException, CannotWriteException
1
2023-12-11 05:58:19+00:00
16k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/permissions/service/impl/SysRoleServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.mybatis.core.enums.DeptUserDataScopeEnum; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.framework.security.support.SecurityContextUtil; import com.xht.cloud.system.exceptions.PermissionException; import com.xht.cloud.system.manager.PermissionsManager; import com.xht.cloud.system.module.dept.convert.SysDeptConvert; import com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO; import com.xht.cloud.system.module.dept.dao.dataobject.SysRoleDeptDO; import com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper; import com.xht.cloud.system.module.dept.dao.mapper.SysRoleDeptMapper; import com.xht.cloud.system.module.dept.dao.wrapper.SysRoleDeptWrapper; import com.xht.cloud.system.module.permissions.controller.request.SysRoleAddRequest; import com.xht.cloud.system.module.permissions.controller.request.SysRoleQueryRequest; import com.xht.cloud.system.module.permissions.controller.request.SysRoleUpdateRequest; import com.xht.cloud.system.module.permissions.controller.response.SysRoleResponse; import com.xht.cloud.system.module.permissions.convert.SysRoleConvert; import com.xht.cloud.system.module.permissions.dao.dataobject.SysRoleDO; import com.xht.cloud.system.module.permissions.dao.dataobject.SysUserRoleDO; import com.xht.cloud.system.module.permissions.dao.mapper.SysRoleMapper; import com.xht.cloud.system.module.permissions.dao.mapper.SysUserRoleMapper; import com.xht.cloud.system.module.permissions.dao.wrapper.SysRoleWrapper; import com.xht.cloud.system.module.permissions.service.ISysRoleService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
10,807
package com.xht.cloud.system.module.permissions.service.impl; /** * 描述 :系统角色表 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper sysRoleMapper; private final SysRoleConvert sysRoleConvert; private final SysDeptMapper sysDeptMapper; private final SysDeptConvert sysDeptConvert; private final SysRoleDeptMapper sysRoleDeptMapper; private final SysUserRoleMapper sysUserRoleMapper; private final PermissionsManager permissionsManager; /** * 创建 * * @param addRequest {@link SysRoleAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysRoleAddRequest addRequest) { SysRoleDO entity = sysRoleConvert.toDO(addRequest); sysRoleMapper.insert(entity); permissionsManager.saveRoleDept(entity.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, addRequest.getDeptIds()); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysRoleUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysRoleUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } SysRoleDO entity = sysRoleConvert.toDO(updateRequest); sysRoleDeptMapper.delete(SysRoleDeptWrapper.getInstance().lambdaQuery().eq(SysRoleDeptDO::getRoleId, entity.getId())); permissionsManager.saveRoleDept(updateRequest.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, updateRequest.getDeptIds()); sysRoleMapper.updateById(entity); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) {
package com.xht.cloud.system.module.permissions.service.impl; /** * 描述 :系统角色表 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper sysRoleMapper; private final SysRoleConvert sysRoleConvert; private final SysDeptMapper sysDeptMapper; private final SysDeptConvert sysDeptConvert; private final SysRoleDeptMapper sysRoleDeptMapper; private final SysUserRoleMapper sysUserRoleMapper; private final PermissionsManager permissionsManager; /** * 创建 * * @param addRequest {@link SysRoleAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysRoleAddRequest addRequest) { SysRoleDO entity = sysRoleConvert.toDO(addRequest); sysRoleMapper.insert(entity); permissionsManager.saveRoleDept(entity.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, addRequest.getDeptIds()); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysRoleUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysRoleUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } SysRoleDO entity = sysRoleConvert.toDO(updateRequest); sysRoleDeptMapper.delete(SysRoleDeptWrapper.getInstance().lambdaQuery().eq(SysRoleDeptDO::getRoleId, entity.getId())); permissionsManager.saveRoleDept(updateRequest.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, updateRequest.getDeptIds()); sysRoleMapper.updateById(entity); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) {
long l = sysUserRoleMapper.selectCount(new LambdaQueryWrapper<SysUserRoleDO>().in(SysUserRoleDO::getRoleId, ids));
20
2023-12-12 08:16:30+00:00
16k
serendipitk/LunarCore
src/main/java/emu/lunarcore/game/rogue/RogueEntityLoader.java
[ { "identifier": "GameData", "path": "src/main/java/emu/lunarcore/data/GameData.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2O...
import emu.lunarcore.data.GameData; import emu.lunarcore.data.GameDepot; import emu.lunarcore.data.config.GroupInfo; import emu.lunarcore.data.config.MonsterInfo; import emu.lunarcore.data.config.NpcInfo; import emu.lunarcore.data.config.PropInfo; import emu.lunarcore.data.excel.NpcMonsterExcel; import emu.lunarcore.data.excel.PropExcel; import emu.lunarcore.data.excel.RogueMonsterExcel; import emu.lunarcore.data.excel.RogueNPCExcel; import emu.lunarcore.game.enums.PropState; import emu.lunarcore.game.scene.Scene; import emu.lunarcore.game.scene.SceneEntityLoader; import emu.lunarcore.game.scene.entity.EntityMonster; import emu.lunarcore.game.scene.entity.EntityNpc; import emu.lunarcore.game.scene.entity.EntityProp; import emu.lunarcore.game.scene.entity.extra.PropRogueData; import emu.lunarcore.util.Utils;
14,274
package emu.lunarcore.game.rogue; public class RogueEntityLoader extends SceneEntityLoader { @Override public void onSceneLoad(Scene scene) { // Make sure player is in a rogue instance RogueInstance rogue = scene.getPlayer().getRogueInstance(); if (rogue == null) return; // Get current room RogueRoomData room = rogue.getCurrentRoom(); if (room == null) return; // Load scene groups for (int key : room.getExcel().getGroupWithContent().keySet()) { scene.loadGroup(key); } } @Override
package emu.lunarcore.game.rogue; public class RogueEntityLoader extends SceneEntityLoader { @Override public void onSceneLoad(Scene scene) { // Make sure player is in a rogue instance RogueInstance rogue = scene.getPlayer().getRogueInstance(); if (rogue == null) return; // Get current room RogueRoomData room = rogue.getCurrentRoom(); if (room == null) return; // Load scene groups for (int key : room.getExcel().getGroupWithContent().keySet()) { scene.loadGroup(key); } } @Override
public EntityMonster loadMonster(Scene scene, GroupInfo group, MonsterInfo monsterInfo) {
2
2023-12-08 14:13:04+00:00
16k
quentin452/Garden-Stuff-Continuation
src/main/java/com/jaquadro/minecraft/gardenstuff/renderer/FenceRenderer.java
[ { "identifier": "ModularBoxRenderer", "path": "src/main/java/com/jaquadro/minecraft/gardencore/client/renderer/support/ModularBoxRenderer.java", "snippet": "public class ModularBoxRenderer {\n\n public static final int CONNECT_YNEG = 1;\n public static final int CONNECT_YPOS = 2;\n public stati...
import com.jaquadro.minecraft.gardencore.client.renderer.support.ModularBoxRenderer; import com.jaquadro.minecraft.gardenstuff.block.BlockFence; import com.jaquadro.minecraft.gardenstuff.core.ClientProxy; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess;
13,214
package com.jaquadro.minecraft.gardenstuff.renderer; public class FenceRenderer implements ISimpleBlockRenderingHandler { private static final float UN4 = -0.25F; private static final float U1 = 0.0615F; private static final float U7 = 0.4385F; private static final float U8 = 0.5F; private static final float U9 = 0.5615F; private static final float U15 = 0.9385F; private static final float U20 = 1.25F; private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {} public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
package com.jaquadro.minecraft.gardenstuff.renderer; public class FenceRenderer implements ISimpleBlockRenderingHandler { private static final float UN4 = -0.25F; private static final float U1 = 0.0615F; private static final float U7 = 0.4385F; private static final float U8 = 0.5F; private static final float U9 = 0.5615F; private static final float U15 = 0.9385F; private static final float U20 = 1.25F; private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {} public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
return !(block instanceof BlockFence) ? false
1
2023-12-12 08:13:16+00:00
16k
Zergatul/java-scripting-language
src/test/java/com/zergatul/scripting/tests/LambdaTest.java
[ { "identifier": "IntStorage", "path": "src/test/java/com/zergatul/scripting/helpers/IntStorage.java", "snippet": "public class IntStorage {\r\n\r\n public final List<Integer> list = new ArrayList<>();\r\n\r\n public void add(int value) {\r\n list.add(value);\r\n }\r\n}\r" }, { "i...
import com.zergatul.scripting.helpers.IntStorage; import com.zergatul.scripting.compiler.ScriptingLanguageCompiler; import com.zergatul.scripting.helpers.Run; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List;
13,651
package com.zergatul.scripting.tests; public class LambdaTest { @BeforeEach public void clean() { ApiRoot.run = new Run(); ApiRoot.storage = new IntStorage(); } @Test public void simpleTest() throws Exception { String code = """ run.skip(() => { storage.add(20); }); run.once(() => { storage.add(10); storage.add(5); }); """;
package com.zergatul.scripting.tests; public class LambdaTest { @BeforeEach public void clean() { ApiRoot.run = new Run(); ApiRoot.storage = new IntStorage(); } @Test public void simpleTest() throws Exception { String code = """ run.skip(() => { storage.add(20); }); run.once(() => { storage.add(10); storage.add(5); }); """;
ScriptingLanguageCompiler compiler = new ScriptingLanguageCompiler(ApiRoot.class);
1
2023-12-10 00:37:27+00:00
16k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2OpenController.java
[ { "identifier": "UserTypeEnum", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/UserTypeEnum.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum UserTypeEnum implements IntArrayValuable {\n\n MEMBER(1, \"会员\"), // 面向 c 端,普通用户\n ADMIN(2, \"管理员\")...
import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.util.http.HttpUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.security.core.annotation.LoginFree; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAccessTokenRespVO; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAuthorizeInfoRespVO; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenCheckTokenRespVO; import cn.iocoder.yudao.module.system.convert.oauth2.OAuth2OpenConvert; import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO; import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ApproveDO; import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ClientDO; import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2GrantTypeEnum; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2ApproveService; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2ClientService; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2GrantService; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2TokenService; import cn.iocoder.yudao.module.system.util.oauth2.OAuth2Utils; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
12,851
@RequestParam(value = "refresh_token", required = false) String refreshToken) { // 刷新模式 List<String> scopes = OAuth2Utils.buildScopes(scope); // 1.1 校验授权类型 OAuth2GrantTypeEnum grantTypeEnum = OAuth2GrantTypeEnum.getByGranType(grantType); if (grantTypeEnum == null) { throw exception0(BAD_REQUEST.getCode(), StrUtil.format("未知授权类型({})", grantType)); } if (grantTypeEnum == OAuth2GrantTypeEnum.IMPLICIT) { throw exception0(BAD_REQUEST.getCode(), "Token 接口不支持 implicit 授权模式"); } // 1.2 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], grantType, scopes, redirectUri); // 2. 根据授权模式,获取访问令牌 OAuth2AccessTokenDO accessTokenDO; switch (grantTypeEnum) { case AUTHORIZATION_CODE: accessTokenDO = oauth2GrantService.grantAuthorizationCodeForAccessToken(client.getClientId(), code, redirectUri, state); break; case PASSWORD: accessTokenDO = oauth2GrantService.grantPassword(username, password, client.getClientId(), scopes); break; case CLIENT_CREDENTIALS: accessTokenDO = oauth2GrantService.grantClientCredentials(client.getClientId(), scopes); break; case REFRESH_TOKEN: accessTokenDO = oauth2GrantService.grantRefreshToken(refreshToken, client.getClientId()); break; default: throw new IllegalArgumentException("未知授权类型:" + grantType); } Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查 return success(OAuth2OpenConvert.INSTANCE.convert(accessTokenDO)); } @DeleteMapping("/token") @LoginFree @Operation(summary = "删除访问令牌") @Parameter(name = "token", required = true, description = "访问令牌", example = "biu") @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<Boolean> revokeToken(HttpServletRequest request, @RequestParam("token") String token) { // 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], null, null, null); // 删除访问令牌 return success(oauth2GrantService.revokeToken(client.getClientId(), token)); } /** * 对应 Spring Security OAuth 的 CheckTokenEndpoint 类的 checkToken 方法 */ @PostMapping("/check-token") @LoginFree @Operation(summary = "校验访问令牌") @Parameter(name = "token", required = true, description = "访问令牌", example = "biu") @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<OAuth2OpenCheckTokenRespVO> checkToken(HttpServletRequest request, @RequestParam("token") String token) { // 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], null, null, null); // 校验令牌 OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.checkAccessToken(token); Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查 return success(OAuth2OpenConvert.INSTANCE.convert2(accessTokenDO)); } /** * 对应 Spring Security OAuth 的 AuthorizationEndpoint 类的 authorize 方法 */ @GetMapping("/authorize") @Operation(summary = "获得授权信息", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameter(name = "clientId", required = true, description = "客户端编号", example = "tudou") public CommonResult<OAuth2OpenAuthorizeInfoRespVO> authorize(@RequestParam("clientId") String clientId) { // 0. 校验用户已经登录。通过 Spring Security 实现 // 1. 获得 Client 客户端的信息 OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientId); // 2. 获得用户已经授权的信息 List<OAuth2ApproveDO> approves = oauth2ApproveService.getApproveList(getLoginUserId(), getUserType(), clientId); // 拼接返回 return success(OAuth2OpenConvert.INSTANCE.convert(client, approves)); } /** * 对应 Spring Security OAuth 的 AuthorizationEndpoint 类的 approveOrDeny 方法 * * 场景一:【自动授权 autoApprove = true】 * 刚进入 sso.vue 界面,调用该接口,用户历史已经给该应用做过对应的授权,或者 OAuth2Client 支持该 scope 的自动授权 * 场景二:【手动授权 autoApprove = false】 * 在 sso.vue 界面,用户选择好 scope 授权范围,调用该接口,进行授权。此时,approved 为 true 或者 false * * 因为前后端分离,Axios 无法很好的处理 302 重定向,所以和 Spring Security OAuth 略有不同,返回结果是重定向的 URL,剩余交给前端处理 */ @PostMapping("/authorize") @Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用") @Parameters({ @Parameter(name = "response_type", required = true, description = "响应类型", example = "code"), @Parameter(name = "client_id", required = true, description = "客户端编号", example = "tudou"), @Parameter(name = "scope", description = "授权范围", example = "userinfo.read"), // 使用 Map<String, Boolean> 格式,Spring MVC 暂时不支持这么接收参数 @Parameter(name = "redirect_uri", required = true, description = "重定向 URI", example = "https://www.iocoder.cn"), @Parameter(name = "auto_approve", required = true, description = "用户是否接受", example = "true"), @Parameter(name = "state", example = "1") }) @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<String> approveOrDeny(@RequestParam("response_type") String responseType, @RequestParam("client_id") String clientId, @RequestParam(value = "scope", required = false) String scope, @RequestParam("redirect_uri") String redirectUri, @RequestParam(value = "auto_approve") Boolean autoApprove, @RequestParam(value = "state", required = false) String state) { @SuppressWarnings("unchecked")
package cn.iocoder.yudao.module.system.controller.admin.oauth2; /** * 提供给外部应用调用为主 * * 一般来说,管理后台的 /system-api/* 是不直接提供给外部应用使用,主要是外部应用能够访问的数据与接口是有限的,而管理后台的 RBAC 无法很好的控制。 * 参考大量的开放平台,都是独立的一套 OpenAPI,对应到【本系统】就是在 Controller 下新建 open 包,实现 /open-api/* 接口,然后通过 scope 进行控制。 * 另外,一个公司如果有多个管理后台,它们 client_id 产生的 access token 相互之间是无法互通的,即无法访问它们系统的 API 接口,直到两个 client_id 产生信任授权。 * * 考虑到【本系统】暂时不想做的过于复杂,默认只有获取到 access token 之后,可以访问【本系统】管理后台的 /system-api/* 所有接口,除非手动添加 scope 控制。 * scope 的使用示例,可见 {@link OAuth2UserController} 类 * * @author 芋道源码 */ @Tag(name = "管理后台 - OAuth2.0 授权") @RestController @RequestMapping("/system/oauth2") @Validated @Slf4j public class OAuth2OpenController { @Resource private OAuth2GrantService oauth2GrantService; @Resource private OAuth2ClientService oauth2ClientService; @Resource private OAuth2ApproveService oauth2ApproveService; @Resource private OAuth2TokenService oauth2TokenService; /** * 对应 Spring Security OAuth 的 TokenEndpoint 类的 postAccessToken 方法 * * 授权码 authorization_code 模式时:code + redirectUri + state 参数 * 密码 password 模式时:username + password + scope 参数 * 刷新 refresh_token 模式时:refreshToken 参数 * 客户端 client_credentials 模式:scope 参数 * 简化 implicit 模式时:不支持 * * 注意,默认需要传递 client_id + client_secret 参数 */ @PostMapping("/token") @LoginFree @Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameters({ @Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"), @Parameter(name = "code", description = "授权范围", example = "userinfo.read"), @Parameter(name = "redirect_uri", description = "重定向 URI", example = "https://www.iocoder.cn"), @Parameter(name = "state", description = "状态", example = "1"), @Parameter(name = "username", example = "tudou"), @Parameter(name = "password", example = "cai"), // 多个使用空格分隔 @Parameter(name = "scope", example = "user_info"), @Parameter(name = "refresh_token", example = "123424233"), }) @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<OAuth2OpenAccessTokenRespVO> postAccessToken(HttpServletRequest request, @RequestParam("grant_type") String grantType, @RequestParam(value = "code", required = false) String code, // 授权码模式 @RequestParam(value = "redirect_uri", required = false) String redirectUri, // 授权码模式 @RequestParam(value = "state", required = false) String state, // 授权码模式 @RequestParam(value = "username", required = false) String username, // 密码模式 @RequestParam(value = "password", required = false) String password, // 密码模式 @RequestParam(value = "scope", required = false) String scope, // 密码模式 @RequestParam(value = "refresh_token", required = false) String refreshToken) { // 刷新模式 List<String> scopes = OAuth2Utils.buildScopes(scope); // 1.1 校验授权类型 OAuth2GrantTypeEnum grantTypeEnum = OAuth2GrantTypeEnum.getByGranType(grantType); if (grantTypeEnum == null) { throw exception0(BAD_REQUEST.getCode(), StrUtil.format("未知授权类型({})", grantType)); } if (grantTypeEnum == OAuth2GrantTypeEnum.IMPLICIT) { throw exception0(BAD_REQUEST.getCode(), "Token 接口不支持 implicit 授权模式"); } // 1.2 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], grantType, scopes, redirectUri); // 2. 根据授权模式,获取访问令牌 OAuth2AccessTokenDO accessTokenDO; switch (grantTypeEnum) { case AUTHORIZATION_CODE: accessTokenDO = oauth2GrantService.grantAuthorizationCodeForAccessToken(client.getClientId(), code, redirectUri, state); break; case PASSWORD: accessTokenDO = oauth2GrantService.grantPassword(username, password, client.getClientId(), scopes); break; case CLIENT_CREDENTIALS: accessTokenDO = oauth2GrantService.grantClientCredentials(client.getClientId(), scopes); break; case REFRESH_TOKEN: accessTokenDO = oauth2GrantService.grantRefreshToken(refreshToken, client.getClientId()); break; default: throw new IllegalArgumentException("未知授权类型:" + grantType); } Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查 return success(OAuth2OpenConvert.INSTANCE.convert(accessTokenDO)); } @DeleteMapping("/token") @LoginFree @Operation(summary = "删除访问令牌") @Parameter(name = "token", required = true, description = "访问令牌", example = "biu") @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<Boolean> revokeToken(HttpServletRequest request, @RequestParam("token") String token) { // 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], null, null, null); // 删除访问令牌 return success(oauth2GrantService.revokeToken(client.getClientId(), token)); } /** * 对应 Spring Security OAuth 的 CheckTokenEndpoint 类的 checkToken 方法 */ @PostMapping("/check-token") @LoginFree @Operation(summary = "校验访问令牌") @Parameter(name = "token", required = true, description = "访问令牌", example = "biu") @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<OAuth2OpenCheckTokenRespVO> checkToken(HttpServletRequest request, @RequestParam("token") String token) { // 校验客户端 String[] clientIdAndSecret = obtainBasicAuthorization(request); oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1], null, null, null); // 校验令牌 OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.checkAccessToken(token); Assert.notNull(accessTokenDO, "访问令牌不能为空"); // 防御性检查 return success(OAuth2OpenConvert.INSTANCE.convert2(accessTokenDO)); } /** * 对应 Spring Security OAuth 的 AuthorizationEndpoint 类的 authorize 方法 */ @GetMapping("/authorize") @Operation(summary = "获得授权信息", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameter(name = "clientId", required = true, description = "客户端编号", example = "tudou") public CommonResult<OAuth2OpenAuthorizeInfoRespVO> authorize(@RequestParam("clientId") String clientId) { // 0. 校验用户已经登录。通过 Spring Security 实现 // 1. 获得 Client 客户端的信息 OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientId); // 2. 获得用户已经授权的信息 List<OAuth2ApproveDO> approves = oauth2ApproveService.getApproveList(getLoginUserId(), getUserType(), clientId); // 拼接返回 return success(OAuth2OpenConvert.INSTANCE.convert(client, approves)); } /** * 对应 Spring Security OAuth 的 AuthorizationEndpoint 类的 approveOrDeny 方法 * * 场景一:【自动授权 autoApprove = true】 * 刚进入 sso.vue 界面,调用该接口,用户历史已经给该应用做过对应的授权,或者 OAuth2Client 支持该 scope 的自动授权 * 场景二:【手动授权 autoApprove = false】 * 在 sso.vue 界面,用户选择好 scope 授权范围,调用该接口,进行授权。此时,approved 为 true 或者 false * * 因为前后端分离,Axios 无法很好的处理 302 重定向,所以和 Spring Security OAuth 略有不同,返回结果是重定向的 URL,剩余交给前端处理 */ @PostMapping("/authorize") @Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用") @Parameters({ @Parameter(name = "response_type", required = true, description = "响应类型", example = "code"), @Parameter(name = "client_id", required = true, description = "客户端编号", example = "tudou"), @Parameter(name = "scope", description = "授权范围", example = "userinfo.read"), // 使用 Map<String, Boolean> 格式,Spring MVC 暂时不支持这么接收参数 @Parameter(name = "redirect_uri", required = true, description = "重定向 URI", example = "https://www.iocoder.cn"), @Parameter(name = "auto_approve", required = true, description = "用户是否接受", example = "true"), @Parameter(name = "state", example = "1") }) @OperateLog(enable = false) // 避免 Post 请求被记录操作日志 public CommonResult<String> approveOrDeny(@RequestParam("response_type") String responseType, @RequestParam("client_id") String clientId, @RequestParam(value = "scope", required = false) String scope, @RequestParam("redirect_uri") String redirectUri, @RequestParam(value = "auto_approve") Boolean autoApprove, @RequestParam(value = "state", required = false) String state) { @SuppressWarnings("unchecked")
Map<String, Boolean> scopes = JsonUtils.parseObject(scope, Map.class);
3
2023-12-08 02:48:42+00:00
16k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/special/moveBotTile.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import static com.senetboom.game.SenetBoom.tileSize;
11,314
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end; private Coordinate startPx; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f;
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end; private Coordinate startPx; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f;
Tile[] gameBoard = Board.getBoard();
1
2023-12-05 22:19:00+00:00
16k
fabriciofx/cactoos-pdf
src/test/java/com/github/fabriciofx/cactoos/pdf/DocumentTest.java
[ { "identifier": "Contents", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/content/Contents.java", "snippet": "public final class Contents extends ListEnvelope<Content> implements Object {\n /**\n * Ctor.\n *\n * @param objects An array of objects\n */\n public Contents(f...
import com.github.fabriciofx.cactoos.pdf.content.Contents; import com.github.fabriciofx.cactoos.pdf.content.Image; import com.github.fabriciofx.cactoos.pdf.content.Text; import com.github.fabriciofx.cactoos.pdf.id.Serial; import com.github.fabriciofx.cactoos.pdf.image.format.Jpeg; import com.github.fabriciofx.cactoos.pdf.image.format.Png; import com.github.fabriciofx.cactoos.pdf.object.Catalog; import com.github.fabriciofx.cactoos.pdf.page.DefaultPage; import com.github.fabriciofx.cactoos.pdf.page.Format; import com.github.fabriciofx.cactoos.pdf.pages.DefaultPages; import com.github.fabriciofx.cactoos.pdf.resource.ProcSet; import com.github.fabriciofx.cactoos.pdf.resource.Resources; import com.github.fabriciofx.cactoos.pdf.resource.XObject; import com.github.fabriciofx.cactoos.pdf.resource.font.Courier; import com.github.fabriciofx.cactoos.pdf.resource.font.Helvetica; import com.github.fabriciofx.cactoos.pdf.resource.font.Symbol; import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman; import com.github.fabriciofx.cactoos.pdf.resource.font.ZapfDingbats; import java.io.File; import java.nio.file.Files; import org.cactoos.bytes.BytesOf; import org.cactoos.io.ResourceOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion;
12,723
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * 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 NON-INFRINGEMENT. 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.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16); final Font helvetica = new Helvetica(id, 16); final Font courier = new Courier(id, 16); final Font symbol = new Symbol(id, 16); final Font zapf = new ZapfDingbats(id, 16);
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * 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 NON-INFRINGEMENT. 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.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16); final Font helvetica = new Helvetica(id, 16); final Font courier = new Courier(id, 16); final Font symbol = new Symbol(id, 16); final Font zapf = new ZapfDingbats(id, 16);
final Image cat = new Image(
1
2023-12-05 00:07:24+00:00
16k
sinbad-navigator/erp-crm
erp/src/main/java/com/ec/erp/controller/ErpStockOrderController.java
[ { "identifier": "BaseController", "path": "common/src/main/java/com/ec/common/core/controller/BaseController.java", "snippet": "public class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBi...
import com.ec.common.annotation.Log; import com.ec.common.core.controller.BaseController; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.page.TableDataInfo; import com.ec.common.enums.BusinessType; import com.ec.common.utils.poi.ExcelUtil; import com.ec.erp.domain.ErpStockOrder; import com.ec.erp.service.IErpStockOrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List;
13,581
package com.ec.erp.controller; /** * 进货流水单Controller * * @author xxx * @date xxxx-xx-xx */ @RestController @RequestMapping("/erp/stock") public class ErpStockOrderController extends BaseController { @Autowired private IErpStockOrderService erpStockOrderService; /** * 查询进货流水单列表 */ @PreAuthorize("@ss.hasPermi('erp:stock:list')") @GetMapping("/list")
package com.ec.erp.controller; /** * 进货流水单Controller * * @author xxx * @date xxxx-xx-xx */ @RestController @RequestMapping("/erp/stock") public class ErpStockOrderController extends BaseController { @Autowired private IErpStockOrderService erpStockOrderService; /** * 查询进货流水单列表 */ @PreAuthorize("@ss.hasPermi('erp:stock:list')") @GetMapping("/list")
public TableDataInfo list(ErpStockOrder erpStockOrder) {
5
2023-12-07 14:23:12+00:00
16k
Crydsch/the-one
src/core/DTNHost.java
[ { "identifier": "ConnectivityGrid", "path": "src/interfaces/ConnectivityGrid.java", "snippet": "public class ConnectivityGrid extends ConnectivityOptimizer {\n\n\t/**\n\t * Cell based optimization cell size multiplier -setting id ({@value}).\n\t * Used in {@link World#OPTIMIZATION_SETTINGS_NS} name spac...
import java.util.ArrayList; import java.util.Collection; import java.util.List; import interfaces.ConnectivityGrid; import movement.MovementEngine; import movement.MovementModel; import movement.Path; import routing.MessageRouter; import routing.util.RoutingInfo; import static core.Constants.DEBUG;
13,144
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package core; /** * A DTN capable host. */ public class DTNHost implements Comparable<DTNHost> { private static int count = 0; private int ID; private Coord destination; // where is it going private MessageRouter router; private MovementEngine movementEngine; private MovementModel movementModel;
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package core; /** * A DTN capable host. */ public class DTNHost implements Comparable<DTNHost> { private static int count = 0; private int ID; private Coord destination; // where is it going private MessageRouter router; private MovementEngine movementEngine; private MovementModel movementModel;
private Path path;
3
2023-12-10 15:51:41+00:00
16k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java
[ { "identifier": "PRESS_WAIT", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/InputHandler.java", "snippet": "final static public int PRESS_WAIT = 100;" }, { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.jav...
import static com.seleuco.mame4droid.input.InputHandler.PRESS_WAIT; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.view.View; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.input.ControlCustomizer; import com.seleuco.mame4droid.views.IEmuView; import java.util.Arrays;
11,219
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13; protected MAME4droid mm = null; static protected String errorMsg; static protected String infoMsg; public void setErrorMsg(String errorMsg) { DialogHelper.errorMsg = errorMsg; } public void setInfoMsg(String infoMsg) { DialogHelper.infoMsg = infoMsg; } public DialogHelper(MAME4droid value) { mm = value; } public Dialog createDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(mm); switch (id) { case DIALOG_FINISH_CUSTOM_LAYOUT: builder.setMessage("Do you want to save changes?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT); ControlCustomizer.setEnabled(false); mm.getInputHandler().getControlCustomizer().saveDefinedControlLayout(); mm.getEmuView().setVisibility(View.VISIBLE); mm.getEmuView().requestFocus();
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13; protected MAME4droid mm = null; static protected String errorMsg; static protected String infoMsg; public void setErrorMsg(String errorMsg) { DialogHelper.errorMsg = errorMsg; } public void setInfoMsg(String infoMsg) { DialogHelper.infoMsg = infoMsg; } public DialogHelper(MAME4droid value) { mm = value; } public Dialog createDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(mm); switch (id) { case DIALOG_FINISH_CUSTOM_LAYOUT: builder.setMessage("Do you want to save changes?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT); ControlCustomizer.setEnabled(false); mm.getInputHandler().getControlCustomizer().saveDefinedControlLayout(); mm.getEmuView().setVisibility(View.VISIBLE); mm.getEmuView().requestFocus();
Emulator.resume();
1
2023-12-18 11:16:18+00:00
16k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/event/actions/player/data/ActionPlayerDataLoad.java
[ { "identifier": "DataHandler", "path": "generic/src/main/java/net/swofty/types/generic/data/DataHandler.java", "snippet": "public class DataHandler {\n public static Map<UUID, DataHandler> userCache = new HashMap<>();\n @Getter\n private UUID uuid;\n private final Map<String, Datapoint> data...
import com.mongodb.client.model.Filters; import lombok.SneakyThrows; import net.minestom.server.entity.Player; import net.minestom.server.event.Event; import net.minestom.server.event.player.PlayerLoginEvent; import net.swofty.types.generic.SkyBlockGenericLoader; import net.swofty.types.generic.data.DataHandler; import net.swofty.types.generic.data.datapoints.DatapointBoolean; import net.swofty.types.generic.data.datapoints.DatapointUUID; import net.swofty.types.generic.data.mongodb.CoopDatabase; import net.swofty.types.generic.data.mongodb.ProfilesDatabase; import net.swofty.types.generic.data.mongodb.UserDatabase; import net.swofty.types.generic.user.SkyBlockIsland; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.user.UserProfiles; import net.swofty.types.generic.event.EventException; import net.swofty.types.generic.event.EventNodes; import net.swofty.types.generic.event.EventParameters; import net.swofty.types.generic.event.SkyBlockEvent; import org.bson.Document; import org.tinylog.Logger; import java.util.ArrayList; import java.util.UUID;
11,879
package net.swofty.types.generic.event.actions.player.data; @EventParameters(description = "Load player data on join", node = EventNodes.PLAYER_DATA, requireDataLoaded = false) public class ActionPlayerDataLoad extends SkyBlockEvent implements EventException { @Override public Class<? extends Event> getEvent() { return PlayerLoginEvent.class; } @SneakyThrows @Override public void run(Event event) { PlayerLoginEvent playerLoginEvent = (PlayerLoginEvent) event; // Ensure we use player here final Player player = playerLoginEvent.getPlayer(); UUID playerUuid = player.getUuid(); UUID islandUUID; // Registers the users profiles within the profiles cache new UserDatabase(player.getUuid()).getProfiles(); UserProfiles profiles = ((SkyBlockPlayer) playerLoginEvent.getPlayer()).getProfiles(); UUID profileId = profiles.getCurrentlySelected(); if (profileId == null) { profileId = UUID.randomUUID(); islandUUID = profileId; profiles.setCurrentlySelected(profileId); profiles.addProfile(profileId); } else { profileId = profiles.getCurrentlySelected(); islandUUID = DataHandler.fromDocument(new ProfilesDatabase(profileId.toString()).getDocument()) .get(DataHandler.Data.ISLAND_UUID, DatapointUUID.class).getValue(); } SkyBlockIsland island; if (SkyBlockIsland.getIsland(islandUUID) == null) { island = new SkyBlockIsland(islandUUID, profileId); } else { // Island is already loaded, presumably from a coop island = SkyBlockIsland.getIsland(islandUUID); } ((SkyBlockPlayer) player).setSkyBlockIsland(island); ProfilesDatabase profilesDatabase = new ProfilesDatabase(profileId.toString()); DataHandler handler; if (profilesDatabase.exists()) { Document document = profilesDatabase.getDocument(); handler = DataHandler.fromDocument(document); } else { handler = DataHandler.initUserWithDefaultData(playerUuid); } DataHandler.userCache.put(playerUuid, handler); if (profiles.getProfiles().size() >= 2) { UUID finalProfileId1 = profileId; Document previousProfile = ProfilesDatabase.collection .find(Filters.eq("_owner", playerUuid.toString())).into(new ArrayList<>()) .stream().filter(document -> !document.get("_id").equals(finalProfileId1.toString())) .findFirst().get(); DataHandler previousHandler = DataHandler.fromDocument(previousProfile); previousHandler.getPersistentValues().forEach((key, value) -> { handler.getDatapoint(key).setValue(value); }); } if (handler.get(DataHandler.Data.IS_COOP, DatapointBoolean.class).getValue()) {
package net.swofty.types.generic.event.actions.player.data; @EventParameters(description = "Load player data on join", node = EventNodes.PLAYER_DATA, requireDataLoaded = false) public class ActionPlayerDataLoad extends SkyBlockEvent implements EventException { @Override public Class<? extends Event> getEvent() { return PlayerLoginEvent.class; } @SneakyThrows @Override public void run(Event event) { PlayerLoginEvent playerLoginEvent = (PlayerLoginEvent) event; // Ensure we use player here final Player player = playerLoginEvent.getPlayer(); UUID playerUuid = player.getUuid(); UUID islandUUID; // Registers the users profiles within the profiles cache new UserDatabase(player.getUuid()).getProfiles(); UserProfiles profiles = ((SkyBlockPlayer) playerLoginEvent.getPlayer()).getProfiles(); UUID profileId = profiles.getCurrentlySelected(); if (profileId == null) { profileId = UUID.randomUUID(); islandUUID = profileId; profiles.setCurrentlySelected(profileId); profiles.addProfile(profileId); } else { profileId = profiles.getCurrentlySelected(); islandUUID = DataHandler.fromDocument(new ProfilesDatabase(profileId.toString()).getDocument()) .get(DataHandler.Data.ISLAND_UUID, DatapointUUID.class).getValue(); } SkyBlockIsland island; if (SkyBlockIsland.getIsland(islandUUID) == null) { island = new SkyBlockIsland(islandUUID, profileId); } else { // Island is already loaded, presumably from a coop island = SkyBlockIsland.getIsland(islandUUID); } ((SkyBlockPlayer) player).setSkyBlockIsland(island); ProfilesDatabase profilesDatabase = new ProfilesDatabase(profileId.toString()); DataHandler handler; if (profilesDatabase.exists()) { Document document = profilesDatabase.getDocument(); handler = DataHandler.fromDocument(document); } else { handler = DataHandler.initUserWithDefaultData(playerUuid); } DataHandler.userCache.put(playerUuid, handler); if (profiles.getProfiles().size() >= 2) { UUID finalProfileId1 = profileId; Document previousProfile = ProfilesDatabase.collection .find(Filters.eq("_owner", playerUuid.toString())).into(new ArrayList<>()) .stream().filter(document -> !document.get("_id").equals(finalProfileId1.toString())) .findFirst().get(); DataHandler previousHandler = DataHandler.fromDocument(previousProfile); previousHandler.getPersistentValues().forEach((key, value) -> { handler.getDatapoint(key).setValue(value); }); } if (handler.get(DataHandler.Data.IS_COOP, DatapointBoolean.class).getValue()) {
CoopDatabase.Coop coop = CoopDatabase.getFromMember(playerUuid);
3
2023-12-14 09:51:15+00:00
16k
litongjava/next-jfinal
src/main/java/com/jfinal/core/ActionHandler.java
[ { "identifier": "Invocation", "path": "src/main/java/com/jfinal/aop/Invocation.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class Invocation {\n\n private static final Object[] NULL_ARGS = new Object[0]; // Prevent new Object[0] by jvm for args of method invoking\n\n private Action acti...
import java.util.function.BiFunction; import com.jfinal.aop.Invocation; import com.jfinal.config.Constants; import com.jfinal.core.paragetter.JsonRequest; import com.jfinal.handler.Handler; import com.jfinal.kit.ReflectKit; import com.jfinal.log.Log; import com.jfinal.render.Render; import com.jfinal.render.RenderException; import com.jfinal.render.RenderManager; import com.jfinal.servlet.http.HttpServletRequest; import com.jfinal.servlet.http.HttpServletResponse;
14,111
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.core; /** * ActionHandler */ public class ActionHandler extends Handler { protected boolean devMode; protected ActionMapping actionMapping; protected ControllerFactory controllerFactory; protected ActionReporter actionReporter; protected static final RenderManager renderManager = RenderManager.me(); private static final Log log = Log.getLog(ActionHandler.class); public static boolean resolveJson = false; // 默认 JsonRequestFactory private static BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory = (jsonString, req) -> { return new JsonRequest(jsonString, req); }; public static void setResolveJson(boolean resolveJson) { ActionHandler.resolveJson = resolveJson; } public static void setJsonRequestFactory(BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory) { ActionHandler.jsonRequestFactory = jsonRequestFactory; }
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.core; /** * ActionHandler */ public class ActionHandler extends Handler { protected boolean devMode; protected ActionMapping actionMapping; protected ControllerFactory controllerFactory; protected ActionReporter actionReporter; protected static final RenderManager renderManager = RenderManager.me(); private static final Log log = Log.getLog(ActionHandler.class); public static boolean resolveJson = false; // 默认 JsonRequestFactory private static BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory = (jsonString, req) -> { return new JsonRequest(jsonString, req); }; public static void setResolveJson(boolean resolveJson) { ActionHandler.resolveJson = resolveJson; } public static void setJsonRequestFactory(BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory) { ActionHandler.jsonRequestFactory = jsonRequestFactory; }
protected void init(ActionMapping actionMapping, Constants constants) {
1
2023-12-19 10:58:33+00:00
16k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/world/SecretAura.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import com.mojang.authlib.GameProfile; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockLever; import net.minecraft.block.BlockSkull; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiChest; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientChatReceivedEvent; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.PlayerInteractEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.FloatSetting; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.render.Render3DUtils; import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils;
13,004
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange") private FloatSetting clickRange = new FloatSetting(Float.valueOf(5.0f), Float.valueOf(0.0f), Float.valueOf(8.0f)); @Setting(name="ClickSlot") private IntegerSetting clickSlot = new IntegerSetting(0, 0, 8); @Setting(name="Chests")
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange") private FloatSetting clickRange = new FloatSetting(Float.valueOf(5.0f), Float.valueOf(0.0f), Float.valueOf(8.0f)); @Setting(name="ClickSlot") private IntegerSetting clickSlot = new IntegerSetting(0, 0, 8); @Setting(name="Chests")
private BooleanSetting chests = new BooleanSetting(true);
7
2023-12-21 16:22:25+00:00
16k
emtee40/ApkSignatureKill-pc
apksigner/src/main/java/com/android/apksig/internal/util/X509CertificateUtils.java
[ { "identifier": "Asn1BerParser", "path": "apksigner/src/main/java/com/android/apksig/internal/asn1/Asn1BerParser.java", "snippet": "public final class Asn1BerParser {\n private Asn1BerParser() {\n }\n\n /**\n * Returns the ASN.1 structure contained in the BER encoded input.\n *\n * ...
import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import android.util.Base64; import com.android.apksig.internal.asn1.Asn1BerParser; import com.android.apksig.internal.asn1.Asn1DecodingException; import com.android.apksig.internal.asn1.Asn1DerEncoder; import com.android.apksig.internal.asn1.Asn1EncodingException; import com.android.apksig.internal.x509.Certificate; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.security.cert.CertificateException;
13,451
/* * Copyright (C) 2020 Muntashir Al-Islam * Copyright (C) 2018 The Android Open Source Project * * 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.android.apksig.internal.util; /** * Provides methods to generate {@code X509Certificate}s from their encoded form. These methods * can be used to generate certificates that would be rejected by the Java {@code * CertificateFactory}. */ public class X509CertificateUtils { // The PEM certificate header and footer as specified in RFC 7468: // There is exactly one space character (SP) separating the "BEGIN" or // "END" from the label. There are exactly five hyphen-minus (also // known as dash) characters ("-") on both ends of the encapsulation // boundaries, no more, no less. public static final byte[] BEGIN_CERT_HEADER = "-----BEGIN CERTIFICATE-----".getBytes(); public static final byte[] END_CERT_FOOTER = "-----END CERTIFICATE-----".getBytes(); private static CertificateFactory sCertFactory = null; private static void buildCertFactory() { if (sCertFactory != null) { return; } try { sCertFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException("Failed to create X.509 CertificateFactory", e); } } /** * Generates an {@code X509Certificate} from the {@code InputStream}. * * @throws CertificateException if the {@code InputStream} cannot be decoded to a valid * certificate. */ public static X509Certificate generateCertificate(InputStream in) throws CertificateException { byte[] encodedForm; try { encodedForm = ByteStreams.toByteArray(in); } catch (IOException e) { throw new CertificateException("Failed to parse certificate", e); } return generateCertificate(encodedForm); } /** * Generates an {@code X509Certificate} from the encoded form. * * @throws CertificateException if the encodedForm cannot be decoded to a valid certificate. */ public static X509Certificate generateCertificate(byte[] encodedForm) throws CertificateException { if (sCertFactory == null) { buildCertFactory(); } return generateCertificate(encodedForm, sCertFactory); } /** * Generates an {@code X509Certificate} from the encoded form using the provided * {@code CertificateFactory}. * * @throws CertificateException if the encodedForm cannot be decoded to a valid certificate. */ public static X509Certificate generateCertificate(byte[] encodedForm, CertificateFactory certFactory) throws CertificateException { X509Certificate certificate; try { certificate = (X509Certificate) certFactory.generateCertificate( new ByteArrayInputStream(encodedForm)); return certificate; } catch (CertificateException e) { // This could be expected if the certificate is encoded using a BER encoding that does // not use the minimum number of bytes to represent the length of the contents; attempt // to decode the certificate using the BER parser and re-encode using the DER encoder // below. } try { // Some apps were previously signed with a BER encoded certificate that now results // in exceptions from the CertificateFactory generateCertificate(s) methods. Since // the original BER encoding of the certificate is used as the signature for these // apps that original encoding must be maintained when signing updated versions of // these apps and any new apps that may require capabilities guarded by the // signature. To maintain the same signature the BER parser can be used to parse // the certificate, then it can be re-encoded to its DER equivalent which is // accepted by the generateCertificate method. The positions in the ByteBuffer can // then be used with the GuaranteedEncodedFormX509Certificate object to ensure the // getEncoded method returns the original signature of the app. ByteBuffer encodedCertBuffer = getNextDEREncodedCertificateBlock( ByteBuffer.wrap(encodedForm)); int startingPos = encodedCertBuffer.position();
/* * Copyright (C) 2020 Muntashir Al-Islam * Copyright (C) 2018 The Android Open Source Project * * 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.android.apksig.internal.util; /** * Provides methods to generate {@code X509Certificate}s from their encoded form. These methods * can be used to generate certificates that would be rejected by the Java {@code * CertificateFactory}. */ public class X509CertificateUtils { // The PEM certificate header and footer as specified in RFC 7468: // There is exactly one space character (SP) separating the "BEGIN" or // "END" from the label. There are exactly five hyphen-minus (also // known as dash) characters ("-") on both ends of the encapsulation // boundaries, no more, no less. public static final byte[] BEGIN_CERT_HEADER = "-----BEGIN CERTIFICATE-----".getBytes(); public static final byte[] END_CERT_FOOTER = "-----END CERTIFICATE-----".getBytes(); private static CertificateFactory sCertFactory = null; private static void buildCertFactory() { if (sCertFactory != null) { return; } try { sCertFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new RuntimeException("Failed to create X.509 CertificateFactory", e); } } /** * Generates an {@code X509Certificate} from the {@code InputStream}. * * @throws CertificateException if the {@code InputStream} cannot be decoded to a valid * certificate. */ public static X509Certificate generateCertificate(InputStream in) throws CertificateException { byte[] encodedForm; try { encodedForm = ByteStreams.toByteArray(in); } catch (IOException e) { throw new CertificateException("Failed to parse certificate", e); } return generateCertificate(encodedForm); } /** * Generates an {@code X509Certificate} from the encoded form. * * @throws CertificateException if the encodedForm cannot be decoded to a valid certificate. */ public static X509Certificate generateCertificate(byte[] encodedForm) throws CertificateException { if (sCertFactory == null) { buildCertFactory(); } return generateCertificate(encodedForm, sCertFactory); } /** * Generates an {@code X509Certificate} from the encoded form using the provided * {@code CertificateFactory}. * * @throws CertificateException if the encodedForm cannot be decoded to a valid certificate. */ public static X509Certificate generateCertificate(byte[] encodedForm, CertificateFactory certFactory) throws CertificateException { X509Certificate certificate; try { certificate = (X509Certificate) certFactory.generateCertificate( new ByteArrayInputStream(encodedForm)); return certificate; } catch (CertificateException e) { // This could be expected if the certificate is encoded using a BER encoding that does // not use the minimum number of bytes to represent the length of the contents; attempt // to decode the certificate using the BER parser and re-encode using the DER encoder // below. } try { // Some apps were previously signed with a BER encoded certificate that now results // in exceptions from the CertificateFactory generateCertificate(s) methods. Since // the original BER encoding of the certificate is used as the signature for these // apps that original encoding must be maintained when signing updated versions of // these apps and any new apps that may require capabilities guarded by the // signature. To maintain the same signature the BER parser can be used to parse // the certificate, then it can be re-encoded to its DER equivalent which is // accepted by the generateCertificate method. The positions in the ByteBuffer can // then be used with the GuaranteedEncodedFormX509Certificate object to ensure the // getEncoded method returns the original signature of the app. ByteBuffer encodedCertBuffer = getNextDEREncodedCertificateBlock( ByteBuffer.wrap(encodedForm)); int startingPos = encodedCertBuffer.position();
Certificate reencodedCert = Asn1BerParser.parse(encodedCertBuffer, Certificate.class);
0
2023-12-16 11:11:16+00:00
16k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
13,141
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
19
2023-12-15 08:13:42+00:00
16k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/login/LoginActivity.java
[ { "identifier": "AuthConstants", "path": "play-services-basement/src/main/java/org/microg/gms/auth/AuthConstants.java", "snippet": "public class AuthConstants {\n public static final String DEFAULT_ACCOUNT = \"<<default account>>\";\n public static final String SCOPE_GET_ACCOUNT_ID = \"^^_account_...
import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.StringRes; import androidx.preference.PreferenceManager; import androidx.webkit.WebViewClientCompat; import com.google.android.gms.R; import org.json.JSONArray; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthRequest; import org.microg.gms.auth.AuthResponse; import org.microg.gms.checkin.CheckinManager; import org.microg.gms.checkin.LastCheckinInfo; import org.microg.gms.common.HttpFormClient; import org.microg.gms.common.Utils; import org.microg.gms.people.PeopleManager; import org.microg.gms.profile.Build; import org.microg.gms.profile.ProfileManager; import java.io.IOException; import java.security.MessageDigest; import java.util.Locale; import static android.accounts.AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE; import static android.accounts.AccountManager.VISIBILITY_USER_MANAGED_VISIBLE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; import static android.view.KeyEvent.KEYCODE_BACK; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static org.microg.gms.auth.AuthPrefs.isAuthVisible; import static org.microg.gms.checkin.CheckinPreferences.isSpoofingEnabled; import static org.microg.gms.checkin.CheckinPreferences.setSpoofingEnabled; import static org.microg.gms.common.Constants.GMS_PACKAGE_NAME; import static org.microg.gms.common.Constants.GMS_VERSION_CODE; import static org.microg.gms.common.Constants.GOOGLE_GMS_PACKAGE_NAME;
12,111
setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) { final AuthManager authManager = new AuthManager(this, account.name, GOOGLE_GMS_PACKAGE_NAME, "ac2dm"); authManager.setPermitted(true); new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service(authManager.getService()) .email(account.name) .token(AccountManager.get(this).getPassword(account)) .systemPartition(true) .hasPermission(true) .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { authManager.storeResponse(response); String accountId = PeopleManager.loadUserInfo(LoginActivity.this, account); if (!TextUtils.isEmpty(accountId)) accountManager.setUserData(account, "GoogleUserId", accountId); checkin(true); finish(); } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private boolean checkin(boolean force) { try {
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.login; public class LoginActivity extends AssistantActivity { public static final String TMPL_NEW_ACCOUNT = "new_account"; public static final String EXTRA_TMPL = "tmpl"; public static final String EXTRA_EMAIL = "email"; public static final String EXTRA_TOKEN = "masterToken"; public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; private static final String TAG = "GmsAuthLoginBrowser"; private static final String EMBEDDED_SETUP_URL = "https://accounts.google.com/EmbeddedSetup"; private static final String PROGRAMMATIC_AUTH_URL = "https://accounts.google.com/o/oauth2/programmatic_auth"; private static final String GOOGLE_SUITE_URL = "https://accounts.google.com/signin/continue"; private static final String MAGIC_USER_AGENT = " MinuteMaid"; private static final String COOKIE_OAUTH_TOKEN = "oauth_token"; private WebView webView; private String accountType; private AccountManager accountManager; private InputMethodManager inputMethodManager; private ViewGroup authContent; private int state = 0; @SuppressLint("AddJavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; accountManager = AccountManager.get(LoginActivity.this); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); webView = createWebView(this); webView.addJavascriptInterface(new JsBridge(), "mm"); authContent = (ViewGroup) findViewById(R.id.auth_content); ((ViewGroup) findViewById(R.id.auth_root)).addView(webView); webView.setWebViewClient(new WebViewClientCompat() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "pageFinished: " + view.getUrl()); Uri uri = Uri.parse(view.getUrl()); // Begin login. // Only required if client code does not invoke showView() via JSBridge if ("identifier".equals(uri.getFragment()) || uri.getPath().endsWith("/identifier")) runOnUiThread(() -> webView.setVisibility(VISIBLE)); // Normal login. if ("close".equals(uri.getFragment())) closeWeb(false); // Google Suite login. if (url.startsWith(GOOGLE_SUITE_URL)) closeWeb(false); // IDK when this is called. if (url.startsWith(PROGRAMMATIC_AUTH_URL)) closeWeb(true); } }); if (getIntent().hasExtra(EXTRA_TOKEN)) { if (getIntent().hasExtra(EXTRA_EMAIL)) { AccountManager accountManager = AccountManager.get(this); Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType); accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null); if (isAuthVisible(this) && SDK_INT >= 26) { accountManager.setAccountVisibility(account, PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, VISIBILITY_USER_MANAGED_VISIBLE); } retrieveGmsToken(account); } else { retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN)); } } else if (android.os.Build.VERSION.SDK_INT < 21) { init(); } else { setMessage(R.string.auth_before_connect); setSpoofButtonText(R.string.brand_spoof_button); setNextButtonText(R.string.auth_sign_in); } } @Override protected void onNextButtonClicked() { super.onNextButtonClicked(); state++; if (state == 1) { if (isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, false); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } @Override protected void onHuaweiButtonClicked() { super.onHuaweiButtonClicked(); state++; if (state == 1) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("pref_hide_launcher_icon", false).apply(); if (!isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, true); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } private void init() { setTitle(R.string.just_a_sec); setSpoofButtonText(null); setNextButtonText(null); View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false); authContent.removeAllViews(); authContent.addView(loading); setMessage(R.string.auth_connecting); CookieManager.getInstance().setAcceptCookie(true); if (SDK_INT >= LOLLIPOP) { CookieManager.getInstance().removeAllCookies(value -> start()); } else { //noinspection deprecation CookieManager.getInstance().removeAllCookie(); start(); } } private static WebView createWebView(Context context) { WebView webView = new WebView(context); if (SDK_INT < LOLLIPOP) { webView.setVisibility(VISIBLE); } else { webView.setVisibility(INVISIBLE); } webView.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); prepareWebViewSettings(context, webView.getSettings()); return webView; } @SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) { final AuthManager authManager = new AuthManager(this, account.name, GOOGLE_GMS_PACKAGE_NAME, "ac2dm"); authManager.setPermitted(true); new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service(authManager.getService()) .email(account.name) .token(AccountManager.get(this).getPassword(account)) .systemPartition(true) .hasPermission(true) .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { authManager.storeResponse(response); String accountId = PeopleManager.loadUserInfo(LoginActivity.this, account); if (!TextUtils.isEmpty(accountId)) accountManager.setUserData(account, "GoogleUserId", accountId); checkin(true); finish(); } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private boolean checkin(boolean force) { try {
CheckinManager.checkin(LoginActivity.this, force);
4
2023-12-17 16:14:53+00:00
16k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
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.bosch.BNO055IMU; import com.qualcomm.hardware.lynx.LynxModule; 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.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
11,169
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 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 BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); }
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 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 BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); }
if (RUN_USING_ENCODER) {
9
2023-12-15 16:57:19+00:00
16k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/HomePageController.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import com.jfoenix.controls.JFXTimePicker; import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.StopsEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.VoucherEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.CachedStopsService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.VoucherService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.Rimborso; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.ValoreVoucher; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.ricerca.Ricerca; import it.unipv.po.aioobe.trenissimo.view.*; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Group; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.StringConverter; import org.controlsfx.control.SearchableComboBox; import org.controlsfx.control.ToggleSwitch; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.ResourceBundle;
14,146
boxContent.setDisable(true); Task<Ricerca> task = new Task<>() { /** * Permette di effettuare la ricerca * @return Ritorna un oggetto Ricerca contenente i risultati della ricerca * @see Ricerca */ @Override public @NotNull Ricerca call() { int partenzaId = (scbBigliettoPartenza.getValue()).getStopId(); int destinazioneId = (scbBigliettoDestinazione.getValue()).getStopId(); LocalDateTime data = LocalDateTime.of(dtpBigliettoPartenza.getValue(), tmpBigliettoAndata.getValue()); Ricerca search = new Ricerca(partenzaId, destinazioneId, data); if (tgsBigliettoAR.isSelected()) { search.setAndataRitorno(true); search.setDataRitorno(LocalDateTime.of(dtpBigliettoRitorno.getValue(), tmpBigliettoRitorno.getValue())); } search.setNumAdulti((int) spnBigliettoAdulti.getValue()); search.setNumRagazzi((int) spnBigliettoRagazzi.getValue()); search.setNumBambini((int) spnBigliettoBambini.getValue()); search.setNumAnimali((int) spnBigliettoAnimali.getValue()); search.eseguiRicerca(); return search; } }; task.setOnSucceeded(e -> { boxLoading.setVisible(false); boxContent.setDisable(false); try { RicercaView.openScene((Ricerca) e.getSource().getValue(), boxContent.getScene().getWindow()); } catch (NoSuchElementException event) { setAlert("Viaggio inesistente!"); } }); new Thread(task).start(); } /** * Permette l'apertura della finestra d'acquisto del voucher, acquistoVoucher.fxml * * @see AcquistoVoucherView * @see it.unipv.po.aioobe.trenissimo.view.acquistoView */ @FXML protected void onVoucherCheckout() { if (cmbVoucherValore.getValue() == null) { setAlert("Impossibile effettuare il checkout. Scegliere il valore del voucher!"); return; } else AcquistoVoucherView.openScene(boxContent.getScene().getWindow(), cmbVoucherValore.getValue()); } /** * Permette l'apertura della finestra di login, login-view.fxml * * @throws IOException * @see Login * @see it.unipv.po.aioobe.trenissimo.view.login */ @FXML protected void onLogin() throws IOException { Login.open((boxContent).getScene().getWindow()); } /** * Permette di spostarsi nella sezione ricerca */ @FXML protected void onRicercaSelected() { tabPaneRicerca.setVisible(true); tabPaneRimborso.setVisible(false); txtRimborsoTitoloID.setText(""); lblRimborsoOK.setVisible(false); lblErroreRimborsoEmpty.setVisible(false); lblErroreRimborso.setVisible(false); txtRimborsoTitoloID.setStyle("-fx-border-color: #cccccc"); } /** * Permette di spostarsi nella sezione ricerca */ @FXML protected void onRimborsoSelected() { tabPaneRicerca.setVisible(false); tabPaneRimborso.setVisible(true); } /** * Gestisce il rimborso di un titolo di viaggio in base ai criteri Rimborso presenti i properties * * @throws Exception * @see #setAlert(String) * @see #onScaricaBigliettoPDF(VoucherEntity) * @see Rimborso * @see VoucherService * @see VoucherEntity * @see it.unipv.po.aioobe.trenissimo.properties */ @FXML protected void onRimborso() throws Exception { if (txtRimborsoTitoloID.getText().isEmpty()) { lblErroreRimborsoEmpty.setVisible(true); txtRimborsoTitoloID.setStyle("-fx-border-color: #d70000"); isIdBigliettoOK = false; } if (!(Rimborso.checkIdBiglietto(txtRimborsoTitoloID.getText()))) { lblErroreRimborso.setVisible(true); txtRimborsoTitoloID.setStyle("-fx-border-color: #d70000"); isIdBigliettoOK = false; } if (isIdBigliettoOK) { Rimborso r = new Rimborso(txtRimborsoTitoloID.getText()); VoucherService voucherService = new VoucherService();
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per homePage-view.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.homePage * @see javafx.fxml.Initializable */ public class HomePageController implements Initializable { @FXML private DatePicker dtpBigliettoPartenza; @FXML private ToggleSwitch tgsBigliettoAR; @FXML private VBox boxLoading; @FXML private VBox boxContent; @FXML private DatePicker dtpBigliettoRitorno; @FXML private JFXTimePicker tmpBigliettoRitorno; @FXML private JFXTimePicker tmpBigliettoAndata; @FXML private ComboBox<ValoreVoucher> cmbVoucherValore; @FXML private Label lblNumAdulti; @FXML private Label lblNumRagazzi; @FXML private Label lblNumBambini; @FXML private Label lblNumAnimali; @FXML private Spinner spnBigliettoAdulti; @FXML private Spinner spnBigliettoRagazzi; @FXML private Spinner spnBigliettoBambini; @FXML private Spinner spnBigliettoAnimali; @FXML private Group grpLoggedIn; @FXML private Group grpLoggedOut; @FXML private SearchableComboBox<StopsEntity> scbBigliettoPartenza; @FXML private SearchableComboBox<StopsEntity> scbBigliettoDestinazione; @FXML private TabPane tabPaneRicerca; @FXML private TabPane tabPaneRimborso; @FXML private TextField txtRimborsoTitoloID; @FXML private Label lblErroreRimborso; @FXML private Label lblErroreRimborsoEmpty; @FXML private Label lblRimborsoOK; @FXML private Button btnRichiestaRimborso; private TicketBuilder titoloViaggio; private boolean isIdBigliettoOK; /** * Permette di ricercare, in tempo reale, una stazione tra quelle esistenti * * @param scb componente searchable combo box * @see SearchableComboBox * @see StopsEntity * @see CachedStopsService * @see StringConverter */ protected void initScb(@NotNull SearchableComboBox scb) { var result = CachedStopsService.getInstance().findAll().stream().sorted(Comparator.comparing(StopsEntity::getStopName)).toList(); scb.setItems(FXCollections.observableArrayList(result)); scb.setConverter(new StringConverter<StopsEntity>() { @Override public String toString(StopsEntity user) { if (user == null) { return null; } else { return user.getStopName(); } } @Override public StopsEntity fromString(String id) { return null; } }); } /** * Mostra una finestra di dialogo contenente informazioni personalizzate * * @param contentText messaggio da stampare nell'alert * @see Alert * @see Stage */ private void setAlert(String contentText) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Trenissimo"); alert.setHeaderText(null); alert.setContentText(contentText); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image(Objects.requireNonNull(HomePage.class.getResourceAsStream("HomePage/LogoIcona.png")))); alert.showAndWait(); } /** * Metodo d'Inizializzazione * * @param url * @param resourceBundle * @see #onRicercaSelected() * @see #onAccountChange() * @see #checkIdRealTime() * @see Account */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { spnBigliettoAdulti.valueProperty().addListener((obs, oldV, newV) -> { lblNumAdulti.setText(newV.toString()); }); spnBigliettoRagazzi.valueProperty().addListener((obs, oldV, newV) -> { lblNumRagazzi.setText(newV.toString()); }); spnBigliettoBambini.valueProperty().addListener((obs, oldV, newV) -> { lblNumBambini.setText(newV.toString()); }); spnBigliettoAnimali.valueProperty().addListener((obs, oldV, newV) -> { lblNumAnimali.setText(newV.toString()); }); tmpBigliettoAndata.set24HourView(true); tmpBigliettoRitorno.set24HourView(true); dtpBigliettoPartenza.setValue(LocalDate.now()); tmpBigliettoAndata.setValue(LocalTime.now()); initScb(scbBigliettoPartenza); initScb(scbBigliettoDestinazione); cmbVoucherValore.setItems(FXCollections.observableArrayList(ValoreVoucher.values())); tgsBigliettoAR.selectedProperty().addListener((obs, oldVal, newVal) -> { dtpBigliettoRitorno.setDisable(!newVal); tmpBigliettoRitorno.setDisable(!newVal); }); Account.loggedInProperty.addListener((obs, old, newV) -> onAccountChange()); onAccountChange(); onRicercaSelected(); checkIdRealTime(); } /** * Cambio gli elementi visibili in base al tipo di cliente, ospite o utente loggato */ private void onAccountChange() { grpLoggedIn.setManaged(Account.getLoggedIn()); grpLoggedIn.setVisible(Account.getLoggedIn()); grpLoggedOut.setManaged(!Account.getLoggedIn()); grpLoggedOut.setVisible(!Account.getLoggedIn()); } /** * Permette l'aperture della finestra di registrazione, registrazione-view.fxml * * @throws IOException * @see Registrazione * @see it.unipv.po.aioobe.trenissimo.view.registrazione */ @FXML protected void onSignup() throws IOException { Registrazione.open(boxContent.getScene().getWindow()); } /** * Permette di effettuare il logout * * @see Account */ @FXML protected void onLogout() { Account.getInstance().logout(); } /** * Permette l'apertura della finestra delle impostazioni, accountSettings-view.fxml * * @see AccountSettingsController * @see it.unipv.po.aioobe.trenissimo.view.accountSettingsView */ @FXML protected void onAccountSettings() { AccountSettings.openScene(boxContent.getScene().getWindow()); } /** * Permette di ricercare i viaggi disponibili e di mostrarli aprendo ricercaView.fxml * * @see #setAlert(String) * @see Ricerca * @see RicercaView * @see it.unipv.po.aioobe.trenissimo.view.ricercaView */ @FXML protected void onRicerca() { if (scbBigliettoPartenza.getValue() == null || scbBigliettoDestinazione.getValue() == null || scbBigliettoDestinazione.getValue() == scbBigliettoPartenza.getValue()) { setAlert("Selezionare stazione di partenza e/o destinazione validi!"); return; } else if (dtpBigliettoPartenza.getValue() == null || tmpBigliettoAndata.getValue() == null || (tgsBigliettoAR.isSelected() && dtpBigliettoRitorno.getValue() == null) || (tgsBigliettoAR.isSelected() && tmpBigliettoRitorno.getValue() == null) || (dtpBigliettoPartenza.getValue().isBefore(LocalDate.now())) || (tmpBigliettoAndata.getValue().isBefore(LocalTime.now().truncatedTo(ChronoUnit.HOURS)) && dtpBigliettoPartenza.getValue().equals(LocalDate.now())) || (tgsBigliettoAR.isSelected() && dtpBigliettoRitorno.getValue().isBefore(LocalDate.now())) || (tgsBigliettoAR.isSelected() && tmpBigliettoRitorno.getValue().isBefore(LocalTime.now().truncatedTo(ChronoUnit.HOURS)) && dtpBigliettoRitorno.getValue().equals(LocalDate.now())) || (tgsBigliettoAR.isSelected() && dtpBigliettoRitorno.getValue().isBefore(dtpBigliettoPartenza.getValue())) || (tgsBigliettoAR.isSelected() && tmpBigliettoRitorno.getValue().isBefore(tmpBigliettoAndata.getValue()) && dtpBigliettoRitorno.getValue().equals(dtpBigliettoPartenza.getValue()))){ setAlert("Inserire data e/o orario di partenza e/o ritorno validi!"); return; } else if ((int)spnBigliettoAdulti.getValue() == 0 && (int)spnBigliettoRagazzi.getValue() == 0 && (int)spnBigliettoBambini.getValue() == 0 && (int)spnBigliettoAnimali.getValue() == 0) { setAlert("Inserire almeno un passeggero!"); return; } boxLoading.setVisible(true); boxContent.setDisable(true); Task<Ricerca> task = new Task<>() { /** * Permette di effettuare la ricerca * @return Ritorna un oggetto Ricerca contenente i risultati della ricerca * @see Ricerca */ @Override public @NotNull Ricerca call() { int partenzaId = (scbBigliettoPartenza.getValue()).getStopId(); int destinazioneId = (scbBigliettoDestinazione.getValue()).getStopId(); LocalDateTime data = LocalDateTime.of(dtpBigliettoPartenza.getValue(), tmpBigliettoAndata.getValue()); Ricerca search = new Ricerca(partenzaId, destinazioneId, data); if (tgsBigliettoAR.isSelected()) { search.setAndataRitorno(true); search.setDataRitorno(LocalDateTime.of(dtpBigliettoRitorno.getValue(), tmpBigliettoRitorno.getValue())); } search.setNumAdulti((int) spnBigliettoAdulti.getValue()); search.setNumRagazzi((int) spnBigliettoRagazzi.getValue()); search.setNumBambini((int) spnBigliettoBambini.getValue()); search.setNumAnimali((int) spnBigliettoAnimali.getValue()); search.eseguiRicerca(); return search; } }; task.setOnSucceeded(e -> { boxLoading.setVisible(false); boxContent.setDisable(false); try { RicercaView.openScene((Ricerca) e.getSource().getValue(), boxContent.getScene().getWindow()); } catch (NoSuchElementException event) { setAlert("Viaggio inesistente!"); } }); new Thread(task).start(); } /** * Permette l'apertura della finestra d'acquisto del voucher, acquistoVoucher.fxml * * @see AcquistoVoucherView * @see it.unipv.po.aioobe.trenissimo.view.acquistoView */ @FXML protected void onVoucherCheckout() { if (cmbVoucherValore.getValue() == null) { setAlert("Impossibile effettuare il checkout. Scegliere il valore del voucher!"); return; } else AcquistoVoucherView.openScene(boxContent.getScene().getWindow(), cmbVoucherValore.getValue()); } /** * Permette l'apertura della finestra di login, login-view.fxml * * @throws IOException * @see Login * @see it.unipv.po.aioobe.trenissimo.view.login */ @FXML protected void onLogin() throws IOException { Login.open((boxContent).getScene().getWindow()); } /** * Permette di spostarsi nella sezione ricerca */ @FXML protected void onRicercaSelected() { tabPaneRicerca.setVisible(true); tabPaneRimborso.setVisible(false); txtRimborsoTitoloID.setText(""); lblRimborsoOK.setVisible(false); lblErroreRimborsoEmpty.setVisible(false); lblErroreRimborso.setVisible(false); txtRimborsoTitoloID.setStyle("-fx-border-color: #cccccc"); } /** * Permette di spostarsi nella sezione ricerca */ @FXML protected void onRimborsoSelected() { tabPaneRicerca.setVisible(false); tabPaneRimborso.setVisible(true); } /** * Gestisce il rimborso di un titolo di viaggio in base ai criteri Rimborso presenti i properties * * @throws Exception * @see #setAlert(String) * @see #onScaricaBigliettoPDF(VoucherEntity) * @see Rimborso * @see VoucherService * @see VoucherEntity * @see it.unipv.po.aioobe.trenissimo.properties */ @FXML protected void onRimborso() throws Exception { if (txtRimborsoTitoloID.getText().isEmpty()) { lblErroreRimborsoEmpty.setVisible(true); txtRimborsoTitoloID.setStyle("-fx-border-color: #d70000"); isIdBigliettoOK = false; } if (!(Rimborso.checkIdBiglietto(txtRimborsoTitoloID.getText()))) { lblErroreRimborso.setVisible(true); txtRimborsoTitoloID.setStyle("-fx-border-color: #d70000"); isIdBigliettoOK = false; } if (isIdBigliettoOK) { Rimborso r = new Rimborso(txtRimborsoTitoloID.getText()); VoucherService voucherService = new VoucherService();
VoucherEntity v = r.getRimborso();
2
2023-12-21 10:41:11+00:00
16k
pan2013e/ppt4j
framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java
[ { "identifier": "DatabaseType", "path": "framework/src/main/java/ppt4j/database/DatabaseType.java", "snippet": "public enum DatabaseType {\n\n PREPATCH, POSTPATCH;\n\n @Property(\"ppt4j.database.prepatch.name\")\n private static String PREPATCH_DIR;\n\n @Property(\"ppt4j.database.postpatch.n...
import ppt4j.annotation.MethodProfiler; import ppt4j.annotation.Property; import ppt4j.database.DatabaseType; import ppt4j.database.Vulnerability; import ppt4j.diff.BlockDiff; import ppt4j.diff.DiffParser; import ppt4j.diff.FileDiff; import ppt4j.factory.DatabaseFactory; import ppt4j.factory.ExtractorFactory; import ppt4j.feature.FeatureMatcher; import ppt4j.feature.Features; import ppt4j.feature.java.JavaExtractor; import ppt4j.feature.java.JavaFeatures; import ppt4j.util.StringUtils; import lombok.extern.log4j.Log4j; import java.io.IOException; import java.util.*;
13,586
package ppt4j.analysis.patch; @Log4j public class PatchAnalyzer { @Property("ppt4j.analysis.patch.presence_threshold") private static double PATCH_PRESENCE_THRESHOLD; @Property("ppt4j.features.similarity.threshold") private static double SIM_THRESHOLD; @Property("ppt4j.features.similarity.algorithm") private static String SIM_ALGORITHM; private final DiffParser diffParser; private final ExtractorFactory factory; private final Vulnerability cve; private final List<String> filterMatch = new ArrayList<>(); private final List<String> filterNotMatch = new ArrayList<>(); private int total = 0, found = 0; private final Set<Integer> preUsedLines = new HashSet<>(); private final Set<Integer> postUsedLines = new HashSet<>(); public PatchAnalyzer(Vulnerability cve, ExtractorFactory factory) throws IOException { this.cve = cve; this.diffParser = new DiffParser(cve.getDiffUrl()); this.factory = factory; this.filterIfMatch(cve.getRequiredFilePatterns()) .filterIfNotMatch(cve.getIgnoredFilePatterns()); } public PatchAnalyzer(Vulnerability cve, DatabaseType type) throws IOException { this(cve, ExtractorFactory.get(cve, type)); log.info("Ground truth binary type in dataset: " + type); } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfMatch(String... patterns) { filterMatch.addAll(Arrays.asList(patterns)); return this; } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfNotMatch(String... patterns) { filterNotMatch.addAll(Arrays.asList(patterns)); return this; } @MethodProfiler public boolean analyze() throws IOException { log.info(String.format("Analyzing patch for %s, " + "CVE ID: %s, Database ID: %d", cve.getProjectName(), cve.getCVEId(), cve.getDatabaseId())); total = 0; found = 0; for(int i = 0;i < diffParser.getNumOfDiffs();i++) { String fileName = diffParser.getFileName(i, true); if(filterNotMatch.stream().anyMatch(fileName::matches)) { continue; } if(!filterMatch.stream().allMatch(fileName::matches)) { continue; } if(!fileName.startsWith(cve.getJavaSrcTopLevelDir())) { continue; } String className = StringUtils.extractClassName( fileName, cve.getJavaSrcTopLevelDir() ); FileDiff fileDiff = diffParser.getFileDiff(i);
package ppt4j.analysis.patch; @Log4j public class PatchAnalyzer { @Property("ppt4j.analysis.patch.presence_threshold") private static double PATCH_PRESENCE_THRESHOLD; @Property("ppt4j.features.similarity.threshold") private static double SIM_THRESHOLD; @Property("ppt4j.features.similarity.algorithm") private static String SIM_ALGORITHM; private final DiffParser diffParser; private final ExtractorFactory factory; private final Vulnerability cve; private final List<String> filterMatch = new ArrayList<>(); private final List<String> filterNotMatch = new ArrayList<>(); private int total = 0, found = 0; private final Set<Integer> preUsedLines = new HashSet<>(); private final Set<Integer> postUsedLines = new HashSet<>(); public PatchAnalyzer(Vulnerability cve, ExtractorFactory factory) throws IOException { this.cve = cve; this.diffParser = new DiffParser(cve.getDiffUrl()); this.factory = factory; this.filterIfMatch(cve.getRequiredFilePatterns()) .filterIfNotMatch(cve.getIgnoredFilePatterns()); } public PatchAnalyzer(Vulnerability cve, DatabaseType type) throws IOException { this(cve, ExtractorFactory.get(cve, type)); log.info("Ground truth binary type in dataset: " + type); } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfMatch(String... patterns) { filterMatch.addAll(Arrays.asList(patterns)); return this; } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfNotMatch(String... patterns) { filterNotMatch.addAll(Arrays.asList(patterns)); return this; } @MethodProfiler public boolean analyze() throws IOException { log.info(String.format("Analyzing patch for %s, " + "CVE ID: %s, Database ID: %d", cve.getProjectName(), cve.getCVEId(), cve.getDatabaseId())); total = 0; found = 0; for(int i = 0;i < diffParser.getNumOfDiffs();i++) { String fileName = diffParser.getFileName(i, true); if(filterNotMatch.stream().anyMatch(fileName::matches)) { continue; } if(!filterMatch.stream().allMatch(fileName::matches)) { continue; } if(!fileName.startsWith(cve.getJavaSrcTopLevelDir())) { continue; } String className = StringUtils.extractClassName( fileName, cve.getJavaSrcTopLevelDir() ); FileDiff fileDiff = diffParser.getFileDiff(i);
for (BlockDiff block : fileDiff.getBlocks()) {
2
2023-12-14 15:33:50+00:00
16k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/entity/ThrowableStunGrenadeEntity.java
[ { "identifier": "Config", "path": "src/main/java/com/mrcrayfish/guns/Config.java", "snippet": "public class Config\n{\n /**\n * Client related config options\n */\n public static class Client\n {\n public final Sounds sounds;\n public final Display display;\n public...
import com.mrcrayfish.framework.api.network.LevelLocation; import com.mrcrayfish.guns.Config; import com.mrcrayfish.guns.Config.EffectCriteria; import com.mrcrayfish.guns.init.ModEffects; import com.mrcrayfish.guns.init.ModEntities; import com.mrcrayfish.guns.init.ModItems; import com.mrcrayfish.guns.init.ModSounds; import com.mrcrayfish.guns.network.PacketHandler; import com.mrcrayfish.guns.network.message.S2CMessageStunGrenade; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.Shapes; import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.network.PacketDistributor; import javax.annotation.Nullable;
11,872
package com.mrcrayfish.guns.entity; @Mod.EventBusSubscriber public class ThrowableStunGrenadeEntity extends ThrowableGrenadeEntity { public ThrowableStunGrenadeEntity(EntityType<? extends ThrowableGrenadeEntity> entityType, Level world) { super(entityType, world); } public ThrowableStunGrenadeEntity(EntityType<? extends ThrowableGrenadeEntity> entityType, Level world, LivingEntity player) { super(entityType, world, player); this.setItem(new ItemStack(ModItems.STUN_GRENADE.get())); } public ThrowableStunGrenadeEntity(Level world, LivingEntity player, int maxCookTime) { super(ModEntities.THROWABLE_STUN_GRENADE.get(), world, player); this.setItem(new ItemStack(ModItems.STUN_GRENADE.get())); this.setMaxLife(maxCookTime); } @SubscribeEvent public static void blindMobs(LivingSetAttackTargetEvent event) { if(Config.COMMON.stunGrenades.blind.blindMobs.get() && event.getTarget() != null && event.getEntity() instanceof Mob && event.getEntity().hasEffect(ModEffects.BLINDED.get())) { ((Mob) event.getEntity()).setTarget(null); } } @Override public void onDeath() { double y = this.getY() + this.getType().getDimensions().height * 0.5; this.level.playSound(null, this.getX(), y, this.getZ(), ModSounds.ENTITY_STUN_GRENADE_EXPLOSION.get(), SoundSource.BLOCKS, 4, (1 + (level.random.nextFloat() - level.random.nextFloat()) * 0.2F) * 0.7F); if(this.level.isClientSide) { return; } PacketHandler.getPlayChannel().sendToNearbyPlayers(() -> LevelLocation.create(this.level, this.getX(), y, this.getZ(), 64), new S2CMessageStunGrenade(this.getX(), y, this.getZ())); // Calculate bounds of area where potentially effected players my be double diameter = Math.max(Config.COMMON.stunGrenades.deafen.criteria.radius.get(), Config.COMMON.stunGrenades.blind.criteria.radius.get()) * 2 + 1; int minX = Mth.floor(this.getX() - diameter); int maxX = Mth.floor(this.getX() + diameter); int minY = Mth.floor(y - diameter); int maxY = Mth.floor(y + diameter); int minZ = Mth.floor(this.getZ() - diameter); int maxZ = Mth.floor(this.getZ() + diameter); // Affect all non-spectating players in range of the blast Vec3 grenade = new Vec3(this.getX(), y, this.getZ()); Vec3 eyes, directionGrenade; double distance; for(LivingEntity entity : this.level.getEntitiesOfClass(LivingEntity.class, new AABB(minX, minY, minZ, maxX, maxY, maxZ))) { if(entity.ignoreExplosion()) continue; eyes = entity.getEyePosition(1.0F); directionGrenade = grenade.subtract(eyes); distance = directionGrenade.length(); // Calculate angle between eye-gaze line and eye-grenade line double angle = Math.toDegrees(Math.acos(entity.getViewVector(1.0F).dot(directionGrenade.normalize()))); // Apply effects as determined by their criteria if(this.calculateAndApplyEffect(ModEffects.DEAFENED.get(), Config.COMMON.stunGrenades.deafen.criteria, entity, grenade, eyes, distance, angle) && Config.COMMON.stunGrenades.deafen.panicMobs.get()) { entity.setLastHurtByMob(entity); } if(this.calculateAndApplyEffect(ModEffects.BLINDED.get(), Config.COMMON.stunGrenades.blind.criteria, entity, grenade, eyes, distance, angle) && Config.COMMON.stunGrenades.blind.blindMobs.get() && entity instanceof Mob) { ((Mob) entity).setTarget(null); } } }
package com.mrcrayfish.guns.entity; @Mod.EventBusSubscriber public class ThrowableStunGrenadeEntity extends ThrowableGrenadeEntity { public ThrowableStunGrenadeEntity(EntityType<? extends ThrowableGrenadeEntity> entityType, Level world) { super(entityType, world); } public ThrowableStunGrenadeEntity(EntityType<? extends ThrowableGrenadeEntity> entityType, Level world, LivingEntity player) { super(entityType, world, player); this.setItem(new ItemStack(ModItems.STUN_GRENADE.get())); } public ThrowableStunGrenadeEntity(Level world, LivingEntity player, int maxCookTime) { super(ModEntities.THROWABLE_STUN_GRENADE.get(), world, player); this.setItem(new ItemStack(ModItems.STUN_GRENADE.get())); this.setMaxLife(maxCookTime); } @SubscribeEvent public static void blindMobs(LivingSetAttackTargetEvent event) { if(Config.COMMON.stunGrenades.blind.blindMobs.get() && event.getTarget() != null && event.getEntity() instanceof Mob && event.getEntity().hasEffect(ModEffects.BLINDED.get())) { ((Mob) event.getEntity()).setTarget(null); } } @Override public void onDeath() { double y = this.getY() + this.getType().getDimensions().height * 0.5; this.level.playSound(null, this.getX(), y, this.getZ(), ModSounds.ENTITY_STUN_GRENADE_EXPLOSION.get(), SoundSource.BLOCKS, 4, (1 + (level.random.nextFloat() - level.random.nextFloat()) * 0.2F) * 0.7F); if(this.level.isClientSide) { return; } PacketHandler.getPlayChannel().sendToNearbyPlayers(() -> LevelLocation.create(this.level, this.getX(), y, this.getZ(), 64), new S2CMessageStunGrenade(this.getX(), y, this.getZ())); // Calculate bounds of area where potentially effected players my be double diameter = Math.max(Config.COMMON.stunGrenades.deafen.criteria.radius.get(), Config.COMMON.stunGrenades.blind.criteria.radius.get()) * 2 + 1; int minX = Mth.floor(this.getX() - diameter); int maxX = Mth.floor(this.getX() + diameter); int minY = Mth.floor(y - diameter); int maxY = Mth.floor(y + diameter); int minZ = Mth.floor(this.getZ() - diameter); int maxZ = Mth.floor(this.getZ() + diameter); // Affect all non-spectating players in range of the blast Vec3 grenade = new Vec3(this.getX(), y, this.getZ()); Vec3 eyes, directionGrenade; double distance; for(LivingEntity entity : this.level.getEntitiesOfClass(LivingEntity.class, new AABB(minX, minY, minZ, maxX, maxY, maxZ))) { if(entity.ignoreExplosion()) continue; eyes = entity.getEyePosition(1.0F); directionGrenade = grenade.subtract(eyes); distance = directionGrenade.length(); // Calculate angle between eye-gaze line and eye-grenade line double angle = Math.toDegrees(Math.acos(entity.getViewVector(1.0F).dot(directionGrenade.normalize()))); // Apply effects as determined by their criteria if(this.calculateAndApplyEffect(ModEffects.DEAFENED.get(), Config.COMMON.stunGrenades.deafen.criteria, entity, grenade, eyes, distance, angle) && Config.COMMON.stunGrenades.deafen.panicMobs.get()) { entity.setLastHurtByMob(entity); } if(this.calculateAndApplyEffect(ModEffects.BLINDED.get(), Config.COMMON.stunGrenades.blind.criteria, entity, grenade, eyes, distance, angle) && Config.COMMON.stunGrenades.blind.blindMobs.get() && entity instanceof Mob) { ((Mob) entity).setTarget(null); } } }
private boolean calculateAndApplyEffect(MobEffect effect, EffectCriteria criteria, LivingEntity entity, Vec3 grenade, Vec3 eyes, double distance, double angle)
1
2023-12-18 15:04:35+00:00
16k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/MainController.java
[ { "identifier": "SaveOptionCallback", "path": "src/main/java/org/fofaviewer/callback/SaveOptionCallback.java", "snippet": "public interface SaveOptionCallback{\n default void setProjectName(String name){}\n default String getProjectName(){\n return null;\n }\n}" }, { "identifier"...
import java.io.BufferedReader; import java.io.File; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.FileChooser; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javafx.scene.control.Alert; import javafx.scene.control.Tab; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.DirectoryChooser; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ProgressBar; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.StageStyle; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.text.Font; import org.controlsfx.control.StatusBar; import org.controlsfx.dialog.CommandLinksDialog; import org.controlsfx.dialog.ProgressDialog; import org.fofaviewer.bean.*; import org.fofaviewer.callback.SaveOptionCallback; import org.fofaviewer.controls.*; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.request.Request; import org.fofaviewer.callback.RequestCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.controlsfx.control.textfield.TextFields; import org.fofaviewer.utils.ResourceBundleUtil; import java.awt.*; import java.io.*; import java.math.BigInteger; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger;
11,016
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField; private static final RequestUtil helper = RequestUtil.getInstance();
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField; private static final RequestUtil helper = RequestUtil.getInstance();
private FofaConfig client;
1
2023-10-25 11:13:47+00:00
16k
Changbaiqi/yatori
yatori-console/src/main/java/com/cbq/yatori/console/run/Launch.java
[ { "identifier": "LoginResponseRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java", "snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n...
import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourse; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourseData; import com.cbq.yatori.core.action.enaea.entity.LoginAblesky; import com.cbq.yatori.core.action.enaea.entity.underwayproject.ResultList; import com.cbq.yatori.core.action.enaea.entity.underwayproject.UnderwayProjectRquest; import com.cbq.yatori.core.action.yinghua.CourseAction; import com.cbq.yatori.core.action.yinghua.CourseStudyAction; import com.cbq.yatori.core.action.yinghua.LoginAction; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseInform; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseRequest; import com.cbq.yatori.core.entity.*; import com.cbq.yatori.core.utils.ConfigUtils; import com.cbq.yatori.core.utils.FileUtils; import com.cbq.yatori.core.utils.VerificationCodeUtil; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask;
11,024
}).start(); } //仓辉 case CANGHUI -> { AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui(); user.setCache(accountCacheCangHui); //refresh_code:1代表密码错误, LoginResponseRequest result=null; do { //获取SESSION String session = null; while ((session = com.cbq.yatori.core.action.canghui.LoginAction.getSESSION(user)) == null) ; accountCacheCangHui.setSession(session); //获取验证码 File code = null; while ((code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user)) == null) ; accountCacheCangHui.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user)) == null) ; } while (result.getCode()==-1002); //对结果进行判定 if (result.getCode()==0) { accountCacheCangHui.setToken(result.getData().getToken()); accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), result.getMsg()); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = com.cbq.yatori.core.action.canghui.LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("成功")) { accountCacheCangHui.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } }
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件 config = ConfigUtils.loadingConfig(); } public void toRun() { //获取账号列表----------------------------- List<User> users = config.getUsers(); //先进行登录---------------------------------------------- for (User user : users) { switch (user.getAccountType()) { //英华,创能 case YINGHUA -> { AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua(); user.setCache(accountCacheYingHua); //refresh_code:1代表密码错误, Map<String, Object> result = null; do { //获取SESSION String session = null; while ((session = LoginAction.getSESSION(user)) == null) ; accountCacheYingHua.setSession(session); //获取验证码 File code = null; while ((code = LoginAction.getCode(user)) == null) ; accountCacheYingHua.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = LoginAction.toLogin(user)) == null) ; } while (!(Boolean) result.get("status") && ((String) result.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) result.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) result.get("msg"))); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("更新成功")) { accountCacheYingHua.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheYingHua.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 Map<String, Object> map; do { //获取验证码 File code = LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 map = LoginAction.toLogin(user); } while (!(Boolean) map.get("status") && ((String) map.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) map.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) map.get("msg"))); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //仓辉 case CANGHUI -> { AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui(); user.setCache(accountCacheCangHui); //refresh_code:1代表密码错误, LoginResponseRequest result=null; do { //获取SESSION String session = null; while ((session = com.cbq.yatori.core.action.canghui.LoginAction.getSESSION(user)) == null) ; accountCacheCangHui.setSession(session); //获取验证码 File code = null; while ((code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user)) == null) ; accountCacheCangHui.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user)) == null) ; } while (result.getCode()==-1002); //对结果进行判定 if (result.getCode()==0) { accountCacheCangHui.setToken(result.getData().getToken()); accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), result.getMsg()); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = com.cbq.yatori.core.action.canghui.LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("成功")) { accountCacheCangHui.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } }
CourseStudyAction bulild = CourseStudyAction.builder()
7
2023-10-30 04:15:41+00:00
16k
sgware/sabre
src/edu/uky/cs/nil/sabre/hg/NominalFluentNode.java
[ { "identifier": "Fluent", "path": "src/edu/uky/cs/nil/sabre/Fluent.java", "snippet": "public class Fluent implements Expression, Signed {\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * An ordered list of {@link Character characters} o...
import java.util.Arrays; import java.util.Iterator; import edu.uky.cs.nil.sabre.Fluent; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.logic.Comparison; import edu.uky.cs.nil.sabre.logic.Comparison.Operator; import edu.uky.cs.nil.sabre.logic.Precondition; import edu.uky.cs.nil.sabre.logic.Value; import edu.uky.cs.nil.sabre.util.ArrayIterator;
13,593
package edu.uky.cs.nil.sabre.hg; /** * A {@link FluentNode fluent node} representing a {@link * edu.uky.cs.nil.sabre.logic.Expression#mustNotBeNumber() non-numeric} {@link * Fluent fluent}, which is any fluent that has a discrete, finite set of * possible values. * * @author Stephen G. Ware */ public class NominalFluentNode extends FluentNode { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * An array of {@link #getGroup(Value) value groups}, indexed by the hash * code of the group's value */ protected final List<PreconditionNode>[] groups; /** * Constructs a new fluent node that belongs to a given graph and * represents a given nominal fluent. * * @param graph the graph this node belongs to * @param label the nominal fluent this node represents * @throws edu.uky.cs.nil.sabre.FormatException if the fluent is numeric */ @SuppressWarnings("unchecked")
package edu.uky.cs.nil.sabre.hg; /** * A {@link FluentNode fluent node} representing a {@link * edu.uky.cs.nil.sabre.logic.Expression#mustNotBeNumber() non-numeric} {@link * Fluent fluent}, which is any fluent that has a discrete, finite set of * possible values. * * @author Stephen G. Ware */ public class NominalFluentNode extends FluentNode { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * An array of {@link #getGroup(Value) value groups}, indexed by the hash * code of the group's value */ protected final List<PreconditionNode>[] groups; /** * Constructs a new fluent node that belongs to a given graph and * represents a given nominal fluent. * * @param graph the graph this node belongs to * @param label the nominal fluent this node represents * @throws edu.uky.cs.nil.sabre.FormatException if the fluent is numeric */ @SuppressWarnings("unchecked")
protected NominalFluentNode(HeuristicGraph graph, Fluent label) {
0
2023-10-26 18:14:19+00:00
16k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/command/CommandHandler.java
[ { "identifier": "ConfirmCommand", "path": "core/src/main/java/net/pl3x/map/core/command/commands/ConfirmCommand.java", "snippet": "public class ConfirmCommand extends Pl3xMapCommand {\n private final CommandConfirmationManager<@NotNull Sender> confirmationManager = new CommandConfirmationManager<>(\n...
import cloud.commandframework.Command; import cloud.commandframework.CommandManager; import cloud.commandframework.meta.CommandMeta; import cloud.commandframework.minecraft.extras.AudienceProvider; import cloud.commandframework.minecraft.extras.MinecraftExceptionHandler; import java.util.List; import java.util.function.UnaryOperator; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.pl3x.map.core.command.commands.ConfirmCommand; import net.pl3x.map.core.command.commands.FullRenderCommand; import net.pl3x.map.core.command.commands.HelpCommand; import net.pl3x.map.core.command.commands.HideCommand; import net.pl3x.map.core.command.commands.PauseCommand; import net.pl3x.map.core.command.commands.RadiusRenderCommand; import net.pl3x.map.core.command.commands.ReloadCommand; import net.pl3x.map.core.command.commands.ResetMapCommand; import net.pl3x.map.core.command.commands.ShowCommand; import net.pl3x.map.core.command.commands.StatusCommand; import net.pl3x.map.core.command.commands.StitchCommand; import net.pl3x.map.core.command.commands.VersionCommand; import net.pl3x.map.core.configuration.Config; import net.pl3x.map.core.configuration.Lang; import org.jetbrains.annotations.NotNull;
11,535
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.command; /** * Represents the command handler. */ public interface CommandHandler { /** * Get the command manager. * * @return command manager */ @NotNull CommandManager<@NotNull Sender> getManager(); /** * Get the root command. * * @return the root command */ Command.@NotNull Builder<@NotNull Sender> getRoot(); default void setupExceptionHandlers() { new MinecraftExceptionHandler<Sender>() .withDefaultHandlers() .withDecorator(component -> Component.text() .append(Lang.parse(Lang.PREFIX_COMMAND) .hoverEvent(Lang.parse(Lang.CLICK_FOR_HELP)) .clickEvent(ClickEvent.runCommand("/map help"))) .append(component) .build()) .apply(getManager(), AudienceProvider.nativeAudience()); } /** * Register a new subcommand. * * @param builder command builder */ default void registerSubcommand(@NotNull UnaryOperator<Command.@NotNull Builder<@NotNull Sender>> builder) { this.getManager().command(builder.apply(getRoot())); } default Command.@NotNull Builder<@NotNull Sender> buildRoot() { return getManager().commandBuilder("map", "pl3xmap") .permission("pl3xmap.command.map") .meta(CommandMeta.DESCRIPTION, "Pl3xMap command. '/map help'") .handler(context -> { context.getSender().sendMessage(Lang.COMMAND_BASE // minimessage doesn't seem to handle placeholders inside // placeholders, so we have to replace this one manually
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.command; /** * Represents the command handler. */ public interface CommandHandler { /** * Get the command manager. * * @return command manager */ @NotNull CommandManager<@NotNull Sender> getManager(); /** * Get the root command. * * @return the root command */ Command.@NotNull Builder<@NotNull Sender> getRoot(); default void setupExceptionHandlers() { new MinecraftExceptionHandler<Sender>() .withDefaultHandlers() .withDecorator(component -> Component.text() .append(Lang.parse(Lang.PREFIX_COMMAND) .hoverEvent(Lang.parse(Lang.CLICK_FOR_HELP)) .clickEvent(ClickEvent.runCommand("/map help"))) .append(component) .build()) .apply(getManager(), AudienceProvider.nativeAudience()); } /** * Register a new subcommand. * * @param builder command builder */ default void registerSubcommand(@NotNull UnaryOperator<Command.@NotNull Builder<@NotNull Sender>> builder) { this.getManager().command(builder.apply(getRoot())); } default Command.@NotNull Builder<@NotNull Sender> buildRoot() { return getManager().commandBuilder("map", "pl3xmap") .permission("pl3xmap.command.map") .meta(CommandMeta.DESCRIPTION, "Pl3xMap command. '/map help'") .handler(context -> { context.getSender().sendMessage(Lang.COMMAND_BASE // minimessage doesn't seem to handle placeholders inside // placeholders, so we have to replace this one manually
.replace("<web-address>", Config.WEB_ADDRESS));
12
2023-10-26 01:14:31+00:00
16k
d0ge/sessionless
src/main/java/one/d4d/sessionless/presenter/EditorPresenter.java
[ { "identifier": "SignerConfig", "path": "src/main/java/burp/config/SignerConfig.java", "snippet": "public class SignerConfig {\n @Expose\n private boolean enableDangerous;\n @Expose\n private boolean enableExpress;\n @Expose\n private boolean enableOAuth;\n @Expose\n private bool...
import burp.api.montoya.collaborator.CollaboratorPayloadGenerator; import burp.api.montoya.http.message.Cookie; import burp.api.montoya.http.message.params.ParsedHttpParameter; import burp.config.SignerConfig; import one.d4d.sessionless.forms.EditorTab; import one.d4d.sessionless.forms.MessageDialogFactory; import one.d4d.sessionless.forms.dialog.*; import one.d4d.sessionless.itsdangerous.Attack; import one.d4d.sessionless.itsdangerous.model.*; import one.d4d.sessionless.keys.Key; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.ErrorLoggingActionListenerFactory; import one.d4d.sessionless.utils.Utils; import java.net.URL; import java.util.Base64; import java.util.List; import static one.d4d.sessionless.itsdangerous.model.SignedTokenObjectFinder.containsSignedTokenObjects;
11,295
SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } private void signingDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } SignDialog signDialog = new SignDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } public void onAttackClicked(Attack mode) { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); List<String> attackKeys = keysPresenter.getSecrets(); List<String> attackSalts = keysPresenter.getSalts(); if (attackKeys.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_secrets", "error_no_secrets"); return; } if (attackSalts.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_salts", "error_no_salts"); return; } BruteForceAttackDialog bruteForceDialog = new BruteForceAttackDialog( view.window(), actionListenerFactory, attackKeys, attackSalts, keysPresenter.getSigningKeys(), mode, tokenObject); bruteForceDialog.display(); SecretKey k = bruteForceDialog.getSecretKey(); if (k != null) { KeyDialog d; d = new NewKeyDialog(view.window(), presenters, k); d.display(); Key newKey = d.getKey(); if (newKey != null) { keysPresenter.addKey((SecretKey) newKey); } } } public void onAttackKnownKeysClicked() { onAttackClicked(Attack.KNOWN); } public void onAttackFastClicked() { onAttackClicked(Attack.FAST); } public void onAttackBalancedClicked() { onAttackClicked(Attack.Balanced); } public void onAttackDeepClicked() { onAttackClicked(Attack.Deep); } public boolean isEnabled(String text, List<Cookie> cookies, List<ParsedHttpParameter> params) {
package one.d4d.sessionless.presenter; public class EditorPresenter extends Presenter { private final PresenterStore presenters; private final SignerConfig signerConfig; private final EditorModel model; private final EditorTab view; private final CollaboratorPayloadGenerator collaboratorPayloadGenerator; private final ErrorLoggingActionListenerFactory actionListenerFactory; private final MessageDialogFactory messageDialogFactory; private boolean selectionChanging; private URL targetURL; public EditorPresenter( EditorTab view, CollaboratorPayloadGenerator collaboratorPayloadGenerator, ErrorLoggingActionListenerFactory actionListenerFactory, PresenterStore presenters, SignerConfig signerConfig) { this.view = view; this.model = new EditorModel(signerConfig); this.collaboratorPayloadGenerator = collaboratorPayloadGenerator; this.actionListenerFactory = actionListenerFactory; this.presenters = presenters; messageDialogFactory = new MessageDialogFactory(view.uiComponent()); presenters.register(this); this.signerConfig = signerConfig; } public void setMessage(String content, URL targetURL, List<Cookie> cookies, List<ParsedHttpParameter> params) { this.targetURL = targetURL; model.setMessage(content, cookies, params); view.setSignedTokenObjects(model.getSerializedObjectStrings()); } private DangerousSignedToken getDangerous() { String payload; if (view.getDangerouseIsJSON()) { String json = Utils.compactJSON(view.getDangerousPayload()); if (view.getDangerouseIsCompressed()) { payload = Utils.compressBase64(json.getBytes()); } else { payload = Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes()); } } else { payload = view.getDangerousPayload(); } String timestamp; String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(view.getDangerousSignature()); byte[] separator = view.getDangerousSeparator().length == 0 ? new byte[]{46} : view.getDangerousSeparator(); if (view.getDangerouseIsDjangoFormatting()) { timestamp = Utils.encodeBase62TimestampFromDate(view.getDangerousTimestamp()); return new DjangoSignedToken( separator[0], payload, timestamp, signature); } else { timestamp = Utils.encodeBase64TimestampFromDate(view.getDangerousTimestamp()); return new DangerousSignedToken( separator[0], payload, timestamp, signature); } } private void setDangerous(DangerousSignedToken token) { view.setDangerouseIsCompressed(token.isCompressed()); try { String payload = new String(Utils.base64Decompress(token.getPayload().getBytes())); if (Utils.isValidJSON(payload)) { view.setDangerouseIsJSON(true); view.setDangerousPayload(Utils.prettyPrintJSON(payload)); } else { view.setDangerouseIsJSON(false); view.setDangerousPayload(token.getPayload()); } } catch (Exception e) { view.setDangerouseIsJSON(false); view.setDangerousPayload(token.getPayload()); } if (token instanceof DjangoSignedToken) { view.setDangerouseIsDjangoFormatting(true); view.setDangerousTimestamp(token.getTimestamp()); } else { view.setDangerouseIsDjangoFormatting(false); view.setDangerousTimestamp(token.getTimestamp()); } view.setDangerousSignature(token.getSignature()); view.setDangerousSeparator(token.getSeparator()); } private OauthProxySignedToken getOAuth() { String parameter = view.getOAuthParameter(); String payload = view.getOAuthPayload(); String timestamp = Utils.timestampFromDateInSeconds(view.getOAuthTimestamp()); String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(view.getOAuthSignature()); return new OauthProxySignedToken( parameter, payload, timestamp, signature); } private void setOAuth(OauthProxySignedToken token) { view.setOAuthParameter(token.getParameter()); view.setOAuthPayload(token.getPayload()); view.setOAuthTimestamp(token.getTimestamp()); view.setOAuthSignature(token.getSignature()); } private ExpressSignedToken getExpress() { String parameter = view.getExpressParameter(); String payload = Base64.getUrlEncoder().encodeToString(view.getExpressPayload().getBytes()); String signature = view.getExpressSignature(); return new ExpressSignedToken(parameter, payload, signature); } private void setExpress(ExpressSignedToken token) { view.setExpressPayload(token.getPayload()); view.setExpressParameter(token.getParameter()); view.setExpressSignature(new String(token.getSignature())); } private TornadoSignedToken getTornado() { String name = view.getTornadoName(); String value = Base64.getUrlEncoder().encodeToString(view.getTornadoValue().getBytes()); String timestamp = Utils.timestampFromDateInSeconds(view.getTornadoTimestamp()); String signature = new String(view.getTornadoSignature()); return new TornadoSignedToken(timestamp, name, value, signature); } private void setTornado(TornadoSignedToken token) { view.setTornadoTimestamp(token.getTimestamp()); view.setTornadoName(token.getName()); view.setTornadoValue(token.getValue()); view.setTornadoSignature(token.getSignature()); } private UnknownSignedToken getUnknown() { String message = view.getUnknownMessage(); String signature = view.getUnknownSignature(); byte[] separator = view.getUnknownSeparator().length == 0 ? new byte[]{46} : view.getUnknownSeparator(); return new UnknownSignedToken(message,signature,separator[0]); } private void setUnknown(UnknownSignedToken token) { view.setUnknownMessage(token.getEncodedMessage()); view.setUnknownSignature(token.getEncodedSignature()); view.setUnknownSeparator(token.getSeparator()); } public void componentChanged() { MutableSignedToken mutableSignedTokenObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject; switch (view.getMode()) { case EditorTab.TAB_DANGEROUSE -> tokenObject = getDangerous(); case EditorTab.TAB_EXPRESS -> tokenObject = getExpress(); case EditorTab.TAB_OAUTH -> tokenObject = getOAuth(); case EditorTab.TAB_TORNADO -> tokenObject = getTornado(); default -> tokenObject = getUnknown(); } mutableSignedTokenObject.setModified(tokenObject); view.setSignedToken(tokenObject.serialize(), mutableSignedTokenObject.changed() && !selectionChanging); } public void onSelectionChanged() { selectionChanging = true; MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (tokenObject instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) tokenObject); } else if (tokenObject instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) tokenObject); } else if (tokenObject instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) tokenObject); } else if (tokenObject instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) tokenObject); } else if (tokenObject instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) tokenObject); } selectionChanging = false; } public void copyExpressSignature() { Utils.copyToClipboard(view.getExpressSignature()); } public void onSignClicked() { signingDialog(); } public void onAttackClicked() { attackDialog(); } private void attackDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } AttackDialog signDialog = new AttackDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), targetURL, tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } private void signingDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } SignDialog signDialog = new SignDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } public void onAttackClicked(Attack mode) { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); List<String> attackKeys = keysPresenter.getSecrets(); List<String> attackSalts = keysPresenter.getSalts(); if (attackKeys.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_secrets", "error_no_secrets"); return; } if (attackSalts.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_salts", "error_no_salts"); return; } BruteForceAttackDialog bruteForceDialog = new BruteForceAttackDialog( view.window(), actionListenerFactory, attackKeys, attackSalts, keysPresenter.getSigningKeys(), mode, tokenObject); bruteForceDialog.display(); SecretKey k = bruteForceDialog.getSecretKey(); if (k != null) { KeyDialog d; d = new NewKeyDialog(view.window(), presenters, k); d.display(); Key newKey = d.getKey(); if (newKey != null) { keysPresenter.addKey((SecretKey) newKey); } } } public void onAttackKnownKeysClicked() { onAttackClicked(Attack.KNOWN); } public void onAttackFastClicked() { onAttackClicked(Attack.FAST); } public void onAttackBalancedClicked() { onAttackClicked(Attack.Balanced); } public void onAttackDeepClicked() { onAttackClicked(Attack.Deep); } public boolean isEnabled(String text, List<Cookie> cookies, List<ParsedHttpParameter> params) {
return containsSignedTokenObjects(signerConfig, text, cookies, params);
8
2023-10-30 09:12:06+00:00
16k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/event/ThirdPersonEvents.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA...
import com.mojang.blaze3d.Blaze3D; import com.mojang.blaze3d.platform.Window; import dev.architectury.event.EventResult; import dev.architectury.event.events.client.ClientPlayerEvent; import dev.architectury.event.events.client.ClientRawInputEvent; import dev.architectury.event.events.client.ClientTickEvent; import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.api.ModConstants; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetScheme; import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.math.LMath; import net.minecraft.client.CameraType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockGetter;
12,033
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig(); CameraAgent.updateSmoothEyePosition(0.05); PlayerAgent.updateSmoothRotations(0.05); PlayerAgent.wasInterecting = PlayerAgent.isInterecting(); PlayerAgent.wasAiming = ModReferee.isCameraEntityAiming(); config.cameraOffsetScheme.setAiming(PlayerAgent.wasAiming); } /** * 当玩家死亡后重生或加入新的维度时触发 */ private static void onClientPlayerRespawn (LocalPlayer oldPlayer, LocalPlayer newPlayer) { onPlayerReset(); ThirdPerson.LOGGER.info("on Client player respawn"); } private static void onClientPlayerJoin (LocalPlayer player) { onPlayerReset(); ThirdPerson.LOGGER.info("on Client player join"); } /** * 使用滚轮调整距离 * * @param minecraft mc * @param amount 向前滚是+1,向后滚是-1 */ private static EventResult onMouseScrolled (Minecraft minecraft, double amount) { Config config = ThirdPerson.getConfig(); if (ModReferee.isAdjustingCameraDistance()) { double dist = config.cameraOffsetScheme.getMode().getMaxDistance(); dist = config.distanceMonoList.offset(dist, (int)-Math.signum(amount)); config.cameraOffsetScheme.getMode().setMaxDistance(dist); return EventResult.interruptFalse(); } else { return EventResult.pass(); } } private static void onPlayerReset () { CameraAgent.reset(); PlayerAgent.reset(); } /** * 调用Camera.setup时触发 * <p> * 该调用位于真正渲染画面之前。 * <p> * GameRender#render -> GameRender#renderLevel -> Camera#setup */ static void onCameraSetup (BlockGetter level, float partialTick) { ThirdPerson.lastPartialTick = partialTick; CameraAgent.level = level; Minecraft mc = Minecraft.getInstance(); if (mc.player == null) { return; } double now = Blaze3D.getTime(); double period = now - ThirdPerson.lastCameraSetupTimeStamp; ThirdPerson.lastCameraSetupTimeStamp = now; if (ModReferee.isThirdPerson()) { CameraAgent.onCameraSetup(period); } PlayerAgent.onCameraSetup(period); if (mc.options.getCameraType().isMirrored()) { mc.options.setCameraType(CameraType.FIRST_PERSON); } } static void onStartAdjustingCameraOffset () { } static void onStopAdjustingCameraOffset () { ThirdPerson.getConfigManager().trySave(); } /** * 移动鼠标调整相机偏移 * * @param xMove 水平移动的像素 * @param yMove 垂直移动的像素 */
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig(); CameraAgent.updateSmoothEyePosition(0.05); PlayerAgent.updateSmoothRotations(0.05); PlayerAgent.wasInterecting = PlayerAgent.isInterecting(); PlayerAgent.wasAiming = ModReferee.isCameraEntityAiming(); config.cameraOffsetScheme.setAiming(PlayerAgent.wasAiming); } /** * 当玩家死亡后重生或加入新的维度时触发 */ private static void onClientPlayerRespawn (LocalPlayer oldPlayer, LocalPlayer newPlayer) { onPlayerReset(); ThirdPerson.LOGGER.info("on Client player respawn"); } private static void onClientPlayerJoin (LocalPlayer player) { onPlayerReset(); ThirdPerson.LOGGER.info("on Client player join"); } /** * 使用滚轮调整距离 * * @param minecraft mc * @param amount 向前滚是+1,向后滚是-1 */ private static EventResult onMouseScrolled (Minecraft minecraft, double amount) { Config config = ThirdPerson.getConfig(); if (ModReferee.isAdjustingCameraDistance()) { double dist = config.cameraOffsetScheme.getMode().getMaxDistance(); dist = config.distanceMonoList.offset(dist, (int)-Math.signum(amount)); config.cameraOffsetScheme.getMode().setMaxDistance(dist); return EventResult.interruptFalse(); } else { return EventResult.pass(); } } private static void onPlayerReset () { CameraAgent.reset(); PlayerAgent.reset(); } /** * 调用Camera.setup时触发 * <p> * 该调用位于真正渲染画面之前。 * <p> * GameRender#render -> GameRender#renderLevel -> Camera#setup */ static void onCameraSetup (BlockGetter level, float partialTick) { ThirdPerson.lastPartialTick = partialTick; CameraAgent.level = level; Minecraft mc = Minecraft.getInstance(); if (mc.player == null) { return; } double now = Blaze3D.getTime(); double period = now - ThirdPerson.lastCameraSetupTimeStamp; ThirdPerson.lastCameraSetupTimeStamp = now; if (ModReferee.isThirdPerson()) { CameraAgent.onCameraSetup(period); } PlayerAgent.onCameraSetup(period); if (mc.options.getCameraType().isMirrored()) { mc.options.setCameraType(CameraType.FIRST_PERSON); } } static void onStartAdjustingCameraOffset () { } static void onStopAdjustingCameraOffset () { ThirdPerson.getConfigManager().trySave(); } /** * 移动鼠标调整相机偏移 * * @param xMove 水平移动的像素 * @param yMove 垂直移动的像素 */
static void onAdjustingCameraOffset (Vector2d movement) {
8
2023-10-31 05:52:36+00:00
16k
siam1026/siam-cloud
siam-order/order-provider/src/main/java/com/siam/package_order/controller/member/WxPayService.java
[ { "identifier": "AliyunSms", "path": "siam-common/src/main/java/com/siam/package_common/service/AliyunSms.java", "snippet": "@Component\n@ConfigurationProperties(value = \"aliyun.dysms\")\npublic class AliyunSms {\n private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n private stat...
import com.siam.package_common.service.AliyunSms; import com.siam.package_common.util.CommonUtils; import com.siam.package_common.util.GenerateNo; import com.siam.package_order.service.OrderRefundProcessService; import com.siam.package_order.service.OrderRefundService; import com.siam.package_order.service.OrderService; import com.siam.package_weixin_basic.service.WxPublicPlatformNotifyService; import com.siam.package_weixin_pay.config.WxPayConfig; import com.siam.package_weixin_pay.entity.TransfersDto; import com.siam.package_weixin_pay.util.Constants; import com.siam.package_weixin_pay.util.PayUtil; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.SocketTimeoutException; import java.security.KeyStore; import java.util.*;
13,668
package com.siam.package_order.controller.member; @Data @Slf4j @Service public class WxPayService { @Value("${spring.profiles.active}") private String profilesActive; @Autowired
package com.siam.package_order.controller.member; @Data @Slf4j @Service public class WxPayService { @Value("${spring.profiles.active}") private String profilesActive; @Autowired
private WxPayConfig wxPayConfig;
7
2023-10-26 10:45:10+00:00
16k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs4/F4NRecord.java
[ { "identifier": "NewRecord", "path": "src/main/java/yaa/ast/NewRecord.java", "snippet": "public class NewRecord extends Stmt {\r\n public Map<String, YaaToken> options = new HashMap<>(1);\r\n public List<TypeParam> typeParams = new ArrayList<>(1);\r\n public List<RunBlock> runBlocks = new ArrayList<>...
import yaa.ast.NewRecord; import yaa.pojos.YaaClz; import yaa.semantic.handlers.VDefOp; import static yaa.pojos.GlobalData.*; import static yaa.pojos.GlobalData.fs4;
12,512
package yaa.semantic.passes.fs4; public class F4NRecord { public static void newRecord(NewRecord newRecord) { fs4.pushTable(newRecord); var currentClz = (YaaClz) fs4.getSymbol(newRecord.placeOfUse()); topClz.push(currentClz); for (var def : newRecord.vDefinitions) {
package yaa.semantic.passes.fs4; public class F4NRecord { public static void newRecord(NewRecord newRecord) { fs4.pushTable(newRecord); var currentClz = (YaaClz) fs4.getSymbol(newRecord.placeOfUse()); topClz.push(currentClz); for (var def : newRecord.vDefinitions) {
VDefOp.defOp(def);
2
2023-10-26 17:41:13+00:00
16k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/util/RPGHelper.java
[ { "identifier": "IRPGItem", "path": "src/main/java/mixac1/dangerrpg/api/item/IRPGItem.java", "snippet": "public interface IRPGItem {\n\n public void registerAttributes(Item item, RPGItemData map);\n\n public interface IRPGItemMod extends IRPGItem {\n\n public RPGItemComponent getItemCompone...
import com.google.common.collect.Multimap; import mixac1.dangerrpg.api.item.IRPGItem; import mixac1.dangerrpg.api.item.IRPGItem.IRPGItemArmor; import mixac1.dangerrpg.api.item.IRPGItem.IRPGItemTool; import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.PlayerAttributes; import mixac1.dangerrpg.capability.RPGEntityHelper; import mixac1.dangerrpg.capability.RPGItemHelper; import mixac1.dangerrpg.init.RPGCapability; import mixac1.dangerrpg.item.IMaterialSpecial; import mixac1.dangerrpg.item.gem.Gem; import mixac1.dangerrpg.util.IMultiplier.Multiplier; import mixac1.dangerrpg.util.IMultiplier.MultiplierAdd; import mixac1.dangerrpg.util.IMultiplier.MultiplierMul; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import java.util.*; import java.util.Map.Entry;
13,608
package mixac1.dangerrpg.util; public abstract class RPGHelper { public static void knockBack(EntityLivingBase entityliving, EntityLivingBase attacker, float knockback) { double i = Math.sqrt(knockback); double x = -MathHelper.sin(attacker.rotationYaw / 180.0F * (float) Math.PI) * 0.4; double z = MathHelper.cos(attacker.rotationYaw / 180.0F * (float) Math.PI) * 0.4; double y = -MathHelper.sin(attacker.rotationPitch / 180.0F * (float) Math.PI) * 0.1; entityliving.addVelocity(x * i, y * i, z * i); } public static void rebuildPlayerExp(EntityPlayer player) { int lvl = player.experienceLevel; int exp = (int) (player.xpBarCap() * player.experience); player.experience = 0.0F; player.experienceTotal = 0; player.experienceLevel = 0; for (int i = 0; i < lvl; ++i) { player.addExperience(player.xpBarCap()); } player.addExperience(exp); } public static void rebuildPlayerLvl(EntityPlayer player) { int exp = player.experienceTotal; player.experience = 0.0F; player.experienceTotal = 0; player.experienceLevel = 0; player.addExperience(exp); } public static MovingObjectPosition getMouseOver(float frame, float dist) { Minecraft mc = Minecraft.getMinecraft(); MovingObjectPosition mop = null; if (mc.renderViewEntity != null) { if (mc.theWorld != null) { mop = mc.renderViewEntity.rayTrace(dist, frame); Vec3 pos = mc.renderViewEntity.getPosition(frame); double calcDist = dist; if (mop != null) { calcDist = mop.hitVec.distanceTo(pos); } Vec3 look = mc.renderViewEntity.getLook(frame); look = Vec3.createVectorHelper(look.xCoord * dist, look.yCoord * dist, look.zCoord * dist); Vec3 vec = pos.addVector(look.xCoord, look.yCoord, look.zCoord); Entity pointedEntity = null; @SuppressWarnings("unchecked") List<Entity> list = mc.theWorld.getEntitiesWithinAABBExcludingEntity( mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(look.xCoord, look.yCoord, look.zCoord) .expand(1.0F, 1.0F, 1.0F)); double d = calcDist; for (Entity entity : list) { if (entity.canBeCollidedWith()) { float borderSize = entity.getCollisionBorderSize(); AxisAlignedBB aabb = entity.boundingBox.expand(borderSize, borderSize, borderSize); MovingObjectPosition mop0 = aabb.calculateIntercept(pos, vec); if (aabb.isVecInside(pos)) { if (0.0D <= d) { pointedEntity = entity; d = 0.0D; } } else if (mop0 != null) { double d1 = pos.distanceTo(mop0.hitVec); if (d1 < d || d == 0.0D) { pointedEntity = entity; d = d1; } } } } if (pointedEntity != null && (d < calcDist || mop == null)) { mop = new MovingObjectPosition(pointedEntity); } } } return mop; } public static float getUsePower(EntityPlayer player, ItemStack stack, int useDuration, float defMaxPow, float defMinPow) { float power = getUsePower(player, stack, useDuration, defMaxPow); float minPower = ItemAttributes.MIN_CUST_TIME.getSafe(stack, player, defMinPow); if (power < minPower) { return -1f; } return power; } public static float getUsePower(EntityPlayer player, ItemStack stack, int useDuration, float defMaxPow) { float power = useDuration / ItemAttributes.SHOT_SPEED.getSafe(stack, player, defMaxPow); power = (power * power + power * 2.0F) / 3.0F; if (power > 1.0F) { return 1f; } return power; } public static IMaterialSpecial getMaterialSpecial(ItemStack stack) {
package mixac1.dangerrpg.util; public abstract class RPGHelper { public static void knockBack(EntityLivingBase entityliving, EntityLivingBase attacker, float knockback) { double i = Math.sqrt(knockback); double x = -MathHelper.sin(attacker.rotationYaw / 180.0F * (float) Math.PI) * 0.4; double z = MathHelper.cos(attacker.rotationYaw / 180.0F * (float) Math.PI) * 0.4; double y = -MathHelper.sin(attacker.rotationPitch / 180.0F * (float) Math.PI) * 0.1; entityliving.addVelocity(x * i, y * i, z * i); } public static void rebuildPlayerExp(EntityPlayer player) { int lvl = player.experienceLevel; int exp = (int) (player.xpBarCap() * player.experience); player.experience = 0.0F; player.experienceTotal = 0; player.experienceLevel = 0; for (int i = 0; i < lvl; ++i) { player.addExperience(player.xpBarCap()); } player.addExperience(exp); } public static void rebuildPlayerLvl(EntityPlayer player) { int exp = player.experienceTotal; player.experience = 0.0F; player.experienceTotal = 0; player.experienceLevel = 0; player.addExperience(exp); } public static MovingObjectPosition getMouseOver(float frame, float dist) { Minecraft mc = Minecraft.getMinecraft(); MovingObjectPosition mop = null; if (mc.renderViewEntity != null) { if (mc.theWorld != null) { mop = mc.renderViewEntity.rayTrace(dist, frame); Vec3 pos = mc.renderViewEntity.getPosition(frame); double calcDist = dist; if (mop != null) { calcDist = mop.hitVec.distanceTo(pos); } Vec3 look = mc.renderViewEntity.getLook(frame); look = Vec3.createVectorHelper(look.xCoord * dist, look.yCoord * dist, look.zCoord * dist); Vec3 vec = pos.addVector(look.xCoord, look.yCoord, look.zCoord); Entity pointedEntity = null; @SuppressWarnings("unchecked") List<Entity> list = mc.theWorld.getEntitiesWithinAABBExcludingEntity( mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(look.xCoord, look.yCoord, look.zCoord) .expand(1.0F, 1.0F, 1.0F)); double d = calcDist; for (Entity entity : list) { if (entity.canBeCollidedWith()) { float borderSize = entity.getCollisionBorderSize(); AxisAlignedBB aabb = entity.boundingBox.expand(borderSize, borderSize, borderSize); MovingObjectPosition mop0 = aabb.calculateIntercept(pos, vec); if (aabb.isVecInside(pos)) { if (0.0D <= d) { pointedEntity = entity; d = 0.0D; } } else if (mop0 != null) { double d1 = pos.distanceTo(mop0.hitVec); if (d1 < d || d == 0.0D) { pointedEntity = entity; d = d1; } } } } if (pointedEntity != null && (d < calcDist || mop == null)) { mop = new MovingObjectPosition(pointedEntity); } } } return mop; } public static float getUsePower(EntityPlayer player, ItemStack stack, int useDuration, float defMaxPow, float defMinPow) { float power = getUsePower(player, stack, useDuration, defMaxPow); float minPower = ItemAttributes.MIN_CUST_TIME.getSafe(stack, player, defMinPow); if (power < minPower) { return -1f; } return power; } public static float getUsePower(EntityPlayer player, ItemStack stack, int useDuration, float defMaxPow) { float power = useDuration / ItemAttributes.SHOT_SPEED.getSafe(stack, player, defMaxPow); power = (power * power + power * 2.0F) / 3.0F; if (power > 1.0F) { return 1f; } return power; } public static IMaterialSpecial getMaterialSpecial(ItemStack stack) {
if (stack != null && RPGItemHelper.isRPGable(stack)) {
6
2023-10-31 21:00:14+00:00
16k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/sql/SqlGenerator.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.util.StringUtils; import org.tinycloud.jdbc.annotation.Column; import org.tinycloud.jdbc.annotation.Table; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.annotation.IdType; import org.tinycloud.jdbc.id.IdUtils; import org.tinycloud.jdbc.util.ReflectUtils; import org.tinycloud.jdbc.util.Triple; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
11,585
Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder whereColumns = new StringBuilder(); Object whereValues = new Object(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { whereColumns.append(column); whereValues = filedValue; continue; } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } if (whereValues == null) { throw new JdbcException("SqlGenerator updateByIdSql primaryKeyId can not null!"); } String tableColumn = columns.subSequence(0, columns.length() - 1).toString(); sql.append("UPDATE ").append(tableAnnotation.value()).append(" SET ").append(tableColumn); sql.append(" WHERE "); sql.append(whereColumns); sql.append("=?"); parameters.add(whereValues); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 实体对象 * @param ignoreNulls 是否忽略null * @param criteria 条件构造器 * @return 组装完毕的SqlProvider */ public static SqlProvider updateByCriteriaSql(Object object, boolean ignoreNulls, Criteria criteria) { String criteriaSql = criteria.generateSql(); if (StringUtils.isEmpty(criteriaSql) || !criteriaSql.contains("WHERE")) { throw new JdbcException("SqlGenerator updateByCriteriaSql criteria can not null or empty!"); } Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } String tableColumn = columns.subSequence(0, columns.length() - 1).toString(); sql.append("UPDATE ").append(tableAnnotation.value()).append(" SET ").append(tableColumn); sql.append(criteriaSql); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); parameters.addAll(criteria.getParameters()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 实体对象 * @param ignoreNulls 是否忽略null * @param criteria 条件构造器Lambda * @return 组装完毕的SqlProvider */
package org.tinycloud.jdbc.sql; /** * sql生成器,通过传入的对象,将对象转为要执行的SQL,要绑定到SQL的参数 * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public class SqlGenerator { /** * 构建插入SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider insertSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { IdType idType = columnAnnotation.idType(); if (idType == IdType.AUTO_INCREMENT) { // 自增主键直接跳过,无需处理 continue; } // 如果是其他主键策略,设置完主键后,塞回到实体类里,这样可以方便插入后获取主键值 if (idType == IdType.OBJECT_ID) { Object fieldValue = IdUtils.objectId(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when objectId!"); } } if (idType == IdType.ASSIGN_ID) { Class<?> type = field.getType(); Object fieldValue = (type == java.lang.String.class) ? IdUtils.nextId() : IdUtils.nextLongId(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String or Long when assignId!"); } } if (idType == IdType.UUID) { Object fieldValue = IdUtils.simpleUUID(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when uuid!"); } } } Object fieldValue = null; try { fieldValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } // 是否忽略null if (ignoreNulls && fieldValue == null) { continue; } columns.append(column).append(","); values.append("?").append(","); parameters.add(fieldValue); } String tableColumns = columns.subSequence(0, columns.length() - 1).toString(); String tableValues = values.subSequence(0, values.length() - 1).toString(); sql.append("INSERT INTO ").append(tableAnnotation.value()); sql.append(" (").append(tableColumns).append(")"); sql.append(" VALUES (").append(tableValues).append(")"); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider updateByIdSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder whereColumns = new StringBuilder(); Object whereValues = new Object(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { whereColumns.append(column); whereValues = filedValue; continue; } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } if (whereValues == null) { throw new JdbcException("SqlGenerator updateByIdSql primaryKeyId can not null!"); } String tableColumn = columns.subSequence(0, columns.length() - 1).toString(); sql.append("UPDATE ").append(tableAnnotation.value()).append(" SET ").append(tableColumn); sql.append(" WHERE "); sql.append(whereColumns); sql.append("=?"); parameters.add(whereValues); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 实体对象 * @param ignoreNulls 是否忽略null * @param criteria 条件构造器 * @return 组装完毕的SqlProvider */ public static SqlProvider updateByCriteriaSql(Object object, boolean ignoreNulls, Criteria criteria) { String criteriaSql = criteria.generateSql(); if (StringUtils.isEmpty(criteriaSql) || !criteriaSql.contains("WHERE")) { throw new JdbcException("SqlGenerator updateByCriteriaSql criteria can not null or empty!"); } Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } String tableColumn = columns.subSequence(0, columns.length() - 1).toString(); sql.append("UPDATE ").append(tableAnnotation.value()).append(" SET ").append(tableColumn); sql.append(criteriaSql); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); parameters.addAll(criteria.getParameters()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 实体对象 * @param ignoreNulls 是否忽略null * @param criteria 条件构造器Lambda * @return 组装完毕的SqlProvider */
public static SqlProvider updateByLambdaCriteriaSql(Object object, boolean ignoreNulls, LambdaCriteria criteria) {
1
2023-10-25 14:44:59+00:00
16k
simply-kel/AlinLib
src/main/java/ru/kelcuprum/alinlib/gui/screens/AlinaDemoScreen.java
[ { "identifier": "AlinLib", "path": "src/main/java/ru/kelcuprum/alinlib/AlinLib.java", "snippet": "public class AlinLib implements ClientModInitializer {\r\n public static final Logger LOG = LogManager.getLogger(\"AlinaLib\");\r\n public static Config bariumConfig = new Config(\"config/AlibLib/conf...
import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.screens.*; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import ru.kelcuprum.alinlib.AlinLib; import ru.kelcuprum.alinlib.Colors; import ru.kelcuprum.alinlib.config.Localization; import ru.kelcuprum.alinlib.gui.InterfaceUtils; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonSprite; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxString; import ru.kelcuprum.alinlib.gui.components.sliders.SliderInteger; import ru.kelcuprum.alinlib.gui.components.sliders.SliderPercent; import ru.kelcuprum.alinlib.gui.components.text.TextBox; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonBoolean; import ru.kelcuprum.alinlib.gui.components.buttons.Button; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxColor; import ru.kelcuprum.alinlib.gui.components.selector.SelectorStringButton; import ru.kelcuprum.alinlib.gui.toast.AlinaToast; import java.util.ArrayList; import java.util.List;
13,093
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox;
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox;
private EditBoxString stringEditBox;
5
2023-10-29 13:30:26+00:00
16k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/components/GroupComponent.java
[ { "identifier": "AccessGroup", "path": "src/main/java/com/buschmais/backend/adrAccess/AccessGroup.java", "snippet": "@Document\n@Data\npublic class AccessGroup implements Comparable<AccessGroup> {\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsAndHashCode.Exclude\n\t@Id\n\tprivate String id;\n\n\t@Indexed\...
import com.buschmais.backend.adrAccess.AccessGroup; import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao; import com.buschmais.backend.users.User; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.buschmais.frontend.views.usercontrol.GroupsInformationView; import com.buschmais.frontend.views.usercontrol.UserControlView; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.RouteConfiguration; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collection;
10,973
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/UserControl/GroupComponent.css") public class GroupComponent extends VerticalLayout {
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/UserControl/GroupComponent.css") public class GroupComponent extends VerticalLayout {
private final ADRAccessDao adrAccessDao;
1
2023-10-25 15:18:06+00:00
16k
Java-Game-Engine-Merger/Libgdx-Processing
server-framework/src/main/java/pama1234/math/mat/Mat4f.java
[ { "identifier": "UtilMath", "path": "server-framework/src/main/java/pama1234/math/UtilMath.java", "snippet": "public class UtilMath{\n private static final class RandomNumberGeneratorHolder{\n static final Random randomNumberGenerator=new Random();\n }\n public static final float radDeg=(float)(18...
import pama1234.math.UtilMath; import pama1234.math.gdx.temp.ServerAffine2; import pama1234.math.gdx.temp.ServerQuaternion; import pama1234.math.vec.Vec3f;
13,424
package pama1234.math.mat; /** * 直接从libgdx复制过来的 */ public class Mat4f{ private static final long serialVersionUID=-2717655254359579617L; public static final int M00=0; public static final int M01=4; public static final int M02=8; public static final int M03=12; public static final int M10=1; public static final int M11=5; public static final int M12=9; public static final int M13=13; public static final int M20=2; public static final int M21=6; public static final int M22=10; public static final int M23=14; public static final int M30=3; public static final int M31=7; public static final int M32=11; public static final int M33=15;
package pama1234.math.mat; /** * 直接从libgdx复制过来的 */ public class Mat4f{ private static final long serialVersionUID=-2717655254359579617L; public static final int M00=0; public static final int M01=4; public static final int M02=8; public static final int M03=12; public static final int M10=1; public static final int M11=5; public static final int M12=9; public static final int M13=13; public static final int M20=2; public static final int M21=6; public static final int M22=10; public static final int M23=14; public static final int M30=3; public static final int M31=7; public static final int M32=11; public static final int M33=15;
static final ServerQuaternion quat=new ServerQuaternion();
2
2023-10-27 05:47:39+00:00
16k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java
[ { "identifier": "UcUser", "path": "tinycloud-bean/src/main/java/org/tinycloud/bean/entity/UcUser.java", "snippet": "@TableName(\"t_uc_user\")\n@ApiModel(value = \"UcUser对象\", description = \"系统用户信息表\")\npublic class UcUser implements Serializable {\n private static final long serialVersionUID = 1L;\n...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.tinycloud.bean.entity.UcUser; import org.tinycloud.bean.param.UcUserPageQuery; import org.tinycloud.bean.vo.UcUserVo; import org.tinycloud.common.consts.GlobalConstant; import org.tinycloud.common.model.PageModel; import org.tinycloud.common.utils.LambdaUtils; import org.tinycloud.common.utils.StringUtils; import org.tinycloud.common.utils.bean.BeanUtils; import org.tinycloud.user.mapper.UcUserMapper; import org.tinycloud.user.service.UcUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.stream.Collectors;
11,914
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override
public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) {
4
2023-10-28 02:05:15+00:00
16k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/common/config/auth/util/UserInfoUtil.java
[ { "identifier": "AuthConstant", "path": "src/main/java/com/bluewind/base/common/config/auth/constant/AuthConstant.java", "snippet": "public class AuthConstant {\n\n // 登录用户token-key\n public static final String BLUEWIND_TOKEN_KEY = \"token\";\n\n\n // 用户会话redis的key\n public final static Stri...
import com.bluewind.base.common.config.auth.constant.AuthConstant; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.common.util.spring.SpringContextUtil; import com.bluewind.base.common.util.web.CookieUtils; import com.bluewind.base.common.util.web.ServletUtils; import com.bluewind.base.module.system.auth.entity.UserInfo; import com.bluewind.base.module.system.auth.service.AuthService; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.util.Objects;
14,342
package com.bluewind.base.common.config.auth.util; /** * @author liuxingyu01 * @date 2022-08-27 13:42 * @description 用户会话工具类 **/ public class UserInfoUtil { private static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } private static AuthService authService; private static AuthService getAuthService() { if (authService == null) { AuthService bean = SpringContextUtil.getBean(AuthService.class); if (bean == null) { logger.error("FinanceConvertUtilsService bean is null"); } authService = bean; return authService; } return authService; } /** * 获取当前登录用户的token会话串 * * @return String */ public static String getToken() { HttpServletRequest httpServletRequest = ServletUtils.getRequest(); if (Objects.isNull(httpServletRequest)) { return null; }
package com.bluewind.base.common.config.auth.util; /** * @author liuxingyu01 * @date 2022-08-27 13:42 * @description 用户会话工具类 **/ public class UserInfoUtil { private static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } private static AuthService authService; private static AuthService getAuthService() { if (authService == null) { AuthService bean = SpringContextUtil.getBean(AuthService.class); if (bean == null) { logger.error("FinanceConvertUtilsService bean is null"); } authService = bean; return authService; } return authService; } /** * 获取当前登录用户的token会话串 * * @return String */ public static String getToken() { HttpServletRequest httpServletRequest = ServletUtils.getRequest(); if (Objects.isNull(httpServletRequest)) { return null; }
String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);
0
2023-10-26 10:02:07+00:00
16k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/readPct/ModificarControlFields.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.model.ControlMensualModel; import com.utils.Styles; import com.utils.Tools; import com.view.createPacient.NewContext; import static com.view.createPacient.NewContext.dateTimeFormatter; import java.time.LocalDateTime;
11,047
package com.view.readPct; /** * * @author Daniel Batres */ public class ModificarControlFields extends Styles { /** * Creates new form NuevoControlFields */ public ModificarControlFields() { initComponents(); styleMyComponentBaby(); } public ControlMensualModel getData() { ControlMensualModel controlMensual = new ControlMensualModel(); controlMensual.setId(ApplicationContext.selectedControlMensual.getId());
package com.view.readPct; /** * * @author Daniel Batres */ public class ModificarControlFields extends Styles { /** * Creates new form NuevoControlFields */ public ModificarControlFields() { initComponents(); styleMyComponentBaby(); } public ControlMensualModel getData() { ControlMensualModel controlMensual = new ControlMensualModel(); controlMensual.setId(ApplicationContext.selectedControlMensual.getId());
controlMensual.setMd(NewContext.emptyMessage(textField1.getText()));
5
2023-10-26 19:35:40+00:00
16k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/serialization/JacksonModuleFactory.java
[ { "identifier": "FormatProvider", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java", "snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\...
import com.dawex.sigourney.trustframework.vc.core.Proof; import com.dawex.sigourney.trustframework.vc.core.SignedObject; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdContextsSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.SignedObjectJsonLdSerializer; import com.dawex.sigourney.trustframework.vc.model.shared.Did; import com.dawex.sigourney.trustframework.vc.model.shared.JsonWebKey2020; import com.dawex.sigourney.trustframework.vc.model.v2310.common.Address; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.AggregationOf; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductVerifiableCredential; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Distribution; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Location; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationVerifiableCredential; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.module.SimpleModule; import java.util.function.Supplier;
12,889
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider));
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider));
module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class,
12
2023-10-25 16:10:40+00:00
16k
inceptive-tech/ENTSOEDataRetrieval
src/test/java/tech/inceptive/ai4czc/entsoedataretrieval/TestENTSOEHistoricalDataRetrieval.java
[ { "identifier": "CSVGenerator", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/CSVGenerator.java", "snippet": "public class CSVGenerator {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVGenerator.class);\n \n private static record ColumnBlock(List<ColumnD...
import java.io.File; import java.time.Duration; import java.time.LocalDateTime; import java.time.Month; import java.util.Arrays; import java.util.Optional; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.junit.MockitoJUnitRunner; import tech.inceptive.ai4czc.entsoedataretrieval.csv.CSVGenerator; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.GLDocumentCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.ENTSOEDataFetcher; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument;
11,100
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * * @author Andres Bel Alonso */ @RunWith(MockitoJUnitRunner.class) public class TestENTSOEHistoricalDataRetrieval { private static final Logger LOGGER = LogManager.getLogger(TestENTSOEHistoricalDataRetrieval.class); @Mock private ENTSOEDataFetcher fetcher; @Mock private CSVGenerator csvGen; @InjectMocks private ENTSOEHistoricalDataRetrieval retriever = new ENTSOEHistoricalDataRetrieval("token", Set.of(ColumnType.ACTUAL_LOAD), "\'", ",", false); @Test public void testFetchDatasetActualLoadLessOneYear() { // the aim of this test is verify the fetcher and csvGen entries // so we mock the fetcher output and check both //given LocalDateTime startDate = LocalDateTime.of(2022, Month.FEBRUARY, 1, 0, 0); LocalDateTime endDate = LocalDateTime.of(2023, Month.JANUARY, 7, 12, 0); GLMarketDocument mockedDoc = mock(GLMarketDocument.class); when(fetcher.fetchActualLoad(any(), eq(startDate), eq(endDate))). thenReturn(Optional.of(mockedDoc)); //when
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * * @author Andres Bel Alonso */ @RunWith(MockitoJUnitRunner.class) public class TestENTSOEHistoricalDataRetrieval { private static final Logger LOGGER = LogManager.getLogger(TestENTSOEHistoricalDataRetrieval.class); @Mock private ENTSOEDataFetcher fetcher; @Mock private CSVGenerator csvGen; @InjectMocks private ENTSOEHistoricalDataRetrieval retriever = new ENTSOEHistoricalDataRetrieval("token", Set.of(ColumnType.ACTUAL_LOAD), "\'", ",", false); @Test public void testFetchDatasetActualLoadLessOneYear() { // the aim of this test is verify the fetcher and csvGen entries // so we mock the fetcher output and check both //given LocalDateTime startDate = LocalDateTime.of(2022, Month.FEBRUARY, 1, 0, 0); LocalDateTime endDate = LocalDateTime.of(2023, Month.JANUARY, 7, 12, 0); GLMarketDocument mockedDoc = mock(GLMarketDocument.class); when(fetcher.fetchActualLoad(any(), eq(startDate), eq(endDate))). thenReturn(Optional.of(mockedDoc)); //when
File file = retriever.fetchDataset(startDate, endDate, Duration.ofMinutes(60), Set.of(Area.MONTENEGRO),
3
2023-10-30 09:09:53+00:00
16k
EricFan2002/SC2002
src/app/ui/camp/enquiriesview/OverlayCampInfoDisplayEnquiries.java
[ { "identifier": "RepositoryCollection", "path": "src/app/entity/RepositoryCollection.java", "snippet": "public class RepositoryCollection {\n\n /**\n * The repository for user objects.\n */\n private static UserList userRepository;\n\n /**\n * The repository for camp objects.\n ...
import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.enquiry.Enquiry; import app.entity.enquiry.EnquiryList; import app.entity.user.Student; import app.ui.camp.infomationview.OverlayCampInfoDisplayView; import app.ui.overlayactions.OverlayChooseBox; import app.ui.overlayactions.OverlayNotification; import app.ui.overlayactions.OverlayTextInputAction; import app.ui.widgets.*; import app.ui.windows.ICallBack; import app.ui.windows.Window; import java.util.ArrayList;
13,729
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView and implements ICallBack. * This class manages the display and interactions related to camp enquiries within an overlay view. */ public class OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView implements ICallBack { protected WidgetLabel labelNewEnq; protected WidgetTextBox textBoxEnq; protected WidgetButton sendButton; protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean editEnq = false; public OverlayCampInfoDisplayEnquiries(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>();
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView and implements ICallBack. * This class manages the display and interactions related to camp enquiries within an overlay view. */ public class OverlayCampInfoDisplayEnquiries extends OverlayCampInfoDisplayView implements ICallBack { protected WidgetLabel labelNewEnq; protected WidgetTextBox textBoxEnq; protected WidgetButton sendButton; protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean editEnq = false; public OverlayCampInfoDisplayEnquiries(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>();
EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp);
3
2023-11-01 05:18:29+00:00
16k
TNO/PPS
plugins/nl.esi.pps.tmsc/xtend-gen/nl/esi/pps/tmsc/validation/DefaultTmscValidator.java
[ { "identifier": "Function", "path": "plugins/nl.esi.pps.architecture/src-gen/nl/esi/pps/architecture/implemented/Function.java", "snippet": "public interface Function extends NamedArchitectureElement {\n\t/**\n\t * Returns the value of the '<em><b>Operation</b></em>' reference.\n\t * <!-- begin-user-doc...
import com.google.common.base.Objects; import nl.esi.pps.architecture.implemented.Function; import nl.esi.pps.architecture.specified.Component; import nl.esi.pps.common.emf.ecore.validation.EValidatorBase; import nl.esi.pps.common.emf.ecore.validation.ValidationReporter; import nl.esi.pps.tmsc.Dependency; import nl.esi.pps.tmsc.EntryEvent; import nl.esi.pps.tmsc.Event; import nl.esi.pps.tmsc.Execution; import nl.esi.pps.tmsc.ExitEvent; import nl.esi.pps.tmsc.Lifeline; import nl.esi.pps.tmsc.LifelineSegment; import nl.esi.pps.tmsc.ScopedTMSC; import nl.esi.pps.tmsc.TMSC; import nl.esi.pps.tmsc.TmscPlugin; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.xbase.lib.Extension;
14,078
/** * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.validation; @SuppressWarnings("all") public class DefaultTmscValidator extends EValidatorBase { public DefaultTmscValidator() { super(TmscPlugin.PLUGIN_ID); } @Override
/** * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.validation; @SuppressWarnings("all") public class DefaultTmscValidator extends EValidatorBase { public DefaultTmscValidator() { super(TmscPlugin.PLUGIN_ID); } @Override
public void validate(final EClass eClass, final EObject eObject, final ValidationReporter reporter) {
3
2023-10-30 16:00:25+00:00
16k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/block/custom/ObsidilithSummonBlock.java
[ { "identifier": "BMDBlocks", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/block/BMDBlocks.java", "snippet": "public class BMDBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, BMDConstants.MOD_ID);\n\n public...
import com.cerbon.bosses_of_mass_destruction.block.BMDBlocks; import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithEntity; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.cerbons_api.api.general.event.EventScheduler; import com.cerbon.cerbons_api.api.general.event.TimedEvent; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.cerbon.cerbons_api.capability.CerbonsApiCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.BlockGetter; 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.EndPortalFrameBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
11,825
package com.cerbon.bosses_of_mass_destruction.block.custom; public class ObsidilithSummonBlock extends Block { public static final BooleanProperty eye = BlockStateProperties.EYE; protected final VoxelShape frameShape = box(0.0, 0.0, 0.0, 16.0, 13.0, 16.0); protected final VoxelShape eyeShape = box(4.0, 13.0, 4.0, 12.0, 16.0, 12.0); protected final VoxelShape frameWithEyeShape = Shapes.or(frameShape, eyeShape); public ObsidilithSummonBlock(Properties properties) { super(properties); registerDefaultState(getStateDefinition().any().setValue(eye, false)); } @Override public boolean useShapeForLightOcclusion(@NotNull BlockState state) { return true; } @Override public @NotNull VoxelShape getShape(BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { return state.getValue(eye) ? frameWithEyeShape : frameShape; } @Nullable @Override public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) { return defaultBlockState().setValue(eye, false); } @Override public boolean hasAnalogOutputSignal(@NotNull BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState state, @NotNull Level level, @NotNull BlockPos pos) { return state.getValue(eye) ? 15 : 0; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(eye); } public static void onEnderEyeUsed(UseOnContext context, CallbackInfoReturnable<InteractionResult> cir){ Level level = context.getLevel(); BlockPos blockPos = context.getClickedPos(); BlockState blockState = level.getBlockState(blockPos);
package com.cerbon.bosses_of_mass_destruction.block.custom; public class ObsidilithSummonBlock extends Block { public static final BooleanProperty eye = BlockStateProperties.EYE; protected final VoxelShape frameShape = box(0.0, 0.0, 0.0, 16.0, 13.0, 16.0); protected final VoxelShape eyeShape = box(4.0, 13.0, 4.0, 12.0, 16.0, 12.0); protected final VoxelShape frameWithEyeShape = Shapes.or(frameShape, eyeShape); public ObsidilithSummonBlock(Properties properties) { super(properties); registerDefaultState(getStateDefinition().any().setValue(eye, false)); } @Override public boolean useShapeForLightOcclusion(@NotNull BlockState state) { return true; } @Override public @NotNull VoxelShape getShape(BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { return state.getValue(eye) ? frameWithEyeShape : frameShape; } @Nullable @Override public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) { return defaultBlockState().setValue(eye, false); } @Override public boolean hasAnalogOutputSignal(@NotNull BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState state, @NotNull Level level, @NotNull BlockPos pos) { return state.getValue(eye) ? 15 : 0; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(eye); } public static void onEnderEyeUsed(UseOnContext context, CallbackInfoReturnable<InteractionResult> cir){ Level level = context.getLevel(); BlockPos blockPos = context.getClickedPos(); BlockState blockState = level.getBlockState(blockPos);
if (blockState.is(BMDBlocks.OBSIDILITH_SUMMON_BLOCK.get()) && !blockState.getValue(EndPortalFrameBlock.HAS_EYE)){
0
2023-10-25 16:28:17+00:00
16k
SmartGecko44/Spigot-Admin-Toys
src/main/java/org/gecko/wauh/logic/Scale.java
[ { "identifier": "Main", "path": "src/main/java/org/gecko/wauh/Main.java", "snippet": "public final class Main extends JavaPlugin {\n\n ConfigurationManager configManager;\n FileConfiguration config;\n private int playerRadiusLimit;\n private int tntRadiusLimit;\n private int creeperRadius...
import org.bukkit.block.Block; import org.gecko.wauh.Main; import org.gecko.wauh.listeners.BarrierListener; import org.gecko.wauh.listeners.BedrockListener; import org.gecko.wauh.listeners.BucketListener; import org.gecko.wauh.listeners.WaterBucketListener; import java.util.*;
13,891
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) { Main mainPlugin = Main.getPlugin(Main.class); BucketListener bucketListener = mainPlugin.getBucketListener(); BarrierListener barrierListener = mainPlugin.getBarrierListener();
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) { Main mainPlugin = Main.getPlugin(Main.class); BucketListener bucketListener = mainPlugin.getBucketListener(); BarrierListener barrierListener = mainPlugin.getBarrierListener();
BedrockListener bedrockListener = mainPlugin.getBedrockListener();
2
2023-10-28 11:26:45+00:00
16k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/adapters/InboundsService.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.models.pagination.Page; import com.sinch.sdk.domains.sms.adapters.api.v1.InboundsApi; import com.sinch.sdk.domains.sms.adapters.converters.InboundsDtoConverter; import com.sinch.sdk.domains.sms.models.Inbound; import com.sinch.sdk.domains.sms.models.SMSCursorPageNavigator; import com.sinch.sdk.domains.sms.models.dto.v1.ApiInboundListDto; import com.sinch.sdk.domains.sms.models.dto.v1.InboundDto; import com.sinch.sdk.domains.sms.models.requests.InboundsListRequestParameters; import com.sinch.sdk.domains.sms.models.responses.InboundsListResponse; import com.sinch.sdk.models.Configuration; import java.time.Instant; import java.util.Collection; import java.util.Map;
13,889
package com.sinch.sdk.domains.sms.adapters; public class InboundsService implements com.sinch.sdk.domains.sms.InboundsService { private Configuration configuration; private InboundsApi api; public InboundsService() {} private InboundsApi getApi() { return this.api; } public InboundsService( Configuration configuration, HttpClient httpClient, Map<String, AuthManager> authManagers) { this.configuration = configuration; this.api = new InboundsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); } public InboundsListResponse list() throws ApiException { return this.list(null); } public InboundsListResponse list(InboundsListRequestParameters parameters) throws ApiException { InboundsListRequestParameters guardParameters = null != parameters ? parameters : InboundsListRequestParameters.builder().build(); ApiInboundListDto response = getApi() .listInboundMessages( configuration.getProjectId(), guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null), guardParameters.getTo().map(f -> String.join(",", f)).orElse(null), guardParameters.getStartDate().map(Instant::toString).orElse(null), guardParameters.getEndDate().map(Instant::toString).orElse(null), guardParameters.getClientReference().orElse(null)); Collection<Inbound<?>> content = InboundsDtoConverter.convert(response);
package com.sinch.sdk.domains.sms.adapters; public class InboundsService implements com.sinch.sdk.domains.sms.InboundsService { private Configuration configuration; private InboundsApi api; public InboundsService() {} private InboundsApi getApi() { return this.api; } public InboundsService( Configuration configuration, HttpClient httpClient, Map<String, AuthManager> authManagers) { this.configuration = configuration; this.api = new InboundsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); } public InboundsListResponse list() throws ApiException { return this.list(null); } public InboundsListResponse list(InboundsListRequestParameters parameters) throws ApiException { InboundsListRequestParameters guardParameters = null != parameters ? parameters : InboundsListRequestParameters.builder().build(); ApiInboundListDto response = getApi() .listInboundMessages( configuration.getProjectId(), guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null), guardParameters.getTo().map(f -> String.join(",", f)).orElse(null), guardParameters.getStartDate().map(Instant::toString).orElse(null), guardParameters.getEndDate().map(Instant::toString).orElse(null), guardParameters.getClientReference().orElse(null)); Collection<Inbound<?>> content = InboundsDtoConverter.convert(response);
SMSCursorPageNavigator navigator =
8
2023-10-31 08:32:59+00:00
16k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/DashscopeCommand.java
[ { "identifier": "SpCoBot", "path": "src/main/java/top/spco/SpCoBot.java", "snippet": "public class SpCoBot {\n private static SpCoBot instance;\n public static Logger logger;\n public static File dataFolder;\n public static File configFolder;\n public long botId;\n public long botOwner...
import java.util.List; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.utils.Constants; import top.spco.SpCoBot; import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.User; import top.spco.api.message.Message; import top.spco.core.config.DashScopeSettings; import top.spco.service.command.AbstractCommand; import top.spco.service.command.CommandMeta; import top.spco.service.command.CommandParam; import top.spco.service.command.CommandUsage; import top.spco.service.dashscope.DashScope; import top.spco.user.BotUser;
10,820
/* * Copyright 2023 SpCo * * 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 top.spco.service.command.commands; /** * @author SpCo * @version 1.0.0 * @since 0.2.1 */ public class DashscopeCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"dashscope"}; } @Override public String getDescriptions() { return "调用一次DashScope模型"; } @Override public List<CommandUsage> getUsages() { return List.of(new CommandUsage(getLabels()[0], getDescriptions(), new CommandParam("内容", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public void init() { Constants.apiKey = SpCoBot.getInstance().getSettings().getProperty(DashScopeSettings.API_KET).toString(); } @Override
/* * Copyright 2023 SpCo * * 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 top.spco.service.command.commands; /** * @author SpCo * @version 1.0.0 * @since 0.2.1 */ public class DashscopeCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"dashscope"}; } @Override public String getDescriptions() { return "调用一次DashScope模型"; } @Override public List<CommandUsage> getUsages() { return List.of(new CommandUsage(getLabels()[0], getDescriptions(), new CommandParam("内容", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public void init() { Constants.apiKey = SpCoBot.getInstance().getSettings().getProperty(DashScopeSettings.API_KET).toString(); } @Override
public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) {
3
2023-10-26 10:27:47+00:00
16k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/service/infra/codegen/inner/CodegenEngine.java
[ { "identifier": "ServiceExceptionUtil", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/util/ServiceExceptionUtil.java", "snippet": "@Slf4j\npublic class ServiceExceptionUtil {\n\n /**\n * 错误码提示模板\n */\n private static final Concurren...
import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.engine.velocity.VelocityEngine; import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageParam; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils; import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat; import cn.iocoder.yudao.framework.excel.core.convert.DictConvert; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum; import cn.iocoder.yudao.service.convert.infra.codegen.CodegenConvert; import cn.iocoder.yudao.service.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.service.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.service.framework.codegen.config.SchemaHistory; import cn.iocoder.yudao.service.model.infra.codegen.*; import cn.iocoder.yudao.service.repository.infra.codegen.*; import cn.iocoder.yudao.service.vo.infra.codegen.database.DatabaseUpdateReq; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.*; import static cn.hutool.core.map.MapUtil.getStr; import static cn.hutool.core.text.CharSequenceUtil.*;
12,126
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName());
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName());
globalBindingMap.put("LocalDateTimeUtilsClassName", LocalDateTimeUtils.class.getName());
5
2023-10-27 06:35:24+00:00
16k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/SampleTankDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<Sequence...
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.TankDrive; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; 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.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; 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.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;
11,052
package org.firstinspires.ftc.teamcode.RoadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); // add/remove motors depending on your robot (e.g., 6WD) DcMotorEx leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); DcMotorEx leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); DcMotorEx rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); DcMotorEx rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); leftMotors = Arrays.asList(leftFront, leftRear); rightMotors = Arrays.asList(rightFront, rightRear); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>() ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, accelConstraint); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, accelConstraint, DriveConstants.MAX_ANG_VEL, DriveConstants.MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); }
package org.firstinspires.ftc.teamcode.RoadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); // add/remove motors depending on your robot (e.g., 6WD) DcMotorEx leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); DcMotorEx leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); DcMotorEx rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); DcMotorEx rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); leftMotors = Arrays.asList(leftFront, leftRear); rightMotors = Arrays.asList(rightFront, rightRear); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>() ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, accelConstraint); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, accelConstraint, DriveConstants.MAX_ANG_VEL, DriveConstants.MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); }
public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {
0
2023-10-31 16:06:46+00:00
16k
slatepowered/slate
slate-cluster/src/main/java/slatepowered/slate/cluster/ClusterInstance.java
[ { "identifier": "CommunicationKey", "path": "slate-common/src/main/java/slatepowered/slate/communication/CommunicationKey.java", "snippet": "public class CommunicationKey {\r\n\r\n public static class ClusterDeclareCommunicationKey extends CommunicationKey {\r\n @Override\r\n public int...
import slatepowered.slate.allocation.*; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.model.ClusterManagedNode; import slatepowered.slate.model.ClusterNetwork; import slatepowered.slate.model.Node; import slatepowered.slate.model.NodeComponent; import slatepowered.slate.action.NodeAllocationAdapter; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageAttachment; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.Packages; import slatepowered.slate.packages.service.LateAttachmentService; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.collection.Sequence; import slatepowered.veru.misc.Throwables; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture;
12,232
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true; public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.cluster = cluster; this.directory = cluster.getInstanceDirectory(this); cluster.getPluginManager().initialize(this); try { Files.createDirectories(directory); } catch (Throwable t) { Throwables.sneakyThrow(t); } } /** * Set if this cluster instance is enabled. * * When disabled a cluster instance will not accept allocation * or destruction of nodes, essentially sitting idle. * * @param enabled Enable flag. * @return This. */ public ClusterInstance setEnabled(boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { return enabled; } public Cluster getCluster() { return cluster; } // first check registered nodes, otherwise // fetch the info about a node remotely // and create it as a non-managed node private Node fetchAndCreateNode(String name) { Node node = getNode(name); if (node == null) { NetworkInfoService.NodeInfo nodeInfo = getService(NetworkInfoService.KEY) .fetchNodeInfo(name); node = new Node(nodeInfo.getName(), this) { @Override public String[] getTags() { return nodeInfo.getTags(); } }; } return node; } /** * Closes this cluster instance. */ public void close() { cluster.getPluginManager().disable(this); cluster.closeInstance(this); } /** * Get the allocation checker to check availability. * * @return The allocation checker. */ protected ClusterAllocationChecker getAllocationChecker() { return null; } /** * Attempts to allocate and initialize a node following the given request. * * @param request The allocation request. * @return The allocation result. */ @SuppressWarnings("unchecked") public ClusterManagedNode allocateAndInitializeNode(NodeAllocationRequest request) { try { NetworkInfoService networkInfoService = getService(NetworkInfoService.KEY); // create node locally LOGGER.debug("Allocating node with name(" + request.getNodeName() + ") with componentCount(" + request.getComponents().size() + ")"); ClusterManagedNode node = new ClusterManagedNode( fetchAndCreateNode(request.getParentNodeName()), request.getNodeName(), ClusterInstance.this, (List<NodeComponent>)(Object)request.getComponents(), request.getTags() ) { }; // create allocation LocalNodeAllocation localNodeAllocation = new LocalNodeAllocation(node, directory.resolve("nodes").resolve(node.getName())); cluster.localAllocations.add(localNodeAllocation); Files.createDirectories(localNodeAllocation.getDirectory()); LOGGER.debug("Created allocation for node(" + node.getName() + ") in directory(" + directory + ")"); // install packages PackageManager packageManager = cluster.getLocalPackageManager();
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true; public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.cluster = cluster; this.directory = cluster.getInstanceDirectory(this); cluster.getPluginManager().initialize(this); try { Files.createDirectories(directory); } catch (Throwable t) { Throwables.sneakyThrow(t); } } /** * Set if this cluster instance is enabled. * * When disabled a cluster instance will not accept allocation * or destruction of nodes, essentially sitting idle. * * @param enabled Enable flag. * @return This. */ public ClusterInstance setEnabled(boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { return enabled; } public Cluster getCluster() { return cluster; } // first check registered nodes, otherwise // fetch the info about a node remotely // and create it as a non-managed node private Node fetchAndCreateNode(String name) { Node node = getNode(name); if (node == null) { NetworkInfoService.NodeInfo nodeInfo = getService(NetworkInfoService.KEY) .fetchNodeInfo(name); node = new Node(nodeInfo.getName(), this) { @Override public String[] getTags() { return nodeInfo.getTags(); } }; } return node; } /** * Closes this cluster instance. */ public void close() { cluster.getPluginManager().disable(this); cluster.closeInstance(this); } /** * Get the allocation checker to check availability. * * @return The allocation checker. */ protected ClusterAllocationChecker getAllocationChecker() { return null; } /** * Attempts to allocate and initialize a node following the given request. * * @param request The allocation request. * @return The allocation result. */ @SuppressWarnings("unchecked") public ClusterManagedNode allocateAndInitializeNode(NodeAllocationRequest request) { try { NetworkInfoService networkInfoService = getService(NetworkInfoService.KEY); // create node locally LOGGER.debug("Allocating node with name(" + request.getNodeName() + ") with componentCount(" + request.getComponents().size() + ")"); ClusterManagedNode node = new ClusterManagedNode( fetchAndCreateNode(request.getParentNodeName()), request.getNodeName(), ClusterInstance.this, (List<NodeComponent>)(Object)request.getComponents(), request.getTags() ) { }; // create allocation LocalNodeAllocation localNodeAllocation = new LocalNodeAllocation(node, directory.resolve("nodes").resolve(node.getName())); cluster.localAllocations.add(localNodeAllocation); Files.createDirectories(localNodeAllocation.getDirectory()); LOGGER.debug("Created allocation for node(" + node.getName() + ") in directory(" + directory + ")"); // install packages PackageManager packageManager = cluster.getLocalPackageManager();
Packages.attachAll(
12
2023-10-30 08:58:02+00:00
16k
Melledy/LunarCore
src/main/java/emu/lunarcore/LunarCore.java
[ { "identifier": "PluginManager", "path": "src/main/java/emu/lunarcore/plugin/PluginManager.java", "snippet": "@Getter\npublic final class PluginManager {\n /*\n * This should only be changed when a breaking change is made to the plugin API.\n * A 'breaking change' is something which changes t...
import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import emu.lunarcore.plugin.PluginManager; import org.jline.reader.EndOfFileException; import org.jline.reader.LineReaderBuilder; import org.jline.reader.UserInterruptException; import org.jline.reader.impl.LineReaderImpl; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import emu.lunarcore.command.CommandManager; import emu.lunarcore.data.ResourceLoader; import emu.lunarcore.database.DatabaseManager; import emu.lunarcore.server.game.GameServer; import emu.lunarcore.server.http.HttpServer; import emu.lunarcore.util.Handbook; import emu.lunarcore.util.JsonUtils; import lombok.Getter;
13,436
package emu.lunarcore; public class LunarCore { private static final Logger log = LoggerFactory.getLogger(LunarCore.class); private static File configFile = new File("./config.json"); @Getter private static Config config; @Getter private static DatabaseManager accountDatabase; @Getter private static DatabaseManager gameDatabase; @Getter private static HttpServer httpServer; @Getter private static GameServer gameServer; @Getter private static CommandManager commandManager; @Getter private static PluginManager pluginManager; @Getter private static ServerType serverType = ServerType.BOTH; private static LineReaderImpl reader; @Getter private static boolean usingDumbTerminal; private static long timeOffset = 0; static { // Setup console reader try { reader = (LineReaderImpl) LineReaderBuilder.builder() .terminal(TerminalBuilder.builder().dumb(true).build()) .build(); usingDumbTerminal = Terminal.TYPE_DUMB.equals(reader.getTerminal().getType()); } catch (IOException e) { e.printStackTrace(); } // Load config LunarCore.loadConfig(); LunarCore.updateServerTimeOffset(); } public static void main(String[] args) { // Start Server LunarCore.getLogger().info("Starting Lunar Core " + getJarVersion()); LunarCore.getLogger().info("Git hash: " + getGitHash()); LunarCore.getLogger().info("Game version: " + GameConstants.VERSION); boolean generateHandbook = true; // Load commands LunarCore.commandManager = new CommandManager(); // Load plugin manager LunarCore.pluginManager = new PluginManager(); try { LunarCore.getPluginManager().loadPlugins(); } catch (Exception exception) { LunarCore.getLogger().error("Unable to load plugins.", exception); } // Parse arguments for (String arg : args) { switch (arg) { case "-dispatch": serverType = ServerType.DISPATCH; break; case "-game": serverType = ServerType.GAME; break; case "-nohandbook": case "-skiphandbook": generateHandbook = false; break; case "-database": // Database only DatabaseManager.startInternalMongoServer(LunarCore.getConfig().getInternalMongoServer()); LunarCore.getLogger().info("Running local mongo server at " + DatabaseManager.getServer().getConnectionString()); // Console LunarCore.startConsole(); return; } } // Skip these if we are only running the http server in dispatch mode if (serverType.runGame()) { // Load resources ResourceLoader.loadAll(); // Build handbook if (generateHandbook) {
package emu.lunarcore; public class LunarCore { private static final Logger log = LoggerFactory.getLogger(LunarCore.class); private static File configFile = new File("./config.json"); @Getter private static Config config; @Getter private static DatabaseManager accountDatabase; @Getter private static DatabaseManager gameDatabase; @Getter private static HttpServer httpServer; @Getter private static GameServer gameServer; @Getter private static CommandManager commandManager; @Getter private static PluginManager pluginManager; @Getter private static ServerType serverType = ServerType.BOTH; private static LineReaderImpl reader; @Getter private static boolean usingDumbTerminal; private static long timeOffset = 0; static { // Setup console reader try { reader = (LineReaderImpl) LineReaderBuilder.builder() .terminal(TerminalBuilder.builder().dumb(true).build()) .build(); usingDumbTerminal = Terminal.TYPE_DUMB.equals(reader.getTerminal().getType()); } catch (IOException e) { e.printStackTrace(); } // Load config LunarCore.loadConfig(); LunarCore.updateServerTimeOffset(); } public static void main(String[] args) { // Start Server LunarCore.getLogger().info("Starting Lunar Core " + getJarVersion()); LunarCore.getLogger().info("Git hash: " + getGitHash()); LunarCore.getLogger().info("Game version: " + GameConstants.VERSION); boolean generateHandbook = true; // Load commands LunarCore.commandManager = new CommandManager(); // Load plugin manager LunarCore.pluginManager = new PluginManager(); try { LunarCore.getPluginManager().loadPlugins(); } catch (Exception exception) { LunarCore.getLogger().error("Unable to load plugins.", exception); } // Parse arguments for (String arg : args) { switch (arg) { case "-dispatch": serverType = ServerType.DISPATCH; break; case "-game": serverType = ServerType.GAME; break; case "-nohandbook": case "-skiphandbook": generateHandbook = false; break; case "-database": // Database only DatabaseManager.startInternalMongoServer(LunarCore.getConfig().getInternalMongoServer()); LunarCore.getLogger().info("Running local mongo server at " + DatabaseManager.getServer().getConnectionString()); // Console LunarCore.startConsole(); return; } } // Skip these if we are only running the http server in dispatch mode if (serverType.runGame()) { // Load resources ResourceLoader.loadAll(); // Build handbook if (generateHandbook) {
Handbook.generate();
6
2023-10-10 12:57:35+00:00
16k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/loader/LoaderUtils.java
[ { "identifier": "CorruptedWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/CorruptedWorldException.java", "snippet": "public class CorruptedWorldException extends SlimeException {\n\n public CorruptedWorldException(String world) {\n this(world, null)...
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import com.flowpowered.nbt.DoubleTag; import com.flowpowered.nbt.IntArrayTag; import com.flowpowered.nbt.IntTag; import com.flowpowered.nbt.ListTag; import com.flowpowered.nbt.stream.NBTInputStream; import com.github.luben.zstd.Zstd; import net.swofty.swm.api.exceptions.CorruptedWorldException; import net.swofty.swm.api.exceptions.NewerFormatException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.utils.NibbleArray; import net.swofty.swm.api.utils.SlimeFormat; import net.swofty.swm.api.world.SlimeChunk; import net.swofty.swm.api.world.SlimeChunkSection; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeChunk; import net.swofty.swm.nms.craft.CraftSlimeChunkSection; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.config.DatasourcesConfig; import net.swofty.swm.plugin.loader.loaders.FileLoader; import net.swofty.swm.plugin.loader.loaders.MongoLoader; import net.swofty.swm.plugin.loader.loaders.MysqlLoader; import net.swofty.swm.plugin.log.Logging; import com.mongodb.MongoException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.sql.SQLException; import java.util.*;
13,498
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() {
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() {
DatasourcesConfig config = ConfigManager.getDatasourcesConfig();
12
2023-10-08 10:54:28+00:00
16k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/RepairImpl.java
[ { "identifier": "Repair", "path": "src/main/java/zju/cst/aces/api/Repair.java", "snippet": "public interface Repair {\n\n String ruleBasedRepair(String code);\n String LLMBasedRepair(String code);\n String LLMBasedRepair(String code, int rounds);\n\n}" }, { "identifier": "Validator", ...
import lombok.Data; import okhttp3.Response; import zju.cst.aces.api.Repair; import zju.cst.aces.api.Validator; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.runner.MethodRunner; import java.io.IOException; import static zju.cst.aces.runner.AbstractRunner.*; import static zju.cst.aces.api.impl.ChatGenerator.*;
12,967
package zju.cst.aces.api.impl; @Data public class RepairImpl implements Repair { Config config; PromptConstructorImpl promptConstructorImpl; boolean success = false; public RepairImpl(Config config, PromptConstructorImpl promptConstructorImpl) { this.config = config; this.promptConstructorImpl = promptConstructorImpl; } @Override public String ruleBasedRepair(String code) { code = changeTestName(code, promptConstructorImpl.getTestName()); code = repairPackage(code, promptConstructorImpl.getPromptInfo().getClassInfo().getPackageName()); code = repairImports(code, promptConstructorImpl.getPromptInfo().getClassInfo().getImports()); return code; } @Override public String LLMBasedRepair(String code, int rounds) {
package zju.cst.aces.api.impl; @Data public class RepairImpl implements Repair { Config config; PromptConstructorImpl promptConstructorImpl; boolean success = false; public RepairImpl(Config config, PromptConstructorImpl promptConstructorImpl) { this.config = config; this.promptConstructorImpl = promptConstructorImpl; } @Override public String ruleBasedRepair(String code) { code = changeTestName(code, promptConstructorImpl.getTestName()); code = repairPackage(code, promptConstructorImpl.getPromptInfo().getClassInfo().getPackageName()); code = repairImports(code, promptConstructorImpl.getPromptInfo().getClassInfo().getImports()); return code; } @Override public String LLMBasedRepair(String code, int rounds) {
PromptInfo promptInfo = promptConstructorImpl.getPromptInfo();
3
2023-10-14 07:15:10+00:00
16k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/gamestates/Playing.java
[ { "identifier": "LevelManager", "path": "src/Level/LevelManager.java", "snippet": "public class LevelManager {\n\n\tprivate Game game;\n\tprivate BufferedImage[] levelSprite;\n\tprivate ArrayList<levels> Levels;\n\tprivate int lvlIndex = 0;\n\n\tpublic LevelManager(Game game) {\n\t\tthis.game = game;\n\...
import Level.LevelManager; import UI.GameOverOverlay; import UI.LevelCompleted; import UI.PauseOverlay; import entities.EnemyManager; import entities.Player; import main.Game; import utilz.LoadSave; import objects.ObjectManager; import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Random; import static utilz.Constants.Environment.*;
11,826
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager;
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager;
private EnemyManager enemyManager;
4
2023-10-07 12:07:45+00:00
16k
yc-huang/bsdb
src/main/java/tech/bsdb/read/Reader.java
[ { "identifier": "GOVMinimalPerfectHashFunctionModified", "path": "src/main/java/it/unimi/dsi/sux4j/mph/GOVMinimalPerfectHashFunctionModified.java", "snippet": "public class GOVMinimalPerfectHashFunctionModified<T> extends AbstractHashFunction<T> implements Serializable {\n public static final long se...
import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.sux4j.mph.GOVMinimalPerfectHashFunction; import it.unimi.dsi.sux4j.mph.GOVMinimalPerfectHashFunctionModified; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; import tech.bsdb.read.kv.KVReader; import tech.bsdb.serde.Field; import tech.bsdb.util.Common; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.channels.CompletionHandler; import java.nio.file.Files; import java.util.Objects;
11,135
package tech.bsdb.read; public abstract class Reader { protected File idxFile; protected File kvFile; protected long idxCapacity; protected boolean approximateMode; protected GOVMinimalPerfectHashFunctionModified<byte[]> hashFunction; private Configuration config; private Field[] valueSchema; public Reader(File basePath, boolean approximate) throws IOException, ClassNotFoundException { this.hashFunction = (GOVMinimalPerfectHashFunctionModified<byte[]>) BinIO.loadObject(new File(basePath, Common.FILE_NAME_KEY_HASH)); this.approximateMode = approximate; this.idxFile = new File(basePath, approximate ? Common.FILE_NAME_KV_APPROXIMATE_INDEX : Common.FILE_NAME_KV_INDEX); this.kvFile = new File(basePath, Common.FILE_NAME_KV_DATA); try { this.config = new Configurations().properties(new File(basePath, Common.FILE_NAME_CONFIG)); } catch (ConfigurationException e) { throw new RuntimeException(e); } File schemaFile = new File(basePath, Common.FILE_NAME_VALUE_SCHEMA); if (schemaFile.exists()) { this.valueSchema = (Field[]) BinIO.loadObject(schemaFile); } } public Field[] getValueSchema() { return this.valueSchema; } public Configuration getConfig(){ return this.config; } public boolean isCompressed(){ return config.getBoolean(Common.CONFIG_KEY_KV_COMPRESS); } public boolean isCompact(){ return config.getBoolean(Common.CONFIG_KEY_KV_COMPACT); } protected long checkAndGetIndex(byte[] key) { if (!Objects.isNull(key)) { return hashFunction.getLong(key); } else { return -1; } } public interface IndexCompletionHandler {
package tech.bsdb.read; public abstract class Reader { protected File idxFile; protected File kvFile; protected long idxCapacity; protected boolean approximateMode; protected GOVMinimalPerfectHashFunctionModified<byte[]> hashFunction; private Configuration config; private Field[] valueSchema; public Reader(File basePath, boolean approximate) throws IOException, ClassNotFoundException { this.hashFunction = (GOVMinimalPerfectHashFunctionModified<byte[]>) BinIO.loadObject(new File(basePath, Common.FILE_NAME_KEY_HASH)); this.approximateMode = approximate; this.idxFile = new File(basePath, approximate ? Common.FILE_NAME_KV_APPROXIMATE_INDEX : Common.FILE_NAME_KV_INDEX); this.kvFile = new File(basePath, Common.FILE_NAME_KV_DATA); try { this.config = new Configurations().properties(new File(basePath, Common.FILE_NAME_CONFIG)); } catch (ConfigurationException e) { throw new RuntimeException(e); } File schemaFile = new File(basePath, Common.FILE_NAME_VALUE_SCHEMA); if (schemaFile.exists()) { this.valueSchema = (Field[]) BinIO.loadObject(schemaFile); } } public Field[] getValueSchema() { return this.valueSchema; } public Configuration getConfig(){ return this.config; } public boolean isCompressed(){ return config.getBoolean(Common.CONFIG_KEY_KV_COMPRESS); } public boolean isCompact(){ return config.getBoolean(Common.CONFIG_KEY_KV_COMPACT); } protected long checkAndGetIndex(byte[] key) { if (!Objects.isNull(key)) { return hashFunction.getLong(key); } else { return -1; } } public interface IndexCompletionHandler {
public void completed(Long addr, KVReader reader, byte[] key, CompletionHandler<byte[], Object> appHandler, Object appAttach);
1
2023-10-07 03:32:27+00:00
16k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/TableRow.java
[ { "identifier": "Format", "path": "src/main/java/net/wiseoldman/util/Format.java", "snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n ...
import net.wiseoldman.util.Format; import net.wiseoldman.util.Utils; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.Boss; import net.wiseoldman.beans.Activity; import net.wiseoldman.beans.Skill; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Experience; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import net.runelite.client.util.ImageUtil; import net.runelite.client.util.QuantityFormatter; import net.runelite.client.hiscore.HiscoreSkill; import net.runelite.client.hiscore.HiscoreSkillType; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.HashMap; import java.util.Map;
11,657
/* * Copyright (c) 2021, Rorro <https://github.com/rorro> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.wiseoldman.panel; @Slf4j public class TableRow extends JPanel { private static final int ICON_WIDTH = 35; Map<String, JLabel> labels = new HashMap<>(); TableRow(String name, String formattedName, HiscoreSkillType type, String... labels) { setLayout(new BorderLayout()); setBorder(new EmptyBorder(2, 0, 2, 0)); setBackground(ColorScheme.DARKER_GRAY_COLOR); JPanel dataPanel = new JPanel(new GridLayout()); dataPanel.setOpaque(false); final String directory; if (type == HiscoreSkillType.BOSS) { directory = "bosses/"; } else if (type == HiscoreSkillType.ACTIVITY) { directory = "activities/"; } else { directory = "/skill_icons_small/"; } for (String l : labels) { dataPanel.add(createCell(l)); } String iconDirectory = directory + name.toLowerCase() + ".png"; log.debug("Loading icon for {}", iconDirectory); JPanel iconPanel = new JPanel(new BorderLayout()); iconPanel.setOpaque(false); JLabel iconLabel = new JLabel("", SwingConstants.CENTER); iconPanel.add(iconLabel); ImageIcon icon = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, iconDirectory)); iconPanel.setPreferredSize(new Dimension(ICON_WIDTH, icon.getIconHeight())); iconLabel.setIcon(icon); iconLabel.setToolTipText(formattedName); add(iconPanel, BorderLayout.WEST); add(dataPanel); } private JLabel createCell(String l) { JLabel label = new JLabel("--", SwingConstants.CENTER); label.setFont(FontManager.getRunescapeSmallFont()); labels.put(l, label); return label; } void update(Skill skill, boolean virtualLevels) { long experience = skill.getExperience(); int level = skill.getLevel(); int rank = skill.getRank(); boolean ranked = rank != -1; double ehp = skill.getEhp(); JLabel experienceLabel = labels.get("experience"); experienceLabel.setText(experience > 0 ? Format.formatNumber(experience) : "--"); experienceLabel.setToolTipText(experience > 0 ? QuantityFormatter.formatNumber(experience) : ""); JLabel levelLabel = labels.get("level"); int levelToDisplay = !virtualLevels && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level; levelLabel.setText(String.valueOf(levelToDisplay)); levelLabel.setToolTipText(String.valueOf(levelToDisplay)); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehpLabel = labels.get("ehp"); ehpLabel.setText(Format.formatNumber(ehp)); ehpLabel.setToolTipText(QuantityFormatter.formatNumber(ehp)); } void update(Boss boss, HiscoreSkill b) { int kills = boss.getKills(); int minimumKc = Utils.getMinimumKc(b); boolean ranked = kills >= minimumKc; int rank = boss.getRank(); double ehb = boss.getEhb(); JLabel killsLabel = labels.get("kills"); killsLabel.setText(ranked ? Format.formatNumber(kills) : "< " + minimumKc); killsLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(kills) : "The Hiscores only start tracking " + b.getName() + " after " + minimumKc + " kc"); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehbLabel = labels.get("ehb"); ehbLabel.setText(Format.formatNumber(ehb)); ehbLabel.setToolTipText(QuantityFormatter.formatNumber(ehb)); }
/* * Copyright (c) 2021, Rorro <https://github.com/rorro> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.wiseoldman.panel; @Slf4j public class TableRow extends JPanel { private static final int ICON_WIDTH = 35; Map<String, JLabel> labels = new HashMap<>(); TableRow(String name, String formattedName, HiscoreSkillType type, String... labels) { setLayout(new BorderLayout()); setBorder(new EmptyBorder(2, 0, 2, 0)); setBackground(ColorScheme.DARKER_GRAY_COLOR); JPanel dataPanel = new JPanel(new GridLayout()); dataPanel.setOpaque(false); final String directory; if (type == HiscoreSkillType.BOSS) { directory = "bosses/"; } else if (type == HiscoreSkillType.ACTIVITY) { directory = "activities/"; } else { directory = "/skill_icons_small/"; } for (String l : labels) { dataPanel.add(createCell(l)); } String iconDirectory = directory + name.toLowerCase() + ".png"; log.debug("Loading icon for {}", iconDirectory); JPanel iconPanel = new JPanel(new BorderLayout()); iconPanel.setOpaque(false); JLabel iconLabel = new JLabel("", SwingConstants.CENTER); iconPanel.add(iconLabel); ImageIcon icon = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, iconDirectory)); iconPanel.setPreferredSize(new Dimension(ICON_WIDTH, icon.getIconHeight())); iconLabel.setIcon(icon); iconLabel.setToolTipText(formattedName); add(iconPanel, BorderLayout.WEST); add(dataPanel); } private JLabel createCell(String l) { JLabel label = new JLabel("--", SwingConstants.CENTER); label.setFont(FontManager.getRunescapeSmallFont()); labels.put(l, label); return label; } void update(Skill skill, boolean virtualLevels) { long experience = skill.getExperience(); int level = skill.getLevel(); int rank = skill.getRank(); boolean ranked = rank != -1; double ehp = skill.getEhp(); JLabel experienceLabel = labels.get("experience"); experienceLabel.setText(experience > 0 ? Format.formatNumber(experience) : "--"); experienceLabel.setToolTipText(experience > 0 ? QuantityFormatter.formatNumber(experience) : ""); JLabel levelLabel = labels.get("level"); int levelToDisplay = !virtualLevels && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level; levelLabel.setText(String.valueOf(levelToDisplay)); levelLabel.setToolTipText(String.valueOf(levelToDisplay)); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehpLabel = labels.get("ehp"); ehpLabel.setText(Format.formatNumber(ehp)); ehpLabel.setToolTipText(QuantityFormatter.formatNumber(ehp)); } void update(Boss boss, HiscoreSkill b) { int kills = boss.getKills(); int minimumKc = Utils.getMinimumKc(b); boolean ranked = kills >= minimumKc; int rank = boss.getRank(); double ehb = boss.getEhb(); JLabel killsLabel = labels.get("kills"); killsLabel.setText(ranked ? Format.formatNumber(kills) : "< " + minimumKc); killsLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(kills) : "The Hiscores only start tracking " + b.getName() + " after " + minimumKc + " kc"); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehbLabel = labels.get("ehb"); ehbLabel.setText(Format.formatNumber(ehb)); ehbLabel.setToolTipText(QuantityFormatter.formatNumber(ehb)); }
void update(Activity minigame)
4
2023-10-09 14:23:06+00:00
16k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/MRPGCMod.java
[ { "identifier": "MoreParticles", "path": "src/main/java/net/more_rpg_classes/client/particle/MoreParticles.java", "snippet": "public class MoreParticles {\n public static final DefaultParticleType IGNI_SIGN = FabricParticleTypes.simple();\n public static final DefaultParticleType AARD_SIGN = Fabri...
import net.fabricmc.api.ModInitializer; import net.more_rpg_classes.client.particle.MoreParticles; import net.more_rpg_classes.custom.custom_spells.CustomSpells; import net.more_rpg_classes.effect.MRPGCEffects; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.more_rpg_classes.item.MRPGCBooks; import net.more_rpg_classes.item.MRPGCGroup; import net.more_rpg_classes.item.MRPGCItems; import net.more_rpg_classes.sounds.ModSounds; import net.more_rpg_classes.util.MRPGCLootTableChestModifiers; import net.more_rpg_classes.util.MRPGCLootTableEntityModifiers; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,453
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables(); MRPGCLootTableChestModifiers.modifyChestLootTables();
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables(); MRPGCLootTableChestModifiers.modifyChestLootTables();
MRPGCEffects.register();
2
2023-10-14 12:44:07+00:00
16k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/Auto.java
[ { "identifier": "SubSys_Photonvision", "path": "src/main/java/frc/robot/library/vision/photonvision/SubSys_Photonvision.java", "snippet": "public class SubSys_Photonvision extends SubsystemBase {\n\n /** Creates a new PhotonVisionSubsytem. */\n public SubSys_Photonvision() {\n\n /* CONFIG PID */\n ...
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import frc.robot.library.vision.photonvision.SubSys_Photonvision; import frc.robot.chargedup.commands.auto.basic.*; import frc.robot.chargedup.commands.auto.singleelement.cube.*; import frc.robot.chargedup.commands.auto.tripleelement.*; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.bling.SubSys_Bling; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
12,041
package frc.robot; /** * The Auto class is responsible for handling the autonomous mode of the robot. It includes a * variety of commands for different tasks such as escaping, state middle leave, state barrier, and * others. The class also includes a SendableChooser object to select the desired command. */ public class Auto { private final SendableChooser<Command> m_chooser = new SendableChooser<>(); /** Constructor for the Auto class. Initializes all the subsystems and commands. */
package frc.robot; /** * The Auto class is responsible for handling the autonomous mode of the robot. It includes a * variety of commands for different tasks such as escaping, state middle leave, state barrier, and * others. The class also includes a SendableChooser object to select the desired command. */ public class Auto { private final SendableChooser<Command> m_chooser = new SendableChooser<>(); /** Constructor for the Auto class. Initializes all the subsystems and commands. */
public Auto(SubSys_Bling blingSubSys, SubSys_Photonvision photonvisionSubSys, SubSys_Hand handSubSys, SubSys_Arm armSubSys, SubSys_PigeonGyro gyroSubSys, SubSys_DriveTrain driveSubSys) {
3
2023-10-09 00:27:11+00:00
16k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/handler/WatchMapHandler.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import com.fasterxml.jackson.databind.ObjectMapper; import com.monitor.agent.server.FileState; import com.monitor.agent.server.FileWatcher; import com.monitor.agent.server.Section; import com.monitor.agent.server.Server; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import java.util.Collection; import java.util.HashMap; import java.util.Map;
11,420
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class WatchMapHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидание снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем имя секции, в пределах которой нужно получить данные об отслеживаемых файлах String sectionName = (String) parameters.get("section", null);
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class WatchMapHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидание снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем имя секции, в пределах которой нужно получить данные об отслеживаемых файлах String sectionName = (String) parameters.get("section", null);
Collection<FileWatcher> watchers = server.getWatchers(Section.byName(sectionName));
2
2023-10-11 20:25:12+00:00
16k
mhaupt/basicode
src/main/java/de/haupz/basicode/ast/GotoNode.java
[ { "identifier": "InterpreterState", "path": "src/main/java/de/haupz/basicode/interpreter/InterpreterState.java", "snippet": "public class InterpreterState {\n\n /**\n * The root node of the program whose state this instance represents.\n */\n private final ProgramNode program;\n\n /**\n...
import de.haupz.basicode.interpreter.InterpreterState; import de.haupz.basicode.subroutines.Subroutines;
12,563
package de.haupz.basicode.ast; /** * <p>{@code GOTO}. The implementation performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a jump to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOTO}.</p> */ public class GotoNode extends StatementNode { private final int target; public GotoNode(int target) { this.target = target; } @Override
package de.haupz.basicode.ast; /** * <p>{@code GOTO}. The implementation performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a jump to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOTO}.</p> */ public class GotoNode extends StatementNode { private final int target; public GotoNode(int target) { this.target = target; } @Override
public void run(InterpreterState state) {
0
2023-10-14 12:20:59+00:00
16k
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/PurchaseRequisitionController.java
[ { "identifier": "PurchaseRequisition", "path": "nhXJH-admin/src/main/java/com/nhXJH/web/domain/PurchaseRequisition.java", "snippet": "@TableName(\"base_purchase_requisition\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PurchaseRequisition extends BaseEntity {\n private s...
import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.web.domain.PurchaseRequisition; import com.nhXJH.web.service.IPurchaseRequisitionService; 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,538
package com.nhXJH.web.controller.appllication; /** * 采购申请信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/requisition") @Api(tags = {"采购申请信息"}) public class PurchaseRequisitionController extends BaseController { @Autowired private IPurchaseRequisitionService purchaseRequisitionService; /** * 查询采购申请信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:requisition:list')") @GetMapping("/list") @ApiOperation(value ="查询采购申请信息列表",notes = "查询采购申请信息列表")
package com.nhXJH.web.controller.appllication; /** * 采购申请信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/requisition") @Api(tags = {"采购申请信息"}) public class PurchaseRequisitionController extends BaseController { @Autowired private IPurchaseRequisitionService purchaseRequisitionService; /** * 查询采购申请信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:requisition:list')") @GetMapping("/list") @ApiOperation(value ="查询采购申请信息列表",notes = "查询采购申请信息列表")
public TableDataInfo list(PurchaseRequisition purchaseRequisition) {
5
2023-10-13 07:19:20+00:00
16k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/core/entities/ConsoleControlEntity.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 mdteam.ait.AITMod; import mdteam.ait.core.AITItems; import mdteam.ait.core.AITSounds; import mdteam.ait.core.blockentities.ConsoleBlockEntity; import mdteam.ait.core.managers.DeltaTimeManager; import mdteam.ait.tardis.console.ConsoleSchema; import mdteam.ait.tardis.control.Control; import mdteam.ait.tardis.control.ControlTypes; import net.minecraft.entity.EntityDimensions; import net.minecraft.entity.EntityPose; import net.minecraft.entity.EntityType; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtHelper; import net.minecraft.network.packet.s2c.play.EntitySpawnS2CPacket; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; import net.minecraft.sound.SoundEvents; import net.minecraft.text.Text; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; import mdteam.ait.tardis.Tardis; import java.util.List; import java.util.Random;
13,814
// this.controlTypes = this.controlTypes.deserializeTypes(nbt); var console = (NbtCompound) nbt.get("console"); if (console != null) this.consoleBlockPos = NbtHelper.toBlockPos(console); if (nbt.contains("identity")) { this.setIdentity(nbt.getString("identity")); } if (nbt.contains("width") && nbt.contains("height")) { this.setControlWidth(nbt.getFloat("width")); this.setControlWidth(nbt.getFloat("height")); this.calculateDimensions(); } if (nbt.contains("offsetX") && nbt.contains("offsetY") && nbt.contains("offsetZ")) { this.setOffset(new Vector3f(nbt.getFloat("offsetX"), nbt.getFloat("offsetY"), nbt.getFloat("offsetZ"))); } } @Override public boolean cannotDespawn() { return true; } @Override public ActionResult interactAt(PlayerEntity player, Vec3d hitPos, Hand hand) { if (player.getOffHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); return ActionResult.SUCCESS; } if (hand == Hand.MAIN_HAND) this.run(player, player.getWorld(), false); return ActionResult.SUCCESS; } @Override public boolean damage(DamageSource source, float amount) { if (source.getAttacker() instanceof PlayerEntity player) { if (player.getOffHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); } else this.run((PlayerEntity) source.getAttacker(), source.getAttacker().getWorld(), true); } return super.damage(source, source.getAttacker() instanceof PlayerEntity ? 0 : amount); } public boolean run(PlayerEntity player, World world, boolean leftClick) { Random random = new Random(); int chance_int = random.nextInt(1, 10_000); if (chance_int == 72) { // play sound this.getWorld().playSound(null, this.getBlockPos(), AITSounds.EVEN_MORE_SECRET_MUSIC, SoundCategory.MASTER, 1F, 1F); } if (this.consoleBlockPos != null) this.getWorld().playSound(null, this.getBlockPos(), this.control.getSound(), SoundCategory.BLOCKS, 0.7f, 1f); if (!world.isClient()) { if (player.getMainHandStack().getItem() == AITItems.TARDIS_ITEM) { this.remove(RemovalReason.DISCARDED); }/* else if (player.getMainHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); }*/ if (this.getTardis() == null) return false; // AAAAAAAAAAA //blahblah //if (DeltaTimeManager.isStillWaitingOnDelay(getDelayId(this.getTardis()))) return false; //DeltaTimeManager.createDelay(getDelayId(this.getTardis()), 500L); control.runAnimation(getTardis(world), (ServerPlayerEntity) player, (ServerWorld) world); if (this.getTardis(world) == null) { this.discard(); AITMod.LOGGER.warn("Discarding invalid control entity at " + this.getPos()); return false; } if (control.shouldFailOnNoPower() && !this.getTardis(world).hasPower()) { return false; } if (this.isOnDelay()) return false; if (this.control.shouldHaveDelay() && !this.isOnDelay()) { this.createDelay(this.control.getDelayLength()); } // this.getTardis(world).getHandlers().getSequencing().add(this.control); return this.control.runServer(this.getTardis(world), (ServerPlayerEntity) player, (ServerWorld) world, leftClick); // i dont gotta check these cus i know its server } return false; } private static String getDelayId(Tardis tardis) { return "tardis-" + tardis.getUuid() + "-control"; } // clearly loqor has trust issues with running this so i do too so im overwriting it to do what he did fixme pls public Tardis getTardis(World world) { if (!(this.consoleBlockPos != null && this.control != null && world.getBlockEntity(this.consoleBlockPos) instanceof ConsoleBlockEntity console)) return null; return console.getTardis(); } public void setScaleAndCalculate(float width, float height) { this.setControlWidth(width); this.setControlHeight(height); this.calculateDimensions(); } @Override public Text getName() { if (this.control != null) return Text.translatable(this.control.getId()); else return super.getName(); }
package mdteam.ait.core.entities; public class ConsoleControlEntity extends BaseControlEntity { private BlockPos consoleBlockPos; private Control control; private static final TrackedData<String> IDENTITY = DataTracker.registerData(ConsoleControlEntity.class, TrackedDataHandlerRegistry.STRING); private static final TrackedData<Float> WIDTH = DataTracker.registerData(ConsoleControlEntity.class, TrackedDataHandlerRegistry.FLOAT); private static final TrackedData<Float> HEIGHT = DataTracker.registerData(ConsoleControlEntity.class, TrackedDataHandlerRegistry.FLOAT); private static final TrackedData<Vector3f> OFFSET = DataTracker.registerData(ConsoleControlEntity.class, TrackedDataHandlerRegistry.VECTOR3F); public ConsoleControlEntity(EntityType<? extends BaseControlEntity> entityType, World world) { super(entityType, world); } @Override public void onSpawnPacket(EntitySpawnS2CPacket packet) { super.onSpawnPacket(packet); } @Override public void onRemoved() { if(this.consoleBlockPos == null) { super.onRemoved(); return; } if(this.getWorld().getBlockEntity(this.consoleBlockPos) instanceof ConsoleBlockEntity console) { console.markNeedsControl(); } } @Override protected void initDataTracker() { super.initDataTracker(); this.dataTracker.startTracking(IDENTITY, ""); this.dataTracker.startTracking(WIDTH, 0.125f); this.dataTracker.startTracking(HEIGHT, 0.125f); this.dataTracker.startTracking(OFFSET, new Vector3f(0)); } public String getIdentity() { return this.dataTracker.get(IDENTITY); } public void setIdentity(String string) { this.dataTracker.set(IDENTITY, string); } public float getControlWidth() { return this.dataTracker.get(WIDTH); } public float getControlHeight() { return this.dataTracker.get(HEIGHT); } public void setControlWidth(float width) { this.dataTracker.set(WIDTH, width); } public void setControlHeight(float height) { this.dataTracker.set(HEIGHT, height); } // fixme idk i added it i dunno if it'll work it didnt crash when i tried it so public Control getControl() { if(control == null) return null; return control; } public Vector3f getOffset() { return this.dataTracker.get(OFFSET); } public void setOffset(Vector3f offset) { this.dataTracker.set(OFFSET, offset); } public String createDelayId() { return "delay-" + this.getControl().id + "-" + this.getTardis().getUuid(); } public void createDelay(long millis) { DeltaTimeManager.createDelay(createDelayId(), millis); } public boolean isOnDelay() { return DeltaTimeManager.isStillWaitingOnDelay(createDelayId()); } @Override public void writeCustomDataToNbt(NbtCompound nbt) { super.writeCustomDataToNbt(nbt); //if(this.controlTypes != null) // nbt.put("controlTypes", this.controlTypes.serializeTypes(nbt)); if (consoleBlockPos != null) nbt.put("console", NbtHelper.fromBlockPos(this.consoleBlockPos)); nbt.putString("identity", this.getIdentity()); nbt.putFloat("width", this.getControlWidth()); nbt.putFloat("height", this.getControlHeight()); nbt.putFloat("offsetX", this.getOffset().x()); nbt.putFloat("offsetY", this.getOffset().y()); nbt.putFloat("offsetZ", this.getOffset().z()); } @Override public void readCustomDataFromNbt(NbtCompound nbt) { super.readCustomDataFromNbt(nbt); //if(this.controlTypes != null) // this.controlTypes = this.controlTypes.deserializeTypes(nbt); var console = (NbtCompound) nbt.get("console"); if (console != null) this.consoleBlockPos = NbtHelper.toBlockPos(console); if (nbt.contains("identity")) { this.setIdentity(nbt.getString("identity")); } if (nbt.contains("width") && nbt.contains("height")) { this.setControlWidth(nbt.getFloat("width")); this.setControlWidth(nbt.getFloat("height")); this.calculateDimensions(); } if (nbt.contains("offsetX") && nbt.contains("offsetY") && nbt.contains("offsetZ")) { this.setOffset(new Vector3f(nbt.getFloat("offsetX"), nbt.getFloat("offsetY"), nbt.getFloat("offsetZ"))); } } @Override public boolean cannotDespawn() { return true; } @Override public ActionResult interactAt(PlayerEntity player, Vec3d hitPos, Hand hand) { if (player.getOffHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); return ActionResult.SUCCESS; } if (hand == Hand.MAIN_HAND) this.run(player, player.getWorld(), false); return ActionResult.SUCCESS; } @Override public boolean damage(DamageSource source, float amount) { if (source.getAttacker() instanceof PlayerEntity player) { if (player.getOffHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); } else this.run((PlayerEntity) source.getAttacker(), source.getAttacker().getWorld(), true); } return super.damage(source, source.getAttacker() instanceof PlayerEntity ? 0 : amount); } public boolean run(PlayerEntity player, World world, boolean leftClick) { Random random = new Random(); int chance_int = random.nextInt(1, 10_000); if (chance_int == 72) { // play sound this.getWorld().playSound(null, this.getBlockPos(), AITSounds.EVEN_MORE_SECRET_MUSIC, SoundCategory.MASTER, 1F, 1F); } if (this.consoleBlockPos != null) this.getWorld().playSound(null, this.getBlockPos(), this.control.getSound(), SoundCategory.BLOCKS, 0.7f, 1f); if (!world.isClient()) { if (player.getMainHandStack().getItem() == AITItems.TARDIS_ITEM) { this.remove(RemovalReason.DISCARDED); }/* else if (player.getMainHandStack().getItem() == Items.COMMAND_BLOCK) { controlEditorHandler(player); }*/ if (this.getTardis() == null) return false; // AAAAAAAAAAA //blahblah //if (DeltaTimeManager.isStillWaitingOnDelay(getDelayId(this.getTardis()))) return false; //DeltaTimeManager.createDelay(getDelayId(this.getTardis()), 500L); control.runAnimation(getTardis(world), (ServerPlayerEntity) player, (ServerWorld) world); if (this.getTardis(world) == null) { this.discard(); AITMod.LOGGER.warn("Discarding invalid control entity at " + this.getPos()); return false; } if (control.shouldFailOnNoPower() && !this.getTardis(world).hasPower()) { return false; } if (this.isOnDelay()) return false; if (this.control.shouldHaveDelay() && !this.isOnDelay()) { this.createDelay(this.control.getDelayLength()); } // this.getTardis(world).getHandlers().getSequencing().add(this.control); return this.control.runServer(this.getTardis(world), (ServerPlayerEntity) player, (ServerWorld) world, leftClick); // i dont gotta check these cus i know its server } return false; } private static String getDelayId(Tardis tardis) { return "tardis-" + tardis.getUuid() + "-control"; } // clearly loqor has trust issues with running this so i do too so im overwriting it to do what he did fixme pls public Tardis getTardis(World world) { if (!(this.consoleBlockPos != null && this.control != null && world.getBlockEntity(this.consoleBlockPos) instanceof ConsoleBlockEntity console)) return null; return console.getTardis(); } public void setScaleAndCalculate(float width, float height) { this.setControlWidth(width); this.setControlHeight(height); this.calculateDimensions(); } @Override public Text getName() { if (this.control != null) return Text.translatable(this.control.getId()); else return super.getName(); }
public void setControlData(ConsoleSchema consoleType, ControlTypes type, BlockPos consoleBlockPosition) {
7
2023-10-08 00:38:53+00:00
16k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/monitor/SysOperlogController.java
[ { "identifier": "BaseController", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/controller/BaseController.java", "snippet": "public class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; 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.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.core.page.TableDataInfo; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.system.domain.SysOperLog; import com.nhXJH.system.service.ISysOperLogService;
14,259
package com.nhXJH.web.controller.monitor; /** * 操作日志记录 * * @author nhXJH */ @RestController @RequestMapping("/monitor/operlog") public class SysOperlogController extends BaseController { @Autowired
package com.nhXJH.web.controller.monitor; /** * 操作日志记录 * * @author nhXJH */ @RestController @RequestMapping("/monitor/operlog") public class SysOperlogController extends BaseController { @Autowired
private ISysOperLogService operLogService;
6
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;
13,976
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();
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
1
2023-10-14 21:51:49+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,507
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;
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;
4
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,197
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();
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);
9
2023-10-10 18:56:27+00:00
16k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/upload/GenerateShaThread.java
[ { "identifier": "Core", "path": "src/main/java/frost/Core.java", "snippet": "public class Core {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Core.class);\r\n\r\n // Core instanciates itself, frostSettings must be created before instance=Core() !\r\n public static final Se...
import java.io.File; import java.util.LinkedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.Core; import frost.fileTransfer.FileTransferManager; import frost.fileTransfer.NewUploadFilesManager; import frost.fileTransfer.sharing.FrostSharedFileItem; import frost.storage.perst.NewUploadFile; import frost.util.Mixed;
10,960
/* GenerateShaThread.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.upload; /** * Generates the sha checksum of a file. */ public class GenerateShaThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class); private NewUploadFilesManager newUploadFilesManager; private static final int wait1minute = 1 * 60 * 1000; FileQueue fileQueue; /** * @param newUploadFilesManager */ public GenerateShaThread(NewUploadFilesManager newUploadFilesManager) { this.newUploadFilesManager = newUploadFilesManager; fileQueue = new FileQueue(); } /** * @param f */ public void addToFileQueue(final NewUploadFile f) { // awakes thread fileQueue.appendFileToQueue(f); } /** * @return */ public int getQueueSize() { return fileQueue.getQueueSize(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while(true) { try { // if now work is in queue this call waits for a new queueitem final NewUploadFile newUploadFile = fileQueue.getFileFromQueue(); if( newUploadFile == null ) { // paranoia Mixed.wait(wait1minute); continue; } final File newFile = new File(newUploadFile.getFilePath());
/* GenerateShaThread.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.upload; /** * Generates the sha checksum of a file. */ public class GenerateShaThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class); private NewUploadFilesManager newUploadFilesManager; private static final int wait1minute = 1 * 60 * 1000; FileQueue fileQueue; /** * @param newUploadFilesManager */ public GenerateShaThread(NewUploadFilesManager newUploadFilesManager) { this.newUploadFilesManager = newUploadFilesManager; fileQueue = new FileQueue(); } /** * @param f */ public void addToFileQueue(final NewUploadFile f) { // awakes thread fileQueue.appendFileToQueue(f); } /** * @return */ public int getQueueSize() { return fileQueue.getQueueSize(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while(true) { try { // if now work is in queue this call waits for a new queueitem final NewUploadFile newUploadFile = fileQueue.getFileFromQueue(); if( newUploadFile == null ) { // paranoia Mixed.wait(wait1minute); continue; } final File newFile = new File(newUploadFile.getFilePath());
final String sha = Core.getCrypto().computeChecksumSHA256(newFile);
0
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,566
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) -> {
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)) {
10
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,856
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); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.3ds"); assertNotNull(scenes); } @Test void loadCollada() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.dae"); assertNotNull(scenes); } @Test void loadColladaWithKml() throws URISyntaxException, IOException, ParserConfigurationException { Configurator.initConsoleLogger(); File kml = new File(getAbsolutePath(INPUT_PATH) + "a_bd001.kml"); //KmlReader kmlReader = new KmlReader(); FastKmlReader kmlReader = new FastKmlReader(); KmlInfo kmlInfo = kmlReader.read(kml); Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + kmlInfo.getHref()); assertNotNull(scenes);
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); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.3ds"); assertNotNull(scenes); } @Test void loadCollada() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.dae"); assertNotNull(scenes); } @Test void loadColladaWithKml() throws URISyntaxException, IOException, ParserConfigurationException { Configurator.initConsoleLogger(); File kml = new File(getAbsolutePath(INPUT_PATH) + "a_bd001.kml"); //KmlReader kmlReader = new KmlReader(); FastKmlReader kmlReader = new FastKmlReader(); KmlInfo kmlInfo = kmlReader.read(kml); Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + kmlInfo.getHref()); assertNotNull(scenes);
ContentInfo batchInfo = new ContentInfo();
7
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;
12,910
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())); }
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) {
4
2023-11-27 10:54:49+00:00
16k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/skin/SkinBPMGraph.java
[ { "identifier": "MainState", "path": "core/src/bms/player/beatoraja/MainState.java", "snippet": "public abstract class MainState {\n\n\tpublic final MainController main;\n\n\t/**\n\t * スキン\n\t */\n\tprivate Skin skin;\n\n\tprivate Stage stage;\n\t\n\tpublic final TimerManager timer;\n\t\n\tpublic final ...
import bms.model.*; import bms.player.beatoraja.MainState; import bms.player.beatoraja.skin.Skin.SkinObjectRenderer; import bms.player.beatoraja.song.SongData; import bms.player.beatoraja.song.SongInformation; import java.util.*; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.fasterxml.jackson.databind.deser.std.NumberDeserializers.LongDeserializer;
11,180
package bms.player.beatoraja.skin; /** * BPM推移のグラフ * * @author niente1899 */ public class SkinBPMGraph extends SkinObject { /** * グラフテクスチャ */ private TextureRegion shapetex; private long time;
package bms.player.beatoraja.skin; /** * BPM推移のグラフ * * @author niente1899 */ public class SkinBPMGraph extends SkinObject { /** * グラフテクスチャ */ private TextureRegion shapetex; private long time;
private MainState state;
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,161
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;
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;
9
2023-11-28 16:53:29+00:00
16k
WiIIiam278/HuskClaims
bukkit/src/main/java/net/william278/huskclaims/event/BukkitResizeChildClaimEvent.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;
11,025
/* * 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 BukkitResizeChildClaimEvent extends BukkitPlayerEvent implements ResizeChildClaimEvent, Cancellable { private final Region newChildRegion; private final Claim parentClaim; private final Claim claim; private final ClaimWorld claimWorld; @Setter private boolean cancelled; protected BukkitResizeChildClaimEvent(@NotNull OnlineUser user, @NotNull Claim claim, @NotNull Claim parentClaim, @NotNull Region newRegion, @NotNull ClaimWorld claimWorld,
/* * 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 BukkitResizeChildClaimEvent extends BukkitPlayerEvent implements ResizeChildClaimEvent, Cancellable { private final Region newChildRegion; private final Claim parentClaim; private final Claim claim; private final ClaimWorld claimWorld; @Setter private boolean cancelled; protected BukkitResizeChildClaimEvent(@NotNull OnlineUser user, @NotNull Claim claim, @NotNull Claim parentClaim, @NotNull Region newRegion, @NotNull ClaimWorld claimWorld,
@NotNull HuskClaims plugin) {
0
2023-11-28 01:09:43+00:00
16k
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/service/impl/DataServiceImpl.java
[ { "identifier": "HttpStatus", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/HttpStatus.java", "snippet": "public class HttpStatus\n{\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static fin...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.metax.common.core.constant.HttpStatus; import com.metax.common.core.context.SecurityContextHolder; import com.metax.common.core.web.page.TableDataInfo; import com.metax.system.api.domain.SysUser; import com.metax.web.domain.content.SendContent; import com.metax.web.vo.ReceiverRecordsPage; import com.metax.web.vo.SendTaskInfoVoPage; import com.metax.web.service.IDataService; import com.metax.web.util.DataUtil; import com.metax.web.util.RedisKeyUtil; import com.metax.web.util.RedisUtil; import com.metax.web.vo.MessageTemplateDataVo; import com.metax.web.vo.ReceiverRecords; import com.metax.web.vo.SendTaskInfoVo; import com.metax.web.xxljob.domain.CronTaskCords; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static com.metax.common.core.constant.MetaxDataConstants.*;
13,460
package com.metax.web.service.impl; /** * @Author: hanabi * @DateTime: 2023/10/4 14:06 **/ @Data @Service @Slf4j public class DataServiceImpl implements IDataService { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired public DataUtil dataUtil; @Autowired private RedisUtil redisUtil; //当前用户这天成功发送人数、失败人数和发送中 public int success = 0; public int fail = 0; public int sending = 0; //指定日期的发送成功key public static String successKey = ""; public static String failKey = ""; public static String sendingKey = ""; //当天渠道统计情况key public static String channelCountKey = ""; //当天下发人数key public static String totalOfDayKey = ""; //用于其它类使用 public int sendTotalOfDayTem; public Map<Integer, Integer> channelCountTem = new HashMap<>(); public int successTem = 0; public int failTem = 0; public int sendingTem = 0; @Override public SendTaskInfoVoPage getCurrentDayData(int pageNum, int pageSize, String sendMessageKey, Long userId) { String day = null; if (StrUtil.isNotBlank(sendMessageKey) && !sendMessageKey.equals("null")) { LocalDate date = LocalDate.parse(sendMessageKey); day = date.format(DateTimeFormatter.ofPattern(REDIS_DAY_KEY_FORMAT)); } else { day = RedisKeyUtil.getCurrentDay(); } if (userId == null || userId == 0) { userId = SecurityContextHolder.getUserId(); } String redisKey = RedisKeyUtil.getMessageRedisKey(userId, day); successKey = RedisKeyUtil.getSuccessRedisKey(userId, day); failKey = RedisKeyUtil.getFailRedisKey(userId, day); sendingKey = RedisKeyUtil.getSendingRedisKey(userId, day); channelCountKey = RedisKeyUtil.getSendChannelCountRedisKey(userId, day); totalOfDayKey = RedisKeyUtil.getSendTotalOfDay(userId, day); List<SendTaskInfoVo> sendTaskInfoVos = sendContentsProcess(redisKey); if (CollectionUtil.isEmpty(sendTaskInfoVos)) { return SendTaskInfoVoPage.builder().sendTaskInfoVos(new ArrayList<>()).total(0).build(); } int start = (pageNum - 1) * pageSize; //取数据结束下标和集合大小之间最小的值 int end = Math.min(start + pageSize, sendTaskInfoVos.size()); //end是开区间 List<SendTaskInfoVo> list = sendTaskInfoVos.subList(start, end); return SendTaskInfoVoPage.builder().sendTaskInfoVos(list).total(sendTaskInfoVos.size()).build(); } /** * 清空指定日期消息 * * @param day * @return */ @Override public boolean clear(String day,Long userId) { if (StrUtil.isBlank(day) || "null".equals(day)) { day = RedisKeyUtil.getCurrentDay(); } else { LocalDate date = LocalDate.parse(day); day = date.format(DateTimeFormatter.ofPattern(REDIS_DAY_KEY_FORMAT)); } if (userId == null || userId == 0) { userId = SecurityContextHolder.getUserId(); } String redisKey = RedisKeyUtil.getMessageRedisKey(userId, day); Boolean delete = stringRedisTemplate.delete(redisKey); if (Objects.isNull(delete)) { return false; } return delete.booleanValue(); } /** * 查询定时任务记录 * * @param pageNum * @param pageSize * @param messageTemplateId * @return */ @Override public TableDataInfo cronTaskCordsList(int pageNum, int pageSize, String messageTemplateId) {
package com.metax.web.service.impl; /** * @Author: hanabi * @DateTime: 2023/10/4 14:06 **/ @Data @Service @Slf4j public class DataServiceImpl implements IDataService { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired public DataUtil dataUtil; @Autowired private RedisUtil redisUtil; //当前用户这天成功发送人数、失败人数和发送中 public int success = 0; public int fail = 0; public int sending = 0; //指定日期的发送成功key public static String successKey = ""; public static String failKey = ""; public static String sendingKey = ""; //当天渠道统计情况key public static String channelCountKey = ""; //当天下发人数key public static String totalOfDayKey = ""; //用于其它类使用 public int sendTotalOfDayTem; public Map<Integer, Integer> channelCountTem = new HashMap<>(); public int successTem = 0; public int failTem = 0; public int sendingTem = 0; @Override public SendTaskInfoVoPage getCurrentDayData(int pageNum, int pageSize, String sendMessageKey, Long userId) { String day = null; if (StrUtil.isNotBlank(sendMessageKey) && !sendMessageKey.equals("null")) { LocalDate date = LocalDate.parse(sendMessageKey); day = date.format(DateTimeFormatter.ofPattern(REDIS_DAY_KEY_FORMAT)); } else { day = RedisKeyUtil.getCurrentDay(); } if (userId == null || userId == 0) { userId = SecurityContextHolder.getUserId(); } String redisKey = RedisKeyUtil.getMessageRedisKey(userId, day); successKey = RedisKeyUtil.getSuccessRedisKey(userId, day); failKey = RedisKeyUtil.getFailRedisKey(userId, day); sendingKey = RedisKeyUtil.getSendingRedisKey(userId, day); channelCountKey = RedisKeyUtil.getSendChannelCountRedisKey(userId, day); totalOfDayKey = RedisKeyUtil.getSendTotalOfDay(userId, day); List<SendTaskInfoVo> sendTaskInfoVos = sendContentsProcess(redisKey); if (CollectionUtil.isEmpty(sendTaskInfoVos)) { return SendTaskInfoVoPage.builder().sendTaskInfoVos(new ArrayList<>()).total(0).build(); } int start = (pageNum - 1) * pageSize; //取数据结束下标和集合大小之间最小的值 int end = Math.min(start + pageSize, sendTaskInfoVos.size()); //end是开区间 List<SendTaskInfoVo> list = sendTaskInfoVos.subList(start, end); return SendTaskInfoVoPage.builder().sendTaskInfoVos(list).total(sendTaskInfoVos.size()).build(); } /** * 清空指定日期消息 * * @param day * @return */ @Override public boolean clear(String day,Long userId) { if (StrUtil.isBlank(day) || "null".equals(day)) { day = RedisKeyUtil.getCurrentDay(); } else { LocalDate date = LocalDate.parse(day); day = date.format(DateTimeFormatter.ofPattern(REDIS_DAY_KEY_FORMAT)); } if (userId == null || userId == 0) { userId = SecurityContextHolder.getUserId(); } String redisKey = RedisKeyUtil.getMessageRedisKey(userId, day); Boolean delete = stringRedisTemplate.delete(redisKey); if (Objects.isNull(delete)) { return false; } return delete.booleanValue(); } /** * 查询定时任务记录 * * @param pageNum * @param pageSize * @param messageTemplateId * @return */ @Override public TableDataInfo cronTaskCordsList(int pageNum, int pageSize, String messageTemplateId) {
List<CronTaskCords> cords = new ArrayList<>();
14
2023-12-04 05:10:13+00:00
16k
ydb-platform/yoj-project
repository-ydb-v1/src/test/java/tech/ydb/yoj/repository/ydb/YqlPredicateTest.java
[ { "identifier": "Entity", "path": "repository/src/main/java/tech/ydb/yoj/repository/db/Entity.java", "snippet": "public interface Entity<E extends Entity<E>> extends Table.ViewId<E> {\n @Override\n Id<E> getId();\n\n @SuppressWarnings(\"unchecked\")\n default E postLoad() {\n return (...
import lombok.Value; import org.junit.Test; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.ydb.statement.PredicateStatement.CollectionKind; import tech.ydb.yoj.repository.ydb.statement.PredicateStatement.ComplexField; import tech.ydb.yoj.repository.ydb.yql.YqlPredicate; import tech.ydb.yoj.repository.ydb.yql.YqlPredicateParam; import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.eq; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.gt; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.gte; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.in; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.like; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.lt; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.lte; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.neq; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.not; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.notLike; import static tech.ydb.yoj.repository.ydb.yql.YqlPredicate.where;
11,475
package tech.ydb.yoj.repository.ydb; public class YqlPredicateTest { private final EntitySchema<FakeEntity> schema = EntitySchema.of(FakeEntity.class); private final EntitySchema<FakeComplexEntity> complexSchema = EntitySchema.of(FakeComplexEntity.class); @Test public void in_fluent() { assertThat(where("status").in("DONE", "DONE_KEEP").toYql(schema)).isEqualToIgnoringCase("`status` IN ?"); } @Test public void in_chained() { assertThat(in("status", "DONE", "DONE_KEEP").toYql(schema)).isEqualToIgnoringCase("`status` IN ?"); } @Test public void rel_eq_fluent() { assertThat(where("workers").eq(42L).toYql(schema)).isEqualToIgnoringCase("`workers` = ?"); } @Test public void rel_eq_chained() { assertThat(eq("workers", 42L).toYql(schema)).isEqualToIgnoringCase("`workers` = ?"); } @Test public void rel_neq_fluent() { assertThat(where("workers").neq(42L).toYql(schema)).isEqualToIgnoringCase("`workers` <> ?"); } @Test public void rel_neq_chained() { assertThat(neq("workers", 42L).toYql(schema)).isEqualToIgnoringCase("`workers` <> ?"); } @Test public void rel_like_fluent() { assertThat(where("status").like("%OK%").toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_like_chained() { assertThat(like("status", "%OK%").toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_not_like_fluent() { assertThat(not(where("status").like("%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_not_like_chained() { assertThat(not(like("status", "%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_notLike_fluent() { assertThat(where("status").notLike("%OK%").toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_notLike_chained() { assertThat(notLike("status", "%OK%").toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_not_notLike_fluent() { assertThat(not(where("status").notLike("%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_not_notLike_chained() { assertThat(not(notLike("status", "%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_like_escape_fluent() { assertThat(where("status").like("%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_like_escape_chained() { assertThat(like("status", "%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_not_like_escape_fluent() { assertThat(not(where("status").like("%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_not_like_escape_chained() { assertThat(not(like("status", "%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_notLike_escape_fluent() { assertThat(where("status").notLike("%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_notLike_escape_chained() { assertThat(notLike("status", "%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_not_notLike_escape_fluent() { assertThat(not(where("status").notLike("%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_not_notLike_escape_chained() { assertThat(not(notLike("status", "%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_gt_fluent() {
package tech.ydb.yoj.repository.ydb; public class YqlPredicateTest { private final EntitySchema<FakeEntity> schema = EntitySchema.of(FakeEntity.class); private final EntitySchema<FakeComplexEntity> complexSchema = EntitySchema.of(FakeComplexEntity.class); @Test public void in_fluent() { assertThat(where("status").in("DONE", "DONE_KEEP").toYql(schema)).isEqualToIgnoringCase("`status` IN ?"); } @Test public void in_chained() { assertThat(in("status", "DONE", "DONE_KEEP").toYql(schema)).isEqualToIgnoringCase("`status` IN ?"); } @Test public void rel_eq_fluent() { assertThat(where("workers").eq(42L).toYql(schema)).isEqualToIgnoringCase("`workers` = ?"); } @Test public void rel_eq_chained() { assertThat(eq("workers", 42L).toYql(schema)).isEqualToIgnoringCase("`workers` = ?"); } @Test public void rel_neq_fluent() { assertThat(where("workers").neq(42L).toYql(schema)).isEqualToIgnoringCase("`workers` <> ?"); } @Test public void rel_neq_chained() { assertThat(neq("workers", 42L).toYql(schema)).isEqualToIgnoringCase("`workers` <> ?"); } @Test public void rel_like_fluent() { assertThat(where("status").like("%OK%").toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_like_chained() { assertThat(like("status", "%OK%").toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_not_like_fluent() { assertThat(not(where("status").like("%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_not_like_chained() { assertThat(not(like("status", "%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_notLike_fluent() { assertThat(where("status").notLike("%OK%").toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_notLike_chained() { assertThat(notLike("status", "%OK%").toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ?"); } @Test public void rel_not_notLike_fluent() { assertThat(not(where("status").notLike("%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_not_notLike_chained() { assertThat(not(notLike("status", "%OK%")).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ?"); } @Test public void rel_like_escape_fluent() { assertThat(where("status").like("%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_like_escape_chained() { assertThat(like("status", "%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_not_like_escape_fluent() { assertThat(not(where("status").like("%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_not_like_escape_chained() { assertThat(not(like("status", "%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_notLike_escape_fluent() { assertThat(where("status").notLike("%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_notLike_escape_chained() { assertThat(notLike("status", "%OK/_%", '/').toYql(schema)).isEqualToIgnoringCase("`status` NOT LIKE ? ESCAPE '/'"); } @Test public void rel_not_notLike_escape_fluent() { assertThat(not(where("status").notLike("%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_not_notLike_escape_chained() { assertThat(not(notLike("status", "%OK/_%", '/')).toYql(schema)).isEqualToIgnoringCase("`status` LIKE ? ESCAPE '/'"); } @Test public void rel_gt_fluent() {
assertThat(where("workers").gt(42L).toYql(schema)).isEqualToIgnoringCase("`workers` > ?");
7
2023-12-05 15:57:58+00:00
16k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/FabriclikeUtils.java
[ { "identifier": "Tools", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Tools.java", "snippet": "@SuppressWarnings(\"IOStreamConstructor\")\npublic final class Tools {\n public static final float BYTE_TO_MB = 1024 * 1024;\n public static final Handler MAIN_HANDLER = new Handler(Loop...
import com.google.gson.JsonSyntaxException; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.DownloadUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder;
13,408
package net.kdt.pojavlaunch.modloaders; public class FabriclikeUtils { public static final FabriclikeUtils FABRIC_UTILS = new FabriclikeUtils("https://meta.fabricmc.net/v2", "fabric", "Fabric", "fabric"); public static final FabriclikeUtils QUILT_UTILS = new FabriclikeUtils("https://meta.quiltmc.org/v3", "quilt", "Quilt", "quilt"); private static final String LOADER_METADATA_URL = "%s/versions/loader/%s"; private static final String GAME_METADATA_URL = "%s/versions/game"; private static final String JSON_DOWNLOAD_URL = "%s/versions/loader/%s/%s/profile/json"; private final String mApiUrl; private final String mCachePrefix; private final String mName; private final String mIconName; private FabriclikeUtils(String mApiUrl, String cachePrefix, String mName, String iconName) { this.mApiUrl = mApiUrl; this.mCachePrefix = cachePrefix; this.mIconName = iconName; this.mName = mName; } public FabricVersion[] downloadGameVersions() throws IOException{ try {
package net.kdt.pojavlaunch.modloaders; public class FabriclikeUtils { public static final FabriclikeUtils FABRIC_UTILS = new FabriclikeUtils("https://meta.fabricmc.net/v2", "fabric", "Fabric", "fabric"); public static final FabriclikeUtils QUILT_UTILS = new FabriclikeUtils("https://meta.quiltmc.org/v3", "quilt", "Quilt", "quilt"); private static final String LOADER_METADATA_URL = "%s/versions/loader/%s"; private static final String GAME_METADATA_URL = "%s/versions/game"; private static final String JSON_DOWNLOAD_URL = "%s/versions/loader/%s/%s/profile/json"; private final String mApiUrl; private final String mCachePrefix; private final String mName; private final String mIconName; private FabriclikeUtils(String mApiUrl, String cachePrefix, String mName, String iconName) { this.mApiUrl = mApiUrl; this.mCachePrefix = cachePrefix; this.mIconName = iconName; this.mName = mName; } public FabricVersion[] downloadGameVersions() throws IOException{ try {
return DownloadUtils.downloadStringCached(String.format(GAME_METADATA_URL, mApiUrl), mCachePrefix+"_game_versions",
1
2023-12-01 16:16:12+00:00
16k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/worldGeneration/step/StepNoise.java
[ { "identifier": "ChunkWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/chunk/ChunkWrapper.java", "snippet": "public class ChunkWrapper implements IChunkWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger();\n\t\n\t/** useful for debugging, but c...
import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.levelgen.blending.Blender; import java.util.ArrayList; import java.util.List; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.common.wrappers.worldGeneration.ThreadedParameters; import com.seibel.distanthorizons.core.util.objects.UncheckedInterruptedException; import net.minecraft.server.level.WorldGenRegion;
11,975
/* * 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.worldGeneration.step; #if POST_MC_1_17_1 #endif #if PRE_MC_1_19_2 #endif import net.minecraft.world.level.chunk.ChunkAccess; #if POST_MC_1_18_2 #endif public final class StepNoise { private static final ChunkStatus STATUS = ChunkStatus.NOISE; private final BatchGenerationEnvironment environment; public StepNoise(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup( ThreadedParameters tParams, WorldGenRegion worldGenRegion,
/* * 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.worldGeneration.step; #if POST_MC_1_17_1 #endif #if PRE_MC_1_19_2 #endif import net.minecraft.world.level.chunk.ChunkAccess; #if POST_MC_1_18_2 #endif public final class StepNoise { private static final ChunkStatus STATUS = ChunkStatus.NOISE; private final BatchGenerationEnvironment environment; public StepNoise(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup( ThreadedParameters tParams, WorldGenRegion worldGenRegion,
List<ChunkWrapper> chunkWrappers)
0
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;
14,083
@PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator = PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP); int remainingJurors = totalCount; Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types while (remainingJurors > 0) { final int totalJurorsInPool = RandomGenerator.nextInt( jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive); PoolRequest poolRequest = poolRequestGenerator.generate(); poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16)); pools.add(poolRequest); List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList( Math.max(0, remainingJurors - totalJurorsInPool), remainingJurors); selectedJurors.parallelStream().forEach(juror -> { String firstJurorPoolOwner = null; List<JurorPool> jurorPools = juror.getJurorPools(); for (JurorPool jurorPool : jurorPools) { if (firstJurorPoolOwner == null) { firstJurorPoolOwner = jurorPool.getOwner(); } //Set owner so we know which pool this juror can not be in jurorPool.setOwner(jurorPool.getOwner()); if (jurorPool.getOwner().equals(firstJurorPoolOwner)) { jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } else { needRandomPool.add(jurorPool); } } } ); remainingJurors -= totalJurorsInPool; } reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools); stopWatch.start("Saving Pool Request's"); log.info("Saving Pool Request's to database"); Util.batchSave(poolRequestRepository, pools, BATCH_SIZE); stopWatch.stop(); saveJurorAccountDetailsDtos(jurorAccountDetailsDtos); } private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) { stopWatch.start("Saving Juror's"); log.info("Saving Juror's to database"); Util.batchSave(jurorRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Paper Response's"); log.info("Saving Juror Paper Response's"); Util.batchSave(paperResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse)
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; private static final Set<String> courtOwners; private static final int BATCH_SIZE = 100; static { courtLocations = new ArrayList<>(); courtOwners = new HashSet<>(); } public static List<CourtLocation> getCourtLocations() { return Collections.unmodifiableList(courtLocations); } public static Set<String> getCourtOwners() { return Collections.unmodifiableSet(courtOwners); } @PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator = PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP); int remainingJurors = totalCount; Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types while (remainingJurors > 0) { final int totalJurorsInPool = RandomGenerator.nextInt( jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive); PoolRequest poolRequest = poolRequestGenerator.generate(); poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16)); pools.add(poolRequest); List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList( Math.max(0, remainingJurors - totalJurorsInPool), remainingJurors); selectedJurors.parallelStream().forEach(juror -> { String firstJurorPoolOwner = null; List<JurorPool> jurorPools = juror.getJurorPools(); for (JurorPool jurorPool : jurorPools) { if (firstJurorPoolOwner == null) { firstJurorPoolOwner = jurorPool.getOwner(); } //Set owner so we know which pool this juror can not be in jurorPool.setOwner(jurorPool.getOwner()); if (jurorPool.getOwner().equals(firstJurorPoolOwner)) { jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } else { needRandomPool.add(jurorPool); } } } ); remainingJurors -= totalJurorsInPool; } reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools); stopWatch.start("Saving Pool Request's"); log.info("Saving Pool Request's to database"); Util.batchSave(poolRequestRepository, pools, BATCH_SIZE); stopWatch.stop(); saveJurorAccountDetailsDtos(jurorAccountDetailsDtos); } private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) { stopWatch.start("Saving Juror's"); log.info("Saving Juror's to database"); Util.batchSave(jurorRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Paper Response's"); log.info("Saving Juror Paper Response's"); Util.batchSave(paperResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse)
.filter(PaperResponse.class::isInstance)
10
2023-12-01 11:38:42+00:00
16k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/EventHandler.java
[ { "identifier": "Main", "path": "src/main/java/net/superricky/tpaplusplus/Main.java", "snippet": "@Mod(Main.MOD_ID)\npublic class Main {\n // Our mod id\n public static final String MOD_ID = \"tpaplusplus\";\n public static final String MOD_VERSION = \"1.3-1.20.x-BETA-3\";\n\n public Main() ...
import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.LivingEntity; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.event.server.ServerStartedEvent; import net.minecraftforge.event.server.ServerStoppedEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.superricky.tpaplusplus.Main; import net.superricky.tpaplusplus.event.RequestMovedEvent; import net.superricky.tpaplusplus.util.LevelBoundVec3; import net.superricky.tpaplusplus.util.Request; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.event.RequestAcceptSuccessEvent; import net.superricky.tpaplusplus.event.RequestTimeoutEvent; import net.superricky.tpaplusplus.util.configuration.formatters.MessageParser; import net.superricky.tpaplusplus.util.manager.saved.SaveDataManager; import java.util.Map;
13,272
package net.superricky.tpaplusplus.util.manager; @Mod.EventBusSubscriber public class EventHandler { private EventHandler() {} /** * Our custom event. * This event is triggered once the timer of a teleport request reaches 0, notifying all members that were affected. * * @param event Takes a RequestTimeoutEvent parameter */ @SubscribeEvent public static void onTimeoutEvent(RequestTimeoutEvent event) { Request request = event.getRequest(); /* Check if the request has not been accepted or denied, so you don't print timeout messages multiple times. * UPDATE: This now ACTUALLY prevents printing timeout messages multiple times, because now the check is inverted (see RequestManager#alreadySentTeleportRequest), * since before we were only displaying your timeout message IF the timeout message did NOT expire, which you can imagine that caused problems. */ if (Boolean.FALSE.equals(RequestManager.alreadySentTeleportRequest(request))) return; ServerPlayer receiver = request.getReceiver(); ServerPlayer sender = request.getSender(); if (request.isHereRequest()) { sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPAHERE_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPAHERE_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); return; } sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPA_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPA_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); } /** * Triggered when a TPAAcceptTimer is successful. * Here we just run our acceptTeleportRequest method from TeleportManager.java with ABSOLUTE mode enabled, so the player will be teleported to the other player. * This is what will happen after the 5 4 3 2 1 (or whatever countdown in the config) is finished! * @param event Takes a RequestAcceptSuccessEvent parameter */ @SubscribeEvent public static void onTPAAcceptTimerSuccess(RequestAcceptSuccessEvent event) { Request request = event.getRequest(); RequestManager.acceptFunctionality(request, request.getReceiver(), true); } @SubscribeEvent public static void onTPAMove(RequestMovedEvent event) { Request request = event.getRequest(); if (request.isHereRequest()) { request.getReceiver().sendSystemMessage(Component.literal(Messages.RECEIVER_MOVED_DURING_COUNTDOWN.get()));
package net.superricky.tpaplusplus.util.manager; @Mod.EventBusSubscriber public class EventHandler { private EventHandler() {} /** * Our custom event. * This event is triggered once the timer of a teleport request reaches 0, notifying all members that were affected. * * @param event Takes a RequestTimeoutEvent parameter */ @SubscribeEvent public static void onTimeoutEvent(RequestTimeoutEvent event) { Request request = event.getRequest(); /* Check if the request has not been accepted or denied, so you don't print timeout messages multiple times. * UPDATE: This now ACTUALLY prevents printing timeout messages multiple times, because now the check is inverted (see RequestManager#alreadySentTeleportRequest), * since before we were only displaying your timeout message IF the timeout message did NOT expire, which you can imagine that caused problems. */ if (Boolean.FALSE.equals(RequestManager.alreadySentTeleportRequest(request))) return; ServerPlayer receiver = request.getReceiver(); ServerPlayer sender = request.getSender(); if (request.isHereRequest()) { sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPAHERE_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPAHERE_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); return; } sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPA_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPA_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); } /** * Triggered when a TPAAcceptTimer is successful. * Here we just run our acceptTeleportRequest method from TeleportManager.java with ABSOLUTE mode enabled, so the player will be teleported to the other player. * This is what will happen after the 5 4 3 2 1 (or whatever countdown in the config) is finished! * @param event Takes a RequestAcceptSuccessEvent parameter */ @SubscribeEvent public static void onTPAAcceptTimerSuccess(RequestAcceptSuccessEvent event) { Request request = event.getRequest(); RequestManager.acceptFunctionality(request, request.getReceiver(), true); } @SubscribeEvent public static void onTPAMove(RequestMovedEvent event) { Request request = event.getRequest(); if (request.isHereRequest()) { request.getReceiver().sendSystemMessage(Component.literal(Messages.RECEIVER_MOVED_DURING_COUNTDOWN.get()));
if (Boolean.TRUE.equals(Config.SEND_COUNTDOWN_MOVEMENT_CANCEL_TO_BOTH_PLAYERS.get()))
4
2023-12-02 05:41:24+00:00
16k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/model/conditions/Condition.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import static java.lang.Thread.State.NEW; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.db.LocalDBHelper; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.model.DiaryActivity;
11,679
/* * 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.model.conditions; /* * Conditions model a specific aspect which influences the likelihood of the activities. **/ public abstract class Condition { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public class Likelihood{ public DiaryActivity activity; public double likelihood; public Likelihood(DiaryActivity a, double likelihood){ activity = a; this.likelihood = likelihood; } } /* it seems most conditions will need dedicated database operations, and we don't want * to mess up with the ContentProvider, so let's get a new helper here */
/* * 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.model.conditions; /* * Conditions model a specific aspect which influences the likelihood of the activities. **/ public abstract class Condition { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public class Likelihood{ public DiaryActivity activity; public double likelihood; public Likelihood(DiaryActivity a, double likelihood){ activity = a; this.likelihood = likelihood; } } /* it seems most conditions will need dedicated database operations, and we don't want * to mess up with the ContentProvider, so let's get a new helper here */
public static LocalDBHelper mOpenHelper = new LocalDBHelper(ActivityDiaryApplication.getAppContext());
1
2023-12-02 12:36:40+00:00
16k