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
Pigalala/TrackExchange
src/main/java/me/pigalala/trackexchange/processes/ProcessSave.java
[ { "identifier": "TrackExchange", "path": "src/main/java/me/pigalala/trackexchange/TrackExchange.java", "snippet": "public final class TrackExchange extends JavaPlugin {\n public static final int TRACK_VERSION = 4;\n\n public static TrackExchange instance;\n private static TaskChainFactory taskC...
import co.aikar.taskchain.TaskChain; import com.fastasyncworldedit.core.Fawe; import com.fastasyncworldedit.core.FaweAPI; import com.sk89q.worldedit.*; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.regions.Region; import me.makkuusen.timing.system.track.Track; import me.pigalala.trackexchange.TrackExchange; import me.pigalala.trackexchange.trackcomponents.TrackExchangeFile; import me.pigalala.trackexchange.trackcomponents.TrackExchangeSchematic; import me.pigalala.trackexchange.trackcomponents.TrackExchangeTrack; import me.pigalala.trackexchange.trackcomponents.SimpleLocation; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture;
3,916
package me.pigalala.trackexchange.processes; public class ProcessSave extends Process { private final Track track; private final String saveAs; private final TaskChain<?> chain; private final Location origin; public ProcessSave(Player player, Track track, String saveAs) { super(player, "SAVE"); this.track = track; this.saveAs = saveAs; this.chain = TrackExchange.newChain(); this.origin = player.getLocation(); } @Override public void execute() { final long startTime = System.currentTimeMillis(); notifyProcessStartText(); chain.asyncFutures((f) -> List.of(CompletableFuture.supplyAsync(this::doTrackStage), CompletableFuture.supplyAsync(this::doSchematicStage))) .async(this::doWriteStage) .execute((success) -> { if(success) notifyProcessFinishText(System.currentTimeMillis() - startTime); else notifyProcessFinishExceptionallyText(); }); } private Void doTrackStage() { final String stage = "TRACK"; final long startTime = System.currentTimeMillis(); notifyStageBeginText(stage);
package me.pigalala.trackexchange.processes; public class ProcessSave extends Process { private final Track track; private final String saveAs; private final TaskChain<?> chain; private final Location origin; public ProcessSave(Player player, Track track, String saveAs) { super(player, "SAVE"); this.track = track; this.saveAs = saveAs; this.chain = TrackExchange.newChain(); this.origin = player.getLocation(); } @Override public void execute() { final long startTime = System.currentTimeMillis(); notifyProcessStartText(); chain.asyncFutures((f) -> List.of(CompletableFuture.supplyAsync(this::doTrackStage), CompletableFuture.supplyAsync(this::doSchematicStage))) .async(this::doWriteStage) .execute((success) -> { if(success) notifyProcessFinishText(System.currentTimeMillis() - startTime); else notifyProcessFinishExceptionallyText(); }); } private Void doTrackStage() { final String stage = "TRACK"; final long startTime = System.currentTimeMillis(); notifyStageBeginText(stage);
TrackExchangeTrack trackExchangeTrack = new TrackExchangeTrack(track, new SimpleLocation(origin));
3
2023-12-06 12:43:51+00:00
8k
Serilum/Collective
Common/src/main/java/com/natamus/collective/functions/ItemFunctions.java
[ { "identifier": "CollectiveConfigHandler", "path": "Common/src/main/java/com/natamus/collective/config/CollectiveConfigHandler.java", "snippet": "public class CollectiveConfigHandler extends DuskConfig {\n public static HashMap<String, List<String>> configMetaData = new HashMap<String, List<String>>(...
import com.natamus.collective.config.CollectiveConfigHandler; import com.natamus.collective.data.GlobalVariables; import com.natamus.collective.fakeplayer.FakePlayer; import com.natamus.collective.fakeplayer.FakePlayerFactory; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map.Entry;
4,317
package com.natamus.collective.functions; public class ItemFunctions { public static void generateEntityDropsFromLootTable(Level level) { MinecraftServer server = level.getServer(); if (server == null) { return; } GlobalVariables.entitydrops = new HashMap<EntityType<?>, List<Item>>(); FakePlayer fakeplayer = FakePlayerFactory.getMinecraft((ServerLevel)level); Vec3 vec = new Vec3(0, 0, 0); ItemStack lootingsword = new ItemStack(Items.DIAMOND_SWORD, 1); lootingsword.enchant(Enchantments.MOB_LOOTING, 10); fakeplayer.setItemSlot(EquipmentSlot.MAINHAND, lootingsword); Collection<Entry<ResourceKey<EntityType<?>>, EntityType<?>>> entitytypes = level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).entrySet(); for (Entry<ResourceKey<EntityType<?>>, EntityType<?>> entry : entitytypes) { EntityType<?> type = entry.getValue(); if (type == null) { continue; } Entity entity = type.create(level); if (!(entity instanceof LivingEntity)) { continue; } LivingEntity le = (LivingEntity)entity; ResourceLocation lootlocation = le.getType().getDefaultLootTable(); LootTable loottable = server.getLootData().getLootTable(lootlocation); LootParams lootParams = new LootParams.Builder((ServerLevel)level) .withLuck(1000000F) .withParameter(LootContextParams.THIS_ENTITY, entity) .withParameter(LootContextParams.ORIGIN, vec) .withParameter(LootContextParams.KILLER_ENTITY, fakeplayer) .withParameter(LootContextParams.DAMAGE_SOURCE, level.damageSources().playerAttack(fakeplayer)) .create(LootContextParamSets.ENTITY); List<Item> alldrops = new ArrayList<Item>();
package com.natamus.collective.functions; public class ItemFunctions { public static void generateEntityDropsFromLootTable(Level level) { MinecraftServer server = level.getServer(); if (server == null) { return; } GlobalVariables.entitydrops = new HashMap<EntityType<?>, List<Item>>(); FakePlayer fakeplayer = FakePlayerFactory.getMinecraft((ServerLevel)level); Vec3 vec = new Vec3(0, 0, 0); ItemStack lootingsword = new ItemStack(Items.DIAMOND_SWORD, 1); lootingsword.enchant(Enchantments.MOB_LOOTING, 10); fakeplayer.setItemSlot(EquipmentSlot.MAINHAND, lootingsword); Collection<Entry<ResourceKey<EntityType<?>>, EntityType<?>>> entitytypes = level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).entrySet(); for (Entry<ResourceKey<EntityType<?>>, EntityType<?>> entry : entitytypes) { EntityType<?> type = entry.getValue(); if (type == null) { continue; } Entity entity = type.create(level); if (!(entity instanceof LivingEntity)) { continue; } LivingEntity le = (LivingEntity)entity; ResourceLocation lootlocation = le.getType().getDefaultLootTable(); LootTable loottable = server.getLootData().getLootTable(lootlocation); LootParams lootParams = new LootParams.Builder((ServerLevel)level) .withLuck(1000000F) .withParameter(LootContextParams.THIS_ENTITY, entity) .withParameter(LootContextParams.ORIGIN, vec) .withParameter(LootContextParams.KILLER_ENTITY, fakeplayer) .withParameter(LootContextParams.DAMAGE_SOURCE, level.damageSources().playerAttack(fakeplayer)) .create(LootContextParamSets.ENTITY); List<Item> alldrops = new ArrayList<Item>();
for (int n = 0; n < CollectiveConfigHandler.loopsAmountUsedToGetAllEntityDrops; n++) {
0
2023-12-11 22:37:15+00:00
8k
MrXiaoM/plugin-template
src/main/java/top/mrxiaom/example/ExamplePlugin.java
[ { "identifier": "AbstractPluginHolder", "path": "src/main/java/top/mrxiaom/example/func/AbstractPluginHolder.java", "snippet": "@SuppressWarnings({\"unused\"})\npublic abstract class AbstractPluginHolder {\n private static final Map<Class<?>, AbstractPluginHolder> registeredHolders = new HashMap<>();...
import com.google.common.collect.Lists; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import top.mrxiaom.example.func.AbstractPluginHolder; import top.mrxiaom.example.func.DatabaseManager; import top.mrxiaom.example.func.GuiManager; import top.mrxiaom.example.hooks.Placeholder; import top.mrxiaom.example.commands.CommandMain; import top.mrxiaom.example.utils.Util;
4,104
package top.mrxiaom.example; @SuppressWarnings({"unused"}) public class ExamplePlugin extends JavaPlugin implements Listener, TabCompleter { private static ExamplePlugin instance; public static ExamplePlugin getInstance() { return instance; } private GuiManager guiManager = null;
package top.mrxiaom.example; @SuppressWarnings({"unused"}) public class ExamplePlugin extends JavaPlugin implements Listener, TabCompleter { private static ExamplePlugin instance; public static ExamplePlugin getInstance() { return instance; } private GuiManager guiManager = null;
Placeholder papi = null;
3
2023-12-08 15:50:57+00:00
8k
ExcaliburFRC/2024RobotTamplate
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "LEDs", "path": "src/main/java/frc/robot/subsystems/LEDs.java", "snippet": "public class LEDs extends SubsystemBase {\n private final AddressableLED LedStrip = new AddressableLED(LEDS_PORT);\n private final AddressableLEDBuffer buffer = new AddressableLEDBuffer(LENGTH);\n\n priv...
import com.pathplanner.lib.auto.NamedCommands; import com.pathplanner.lib.commands.PathPlannerAuto; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.button.CommandPS4Controller; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.subsystems.LEDs; import frc.robot.subsystems.swerve.Swerve; import static edu.wpi.first.math.MathUtil.applyDeadband; import static frc.lib.Color.Colors.WHITE; import static frc.robot.subsystems.LEDs.LEDPattern.SOLID;
6,492
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; public class RobotContainer { // subsystems private final Swerve swerve = new Swerve();
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; public class RobotContainer { // subsystems private final Swerve swerve = new Swerve();
private final LEDs leds = LEDs.getInstance();
0
2023-12-13 22:33:35+00:00
8k
muchfish/ruoyi-vue-pro-sample
yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/job/JobLogController.java
[ { "identifier": "CommonResult", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/CommonResult.java", "snippet": "@Data\npublic class CommonResult<T> implements Serializable {\n\n /**\n * 错误码\n *\n * @see ErrorCode#getCode()\n */\n private I...
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogExcelVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogPageReqVO; import cn.iocoder.yudao.module.infra.controller.admin.job.vo.log.JobLogRespVO; import cn.iocoder.yudao.module.infra.convert.job.JobLogConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.job.JobLogDO; import cn.iocoder.yudao.module.infra.service.job.JobLogService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.util.Collection; import java.util.List; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
4,041
package cn.iocoder.yudao.module.infra.controller.admin.job; @Tag(name = "管理后台 - 定时任务日志") @RestController @RequestMapping("/infra/job-log") @Validated public class JobLogController { @Resource private JobLogService jobLogService; @GetMapping("/get") @Operation(summary = "获得定时任务日志") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('infra:job:query')")
package cn.iocoder.yudao.module.infra.controller.admin.job; @Tag(name = "管理后台 - 定时任务日志") @RestController @RequestMapping("/infra/job-log") @Validated public class JobLogController { @Resource private JobLogService jobLogService; @GetMapping("/get") @Operation(summary = "获得定时任务日志") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('infra:job:query')")
public CommonResult<JobLogRespVO> getJobLog(@RequestParam("id") Long id) {
0
2023-12-08 02:48:42+00:00
8k
ItzOverS/CoReScreen
src/main/java/me/overlight/corescreen/Commands.java
[ { "identifier": "AnalyzeModule", "path": "src/main/java/me/overlight/corescreen/Analyzer/AnalyzeModule.java", "snippet": "public class AnalyzeModule {\n public String getName() {\n return name;\n }\n\n private final String name;\n\n public AnalyzeModule(String name) {\n this.na...
import me.overlight.corescreen.Analyzer.AnalyzeModule; import me.overlight.corescreen.Analyzer.AnalyzerManager; import me.overlight.corescreen.ClientSettings.CSManager; import me.overlight.corescreen.ClientSettings.CSModule; import me.overlight.corescreen.Freeze.Cache.CacheManager; import me.overlight.corescreen.Freeze.FreezeManager; import me.overlight.corescreen.Freeze.Warps.WarpManager; import me.overlight.corescreen.Profiler.ProfilerManager; import me.overlight.corescreen.Profiler.Profiles.NmsHandler; import me.overlight.corescreen.Profiler.ProfilingSystem; import me.overlight.corescreen.Test.TestCheck; import me.overlight.corescreen.Test.TestManager; import me.overlight.corescreen.Vanish.VanishManager; import me.overlight.corescreen.api.Freeze.PlayerFreezeEvent; import me.overlight.corescreen.api.Freeze.PlayerUnfreezeEvent; import me.overlight.powerlib.Chat.Text.impl.PlayerChatMessage; import me.overlight.powerlib.Chat.Text.impl.ext.ClickableCommand; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors;
7,083
package me.overlight.corescreen; public class Commands { public static String prefix; public static class Vanish implements CommandExecutor { private final HashMap<String, Long> cooldown_vanish = new HashMap<>(); private final HashMap<String, Long> cooldown_unvanish = new HashMap<>(); private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"), unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish"); @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 0) { if (!commandSender.hasPermission("corescreen.vanish.self")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) || (VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) { if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis()); else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis()); VanishManager.toggleVanish((Player) commandSender); if (VanishManager.isVanish((Player) commandSender)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute(); } } else { commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message")); } } else if (args.length == 1) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); VanishManager.toggleVanish(who); if (VanishManager.isVanish(who)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute(); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } boolean forceEnabled = args[1].equalsIgnoreCase("on"); List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); if (forceEnabled) VanishManager.vanishPlayer(who); else VanishManager.unVanishPlayer(who); if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Profiler implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("remove")) { if (!commandSender.hasPermission("corescreen.profiler.remove")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; }
package me.overlight.corescreen; public class Commands { public static String prefix; public static class Vanish implements CommandExecutor { private final HashMap<String, Long> cooldown_vanish = new HashMap<>(); private final HashMap<String, Long> cooldown_unvanish = new HashMap<>(); private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"), unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish"); @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 0) { if (!commandSender.hasPermission("corescreen.vanish.self")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) || (VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) { if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis()); else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis()); VanishManager.toggleVanish((Player) commandSender); if (VanishManager.isVanish((Player) commandSender)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute(); } } else { commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message")); } } else if (args.length == 1) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); VanishManager.toggleVanish(who); if (VanishManager.isVanish(who)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute(); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } boolean forceEnabled = args[1].equalsIgnoreCase("on"); List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); if (forceEnabled) VanishManager.vanishPlayer(who); else VanishManager.unVanishPlayer(who); if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Profiler implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("remove")) { if (!commandSender.hasPermission("corescreen.profiler.remove")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; }
ProfilerManager.removeProfiler((Player) commandSender);
7
2023-12-07 16:34:39+00:00
8k
Khoshimjonov/SalahTimes
src/main/java/uz/khoshimjonov/widget/SettingsWindow.java
[ { "identifier": "Api", "path": "src/main/java/uz/khoshimjonov/api/Api.java", "snippet": "public class Api {\n private static final String AL_ADHAN_URL = \"https://api.aladhan.com/v1/timings/%s?school=%s&method=%s&latitude=%s&longitude=%s\";\n private static final String NOMINATIM_URL = \"https://n...
import uz.khoshimjonov.api.Api; import uz.khoshimjonov.dto.MethodEnum; import uz.khoshimjonov.dto.NominatimResponse; import uz.khoshimjonov.service.ConfigurationManager; import uz.khoshimjonov.service.LanguageHelper; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.text.NumberFormatter; import java.awt.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import java.util.Objects;
5,079
package uz.khoshimjonov.widget; public class SettingsWindow extends JFrame { private final ConfigurationManager configManager; private final Api api = new Api(); private final JRadioButton shafiRadioButton; private final JRadioButton hanafiRadioButton; private final JTextField addressTextField; private final JLabel addressLabel; private final JTextField latitudeTextField; private final JTextField longitudeTextField; private final JComboBox<String> methodComboBox; private final JComboBox<String> languageComboBox; private final JFormattedTextField updateIntervalField; private final JFormattedTextField notificationBeforeField; private final JCheckBox notificationsCheckBox; private final JCheckBox lookAndFeelCheckBox; private final JCheckBox draggableCheckBox; private final JCheckBox alwaysOnTopCheckBox; public SettingsWindow() { this.configManager = ConfigurationManager.getInstance(); setTitle(LanguageHelper.getText("settingsTitle")); setSize(400, 300); try { setIconImage(ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/main.png")))); } catch (Exception ignored) {} setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationByPlatform(true); setLocationRelativeTo(null); List<String> methodNames = Arrays.stream(MethodEnum.values()).map(MethodEnum::getTitle).toList(); String[] methodNamesArray = methodNames.toArray(new String[0]); String[] localesArray = LanguageHelper.getAvailableLocales(); methodComboBox = new JComboBox<>(methodNamesArray); languageComboBox = new JComboBox<>(localesArray); shafiRadioButton = new JRadioButton(LanguageHelper.getText("shafiTitle")); hanafiRadioButton = new JRadioButton(LanguageHelper.getText("hanafiTitle")); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(shafiRadioButton); buttonGroup.add(hanafiRadioButton); JPanel schoolRadioButtonPanel = new JPanel(); schoolRadioButtonPanel.add(shafiRadioButton); schoolRadioButtonPanel.add(hanafiRadioButton); latitudeTextField = new JTextField(25); longitudeTextField = new JTextField(25); addressTextField = new JTextField(25); addressLabel = new JLabel(LanguageHelper.getText("addressLabelTitle")); JButton submitAddressButton = new JButton(LanguageHelper.getText("applyAddressTitle")); submitAddressButton.addActionListener(e -> fetchLatLongFromAddress()); JPanel addressPanel = new JPanel(); addressPanel.add(addressTextField); addressPanel.add(submitAddressButton); NumberFormat format = NumberFormat.getInstance(); NumberFormatter formatter = new NumberFormatter(format); formatter.setValueClass(Integer.class); formatter.setMinimum(1); formatter.setMaximum(1800); formatter.setAllowsInvalid(false); formatter.setCommitsOnValidEdit(true); updateIntervalField = new JFormattedTextField(formatter); updateIntervalField.setValue(1); updateIntervalField.setPreferredSize(new Dimension(100, updateIntervalField.getPreferredSize().height)); notificationBeforeField = new JFormattedTextField(formatter); notificationBeforeField.setValue(30); notificationBeforeField.setPreferredSize(new Dimension(100, updateIntervalField.getPreferredSize().height)); notificationsCheckBox = new JCheckBox(LanguageHelper.getText("notificationsTitle")); lookAndFeelCheckBox = new JCheckBox(LanguageHelper.getText("lookAndFeelTitle")); draggableCheckBox = new JCheckBox(LanguageHelper.getText("draggableTitle")); alwaysOnTopCheckBox = new JCheckBox(LanguageHelper.getText("alwaysOnTopTitle")); JPanel checkBoxPanel1 = new JPanel(); JPanel checkBoxPanel2 = new JPanel(); checkBoxPanel1.add(lookAndFeelCheckBox); checkBoxPanel1.add(draggableCheckBox); checkBoxPanel2.add(notificationsCheckBox); checkBoxPanel2.add(alwaysOnTopCheckBox); JButton submitButton = new JButton(LanguageHelper.getText("saveTitle")); submitButton.addActionListener(e -> saveSettings()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(submitButton); int order = 0; JPanel northGridPanel = new JPanel(); northGridPanel.setLayout(new GridBagLayout()); northGridPanel.add(new JLabel(LanguageHelper.getText("warning1")), getConstraints(0, order++)); northGridPanel.add(new JLabel(LanguageHelper.getText("warning2")), getConstraints(0, order++)); northGridPanel.add(new JLabel(LanguageHelper.getText("warning3")), getConstraints(0, order++)); northGridPanel.add(new JSeparator(), getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("addressTitle")), getConstraints(0, order++)); northGridPanel.add(addressPanel, getConstraints(0, order++, 5)); northGridPanel.add(addressLabel, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("latitudeTitle")), getConstraints(0, order++)); northGridPanel.add(latitudeTextField, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("longitudeTitle")), getConstraints(0, order++)); northGridPanel.add(longitudeTextField, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("methodTitle")), getConstraints(0, order++)); northGridPanel.add(methodComboBox, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("languageTitle")), getConstraints(0, order++)); northGridPanel.add(languageComboBox, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("schoolTitle")), getConstraints(0, order++)); northGridPanel.add(schoolRadioButtonPanel, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("updateIntervalTitle")), getConstraints(0, order++)); northGridPanel.add(updateIntervalField, getConstraints(0, order++, 15)); northGridPanel.add(checkBoxPanel1, getConstraints(0, order++)); northGridPanel.add(checkBoxPanel2, getConstraints(0, order++)); add(northGridPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); pack(); setVisible(true); setLocationRelativeTo(null); loadConfigValues(); } private void fetchLatLongFromAddress() { try { String address = URLEncoder.encode(addressTextField.getText(), StandardCharsets.UTF_8);
package uz.khoshimjonov.widget; public class SettingsWindow extends JFrame { private final ConfigurationManager configManager; private final Api api = new Api(); private final JRadioButton shafiRadioButton; private final JRadioButton hanafiRadioButton; private final JTextField addressTextField; private final JLabel addressLabel; private final JTextField latitudeTextField; private final JTextField longitudeTextField; private final JComboBox<String> methodComboBox; private final JComboBox<String> languageComboBox; private final JFormattedTextField updateIntervalField; private final JFormattedTextField notificationBeforeField; private final JCheckBox notificationsCheckBox; private final JCheckBox lookAndFeelCheckBox; private final JCheckBox draggableCheckBox; private final JCheckBox alwaysOnTopCheckBox; public SettingsWindow() { this.configManager = ConfigurationManager.getInstance(); setTitle(LanguageHelper.getText("settingsTitle")); setSize(400, 300); try { setIconImage(ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/main.png")))); } catch (Exception ignored) {} setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationByPlatform(true); setLocationRelativeTo(null); List<String> methodNames = Arrays.stream(MethodEnum.values()).map(MethodEnum::getTitle).toList(); String[] methodNamesArray = methodNames.toArray(new String[0]); String[] localesArray = LanguageHelper.getAvailableLocales(); methodComboBox = new JComboBox<>(methodNamesArray); languageComboBox = new JComboBox<>(localesArray); shafiRadioButton = new JRadioButton(LanguageHelper.getText("shafiTitle")); hanafiRadioButton = new JRadioButton(LanguageHelper.getText("hanafiTitle")); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(shafiRadioButton); buttonGroup.add(hanafiRadioButton); JPanel schoolRadioButtonPanel = new JPanel(); schoolRadioButtonPanel.add(shafiRadioButton); schoolRadioButtonPanel.add(hanafiRadioButton); latitudeTextField = new JTextField(25); longitudeTextField = new JTextField(25); addressTextField = new JTextField(25); addressLabel = new JLabel(LanguageHelper.getText("addressLabelTitle")); JButton submitAddressButton = new JButton(LanguageHelper.getText("applyAddressTitle")); submitAddressButton.addActionListener(e -> fetchLatLongFromAddress()); JPanel addressPanel = new JPanel(); addressPanel.add(addressTextField); addressPanel.add(submitAddressButton); NumberFormat format = NumberFormat.getInstance(); NumberFormatter formatter = new NumberFormatter(format); formatter.setValueClass(Integer.class); formatter.setMinimum(1); formatter.setMaximum(1800); formatter.setAllowsInvalid(false); formatter.setCommitsOnValidEdit(true); updateIntervalField = new JFormattedTextField(formatter); updateIntervalField.setValue(1); updateIntervalField.setPreferredSize(new Dimension(100, updateIntervalField.getPreferredSize().height)); notificationBeforeField = new JFormattedTextField(formatter); notificationBeforeField.setValue(30); notificationBeforeField.setPreferredSize(new Dimension(100, updateIntervalField.getPreferredSize().height)); notificationsCheckBox = new JCheckBox(LanguageHelper.getText("notificationsTitle")); lookAndFeelCheckBox = new JCheckBox(LanguageHelper.getText("lookAndFeelTitle")); draggableCheckBox = new JCheckBox(LanguageHelper.getText("draggableTitle")); alwaysOnTopCheckBox = new JCheckBox(LanguageHelper.getText("alwaysOnTopTitle")); JPanel checkBoxPanel1 = new JPanel(); JPanel checkBoxPanel2 = new JPanel(); checkBoxPanel1.add(lookAndFeelCheckBox); checkBoxPanel1.add(draggableCheckBox); checkBoxPanel2.add(notificationsCheckBox); checkBoxPanel2.add(alwaysOnTopCheckBox); JButton submitButton = new JButton(LanguageHelper.getText("saveTitle")); submitButton.addActionListener(e -> saveSettings()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(submitButton); int order = 0; JPanel northGridPanel = new JPanel(); northGridPanel.setLayout(new GridBagLayout()); northGridPanel.add(new JLabel(LanguageHelper.getText("warning1")), getConstraints(0, order++)); northGridPanel.add(new JLabel(LanguageHelper.getText("warning2")), getConstraints(0, order++)); northGridPanel.add(new JLabel(LanguageHelper.getText("warning3")), getConstraints(0, order++)); northGridPanel.add(new JSeparator(), getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("addressTitle")), getConstraints(0, order++)); northGridPanel.add(addressPanel, getConstraints(0, order++, 5)); northGridPanel.add(addressLabel, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("latitudeTitle")), getConstraints(0, order++)); northGridPanel.add(latitudeTextField, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("longitudeTitle")), getConstraints(0, order++)); northGridPanel.add(longitudeTextField, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("methodTitle")), getConstraints(0, order++)); northGridPanel.add(methodComboBox, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("languageTitle")), getConstraints(0, order++)); northGridPanel.add(languageComboBox, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("schoolTitle")), getConstraints(0, order++)); northGridPanel.add(schoolRadioButtonPanel, getConstraints(0, order++, 15)); northGridPanel.add(new JLabel(LanguageHelper.getText("updateIntervalTitle")), getConstraints(0, order++)); northGridPanel.add(updateIntervalField, getConstraints(0, order++, 15)); northGridPanel.add(checkBoxPanel1, getConstraints(0, order++)); northGridPanel.add(checkBoxPanel2, getConstraints(0, order++)); add(northGridPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); pack(); setVisible(true); setLocationRelativeTo(null); loadConfigValues(); } private void fetchLatLongFromAddress() { try { String address = URLEncoder.encode(addressTextField.getText(), StandardCharsets.UTF_8);
List<NominatimResponse> positionByAddress = api.getPositionByAddress(address);
2
2023-12-07 13:40:16+00:00
8k
Akshar062/MovieReviews
app/src/main/java/com/akshar/moviereviews/adapters/MovieAdapter.java
[ { "identifier": "MainActivity", "path": "app/src/main/java/com/akshar/moviereviews/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n //Define parameters here\n private ViewPager viewPager;\n private BottomNavigationView bottomNavigationView;\n\n\n @Ove...
import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.RecyclerView; import com.akshar.moviereviews.MainActivity; import com.akshar.moviereviews.Models.AllModel; import com.akshar.moviereviews.R; import com.akshar.moviereviews.Utils.Constants; import com.akshar.moviereviews.Utils.GenreHelper; import com.akshar.moviereviews.fragments.DetailsFragment; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import java.util.Map;
4,261
package com.akshar.moviereviews.adapters; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> { private Context context; private List<AllModel.Result> resultList; public MovieAdapter(Context context, List<AllModel.Result> resultList) { this.context = context; this.resultList = resultList; } @NonNull @Override public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false); return new MovieViewHolder(view); } @Override public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) { AllModel.Result result = resultList.get(position); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDetailsDialog(result); } }); holder.progressBar.setVisibility(View.VISIBLE); switch (result.getMediaType()) { case "movie": holder.movieName.setText(result.getTitle()); holder.movieReleaseDate.setText(result.getReleaseDate()); holder.movieRating.setText(String.valueOf(result.getVoteAverage())); setImage(holder,result.getPosterPath()); break; case "tv": holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getFirstAirDate()); holder.movieRating.setText(String.valueOf(result.getVoteAverage())); setImage(holder,result.getPosterPath()); break; case "person": holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getKnownForDepartment()); holder.movieRating.setText(String.valueOf(result.getPopularity())); setImage(holder,result.getProfilePath()); break; } } private void showDetailsDialog(AllModel.Result result) { List<AllModel.Result.KnownFor> knownForList = result.getKnownFor(); DetailsFragment detailsFragment = new DetailsFragment(); // Pass data to the fragment using Bundle Bundle bundle = new Bundle(); switch (result.getMediaType()) { case "movie": bundle.putString("title", result.getTitle()); bundle.putString("releaseDate", result.getReleaseDate()); bundle.putString("posterPath", result.getBackdropPath()); bundle.putString("overview", result.getOverview()); List<Integer> movieGenreIds = result.getGenreIds();
package com.akshar.moviereviews.adapters; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> { private Context context; private List<AllModel.Result> resultList; public MovieAdapter(Context context, List<AllModel.Result> resultList) { this.context = context; this.resultList = resultList; } @NonNull @Override public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false); return new MovieViewHolder(view); } @Override public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) { AllModel.Result result = resultList.get(position); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDetailsDialog(result); } }); holder.progressBar.setVisibility(View.VISIBLE); switch (result.getMediaType()) { case "movie": holder.movieName.setText(result.getTitle()); holder.movieReleaseDate.setText(result.getReleaseDate()); holder.movieRating.setText(String.valueOf(result.getVoteAverage())); setImage(holder,result.getPosterPath()); break; case "tv": holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getFirstAirDate()); holder.movieRating.setText(String.valueOf(result.getVoteAverage())); setImage(holder,result.getPosterPath()); break; case "person": holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getKnownForDepartment()); holder.movieRating.setText(String.valueOf(result.getPopularity())); setImage(holder,result.getProfilePath()); break; } } private void showDetailsDialog(AllModel.Result result) { List<AllModel.Result.KnownFor> knownForList = result.getKnownFor(); DetailsFragment detailsFragment = new DetailsFragment(); // Pass data to the fragment using Bundle Bundle bundle = new Bundle(); switch (result.getMediaType()) { case "movie": bundle.putString("title", result.getTitle()); bundle.putString("releaseDate", result.getReleaseDate()); bundle.putString("posterPath", result.getBackdropPath()); bundle.putString("overview", result.getOverview()); List<Integer> movieGenreIds = result.getGenreIds();
List<String> movieGenres = getGenresAsString(movieGenreIds, GenreHelper.getAllMovieGenres());
3
2023-12-05 10:20:16+00:00
8k
fabriciofx/cactoos-pdf
src/main/java/com/github/fabriciofx/cactoos/pdf/content/Image.java
[ { "identifier": "Content", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Content.java", "snippet": "@SuppressWarnings(\"PMD.ExtendsObject\")\npublic interface Content extends Object {\n /**\n * Stream of a content.\n *\n * @return The stream content\n * @throws Exception if...
import com.github.fabriciofx.cactoos.pdf.type.Dictionary; import com.github.fabriciofx.cactoos.pdf.type.Int; import com.github.fabriciofx.cactoos.pdf.type.Stream; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import org.cactoos.list.ListOf; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; import com.github.fabriciofx.cactoos.pdf.Content; import com.github.fabriciofx.cactoos.pdf.Id; import com.github.fabriciofx.cactoos.pdf.Indirect; import com.github.fabriciofx.cactoos.pdf.Resource; import com.github.fabriciofx.cactoos.pdf.image.Format; import com.github.fabriciofx.cactoos.pdf.indirect.DefaultIndirect; import com.github.fabriciofx.cactoos.pdf.resource.XObject;
4,193
/* * 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.content; /** * Image. * * @since 0.0.1 */ public final class Image implements Content { /** * Object number. */ private final int number; /** * Generation number. */ private final int generation; /** * Resource. */ private final Resource resrc; /** * Image Format. */ private final Format fmt; /** * Position X. */ private final double posx; /** * Position Y. */ private final double posy; /** * Ctor. * * @param id Id number * @param format Raw image format * @param posx Position X * @param posy Position Y * @checkstyle ParameterNumberCheck (10 lines) */ public Image( final Id id, final Format format, final double posx, final double posy ) { this( id.increment(), 0, id, format, posx, posy ); } /** * Ctor. * * @param number Object number * @param generation Generation number * @param id Id number * @param format Raw image format * @param posx Position X * @param posy Position Y * @checkstyle ParameterNumberCheck (10 lines) */ public Image( final int number, final int generation, final Id id, final Format format, final double posx, final double posy ) { this.number = number; this.generation = generation; this.fmt = format; this.posx = posx; this.posy = posy; this.resrc = new XObject(id, this); } /** * Image name. * * @return The image name */ public String name() { return new UncheckedText( new FormattedText("I%d", this.number) ).asString(); } @Override public byte[] asStream() throws Exception { return new FormattedText( "q %d 0 0 %d %.2f %.2f cm /%s Do Q", Locale.ENGLISH, this.fmt.width(), this.fmt.height(), this.posx, this.posy, this.name() ).asString().getBytes(StandardCharsets.UTF_8); } @Override public List<Resource> resource() { return new ListOf<>(this.resrc); } @Override
/* * 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.content; /** * Image. * * @since 0.0.1 */ public final class Image implements Content { /** * Object number. */ private final int number; /** * Generation number. */ private final int generation; /** * Resource. */ private final Resource resrc; /** * Image Format. */ private final Format fmt; /** * Position X. */ private final double posx; /** * Position Y. */ private final double posy; /** * Ctor. * * @param id Id number * @param format Raw image format * @param posx Position X * @param posy Position Y * @checkstyle ParameterNumberCheck (10 lines) */ public Image( final Id id, final Format format, final double posx, final double posy ) { this( id.increment(), 0, id, format, posx, posy ); } /** * Ctor. * * @param number Object number * @param generation Generation number * @param id Id number * @param format Raw image format * @param posx Position X * @param posy Position Y * @checkstyle ParameterNumberCheck (10 lines) */ public Image( final int number, final int generation, final Id id, final Format format, final double posx, final double posy ) { this.number = number; this.generation = generation; this.fmt = format; this.posx = posx; this.posy = posy; this.resrc = new XObject(id, this); } /** * Image name. * * @return The image name */ public String name() { return new UncheckedText( new FormattedText("I%d", this.number) ).asString(); } @Override public byte[] asStream() throws Exception { return new FormattedText( "q %d 0 0 %d %.2f %.2f cm /%s Do Q", Locale.ENGLISH, this.fmt.width(), this.fmt.height(), this.posx, this.posy, this.name() ).asString().getBytes(StandardCharsets.UTF_8); } @Override public List<Resource> resource() { return new ListOf<>(this.resrc); } @Override
public Indirect indirect() throws Exception {
2
2023-12-05 00:07:24+00:00
8k
ibm-messaging/kafka-connect-xml-converter
src/main/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/XmlConverter.java
[ { "identifier": "CollectionToXmlBytes", "path": "src/main/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/engines/CollectionToXmlBytes.java", "snippet": "public class CollectionToXmlBytes extends ToXmlBytes {\n\n private final Logger log = LoggerFactory.getLogger(CollectionToXmlBytes.class);\n\n ...
import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.StructToXmlBytes; import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.XmlBytesToStruct; import com.ibm.eventstreams.kafkaconnect.plugins.xml.exceptions.NotImplementedException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.storage.Converter; import org.apache.kafka.connect.storage.ConverterConfig; import org.apache.kafka.connect.storage.ConverterType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.CollectionToXmlBytes;
6,205
/** * Copyright 2023 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.eventstreams.kafkaconnect.plugins.xml; public class XmlConverter implements Converter { private final Logger log = LoggerFactory.getLogger(XmlConverter.class); private XmlPluginsConfig config; private StructToXmlBytes structToXml = null; private CollectionToXmlBytes collectionToStruct = null;
/** * Copyright 2023 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.eventstreams.kafkaconnect.plugins.xml; public class XmlConverter implements Converter { private final Logger log = LoggerFactory.getLogger(XmlConverter.class); private XmlPluginsConfig config; private StructToXmlBytes structToXml = null; private CollectionToXmlBytes collectionToStruct = null;
private XmlBytesToStruct xmlToStruct = null;
2
2023-12-11 13:56:48+00:00
8k
BeansGalaxy/Beans-Backpacks-2
fabric/src/main/java/com/beansgalaxy/backpacks/events/ElytraFlightEvent.java
[ { "identifier": "Constants", "path": "common/src/main/java/com/beansgalaxy/backpacks/Constants.java", "snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"beansbackpacks\";\n\tpublic static final String MOD_NAME = \"Beans' Backpacks\";\n\tpublic static final Logger LOG = Logge...
import com.beansgalaxy.backpacks.Constants; import com.beansgalaxy.backpacks.screen.BackSlot; import net.fabricmc.fabric.api.entity.event.v1.EntityElytraEvents; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ElytraItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.gameevent.GameEvent;
3,881
package com.beansgalaxy.backpacks.events; public class ElytraFlightEvent implements EntityElytraEvents.Custom { @Override public boolean useCustomElytra(LivingEntity entity, boolean tickElytra) { if (Constants.CHESTPLATE_DISABLED.contains(Items.ELYTRA) && entity instanceof Player player) {
package com.beansgalaxy.backpacks.events; public class ElytraFlightEvent implements EntityElytraEvents.Custom { @Override public boolean useCustomElytra(LivingEntity entity, boolean tickElytra) { if (Constants.CHESTPLATE_DISABLED.contains(Items.ELYTRA) && entity instanceof Player player) {
ItemStack backStack = BackSlot.get(player).getItem();
1
2023-12-14 21:55:00+00:00
8k
CADIndie/Scout
src/main/java/pm/c7/scout/mixin/ServerPlayerEntityMixin.java
[ { "identifier": "ScoutNetworking", "path": "src/main/java/pm/c7/scout/ScoutNetworking.java", "snippet": "public class ScoutNetworking {\n public static final Identifier ENABLE_SLOTS = new Identifier(Scout.MOD_ID, \"enable_slots\");\n}" }, { "identifier": "ScoutPlayerScreenHandler", "path"...
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.entity.damage.DamageSource; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.collection.DefaultedList; import net.minecraft.world.GameRules; import pm.c7.scout.ScoutNetworking; import pm.c7.scout.ScoutPlayerScreenHandler; import pm.c7.scout.ScoutUtil; import pm.c7.scout.item.BaseBagItem; import pm.c7.scout.item.BaseBagItem.BagType; import pm.c7.scout.screen.BagSlot;
3,930
package pm.c7.scout.mixin; @SuppressWarnings("deprecation") @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "onDeath", at = @At("HEAD")) private void scout$attemptFixGraveMods(DamageSource source, CallbackInfo callbackInfo) { ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler; if (!player.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY)) { ItemStack backStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false); if (!backStack.isEmpty()) {
package pm.c7.scout.mixin; @SuppressWarnings("deprecation") @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "onDeath", at = @At("HEAD")) private void scout$attemptFixGraveMods(DamageSource source, CallbackInfo callbackInfo) { ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler; if (!player.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY)) { ItemStack backStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false); if (!backStack.isEmpty()) {
BaseBagItem bagItem = (BaseBagItem) backStack.getItem();
3
2023-12-10 07:43:34+00:00
8k
Viola-Siemens/Mod-Whitelist
src/main/java/com/hexagram2021/mod_whitelist/mixin/ServerHandshakePacketListenerImplMixin.java
[ { "identifier": "IPacketWithModIds", "path": "src/main/java/com/hexagram2021/mod_whitelist/common/network/IPacketWithModIds.java", "snippet": "public interface IPacketWithModIds {\n\t@Nullable\n\tList<String> getModIds();\n\n\t@SuppressWarnings(\"unused\")\n\tvoid setModIds(@Nullable List<String> modIds...
import com.hexagram2021.mod_whitelist.common.network.IPacketWithModIds; import com.hexagram2021.mod_whitelist.server.config.MWServerConfig; import com.hexagram2021.mod_whitelist.server.config.MismatchType; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.protocol.handshake.ClientIntentionPacket; import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; import net.minecraft.server.network.ServerHandshakePacketListenerImpl; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List;
3,911
package com.hexagram2021.mod_whitelist.mixin; @Mixin(ServerHandshakePacketListenerImpl.class) public class ServerHandshakePacketListenerImplMixin { @Shadow @Final private Connection connection; @Inject(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/Connection;setProtocol(Lnet/minecraft/network/ConnectionProtocol;)V", shift = At.Shift.AFTER, ordinal = 0), cancellable = true) private void tryDisconnectPlayersIfModlistNotMatches(ClientIntentionPacket clientIntentionPacket, CallbackInfo ci) { MutableComponent reason = null; if(clientIntentionPacket instanceof IPacketWithModIds packetWithModIds && packetWithModIds.getModIds() != null) {
package com.hexagram2021.mod_whitelist.mixin; @Mixin(ServerHandshakePacketListenerImpl.class) public class ServerHandshakePacketListenerImplMixin { @Shadow @Final private Connection connection; @Inject(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/Connection;setProtocol(Lnet/minecraft/network/ConnectionProtocol;)V", shift = At.Shift.AFTER, ordinal = 0), cancellable = true) private void tryDisconnectPlayersIfModlistNotMatches(ClientIntentionPacket clientIntentionPacket, CallbackInfo ci) { MutableComponent reason = null; if(clientIntentionPacket instanceof IPacketWithModIds packetWithModIds && packetWithModIds.getModIds() != null) {
List<Pair<String, MismatchType>> mismatches = MWServerConfig.test(packetWithModIds.getModIds());
2
2023-12-06 12:16:52+00:00
8k
sinbad-navigator/erp-crm
common/src/main/java/com/ec/common/utils/file/FileUtils.java
[ { "identifier": "ErpCrmConfig", "path": "common/src/main/java/com/ec/common/config/ErpCrmConfig.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"ec\")\npublic class ErpCrmConfig {\n /**\n * 上传路径\n */\n private static String profile;\n /**\n * 获取地址开关\n */\n p...
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import com.ec.common.config.ErpCrmConfig; import com.ec.common.utils.DateUtils; import com.ec.common.utils.StringUtils; import com.ec.common.utils.uuid.IdUtils;
6,010
package com.ec.common.utils.file; /** * 文件处理工具类 * * @author ec */ public class FileUtils { public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 * * @param filePath 文件路径 * @param os 输出流 * @return */ public static void writeBytes(String filePath, OutputStream os) throws IOException { FileInputStream fis = null; try { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } fis = new FileInputStream(file); byte[] b = new byte[1024]; int length; while ((length = fis.read(b)) > 0) { os.write(b, 0, length); } } catch (IOException e) { throw e; } finally { IOUtils.close(os); IOUtils.close(fis); } } /** * 写数据到文件中 * * @param data 数据 * @return 目标文件 * @throws IOException IO异常 */ public static String writeImportBytes(byte[] data) throws IOException {
package com.ec.common.utils.file; /** * 文件处理工具类 * * @author ec */ public class FileUtils { public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 * * @param filePath 文件路径 * @param os 输出流 * @return */ public static void writeBytes(String filePath, OutputStream os) throws IOException { FileInputStream fis = null; try { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } fis = new FileInputStream(file); byte[] b = new byte[1024]; int length; while ((length = fis.read(b)) > 0) { os.write(b, 0, length); } } catch (IOException e) { throw e; } finally { IOUtils.close(os); IOUtils.close(fis); } } /** * 写数据到文件中 * * @param data 数据 * @return 目标文件 * @throws IOException IO异常 */ public static String writeImportBytes(byte[] data) throws IOException {
return writeBytes(data, ErpCrmConfig.getImportPath());
0
2023-12-07 14:23:12+00:00
8k
FRC8806/frcBT_2023
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "ChangPipeLine", "path": "src/main/java/frc/robot/commands/ChangPipeLine.java", "snippet": "public class ChangPipeLine extends CommandBase {\n Limelight limelight;\n int pipeLine;\n\n public ChangPipeLine(Limelight limelight, int pipeLine) {\n this.limelight = limelight;\n this....
import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.commands.ChangPipeLine; import frc.robot.commands.TeleSwerveControl; import frc.robot.commands.auto.AprilTagTracking; import frc.robot.commands.auto.AutoMap; import frc.robot.constants.ControllerConstants; import frc.robot.subsystems.Limelight; import frc.robot.subsystems.chassis.DriveTrain;
3,611
// ___________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________ // 88 88 88 88 00 00 66 // 88 88 88 88 00 00 66 ________________________ // 88 88 88 88 00 00 66 // 8888888888888888 8888888888888888 00 00 6666666666666666 _____________ // 88 88 88 88 00 00 66 66 // 88 88 88 88 00 00 66 66 _____________________ // 88 88 88 88 00 00 66 66 ________________________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________ // __________________________ __________ package frc.robot; public class RobotContainer { // instantiate controller here public static XboxController driverController = new XboxController(ControllerConstants.DRIVER_CONTROLLER_PORT); public static XboxController operaterController = new XboxController(ControllerConstants.OPERATER_CONTROLLER_PORT); // instantiate subsystem here
// ___________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________ // 88 88 88 88 00 00 66 // 88 88 88 88 00 00 66 ________________________ // 88 88 88 88 00 00 66 // 8888888888888888 8888888888888888 00 00 6666666666666666 _____________ // 88 88 88 88 00 00 66 66 // 88 88 88 88 00 00 66 66 _____________________ // 88 88 88 88 00 00 66 66 ________________________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________ // __________________________ __________ package frc.robot; public class RobotContainer { // instantiate controller here public static XboxController driverController = new XboxController(ControllerConstants.DRIVER_CONTROLLER_PORT); public static XboxController operaterController = new XboxController(ControllerConstants.OPERATER_CONTROLLER_PORT); // instantiate subsystem here
public static DriveTrain driveTrain = new DriveTrain();
6
2023-12-13 11:38:11+00:00
8k
ganeshbabugb/NASC-CMS
src/main/java/com/nasc/application/views/auth/create/CreateUsers.java
[ { "identifier": "AcademicYearEntity", "path": "src/main/java/com/nasc/application/data/core/AcademicYearEntity.java", "snippet": "@Data\n@Entity\n@Table(name = \"t_academic_year\")\npublic class AcademicYearEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY...
import com.flowingcode.vaadin.addons.fontawesome.FontAwesome; import com.nasc.application.data.core.AcademicYearEntity; import com.nasc.application.data.core.DepartmentEntity; import com.nasc.application.data.core.User; import com.nasc.application.data.core.enums.Role; import com.nasc.application.data.core.enums.StudentSection; import com.nasc.application.services.AcademicYearService; import com.nasc.application.services.DepartmentService; import com.nasc.application.services.UserService; import com.nasc.application.utils.NotificationUtils; import com.nasc.application.views.MainLayout; import com.opencsv.CSVReader; import com.opencsv.bean.CsvToBeanBuilder; import com.opencsv.bean.HeaderColumnNameMappingStrategy; import com.opencsv.exceptions.CsvException; import com.vaadin.flow.component.HasValue; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.checkbox.Checkbox; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.GridVariant; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.upload.SucceededEvent; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.data.provider.DataProvider; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.theme.lumo.LumoIcon; import jakarta.annotation.security.RolesAllowed; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.vaadin.olli.FileDownloadWrapper; import java.io.*; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
6,250
package com.nasc.application.views.auth.create; @PageTitle("Create User Account") @Route(value = "create-user", layout = MainLayout.class) @RolesAllowed({"EDITOR", "ADMIN"}) @JsModule("./recipe/copytoclipboard/copytoclipboard.js") @Slf4j public class CreateUsers extends VerticalLayout { private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final UserService userService; private final PasswordEncoder passwordEncoder; private final Upload upload; private final Grid<User> userGrid; private final Checkbox verifyCheckbox; private final Button createUserButton; private ComboBox<Role> roleComboBox; private ComboBox<DepartmentEntity> departmentComboBox;
package com.nasc.application.views.auth.create; @PageTitle("Create User Account") @Route(value = "create-user", layout = MainLayout.class) @RolesAllowed({"EDITOR", "ADMIN"}) @JsModule("./recipe/copytoclipboard/copytoclipboard.js") @Slf4j public class CreateUsers extends VerticalLayout { private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final UserService userService; private final PasswordEncoder passwordEncoder; private final Upload upload; private final Grid<User> userGrid; private final Checkbox verifyCheckbox; private final Button createUserButton; private ComboBox<Role> roleComboBox; private ComboBox<DepartmentEntity> departmentComboBox;
private ComboBox<AcademicYearEntity> academicYearComboBox;
0
2023-12-10 18:07:28+00:00
8k
Viola-Siemens/StellarForge
src/main/java/com/hexagram2021/stellarforge/mixin/I18nMixin.java
[ { "identifier": "SFCommonConfig", "path": "src/main/java/com/hexagram2021/stellarforge/common/config/SFCommonConfig.java", "snippet": "public class SFCommonConfig {\n\tprivate static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n\tprivate static final ForgeConfigSpec SPEC;\n\n\...
import com.hexagram2021.stellarforge.common.config.SFCommonConfig; import com.hexagram2021.stellarforge.common.util.RegistryChecker; import net.minecraft.client.resources.language.I18n; import net.minecraft.locale.Language; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
6,437
package com.hexagram2021.stellarforge.mixin; @Mixin(I18n.class) public class I18nMixin { @Inject(method = "setLanguage", at = @At(value = "TAIL")) private static void checkI18n(Language language, CallbackInfo ci) { if(SFCommonConfig.ENABLE_REGISTRY_CHECK.get()) {
package com.hexagram2021.stellarforge.mixin; @Mixin(I18n.class) public class I18nMixin { @Inject(method = "setLanguage", at = @At(value = "TAIL")) private static void checkI18n(Language language, CallbackInfo ci) { if(SFCommonConfig.ENABLE_REGISTRY_CHECK.get()) {
RegistryChecker.i18nCheck();
1
2023-12-10 07:20:43+00:00
8k
nilsgenge/finite-state-machine-visualizer
src/gui/Toolbar.java
[ { "identifier": "MouseInputs", "path": "src/inputs/MouseInputs.java", "snippet": "public class MouseInputs implements MouseListener {\n\n\tprivate Boolean m1Pressed = false; // left mouse button\n\tprivate Boolean m2Pressed = false; // right mouse button\n\tprivate Boolean m3Pressed = false; // middle m...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.util.LinkedList; import inputs.MouseInputs; import utilz.colortable; import utilz.tools; import workspace.ToolHandler; import workspace.Transition;
5,558
package gui; public class Toolbar { private GuiHandler gh; private MouseInputs m; private ToolHandler th; private int height = 100; private LinkedList<ToolButton> toolButtons; public Toolbar(GuiHandler gh, MouseInputs m, ToolHandler th) { this.gh = gh; this.m = m; this.th = th; toolButtons = new LinkedList<ToolButton>(); initializeToolButtons(); } public void render(Graphics2D g2) { g2.setStroke(new BasicStroke(3));
package gui; public class Toolbar { private GuiHandler gh; private MouseInputs m; private ToolHandler th; private int height = 100; private LinkedList<ToolButton> toolButtons; public Toolbar(GuiHandler gh, MouseInputs m, ToolHandler th) { this.gh = gh; this.m = m; this.th = th; toolButtons = new LinkedList<ToolButton>(); initializeToolButtons(); } public void render(Graphics2D g2) { g2.setStroke(new BasicStroke(3));
g2.setColor(colortable.BG_MENU);
1
2023-12-12 20:43:41+00:00
8k
kaushikMreddy293/Cafe-Management-with-Java
CafeManagement/src/main/java/edu/neu/cafemanagement/Items.java
[ { "identifier": "BeverageFactoryLazySingleton", "path": "CafeManagement/src/main/java/edu/neu/csye6200/BeverageFactoryLazySingleton.java", "snippet": "public class BeverageFactoryLazySingleton implements CafeItemFactoryAPI {\n private static BeverageFactoryLazySingleton instance;\n\n private Bever...
import edu.neu.csye6200.BeverageFactoryLazySingleton; import edu.neu.csye6200.CafeItem; import edu.neu.csye6200.CakeFactoryLazySingleton; import edu.neu.csye6200.ShakeFactoryEagerSingleton; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import net.proteanit.sql.DbUtils;
3,951
SellingLbMouseClicked(evt); } }); VIewBillsLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N VIewBillsLb.setForeground(new java.awt.Color(255, 51, 51)); VIewBillsLb.setText("View Bills"); VIewBillsLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { VIewBillsLbMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(VIewBillsLb, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE) .addGap(18, 18, 18))) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(920, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(183, 183, 183) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(VIewBillsLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(148, 148, 148) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(394, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void PriceTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PriceTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PriceTbActionPerformed private void PrNameTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrNameTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PrNameTbActionPerformed private void ShowProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { } } private void FilterProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl where Category='" + FilterCb.getSelectedItem().toString()+"'"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { JOptionPane.showMessageDialog(this, e); } } private void AddBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBtnActionPerformed if( PrNameTb.getText().isEmpty() && PriceTb.getText().isEmpty() && PrCatCb.getSelectedIndex() != -1) { JOptionPane.showMessageDialog(this, "Missing Information!"); } else { String Temp = PrCatCb.getSelectedItem().toString(); if(Temp.equalsIgnoreCase("Beverage")) {
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package edu.neu.cafemanagement; /** * * @author kaush */ public class Items extends javax.swing.JFrame { /** * Creates new form Items */ public Items() { initComponents(); ShowProducts(); } ResultSet Rs = null, Rs1 = null; Connection Con = null; Statement St = null, St1 = null; int PrNum; String dbUrl = "jdbc:mysql://localhost:3306/cafedb"; String dbUser = "root"; String dbPwd = "cnwFri_123"; private void CountProd() { try { St1 = Con.createStatement(); Rs1 = St1.executeQuery("select Max(PNum) from ProductTbl"); Rs1.next(); PrNum = Rs1.getInt(1)+1; } catch (Exception e) { } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); PriceTb = new javax.swing.JTextField(); PrNameTb = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); PrCatCb = new javax.swing.JComboBox<>(); jLabel9 = new javax.swing.JLabel(); AddBtn = new javax.swing.JButton(); DeleteBtn = new javax.swing.JButton(); EditBtn = new javax.swing.JButton(); FilterCb = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); ProductList = new javax.swing.JTable(); RefreshBtn = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); ItemsLogoutBtn = new javax.swing.JLabel(); SellingLb = new javax.swing.JLabel(); VIewBillsLb = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBackground(new java.awt.Color(255, 51, 102)); jLabel4.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Items List"); PriceTb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PriceTbActionPerformed(evt); } }); PrNameTb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PrNameTbActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Price"); jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Category"); jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Name"); jLabel8.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("Items Management"); PrCatCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Beverage", "Shake", "Cake", " " })); PrCatCb.setToolTipText(""); jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("Filter"); AddBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N AddBtn.setText("Add"); AddBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddBtnActionPerformed(evt); } }); DeleteBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N DeleteBtn.setText("Delete"); DeleteBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DeleteBtnActionPerformed(evt); } }); EditBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N EditBtn.setText("Edit"); EditBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EditBtnActionPerformed(evt); } }); FilterCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Beverage", "Shake", "Cake", " " })); FilterCb.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { FilterCbItemStateChanged(evt); } }); ProductList.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "ID", "Name", "Category", "Price" } )); ProductList.setRowHeight(30); ProductList.setShowHorizontalLines(true); ProductList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ProductListMouseClicked(evt); } }); jScrollPane1.setViewportView(ProductList); RefreshBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N RefreshBtn.setText("Refresh"); RefreshBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RefreshBtnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(103, 103, 103) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrNameTb, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(132, 132, 132)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(PrCatCb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(PriceTb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(126, 126, 126)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(324, 324, 324) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FilterCb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(RefreshBtn)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(198, 198, 198) .addComponent(DeleteBtn) .addGap(108, 108, 108) .addComponent(AddBtn) .addGap(132, 132, 132) .addComponent(EditBtn)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(357, 357, 357) .addComponent(jLabel4))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(345, 345, 345) .addComponent(jLabel8) .addContainerGap(372, Short.MAX_VALUE))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(75, 75, 75) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PriceTb, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrNameTb, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrCatCb, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddBtn) .addComponent(DeleteBtn) .addComponent(EditBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(FilterCb, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addGap(21, 21, 21)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(RefreshBtn) .addGap(27, 27, 27))) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(487, Short.MAX_VALUE))) ); jLabel2.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 51, 51)); jLabel2.setText("Items"); ItemsLogoutBtn.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N ItemsLogoutBtn.setForeground(new java.awt.Color(255, 51, 51)); ItemsLogoutBtn.setText("Logout"); ItemsLogoutBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ItemsLogoutBtnMouseClicked(evt); } }); SellingLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N SellingLb.setForeground(new java.awt.Color(255, 51, 51)); SellingLb.setText("Selling"); SellingLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { SellingLbMouseClicked(evt); } }); VIewBillsLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N VIewBillsLb.setForeground(new java.awt.Color(255, 51, 51)); VIewBillsLb.setText("View Bills"); VIewBillsLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { VIewBillsLbMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(VIewBillsLb, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE) .addGap(18, 18, 18))) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(920, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(183, 183, 183) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(VIewBillsLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(148, 148, 148) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(394, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void PriceTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PriceTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PriceTbActionPerformed private void PrNameTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrNameTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PrNameTbActionPerformed private void ShowProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { } } private void FilterProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl where Category='" + FilterCb.getSelectedItem().toString()+"'"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { JOptionPane.showMessageDialog(this, e); } } private void AddBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBtnActionPerformed if( PrNameTb.getText().isEmpty() && PriceTb.getText().isEmpty() && PrCatCb.getSelectedIndex() != -1) { JOptionPane.showMessageDialog(this, "Missing Information!"); } else { String Temp = PrCatCb.getSelectedItem().toString(); if(Temp.equalsIgnoreCase("Beverage")) {
BeverageFactoryLazySingleton bItem = BeverageFactoryLazySingleton.getInstance();
0
2023-12-14 22:44:56+00:00
8k
zerodevstuff/ExploitFixerv2
src/main/java/dev/_2lstudios/exploitfixer/utils/ExploitUtil.java
[ { "identifier": "CheckItemResult", "path": "src/main/java/dev/_2lstudios/exploitfixer/enums/CheckItemResult.java", "snippet": "public enum CheckItemResult {\n // General Items\n INVALID_ITEM,\n INVALID_ITEM_NAME,\n INVALID_ITEM_LORE,\n // Fireworks\n INVALID_FIREWORK_POWER, \n INVAL...
import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.List; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import dev._2lstudios.exploitfixer.enums.CheckItemResult; import dev._2lstudios.exploitfixer.exploit.BukkitExploitPlayer; import dev._2lstudios.exploitfixer.managers.ExploitPlayerManager; import dev._2lstudios.exploitfixer.managers.ModuleManager; import dev._2lstudios.exploitfixer.modules.CreativeItemsFixModule; import dev._2lstudios.exploitfixer.modules.NotificationsModule; import dev._2lstudios.exploitfixer.modules.PacketsModule; import dev._2lstudios.exploitfixer.modules.interfaces.ViolationModule; import dev._2lstudios.hamsterapi.hamsterplayer.HamsterPlayer;
7,128
package dev._2lstudios.exploitfixer.utils; public class ExploitUtil { private ExploitPlayerManager exploitPlayerManager; private CreativeItemsFixModule itemsFixModule;
package dev._2lstudios.exploitfixer.utils; public class ExploitUtil { private ExploitPlayerManager exploitPlayerManager; private CreativeItemsFixModule itemsFixModule;
private NotificationsModule notificationsModule;
5
2023-12-13 21:49:27+00:00
8k
xuexu2/Crasher
src/main/java/cn/xuexu/crasher/utils/Utils.java
[ { "identifier": "Crasher", "path": "src/main/java/cn/xuexu/crasher/Crasher.java", "snippet": "public final class Crasher extends JavaPlugin {\n @Override\n public void onLoad() {\n new Utils(this);\n getLogger().info(\"Loaded \" + getDescription().getFullName());\n }\n\n @Overr...
import cn.xuexu.crasher.Crasher; import cn.xuexu.crasher.bstats.Metrics; import cn.xuexu.crasher.commands.Crash; import cn.xuexu.crasher.listener.PlayerListener; import cn.xuexu.crasher.tasks.CheckUpdate; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors;
6,610
package cn.xuexu.crasher.utils; public final class Utils { public final static Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final static Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final static Set<UUID> crashSet = new HashSet<>(); public final static Set<UUID> frozenSet = new HashSet<>();
package cn.xuexu.crasher.utils; public final class Utils { public final static Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final static Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final static Set<UUID> crashSet = new HashSet<>(); public final static Set<UUID> frozenSet = new HashSet<>();
public static Crasher instance;
0
2023-12-05 15:08:54+00:00
8k
xIdentified/TavernBard
src/main/java/me/xidentified/tavernbard/CommandHandler.java
[ { "identifier": "QueueManager", "path": "src/main/java/me/xidentified/tavernbard/managers/QueueManager.java", "snippet": "public class QueueManager {\n private final SongManager songManager;\n private final CooldownManager cooldownManager;\n private final Map<UUID, Queue<Song>> npcSongQueues = ...
import me.xidentified.tavernbard.managers.QueueManager; import me.xidentified.tavernbard.managers.SongManager; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Queue; import java.util.UUID;
4,178
package me.xidentified.tavernbard; public class CommandHandler implements CommandExecutor { private final SongManager songManager;
package me.xidentified.tavernbard; public class CommandHandler implements CommandExecutor { private final SongManager songManager;
private final QueueManager queueManager;
0
2023-12-06 06:00:57+00:00
8k
Crydsch/the-one
src/gui/GUIControls.java
[ { "identifier": "PlayField", "path": "src/gui/playfield/PlayField.java", "snippet": "public class PlayField extends JPanel {\n\tpublic static final int PLAYFIELD_OFFSET = 10;\n\n\tprivate World w;\n\tprivate DTNSimGUI gui;\n\n\tprivate Color bgColor = Color.WHITE;\n\n\tprivate List<PlayFieldGraphic> ove...
import gui.playfield.PlayField; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.event.*; import javax.swing.event.*; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import core.Coord; import core.SimClock;
5,205
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui; /** * GUI's control panel * */ public class GUIControls extends JPanel implements ActionListener, ChangeListener, MouseWheelListener { private static final String PATH_GRAPHICS = "buttonGraphics/"; private static final String ICON_PAUSE = "Pause16.gif"; private static final String ICON_PLAY = "Play16.gif"; private static final String ICON_ZOOM = "Zoom24.gif"; private static final String ICON_STEP = "StepForward16.gif"; private static final String ICON_FFW = "FastForward16.gif"; private static final String TEXT_PAUSE = "pause simulation"; private static final String TEXT_PLAY = "play simulation"; private static final String TEXT_PLAY_UNTIL = "play simulation until sim time..."; private static final String TEXT_STEP = "step forward one interval"; private static final String TEXT_FFW = "enable/disable fast forward"; private static final String TEXT_UP_CHOOSER = "GUI update:"; private static final String TEXT_SCREEN_SHOT = "screen shot"; private static final String TEXT_SIMTIME = "Simulation time - "+ "click to force update, right click to change format"; private static final String TEXT_SEPS = "simulated seconds per second"; // "simulated events per second" averaging time (milliseconds) private static final int EPS_AVG_TIME = 2000; private static final String SCREENSHOT_FILE_TYPE = "png"; private static final String SCREENSHOT_FILE = "screenshot"; private JTextField simTimeField; private JLabel sepsField; // simulated events per second field private JButton playButton; private JButton playUntilButton; private boolean paused; private JButton stepButton; private boolean step; private JButton ffwButton; private boolean isFfw; private int oldSpeedIndex; // what speed was selected before FFW private JButton screenShotButton; private JComboBox guiUpdateChooser; /** * GUI update speeds. Negative values -> how many 1/10 seconds to wait * between updates. Positive values -> show every Nth update */ public static final String[] UP_SPEEDS = {"-10", "-1", "0.1", "1", "10", "100", "1000", "10000", "100000"}; /** Smallest value for the zoom level */ public static final double ZOOM_MIN = 0.001; /** Highest value for the zoom level */ public static final double ZOOM_MAX = 10; /** index of initial update speed setting */ public static final int INITIAL_SPEED_SELECTION = 3; /** index of FFW speed setting */ public static final int FFW_SPEED_INDEX = 7; private double guiUpdateInterval; private javax.swing.JSpinner zoomSelector; private PlayField pf; private DTNSimGUI gui; private long lastUpdate; private double lastSimTime; private double playUntilTime; private boolean useHourDisplay = false; public GUIControls(DTNSimGUI gui, PlayField pf) { /* TODO: read values for paused, isFfw etc from a file */ this.pf = pf; this.gui = gui; this.lastUpdate = System.currentTimeMillis(); this.lastSimTime = 0; this.paused = true; this.isFfw = false; this.playUntilTime = Double.MAX_VALUE; initPanel(); } /** * Creates panel's components and initializes them */ private void initPanel() { this.setLayout(new FlowLayout()); this.simTimeField = new JTextField("0.0"); this.simTimeField.setColumns(6); this.simTimeField.setEditable(false); this.simTimeField.setToolTipText(TEXT_SIMTIME); this.simTimeField.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { useHourDisplay = !useHourDisplay; }
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui; /** * GUI's control panel * */ public class GUIControls extends JPanel implements ActionListener, ChangeListener, MouseWheelListener { private static final String PATH_GRAPHICS = "buttonGraphics/"; private static final String ICON_PAUSE = "Pause16.gif"; private static final String ICON_PLAY = "Play16.gif"; private static final String ICON_ZOOM = "Zoom24.gif"; private static final String ICON_STEP = "StepForward16.gif"; private static final String ICON_FFW = "FastForward16.gif"; private static final String TEXT_PAUSE = "pause simulation"; private static final String TEXT_PLAY = "play simulation"; private static final String TEXT_PLAY_UNTIL = "play simulation until sim time..."; private static final String TEXT_STEP = "step forward one interval"; private static final String TEXT_FFW = "enable/disable fast forward"; private static final String TEXT_UP_CHOOSER = "GUI update:"; private static final String TEXT_SCREEN_SHOT = "screen shot"; private static final String TEXT_SIMTIME = "Simulation time - "+ "click to force update, right click to change format"; private static final String TEXT_SEPS = "simulated seconds per second"; // "simulated events per second" averaging time (milliseconds) private static final int EPS_AVG_TIME = 2000; private static final String SCREENSHOT_FILE_TYPE = "png"; private static final String SCREENSHOT_FILE = "screenshot"; private JTextField simTimeField; private JLabel sepsField; // simulated events per second field private JButton playButton; private JButton playUntilButton; private boolean paused; private JButton stepButton; private boolean step; private JButton ffwButton; private boolean isFfw; private int oldSpeedIndex; // what speed was selected before FFW private JButton screenShotButton; private JComboBox guiUpdateChooser; /** * GUI update speeds. Negative values -> how many 1/10 seconds to wait * between updates. Positive values -> show every Nth update */ public static final String[] UP_SPEEDS = {"-10", "-1", "0.1", "1", "10", "100", "1000", "10000", "100000"}; /** Smallest value for the zoom level */ public static final double ZOOM_MIN = 0.001; /** Highest value for the zoom level */ public static final double ZOOM_MAX = 10; /** index of initial update speed setting */ public static final int INITIAL_SPEED_SELECTION = 3; /** index of FFW speed setting */ public static final int FFW_SPEED_INDEX = 7; private double guiUpdateInterval; private javax.swing.JSpinner zoomSelector; private PlayField pf; private DTNSimGUI gui; private long lastUpdate; private double lastSimTime; private double playUntilTime; private boolean useHourDisplay = false; public GUIControls(DTNSimGUI gui, PlayField pf) { /* TODO: read values for paused, isFfw etc from a file */ this.pf = pf; this.gui = gui; this.lastUpdate = System.currentTimeMillis(); this.lastSimTime = 0; this.paused = true; this.isFfw = false; this.playUntilTime = Double.MAX_VALUE; initPanel(); } /** * Creates panel's components and initializes them */ private void initPanel() { this.setLayout(new FlowLayout()); this.simTimeField = new JTextField("0.0"); this.simTimeField.setColumns(6); this.simTimeField.setEditable(false); this.simTimeField.setToolTipText(TEXT_SIMTIME); this.simTimeField.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { useHourDisplay = !useHourDisplay; }
setSimTime(SimClock.getTime());
2
2023-12-10 15:51:41+00:00
8k
bggRGjQaUbCoE/c001apk
app/src/main/java/com/example/c001apk/view/vertical/VerticalTabLayout.java
[ { "identifier": "TabAdapter", "path": "app/src/main/java/com/example/c001apk/view/vertical/adapter/TabAdapter.java", "snippet": "public interface TabAdapter {\n int getCount();\n\n TabView.TabBadge getBadge(int position);\n\n TabView.TabIcon getIcon(int position);\n\n TabView.TabTitle getTit...
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE; import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.ScrollView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import com.example.c001apk.R; import com.example.c001apk.view.vertical.adapter.TabAdapter; import com.example.c001apk.view.vertical.util.DisplayUtil; import com.example.c001apk.view.vertical.util.TabFragmentManager; import com.example.c001apk.view.vertical.widget.QTabView; import com.example.c001apk.view.vertical.widget.TabView; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List;
4,922
} public void setTabMode(int mode) { if (mode != TAB_MODE_FIXED && mode != TAB_MODE_SCROLLABLE) { throw new IllegalStateException("only support TAB_MODE_FIXED or TAB_MODE_SCROLLABLE"); } if (mode == mTabMode) return; mTabMode = mode; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); initTabWithMode(params); if (i == 0) { params.setMargins(0, 0, 0, 0); } view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param margin margin */ public void setTabMargin(int margin) { if (margin == mTabMargin) return; mTabMargin = margin; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.setMargins(0, i == 0 ? 0 : mTabMargin, 0, 0); view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param height height */ public void setTabHeight(int height) { if (height == mTabHeight) return; mTabHeight = height; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = mTabHeight; view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(() -> mTabStrip.updataIndicator()); } public void setIndicatorColor(int color) { mColorIndicator = color; mTabStrip.invalidate(); } public void setIndicatorWidth(int width) { mIndicatorWidth = width; mTabStrip.setIndicatorGravity(); } public void setIndicatorCorners(int corners) { mIndicatorCorners = corners; mTabStrip.invalidate(); } /** * @param gravity only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL */ public void setIndicatorGravity(int gravity) { if (gravity == Gravity.LEFT || gravity == Gravity.RIGHT || Gravity.FILL == gravity) { mIndicatorGravity = gravity; mTabStrip.setIndicatorGravity(); } else { throw new IllegalStateException("only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL"); } } // public void setTabPadding(int padding) { // // } // // public void setTabPadding(int start, int top, int end, int bottom) { // // } public void addOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.add(listener); } } public void removeOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.remove(listener); } } public void setTabAdapter(TabAdapter adapter) { removeAllTabs(); if (adapter != null) { for (int i = 0; i < adapter.getCount(); i++) {
package com.example.c001apk.view.vertical; /** * @author chqiu * Email:qstumn@163.com */ public class VerticalTabLayout extends ScrollView { private final Context mContext; private TabStrip mTabStrip; private int mColorIndicator; private TabView mSelectedTab; private int mTabMargin; private int mIndicatorWidth; private int mIndicatorGravity; private float mIndicatorCorners; private int mTabMode; private int mTabHeight; public static int TAB_MODE_FIXED = 10; public static int TAB_MODE_SCROLLABLE = 11; private ViewPager mViewPager; private PagerAdapter mPagerAdapter; private final List<OnTabSelectedListener> mTabSelectedListeners; private OnTabPageChangeListener mTabPageChangeListener; private DataSetObserver mPagerAdapterObserver; private TabFragmentManager mTabFragmentManager; public VerticalTabLayout(Context context) { this(context, null); } public VerticalTabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VerticalTabLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; mTabSelectedListeners = new ArrayList<>(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VerticalTabLayout); mColorIndicator = typedArray.getColor(R.styleable.VerticalTabLayout_indicator_color, context.getColor(R.color.black)); mIndicatorWidth = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_width, DisplayUtil.dp2px(context, 3)); mIndicatorCorners = typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_corners, 0); mIndicatorGravity = typedArray.getInteger(R.styleable.VerticalTabLayout_indicator_gravity, Gravity.LEFT); if (mIndicatorGravity == 3) { mIndicatorGravity = Gravity.LEFT; } else if (mIndicatorGravity == 5) { mIndicatorGravity = Gravity.RIGHT; } else if (mIndicatorGravity == 119) { mIndicatorGravity = Gravity.FILL; } mTabMargin = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_margin, 0); mTabMode = typedArray.getInteger(R.styleable.VerticalTabLayout_tab_mode, TAB_MODE_FIXED); int defaultTabHeight = LinearLayout.LayoutParams.WRAP_CONTENT; mTabHeight = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_height, defaultTabHeight); typedArray.recycle(); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() > 0) removeAllViews(); initTabStrip(); } private void initTabStrip() { mTabStrip = new TabStrip(mContext); addView(mTabStrip, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } public void removeAllTabs() { mTabStrip.removeAllViews(); mSelectedTab = null; } public TabView getTabAt(int position) { return (TabView) mTabStrip.getChildAt(position); } public int getTabCount() { return mTabStrip.getChildCount(); } public int getSelectedTabPosition() { int index = mTabStrip.indexOfChild(mSelectedTab); return index == -1 ? 0 : index; } private void addTabWithMode(TabView tabView) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); initTabWithMode(params); mTabStrip.addView(tabView, params); if (mTabStrip.indexOfChild(tabView) == 0) { tabView.setChecked(true); params = (LinearLayout.LayoutParams) tabView.getLayoutParams(); params.setMargins(0, 0, 0, 0); tabView.setLayoutParams(params); mSelectedTab = tabView; mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.moveIndicator(0); } }); } } private void initTabWithMode(LinearLayout.LayoutParams params) { if (mTabMode == TAB_MODE_FIXED) { params.height = 0; params.weight = 1.0f; params.setMargins(0, 0, 0, 0); setFillViewport(true); } else if (mTabMode == TAB_MODE_SCROLLABLE) { params.height = mTabHeight; params.weight = 0f; params.setMargins(0, mTabMargin, 0, 0); setFillViewport(false); } } private void scrollToTab(int position) { final TabView tabView = getTabAt(position); int y = getScrollY(); int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y; int target = getHeight() / 2; if (tabTop > target) { smoothScrollBy(0, tabTop - target); } else if (tabTop < target) { smoothScrollBy(0, tabTop - target); } } private float mLastPositionOffset; private void scrollByTab(int position, final float positionOffset) { final TabView tabView = getTabAt(position); int y = getScrollY(); int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y; int target = getHeight() / 2; int nextScrollY = tabView.getHeight() + mTabMargin; if (positionOffset > 0) { float percent = positionOffset - mLastPositionOffset; if (tabTop > target) { smoothScrollBy(0, (int) (nextScrollY * percent)); } } mLastPositionOffset = positionOffset; } public void addTab(TabView tabView) { if (tabView != null) { addTabWithMode(tabView); tabView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { int position = mTabStrip.indexOfChild(view); setTabSelected(position); } }); } else { throw new IllegalStateException("tabview can't be null"); } } public void setTabSelected(final int position) { setTabSelected(position, true, true); } private void setTabSelected(final int position, final boolean updataIndicator, final boolean callListener) { post(new Runnable() { @Override public void run() { setTabSelectedImpl(position, updataIndicator, callListener); } }); } private void setTabSelectedImpl(final int position, boolean updataIndicator, boolean callListener) { TabView view = getTabAt(position); boolean selected; if (selected = (view != mSelectedTab)) { if (mSelectedTab != null) { mSelectedTab.setChecked(false); } view.setChecked(true); if (updataIndicator) { mTabStrip.moveIndicatorWithAnimator(position); } mSelectedTab = view; scrollToTab(position); } if (callListener) { for (int i = 0; i < mTabSelectedListeners.size(); i++) { OnTabSelectedListener listener = mTabSelectedListeners.get(i); if (listener != null) { if (selected) { listener.onTabSelected(view, position); } else { listener.onTabReselected(view, position); } } } } } public void setTabBadge(int tabPosition, int badgeNum) { getTabAt(tabPosition).getBadgeView().setBadgeNumber(badgeNum); } public void setTabBadge(int tabPosition, String badgeText) { getTabAt(tabPosition).getBadgeView().setBadgeText(badgeText); } public void setTabMode(int mode) { if (mode != TAB_MODE_FIXED && mode != TAB_MODE_SCROLLABLE) { throw new IllegalStateException("only support TAB_MODE_FIXED or TAB_MODE_SCROLLABLE"); } if (mode == mTabMode) return; mTabMode = mode; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); initTabWithMode(params); if (i == 0) { params.setMargins(0, 0, 0, 0); } view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param margin margin */ public void setTabMargin(int margin) { if (margin == mTabMargin) return; mTabMargin = margin; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.setMargins(0, i == 0 ? 0 : mTabMargin, 0, 0); view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param height height */ public void setTabHeight(int height) { if (height == mTabHeight) return; mTabHeight = height; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = mTabHeight; view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(() -> mTabStrip.updataIndicator()); } public void setIndicatorColor(int color) { mColorIndicator = color; mTabStrip.invalidate(); } public void setIndicatorWidth(int width) { mIndicatorWidth = width; mTabStrip.setIndicatorGravity(); } public void setIndicatorCorners(int corners) { mIndicatorCorners = corners; mTabStrip.invalidate(); } /** * @param gravity only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL */ public void setIndicatorGravity(int gravity) { if (gravity == Gravity.LEFT || gravity == Gravity.RIGHT || Gravity.FILL == gravity) { mIndicatorGravity = gravity; mTabStrip.setIndicatorGravity(); } else { throw new IllegalStateException("only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL"); } } // public void setTabPadding(int padding) { // // } // // public void setTabPadding(int start, int top, int end, int bottom) { // // } public void addOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.add(listener); } } public void removeOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.remove(listener); } } public void setTabAdapter(TabAdapter adapter) { removeAllTabs(); if (adapter != null) { for (int i = 0; i < adapter.getCount(); i++) {
addTab(new QTabView(mContext).setIcon(adapter.getIcon(i))
1
2023-12-18 15:02:49+00:00
8k
rcaneppele/simple-openai-client
src/test/java/br/com/rcaneppele/openai/endpoints/run/request/sender/CreateRunRequestSenderTest.java
[ { "identifier": "OpenAIModel", "path": "src/main/java/br/com/rcaneppele/openai/common/OpenAIModel.java", "snippet": "public enum OpenAIModel {\n\n GPT_3_5_TURBO_1106(\"gpt-3.5-turbo-1106\"),\n GPT_3_5_TURBO(\"gpt-3.5-turbo\"),\n GPT_3_5_TURBO_16k(\"gpt-3.5-turbo-16k\"),\n GPT_3_5_TURBO_INSTR...
import br.com.rcaneppele.openai.common.OpenAIModel; import br.com.rcaneppele.openai.common.json.JsonConverter; import br.com.rcaneppele.openai.common.request.HttpMethod; import br.com.rcaneppele.openai.common.request.RequestSender; import br.com.rcaneppele.openai.endpoints.BaseRequestSenderTest; import br.com.rcaneppele.openai.endpoints.assistant.tools.Tool; import br.com.rcaneppele.openai.endpoints.assistant.tools.ToolType; import br.com.rcaneppele.openai.endpoints.run.request.CreateRunRequest; import br.com.rcaneppele.openai.endpoints.run.request.builder.CreateRunRequestBuilder; import br.com.rcaneppele.openai.endpoints.run.response.Run; import br.com.rcaneppele.openai.endpoints.run.response.RunStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Map; import java.util.Set;
3,733
package br.com.rcaneppele.openai.endpoints.run.request.sender; class CreateRunRequestSenderTest extends BaseRequestSenderTest { private static final String THREAD_ID = "thread_123"; private static final String ASSISTANT_ID = "asst_123"; private RequestSender<CreateRunRequest, Run> sender; private JsonConverter<CreateRunRequest> jsonConverter; private CreateRunRequestBuilder builder; @Override protected String expectedURI() { return "threads/" + THREAD_ID +"/runs"; } @Override protected String mockJsonResponse() { return """ { "id": "run_123", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_123", "thread_id": "thread_123", "status": "completed", "started_at": 1699063291, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063292, "last_error": null, "model": "gpt-4", "instructions": null, "tools": [ { "type": "code_interpreter" } ], "file_ids": [ "file-123" ], "metadata": {} } """; } @BeforeEach void setUp() { this.sender = new CreateRunRequestSender(this.url, TIMEOUT, API_KEY, THREAD_ID); this.jsonConverter = new JsonConverter<>(CreateRunRequest.class); this.builder = new CreateRunRequestBuilder(); } @Test public void shouldSendRequest() { var request = builder .threadId(THREAD_ID) .assistantId(ASSISTANT_ID) .build(); var actualResponse = sender.sendRequest(request); var expectedResponse = new Run( "run_123", "thread.run", Instant.ofEpochSecond(1699063290), ASSISTANT_ID, THREAD_ID, RunStatus.COMPLETED, Instant.ofEpochSecond(1699063291), null, null, null, Instant.ofEpochSecond(1699063292), null, OpenAIModel.GPT_4, null, Set.of( new Tool(ToolType.CODE_INTERPRETER.getName(), null) ), Set.of("file-123"), Map.of()); var expectedRequestBody = jsonConverter.convertRequestToJson(request);
package br.com.rcaneppele.openai.endpoints.run.request.sender; class CreateRunRequestSenderTest extends BaseRequestSenderTest { private static final String THREAD_ID = "thread_123"; private static final String ASSISTANT_ID = "asst_123"; private RequestSender<CreateRunRequest, Run> sender; private JsonConverter<CreateRunRequest> jsonConverter; private CreateRunRequestBuilder builder; @Override protected String expectedURI() { return "threads/" + THREAD_ID +"/runs"; } @Override protected String mockJsonResponse() { return """ { "id": "run_123", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_123", "thread_id": "thread_123", "status": "completed", "started_at": 1699063291, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063292, "last_error": null, "model": "gpt-4", "instructions": null, "tools": [ { "type": "code_interpreter" } ], "file_ids": [ "file-123" ], "metadata": {} } """; } @BeforeEach void setUp() { this.sender = new CreateRunRequestSender(this.url, TIMEOUT, API_KEY, THREAD_ID); this.jsonConverter = new JsonConverter<>(CreateRunRequest.class); this.builder = new CreateRunRequestBuilder(); } @Test public void shouldSendRequest() { var request = builder .threadId(THREAD_ID) .assistantId(ASSISTANT_ID) .build(); var actualResponse = sender.sendRequest(request); var expectedResponse = new Run( "run_123", "thread.run", Instant.ofEpochSecond(1699063290), ASSISTANT_ID, THREAD_ID, RunStatus.COMPLETED, Instant.ofEpochSecond(1699063291), null, null, null, Instant.ofEpochSecond(1699063292), null, OpenAIModel.GPT_4, null, Set.of( new Tool(ToolType.CODE_INTERPRETER.getName(), null) ), Set.of("file-123"), Map.of()); var expectedRequestBody = jsonConverter.convertRequestToJson(request);
executeRequestAssertions(expectedRequestBody, 1, HttpMethod.POST, true);
2
2023-12-21 19:17:56+00:00
8k
simasch/vaadin-jooq-template
src/main/java/ch/martinelli/vj/ui/layout/MainLayout.java
[ { "identifier": "AuthenticatedUser", "path": "src/main/java/ch/martinelli/vj/security/AuthenticatedUser.java", "snippet": "@Component\npublic class AuthenticatedUser {\n\n private final AuthenticationContext authenticationContext;\n private final UserService userService;\n\n public Authenticate...
import ch.martinelli.vj.security.AuthenticatedUser; import ch.martinelli.vj.ui.views.helloworld.HelloWorldView; import ch.martinelli.vj.ui.views.person.PersonView; import ch.martinelli.vj.ui.views.user.UserView; import com.vaadin.flow.component.applayout.AppLayout; import com.vaadin.flow.component.applayout.DrawerToggle; import com.vaadin.flow.component.avatar.Avatar; import com.vaadin.flow.component.html.*; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.menubar.MenuBar; import com.vaadin.flow.component.orderedlayout.Scroller; import com.vaadin.flow.component.sidenav.SideNav; import com.vaadin.flow.component.sidenav.SideNavItem; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.server.auth.AccessAnnotationChecker; import com.vaadin.flow.theme.lumo.LumoIcon; import com.vaadin.flow.theme.lumo.LumoUtility; import java.io.ByteArrayInputStream;
4,130
package ch.martinelli.vj.ui.layout; public class MainLayout extends AppLayout { private final transient AuthenticatedUser authenticatedUser; private final AccessAnnotationChecker accessChecker; private H2 viewTitle; public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) { this.authenticatedUser = authenticatedUser; this.accessChecker = accessChecker; setPrimarySection(Section.DRAWER); addDrawerContent(); addHeaderContent(); } private void addHeaderContent() { var toggle = new DrawerToggle(); toggle.setAriaLabel("Menu toggle"); viewTitle = new H2(); viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); addToNavbar(true, toggle, viewTitle); } private void addDrawerContent() { var appName = new H1("Vaadin jOOQ Template"); appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); var header = new Header(appName); var scroller = new Scroller(createNavigation()); addToDrawer(header, scroller, createFooter()); } private SideNav createNavigation() { var nav = new SideNav(); if (accessChecker.hasAccess(HelloWorldView.class)) { nav.addItem(new SideNavItem(getTranslation("Hello World"), HelloWorldView.class, VaadinIcon.GLOBE.create())); } if (accessChecker.hasAccess(PersonView.class)) { nav.addItem(new SideNavItem(getTranslation("Persons"), PersonView.class, VaadinIcon.ARCHIVES.create())); }
package ch.martinelli.vj.ui.layout; public class MainLayout extends AppLayout { private final transient AuthenticatedUser authenticatedUser; private final AccessAnnotationChecker accessChecker; private H2 viewTitle; public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) { this.authenticatedUser = authenticatedUser; this.accessChecker = accessChecker; setPrimarySection(Section.DRAWER); addDrawerContent(); addHeaderContent(); } private void addHeaderContent() { var toggle = new DrawerToggle(); toggle.setAriaLabel("Menu toggle"); viewTitle = new H2(); viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); addToNavbar(true, toggle, viewTitle); } private void addDrawerContent() { var appName = new H1("Vaadin jOOQ Template"); appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); var header = new Header(appName); var scroller = new Scroller(createNavigation()); addToDrawer(header, scroller, createFooter()); } private SideNav createNavigation() { var nav = new SideNav(); if (accessChecker.hasAccess(HelloWorldView.class)) { nav.addItem(new SideNavItem(getTranslation("Hello World"), HelloWorldView.class, VaadinIcon.GLOBE.create())); } if (accessChecker.hasAccess(PersonView.class)) { nav.addItem(new SideNavItem(getTranslation("Persons"), PersonView.class, VaadinIcon.ARCHIVES.create())); }
if (accessChecker.hasAccess(UserView.class)) {
3
2023-12-20 13:08:17+00:00
8k
373675032/academic-report
src/main/java/world/xuewei/service/ReportService.java
[ { "identifier": "AIGCClient", "path": "src/main/java/world/xuewei/component/AIGCClient.java", "snippet": "@Component\npublic class AIGCClient {\n\n @Value(\"${ai-key}\")\n private String apiKey;\n\n public String query(String queryMessage) {\n Constants.apiKey = apiKey;\n try {\n ...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import world.xuewei.component.AIGCClient; import world.xuewei.component.OssClient; import world.xuewei.constant.Leader; import world.xuewei.constant.ReportConstant; import world.xuewei.constant.Role; import world.xuewei.dao.ReportMapper; import world.xuewei.dto.ResponseResult; import world.xuewei.entity.Message; import world.xuewei.entity.Report; import world.xuewei.entity.Teacher; import world.xuewei.entity.User; import javax.annotation.Resource; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Objects;
4,713
package world.xuewei.service; /** * 报告服务 * * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Slf4j @Service public class ReportService { @Resource private AIGCClient aigcClient; @Resource private ReportMapper reportMapper; @Resource private OssClient ossClient; @Resource private TeacherService teacherService; @Resource private MessageService messageService; public boolean insert(Report report) { return reportMapper.insert(report) == 1; } public boolean deleteById(Integer id) { return reportMapper.deleteById(id) == 1; } public Report getById(Integer id) { return reportMapper.getById(id); } public List<Report> listReports() { return reportMapper.listReports(); } public List<Report> listReports(Report report) { return reportMapper.listReports(report); } public List<Report> listReportsByCollegeId(Integer id, Integer status) { return reportMapper.listReportsByCollegeId(id, status); } public int countReports(Report report) { return reportMapper.countReports(report); } public boolean update(Report report) { return reportMapper.update(report) == 1; } /** * 发布学术报告 */ public ResponseResult publishReport(String title, String info, String reporterInfo, MultipartFile file, MultipartFile reportFile, User loginUser) { ResponseResult result = new ResponseResult(); // 上传文件到阿里云对象存储 String fileUrl = ""; String reportFileUrl = ""; if (ObjectUtil.isNotEmpty(file)) { // 检查附件的文件类型 String fileName = file.getOriginalFilename(); assert fileName != null; if (!fileName.endsWith(".zip") && !fileName.endsWith(".rar") && !fileName.endsWith(".7z")) { result.setCode(302); result.setMessage("附件类型请上传压缩包 [ .zip|.rar|.7z ]"); return result; } try { fileUrl = ossClient.upLoad(file, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } } // 检查学术报告文件的类型 String reportFileName = reportFile.getOriginalFilename(); assert reportFileName != null; if (!reportFileName.endsWith(".word") && !reportFileName.endsWith(".pdf") && !reportFileName.endsWith(".doc")) { result.setCode(302); result.setMessage("报告类型请上传文档 [ .word|.pdf|.doc ]"); return result; } try { reportFileUrl = ossClient.upLoad(reportFile, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } // 添加到数据库 Report report = Report.builder() .title(title).info(info).reporterInfo(reporterInfo).attachment(fileUrl).reportFile(reportFileUrl) .status(ReportConstant.WAIT).publishTime(new Date()).reporterNo(loginUser.getNo()) .build(); // 学院院长发布的报告,无需自己审核
package world.xuewei.service; /** * 报告服务 * * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Slf4j @Service public class ReportService { @Resource private AIGCClient aigcClient; @Resource private ReportMapper reportMapper; @Resource private OssClient ossClient; @Resource private TeacherService teacherService; @Resource private MessageService messageService; public boolean insert(Report report) { return reportMapper.insert(report) == 1; } public boolean deleteById(Integer id) { return reportMapper.deleteById(id) == 1; } public Report getById(Integer id) { return reportMapper.getById(id); } public List<Report> listReports() { return reportMapper.listReports(); } public List<Report> listReports(Report report) { return reportMapper.listReports(report); } public List<Report> listReportsByCollegeId(Integer id, Integer status) { return reportMapper.listReportsByCollegeId(id, status); } public int countReports(Report report) { return reportMapper.countReports(report); } public boolean update(Report report) { return reportMapper.update(report) == 1; } /** * 发布学术报告 */ public ResponseResult publishReport(String title, String info, String reporterInfo, MultipartFile file, MultipartFile reportFile, User loginUser) { ResponseResult result = new ResponseResult(); // 上传文件到阿里云对象存储 String fileUrl = ""; String reportFileUrl = ""; if (ObjectUtil.isNotEmpty(file)) { // 检查附件的文件类型 String fileName = file.getOriginalFilename(); assert fileName != null; if (!fileName.endsWith(".zip") && !fileName.endsWith(".rar") && !fileName.endsWith(".7z")) { result.setCode(302); result.setMessage("附件类型请上传压缩包 [ .zip|.rar|.7z ]"); return result; } try { fileUrl = ossClient.upLoad(file, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } } // 检查学术报告文件的类型 String reportFileName = reportFile.getOriginalFilename(); assert reportFileName != null; if (!reportFileName.endsWith(".word") && !reportFileName.endsWith(".pdf") && !reportFileName.endsWith(".doc")) { result.setCode(302); result.setMessage("报告类型请上传文档 [ .word|.pdf|.doc ]"); return result; } try { reportFileUrl = ossClient.upLoad(reportFile, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } // 添加到数据库 Report report = Report.builder() .title(title).info(info).reporterInfo(reporterInfo).attachment(fileUrl).reportFile(reportFileUrl) .status(ReportConstant.WAIT).publishTime(new Date()).reporterNo(loginUser.getNo()) .build(); // 学院院长发布的报告,无需自己审核
if (Objects.equals(loginUser.getRole(), Role.TEACHER) && loginUser.getIsLeader() == Leader.YES) {
4
2023-12-21 06:59:12+00:00
8k
HChenX/ForegroundPin
app/src/main/java/com/hchen/foregroundpin/HookMain.java
[ { "identifier": "Hook", "path": "app/src/main/java/com/hchen/foregroundpin/hookMode/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\...
import com.hchen.foregroundpin.hookMode.Hook; import com.hchen.foregroundpin.pinHook.ForegroundPin; import com.hchen.foregroundpin.pinHook.ShouldHeadUp; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
5,852
package com.hchen.foregroundpin; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { switch (lpparam.packageName) { case "android" -> {
package com.hchen.foregroundpin; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { switch (lpparam.packageName) { case "android" -> {
initHook(new ForegroundPin(), lpparam);
1
2023-12-17 12:05:00+00:00
8k
John200410/rusherhack-spotify
src/main/java/me/john200410/spotify/http/SpotifyAPI.java
[ { "identifier": "Config", "path": "src/main/java/me/john200410/spotify/Config.java", "snippet": "public class Config {\n\t\n\tpublic String appId = \"\";\n\tpublic String appSecret = \"\";\n\tpublic String refresh_token = \"\";\n\t\n}" }, { "identifier": "SpotifyPlugin", "path": "src/main/ja...
import com.google.gson.JsonSyntaxException; import me.john200410.spotify.Config; import me.john200410.spotify.SpotifyPlugin; import me.john200410.spotify.http.responses.CodeGrant; import me.john200410.spotify.http.responses.PlaybackState; import me.john200410.spotify.http.responses.Response; import me.john200410.spotify.http.responses.User; import net.minecraft.Util; import org.rusherhack.client.api.RusherHackAPI; import org.rusherhack.core.notification.NotificationType; import org.rusherhack.core.utils.MathUtils; import org.rusherhack.core.utils.Timer; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import java.util.stream.Collectors;
4,558
return true; } private boolean seek(long ms) throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final long duration = this.currentStatus.item.duration_ms; //clamp ms = MathUtils.clamp(ms, 0, duration); final Response request = this.makeRequest( "PUT", this.getUrl("/v1/me/player/seek?position_ms=" + ms, true) ); switch(request.statusCode()) { case 204: this.playbackAvailable = true; break; case 401: this.plugin.getLogger().error("Lost connection to Spotify"); this.isConnected = false; default: this.plugin.getLogger().error("REPEAT STATUS CODE: " + request.statusCode()); return false; } //update status this.currentStatus = this.getStatus(); return true; } private boolean isPremium() { if(this.premium != null) { return this.premium; } try { this.updateAccessToken(); final Response request = this.makeRequest( "GET", this.getUrl("/v1/me", false) ); switch(request.statusCode()) { case 200 -> { } case 401 -> { this.isConnected = false; this.plugin.getLogger().error("USER STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("USER STATUS CODE: " + request.statusCode()); return false; } } final User user = SpotifyPlugin.GSON.fromJson(request.body(), User.class); this.premium = user.product.equals("premium"); return this.premium; } catch(IOException | InterruptedException e) { return false; } } private Response makeRequest(String method, String endpoint) throws IOException, InterruptedException { final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(API_URL + endpoint)) .header("Authorization", "Bearer " + this.accessToken) .header("Content-Type", "application/json") .header("Accept", "application/json") .method(method, HttpRequest.BodyPublishers.noBody()) .timeout(Duration.ofSeconds(8)) .build(); final HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); return new Response(response.statusCode(), response.body()); } public boolean authorizationCodeGrant(String code) throws IOException, InterruptedException { Map<Object, Object> data = new HashMap<>(); data.put("grant_type", "authorization_code"); data.put("redirect_uri", this.redirectURI); data.put("code", code); data.put("client_id", this.appID); data.put("client_secret", this.appSecret); String requestBody = data.entrySet().stream() .map(entry -> entry.getKey().toString() + "=" + entry.getValue().toString()) .collect(Collectors.joining("&")); final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(AUTH_URL + "/api/token")) .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .timeout(Duration.ofSeconds(8)) .build(); final HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); final CodeGrant body = SpotifyPlugin.GSON.fromJson(response.body(), CodeGrant.class); if(response.statusCode() != 200) { return false; } this.accessToken = body.access_token; this.refreshToken = body.refresh_token; this.setExpiration(body.expires_in); this.isConnected = true;
package me.john200410.spotify.http; public class SpotifyAPI { /** * Constants */ public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final String API_URL = "https://api.spotify.com"; private static final String AUTH_URL = "https://accounts.spotify.com"; /** * Variables */ private final SpotifyPlugin plugin; private boolean isConnected = false; private boolean playbackAvailable = false; private PlaybackState currentStatus; private final Timer statusUpdateTimer = new Timer(); private final Timer refreshTokenTimer = new Timer(); private String accessToken; public String refreshToken; private Integer expiresIn; public String appID; public String appSecret; private String redirectURI; private Boolean premium; private String deviceID; public SpotifyAPI(SpotifyPlugin plugin) { this.plugin = plugin; } public void updateStatus(long rateLimit) { if(rateLimit > 0 && !this.statusUpdateTimer.passed(rateLimit)) { return; } this.submit(() -> { try { this.currentStatus = this.getStatus(); } catch(IOException | InterruptedException | JsonSyntaxException e) { e.printStackTrace(); } }); this.statusUpdateTimer.reset(); } public void submitTogglePlay() { this.submit(() -> { try { this.togglePlay(); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } public void submitNext() { this.submit(() -> { try { this.next(); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } public void submitPrevious() { this.submit(() -> { try { this.previous(); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } public void submitToggleShuffle() { this.submit(() -> { try { this.setShuffle(!this.currentStatus.shuffle_state); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } public void submitToggleRepeat() { this.submit(() -> { try { String repeat = this.currentStatus.repeat_state; if(repeat.equals("track")) { repeat = "off"; } else if(repeat.equals("context")) { repeat = "track"; } else { repeat = "context"; } this.setRepeat(repeat); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } public void submitSeek(long ms) { this.submit(() -> { try { this.seek(ms); } catch(NoPremiumException e) { RusherHackAPI.getNotificationManager().send(NotificationType.ERROR, "Spotify Premium is required for this function!"); } catch(IOException | InterruptedException e) { e.printStackTrace(); } }); } // only method that doesn't require premium private PlaybackState getStatus() throws IOException, InterruptedException, JsonSyntaxException { this.updateAccessToken(); final Response request = this.makeRequest( "GET", this.getUrl("/v1/me/player", false) ); this.statusUpdateTimer.reset(); switch(request.statusCode()) { case 200 -> this.playbackAvailable = true; case 204 -> { this.playbackAvailable = false; //this.plugin.getLogger().error("UPDATESTATUS STATUS CODE: " + request.statusCode()); return null; } case 401 -> { this.isConnected = false; this.plugin.getLogger().error("UPDATESTATUS STATUS CODE: " + request.statusCode()); return null; } default -> { this.plugin.getLogger().error("UPDATESTATUS STATUS CODE: " + request.statusCode()); return null; } } final PlaybackState status = SpotifyPlugin.GSON.fromJson(request.body(), PlaybackState.class); this.deviceID = status.device.id; return status; } private boolean togglePlay() throws IOException, InterruptedException, NoPremiumException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final String url = this.currentStatus.is_playing ? "/v1/me/player/pause" : "/v1/me/player/play"; final Response request = this.makeRequest( "PUT", this.getUrl(url, false) ); switch(request.statusCode()) { case 204 -> this.playbackAvailable = true; case 401 -> { this.isConnected = false; this.plugin.getLogger().error("TOGGLEPLAY STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("TOGGLEPLAY STATUS CODE: " + request.statusCode()); return false; } } //update status this.currentStatus = this.getStatus(); return true; } private boolean next() throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final Response request = this.makeRequest( "POST", this.getUrl("/v1/me/player/next", false) ); switch(request.statusCode()) { case 204 -> this.playbackAvailable = true; case 401 -> { this.isConnected = false; this.plugin.getLogger().error("NEXT STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("NEXT STATUS CODE: " + request.statusCode()); return false; } } //update status this.currentStatus = this.getStatus(); return true; } private boolean previous() throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final Response request = this.makeRequest( "POST", this.getUrl("/v1/me/player/previous", false) ); switch(request.statusCode()) { case 204 -> this.playbackAvailable = true; case 401 -> { this.isConnected = false; this.plugin.getLogger().error("PREVIOUS STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("PREVIOUS STATUS CODE: " + request.statusCode()); return false; } } //update status this.currentStatus = this.getStatus(); return true; } private boolean setShuffle(boolean shuffle) throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final Response request = this.makeRequest( "PUT", this.getUrl("/v1/me/player/shuffle?state=" + shuffle, true) ); switch(request.statusCode()) { case 204 -> this.playbackAvailable = true; case 401 -> { this.isConnected = false; this.plugin.getLogger().error("SHUFFLE STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("SHUFFLE STATUS CODE: " + request.statusCode()); return false; } } //update status this.currentStatus = this.getStatus(); return true; } // repeat can be one of: track, context, or off. // track will repeat the current playlist. // context will repeat the current song. // off will turn repeat off. private boolean setRepeat(String repeat) throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final Response request = this.makeRequest( "PUT", this.getUrl("/v1/me/player/repeat?state=" + repeat, true) ); switch(request.statusCode()) { case 204 -> this.playbackAvailable = true; case 401 -> { this.isConnected = false; this.plugin.getLogger().error("REPEAT STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("REPEAT STATUS CODE: " + request.statusCode()); return false; } } //update status this.currentStatus = this.getStatus(); return true; } private boolean seek(long ms) throws NoPremiumException, IOException, InterruptedException { if(!this.isPremium()) { throw new NoPremiumException(); } this.updateAccessToken(); final long duration = this.currentStatus.item.duration_ms; //clamp ms = MathUtils.clamp(ms, 0, duration); final Response request = this.makeRequest( "PUT", this.getUrl("/v1/me/player/seek?position_ms=" + ms, true) ); switch(request.statusCode()) { case 204: this.playbackAvailable = true; break; case 401: this.plugin.getLogger().error("Lost connection to Spotify"); this.isConnected = false; default: this.plugin.getLogger().error("REPEAT STATUS CODE: " + request.statusCode()); return false; } //update status this.currentStatus = this.getStatus(); return true; } private boolean isPremium() { if(this.premium != null) { return this.premium; } try { this.updateAccessToken(); final Response request = this.makeRequest( "GET", this.getUrl("/v1/me", false) ); switch(request.statusCode()) { case 200 -> { } case 401 -> { this.isConnected = false; this.plugin.getLogger().error("USER STATUS CODE: " + request.statusCode()); return false; } default -> { this.plugin.getLogger().error("USER STATUS CODE: " + request.statusCode()); return false; } } final User user = SpotifyPlugin.GSON.fromJson(request.body(), User.class); this.premium = user.product.equals("premium"); return this.premium; } catch(IOException | InterruptedException e) { return false; } } private Response makeRequest(String method, String endpoint) throws IOException, InterruptedException { final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(API_URL + endpoint)) .header("Authorization", "Bearer " + this.accessToken) .header("Content-Type", "application/json") .header("Accept", "application/json") .method(method, HttpRequest.BodyPublishers.noBody()) .timeout(Duration.ofSeconds(8)) .build(); final HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); return new Response(response.statusCode(), response.body()); } public boolean authorizationCodeGrant(String code) throws IOException, InterruptedException { Map<Object, Object> data = new HashMap<>(); data.put("grant_type", "authorization_code"); data.put("redirect_uri", this.redirectURI); data.put("code", code); data.put("client_id", this.appID); data.put("client_secret", this.appSecret); String requestBody = data.entrySet().stream() .map(entry -> entry.getKey().toString() + "=" + entry.getValue().toString()) .collect(Collectors.joining("&")); final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(AUTH_URL + "/api/token")) .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .timeout(Duration.ofSeconds(8)) .build(); final HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); final CodeGrant body = SpotifyPlugin.GSON.fromJson(response.body(), CodeGrant.class); if(response.statusCode() != 200) { return false; } this.accessToken = body.access_token; this.refreshToken = body.refresh_token; this.setExpiration(body.expires_in); this.isConnected = true;
final Config config = this.plugin.getConfig();
0
2023-12-19 17:59:37+00:00
8k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/entity/villager/SkyBlockVillagerNPC.java
[ { "identifier": "SkyBlockConst", "path": "generic/src/main/java/net/swofty/types/generic/SkyBlockConst.java", "snippet": "public class SkyBlockConst {\n @Getter\n @Setter\n private static SharedInstance instanceContainer;\n @Getter\n @Setter\n private static GlobalEventHandler eventHan...
import lombok.Getter; import net.minestom.server.coordinate.Pos; import net.minestom.server.network.packet.server.play.EntityHeadLookPacket; import net.minestom.server.network.packet.server.play.EntityRotationPacket; import net.swofty.types.generic.SkyBlockConst; import net.swofty.types.generic.entity.hologram.ServerHolograms; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.utility.MathUtility; import java.util.HashMap; import java.util.Map;
4,970
package net.swofty.types.generic.entity.villager; @Getter public abstract class SkyBlockVillagerNPC { private static final int LOOK_DISTANCE = 16; private static final Map<SkyBlockVillagerNPC, VillagerEntityImpl> villagers = new HashMap(); private final NPCVillagerParameters parameters; private final String ID; protected SkyBlockVillagerNPC(NPCVillagerParameters parameters) { this.parameters = parameters; this.ID = this.getClass().getSimpleName(); } public abstract void onClick(PlayerClickVillagerNPCEvent e); public void register() { String[] holograms = parameters.holograms();
package net.swofty.types.generic.entity.villager; @Getter public abstract class SkyBlockVillagerNPC { private static final int LOOK_DISTANCE = 16; private static final Map<SkyBlockVillagerNPC, VillagerEntityImpl> villagers = new HashMap(); private final NPCVillagerParameters parameters; private final String ID; protected SkyBlockVillagerNPC(NPCVillagerParameters parameters) { this.parameters = parameters; this.ID = this.getClass().getSimpleName(); } public abstract void onClick(PlayerClickVillagerNPCEvent e); public void register() { String[] holograms = parameters.holograms();
ServerHolograms.addExternalHologram(ServerHolograms.ExternalHologram.builder()
1
2023-12-14 09:51:15+00:00
8k
refutix/refutix
refutix-server/src/main/java/org/refutix/refutix/server/service/impl/UserServiceImpl.java
[ { "identifier": "LoginDTO", "path": "refutix-server/src/main/java/org/refutix/refutix/server/data/dto/LoginDTO.java", "snippet": "@Data\npublic class LoginDTO {\n /** login username. */\n @NotBlank(message = \"username is required\")\n private String username;\n /** login password. */\n @...
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.StpUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.refutix.refutix.server.data.dto.LoginDTO; import org.refutix.refutix.server.data.enums.UserType; import org.refutix.refutix.server.data.model.Menu; import org.refutix.refutix.server.data.model.Role; import org.refutix.refutix.server.data.model.RoleMenuRel; import org.refutix.refutix.server.data.model.User; import org.refutix.refutix.server.data.model.UserRole; import org.refutix.refutix.server.data.result.exception.BaseException; import org.refutix.refutix.server.data.result.exception.user.UserDisabledException; import org.refutix.refutix.server.data.result.exception.user.UserNotExistsException; import org.refutix.refutix.server.data.result.exception.user.UserPasswordNotMatchException; import org.refutix.refutix.server.data.vo.UserInfoVO; import org.refutix.refutix.server.mapper.UserMapper; import org.refutix.refutix.server.service.LdapService; import org.refutix.refutix.server.service.RoleMenuService; import org.refutix.refutix.server.service.SysMenuService; import org.refutix.refutix.server.service.SysRoleService; import org.refutix.refutix.server.service.TenantService; import org.refutix.refutix.server.service.UserRoleService; import org.refutix.refutix.server.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional;
5,486
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.refutix.server.service.impl; /** UserServiceImpl. */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Autowired private LdapService ldapService; @Autowired private UserMapper userMapper; @Autowired private UserRoleService userRoleService; @Autowired private SysRoleService sysRoleService; @Autowired private RoleMenuService roleMenuService; @Autowired private SysMenuService sysMenuService; @Autowired private TenantService tenantService; /** * login by username and password. * * @param loginDTO login info * @return {@link String} */ @Override public UserInfoVO login(LoginDTO loginDTO) throws BaseException { String username = loginDTO.getUsername(); String password = loginDTO.getPassword(); User user = loginDTO.isLdapLogin() ? ldapLogin(username, password) : localLogin(username, password); if (!user.getEnabled()) { throw new UserDisabledException(); } // query user info UserInfoVO userInfoVo = getUserInfoVo(user); // todo: Currently do not bind tenants /*if (CollectionUtils.isEmpty(userInfoVo.getTenantList())) { throw new UserNotBindTenantException(); }*/ StpUtil.login(user.getId(), loginDTO.isRememberMe()); return userInfoVo; } /** * get user info. include user, role, menu. tenant. * * @param user user * @return {@link UserInfoVO} */ private UserInfoVO getUserInfoVo(User user) { UserInfoVO userInfoVo = new UserInfoVO(); userInfoVo.setUser(user); userInfoVo.setSaTokenInfo(StpUtil.getTokenInfo()); // get user role list List<Role> roles = new ArrayList<>(); List<UserRole> userRoleList = userRoleService.selectUserRoleListByUserId(user); // get role list userRoleList.forEach( userRole -> { roles.add(sysRoleService.getById(userRole.getRoleId())); }); userInfoVo.setRoleList(roles); // get menu list List<Menu> menus = new ArrayList<>(); userRoleList.forEach( userRole -> { roleMenuService .list( new LambdaQueryWrapper<RoleMenuRel>() .eq(RoleMenuRel::getRoleId, userRole.getRoleId())) .forEach( roleMenu -> { menus.add(sysMenuService.getById(roleMenu.getMenuId())); }); }); userInfoVo.setMenuList(menus); userInfoVo.setCurrentTenant(tenantService.getById(1)); return userInfoVo; } private User localLogin(String username, String password) throws BaseException { User user = this.lambdaQuery() .eq(User::getUsername, username)
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.refutix.server.service.impl; /** UserServiceImpl. */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Autowired private LdapService ldapService; @Autowired private UserMapper userMapper; @Autowired private UserRoleService userRoleService; @Autowired private SysRoleService sysRoleService; @Autowired private RoleMenuService roleMenuService; @Autowired private SysMenuService sysMenuService; @Autowired private TenantService tenantService; /** * login by username and password. * * @param loginDTO login info * @return {@link String} */ @Override public UserInfoVO login(LoginDTO loginDTO) throws BaseException { String username = loginDTO.getUsername(); String password = loginDTO.getPassword(); User user = loginDTO.isLdapLogin() ? ldapLogin(username, password) : localLogin(username, password); if (!user.getEnabled()) { throw new UserDisabledException(); } // query user info UserInfoVO userInfoVo = getUserInfoVo(user); // todo: Currently do not bind tenants /*if (CollectionUtils.isEmpty(userInfoVo.getTenantList())) { throw new UserNotBindTenantException(); }*/ StpUtil.login(user.getId(), loginDTO.isRememberMe()); return userInfoVo; } /** * get user info. include user, role, menu. tenant. * * @param user user * @return {@link UserInfoVO} */ private UserInfoVO getUserInfoVo(User user) { UserInfoVO userInfoVo = new UserInfoVO(); userInfoVo.setUser(user); userInfoVo.setSaTokenInfo(StpUtil.getTokenInfo()); // get user role list List<Role> roles = new ArrayList<>(); List<UserRole> userRoleList = userRoleService.selectUserRoleListByUserId(user); // get role list userRoleList.forEach( userRole -> { roles.add(sysRoleService.getById(userRole.getRoleId())); }); userInfoVo.setRoleList(roles); // get menu list List<Menu> menus = new ArrayList<>(); userRoleList.forEach( userRole -> { roleMenuService .list( new LambdaQueryWrapper<RoleMenuRel>() .eq(RoleMenuRel::getRoleId, userRole.getRoleId())) .forEach( roleMenu -> { menus.add(sysMenuService.getById(roleMenu.getMenuId())); }); }); userInfoVo.setMenuList(menus); userInfoVo.setCurrentTenant(tenantService.getById(1)); return userInfoVo; } private User localLogin(String username, String password) throws BaseException { User user = this.lambdaQuery() .eq(User::getUsername, username)
.eq(User::getUserType, UserType.LOCAL.getCode())
1
2023-12-21 03:39:07+00:00
8k
Tianscar/uxgl
base/src/main/java/unrefined/beans/IntegerProperty.java
[ { "identifier": "IntProducer", "path": "base/src/main/java/unrefined/util/concurrent/IntProducer.java", "snippet": "@FunctionalInterface\npublic interface IntProducer extends Callable<Integer> {\n\n @Override\n default Integer call() throws Exception {\n return get();\n }\n\n int get(...
import unrefined.util.concurrent.IntProducer; import unrefined.util.event.Event; import unrefined.util.event.EventSlot; import unrefined.util.function.IntSlot; import unrefined.util.signal.Signal; import java.util.Objects; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger;
4,086
private static class PropertiesBinding extends IntegerProperty { private final Properties properties; private final String key; public PropertiesBinding(Properties properties, String key) { this.properties = Objects.requireNonNull(properties); this.key = Objects.requireNonNull(key); } @Override public boolean isReadOnly() { return false; } @Override public void set(int value) { properties.setProperty(key, Integer.toString(value)); } @Override public int get() { return Integer.parseInt(properties.getProperty(key)); } } private static class FunctionBinding extends IntegerProperty { private final IntProducer getter; private final IntSlot setter; public FunctionBinding(IntProducer getter) { this.getter = Objects.requireNonNull(getter); this.setter = null; } public FunctionBinding(IntProducer getter, IntSlot setter) { this.getter = Objects.requireNonNull(getter); this.setter = setter; } @Override public boolean isReadOnly() { return setter == null; } @Override public void set(int value) { if (setter == null) throw new IllegalArgumentException("Property is read-only"); else setter.accept(value); } @Override public int get() { return getter.get(); } } private static class AtomicInstance extends IntegerProperty { private final AtomicInteger value; public AtomicInstance(int initialValue) { value = new AtomicInteger(initialValue); } public AtomicInstance() { value = new AtomicInteger(); } @Override public boolean isReadOnly() { return false; } public void set(int value) { int previousValue = this.value.getAndSet(value); if (previousValue != value && !onChange().isEmpty()) onChange().emit(new ChangeEvent(this, previousValue, value)); } public int get() { return value.get(); } } private static class Instance extends IntegerProperty { private int value; public Instance(int initialValue) { value = initialValue; } public Instance() { } @Override public boolean isReadOnly() { return false; } public void set(int value) { int previousValue = this.value; this.value = value; if (previousValue != value && !onChange().isEmpty()) onChange().emit(new ChangeEvent(this, previousValue, value)); } public int get() { return value; } } private final Signal<EventSlot<ChangeEvent>> onChange = Signal.ofSlot(); public Signal<EventSlot<ChangeEvent>> onChange() { return onChange; } public abstract void set(int value); public abstract int get(); public abstract boolean isReadOnly(); @Override public String toString() { return Integer.toString(get()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntegerProperty that = (IntegerProperty) o; return get() == that.get(); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + get(); return result; }
package unrefined.beans; public abstract class IntegerProperty { public static IntegerProperty bind(Properties properties, String key) { return new PropertiesBinding(properties, key); } public static IntegerProperty bind(IntProducer getter, IntSlot setter) { return new FunctionBinding(getter, setter); } public static IntegerProperty bind(IntProducer getter) { return new FunctionBinding(getter); } public static IntegerProperty ofAtomic(int initialValue) { return new AtomicInstance(initialValue); } public static IntegerProperty ofAtomic() { return new AtomicInstance(); } public static IntegerProperty of(int initialValue) { return new Instance(initialValue); } public static IntegerProperty ofDefault() { return new Instance(); } private static class PropertiesBinding extends IntegerProperty { private final Properties properties; private final String key; public PropertiesBinding(Properties properties, String key) { this.properties = Objects.requireNonNull(properties); this.key = Objects.requireNonNull(key); } @Override public boolean isReadOnly() { return false; } @Override public void set(int value) { properties.setProperty(key, Integer.toString(value)); } @Override public int get() { return Integer.parseInt(properties.getProperty(key)); } } private static class FunctionBinding extends IntegerProperty { private final IntProducer getter; private final IntSlot setter; public FunctionBinding(IntProducer getter) { this.getter = Objects.requireNonNull(getter); this.setter = null; } public FunctionBinding(IntProducer getter, IntSlot setter) { this.getter = Objects.requireNonNull(getter); this.setter = setter; } @Override public boolean isReadOnly() { return setter == null; } @Override public void set(int value) { if (setter == null) throw new IllegalArgumentException("Property is read-only"); else setter.accept(value); } @Override public int get() { return getter.get(); } } private static class AtomicInstance extends IntegerProperty { private final AtomicInteger value; public AtomicInstance(int initialValue) { value = new AtomicInteger(initialValue); } public AtomicInstance() { value = new AtomicInteger(); } @Override public boolean isReadOnly() { return false; } public void set(int value) { int previousValue = this.value.getAndSet(value); if (previousValue != value && !onChange().isEmpty()) onChange().emit(new ChangeEvent(this, previousValue, value)); } public int get() { return value.get(); } } private static class Instance extends IntegerProperty { private int value; public Instance(int initialValue) { value = initialValue; } public Instance() { } @Override public boolean isReadOnly() { return false; } public void set(int value) { int previousValue = this.value; this.value = value; if (previousValue != value && !onChange().isEmpty()) onChange().emit(new ChangeEvent(this, previousValue, value)); } public int get() { return value; } } private final Signal<EventSlot<ChangeEvent>> onChange = Signal.ofSlot(); public Signal<EventSlot<ChangeEvent>> onChange() { return onChange; } public abstract void set(int value); public abstract int get(); public abstract boolean isReadOnly(); @Override public String toString() { return Integer.toString(get()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntegerProperty that = (IntegerProperty) o; return get() == that.get(); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + get(); return result; }
public static final class ChangeEvent extends Event<IntegerProperty> {
1
2023-12-15 19:03:31+00:00
8k
Outspending/BiomesAPI
src/main/java/me/outspending/biomesapi/registry/CustomBiomeRegistry.java
[ { "identifier": "BiomeLock", "path": "src/main/java/me/outspending/biomesapi/BiomeLock.java", "snippet": "@AsOf(\"0.0.1\")\npublic interface BiomeLock {\n\n /**\n * Unlocks the biome registry, performs an operation, and then locks the biome registry again.\n * This method is useful when you n...
import com.google.common.base.Preconditions; import me.outspending.biomesapi.BiomeLock; import me.outspending.biomesapi.BiomeSettings; import me.outspending.biomesapi.annotations.AsOf; import me.outspending.biomesapi.biome.BiomeHandler; import me.outspending.biomesapi.biome.CustomBiome; import me.outspending.biomesapi.nms.NMSHandler; import me.outspending.biomesapi.renderer.ParticleRenderer; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.*; import org.jetbrains.annotations.NotNull;
6,452
package me.outspending.biomesapi.registry; /** * This class implements the BiomeRegistry interface and provides a method to register a custom biome to a Minecraft server. * It uses the BiomeLock class to unlock the biome registry before registering the custom biome, and then freezes the registry again. * * @version 0.0.1 */ @AsOf("0.0.1") public class CustomBiomeRegistry implements BiomeRegistry { /** * This method registers a custom biome to a Minecraft server. * It first unlocks the biome registry using the BiomeLock class. * Then, it retrieves the biome registry from the server and creates a new Biome object with the settings and colors from the CustomBiome object. * The new Biome object is then registered to the biome registry using the ResourceLocation from the CustomBiome object. * Finally, it freezes the biome registry again using the BiomeLock class. * * @param biome The CustomBiome object that should be registered to the server. * @version 0.0.1 */ @Override @AsOf("0.0.1") @SuppressWarnings("unchecked") public void register(@NotNull CustomBiome biome) { Preconditions.checkNotNull(biome, "biome cannot be null"); BiomeLock.unlock(() -> { // Retrieve the biome registry from NMS
package me.outspending.biomesapi.registry; /** * This class implements the BiomeRegistry interface and provides a method to register a custom biome to a Minecraft server. * It uses the BiomeLock class to unlock the biome registry before registering the custom biome, and then freezes the registry again. * * @version 0.0.1 */ @AsOf("0.0.1") public class CustomBiomeRegistry implements BiomeRegistry { /** * This method registers a custom biome to a Minecraft server. * It first unlocks the biome registry using the BiomeLock class. * Then, it retrieves the biome registry from the server and creates a new Biome object with the settings and colors from the CustomBiome object. * The new Biome object is then registered to the biome registry using the ResourceLocation from the CustomBiome object. * Finally, it freezes the biome registry again using the BiomeLock class. * * @param biome The CustomBiome object that should be registered to the server. * @version 0.0.1 */ @Override @AsOf("0.0.1") @SuppressWarnings("unchecked") public void register(@NotNull CustomBiome biome) { Preconditions.checkNotNull(biome, "biome cannot be null"); BiomeLock.unlock(() -> { // Retrieve the biome registry from NMS
NMSHandler.executeNMS(nms -> {
3
2023-12-17 17:41:45+00:00
8k
lemonguge/autogen4j
src/test/java/cn/homj/autogen4j/support/FunctionCallTest.java
[ { "identifier": "AgentFunction", "path": "src/main/java/cn/homj/autogen4j/AgentFunction.java", "snippet": "@Data\n@Accessors(fluent = true)\npublic class AgentFunction {\n /**\n * The name of the function.\n */\n private String name;\n private String description;\n private Object par...
import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import cn.homj.autogen4j.AgentFunction; import cn.homj.autogen4j.support.openai.chat.Choice; import cn.homj.autogen4j.support.openai.chat.CompletionChunk; import cn.homj.autogen4j.support.openai.chat.CompletionListener; import cn.homj.autogen4j.support.openai.chat.CompletionRequest; import cn.homj.autogen4j.support.openai.chat.CompletionResponse; import cn.homj.autogen4j.support.openai.chat.Tool; import cn.homj.autogen4j.support.openai.chat.ToolCall; import cn.homj.autogen4j.support.openai.chat.ToolChoice; import cn.homj.autogen4j.support.openai.chat.tool.Function; import cn.homj.autogen4j.support.openai.chat.tool.FunctionCall; import okhttp3.sse.EventSource; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static cn.homj.autogen4j.Definition.enableOpenAiProxy; import static cn.homj.autogen4j.Definition.openAiApiKey; import static cn.homj.autogen4j.Definition.openAiProxyCompletionUrl;
4,350
package cn.homj.autogen4j.support; /** * @author jiehong.jh * @date 2023/11/27 */ public class FunctionCallTest { private final Client client = new Client(); private final Tool getCurrentWeather; private final Tool getWeatherForecast; { if (enableOpenAiProxy) { client.setCompletionUrl(openAiProxyCompletionUrl); } AgentFunction function = AgentFunctions.getCurrentWeather(); getCurrentWeather = Tool.of(new Function() .setName(function.name()) .setDescription(function.description()) .setParameters(function.parameters())); function = AgentFunctions.getWeatherForecast(); getWeatherForecast = Tool.of(new Function() .setName(function.name()) .setDescription(function.description()) .setParameters(function.parameters())); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void complete() { CompletionRequest request = new CompletionRequest() .setModel("gpt-4") .addSystemMessage("You are a helpful assistant.") .addUserMessage("What is the weather like in Boston?") .addTool(getCurrentWeather); CompletionResponse response = client.complete(openAiApiKey, request); System.out.println(JSON.toJSONString(response)); Assert.assertTrue(response.isSuccess()); Assert.assertEquals(1, response.getChoices().size()); Choice choice = response.getChoices().get(0); Assert.assertEquals("tool_calls", choice.getFinishReason()); Message message = choice.getMessage(); Assert.assertEquals("assistant", message.getRole()); Assert.assertNull(message.getContent());
package cn.homj.autogen4j.support; /** * @author jiehong.jh * @date 2023/11/27 */ public class FunctionCallTest { private final Client client = new Client(); private final Tool getCurrentWeather; private final Tool getWeatherForecast; { if (enableOpenAiProxy) { client.setCompletionUrl(openAiProxyCompletionUrl); } AgentFunction function = AgentFunctions.getCurrentWeather(); getCurrentWeather = Tool.of(new Function() .setName(function.name()) .setDescription(function.description()) .setParameters(function.parameters())); function = AgentFunctions.getWeatherForecast(); getWeatherForecast = Tool.of(new Function() .setName(function.name()) .setDescription(function.description()) .setParameters(function.parameters())); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void complete() { CompletionRequest request = new CompletionRequest() .setModel("gpt-4") .addSystemMessage("You are a helpful assistant.") .addUserMessage("What is the weather like in Boston?") .addTool(getCurrentWeather); CompletionResponse response = client.complete(openAiApiKey, request); System.out.println(JSON.toJSONString(response)); Assert.assertTrue(response.isSuccess()); Assert.assertEquals(1, response.getChoices().size()); Choice choice = response.getChoices().get(0); Assert.assertEquals("tool_calls", choice.getFinishReason()); Message message = choice.getMessage(); Assert.assertEquals("assistant", message.getRole()); Assert.assertNull(message.getContent());
List<ToolCall> toolCalls = message.getToolCalls();
7
2023-12-15 01:43:11+00:00
8k
Valerde/vadb
vadb-test/src/test/java/com/sovava/vadb/test/collection/list/TestVaArrayList.java
[ { "identifier": "VaList", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaList.java", "snippet": "public interface VaList<E> extends VaCollection<E> {\n\n// boolean addAll(VaCollection<? extends E> c);\n\n /**\n * description: 将制定集合插入到此列表的指定位置之后,后面的元素顺移\n *\n * @retu...
import com.sovava.vacollection.api.VaList; import com.sovava.vacollection.api.VaListIterator; import com.sovava.vacollection.valist.VaArrayList; import com.sovava.vadb.test.collection.utils.RandomObject; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.ListIterator;
6,775
package com.sovava.vadb.test.collection.list; /** * Description: 测试VaArrayList方法 * * @author: ykn * @date: 2023年12月27日 12:09 PM **/ @Slf4j public class TestVaArrayList { /** * description: * <p>测试结果: * <p>remove(idx) element[size--] = null; * <p>rangeCheck private in VaAbstractList private in VaArrayList * * @Author sovava * @Date 12/27/23 1:31 PM */ @Test public void testBasicFunc() { VaList<String> list1 = new VaArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 100; i++) { String elem = RandomObject.getRandomString(10); list1.add(elem); list2.add(elem); } Assert.assertEquals(100, list1.size()); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); Assert.assertTrue(list1.contains(list2.get(i))); } list1.add(3, "ykn"); Assert.assertEquals(101, list1.size()); Assert.assertEquals("ykn", list1.get(3)); Assert.assertEquals("ykn", list1.remove(3)); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); } list1.add(3, "ykn"); list1.remove("ykn"); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); } list1.add("ykn"); Assert.assertEquals("ykn", list1.get(100)); list2.add("ykn"); Assert.assertEquals("ykn", list2.get(100)); list1.clear(); list1.forEach(System.out::println); Assert.assertEquals(0, list1.size()); Assert.assertThrows("抛出异常", IndexOutOfBoundsException.class, () -> list1.get(0)); list1.add("ykn"); list1.add("tom"); list1.add("ykn"); Assert.assertEquals(0, list1.indexOf("ykn")); Assert.assertEquals(2, list1.lastIndexOf("ykn")); Assert.assertTrue(list1.removeIf("tom"::equals)); list1.forEach(log::info); } /** * description: * <p>测试结果: * <p>addAll: rangeCheckForAdd * <p>VaList中的默认replaceAll方法和sort方法 * <p>VaComparator继承Comparator接口 以兼容还 TODO 未写完的Arrays.sort() * * @Author sovava * @Date 12/27/23 2:07 PM */ @Test public void testBatch() { VaList<String> list1 = new VaArrayList<>(); VaList<String> list3 = new VaArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 100; i++) { String elem = RandomObject.getRandomString(10); list1.add(elem); list2.add(elem); } list3.addAll(list1); for (int i = 0; i < 100; i++) { Assert.assertEquals(list3.get(i), list2.get(i)); } for (int i = 0; i < 100; i++) { if (i % 2 == 0) { list3.remove(list2.get(i)); } } list1.removeAll(list3); for (int i = 0; i < 50; i++) { Assert.assertEquals(list1.get(i), list2.get((i << 1))); } list1.addAll(list1.size(), list3); list1.retainAll(list3); for (int i = 0; i < 50; i++) { Assert.assertEquals(list1.get(i), list2.get((i << 1) + 1)); } list1.replaceAll((s) -> s + " replaceAll"); // list1.forEach(log::info); VaList<String> list4 = new VaArrayList<>(list1); VaList<String> subList = list4.subList(10, 40); subList.replaceAll((s) -> s + " testsub"); // list4.forEach(log::info); subList.sort(String::compareTo); list4.forEach(log::info); } /** * description: * 测试结果:iterator.hasPrevious()判断去掉 cursor == 0 * * @Author sovava * @Date 12/27/23 2:44 PM */ @Test public void testListIterator() { VaList<String> list = new VaArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); List<String> list2 = new ArrayList<>(); list2.add("apple"); list2.add("banana"); list2.add("orange"); // 获取ListIterator对象
package com.sovava.vadb.test.collection.list; /** * Description: 测试VaArrayList方法 * * @author: ykn * @date: 2023年12月27日 12:09 PM **/ @Slf4j public class TestVaArrayList { /** * description: * <p>测试结果: * <p>remove(idx) element[size--] = null; * <p>rangeCheck private in VaAbstractList private in VaArrayList * * @Author sovava * @Date 12/27/23 1:31 PM */ @Test public void testBasicFunc() { VaList<String> list1 = new VaArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 100; i++) { String elem = RandomObject.getRandomString(10); list1.add(elem); list2.add(elem); } Assert.assertEquals(100, list1.size()); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); Assert.assertTrue(list1.contains(list2.get(i))); } list1.add(3, "ykn"); Assert.assertEquals(101, list1.size()); Assert.assertEquals("ykn", list1.get(3)); Assert.assertEquals("ykn", list1.remove(3)); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); } list1.add(3, "ykn"); list1.remove("ykn"); for (int i = 0; i < 100; i++) { Assert.assertEquals(list1.get(i), list2.get(i)); } list1.add("ykn"); Assert.assertEquals("ykn", list1.get(100)); list2.add("ykn"); Assert.assertEquals("ykn", list2.get(100)); list1.clear(); list1.forEach(System.out::println); Assert.assertEquals(0, list1.size()); Assert.assertThrows("抛出异常", IndexOutOfBoundsException.class, () -> list1.get(0)); list1.add("ykn"); list1.add("tom"); list1.add("ykn"); Assert.assertEquals(0, list1.indexOf("ykn")); Assert.assertEquals(2, list1.lastIndexOf("ykn")); Assert.assertTrue(list1.removeIf("tom"::equals)); list1.forEach(log::info); } /** * description: * <p>测试结果: * <p>addAll: rangeCheckForAdd * <p>VaList中的默认replaceAll方法和sort方法 * <p>VaComparator继承Comparator接口 以兼容还 TODO 未写完的Arrays.sort() * * @Author sovava * @Date 12/27/23 2:07 PM */ @Test public void testBatch() { VaList<String> list1 = new VaArrayList<>(); VaList<String> list3 = new VaArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 100; i++) { String elem = RandomObject.getRandomString(10); list1.add(elem); list2.add(elem); } list3.addAll(list1); for (int i = 0; i < 100; i++) { Assert.assertEquals(list3.get(i), list2.get(i)); } for (int i = 0; i < 100; i++) { if (i % 2 == 0) { list3.remove(list2.get(i)); } } list1.removeAll(list3); for (int i = 0; i < 50; i++) { Assert.assertEquals(list1.get(i), list2.get((i << 1))); } list1.addAll(list1.size(), list3); list1.retainAll(list3); for (int i = 0; i < 50; i++) { Assert.assertEquals(list1.get(i), list2.get((i << 1) + 1)); } list1.replaceAll((s) -> s + " replaceAll"); // list1.forEach(log::info); VaList<String> list4 = new VaArrayList<>(list1); VaList<String> subList = list4.subList(10, 40); subList.replaceAll((s) -> s + " testsub"); // list4.forEach(log::info); subList.sort(String::compareTo); list4.forEach(log::info); } /** * description: * 测试结果:iterator.hasPrevious()判断去掉 cursor == 0 * * @Author sovava * @Date 12/27/23 2:44 PM */ @Test public void testListIterator() { VaList<String> list = new VaArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); List<String> list2 = new ArrayList<>(); list2.add("apple"); list2.add("banana"); list2.add("orange"); // 获取ListIterator对象
VaListIterator<String> iterator = list.listIterator();
1
2023-12-17 13:29:10+00:00
8k
chamithKavinda/layered-architecture-ChamithKavinda
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "PlaceOrderBO", "path": "src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBO.java", "snippet": "public interface PlaceOrderBO extends SuperBO {\n\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQL...
import com.example.layeredarchitecture.bo.custom.PlaceOrderBO; import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBOImpl; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.ItemDTO; import com.example.layeredarchitecture.dto.OrderDetailDTO; import com.example.layeredarchitecture.view.tdm.OrderDetailTM; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
4,837
loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return placeOrderBO.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return placeOrderBO.existCustomer(id); } public String generateNewOrderId() { try { return placeOrderBO.generateOrderID(); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = placeOrderBO.getAllCustomer(); for (CustomerDTO c : allCustomers) { cmbCustomerId.getItems().add(c.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { ArrayList<ItemDTO> allItems = placeOrderBO.getAllItems(); for (ItemDTO i : allItems) { cmbItemCode.getItems().add(i.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " + total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; PlaceOrderBO placeOrderBO=new PlaceOrderBOImpl(); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { try { if (!existCustomer(newValue + "")) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } CustomerDTO customerDTO = placeOrderBO.searchCustomer(newValue + ""); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } ItemDTO item = placeOrderBO.searchItem(newItemCode + ""); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return placeOrderBO.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return placeOrderBO.existCustomer(id); } public String generateNewOrderId() { try { return placeOrderBO.generateOrderID(); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = placeOrderBO.getAllCustomer(); for (CustomerDTO c : allCustomers) { cmbCustomerId.getItems().add(c.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { ArrayList<ItemDTO> allItems = placeOrderBO.getAllItems(); for (ItemDTO i : allItems) { cmbItemCode.getItems().add(i.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " + total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(orderId,tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
4
2023-12-16 04:21:25+00:00
8k
ZakariaAitAli/MesDepensesTelecom
app/src/main/java/com/gi3/mesdepensestelecom/ui/ShowAbonnements/AbonnementFragment.java
[ { "identifier": "Abonnement", "path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Abonnement.java", "snippet": "public class Abonnement {\n\n public int Id;\n public String dateDebut;\n public String dateFin;\n public float prix;\n public int operateur;\n public int userId ;\n...
import android.app.DatePickerDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.gi3.mesdepensestelecom.Models.Abonnement; import com.gi3.mesdepensestelecom.R; import com.gi3.mesdepensestelecom.database.AbonnementRepository; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List;
3,671
package com.gi3.mesdepensestelecom.ui.ShowAbonnements; public class AbonnementFragment extends Fragment { private Button btnStartDate; private Button btnEndDate; private Calendar calendar; private HashMap<Integer, String> operatorHashMap; private HashMap<Integer, String> TypeAbonnementHashMap; private Spinner spinnerType; private Spinner spinnerOperator; private EditText editTextAmount; private Button buttonSubmit; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_abonnement, container, false); operatorHashMap = new HashMap<>(); operatorHashMap.put(0, "IAM"); operatorHashMap.put(1, "INWI"); operatorHashMap.put(2, "ORANGE"); spinnerOperator = view.findViewById(R.id.spinnerOperator); btnStartDate = view.findViewById(R.id.btnStartDate); btnEndDate = view.findViewById(R.id.btnEndDate); spinnerType = view.findViewById(R.id.spinnerType); editTextAmount = view.findViewById(R.id.editTextAmount); buttonSubmit = view.findViewById(R.id.buttonSubmit); TypeAbonnementHashMap = new HashMap<>(); TypeAbonnementHashMap.put(0, "Fibre Optique"); TypeAbonnementHashMap.put(1, "WIFI"); TypeAbonnementHashMap.put(2, "Mobile Appel"); TypeAbonnementHashMap.put(3, "Fixe"); TypeAbonnementHashMap.put(4, "Mobile Internet"); // Initialiser le calendrier calendar = Calendar.getInstance(); populateOperatorSpinner(); populateTypeAbonnementSpinner(); // Gérer les clics sur les boutons btnStartDate.setOnClickListener(view13 -> showDatePickerDialog(btnStartDate)); btnEndDate.setOnClickListener(view12 -> showDatePickerDialog(btnEndDate)); // Set click listener for the Submit button buttonSubmit.setOnClickListener(view1 -> { // Call a method to handle the insertion of data insertAbonnementData(); }); // Set click listener for the Submit button buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Call a method to handle the insertion of data insertAbonnementData(); } }); // Set click listener for the Submit button buttonSubmit.setOnClickListener(view1 -> { // Call a method to handle the insertion of data insertAbonnementData(); }); return view; } private void populateOperatorSpinner() { List<String> operatorList = new ArrayList<>(operatorHashMap.values()); ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, operatorList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerOperator.setAdapter(adapter); } private void populateTypeAbonnementSpinner() { List<String> typeList = new ArrayList<>(TypeAbonnementHashMap.values()); ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, typeList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerType.setAdapter(adapter); } private void showDatePickerDialog(final Button targetButton) { int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog( requireContext(), (view, selectedYear, selectedMonth, selectedDay) -> { // Mettez à jour le texte du bouton avec la date sélectionnée String dateString = selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear; targetButton.setText(dateString); }, year, month, day); datePickerDialog.show(); } // Method to handle the insertion of data private void insertAbonnementData() { // Retrieve data from UI elements String startDate = btnStartDate.getText().toString(); String endDate = btnEndDate.getText().toString(); String prix = editTextAmount.getText().toString(); // Retrieve selected items as strings from spinners String selectedOperator = spinnerOperator.getSelectedItem().toString(); String selectedTypeAbonnement = spinnerType.getSelectedItem().toString(); // Find the corresponding keys (numbers) from the HashMaps int operator = getKeyByValue(operatorHashMap, selectedOperator); int typeAbonnement = getKeyByValue(TypeAbonnementHashMap, selectedTypeAbonnement); // Assuming you have a user ID, replace "yourUserId" with the actual user ID int userId = 1; // Create an Abonnement object with the retrieved data Abonnement abonnement = new Abonnement(startDate, endDate, Float.parseFloat(prix), operator, userId, typeAbonnement); // Insert the Abonnement data into the database
package com.gi3.mesdepensestelecom.ui.ShowAbonnements; public class AbonnementFragment extends Fragment { private Button btnStartDate; private Button btnEndDate; private Calendar calendar; private HashMap<Integer, String> operatorHashMap; private HashMap<Integer, String> TypeAbonnementHashMap; private Spinner spinnerType; private Spinner spinnerOperator; private EditText editTextAmount; private Button buttonSubmit; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_abonnement, container, false); operatorHashMap = new HashMap<>(); operatorHashMap.put(0, "IAM"); operatorHashMap.put(1, "INWI"); operatorHashMap.put(2, "ORANGE"); spinnerOperator = view.findViewById(R.id.spinnerOperator); btnStartDate = view.findViewById(R.id.btnStartDate); btnEndDate = view.findViewById(R.id.btnEndDate); spinnerType = view.findViewById(R.id.spinnerType); editTextAmount = view.findViewById(R.id.editTextAmount); buttonSubmit = view.findViewById(R.id.buttonSubmit); TypeAbonnementHashMap = new HashMap<>(); TypeAbonnementHashMap.put(0, "Fibre Optique"); TypeAbonnementHashMap.put(1, "WIFI"); TypeAbonnementHashMap.put(2, "Mobile Appel"); TypeAbonnementHashMap.put(3, "Fixe"); TypeAbonnementHashMap.put(4, "Mobile Internet"); // Initialiser le calendrier calendar = Calendar.getInstance(); populateOperatorSpinner(); populateTypeAbonnementSpinner(); // Gérer les clics sur les boutons btnStartDate.setOnClickListener(view13 -> showDatePickerDialog(btnStartDate)); btnEndDate.setOnClickListener(view12 -> showDatePickerDialog(btnEndDate)); // Set click listener for the Submit button buttonSubmit.setOnClickListener(view1 -> { // Call a method to handle the insertion of data insertAbonnementData(); }); // Set click listener for the Submit button buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Call a method to handle the insertion of data insertAbonnementData(); } }); // Set click listener for the Submit button buttonSubmit.setOnClickListener(view1 -> { // Call a method to handle the insertion of data insertAbonnementData(); }); return view; } private void populateOperatorSpinner() { List<String> operatorList = new ArrayList<>(operatorHashMap.values()); ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, operatorList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerOperator.setAdapter(adapter); } private void populateTypeAbonnementSpinner() { List<String> typeList = new ArrayList<>(TypeAbonnementHashMap.values()); ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, typeList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerType.setAdapter(adapter); } private void showDatePickerDialog(final Button targetButton) { int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog( requireContext(), (view, selectedYear, selectedMonth, selectedDay) -> { // Mettez à jour le texte du bouton avec la date sélectionnée String dateString = selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear; targetButton.setText(dateString); }, year, month, day); datePickerDialog.show(); } // Method to handle the insertion of data private void insertAbonnementData() { // Retrieve data from UI elements String startDate = btnStartDate.getText().toString(); String endDate = btnEndDate.getText().toString(); String prix = editTextAmount.getText().toString(); // Retrieve selected items as strings from spinners String selectedOperator = spinnerOperator.getSelectedItem().toString(); String selectedTypeAbonnement = spinnerType.getSelectedItem().toString(); // Find the corresponding keys (numbers) from the HashMaps int operator = getKeyByValue(operatorHashMap, selectedOperator); int typeAbonnement = getKeyByValue(TypeAbonnementHashMap, selectedTypeAbonnement); // Assuming you have a user ID, replace "yourUserId" with the actual user ID int userId = 1; // Create an Abonnement object with the retrieved data Abonnement abonnement = new Abonnement(startDate, endDate, Float.parseFloat(prix), operator, userId, typeAbonnement); // Insert the Abonnement data into the database
long result = new AbonnementRepository(requireContext()).insertAbonnement(abonnement);
1
2023-12-20 13:43:21+00:00
8k
acatai/pn-mcts
src/experiments/RunCustomMatch.java
[ { "identifier": "PNSMCTS_Extension", "path": "src/mcts/PNSMCTS_Extension.java", "snippet": "public class PNSMCTS_Extension extends AI {\n\n\n public static boolean FIN_MOVE_SEL = false;\n public static int SOLVERLIKE_MINVISITS = Integer.MAX_VALUE; // 5; // Integer.MAX_VALUE;\n\n\n //-----------...
import game.Game; import mcts.PNSMCTS_Extension; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.mcts.MCTS; import utils.Utils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
5,674
package experiments; /** * @author Daniel Górski */ public class RunCustomMatch { /** * Name of game we wish to play */ static final String GAME_NAME = "games/Minishogi.lud"; // static final String GAME_NAME = "games/Awari.lud"; // static final String GAME_NAME = "games/Lines of Action 8x8.lud"; // static final String GAME_NAME = "games/Knightthrough.lud"; static final File GAME_FILE = new File(GAME_NAME); private static double TIME_FOR_GAME = 1.0; static final int NUM_GAMES = 1000; public static void main(final String[] args) { System.out.println(GAME_FILE.getAbsolutePath()); // load and create game final Game game = GameLoader.loadGameFromFile(GAME_FILE); final Trial trial = new Trial(game); final Context context = new Context(game, trial); Map<String, Integer> results = new HashMap<>(); int draws = 0; // params to test: boolean finMove = false; int minVisits = 5; double pnCons = 1; AI testedAI = new PNSMCTS_Extension(finMove, minVisits, pnCons); for (int gameCounter = 1; gameCounter <= NUM_GAMES; ++gameCounter) { List<AI> ais = new ArrayList<>(); if (gameCounter % 2 == 0) { ais.add(null); ais.add(MCTS.createUCT()); ais.add(testedAI); } else { ais.add(null); ais.add(testedAI); ais.add(MCTS.createUCT()); } if (gameCounter == 1) { results.put("MCTS", 0); results.put("PNSMCTS_Extension", 0); } game.start(context); for (int p = 1; p < ais.size(); ++p) { ais.get(p).initAI(game, p); } final Model model = context.model(); while (!context.trial().over()) { model.startNewStep(context, ais, TIME_FOR_GAME); } int winner = context.trial().status().winner(); if (winner > 0) { if (gameCounter % 2 == winner % 2) { results.put("PNSMCTS_Extension", results.get("PNSMCTS_Extension") + 1); } else { results.put("MCTS", results.get("MCTS") + 1); } } else ++draws; System.out.print(GAME_NAME + ": " + TIME_FOR_GAME + ": " + gameCounter + ": " + finMove + ", " + minVisits + ", " + pnCons + ": "); for (String algoName : results.keySet()) {
package experiments; /** * @author Daniel Górski */ public class RunCustomMatch { /** * Name of game we wish to play */ static final String GAME_NAME = "games/Minishogi.lud"; // static final String GAME_NAME = "games/Awari.lud"; // static final String GAME_NAME = "games/Lines of Action 8x8.lud"; // static final String GAME_NAME = "games/Knightthrough.lud"; static final File GAME_FILE = new File(GAME_NAME); private static double TIME_FOR_GAME = 1.0; static final int NUM_GAMES = 1000; public static void main(final String[] args) { System.out.println(GAME_FILE.getAbsolutePath()); // load and create game final Game game = GameLoader.loadGameFromFile(GAME_FILE); final Trial trial = new Trial(game); final Context context = new Context(game, trial); Map<String, Integer> results = new HashMap<>(); int draws = 0; // params to test: boolean finMove = false; int minVisits = 5; double pnCons = 1; AI testedAI = new PNSMCTS_Extension(finMove, minVisits, pnCons); for (int gameCounter = 1; gameCounter <= NUM_GAMES; ++gameCounter) { List<AI> ais = new ArrayList<>(); if (gameCounter % 2 == 0) { ais.add(null); ais.add(MCTS.createUCT()); ais.add(testedAI); } else { ais.add(null); ais.add(testedAI); ais.add(MCTS.createUCT()); } if (gameCounter == 1) { results.put("MCTS", 0); results.put("PNSMCTS_Extension", 0); } game.start(context); for (int p = 1; p < ais.size(); ++p) { ais.get(p).initAI(game, p); } final Model model = context.model(); while (!context.trial().over()) { model.startNewStep(context, ais, TIME_FOR_GAME); } int winner = context.trial().status().winner(); if (winner > 0) { if (gameCounter % 2 == winner % 2) { results.put("PNSMCTS_Extension", results.get("PNSMCTS_Extension") + 1); } else { results.put("MCTS", results.get("MCTS") + 1); } } else ++draws; System.out.print(GAME_NAME + ": " + TIME_FOR_GAME + ": " + gameCounter + ": " + finMove + ", " + minVisits + ", " + pnCons + ": "); for (String algoName : results.keySet()) {
System.out.print(algoName + ": " + results.get(algoName) + " RATIO: " + Utils.ratio(results.get(algoName), gameCounter - draws) + ", ");
1
2023-12-15 10:26:35+00:00
8k
litongjava/next-jfinal
src/main/java/com/jfinal/ext/handler/FakeStaticHandler.java
[ { "identifier": "Handler", "path": "src/main/java/com/jfinal/handler/Handler.java", "snippet": "public abstract class Handler {\n\t\n\t/**\n\t * The next handler\n\t */\n\tprotected Handler next;\n\t\n\t/**\n\t * Use next instead of nextHandler\n\t */\n\t@Deprecated\n\tprotected Handler nextHandler;\n\t...
import com.jfinal.handler.Handler; import com.jfinal.kit.HandlerKit; import com.jfinal.kit.StrKit; import com.jfinal.servlet.http.HttpServletRequest; import com.jfinal.servlet.http.HttpServletResponse;
3,624
/** * 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.ext.handler; /** * FakeStaticHandler. */ public class FakeStaticHandler extends Handler { private String viewPostfix; public FakeStaticHandler() { viewPostfix = ".html"; } public FakeStaticHandler(String viewPostfix) { if (StrKit.isBlank(viewPostfix)) { throw new IllegalArgumentException("viewPostfix can not be blank."); } this.viewPostfix = viewPostfix; }
/** * 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.ext.handler; /** * FakeStaticHandler. */ public class FakeStaticHandler extends Handler { private String viewPostfix; public FakeStaticHandler() { viewPostfix = ".html"; } public FakeStaticHandler(String viewPostfix) { if (StrKit.isBlank(viewPostfix)) { throw new IllegalArgumentException("viewPostfix can not be blank."); } this.viewPostfix = viewPostfix; }
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
4
2023-12-19 10:58:33+00:00
8k
ViniciusJPSilva/TSI-PizzeriaExpress
PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/RequestMB.java
[ { "identifier": "DAO", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/DAO.java", "snippet": "public class DAO<T> {\n\tprivate Class<T> tClass;\n\n\t/**\n * Construtor que recebe a classe da entidade para ser manipulada pelo DAO.\n *\n * @param tClass A classe da entidade.\n */...
import java.io.IOException; import java.util.Calendar; import java.util.List; import java.util.Optional; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; import br.vjps.tsi.pe.dao.DAO; import br.vjps.tsi.pe.dao.RequestDAO; import br.vjps.tsi.pe.enumeration.Category; import br.vjps.tsi.pe.model.Client; import br.vjps.tsi.pe.model.Item; import br.vjps.tsi.pe.model.Product; import br.vjps.tsi.pe.model.Request; import br.vjps.tsi.pe.system.SystemSettings; import br.vjps.tsi.pe.utility.EmailSender; import br.vjps.tsi.pe.utility.Utility; import br.vjps.tsi.pe.validator.ListSizeValidator;
6,146
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB {
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB {
private Request request = getOpenOrNewRequest();
6
2023-12-16 01:25:27+00:00
8k
Konloch/HeadlessIRC
src/main/java/com/konloch/ircbot/listener/event/GenericChannelEvent.java
[ { "identifier": "Channel", "path": "src/main/java/com/konloch/ircbot/server/Channel.java", "snippet": "public class Channel\n{\n\tprivate final Server server;\n\tprivate final String name;\n\tprivate boolean active = true;\n\tprivate boolean joined;\n\tprivate long lastJoinAttempt = System.currentTimeMi...
import com.konloch.ircbot.server.Channel; import com.konloch.ircbot.server.Server; import com.konloch.ircbot.server.User;
4,275
package com.konloch.ircbot.listener.event; /** * @author Konloch * @since 12/15/2023 */ public class GenericChannelEvent extends GenericServerEvent { private final Channel channel;
package com.konloch.ircbot.listener.event; /** * @author Konloch * @since 12/15/2023 */ public class GenericChannelEvent extends GenericServerEvent { private final Channel channel;
private final User user;
2
2023-12-16 02:09:21+00:00
8k
madhushiillesinghe/layered-architecture-madhushi
src/main/java/com/example/layeredarchitecture/controller/ManageCustomersFormController.java
[ { "identifier": "CustomerBo", "path": "src/main/java/com/example/layeredarchitecture/bo/custom/CustomerBo.java", "snippet": "public interface CustomerBo extends SuperBo {\n boolean saveCustomer(CustomerDTO customerDTO) throws SQLException, ClassNotFoundException;\n boolean updateCustomer(CustomerD...
import com.example.layeredarchitecture.bo.custom.CustomerBo; import com.example.layeredarchitecture.dao.BOFactory; import com.example.layeredarchitecture.dao.DAOFactory; import com.example.layeredarchitecture.dao.custom.CustomerDao; import com.example.layeredarchitecture.dao.custom.QueryDao; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.CustomerOrderDTO; import com.example.layeredarchitecture.entity.Customer; import com.example.layeredarchitecture.view.tdm.CustomerTM; import com.jfoenix.controls.JFXButton; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.List;
4,184
} } catch(SQLException e){ new Alert(Alert.AlertType.ERROR, "Failed to save the customer " + e.getMessage()).show(); } catch(ClassNotFoundException e){ e.printStackTrace(); } } else { /*Update customer*/ try { if (!existCustomer(id)) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + id).show(); } /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("UPDATE Customer SET name=?, address=? WHERE id=?"); pstm.setString(1, name); pstm.setString(2, address); pstm.setString(3, id); pstm.executeUpdate();*/ boolean isUpdate=customerBo.updateCustomer(new CustomerDTO(id,name,address)); if(isUpdate){tblCustomers.getItems().add(new CustomerTM(id,name,address)); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to update the customer " + id + e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } CustomerTM selectedCustomer = tblCustomers.getSelectionModel().getSelectedItem(); selectedCustomer.setName(name); selectedCustomer.setAddress(address); tblCustomers.refresh(); } btnAddNewCustomer.fire(); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next();*/ boolean isexists = customerBo.existCustomer(id); if (isexists) { return true; } return false; } public void btnDelete_OnAction(ActionEvent actionEvent) { /*Delete Customer*/ String id = tblCustomers.getSelectionModel().getSelectedItem().getId(); try { if (!existCustomer(id)) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + id).show(); } /*Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("DELETE FROM Customer WHERE id=?"); pstm.setString(1, id); pstm.executeUpdate();*/ boolean isDelete=customerBo.deleteCustomer(id); if(isDelete) { tblCustomers.getItems().remove(tblCustomers.getSelectionModel().getSelectedItem()); tblCustomers.getSelectionModel().clearSelection(); initUI(); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to delete the customer " + id).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private String generateNewId() { /*Connection connection = DBConnection.getDbConnection().getConnection(); ResultSet rst = connection.createStatement().executeQuery("SELECT id FROM Customer ORDER BY id DESC LIMIT 1;"); if (rst.next()) { String id = rst.getString("id"); int newCustomerId = Integer.parseInt(id.replace("C00-", "")) + 1; return String.format("C00-%03d", newCustomerId); } else { return "C00-001"; }*/ try{ ResultSet resultSet=customerBo.genarateCustomerId(); if (resultSet.next()) { String id = resultSet.getString("id"); int newCustomerId = Integer.parseInt(id.replace("C00-", "")) + 1; return String.format("C00-%03d", newCustomerId); } else { return "C00-001"; } } catch (SQLException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (tblCustomers.getItems().isEmpty()) { return "C00-001"; } else { String id = getLastCustomerId(); int newCustomerId = Integer.parseInt(id.replace("C", "")) + 1; return String.format("C00-%03d", newCustomerId); } } private String getLastCustomerId() { List<CustomerTM> tempCustomersList = new ArrayList<>(tblCustomers.getItems()); Collections.sort(tempCustomersList); return tempCustomersList.get(tempCustomersList.size() - 1).getId(); } public void getcustomerAndOrders() throws SQLException, ClassNotFoundException {
package com.example.layeredarchitecture.controller; public class ManageCustomersFormController { public AnchorPane root; public TextField txtCustomerName; public TextField txtCustomerId; public JFXButton btnDelete; public JFXButton btnSave; public TextField txtCustomerAddress; public TableView<CustomerTM> tblCustomers; public JFXButton btnAddNewCustomer; CustomerDao customerDao= (CustomerDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.CUSTOMER); QueryDao queryDao= (QueryDao) DAOFactory.getDADFactory().getDao(DAOFactory.DADType.QUARY); CustomerBo customerBo= (CustomerBo) BOFactory.getBoFactory().getBo(BOFactory.BOType.CUSTOM); public void initialize() throws SQLException, ClassNotFoundException { tblCustomers.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("id")); tblCustomers.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("name")); tblCustomers.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("address")); initUI(); tblCustomers.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { btnDelete.setDisable(newValue == null); btnSave.setText(newValue != null ? "Update" : "Save"); btnSave.setDisable(newValue == null); if (newValue != null) { txtCustomerId.setText(newValue.getId()); txtCustomerName.setText(newValue.getName()); txtCustomerAddress.setText(newValue.getAddress()); txtCustomerId.setDisable(false); txtCustomerName.setDisable(false); txtCustomerAddress.setDisable(false); } }); txtCustomerAddress.setOnAction(event -> btnSave.fire()); loadAllCustomers(); // getcustomerAndOrders(); } private void loadAllCustomers() { /*Get all customers*//* try { Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); while (rst.next()) { tblCustomers.getItems().add(new CustomerTM(rst.getString("id"), rst.getString("name"), rst.getString("address"))); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } */ tblCustomers.getItems().clear(); try { /* Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); */ ArrayList<Customer> allCustomer = customerDao.getAll(); for (Customer entity:allCustomer) { tblCustomers.getItems().add( new CustomerTM( entity.getId(), entity.getName(), entity.getAddress())); } getcustomerAndOrders(); /* while (rst.next()) { tblCustomers.getItems().add(new CustomerTM(rst.getString("id"), rst.getString("name"), rst.getString("address"))); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } } private void initUI() { txtCustomerId.clear(); txtCustomerName.clear(); txtCustomerAddress.clear(); txtCustomerId.setDisable(true); txtCustomerName.setDisable(true); txtCustomerAddress.setDisable(true); txtCustomerId.setEditable(false); btnSave.setDisable(true); btnDelete.setDisable(true); } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAddNew_OnAction(ActionEvent actionEvent) { txtCustomerId.setDisable(false); txtCustomerName.setDisable(false); txtCustomerAddress.setDisable(false); txtCustomerId.clear(); txtCustomerId.setText(generateNewId()); txtCustomerName.clear(); txtCustomerAddress.clear(); txtCustomerName.requestFocus(); btnSave.setDisable(false); btnSave.setText("Save"); tblCustomers.getSelectionModel().clearSelection(); } public void btnSave_OnAction(ActionEvent actionEvent) { String id = txtCustomerId.getText(); String name = txtCustomerName.getText(); String address = txtCustomerAddress.getText(); if (!name.matches("[A-Za-z ]+")) { new Alert(Alert.AlertType.ERROR, "Invalid name").show(); txtCustomerName.requestFocus(); return; } else if (!address.matches(".{3,}")) { new Alert(Alert.AlertType.ERROR, "Address should be at least 3 characters long").show(); txtCustomerAddress.requestFocus(); return; } if (btnSave.getText().equalsIgnoreCase("save")) { /*Save Customer*/ try { if (existCustomer(id)) { new Alert(Alert.AlertType.ERROR, id + " already exists").show(); } /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("INSERT INTO Customer (id,name, address) VALUES (?,?,?)"); pstm.setString(1, id); pstm.setString(2, name); pstm.setString(3, address); pstm.executeUpdate();*/ boolean isSaved = customerBo.saveCustomer(new CustomerDTO(id, name, address)); if (isSaved) { tblCustomers.getItems().add(new CustomerTM(id, name, address)); } } catch(SQLException e){ new Alert(Alert.AlertType.ERROR, "Failed to save the customer " + e.getMessage()).show(); } catch(ClassNotFoundException e){ e.printStackTrace(); } } else { /*Update customer*/ try { if (!existCustomer(id)) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + id).show(); } /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("UPDATE Customer SET name=?, address=? WHERE id=?"); pstm.setString(1, name); pstm.setString(2, address); pstm.setString(3, id); pstm.executeUpdate();*/ boolean isUpdate=customerBo.updateCustomer(new CustomerDTO(id,name,address)); if(isUpdate){tblCustomers.getItems().add(new CustomerTM(id,name,address)); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to update the customer " + id + e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } CustomerTM selectedCustomer = tblCustomers.getSelectionModel().getSelectedItem(); selectedCustomer.setName(name); selectedCustomer.setAddress(address); tblCustomers.refresh(); } btnAddNewCustomer.fire(); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next();*/ boolean isexists = customerBo.existCustomer(id); if (isexists) { return true; } return false; } public void btnDelete_OnAction(ActionEvent actionEvent) { /*Delete Customer*/ String id = tblCustomers.getSelectionModel().getSelectedItem().getId(); try { if (!existCustomer(id)) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + id).show(); } /*Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("DELETE FROM Customer WHERE id=?"); pstm.setString(1, id); pstm.executeUpdate();*/ boolean isDelete=customerBo.deleteCustomer(id); if(isDelete) { tblCustomers.getItems().remove(tblCustomers.getSelectionModel().getSelectedItem()); tblCustomers.getSelectionModel().clearSelection(); initUI(); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to delete the customer " + id).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private String generateNewId() { /*Connection connection = DBConnection.getDbConnection().getConnection(); ResultSet rst = connection.createStatement().executeQuery("SELECT id FROM Customer ORDER BY id DESC LIMIT 1;"); if (rst.next()) { String id = rst.getString("id"); int newCustomerId = Integer.parseInt(id.replace("C00-", "")) + 1; return String.format("C00-%03d", newCustomerId); } else { return "C00-001"; }*/ try{ ResultSet resultSet=customerBo.genarateCustomerId(); if (resultSet.next()) { String id = resultSet.getString("id"); int newCustomerId = Integer.parseInt(id.replace("C00-", "")) + 1; return String.format("C00-%03d", newCustomerId); } else { return "C00-001"; } } catch (SQLException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (tblCustomers.getItems().isEmpty()) { return "C00-001"; } else { String id = getLastCustomerId(); int newCustomerId = Integer.parseInt(id.replace("C", "")) + 1; return String.format("C00-%03d", newCustomerId); } } private String getLastCustomerId() { List<CustomerTM> tempCustomersList = new ArrayList<>(tblCustomers.getItems()); Collections.sort(tempCustomersList); return tempCustomersList.get(tempCustomersList.size() - 1).getId(); } public void getcustomerAndOrders() throws SQLException, ClassNotFoundException {
List<CustomerOrderDTO> cuslist = queryDao.customerOrderDetail();
6
2023-12-17 02:17:36+00:00
8k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/combat/ZealotBot.java
[ { "identifier": "Render3DEvent", "path": "src/java/xyz/apfelmus/cheeto/client/events/Render3DEvent.java", "snippet": "public class Render3DEvent\nextends Listener {\n public float partialTicks;\n\n public Render3DEvent(float partialTicks) {\n super(Listener.At.HEAD);\n this.partialTi...
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Enable; 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.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.Rotation; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils;
4,211
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.settings.KeyBinding * net.minecraft.entity.Entity * net.minecraft.entity.monster.EntityEnderman * net.minecraft.util.MovingObjectPosition * net.minecraft.util.Vec3 */ package xyz.apfelmus.cheeto.client.modules.combat; public class ZealotBot { @Setting(name="AimTime") private IntegerSetting aimTime = new IntegerSetting(100, 0, 1000); @Setting(name="ClickDelay") private IntegerSetting clickDelay = new IntegerSetting(100, 0, 1000); @Setting(name="Radius") private IntegerSetting radius = new IntegerSetting(30, 0, 30); @Setting(name="GodGamerMode") public static BooleanSetting godGamerMode = new BooleanSetting(false); private static Minecraft mc = Minecraft.func_71410_x(); private Entity zealot; private KillState ks = KillState.SELECT; @Enable public void onEnable() { this.zealot = null; this.ks = KillState.SELECT; } @Event public void onRender(Render3DEvent event) { switch (this.ks) { case SELECT: { ArrayList<Entity> allPossible = new ArrayList<Entity>(); for (Entity e3 : ZealotBot.mc.field_71441_e.field_72996_f) { if (!(e3 instanceof EntityEnderman) || e3 == null) continue; allPossible.add(e3); } allPossible.forEach(e -> { MovingObjectPosition mop = ZealotBot.mc.field_71441_e.func_72933_a(ZealotBot.mc.field_71439_g.func_174824_e(1.0f), e.func_174791_d()); if (mop != null) { System.out.println((Object)mop.field_72313_a); } }); if (allPossible.isEmpty()) break; this.zealot = Collections.min(allPossible, Comparator.comparing(e2 -> Float.valueOf(e2.func_70032_d((Entity)ZealotBot.mc.field_71439_g)))); Vec3 vec = this.zealot.func_174791_d(); vec = vec.func_72441_c(0.0, 1.0, 0.0);
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.settings.KeyBinding * net.minecraft.entity.Entity * net.minecraft.entity.monster.EntityEnderman * net.minecraft.util.MovingObjectPosition * net.minecraft.util.Vec3 */ package xyz.apfelmus.cheeto.client.modules.combat; public class ZealotBot { @Setting(name="AimTime") private IntegerSetting aimTime = new IntegerSetting(100, 0, 1000); @Setting(name="ClickDelay") private IntegerSetting clickDelay = new IntegerSetting(100, 0, 1000); @Setting(name="Radius") private IntegerSetting radius = new IntegerSetting(30, 0, 30); @Setting(name="GodGamerMode") public static BooleanSetting godGamerMode = new BooleanSetting(false); private static Minecraft mc = Minecraft.func_71410_x(); private Entity zealot; private KillState ks = KillState.SELECT; @Enable public void onEnable() { this.zealot = null; this.ks = KillState.SELECT; } @Event public void onRender(Render3DEvent event) { switch (this.ks) { case SELECT: { ArrayList<Entity> allPossible = new ArrayList<Entity>(); for (Entity e3 : ZealotBot.mc.field_71441_e.field_72996_f) { if (!(e3 instanceof EntityEnderman) || e3 == null) continue; allPossible.add(e3); } allPossible.forEach(e -> { MovingObjectPosition mop = ZealotBot.mc.field_71441_e.func_72933_a(ZealotBot.mc.field_71439_g.func_174824_e(1.0f), e.func_174791_d()); if (mop != null) { System.out.println((Object)mop.field_72313_a); } }); if (allPossible.isEmpty()) break; this.zealot = Collections.min(allPossible, Comparator.comparing(e2 -> Float.valueOf(e2.func_70032_d((Entity)ZealotBot.mc.field_71439_g)))); Vec3 vec = this.zealot.func_174791_d(); vec = vec.func_72441_c(0.0, 1.0, 0.0);
Rotation rot = RotationUtils.getRotation(vec);
5
2023-12-21 16:22:25+00:00
8k
ciallo-dev/JWSystemLib
src/test/java/TestCourseReview.java
[ { "identifier": "JWSystem", "path": "src/main/java/moe/snowflake/jwSystem/JWSystem.java", "snippet": "public class JWSystem {\n public Connection.Response jwLoggedResponse;\n public Connection.Response courseSelectSystemResponse;\n public Map<String, String> headers = new HashMap<>();\n priv...
import moe.snowflake.jwSystem.JWSystem; import moe.snowflake.jwSystem.manager.URLManager; import org.junit.jupiter.api.Test;
4,772
public class TestCourseReview { @Test public void testReview() { // 使用备用路线登录
public class TestCourseReview { @Test public void testReview() { // 使用备用路线登录
URLManager.useLocalNetServer(2);
1
2023-12-21 10:58:12+00:00
8k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/writer/builder/BuilderEncodedValues.java
[ { "identifier": "BaseAnnotationEncodedValue", "path": "app/src/main/java/org/jf/dexlib2/base/value/BaseAnnotationEncodedValue.java", "snippet": "public abstract class BaseAnnotationEncodedValue implements AnnotationEncodedValue {\n @Override\n public int hashCode() {\n int hashCode = getTyp...
import androidx.annotation.NonNull; import org.jf.dexlib2.base.value.BaseAnnotationEncodedValue; import org.jf.dexlib2.base.value.BaseArrayEncodedValue; import org.jf.dexlib2.base.value.BaseBooleanEncodedValue; import org.jf.dexlib2.base.value.BaseEnumEncodedValue; import org.jf.dexlib2.base.value.BaseFieldEncodedValue; import org.jf.dexlib2.base.value.BaseMethodEncodedValue; import org.jf.dexlib2.base.value.BaseNullEncodedValue; import org.jf.dexlib2.base.value.BaseStringEncodedValue; import org.jf.dexlib2.base.value.BaseTypeEncodedValue; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.immutable.value.ImmutableByteEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableCharEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableDoubleEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableFloatEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableIntEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableLongEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableShortEncodedValue; import org.jf.util.ExceptionWithContext; import java.util.List; import java.util.Set;
5,423
} public static class BuilderAnnotationEncodedValue extends BaseAnnotationEncodedValue implements BuilderEncodedValue { @NonNull final BuilderTypeReference typeReference; @NonNull final Set<? extends BuilderAnnotationElement> elements; BuilderAnnotationEncodedValue(@NonNull BuilderTypeReference typeReference, @NonNull Set<? extends BuilderAnnotationElement> elements) { this.typeReference = typeReference; this.elements = elements; } @NonNull @Override public String getType() { return typeReference.getType(); } @NonNull @Override public Set<? extends BuilderAnnotationElement> getElements() { return elements; } } public static class BuilderArrayEncodedValue extends BaseArrayEncodedValue implements BuilderEncodedValue { @NonNull final List<? extends BuilderEncodedValue> elements; BuilderArrayEncodedValue(@NonNull List<? extends BuilderEncodedValue> elements) { this.elements = elements; } @NonNull @Override public List<? extends EncodedValue> getValue() { return elements; } } public static class BuilderBooleanEncodedValue extends BaseBooleanEncodedValue implements BuilderEncodedValue { public static final BuilderBooleanEncodedValue TRUE_VALUE = new BuilderBooleanEncodedValue(true); public static final BuilderBooleanEncodedValue FALSE_VALUE = new BuilderBooleanEncodedValue(false); private final boolean value; private BuilderBooleanEncodedValue(boolean value) { this.value = value; } @Override public boolean getValue() { return value; } } public static class BuilderByteEncodedValue extends ImmutableByteEncodedValue implements BuilderEncodedValue { public BuilderByteEncodedValue(byte value) { super(value); } } public static class BuilderCharEncodedValue extends ImmutableCharEncodedValue implements BuilderEncodedValue { public BuilderCharEncodedValue(char value) { super(value); } } public static class BuilderDoubleEncodedValue extends ImmutableDoubleEncodedValue implements BuilderEncodedValue { public BuilderDoubleEncodedValue(double value) { super(value); } } public static class BuilderEnumEncodedValue extends BaseEnumEncodedValue implements BuilderEncodedValue { @NonNull final BuilderFieldReference enumReference; BuilderEnumEncodedValue(@NonNull BuilderFieldReference enumReference) { this.enumReference = enumReference; } @NonNull @Override public BuilderFieldReference getValue() { return enumReference; } } public static class BuilderFieldEncodedValue extends BaseFieldEncodedValue implements BuilderEncodedValue { @NonNull final BuilderFieldReference fieldReference; BuilderFieldEncodedValue(@NonNull BuilderFieldReference fieldReference) { this.fieldReference = fieldReference; } @NonNull @Override public BuilderFieldReference getValue() { return fieldReference; } } public static class BuilderFloatEncodedValue extends ImmutableFloatEncodedValue implements BuilderEncodedValue { public BuilderFloatEncodedValue(float value) { super(value); } }
/* * Copyright 2013, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 org.jf.dexlib2.writer.builder; public abstract class BuilderEncodedValues { @NonNull public static BuilderEncodedValue defaultValueForType(String type) { switch (type.charAt(0)) { case 'Z': return BuilderBooleanEncodedValue.FALSE_VALUE; case 'B': return new BuilderByteEncodedValue((byte) 0); case 'S': return new BuilderShortEncodedValue((short) 0); case 'C': return new BuilderCharEncodedValue((char) 0); case 'I': return new BuilderIntEncodedValue(0); case 'J': return new BuilderLongEncodedValue(0); case 'F': return new BuilderFloatEncodedValue(0); case 'D': return new BuilderDoubleEncodedValue(0); case 'L': case '[': return BuilderNullEncodedValue.INSTANCE; default: throw new ExceptionWithContext("Unrecognized type: %s", type); } } public static interface BuilderEncodedValue extends EncodedValue { } public static class BuilderAnnotationEncodedValue extends BaseAnnotationEncodedValue implements BuilderEncodedValue { @NonNull final BuilderTypeReference typeReference; @NonNull final Set<? extends BuilderAnnotationElement> elements; BuilderAnnotationEncodedValue(@NonNull BuilderTypeReference typeReference, @NonNull Set<? extends BuilderAnnotationElement> elements) { this.typeReference = typeReference; this.elements = elements; } @NonNull @Override public String getType() { return typeReference.getType(); } @NonNull @Override public Set<? extends BuilderAnnotationElement> getElements() { return elements; } } public static class BuilderArrayEncodedValue extends BaseArrayEncodedValue implements BuilderEncodedValue { @NonNull final List<? extends BuilderEncodedValue> elements; BuilderArrayEncodedValue(@NonNull List<? extends BuilderEncodedValue> elements) { this.elements = elements; } @NonNull @Override public List<? extends EncodedValue> getValue() { return elements; } } public static class BuilderBooleanEncodedValue extends BaseBooleanEncodedValue implements BuilderEncodedValue { public static final BuilderBooleanEncodedValue TRUE_VALUE = new BuilderBooleanEncodedValue(true); public static final BuilderBooleanEncodedValue FALSE_VALUE = new BuilderBooleanEncodedValue(false); private final boolean value; private BuilderBooleanEncodedValue(boolean value) { this.value = value; } @Override public boolean getValue() { return value; } } public static class BuilderByteEncodedValue extends ImmutableByteEncodedValue implements BuilderEncodedValue { public BuilderByteEncodedValue(byte value) { super(value); } } public static class BuilderCharEncodedValue extends ImmutableCharEncodedValue implements BuilderEncodedValue { public BuilderCharEncodedValue(char value) { super(value); } } public static class BuilderDoubleEncodedValue extends ImmutableDoubleEncodedValue implements BuilderEncodedValue { public BuilderDoubleEncodedValue(double value) { super(value); } } public static class BuilderEnumEncodedValue extends BaseEnumEncodedValue implements BuilderEncodedValue { @NonNull final BuilderFieldReference enumReference; BuilderEnumEncodedValue(@NonNull BuilderFieldReference enumReference) { this.enumReference = enumReference; } @NonNull @Override public BuilderFieldReference getValue() { return enumReference; } } public static class BuilderFieldEncodedValue extends BaseFieldEncodedValue implements BuilderEncodedValue { @NonNull final BuilderFieldReference fieldReference; BuilderFieldEncodedValue(@NonNull BuilderFieldReference fieldReference) { this.fieldReference = fieldReference; } @NonNull @Override public BuilderFieldReference getValue() { return fieldReference; } } public static class BuilderFloatEncodedValue extends ImmutableFloatEncodedValue implements BuilderEncodedValue { public BuilderFloatEncodedValue(float value) { super(value); } }
public static class BuilderIntEncodedValue extends ImmutableIntEncodedValue
14
2023-12-16 11:11:16+00:00
8k
nimashidewanmini/layered-architecture-nimashi
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "DBConnection", "path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java", "snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLE...
import com.example.layeredarchitecture.dao.*; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.model.CustomerDTO; import com.example.layeredarchitecture.model.ItemDTO; import com.example.layeredarchitecture.model.OrderDetailDTO; import com.example.layeredarchitecture.util.TransactionConnection; import com.example.layeredarchitecture.view.tdm.OrderDetailTM; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
4,225
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; ItemDao itemDao= new ItemDAOImpl(); OrderDAO orderDAO= new OrderDAOImpl(); CustomerDao customerDao=new customerDAOImpl(); OrderDetailDAO orderDetailDAO=new OrderDetailDAOImpl(); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { if (!existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { // Connection connection = DBConnection.getDbConnection().getConnection(); // PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); // pstm.setString(1, code); // return pstm.executeQuery().next(); return itemDao.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { ResultSet resultSet = orderDAO.generateNewOrderID(); return resultSet.next() ? String.format("OID-%03d", (Integer.parseInt(resultSet.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); // while (rst.next()) { // cmbCustomerId.getItems().add(rst.getString("id")); // } ArrayList <CustomerDTO> allCustomers=customerDao.getAllCustomer(); for (CustomerDTO customerDTO:allCustomers) { cmbCustomerId.getItems().add(customerDTO.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Item"); ArrayList <ItemDTO> allItems=itemDao.getAllItems(); // while (rst.next()) { // cmbItemCode.getItems().add(rst.getString("code")); // } for (ItemDTO itemDTO:allItems){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(), tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList())); if (b) { new Alert(Alert.AlertType.INFORMATION, "Order has been placed successfully").show(); } else { new Alert(Alert.AlertType.ERROR, "Order has not been placed successfully").show(); } orderId = generateNewOrderId(); lblId.setText("Order Id: " + orderId); cmbCustomerId.getSelectionModel().clearSelection(); cmbItemCode.getSelectionModel().clearSelection(); tblOrderDetails.getItems().clear(); txtQty.clear(); calculateTotal(); } public boolean saveOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) { /*Transaction*/ boolean isOrderSaved; boolean isOrderDetailSaved = false; boolean isItemUpdated = false; try { orderDAO.selectOrderId(orderId); isOrderSaved = orderDAO.saveOrder(orderId, orderDate, customerId); for (OrderDetailDTO detail : orderDetails) { isOrderDetailSaved = orderDetailDAO.save(orderId, detail); // //Search & Update Item ItemDTO item = findItem(detail.getItemCode()); item.setQtyOnHand(item.getQtyOnHand() - detail.getQty()); isItemUpdated = itemDao.updateItem(item); } if (isOrderSaved && isOrderDetailSaved && isItemUpdated) {
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; ItemDao itemDao= new ItemDAOImpl(); OrderDAO orderDAO= new OrderDAOImpl(); CustomerDao customerDao=new customerDAOImpl(); OrderDetailDAO orderDetailDAO=new OrderDetailDAOImpl(); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { if (!existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { // Connection connection = DBConnection.getDbConnection().getConnection(); // PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); // pstm.setString(1, code); // return pstm.executeQuery().next(); return itemDao.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { ResultSet resultSet = orderDAO.generateNewOrderID(); return resultSet.next() ? String.format("OID-%03d", (Integer.parseInt(resultSet.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); // while (rst.next()) { // cmbCustomerId.getItems().add(rst.getString("id")); // } ArrayList <CustomerDTO> allCustomers=customerDao.getAllCustomer(); for (CustomerDTO customerDTO:allCustomers) { cmbCustomerId.getItems().add(customerDTO.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Item"); ArrayList <ItemDTO> allItems=itemDao.getAllItems(); // while (rst.next()) { // cmbItemCode.getItems().add(rst.getString("code")); // } for (ItemDTO itemDTO:allItems){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(), tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList())); if (b) { new Alert(Alert.AlertType.INFORMATION, "Order has been placed successfully").show(); } else { new Alert(Alert.AlertType.ERROR, "Order has not been placed successfully").show(); } orderId = generateNewOrderId(); lblId.setText("Order Id: " + orderId); cmbCustomerId.getSelectionModel().clearSelection(); cmbItemCode.getSelectionModel().clearSelection(); tblOrderDetails.getItems().clear(); txtQty.clear(); calculateTotal(); } public boolean saveOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) { /*Transaction*/ boolean isOrderSaved; boolean isOrderDetailSaved = false; boolean isItemUpdated = false; try { orderDAO.selectOrderId(orderId); isOrderSaved = orderDAO.saveOrder(orderId, orderDate, customerId); for (OrderDetailDTO detail : orderDetails) { isOrderDetailSaved = orderDetailDAO.save(orderId, detail); // //Search & Update Item ItemDTO item = findItem(detail.getItemCode()); item.setQtyOnHand(item.getQtyOnHand() - detail.getQty()); isItemUpdated = itemDao.updateItem(item); } if (isOrderSaved && isOrderDetailSaved && isItemUpdated) {
TransactionConnection.getConnection().commit();
4
2023-12-16 04:14:29+00:00
8k
IzanagiCraft/IzanagiWorldGuard
worldguard-plugin-bukkit/src/main/java/com/izanagicraft/guard/events/listener/InventoryItemChangeListener.java
[ { "identifier": "GuardConstants", "path": "worldguard-api/src/main/java/com/izanagicraft/guard/GuardConstants.java", "snippet": "public class GuardConstants {\n\n /**\n * The main prefix used for plugin-related messages.\n */\n public static final String PREFIX = \"&#CB2D3EG&#D4343Du&#DD3A...
import org.bukkit.event.player.PlayerAttemptPickupItemEvent; import org.bukkit.event.player.PlayerDropItemEvent; import com.izanagicraft.guard.GuardConstants; import com.izanagicraft.guard.IzanagiWorldGuardPlugin; import com.izanagicraft.guard.commands.BuildModeCommand; import com.izanagicraft.guard.events.GuardListener; import com.izanagicraft.guard.flags.GuardFlag; import com.izanagicraft.guard.permissions.GuardPermission; import com.izanagicraft.guard.utils.MessageUtils; import io.papermc.paper.event.player.PlayerPickItemEvent; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryPickupItemEvent;
6,990
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com> * Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com> * Copyright (c) 2023 - present | izanagicraft.com team and contributors * * 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 com.izanagicraft.guard.events.listener; /** * IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener * <p> * Handles inventory-related events for IzanagiWorldGuard. * This listener checks and enforces item drop and pickup permissions within protected regions. * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class InventoryItemChangeListener extends GuardListener { /** * Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin. * * @param plugin The IzanagiWorldGuardPlugin instance. */ public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) { super(plugin); } /** * Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions. * * @param event The PlayerDropItemEvent. */ @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); Item item = event.getItemDrop(); if (player == null || item == null) { event.setCancelled(true); return; } if (event.isCancelled()) return;
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com> * Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com> * Copyright (c) 2023 - present | izanagicraft.com team and contributors * * 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 com.izanagicraft.guard.events.listener; /** * IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener * <p> * Handles inventory-related events for IzanagiWorldGuard. * This listener checks and enforces item drop and pickup permissions within protected regions. * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class InventoryItemChangeListener extends GuardListener { /** * Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin. * * @param plugin The IzanagiWorldGuardPlugin instance. */ public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) { super(plugin); } /** * Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions. * * @param event The PlayerDropItemEvent. */ @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); Item item = event.getItemDrop(); if (player == null || item == null) { event.setCancelled(true); return; } if (event.isCancelled()) return;
if (player.hasPermission(GuardPermission.GROUPS_ADMIN.getName())
5
2023-12-17 14:18:31+00:00
8k
123yyh123/xiaofanshu
xfs-job-server/src/main/java/com/yyh/xfs/job/service/impl/UserServiceImpl.java
[ { "identifier": "ExceptionMsgEnum", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/myEnum/ExceptionMsgEnum.java", "snippet": "@Getter\n@ToString\npublic enum ExceptionMsgEnum {\n /**\n * 业务异常\n */\n NOT_LOGIN(StatusCode.NOT_LOGIN,\"未登录\"),\n TOKEN_EXPIRED(StatusCode.TO...
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.OnlyWarnException; import com.yyh.xfs.job.mapper.UserMapper; import com.yyh.xfs.job.service.UserService; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.vo.UserVO; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors;
4,072
package com.yyh.xfs.job.service.impl; /** * @author yyh * @date 2023-12-23 */ @Service @DS("xfs_user") public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { /** * 没有用updateBatchById,因为该方法有事务,会导致事务回滚,而我们不需要事务回滚 * @param userVos vo */ @Override public void updateByVos(List<UserVO> userVos) { if (userVos == null || userVos.isEmpty()) { return; } List<UserDO> users = this.listByIds(userVos.stream().map(UserVO::getId).collect(Collectors.toList())); if (users == null || users.isEmpty()) { return; } users.forEach(userDO -> { UserVO vo = userVos.stream().filter(userVO1 -> userVO1.getId().equals(userDO.getId())).findFirst().orElse(null); if (vo == null) { return; } UserDO user = UserDO.voToDO(userDO, vo); try { this.updateById(user); } catch (Exception e) {
package com.yyh.xfs.job.service.impl; /** * @author yyh * @date 2023-12-23 */ @Service @DS("xfs_user") public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { /** * 没有用updateBatchById,因为该方法有事务,会导致事务回滚,而我们不需要事务回滚 * @param userVos vo */ @Override public void updateByVos(List<UserVO> userVos) { if (userVos == null || userVos.isEmpty()) { return; } List<UserDO> users = this.listByIds(userVos.stream().map(UserVO::getId).collect(Collectors.toList())); if (users == null || users.isEmpty()) { return; } users.forEach(userDO -> { UserVO vo = userVos.stream().filter(userVO1 -> userVO1.getId().equals(userDO.getId())).findFirst().orElse(null); if (vo == null) { return; } UserDO user = UserDO.voToDO(userDO, vo); try { this.updateById(user); } catch (Exception e) {
throw new BusinessException(ExceptionMsgEnum.DB_ERROR);
1
2023-12-15 08:13:42+00:00
8k
catools2/athena
athena-api-boot/src/test/java/org/catools/athena/rest/pipeline/mapper/AthenaPipelineMapperIT.java
[ { "identifier": "EnvironmentDto", "path": "athena-core/src/main/java/org/catools/athena/core/model/EnvironmentDto.java", "snippet": "@Data\n@Accessors(chain = true)\n@NoArgsConstructor\npublic class EnvironmentDto {\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n private String code;\n\n @NotBl...
import org.catools.athena.core.model.EnvironmentDto; import org.catools.athena.core.model.MetadataDto; import org.catools.athena.core.model.ProjectDto; import org.catools.athena.core.model.UserDto; import org.catools.athena.pipeline.model.PipelineDto; import org.catools.athena.pipeline.model.PipelineExecutionDto; import org.catools.athena.pipeline.model.PipelineExecutionStatusDto; import org.catools.athena.pipeline.model.PipelineScenarioExecutionDto; import org.catools.athena.rest.AthenaBaseTest; import org.catools.athena.rest.core.builder.AthenaCoreBuilder; import org.catools.athena.rest.core.entity.Environment; import org.catools.athena.rest.core.entity.Project; import org.catools.athena.rest.core.entity.User; import org.catools.athena.rest.core.service.AthenaCoreService; import org.catools.athena.rest.pipeline.builder.AthenaPipelineBuilder; import org.catools.athena.rest.pipeline.entity.*; import org.catools.athena.rest.pipeline.service.AthenaPipelineService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.IsEqual.equalTo;
5,281
package org.catools.athena.rest.pipeline.mapper; public class AthenaPipelineMapperIT extends AthenaBaseTest { private static PipelineDto PIPELINE_DTO; private static Pipeline PIPELINE; private static PipelineExecutionDto PIPELINE_EXECUTION_DTO; private static PipelineExecution PIPELINE_EXECUTION; private static PipelineScenarioExecutionDto PIPELINE_SCENARIO_EXECUTION_DTO; private static PipelineScenarioExecution PIPELINE_SCENARIO_EXECUTION; @Autowired AthenaPipelineMapper pipelineMapper; @Autowired AthenaCoreService athenaCoreService; @Autowired AthenaPipelineService athenaPipelineService; @BeforeAll public void beforeAll() { UserDto userDto = AthenaCoreBuilder.buildUserDto(); userDto.setId(athenaCoreService.saveUser(userDto).getId()); User user = AthenaCoreBuilder.buildUser(userDto); ProjectDto projectDto = AthenaCoreBuilder.buildProjectDto(); projectDto.setId(athenaCoreService.saveProject(projectDto).getId());
package org.catools.athena.rest.pipeline.mapper; public class AthenaPipelineMapperIT extends AthenaBaseTest { private static PipelineDto PIPELINE_DTO; private static Pipeline PIPELINE; private static PipelineExecutionDto PIPELINE_EXECUTION_DTO; private static PipelineExecution PIPELINE_EXECUTION; private static PipelineScenarioExecutionDto PIPELINE_SCENARIO_EXECUTION_DTO; private static PipelineScenarioExecution PIPELINE_SCENARIO_EXECUTION; @Autowired AthenaPipelineMapper pipelineMapper; @Autowired AthenaCoreService athenaCoreService; @Autowired AthenaPipelineService athenaPipelineService; @BeforeAll public void beforeAll() { UserDto userDto = AthenaCoreBuilder.buildUserDto(); userDto.setId(athenaCoreService.saveUser(userDto).getId()); User user = AthenaCoreBuilder.buildUser(userDto); ProjectDto projectDto = AthenaCoreBuilder.buildProjectDto(); projectDto.setId(athenaCoreService.saveProject(projectDto).getId());
Project project = AthenaCoreBuilder.buildProject(projectDto);
11
2023-12-16 22:30:49+00:00
8k
premiering/permad-game
src/main/java/club/premiering/permad/room/RoomManagerImpl.java
[ { "identifier": "PermaConfig", "path": "src/main/java/club/premiering/permad/PermaConfig.java", "snippet": "@NoArgsConstructor\npublic class PermaConfig {\n public String mongoAddress;\n public boolean debugMode;\n public PermaGlobalMap[] globalMaps;\n}" }, { "identifier": "PermaGlobalM...
import club.premiering.permad.PermaConfig; import club.premiering.permad.PermaGlobalMap; import club.premiering.permad.PermaGlobals; import club.premiering.permad.PermaServer; import club.premiering.permad.networking.GameSession; import club.premiering.permad.protocol.ui.RoomListingPacketOut; import club.premiering.permad.util.FileUtils; import club.premiering.permad.util.InstanceRegistry; import club.premiering.permad.format.MapData; import club.premiering.permad.format.v2.V2MapData; import club.premiering.permad.format.v2.V2MapDataSkapConverter; import java.util.*;
4,992
package club.premiering.permad.room; public class RoomManagerImpl implements RoomManager { private static final InstanceRegistry<String, MapData> MAP_DATA_REGISTRY = new InstanceRegistry<>(); static { MAP_DATA_REGISTRY.register("v2", V2MapData.class); MAP_DATA_REGISTRY.register("sk-v2", V2MapDataSkapConverter.class); } private List<Room> availableRooms = new ArrayList<>(); private Collection<GameSession> subscribedSessions = new HashSet<>(); public RoomManagerImpl() throws Exception { for (PermaGlobalMap globalMap : PermaGlobals.CONFIG.globalMaps) { this.createRoom(new RoomData(globalMap.displayName, globalMap.format, FileUtils.loadFileData(globalMap.path))); } } @Override public Room createRoom(GameSession session, RoomData roomData) throws Exception { var room = this.createRoom(roomData); if (session.room != null) session.room.removePlayer(session); room.registerPlayer(session); return room; } @Override public Room createRoom(RoomData roomData) throws Exception { var format = MAP_DATA_REGISTRY.get(roomData.mapFormat); if (format == null) throw new IllegalArgumentException("Map format " + roomData.mapFormat + " does not exist!"); var room = new RoomImpl(roomData.roomName, MAP_DATA_REGISTRY.create(roomData.mapFormat), roomData.mapData); this.updateSubscribers(); this.availableRooms.add(room); return room; } @Override public void deleteRoom(Room room) { this.availableRooms.remove(room); this.updateSubscribers(); } @Override public void joinRoom(GameSession session, String roomName) { for (Iterator<Room> it = this.availableRooms.iterator(); it.hasNext(); ) { var room = it.next(); if (room.getRoomName().equals(roomName)) { if (session.room != null) { session.room.removePlayer(session); } room.registerPlayer(session); return; } } } @Override public void subscribe(GameSession session) { this.subscribedSessions.add(session); this.updateSubscriber(session); } @Override public void unsubscribe(GameSession session) { this.subscribedSessions.remove(session); } @Override public Collection<Room> getRooms() { return this.availableRooms; } private void updateSubscriber(GameSession session) { var packet = new RoomListingPacketOut(this.availableRooms);
package club.premiering.permad.room; public class RoomManagerImpl implements RoomManager { private static final InstanceRegistry<String, MapData> MAP_DATA_REGISTRY = new InstanceRegistry<>(); static { MAP_DATA_REGISTRY.register("v2", V2MapData.class); MAP_DATA_REGISTRY.register("sk-v2", V2MapDataSkapConverter.class); } private List<Room> availableRooms = new ArrayList<>(); private Collection<GameSession> subscribedSessions = new HashSet<>(); public RoomManagerImpl() throws Exception { for (PermaGlobalMap globalMap : PermaGlobals.CONFIG.globalMaps) { this.createRoom(new RoomData(globalMap.displayName, globalMap.format, FileUtils.loadFileData(globalMap.path))); } } @Override public Room createRoom(GameSession session, RoomData roomData) throws Exception { var room = this.createRoom(roomData); if (session.room != null) session.room.removePlayer(session); room.registerPlayer(session); return room; } @Override public Room createRoom(RoomData roomData) throws Exception { var format = MAP_DATA_REGISTRY.get(roomData.mapFormat); if (format == null) throw new IllegalArgumentException("Map format " + roomData.mapFormat + " does not exist!"); var room = new RoomImpl(roomData.roomName, MAP_DATA_REGISTRY.create(roomData.mapFormat), roomData.mapData); this.updateSubscribers(); this.availableRooms.add(room); return room; } @Override public void deleteRoom(Room room) { this.availableRooms.remove(room); this.updateSubscribers(); } @Override public void joinRoom(GameSession session, String roomName) { for (Iterator<Room> it = this.availableRooms.iterator(); it.hasNext(); ) { var room = it.next(); if (room.getRoomName().equals(roomName)) { if (session.room != null) { session.room.removePlayer(session); } room.registerPlayer(session); return; } } } @Override public void subscribe(GameSession session) { this.subscribedSessions.add(session); this.updateSubscriber(session); } @Override public void unsubscribe(GameSession session) { this.subscribedSessions.remove(session); } @Override public Collection<Room> getRooms() { return this.availableRooms; } private void updateSubscriber(GameSession session) { var packet = new RoomListingPacketOut(this.availableRooms);
PermaServer.getServer().getNetworkServer().sendAsync(session, packet);
3
2023-12-20 03:13:05+00:00
8k
VRavindu/layered-architecture-Vimukthi-Ravindu
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "CustomerDAO", "path": "src/main/java/com/example/layeredarchitecture/dao/custom/CustomerDAO.java", "snippet": "public interface CustomerDAO extends CrudDAO<CustomerDTO> {\n /*ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException;\n\n boolean saveCusto...
import com.example.layeredarchitecture.dao.custom.CustomerDAO; import com.example.layeredarchitecture.dao.custom.ItemDAO; import com.example.layeredarchitecture.dao.custom.OrderDAO; import com.example.layeredarchitecture.dao.custom.OrderDetailsDAO; import com.example.layeredarchitecture.dao.custom.impl.CustomerDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.ItemDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.OrderDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.OrderDetailsDAOimpl; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.model.CustomerDTO; import com.example.layeredarchitecture.model.ItemDTO; import com.example.layeredarchitecture.model.OrderDetailDTO; import com.example.layeredarchitecture.view.tdm.OrderDetailTM; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
3,871
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; CustomerDAO customerDAO = new CustomerDAOimpl();
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; CustomerDAO customerDAO = new CustomerDAOimpl();
ItemDAO itemDAO = new ItemDAOimpl();
5
2023-12-16 04:19:18+00:00
8k
egisac/ethicalvoting
src/main/java/net/egis/ethicalvoting/commands/EthicalVotingCommand.java
[ { "identifier": "EthicalVoting", "path": "src/main/java/net/egis/ethicalvoting/EthicalVoting.java", "snippet": "@Getter\npublic final class EthicalVoting extends JavaPlugin {\n\n @Getter\n private static EthicalVoting self;\n\n private StorageInterface storage;\n private ProfileManager profi...
import net.egis.ethicalvoting.EthicalVoting; import net.egis.ethicalvoting.data.player.EthicalProfile; import net.egis.ethicalvoting.inventories.LeaderboardInventory; import net.egis.ethicalvoting.lists.PagedList; import net.egis.ethicalvoting.utils.Translate; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List;
3,632
package net.egis.ethicalvoting.commands; public class EthicalVotingCommand implements CommandExecutor, TabCompleter { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { //If first arg equals leaderboard, then show leaderboard - add null checks where appropriate END if (args.length == 0) { List<String> message = Translate.translate(EthicalVoting.getSelf().getConfig().getStringList("messages.help")); message.forEach(sender::sendMessage); return false; } if (!(sender instanceof Player)) { sender.sendMessage("§cYou must be a player to use this command."); return false; } Player player = (Player) sender; //If first arg equals leaderboard, then show leaderboard - add null checks where appropriate START String arg = args[0]; if (arg.equalsIgnoreCase("leaderboard") || arg.equalsIgnoreCase("top")) { boolean useGui = EthicalVoting.getSelf().getConfig().getBoolean("leaderboard.use_gui"); //Show leaderboard if (useGui) { if (args.length != 2) { LeaderboardInventory leaderboardInventory = new LeaderboardInventory(player, "leaderboard", "Leaderboard", 3, 0); leaderboardInventory.open(); } else { Integer n = silentParse(args[1]); if (n == null) { player.sendMessage("§cUsage: /vote leaderboard <page>"); return false; } LeaderboardInventory leaderboardInventory = new LeaderboardInventory(player, "leaderboard", "Leaderboard", 3, n); leaderboardInventory.open(); } } else {
package net.egis.ethicalvoting.commands; public class EthicalVotingCommand implements CommandExecutor, TabCompleter { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { //If first arg equals leaderboard, then show leaderboard - add null checks where appropriate END if (args.length == 0) { List<String> message = Translate.translate(EthicalVoting.getSelf().getConfig().getStringList("messages.help")); message.forEach(sender::sendMessage); return false; } if (!(sender instanceof Player)) { sender.sendMessage("§cYou must be a player to use this command."); return false; } Player player = (Player) sender; //If first arg equals leaderboard, then show leaderboard - add null checks where appropriate START String arg = args[0]; if (arg.equalsIgnoreCase("leaderboard") || arg.equalsIgnoreCase("top")) { boolean useGui = EthicalVoting.getSelf().getConfig().getBoolean("leaderboard.use_gui"); //Show leaderboard if (useGui) { if (args.length != 2) { LeaderboardInventory leaderboardInventory = new LeaderboardInventory(player, "leaderboard", "Leaderboard", 3, 0); leaderboardInventory.open(); } else { Integer n = silentParse(args[1]); if (n == null) { player.sendMessage("§cUsage: /vote leaderboard <page>"); return false; } LeaderboardInventory leaderboardInventory = new LeaderboardInventory(player, "leaderboard", "Leaderboard", 3, n); leaderboardInventory.open(); } } else {
PagedList leaderboard = EthicalVoting.getSelf().getProfiles().getPaged();
3
2023-12-15 16:48:38+00:00
8k
SAMJ-CSDC26BB/samj-javafx
samj/src/main/java/com/samj/Application.java
[ { "identifier": "Server", "path": "samj/src/main/java/com/samj/backend/Server.java", "snippet": "public class Server {\n public static List<String> list_features = Arrays.asList(\"forwardcheck\");\n private Database db;\n\n private int port;\n private HttpServer webServer;\n\n public Serv...
import com.samj.backend.Server; import com.samj.frontend.AuthenticationService; import com.samj.frontend.MainTable; import com.samj.shared.CallForwardingDTO; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import java.awt.*; import java.time.LocalDateTime;
4,037
package com.samj; public class Application extends javafx.application.Application { public void start(Stage primaryStage) { primaryStage.setTitle("SAMJ Login"); // Create the layout GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setVgap(10); grid.setHgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); //Label CapsLock Label capsLockLabel = new Label("Caps Lock is ON"); capsLockLabel.setVisible(false); // Initially hidden // Create the components Label userName = new Label("User: "); grid.add(userName, 0, 0); TextField userTextField = new TextField(); grid.add(userTextField, 1, 0); Label pw = new Label("Password:"); grid.add(pw, 0, 1); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 1); Button btn = new Button("Sign in"); btn.setDefaultButton(true); grid.add(btn, 1, 2); final Text actionTarget = new Text(); grid.add(actionTarget, 1, 6); // Add event handling (simple example) AuthenticationService authService = new AuthenticationService(); btn.setOnAction(e -> { String username = userTextField.getText(); String password = pwBox.getText(); if (authService.authenticate(username, password)) { actionTarget.setText("Login successful."); // Proceed to next view or functionality _setMainSceneAfterLogin(primaryStage); } else { actionTarget.setText("Login failed."); } }); pwBox.setOnKeyReleased(event -> { boolean isCapsOn = Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); capsLockLabel.setVisible(isCapsOn); }); userTextField.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); pwBox.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); Scene scene = new Scene(grid, 300, 275); primaryStage.setScene(scene); primaryStage.show(); } /** * Method responsible for setting the scene after login. The scene contains a table with CallForwardingDTOs. * * @param primaryStage - the stage where the new scene is set */ private void _setMainSceneAfterLogin(Stage primaryStage) { ObservableList<CallForwardingDTO> tableData = _getTableData();
package com.samj; public class Application extends javafx.application.Application { public void start(Stage primaryStage) { primaryStage.setTitle("SAMJ Login"); // Create the layout GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setVgap(10); grid.setHgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); //Label CapsLock Label capsLockLabel = new Label("Caps Lock is ON"); capsLockLabel.setVisible(false); // Initially hidden // Create the components Label userName = new Label("User: "); grid.add(userName, 0, 0); TextField userTextField = new TextField(); grid.add(userTextField, 1, 0); Label pw = new Label("Password:"); grid.add(pw, 0, 1); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 1); Button btn = new Button("Sign in"); btn.setDefaultButton(true); grid.add(btn, 1, 2); final Text actionTarget = new Text(); grid.add(actionTarget, 1, 6); // Add event handling (simple example) AuthenticationService authService = new AuthenticationService(); btn.setOnAction(e -> { String username = userTextField.getText(); String password = pwBox.getText(); if (authService.authenticate(username, password)) { actionTarget.setText("Login successful."); // Proceed to next view or functionality _setMainSceneAfterLogin(primaryStage); } else { actionTarget.setText("Login failed."); } }); pwBox.setOnKeyReleased(event -> { boolean isCapsOn = Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); capsLockLabel.setVisible(isCapsOn); }); userTextField.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); pwBox.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); Scene scene = new Scene(grid, 300, 275); primaryStage.setScene(scene); primaryStage.show(); } /** * Method responsible for setting the scene after login. The scene contains a table with CallForwardingDTOs. * * @param primaryStage - the stage where the new scene is set */ private void _setMainSceneAfterLogin(Stage primaryStage) { ObservableList<CallForwardingDTO> tableData = _getTableData();
MainTable mainTable = new MainTable(tableData);
2
2023-12-18 09:42:06+00:00
8k
jollyboss123/astra
modules/heimdall/src/test/java/com/jolly/heimdall/ConfigurableJwtGrantedAuthoritiesConverterTest.java
[ { "identifier": "OpenIdClaimSet", "path": "modules/heimdall/src/main/java/com/jolly/heimdall/claimset/OpenIdClaimSet.java", "snippet": "public class OpenIdClaimSet extends UnmodifiableClaimSet implements IdTokenClaimAccessor, Principal {\n @Serial\n private static final long serialVersionUID = 4908273...
import com.jolly.heimdall.claimset.OpenIdClaimSet; import com.jolly.heimdall.properties.HeimdallOidcProperties; import com.jolly.heimdall.properties.OpenIdProviderProperties; import com.jolly.heimdall.properties.SimpleAuthoritiesMappingProperties; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtClaimNames; import java.net.URI; import java.net.URISyntaxException; import java.time.Instant; import java.util.List; import java.util.Map; import static com.jolly.heimdall.properties.SimpleAuthoritiesMappingProperties.*; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
3,621
package com.jolly.heimdall; /** * @author jolly */ class ConfigurableJwtGrantedAuthoritiesConverterTest { @Test void test() throws URISyntaxException { final URI issuer = new URI("https://authorization-server"); final List<String> client1Roles = List.of("R11", "r12"); final List<String> client2Roles = List.of("R21", "r22"); final List<String> client3Roles = List.of("R31", "r32"); final List<String> realmRoles = List.of("r1", "r2"); final Map<String, Object> claims = Map.of( JwtClaimNames.ISS, issuer, "resource_access", Map.of( "client1", Map.of("roles", client1Roles), "client2", Map.of("roles", String.join(", ", client2Roles)), "client3", Map.of("roles", String.join(" ", client3Roles)) ), "realm_access", Map.of("roles", realmRoles) ); final Instant now = Instant.now(); final Jwt jwt = new Jwt("a.b.C", now, Instant.ofEpochSecond(now.getEpochSecond() + 3600), Map.of("machin", "truc"), claims); final OpenIdProviderProperties issuerProps = mock(OpenIdProviderProperties.class); issuerProps.setIss(issuer); final HeimdallOidcProperties props = mock(HeimdallOidcProperties.class); when(props.getOpProperties(issuer)).thenReturn(issuerProps); final ConfigurableClaimSetAuthoritiesConverter converter = new ConfigurableClaimSetAuthoritiesConverter(props); final OpenIdClaimSet claimSet = new OpenIdClaimSet(jwt.getClaims()); // assert mapping with default properties final List<String> expectedDefault = List.of("r1", "r2"); boolean defaultContains = converter.convert(claimSet).stream() .map(GrantedAuthority::getAuthority) .allMatch(expectedDefault::contains); assertTrue(defaultContains); // assert with prefix and case processing when(issuerProps.getAuthorities()) .thenReturn( List.of( configureSimpleAuthorities("$.realm_access.roles", "MACHIN_", Case.UNCHANGED), configureSimpleAuthorities("resource_access.client1.roles", "TRUC_", Case.LOWER), configureSimpleAuthorities("resource_access.client3.roles", "CHOSE_", Case.UPPER) ) ); final List<String> expected = List.of("TRUC_r11", "TRUC_r12", "CHOSE_R31", "CHOSE_R32", "MACHIN_r1", "MACHIN_r2"); boolean contains = converter.convert(claimSet).stream() .map(GrantedAuthority::getAuthority) .allMatch(expected::contains); assertTrue(contains); }
package com.jolly.heimdall; /** * @author jolly */ class ConfigurableJwtGrantedAuthoritiesConverterTest { @Test void test() throws URISyntaxException { final URI issuer = new URI("https://authorization-server"); final List<String> client1Roles = List.of("R11", "r12"); final List<String> client2Roles = List.of("R21", "r22"); final List<String> client3Roles = List.of("R31", "r32"); final List<String> realmRoles = List.of("r1", "r2"); final Map<String, Object> claims = Map.of( JwtClaimNames.ISS, issuer, "resource_access", Map.of( "client1", Map.of("roles", client1Roles), "client2", Map.of("roles", String.join(", ", client2Roles)), "client3", Map.of("roles", String.join(" ", client3Roles)) ), "realm_access", Map.of("roles", realmRoles) ); final Instant now = Instant.now(); final Jwt jwt = new Jwt("a.b.C", now, Instant.ofEpochSecond(now.getEpochSecond() + 3600), Map.of("machin", "truc"), claims); final OpenIdProviderProperties issuerProps = mock(OpenIdProviderProperties.class); issuerProps.setIss(issuer); final HeimdallOidcProperties props = mock(HeimdallOidcProperties.class); when(props.getOpProperties(issuer)).thenReturn(issuerProps); final ConfigurableClaimSetAuthoritiesConverter converter = new ConfigurableClaimSetAuthoritiesConverter(props); final OpenIdClaimSet claimSet = new OpenIdClaimSet(jwt.getClaims()); // assert mapping with default properties final List<String> expectedDefault = List.of("r1", "r2"); boolean defaultContains = converter.convert(claimSet).stream() .map(GrantedAuthority::getAuthority) .allMatch(expectedDefault::contains); assertTrue(defaultContains); // assert with prefix and case processing when(issuerProps.getAuthorities()) .thenReturn( List.of( configureSimpleAuthorities("$.realm_access.roles", "MACHIN_", Case.UNCHANGED), configureSimpleAuthorities("resource_access.client1.roles", "TRUC_", Case.LOWER), configureSimpleAuthorities("resource_access.client3.roles", "CHOSE_", Case.UPPER) ) ); final List<String> expected = List.of("TRUC_r11", "TRUC_r12", "CHOSE_R31", "CHOSE_R32", "MACHIN_r1", "MACHIN_r2"); boolean contains = converter.convert(claimSet).stream() .map(GrantedAuthority::getAuthority) .allMatch(expected::contains); assertTrue(contains); }
private static SimpleAuthoritiesMappingProperties configureSimpleAuthorities(String jsonPath, String prefix, Case caseProcessing) {
4
2023-12-17 05:24:05+00:00
8k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/AccountContentProvider.java
[ { "identifier": "PackageUtils", "path": "play-services-base/core/src/main/java/org/microg/gms/common/PackageUtils.java", "snippet": "public class PackageUtils {\n\n private static final String GOOGLE_PLATFORM_KEY = GMS_PACKAGE_SIGNATURE_SHA1;\n private static final String GOOGLE_PLATFORM_KEY_2 = G...
import static android.accounts.AccountManager.VISIBILITY_VISIBLE; import android.Manifest; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentProvider; import android.content.ContentValues; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.util.Log; import androidx.annotation.Nullable; import org.microg.gms.common.PackageUtils; import java.util.Arrays; import static android.os.Build.VERSION.SDK_INT; import static org.microg.gms.auth.AuthConstants.DEFAULT_ACCOUNT_TYPE; import static org.microg.gms.auth.AuthConstants.PROVIDER_EXTRA_ACCOUNTS; import static org.microg.gms.auth.AuthConstants.PROVIDER_EXTRA_CLEAR_PASSWORD; import static org.microg.gms.auth.AuthConstants.PROVIDER_METHOD_CLEAR_PASSWORD; import static org.microg.gms.auth.AuthConstants.PROVIDER_METHOD_GET_ACCOUNTS;
4,806
/* * 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; public class AccountContentProvider extends ContentProvider { private static final String TAG = "GmsAuthProvider"; @Override public boolean onCreate() { return true; } @Nullable @Override public Bundle call(String method, String arg, Bundle extras) { String suggestedPackageName = null; if (SDK_INT > 19) { suggestedPackageName = getCallingPackage(); }
/* * 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; public class AccountContentProvider extends ContentProvider { private static final String TAG = "GmsAuthProvider"; @Override public boolean onCreate() { return true; } @Nullable @Override public Bundle call(String method, String arg, Bundle extras) { String suggestedPackageName = null; if (SDK_INT > 19) { suggestedPackageName = getCallingPackage(); }
String packageName = PackageUtils.getAndCheckCallingPackage(getContext(), suggestedPackageName);
0
2023-12-17 16:14:53+00:00
8k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/FinalAutoLeft1.java
[ { "identifier": "SampleMecanumDrive", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java", "snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n publi...
import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.TouchSensor; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.openftc.apriltag.AprilTagDetection; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import java.util.ArrayList;
4,248
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class FinalAutoLeft1 extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 46.5; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; Pose2d myPose = new Pose2d(-36, -60, Math.toRadians(-90)); Pose2d startPose = new Pose2d(-36, -60, Math.toRadians(90)); Pose2d EndPose = new Pose2d(-38.6, -18, Math.toRadians(172)); // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); camera.setPipeline(aprilTagDetectionPipeline); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double ArmIntoCone = 0.17; double ArmIntake = 1; double ArmSecondFloor = 0.91; double ArmThirdfloor = 0.84; double ArmForthFloor = 0.79; double ArmThithFloor = 0.76; double Angle = 0.4; double ClawPos = 0.65; camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); }
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class FinalAutoLeft1 extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 46.5; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; Pose2d myPose = new Pose2d(-36, -60, Math.toRadians(-90)); Pose2d startPose = new Pose2d(-36, -60, Math.toRadians(90)); Pose2d EndPose = new Pose2d(-38.6, -18, Math.toRadians(172)); // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); camera.setPipeline(aprilTagDetectionPipeline); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double ArmIntoCone = 0.17; double ArmIntake = 1; double ArmSecondFloor = 0.91; double ArmThirdfloor = 0.84; double ArmForthFloor = 0.79; double ArmThithFloor = 0.76; double Angle = 0.4; double ClawPos = 0.65; camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); }
SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
0
2023-12-15 16:57:19+00:00
8k
Dhananjay-mygithubcode/CRM-PROJECT
src/main/java/com/inn/cafe/serviceImpl/productServiceImpl.java
[ { "identifier": "CustomerUserDetailsService", "path": "src/main/java/com/inn/cafe/JWT/CustomerUserDetailsService.java", "snippet": "@Slf4j\n@Service\npublic class CustomerUserDetailsService implements UserDetailsService {\n\n @Autowired\n UserDao userDao;\n\n private com.inn.cafe.POJO.User user...
import com.google.common.base.Strings; import com.inn.cafe.JWT.CustomerUserDetailsService; import com.inn.cafe.JWT.JwtFilter; import com.inn.cafe.POJO.Category; import com.inn.cafe.POJO.Product; import com.inn.cafe.constents.CafeConstants; import com.inn.cafe.dao.CategoryDao; import com.inn.cafe.dao.productDao; import com.inn.cafe.service.productService; import com.inn.cafe.utils.CafeUtils; import com.inn.cafe.utils.EmailUtil; import com.inn.cafe.wrapper.ProductWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.Modifying; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional;
4,253
} catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<List<ProductWrapper>> getAllProduct() { try { return new ResponseEntity<>(productDao.getAllProduct(), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ArrayList<>(), HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> update(Map<String, String> requestMap) { try { if (jwtFilter.isAdmin()) { if (validateProductMap(requestMap, true)) { Optional optional = productDao.findById(Integer.parseInt(requestMap.get("id"))); if (optional.isPresent()) { productDao.save(getProductFromMap(requestMap, true)); return CafeUtils.getResponeEntity("Product is updated successfully", HttpStatus.OK); } else { return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } } return CafeUtils.getResponeEntity(CafeConstants.INVALID_DATA, HttpStatus.BAD_REQUEST); } else { return CafeUtils.getResponeEntity(CafeConstants.UNAUTHORIZED_ACCESS, HttpStatus.UNAUTHORIZED); } } catch (Exception ex) { ex.printStackTrace(); } return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> delete(Integer id) { try { if (jwtFilter.isAdmin()) { Optional optional = productDao.findById(id); if (optional.isPresent()) { productDao.deleteById(id); //System.out.println("Product is deleted successfully"); return CafeUtils.getResponeEntity("Product is deleted successfully", HttpStatus.OK); } //System.out.println("Product id doesn't exist"); return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } else { return CafeUtils.getResponeEntity(CafeConstants.UNAUTHORIZED_ACCESS, HttpStatus.UNAUTHORIZED); } } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<List<ProductWrapper>> getByCategory(Integer id) { try { return new ResponseEntity<>(productDao.getByCategory(id), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ArrayList<>(), HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<ProductWrapper> getProductById(Integer id) { try { return new ResponseEntity<>(productDao.getProductById(id), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ProductWrapper(), HttpStatus.INTERNAL_SERVER_ERROR); } @Modifying @Transactional @Override public ResponseEntity<String> updateProductStatus(Map<String, String> requestMap) { try { if (jwtFilter.isAdmin()) { Optional optional = productDao.findById(Integer.parseInt(requestMap.get("id"))); if (optional.isPresent()) { productDao.updateProductStatus(requestMap.get("status"), Integer.parseInt(requestMap.get("id"))); return CafeUtils.getResponeEntity("Product status is updated successfully", HttpStatus.OK); } return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } } catch (Exception ex) { ex.printStackTrace(); } return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } private boolean validateProductMap(Map<String, String> requestMap, boolean validateId) { if (requestMap.containsKey("name")) { if (requestMap.containsKey("id") && validateId) { return true; } else if (!validateId) { return true; } } return false; } private Product getProductFromMap(Map<String, String> requestMap, boolean isAdd) { Product product = new Product();
package com.inn.cafe.serviceImpl; @Slf4j @Service public class productServiceImpl implements productService { @Autowired productDao productDao; @Autowired AuthenticationManager authenticationManager; @Autowired com.inn.cafe.JWT.jwtUtil jwtUtil; @Autowired JwtFilter jwtFilter; @Autowired CustomerUserDetailsService customerUserDetailsService; @Autowired EmailUtil emailUtil; @Override public ResponseEntity<String> addNewProduct(Map<String, String> requestMap) { log.info("Inside addNewProduct{}", requestMap); try { if (jwtFilter.isAdmin()) { if (validateProductMap(requestMap, false)) { productDao.save(getProductFromMap(requestMap, false)); return CafeUtils.getResponeEntity("Product Added Successfully", HttpStatus.OK); } } else { return CafeUtils.getResponeEntity(CafeConstants.UNAUTHORIZED_ACCESS, HttpStatus.UNAUTHORIZED); } } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<List<ProductWrapper>> getAllProduct() { try { return new ResponseEntity<>(productDao.getAllProduct(), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ArrayList<>(), HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> update(Map<String, String> requestMap) { try { if (jwtFilter.isAdmin()) { if (validateProductMap(requestMap, true)) { Optional optional = productDao.findById(Integer.parseInt(requestMap.get("id"))); if (optional.isPresent()) { productDao.save(getProductFromMap(requestMap, true)); return CafeUtils.getResponeEntity("Product is updated successfully", HttpStatus.OK); } else { return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } } return CafeUtils.getResponeEntity(CafeConstants.INVALID_DATA, HttpStatus.BAD_REQUEST); } else { return CafeUtils.getResponeEntity(CafeConstants.UNAUTHORIZED_ACCESS, HttpStatus.UNAUTHORIZED); } } catch (Exception ex) { ex.printStackTrace(); } return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> delete(Integer id) { try { if (jwtFilter.isAdmin()) { Optional optional = productDao.findById(id); if (optional.isPresent()) { productDao.deleteById(id); //System.out.println("Product is deleted successfully"); return CafeUtils.getResponeEntity("Product is deleted successfully", HttpStatus.OK); } //System.out.println("Product id doesn't exist"); return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } else { return CafeUtils.getResponeEntity(CafeConstants.UNAUTHORIZED_ACCESS, HttpStatus.UNAUTHORIZED); } } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<List<ProductWrapper>> getByCategory(Integer id) { try { return new ResponseEntity<>(productDao.getByCategory(id), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ArrayList<>(), HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<ProductWrapper> getProductById(Integer id) { try { return new ResponseEntity<>(productDao.getProductById(id), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); } return new ResponseEntity<>(new ProductWrapper(), HttpStatus.INTERNAL_SERVER_ERROR); } @Modifying @Transactional @Override public ResponseEntity<String> updateProductStatus(Map<String, String> requestMap) { try { if (jwtFilter.isAdmin()) { Optional optional = productDao.findById(Integer.parseInt(requestMap.get("id"))); if (optional.isPresent()) { productDao.updateProductStatus(requestMap.get("status"), Integer.parseInt(requestMap.get("id"))); return CafeUtils.getResponeEntity("Product status is updated successfully", HttpStatus.OK); } return CafeUtils.getResponeEntity("Product id doesn't exist", HttpStatus.OK); } } catch (Exception ex) { ex.printStackTrace(); } return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } private boolean validateProductMap(Map<String, String> requestMap, boolean validateId) { if (requestMap.containsKey("name")) { if (requestMap.containsKey("id") && validateId) { return true; } else if (!validateId) { return true; } } return false; } private Product getProductFromMap(Map<String, String> requestMap, boolean isAdd) { Product product = new Product();
Category category = new Category();
2
2023-12-20 11:47:58+00:00
8k
TheEpicBlock/FLUIwID
src/main/java/nl/theepicblock/fluiwid/packet/UpdateC2SDataPacket.java
[ { "identifier": "FishyBusiness", "path": "src/main/java/nl/theepicblock/fluiwid/FishyBusiness.java", "snippet": "public class FishyBusiness {\n public final static float DELTA_T = 1/20f;\n public final static float DROPLET_SIZE = 1/16f;\n public final static float GRAVITY = 2f*DELTA_T;\n pub...
import net.fabricmc.fabric.api.networking.v1.FabricPacket; import net.fabricmc.fabric.api.networking.v1.PacketType; import net.minecraft.network.PacketByteBuf; import net.minecraft.util.math.Vec3d; import nl.theepicblock.fluiwid.FishyBusiness; import nl.theepicblock.fluiwid.Fluiwid; import org.jetbrains.annotations.NotNull; import org.joml.Vector3f; import java.util.ArrayList;
4,413
package nl.theepicblock.fluiwid.packet; public record UpdateC2SDataPacket(Vec3d cam, ArrayList<Vector3f> offsets) implements FabricPacket { public static PacketType<UpdateC2SDataPacket> TYPE = PacketType.create(Fluiwid.id("update"), UpdateC2SDataPacket::new); public UpdateC2SDataPacket(PacketByteBuf buf) { this(buf.readVec3d(), buf.readCollection(ArrayList::new, PacketByteBuf::readVector3f)); } @Override public void write(PacketByteBuf buf) { buf.writeVec3d(cam); buf.writeCollection(this.offsets, PacketByteBuf::writeVector3f); }
package nl.theepicblock.fluiwid.packet; public record UpdateC2SDataPacket(Vec3d cam, ArrayList<Vector3f> offsets) implements FabricPacket { public static PacketType<UpdateC2SDataPacket> TYPE = PacketType.create(Fluiwid.id("update"), UpdateC2SDataPacket::new); public UpdateC2SDataPacket(PacketByteBuf buf) { this(buf.readVec3d(), buf.readCollection(ArrayList::new, PacketByteBuf::readVector3f)); } @Override public void write(PacketByteBuf buf) { buf.writeVec3d(cam); buf.writeCollection(this.offsets, PacketByteBuf::writeVector3f); }
public void apply(@NotNull FishyBusiness data) {
0
2023-12-18 12:05:13+00:00
8k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/net/NetworkHandler.java
[ { "identifier": "PacketType", "path": "src/com/mojang/minecraft/net/PacketType.java", "snippet": "public final class PacketType {\r\n\r\n public static final PacketType[] packets = new PacketType[256];\r\n public static final PacketType INDENTIFICATION = new PacketType(new Class[]{Byte.TYPE, String....
import com.mojang.minecraft.net.PacketType; import com.mojang.minecraft.server.NetworkManager; import net.io.DummyLogger; import net.io.WebSocketChannel; import java.nio.ByteBuffer; import java.util.Arrays; import org.eclipse.jetty.util.log.Log;
6,209
package com.mojang.net; public final class NetworkHandler { public volatile boolean connected; public ByteBuffer in = ByteBuffer.allocate(1048576); public ByteBuffer out = ByteBuffer.allocate(1048576); public NetworkManager networkManager; private boolean h = false; public String address; private byte[] stringBytes = new byte[64]; public static boolean gay = false; public WebSocketChannel channel; public NetworkHandler(int port) { gay = true; try { Log.setLog(new DummyLogger()); channel = new WebSocketChannel(port); } catch (Exception e) { e.printStackTrace(); throw new Error(e.getLocalizedMessage()); } } public final void close() { try { if(this.out.position() > 0) { this.out.flip(); this.channel.write(this.out); this.out.compact(); } } catch (Exception var2) { ; } this.connected = false; try { channel.stopServer(); } catch (Exception var1) { ; } }
package com.mojang.net; public final class NetworkHandler { public volatile boolean connected; public ByteBuffer in = ByteBuffer.allocate(1048576); public ByteBuffer out = ByteBuffer.allocate(1048576); public NetworkManager networkManager; private boolean h = false; public String address; private byte[] stringBytes = new byte[64]; public static boolean gay = false; public WebSocketChannel channel; public NetworkHandler(int port) { gay = true; try { Log.setLog(new DummyLogger()); channel = new WebSocketChannel(port); } catch (Exception e) { e.printStackTrace(); throw new Error(e.getLocalizedMessage()); } } public final void close() { try { if(this.out.position() > 0) { this.out.flip(); this.channel.write(this.out); this.out.compact(); } } catch (Exception var2) { ; } this.connected = false; try { channel.stopServer(); } catch (Exception var1) { ; } }
public final void send(PacketType var1, Object ... var2) {
0
2023-12-18 15:38:59+00:00
8k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/model/viaggio/Viaggio.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 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.service.CachedStopsService; import it.unipv.po.aioobe.trenissimo.model.viaggio.ricerca.utils.Connection; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoIva.IPrezzoIvaStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoIva.PrezzoIvaFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoPerDistanza.IPrezzoPerDistanzaStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoPerDistanza.PrezzoPerDistanzaFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTot.IPrezzoTotStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTot.PrezzoTotFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTotCambi.IPrezzoTotCambiStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTotCambi.PrezzoTotCambiFactory; import org.jetbrains.annotations.NotNull; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger;
6,258
package it.unipv.po.aioobe.trenissimo.model.viaggio; /** * Classe che modellizza un viaggio. * * @author ArrayIndexOutOfBoundsException */ public class Viaggio { private static final AtomicInteger count = new AtomicInteger(0); private int numAdulti; private int numRagazzi; private int numBambini; private int numAnimali; private LocalDate dataPartenza; private List<Connection> cambi; private final IPrezzoPerDistanzaStrategy prezzoPerDistanzaStrategy; private final IPrezzoTotCambiStrategy prezzoTotCambiStrategy; private final IPrezzoTotStrategy prezzoTotStrategy; private final IPrezzoIvaStrategy prezzoIvaStrategy; /** * Costruttore del viaggio. Vengono istanziate le diverse strategy per il calcolo del prezzo totale. */ public Viaggio() { PrezzoPerDistanzaFactory f = new PrezzoPerDistanzaFactory(); prezzoPerDistanzaStrategy = f.getPrezzoPerDistanzaStrategy(); PrezzoTotCambiFactory f1 = new PrezzoTotCambiFactory(); prezzoTotCambiStrategy = f1.getPrezzoTotCambiStrategy(); PrezzoTotFactory f2 = new PrezzoTotFactory(); prezzoTotStrategy = f2.getPrezzoTot(); PrezzoIvaFactory f3 = new PrezzoIvaFactory(); prezzoIvaStrategy = f3.getPrezzoIvaStrategy(); } public int getNumAdulti() { return numAdulti; } public void setNumAdulti(int numAdulti) { this.numAdulti = numAdulti; } public int getNumRagazzi() { return numRagazzi; } public void setNumRagazzi(int numRagazzi) { this.numRagazzi = numRagazzi; } public int getNumBambini() { return numBambini; } public void setNumBambini(int numBambini) { this.numBambini = numBambini; } public int getNumAnimali() { return numAnimali; } public void setNumAnimali(int numAnimali) { this.numAnimali = numAnimali; } public LocalDate getDataPartenza() { return dataPartenza; } public void setDataPartenza(LocalDate dataPartenza) { this.dataPartenza = dataPartenza; } public List<Connection> getCambi() { return cambi; } public void setCambi(List<Connection> cambi) { this.cambi = cambi; } /** * Metodo per ottenere la stazione di partenza dalla classe CachedStopsService * * @return StopsEntity */ public StopsEntity getStazionePartenza() {
package it.unipv.po.aioobe.trenissimo.model.viaggio; /** * Classe che modellizza un viaggio. * * @author ArrayIndexOutOfBoundsException */ public class Viaggio { private static final AtomicInteger count = new AtomicInteger(0); private int numAdulti; private int numRagazzi; private int numBambini; private int numAnimali; private LocalDate dataPartenza; private List<Connection> cambi; private final IPrezzoPerDistanzaStrategy prezzoPerDistanzaStrategy; private final IPrezzoTotCambiStrategy prezzoTotCambiStrategy; private final IPrezzoTotStrategy prezzoTotStrategy; private final IPrezzoIvaStrategy prezzoIvaStrategy; /** * Costruttore del viaggio. Vengono istanziate le diverse strategy per il calcolo del prezzo totale. */ public Viaggio() { PrezzoPerDistanzaFactory f = new PrezzoPerDistanzaFactory(); prezzoPerDistanzaStrategy = f.getPrezzoPerDistanzaStrategy(); PrezzoTotCambiFactory f1 = new PrezzoTotCambiFactory(); prezzoTotCambiStrategy = f1.getPrezzoTotCambiStrategy(); PrezzoTotFactory f2 = new PrezzoTotFactory(); prezzoTotStrategy = f2.getPrezzoTot(); PrezzoIvaFactory f3 = new PrezzoIvaFactory(); prezzoIvaStrategy = f3.getPrezzoIvaStrategy(); } public int getNumAdulti() { return numAdulti; } public void setNumAdulti(int numAdulti) { this.numAdulti = numAdulti; } public int getNumRagazzi() { return numRagazzi; } public void setNumRagazzi(int numRagazzi) { this.numRagazzi = numRagazzi; } public int getNumBambini() { return numBambini; } public void setNumBambini(int numBambini) { this.numBambini = numBambini; } public int getNumAnimali() { return numAnimali; } public void setNumAnimali(int numAnimali) { this.numAnimali = numAnimali; } public LocalDate getDataPartenza() { return dataPartenza; } public void setDataPartenza(LocalDate dataPartenza) { this.dataPartenza = dataPartenza; } public List<Connection> getCambi() { return cambi; } public void setCambi(List<Connection> cambi) { this.cambi = cambi; } /** * Metodo per ottenere la stazione di partenza dalla classe CachedStopsService * * @return StopsEntity */ public StopsEntity getStazionePartenza() {
return CachedStopsService.getInstance().findAll().stream().filter(x -> x.getStopId() == (cambi.get(0).getDepartureStation())).findFirst().get();
2
2023-12-21 10:41:11+00:00
8k
chulakasam/layered
src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory boFactory;\n private BOFactory(){\n\n }\n public static BOFactory getBOFactory(){\n return (boFactory==null) ? boFact...
import com.example.layeredarchitecture.bo.BOFactory; import com.example.layeredarchitecture.bo.ItemBO; import com.example.layeredarchitecture.bo.ItemBOImpl; import com.example.layeredarchitecture.dao.custom.Impl.ItemDAO; import com.example.layeredarchitecture.dao.custom.ItemDao; import com.example.layeredarchitecture.model.ItemDTO; import com.example.layeredarchitecture.view.tdm.ItemTM; import com.jfoenix.controls.JFXButton; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.util.ArrayList;
4,394
package com.example.layeredarchitecture.controller; public class ManageItemsFormController { public AnchorPane root; public TextField txtCode; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnDelete; public JFXButton btnSave; public TableView<ItemTM> tblItems; public TextField txtUnitPrice; public JFXButton btnAddNewItem; //ItemDao itemDAO = new ItemDAO(); ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.ITEM); public void initialize() { tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand")); tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); initUI(); tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { btnDelete.setDisable(newValue == null); btnSave.setText(newValue != null ? "Update" : "Save"); btnSave.setDisable(newValue == null); if (newValue != null) { txtCode.setText(newValue.getCode()); txtDescription.setText(newValue.getDescription()); txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString()); txtQtyOnHand.setText(newValue.getQtyOnHand() + ""); txtCode.setDisable(false); txtDescription.setDisable(false); txtUnitPrice.setDisable(false); txtQtyOnHand.setDisable(false); } }); txtQtyOnHand.setOnAction(event -> btnSave.fire()); loadAllItems(); } private void loadAllItems() { tblItems.getItems().clear(); try { /*Get all items*/ ArrayList<ItemDTO> allitem = itemBO.getAllItems(); for(ItemDTO dto: allitem){ tblItems.getItems().add(new ItemTM(dto.getCode(),dto.getDescription(),dto.getUnitPrice(),dto.getQtyOnHand())); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void initUI() { txtCode.clear(); txtDescription.clear(); txtUnitPrice.clear(); txtQtyOnHand.clear(); txtCode.setDisable(true); txtDescription.setDisable(true); txtUnitPrice.setDisable(true); txtQtyOnHand.setDisable(true); txtCode.setEditable(false); btnSave.setDisable(true); btnDelete.setDisable(true); } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAddNew_OnAction(ActionEvent actionEvent) { txtCode.setDisable(false); txtDescription.setDisable(false); txtUnitPrice.setDisable(false); txtQtyOnHand.setDisable(false); txtCode.clear(); txtCode.setText(generateNewId()); txtDescription.clear(); txtUnitPrice.clear(); txtQtyOnHand.clear(); txtDescription.requestFocus(); btnSave.setDisable(false); btnSave.setText("Save"); tblItems.getSelectionModel().clearSelection(); } public void btnDelete_OnAction(ActionEvent actionEvent) { /*Delete Item*/ String code = tblItems.getSelectionModel().getSelectedItem().getCode(); try { ItemBOImpl itemBO = new ItemBOImpl(); if (!itemBO.existItem(code)) { new Alert(Alert.AlertType.ERROR, "There is no such item associated with the id " + code).show(); } boolean isDeleted=itemBO.deleteItem(code); if(isDeleted){ tblItems.getItems().remove(tblItems.getSelectionModel().getSelectedItem()); tblItems.getSelectionModel().clearSelection(); initUI(); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to delete the item " + code).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void btnSave_OnAction(ActionEvent actionEvent) { String code = txtCode.getText(); String description = txtDescription.getText(); if (!description.matches("[A-Za-z0-9 ]+")) { new Alert(Alert.AlertType.ERROR, "Invalid description").show(); txtDescription.requestFocus(); return; } else if (!txtUnitPrice.getText().matches("^[0-9]+[.]?[0-9]*$")) { new Alert(Alert.AlertType.ERROR, "Invalid unit price").show(); txtUnitPrice.requestFocus(); return; } else if (!txtQtyOnHand.getText().matches("^\\d+$")) { new Alert(Alert.AlertType.ERROR, "Invalid qty on hand").show(); txtQtyOnHand.requestFocus(); return; } int qtyOnHand = Integer.parseInt(txtQtyOnHand.getText()); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); if (btnSave.getText().equalsIgnoreCase("save")) { try { if (itemBO.existItem(code)) { new Alert(Alert.AlertType.ERROR, code + " already exists").show(); } //Save Item ItemDTO dto = new ItemDTO(code, description, unitPrice, qtyOnHand); boolean isSaved=itemBO.SaveItem(dto); if(isSaved){ tblItems.getItems().add(new ItemTM(code, description, unitPrice, qtyOnHand)); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { try {
package com.example.layeredarchitecture.controller; public class ManageItemsFormController { public AnchorPane root; public TextField txtCode; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnDelete; public JFXButton btnSave; public TableView<ItemTM> tblItems; public TextField txtUnitPrice; public JFXButton btnAddNewItem; //ItemDao itemDAO = new ItemDAO(); ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.ITEM); public void initialize() { tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand")); tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); initUI(); tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { btnDelete.setDisable(newValue == null); btnSave.setText(newValue != null ? "Update" : "Save"); btnSave.setDisable(newValue == null); if (newValue != null) { txtCode.setText(newValue.getCode()); txtDescription.setText(newValue.getDescription()); txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString()); txtQtyOnHand.setText(newValue.getQtyOnHand() + ""); txtCode.setDisable(false); txtDescription.setDisable(false); txtUnitPrice.setDisable(false); txtQtyOnHand.setDisable(false); } }); txtQtyOnHand.setOnAction(event -> btnSave.fire()); loadAllItems(); } private void loadAllItems() { tblItems.getItems().clear(); try { /*Get all items*/ ArrayList<ItemDTO> allitem = itemBO.getAllItems(); for(ItemDTO dto: allitem){ tblItems.getItems().add(new ItemTM(dto.getCode(),dto.getDescription(),dto.getUnitPrice(),dto.getQtyOnHand())); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void initUI() { txtCode.clear(); txtDescription.clear(); txtUnitPrice.clear(); txtQtyOnHand.clear(); txtCode.setDisable(true); txtDescription.setDisable(true); txtUnitPrice.setDisable(true); txtQtyOnHand.setDisable(true); txtCode.setEditable(false); btnSave.setDisable(true); btnDelete.setDisable(true); } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAddNew_OnAction(ActionEvent actionEvent) { txtCode.setDisable(false); txtDescription.setDisable(false); txtUnitPrice.setDisable(false); txtQtyOnHand.setDisable(false); txtCode.clear(); txtCode.setText(generateNewId()); txtDescription.clear(); txtUnitPrice.clear(); txtQtyOnHand.clear(); txtDescription.requestFocus(); btnSave.setDisable(false); btnSave.setText("Save"); tblItems.getSelectionModel().clearSelection(); } public void btnDelete_OnAction(ActionEvent actionEvent) { /*Delete Item*/ String code = tblItems.getSelectionModel().getSelectedItem().getCode(); try { ItemBOImpl itemBO = new ItemBOImpl(); if (!itemBO.existItem(code)) { new Alert(Alert.AlertType.ERROR, "There is no such item associated with the id " + code).show(); } boolean isDeleted=itemBO.deleteItem(code); if(isDeleted){ tblItems.getItems().remove(tblItems.getSelectionModel().getSelectedItem()); tblItems.getSelectionModel().clearSelection(); initUI(); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to delete the item " + code).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void btnSave_OnAction(ActionEvent actionEvent) { String code = txtCode.getText(); String description = txtDescription.getText(); if (!description.matches("[A-Za-z0-9 ]+")) { new Alert(Alert.AlertType.ERROR, "Invalid description").show(); txtDescription.requestFocus(); return; } else if (!txtUnitPrice.getText().matches("^[0-9]+[.]?[0-9]*$")) { new Alert(Alert.AlertType.ERROR, "Invalid unit price").show(); txtUnitPrice.requestFocus(); return; } else if (!txtQtyOnHand.getText().matches("^\\d+$")) { new Alert(Alert.AlertType.ERROR, "Invalid qty on hand").show(); txtQtyOnHand.requestFocus(); return; } int qtyOnHand = Integer.parseInt(txtQtyOnHand.getText()); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); if (btnSave.getText().equalsIgnoreCase("save")) { try { if (itemBO.existItem(code)) { new Alert(Alert.AlertType.ERROR, code + " already exists").show(); } //Save Item ItemDTO dto = new ItemDTO(code, description, unitPrice, qtyOnHand); boolean isSaved=itemBO.SaveItem(dto); if(isSaved){ tblItems.getItems().add(new ItemTM(code, description, unitPrice, qtyOnHand)); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { try {
ItemDao dao= new ItemDAO();
4
2023-12-15 04:45:10+00:00
8k
pan2013e/ppt4j
framework/src/main/java/ppt4j/diff/DiffParser.java
[ { "identifier": "FileUtils", "path": "framework/src/main/java/ppt4j/util/FileUtils.java", "snippet": "@Log4j\npublic class FileUtils {\n\n public static void makeLocalDirectory(String path) {\n File dir = new File(path);\n if(dir.exists() && dir.isDirectory()) {\n return;\n ...
import ppt4j.util.FileUtils; import ppt4j.util.StringUtils; import io.reflectoring.diffparser.api.UnifiedDiffParser; import io.reflectoring.diffparser.api.model.Diff; import io.reflectoring.diffparser.api.model.Line; import lombok.extern.log4j.Log4j; import org.apache.commons.lang3.tuple.Pair; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List;
4,798
package ppt4j.diff; @Log4j public class DiffParser { private final List<Diff> diffs; private final List<List<Pair<Integer, Line>>> diffLines = new ArrayList<>(); private final List<FileDiff> fileDiffs = new ArrayList<>(); private boolean downloadIntegrityCheck = false; @Log4j static class SigintHandler extends Thread { private final DiffParser diff; private final File f; public SigintHandler(DiffParser diff, File f) { this.diff = diff; this.f = f; } public void register() { Runtime.getRuntime().addShutdownHook(this); } @Override @SuppressWarnings("ResultOfMethodCallIgnored") public void run() { if (!diff.downloadIntegrityCheck) { log.error("Download incomplete"); f.delete(); } } } public DiffParser(URL url) throws IOException { FileUtils.makeLocalDirectory(".temp"); boolean web = url.getProtocol().equals("http") || url.getProtocol().equals("https"); if (web) { log.trace("Downloading diff file"); log.trace("URL: " + url); } byte[] buf = download(url); if(web) { log.trace("Download complete"); } UnifiedDiffParser parser = new UnifiedDiffParser(); diffs = parser.parse(preprocess(buf)); buildDiffLines(); for (List<Pair<Integer, Line>> diffLine : diffLines) { fileDiffs.add(new FileDiff(diffLine)); } } @SuppressWarnings("ResultOfMethodCallIgnored") public byte[] download(URL url) throws IOException { byte[] buf = null; File f = new File(".temp/" + url.toString().hashCode()); if(f.exists()) { FileInputStream fis = new FileInputStream(f); buf = fis.readAllBytes(); fis.close(); } else { f.createNewFile(); new SigintHandler(this, f).register(); try { URLConnection socketConn = url.openConnection(); socketConn.setConnectTimeout(10000); socketConn.setReadTimeout(20000); BufferedInputStream bis = new BufferedInputStream(socketConn.getInputStream()); FileOutputStream fos = new FileOutputStream(f); buf = bis.readAllBytes(); fos.write(buf); fos.close(); bis.close(); downloadIntegrityCheck = true; } catch (IOException e) { log.error(e); System.exit(1); } } return buf; } public DiffParser(String patchPath) throws IOException {
package ppt4j.diff; @Log4j public class DiffParser { private final List<Diff> diffs; private final List<List<Pair<Integer, Line>>> diffLines = new ArrayList<>(); private final List<FileDiff> fileDiffs = new ArrayList<>(); private boolean downloadIntegrityCheck = false; @Log4j static class SigintHandler extends Thread { private final DiffParser diff; private final File f; public SigintHandler(DiffParser diff, File f) { this.diff = diff; this.f = f; } public void register() { Runtime.getRuntime().addShutdownHook(this); } @Override @SuppressWarnings("ResultOfMethodCallIgnored") public void run() { if (!diff.downloadIntegrityCheck) { log.error("Download incomplete"); f.delete(); } } } public DiffParser(URL url) throws IOException { FileUtils.makeLocalDirectory(".temp"); boolean web = url.getProtocol().equals("http") || url.getProtocol().equals("https"); if (web) { log.trace("Downloading diff file"); log.trace("URL: " + url); } byte[] buf = download(url); if(web) { log.trace("Download complete"); } UnifiedDiffParser parser = new UnifiedDiffParser(); diffs = parser.parse(preprocess(buf)); buildDiffLines(); for (List<Pair<Integer, Line>> diffLine : diffLines) { fileDiffs.add(new FileDiff(diffLine)); } } @SuppressWarnings("ResultOfMethodCallIgnored") public byte[] download(URL url) throws IOException { byte[] buf = null; File f = new File(".temp/" + url.toString().hashCode()); if(f.exists()) { FileInputStream fis = new FileInputStream(f); buf = fis.readAllBytes(); fis.close(); } else { f.createNewFile(); new SigintHandler(this, f).register(); try { URLConnection socketConn = url.openConnection(); socketConn.setConnectTimeout(10000); socketConn.setReadTimeout(20000); BufferedInputStream bis = new BufferedInputStream(socketConn.getInputStream()); FileOutputStream fos = new FileOutputStream(f); buf = bis.readAllBytes(); fos.write(buf); fos.close(); bis.close(); downloadIntegrityCheck = true; } catch (IOException e) { log.error(e); System.exit(1); } } return buf; } public DiffParser(String patchPath) throws IOException {
this(StringUtils.toURL(patchPath));
1
2023-12-14 15:33:50+00:00
8k
MalithShehan/layered-architecture-Malith-Shehan
src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/PlaceOrderBOImpl.java
[ { "identifier": "PlaceOrderBO", "path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/PlaceOrderBO.java", "snippet": "public interface PlaceOrderBO extends SuperBO {\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLExcept...
import com.example.layeredarchitecture.bo.custom.PlaceOrderBO; import com.example.layeredarchitecture.dao.DAOFactory; import com.example.layeredarchitecture.dao.custom.*; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.ItemDTO; import com.example.layeredarchitecture.dto.OrderDTO; import com.example.layeredarchitecture.dto.OrderDetailDTO; import com.example.layeredarchitecture.entity.Customer; import com.example.layeredarchitecture.entity.Item; import com.example.layeredarchitecture.entity.Order; import com.example.layeredarchitecture.entity.OrderDetails; import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List;
3,680
package com.example.layeredarchitecture.bo.custom.impl; public class PlaceOrderBOImpl implements PlaceOrderBO { CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY); OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL); @Override public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException { Customer customer=customerDAO.search(id); CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()); return customerDTO; } @Override
package com.example.layeredarchitecture.bo.custom.impl; public class PlaceOrderBOImpl implements PlaceOrderBO { CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY); OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL); @Override public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException { Customer customer=customerDAO.search(id); CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()); return customerDTO; } @Override
public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException {
4
2023-12-16 04:19:09+00:00
8k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/render/gun/model/GrenadeLauncherModel.java
[ { "identifier": "GunModel", "path": "src/main/java/com/mrcrayfish/guns/client/GunModel.java", "snippet": "public class GunModel implements BakedModel\n{\n private static final GunModel INSTANCE = new GunModel();\n\n private BakedModel model;\n\n public void setModel(BakedModel model)\n {\n ...
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; import com.mrcrayfish.guns.client.GunModel; import com.mrcrayfish.guns.client.SpecialModels; import com.mrcrayfish.guns.client.render.gun.IOverrideModel; import com.mrcrayfish.guns.client.util.RenderUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemCooldowns; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable;
4,405
package com.mrcrayfish.guns.client.render.gun.model; /** * Author: MrCrayfish */ public class GrenadeLauncherModel implements IOverrideModel { @Override public void render(float partialTicks, ItemTransforms.TransformType transformType, ItemStack stack, ItemStack parent, @Nullable LivingEntity entity, PoseStack poseStack, MultiBufferSource buffer, int light, int overlay) { BakedModel bakedModel = SpecialModels.GRENADE_LAUNCHER_BASE.getModel();
package com.mrcrayfish.guns.client.render.gun.model; /** * Author: MrCrayfish */ public class GrenadeLauncherModel implements IOverrideModel { @Override public void render(float partialTicks, ItemTransforms.TransformType transformType, ItemStack stack, ItemStack parent, @Nullable LivingEntity entity, PoseStack poseStack, MultiBufferSource buffer, int light, int overlay) { BakedModel bakedModel = SpecialModels.GRENADE_LAUNCHER_BASE.getModel();
Minecraft.getInstance().getItemRenderer().render(stack, ItemTransforms.TransformType.NONE, false, poseStack, buffer, light, overlay, GunModel.wrap(bakedModel));
0
2023-12-18 15:04:35+00:00
8k
Qzimyion/BucketEm
src/main/java/com/qzimyion/bucketem/items/ModItems.java
[ { "identifier": "Bucketem", "path": "src/main/java/com/qzimyion/bucketem/Bucketem.java", "snippet": "public class Bucketem implements ModInitializer {\n\n\tpublic static final String MOD_ID = \"bucketem\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\t@Override\n\tpublic v...
import com.qzimyion.bucketem.Bucketem; import com.qzimyion.bucketem.items.NewItems.Bottles.EntityBottle; import com.qzimyion.bucketem.items.NewItems.Bottles.MagmaCubeBottle; import com.qzimyion.bucketem.items.NewItems.Bottles.SlimeBottle; import com.qzimyion.bucketem.items.NewItems.EntityBook; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTemperateFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTropicalFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTundraFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TemperateFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TropicalFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TundraFrogBuckets; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.entity.EntityType; import net.minecraft.fluid.Fluids; import net.minecraft.item.EntityBucketItem; import net.minecraft.item.Item; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Identifier; import net.minecraft.util.Rarity; import static net.minecraft.item.Items.GLASS_BOTTLE;
5,250
package com.qzimyion.bucketem.items; public class ModItems { //Buckets public static final Item STRIDER_BUCKET = registerItem("strider_bucket", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1))); public static final Item SQUID_BUCKET = registerItem("squid_bucket", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item GLOW_SQUID_BUCKET = registerItem("glow_squid_bucket", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item TEMPERATE_FROG_BUCKET = registerItem("temperate_frog_bucket", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TROPICAL_FROG_BUCKET = registerItem("tropical_frog_bucket", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1))); public static final Item TUNDRA_FROG_BUCKET = registerItem("tundra_frog_bucket", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TURTLE_BUCKET = registerItem("turtle_bucket", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem("dry_temperate_frog_bucket", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem("dry_tropical_frog_bucket", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem("dry_tundra_frog_bucket", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1))); //Books public static final Item ALLAY_POSSESSED_BOOK = registerItem("allay_possessed_book", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); public static final Item VEX_POSSESSED_BOOK = registerItem("vex_possessed_book", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); //Bottles public static final Item BEE_BOTTLE = registerItem("bee_bottle", new EntityBottle(EntityType.BEE ,new FabricItemSettings().maxCount(1))); public static final Item SILVERFISH_BOTTLE = registerItem("silverfish_bottle", new EntityBottle(EntityType.SILVERFISH, new FabricItemSettings().maxCount(1))); public static final Item ENDERMITE_BOTTLE = registerItem("endermite_bottle", new EntityBottle(EntityType.ENDERMITE, new FabricItemSettings().maxCount(1))); public static final Item SLIME_BOTTLE = registerItem("slime_bottle", new SlimeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));
package com.qzimyion.bucketem.items; public class ModItems { //Buckets public static final Item STRIDER_BUCKET = registerItem("strider_bucket", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1))); public static final Item SQUID_BUCKET = registerItem("squid_bucket", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item GLOW_SQUID_BUCKET = registerItem("glow_squid_bucket", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item TEMPERATE_FROG_BUCKET = registerItem("temperate_frog_bucket", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TROPICAL_FROG_BUCKET = registerItem("tropical_frog_bucket", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1))); public static final Item TUNDRA_FROG_BUCKET = registerItem("tundra_frog_bucket", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TURTLE_BUCKET = registerItem("turtle_bucket", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem("dry_temperate_frog_bucket", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem("dry_tropical_frog_bucket", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem("dry_tundra_frog_bucket", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1))); //Books public static final Item ALLAY_POSSESSED_BOOK = registerItem("allay_possessed_book", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); public static final Item VEX_POSSESSED_BOOK = registerItem("vex_possessed_book", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); //Bottles public static final Item BEE_BOTTLE = registerItem("bee_bottle", new EntityBottle(EntityType.BEE ,new FabricItemSettings().maxCount(1))); public static final Item SILVERFISH_BOTTLE = registerItem("silverfish_bottle", new EntityBottle(EntityType.SILVERFISH, new FabricItemSettings().maxCount(1))); public static final Item ENDERMITE_BOTTLE = registerItem("endermite_bottle", new EntityBottle(EntityType.ENDERMITE, new FabricItemSettings().maxCount(1))); public static final Item SLIME_BOTTLE = registerItem("slime_bottle", new SlimeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));
public static final Item MAGMA_CUBE_BOTTLE = registerItem("magma_bottle", new MagmaCubeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));
2
2023-12-16 08:12:37+00:00
8k
Team319/SwerveTemplate_with_AK
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DriveCommands", "path": "src/main/java/frc/robot/commands/DriveCommands.java", "snippet": "public class DriveCommands {\n private static final double DEADBAND = 0.2;\n private static final double JOYSTICK_GOVERNOR = 0.3; // this value must not exceed 1.0\n private static final double...
import com.pathplanner.lib.auto.AutoBuilder; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import frc.robot.commands.DriveCommands; import frc.robot.commands.FeedForwardCharacterization; import frc.robot.subsystems.drive.Drive; import frc.robot.subsystems.drive.GyroIO; import frc.robot.subsystems.drive.GyroIOPigeon2; import frc.robot.subsystems.drive.ModuleIO; import frc.robot.subsystems.drive.ModuleIOSim; import frc.robot.subsystems.drive.ModuleIOTalonFX; import org.littletonrobotics.junction.networktables.LoggedDashboardChooser;
7,074
// Copyright 2021-2023 FRC 6328 // http://github.com/Mechanical-Advantage // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation or // available in the root directory of this project. // // 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. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { // Subsystems private final Drive drive; // private final Flywheel flywheel; // Controller private final CommandXboxController controller = new CommandXboxController(0); // Dashboard inputs private final LoggedDashboardChooser<Command> autoChooser; // private final LoggedDashboardNumber flywheelSpeedInput = // new LoggedDashboardNumber("Flywheel Speed", 1500.0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { switch (Constants.currentMode) { case REAL: // Real robot, instantiate hardware IO implementations // drive = // new Drive( // new GyroIOPigeon2(), // new ModuleIOSparkMax(0), // new ModuleIOSparkMax(1), // new ModuleIOSparkMax(2), // new ModuleIOSparkMax(3)); // flywheel = new Flywheel(new FlywheelIOSparkMax()); drive = new Drive( new GyroIOPigeon2(), new ModuleIOTalonFX(0), new ModuleIOTalonFX(1), new ModuleIOTalonFX(2), new ModuleIOTalonFX(3)); // flywheel = new Flywheel(new FlywheelIOTalonFX()); break; case SIM: // Sim robot, instantiate physics sim IO implementations drive = new Drive(
// Copyright 2021-2023 FRC 6328 // http://github.com/Mechanical-Advantage // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation or // available in the root directory of this project. // // 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. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { // Subsystems private final Drive drive; // private final Flywheel flywheel; // Controller private final CommandXboxController controller = new CommandXboxController(0); // Dashboard inputs private final LoggedDashboardChooser<Command> autoChooser; // private final LoggedDashboardNumber flywheelSpeedInput = // new LoggedDashboardNumber("Flywheel Speed", 1500.0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { switch (Constants.currentMode) { case REAL: // Real robot, instantiate hardware IO implementations // drive = // new Drive( // new GyroIOPigeon2(), // new ModuleIOSparkMax(0), // new ModuleIOSparkMax(1), // new ModuleIOSparkMax(2), // new ModuleIOSparkMax(3)); // flywheel = new Flywheel(new FlywheelIOSparkMax()); drive = new Drive( new GyroIOPigeon2(), new ModuleIOTalonFX(0), new ModuleIOTalonFX(1), new ModuleIOTalonFX(2), new ModuleIOTalonFX(3)); // flywheel = new Flywheel(new FlywheelIOTalonFX()); break; case SIM: // Sim robot, instantiate physics sim IO implementations drive = new Drive(
new GyroIO() {},
3
2023-12-16 14:59:04+00:00
8k
lpyleo/disk-back-end
file-web/src/main/java/com/disk/file/service/impl/UserServiceImpl.java
[ { "identifier": "RestResult", "path": "file-web/src/main/java/com/disk/file/common/RestResult.java", "snippet": "@Data\npublic class RestResult<T> {\n private Boolean success = true;\n private Integer code;\n private String message;\n private T data;\n\n // 自定义返回数据\n public RestResult ...
import java.util.*; import javax.annotation.Resource; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.disk.file.common.RestResult; import com.disk.file.constant.FileConstant; import com.disk.file.mapper.UserMapper; import com.disk.file.model.User; import com.disk.file.model.UserFile; import com.disk.file.service.UserService; import com.disk.file.util.DateUtil; import com.disk.file.util.JwtUtil; import com.disk.file.vo.LoginTodayCountVO; import com.disk.file.vo.UserDeptInfoVO; import com.disk.file.vo.UserInfoVO; import com.disk.file.vo.UserfileListVO; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwt; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import org.springframework.util.StringUtils; import lombok.extern.slf4j.Slf4j;
4,553
package com.disk.file.service.impl; @Slf4j @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{ @Resource JwtUtil jwtUtil; @Resource UserMapper userMapper; @Override public RestResult<String> registerUser(User user) { //判断验证码 String username = user.getUsername(); String telephone = user.getTelephone(); String password = user.getPassword(); String avatar = user.getAvatar(); if (!StringUtils.hasLength(username)){ return RestResult.fail().message("用户名不能为空!"); } if (!StringUtils.hasLength(telephone) || !StringUtils.hasLength(password)){ return RestResult.fail().message("手机号或密码不能为空!"); } if (isTelePhoneExit(telephone)){ return RestResult.fail().message("手机号已存在!"); } String salt = UUID.randomUUID().toString().replace("-", "").substring(15); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); user.setSalt(salt); user.setPassword(newPassword); user.setRegisterTime(DateUtil.getCurrentTime()); int result = userMapper.insert(user); if (result == 1) { return RestResult.success(); } else { return RestResult.fail().message("注册用户失败,请检查输入信息!"); } } private boolean isTelePhoneExit(String telePhone) { LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getTelephone, telePhone); List<User> list = userMapper.selectList(lambdaQueryWrapper); if (list != null && !list.isEmpty()) { return true; } else { return false; } } @Override public RestResult<User> login(User user) { String telephone = user.getTelephone(); String password = user.getPassword(); LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getTelephone, telephone); User saveUser = userMapper.selectOne(lambdaQueryWrapper); String salt = saveUser.getSalt(); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); if (newPassword.equals(saveUser.getPassword())) { saveUser.setPassword(""); saveUser.setSalt(""); userMapper.updateLastLoginTime(user.getTelephone(), DateUtil.getCurrentTime()); return RestResult.success().data(saveUser); } else { return RestResult.fail().message("手机号或密码错误!"); } } @Override public User getUserByToken(String token) { User tokenUserInfo = null; try { Claims c = jwtUtil.parseJWT(token); String subject = c.getSubject(); ObjectMapper objectMapper = new ObjectMapper(); tokenUserInfo = objectMapper.readValue(subject, User.class); } catch (Exception e) { log.error("解码异常"); return null; } return tokenUserInfo; } @Override public UserInfoVO selectUserById(Long userId){ return userMapper.getUserInfo(userId); } @Override public RestResult<String> updateUser(User user){ userMapper.updateUser(user); return RestResult.success().data("用户信息修改成功"); } @Override public RestResult<String> updatePassword(User user, String newPsd) { String password = user.getPassword(); Long userId = user.getUserId(); LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getUserId, userId); User saveUser = userMapper.selectOne(lambdaQueryWrapper); String salt = saveUser.getSalt(); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); if (newPassword.equals(saveUser.getPassword())) { user.setPassword(DigestUtils.md5DigestAsHex((newPsd+salt).getBytes())); userMapper.updatePassword(user); return RestResult.success().data("用户密码修改成功"); } else { return RestResult.fail().message("原密码输入错误"); } } @Override public RestResult<List<LoginTodayCountVO>> getLoginTodayCount() { return RestResult.success().data(userMapper.getLoginTodayCount()); } @Override
package com.disk.file.service.impl; @Slf4j @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{ @Resource JwtUtil jwtUtil; @Resource UserMapper userMapper; @Override public RestResult<String> registerUser(User user) { //判断验证码 String username = user.getUsername(); String telephone = user.getTelephone(); String password = user.getPassword(); String avatar = user.getAvatar(); if (!StringUtils.hasLength(username)){ return RestResult.fail().message("用户名不能为空!"); } if (!StringUtils.hasLength(telephone) || !StringUtils.hasLength(password)){ return RestResult.fail().message("手机号或密码不能为空!"); } if (isTelePhoneExit(telephone)){ return RestResult.fail().message("手机号已存在!"); } String salt = UUID.randomUUID().toString().replace("-", "").substring(15); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); user.setSalt(salt); user.setPassword(newPassword); user.setRegisterTime(DateUtil.getCurrentTime()); int result = userMapper.insert(user); if (result == 1) { return RestResult.success(); } else { return RestResult.fail().message("注册用户失败,请检查输入信息!"); } } private boolean isTelePhoneExit(String telePhone) { LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getTelephone, telePhone); List<User> list = userMapper.selectList(lambdaQueryWrapper); if (list != null && !list.isEmpty()) { return true; } else { return false; } } @Override public RestResult<User> login(User user) { String telephone = user.getTelephone(); String password = user.getPassword(); LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getTelephone, telephone); User saveUser = userMapper.selectOne(lambdaQueryWrapper); String salt = saveUser.getSalt(); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); if (newPassword.equals(saveUser.getPassword())) { saveUser.setPassword(""); saveUser.setSalt(""); userMapper.updateLastLoginTime(user.getTelephone(), DateUtil.getCurrentTime()); return RestResult.success().data(saveUser); } else { return RestResult.fail().message("手机号或密码错误!"); } } @Override public User getUserByToken(String token) { User tokenUserInfo = null; try { Claims c = jwtUtil.parseJWT(token); String subject = c.getSubject(); ObjectMapper objectMapper = new ObjectMapper(); tokenUserInfo = objectMapper.readValue(subject, User.class); } catch (Exception e) { log.error("解码异常"); return null; } return tokenUserInfo; } @Override public UserInfoVO selectUserById(Long userId){ return userMapper.getUserInfo(userId); } @Override public RestResult<String> updateUser(User user){ userMapper.updateUser(user); return RestResult.success().data("用户信息修改成功"); } @Override public RestResult<String> updatePassword(User user, String newPsd) { String password = user.getPassword(); Long userId = user.getUserId(); LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(User::getUserId, userId); User saveUser = userMapper.selectOne(lambdaQueryWrapper); String salt = saveUser.getSalt(); String passwordAndSalt = password + salt; String newPassword = DigestUtils.md5DigestAsHex(passwordAndSalt.getBytes()); if (newPassword.equals(saveUser.getPassword())) { user.setPassword(DigestUtils.md5DigestAsHex((newPsd+salt).getBytes())); userMapper.updatePassword(user); return RestResult.success().data("用户密码修改成功"); } else { return RestResult.fail().message("原密码输入错误"); } } @Override public RestResult<List<LoginTodayCountVO>> getLoginTodayCount() { return RestResult.success().data(userMapper.getLoginTodayCount()); } @Override
public List<UserDeptInfoVO> getUserDeptInfo(Long currentPage, Long pageCount) {
9
2023-12-17 05:12:43+00:00
8k
civso/Live2DViewerEXModelDownload
src/main/java/org/Live2DViewerEX/ModelDownload/ListSelector.java
[ { "identifier": "FormatteName", "path": "src/main/java/org/Live2DViewerEX/ModelDownload/LpxFileName/FormatteName.java", "snippet": "public class FormatteName {\r\n\r\n FileUtils Utils;\r\n ArrayList<Live2dModeConfig> LpxConfigrList = new ArrayList<>();\r\n\r\n public String Main(JSONObject conf...
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.Live2DViewerEX.ModelDownload.LpxFileName.FormatteName; import org.Live2DViewerEX.ModelDownload.utils.LpxDecrypt; import org.Live2DViewerEX.ModelDownload.utils.LpxHttpInterface; import org.Live2DViewerEX.ModelDownload.utils.ModelInfoPrinter; import java.util.Scanner;
4,693
package org.Live2DViewerEX.ModelDownload; public class ListSelector { JSONObject postData; //获取请求体json public ListSelector(){
package org.Live2DViewerEX.ModelDownload; public class ListSelector { JSONObject postData; //获取请求体json public ListSelector(){
LpxHttpInterface lpxHttp = new LpxHttpInterface();
2
2023-12-16 14:51:01+00:00
8k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/VariousFragment.java
[ { "identifier": "SettingsPreferenceFragment", "path": "app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/base/SettingsPreferenceFragment.java", "snippet": "public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {\n\n public String mTitle;\n public String mPreferenceKe...
import static com.sevtinge.hyperceiler.utils.api.VoyagerApisKt.isPad; import android.os.Handler; import androidx.annotation.NonNull; import com.sevtinge.hyperceiler.R; import com.sevtinge.hyperceiler.ui.fragment.base.SettingsPreferenceFragment; import com.sevtinge.hyperceiler.utils.PrefsUtils; import com.sevtinge.hyperceiler.utils.ShellUtils; import moralnorm.preference.DropDownPreference; import moralnorm.preference.Preference; import moralnorm.preference.PreferenceCategory; import moralnorm.preference.SwitchPreference;
4,222
package com.sevtinge.hyperceiler.ui.fragment; public class VariousFragment extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { DropDownPreference mSuperModePreference; PreferenceCategory mDefault; SwitchPreference mClipboard; Preference mMipad; // 平板相关功能 Handler handler; @Override public int getContentResId() { return R.xml.various; } @Override public void initPrefs() {
package com.sevtinge.hyperceiler.ui.fragment; public class VariousFragment extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { DropDownPreference mSuperModePreference; PreferenceCategory mDefault; SwitchPreference mClipboard; Preference mMipad; // 平板相关功能 Handler handler; @Override public int getContentResId() { return R.xml.various; } @Override public void initPrefs() {
int mode = Integer.parseInt(PrefsUtils.getSharedStringPrefs(getContext(), "prefs_key_various_super_clipboard_e", "0"));
1
2023-10-27 17:17:42+00:00
8k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/SetConfigDialogController.java
[ { "identifier": "FofaConfig", "path": "src/main/java/org/fofaviewer/main/FofaConfig.java", "snippet": "public class FofaConfig {\n private static FofaConfig config = null;\n private boolean checkStatus;\n private String email;\n private String key;\n private final String page = \"1\";\n ...
import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.main.ProxyConfig; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.ResourceBundleUtil; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger; import java.io.*; import java.util.*;
6,649
@FXML private Label label_proxy_port; @FXML private Label label_proxy_user; @FXML private Label label_proxy_password; @FXML private TextField fofa_api; @FXML private TextField fofa_email; @FXML private TextField fofa_key; @FXML private TextField fofa_max_size; @FXML private ComboBox typeCombo; @FXML private TextField proxy_ip; @FXML private TextField proxy_port; @FXML private TextField proxy_user; @FXML private TextField proxy_password; @FXML private RadioButton enable; @FXML private RadioButton disable; @FXML private Label checkLeftAmount; @FXML private RadioButton enableCheck; @FXML private RadioButton disableCheck; @FXML private void initialize(){ bundle = ResourceBundleUtil.getResource(); fofa_tab.setText(bundle.getString("FOFA_CONFIG")); proxy_tab.setText(bundle.getString("PROXY_CONFIG")); enable.setText(bundle.getString("ENABLE_RADIO")); checkLeftAmount.setText(bundle.getString("CHECK_LEFT_AMOUNT")); enableCheck.setText(bundle.getString("ENABLE_RADIO")); disableCheck.setText(bundle.getString("DISABLE_RADIO")); disable.setText(bundle.getString("DISABLE_RADIO")); label_fofa_api.setText(bundle.getString("FOFA_API")); label_fofa_email.setText(bundle.getString("FOFA_EMAIL")); label_fofa_key.setText(bundle.getString("FOFA_KEY")); label_fofa_max_size.setText(bundle.getString("FOFA_MAX_SIZE")); label_proxy_ip.setText(bundle.getString("PROXY_IP_ADDRESS")); label_proxy_port.setText(bundle.getString("PROXY_PORT")); label_proxy_user.setText(bundle.getString("PROXY_USER")); label_proxy_password.setText(bundle.getString("PROXY_PASSWORD")); labelCombo.setText(bundle.getString("PROXY_TYPE")); propertiesMap = new HashMap<TextField, String>(){{ put(fofa_api, "api"); put(fofa_email, "email"); put(fofa_key, "key"); put(fofa_max_size, "max_size"); put(proxy_ip, "proxy_ip"); put(proxy_port, "proxy_port"); put(proxy_user, "proxy_user"); put(proxy_password, "proxy_password"); }}; ToggleGroup statusGroup = new ToggleGroup(); enable.setToggleGroup(statusGroup); disable.setToggleGroup(statusGroup); statusGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> proxyConfig.setStatus(statusGroup.getSelectedToggle().equals(enable))); ToggleGroup checkStatusGroup = new ToggleGroup(); enableCheck.setToggleGroup(checkStatusGroup); disableCheck.setToggleGroup(checkStatusGroup); checkStatusGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> fofaConfig.setCheckStatus(checkStatusGroup.getSelectedToggle().equals(enableCheck))); fofaConfig = FofaConfig.getInstance(); proxyConfig = ProxyConfig.getInstance(); typeCombo.setItems(FXCollections.observableArrayList(ProxyConfig.ProxyType.HTTP, ProxyConfig.ProxyType.SOCKS5)); typeCombo.getSelectionModel().select(0); createConfigFile(); loadConfigFile(); } public void setAction(DialogPane dialogPane){ dialogPane.lookupButton(ButtonType.OK).addEventFilter(ActionEvent.ACTION, e -> { createConfigFile(); if(enable.isSelected() && (proxy_ip.getText().equals("") || proxy_port.getText().equals(""))){ DataUtil.showAlert(Alert.AlertType.WARNING, null, bundle.getString("PROXY_SET_ERROR")).showAndWait(); e.consume(); }else{ Properties properties = new Properties(); try { fofaConfig.setEmail(fofa_email.getText()); fofaConfig.API = fofa_api.getText(); fofaConfig.setSize(fofa_max_size.getText()); fofaConfig.setKey(fofa_key.getText()); fofaConfig.setCheckStatus(enableCheck.isSelected()); proxyConfig.setStatus(enable.isSelected()); proxyConfig.setProxy_ip(proxy_ip.getText()); proxyConfig.setProxy_port(proxy_port.getText()); proxyConfig.setProxy_user(proxy_user.getText()); proxyConfig.setProxy_password(proxy_password.getText()); FileOutputStream outputStream = new FileOutputStream(this.configFile); for(TextField tf : propertiesMap.keySet()){ properties.setProperty(propertiesMap.get(tf), tf.getText()); } properties.setProperty("proxy_status", proxyConfig.getStatus() ? "on" : "off"); properties.setProperty("check_status", fofaConfig.getCheckStatus() ? "on" : "off"); ProxyConfig.ProxyType type = (ProxyConfig.ProxyType) typeCombo.getSelectionModel().getSelectedItem(); switch (type){ case HTTP: properties.setProperty("proxy_type", "HTTP");break; case SOCKS5: properties.setProperty("proxy_type", "SOCKS5");break; } properties.store(outputStream, "config.properties"); outputStream.close(); } catch (IOException ex) { Logger.error(ex); } } }); } private void createConfigFile(){
package org.fofaviewer.controllers; public class SetConfigDialogController { private File configFile; private Map<TextField, String> propertiesMap; private FofaConfig fofaConfig; private ProxyConfig proxyConfig; private ResourceBundle bundle; @FXML private Tab fofa_tab; @FXML private Tab proxy_tab; @FXML private Label label_fofa_api; @FXML private Label label_fofa_email; @FXML private Label label_fofa_key; @FXML private Label label_fofa_max_size; @FXML private Label labelCombo; @FXML private Label label_proxy_ip; @FXML private Label label_proxy_port; @FXML private Label label_proxy_user; @FXML private Label label_proxy_password; @FXML private TextField fofa_api; @FXML private TextField fofa_email; @FXML private TextField fofa_key; @FXML private TextField fofa_max_size; @FXML private ComboBox typeCombo; @FXML private TextField proxy_ip; @FXML private TextField proxy_port; @FXML private TextField proxy_user; @FXML private TextField proxy_password; @FXML private RadioButton enable; @FXML private RadioButton disable; @FXML private Label checkLeftAmount; @FXML private RadioButton enableCheck; @FXML private RadioButton disableCheck; @FXML private void initialize(){ bundle = ResourceBundleUtil.getResource(); fofa_tab.setText(bundle.getString("FOFA_CONFIG")); proxy_tab.setText(bundle.getString("PROXY_CONFIG")); enable.setText(bundle.getString("ENABLE_RADIO")); checkLeftAmount.setText(bundle.getString("CHECK_LEFT_AMOUNT")); enableCheck.setText(bundle.getString("ENABLE_RADIO")); disableCheck.setText(bundle.getString("DISABLE_RADIO")); disable.setText(bundle.getString("DISABLE_RADIO")); label_fofa_api.setText(bundle.getString("FOFA_API")); label_fofa_email.setText(bundle.getString("FOFA_EMAIL")); label_fofa_key.setText(bundle.getString("FOFA_KEY")); label_fofa_max_size.setText(bundle.getString("FOFA_MAX_SIZE")); label_proxy_ip.setText(bundle.getString("PROXY_IP_ADDRESS")); label_proxy_port.setText(bundle.getString("PROXY_PORT")); label_proxy_user.setText(bundle.getString("PROXY_USER")); label_proxy_password.setText(bundle.getString("PROXY_PASSWORD")); labelCombo.setText(bundle.getString("PROXY_TYPE")); propertiesMap = new HashMap<TextField, String>(){{ put(fofa_api, "api"); put(fofa_email, "email"); put(fofa_key, "key"); put(fofa_max_size, "max_size"); put(proxy_ip, "proxy_ip"); put(proxy_port, "proxy_port"); put(proxy_user, "proxy_user"); put(proxy_password, "proxy_password"); }}; ToggleGroup statusGroup = new ToggleGroup(); enable.setToggleGroup(statusGroup); disable.setToggleGroup(statusGroup); statusGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> proxyConfig.setStatus(statusGroup.getSelectedToggle().equals(enable))); ToggleGroup checkStatusGroup = new ToggleGroup(); enableCheck.setToggleGroup(checkStatusGroup); disableCheck.setToggleGroup(checkStatusGroup); checkStatusGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> fofaConfig.setCheckStatus(checkStatusGroup.getSelectedToggle().equals(enableCheck))); fofaConfig = FofaConfig.getInstance(); proxyConfig = ProxyConfig.getInstance(); typeCombo.setItems(FXCollections.observableArrayList(ProxyConfig.ProxyType.HTTP, ProxyConfig.ProxyType.SOCKS5)); typeCombo.getSelectionModel().select(0); createConfigFile(); loadConfigFile(); } public void setAction(DialogPane dialogPane){ dialogPane.lookupButton(ButtonType.OK).addEventFilter(ActionEvent.ACTION, e -> { createConfigFile(); if(enable.isSelected() && (proxy_ip.getText().equals("") || proxy_port.getText().equals(""))){ DataUtil.showAlert(Alert.AlertType.WARNING, null, bundle.getString("PROXY_SET_ERROR")).showAndWait(); e.consume(); }else{ Properties properties = new Properties(); try { fofaConfig.setEmail(fofa_email.getText()); fofaConfig.API = fofa_api.getText(); fofaConfig.setSize(fofa_max_size.getText()); fofaConfig.setKey(fofa_key.getText()); fofaConfig.setCheckStatus(enableCheck.isSelected()); proxyConfig.setStatus(enable.isSelected()); proxyConfig.setProxy_ip(proxy_ip.getText()); proxyConfig.setProxy_port(proxy_port.getText()); proxyConfig.setProxy_user(proxy_user.getText()); proxyConfig.setProxy_password(proxy_password.getText()); FileOutputStream outputStream = new FileOutputStream(this.configFile); for(TextField tf : propertiesMap.keySet()){ properties.setProperty(propertiesMap.get(tf), tf.getText()); } properties.setProperty("proxy_status", proxyConfig.getStatus() ? "on" : "off"); properties.setProperty("check_status", fofaConfig.getCheckStatus() ? "on" : "off"); ProxyConfig.ProxyType type = (ProxyConfig.ProxyType) typeCombo.getSelectionModel().getSelectedItem(); switch (type){ case HTTP: properties.setProperty("proxy_type", "HTTP");break; case SOCKS5: properties.setProperty("proxy_type", "SOCKS5");break; } properties.store(outputStream, "config.properties"); outputStream.close(); } catch (IOException ex) { Logger.error(ex); } } }); } private void createConfigFile(){
String filePath = SQLiteUtils.getPath() + "config.properties";
4
2023-10-25 11:13:47+00:00
8k
qguangyao/MySound
src/main/java/com/jvspiano/sound/MyPlayer.java
[ { "identifier": "MyFileReaderTxt", "path": "src/main/java/com/jvspiano/sound/file/MyFileReaderTxt.java", "snippet": "public class MyFileReaderTxt implements MyFIleReader {\n @Override\n public RandomAccessFile Read(String path) {\n File file = null;\n RandomAccessFile rf = null;\n ...
import com.jvspiano.sound.file.MyFileReaderTxt; import com.jvspiano.sound.file.MyStringDistributerIMPL; import com.jvspiano.sound.note.MyNoteIMPL; import com.jvspiano.sound.note.NoteInfo; import javax.sound.midi.*; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.concurrent.CopyOnWriteArrayList;
6,502
package com.jvspiano.sound; /** * 对外接口 */ public class MyPlayer implements MetaEventListener { //(command >= 0xF0 || command < 0x80) //0x80开始,0x90结束,0xa0,0xb0,0xc0,0xd0,0xe0 //(channel & 0xFFFFFFF0) != 0) //满足上边两个条件会报错 MyStringDistributerIMPL md = new MyStringDistributerIMPL();
package com.jvspiano.sound; /** * 对外接口 */ public class MyPlayer implements MetaEventListener { //(command >= 0xF0 || command < 0x80) //0x80开始,0x90结束,0xa0,0xb0,0xc0,0xd0,0xe0 //(channel & 0xFFFFFFF0) != 0) //满足上边两个条件会报错 MyStringDistributerIMPL md = new MyStringDistributerIMPL();
MyFileReaderTxt mf = new MyFileReaderTxt();
0
2023-10-27 11:07:06+00:00
8k
rweisleder/archunit-spring
src/test/java/de/rweisleder/archunit/spring/SpringComponentRulesTest.java
[ { "identifier": "ControllerWithDependencyToConfiguration", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Controller\npublic static class ControllerWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public ControllerWi...
import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.lang.EvaluationResult; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithoutDependency; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static de.rweisleder.archunit.spring.TestUtils.importClasses; import static org.assertj.core.api.Assertions.assertThat;
3,931
} @Test void service_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToController.class.getName()); }); } @Test void service_with_dependency_to_other_service_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfRepositories { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfRepositories.getDescription(); assertThat(description).isEqualTo("Spring repositories should only depend on other Spring components that are repositories"); } @Test void repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToController.class.getName()); }); } @Test void repository_with_dependency_to_service_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToService.class.getName()); }); } @Test void repository_with_dependency_to_other_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToConfiguration.class.getName()); }); } @Test void Spring_Data_repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(SpringDataRepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void Spring_Data_repository_with_dependency_to_controller_is_a_violation() {
/* * #%L * ArchUnit Spring Integration * %% * Copyright (C) 2023 Roland Weisleder * %% * 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. * #L% */ package de.rweisleder.archunit.spring; @SuppressWarnings("CodeBlock2Expr") class SpringComponentRulesTest { @Nested class Rule_DependenciesOfControllers { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfControllers.getDescription(); assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories"); } @Test void controller_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_other_controller_is_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ControllerWithDependencyToController.class.getName()); }); } @Test void controller_with_dependency_to_service_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfServices { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfServices.getDescription(); assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories"); } @Test void service_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToController.class.getName()); }); } @Test void service_with_dependency_to_other_service_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfRepositories { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfRepositories.getDescription(); assertThat(description).isEqualTo("Spring repositories should only depend on other Spring components that are repositories"); } @Test void repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToController.class.getName()); }); } @Test void repository_with_dependency_to_service_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToService.class.getName()); }); } @Test void repository_with_dependency_to_other_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToConfiguration.class.getName()); }); } @Test void Spring_Data_repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(SpringDataRepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void Spring_Data_repository_with_dependency_to_controller_is_a_violation() {
JavaClasses classes = importClasses(SpringDataRepositoryWithDependencyToController.class);
19
2023-10-29 10:50:24+00:00
8k
373675032/verio-house
src/main/java/com/verio/controller/RoomOrderController.java
[ { "identifier": "Resp", "path": "src/main/java/com/verio/dto/Resp.java", "snippet": "public class Resp {\n public static String resp(RespResult result) {\n return JSONObject.toJSONString(result);\n }\n}" }, { "identifier": "RespResult", "path": "src/main/java/com/verio/dto/RespR...
import com.verio.dto.Resp; import com.verio.dto.RespResult; import com.verio.entity.Room; import com.verio.entity.RoomDetail; import com.verio.entity.RoomOrder; import com.verio.utils.Assert; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Calendar; import java.util.Date; import java.util.List;
3,618
package com.verio.controller; /** * 订单控制器 * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller @RequestMapping(value = "roomOrder") public class RoomOrderController extends BaseController<RoomOrder> { /** * 支付 */ @PostMapping("/pay") @ResponseBody public String pay(Integer id) { RoomOrder order = roomOrderService.get(id); List<RoomDetail> roomDetails = roomDetailService.query(RoomDetail.builder().roomId(order.getRoomId()).build());
package com.verio.controller; /** * 订单控制器 * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller @RequestMapping(value = "roomOrder") public class RoomOrderController extends BaseController<RoomOrder> { /** * 支付 */ @PostMapping("/pay") @ResponseBody public String pay(Integer id) { RoomOrder order = roomOrderService.get(id); List<RoomDetail> roomDetails = roomDetailService.query(RoomDetail.builder().roomId(order.getRoomId()).build());
if (Assert.notEmpty(roomDetails)) {
5
2023-10-29 14:50:56+00:00
8k
Changbaiqi/yatori
yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/CourseStudyAction.java
[ { "identifier": "Chapter", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/coursedetail/Chapter.java", "snippet": "@lombok.Data\npublic class Chapter {\n @JsonProperty(\"course\")\n private Object course;\n @JsonProperty(\"courseId\")\n private long courseId;\n ...
import com.cbq.yatori.core.action.canghui.entity.coursedetail.Chapter; import com.cbq.yatori.core.action.canghui.entity.coursedetail.CourseDetailData; import com.cbq.yatori.core.action.canghui.entity.coursedetail.Process; import com.cbq.yatori.core.action.canghui.entity.coursedetail.Section; import com.cbq.yatori.core.action.canghui.entity.exam.ExamCourse; import com.cbq.yatori.core.action.canghui.entity.exam.ExamItem; import com.cbq.yatori.core.action.canghui.entity.exam.ExamJson; import com.cbq.yatori.core.action.canghui.entity.exam.ExamTopic; import com.cbq.yatori.core.action.canghui.entity.examsubmit.TopicAnswer; import com.cbq.yatori.core.action.canghui.entity.examsubmit.TopicRequest; import com.cbq.yatori.core.action.canghui.entity.examsubmitrespose.ExamSubmitResponse; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.*; import com.cbq.yatori.core.action.canghui.entity.startexam.StartExam; import com.cbq.yatori.core.action.canghui.entity.submitstudy.ConverterSubmitStudyTime; import com.cbq.yatori.core.action.canghui.entity.submitstudy.SubmitStudyTimeRequest; import com.cbq.yatori.core.entity.AccountCacheCangHui; import com.cbq.yatori.core.entity.CoursesCostom; import com.cbq.yatori.core.entity.CoursesSetting; import com.cbq.yatori.core.entity.User; import com.fasterxml.jackson.core.JsonProcessingException; import lombok.extern.slf4j.Slf4j; import java.util.*;
6,287
/** * 自动考试 */ public void autoExamAction() { new Thread(() -> { Long arr[] = map.keySet().toArray(new Long[0]); while (true) { //判断是否刷课完成 long nowLen = getAcco(); if (nowLen == arr.length) { log.info("{}:正在考试课程>>>{}", user.getAccount(), myCourse.getCourse().getTitle()); AccountCacheCangHui cacheCangHui = (AccountCacheCangHui) user.getCache(); //获取考试 ExamJson examList = null; while ((examList = ExamAction.getExamList(user, String.valueOf(myCourse.getCourseId()))) == null) ; cacheCangHui.setExamJson(examList); for (ExamCourse examCours : examList.getExamCourses()) { boolean interceptFlag = false; //是否拦截,true为拦截,反之不拦截 if (user.getCoursesCostom() != null) {//是否配置了课程定制 if (user.getCoursesCostom().getCoursesSettings() != null) { //是否配置了指定课程配置文件 ArrayList<CoursesSetting> coursesSettings = user.getCoursesCostom().getCoursesSettings(); for (CoursesSetting coursesSetting : coursesSettings) { if (!coursesSetting.getName().equals(myCourse.getCourse().getTitle())) //是否有匹配的定制配置 continue; //是否包含指定考试 Set<String> includeExams = coursesSetting.getIncludeExams(); if (includeExams != null) { if (includeExams.size() != 0) { boolean resState = false;//标记 for (String includeExam : includeExams) { if (includeExam.equals(examCours.getTitle())) { //判断是否与当前考试标签相等 resState = true; break; } } interceptFlag = resState ? false : true; } } //是否包含排除指定考试 Set<String> excludeExams = coursesSetting.getExcludeExams(); if (excludeExams != null) { if (excludeExams.size() != 0) { boolean resState = false;//标记 for (String excludeExam : excludeExams) { if (excludeExam.equals(examCours.getTitle())) { //判断是否与当前考试标签相等 resState = true; break; } } interceptFlag = resState ? true : false; } } } } } if (interceptFlag)//是否触发拦截 continue; Integer id = examCours.getId(); StartExam startExam = null; while ((startExam = ExamAction.startExam(user, String.valueOf(id))) == null) ; if (startExam.getCode() == -1) {//代表考试考过了 log.info("{}:课程:{}考试失败!对应考试试卷{},失败原因:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), startExam.getMsg()); continue; } TopicRequest topicRequest = new TopicRequest(); topicRequest.setId(String.valueOf(id)); topicRequest.setExamId(String.valueOf(id)); List<TopicAnswer> list = new ArrayList<>(); topicRequest.setAnswers(list); //获取对应考试题目 LinkedHashMap<String, ExamTopic> examTopics = examCours.getExamTopics(); //答案装载 examTopics.forEach((k, v) -> { boolean flag = true; for (ExamItem examItem : v.getItem()) { if (v.getType() == 5) { flag = false; list.add(new TopicAnswer(List.of(examItem.getKey()), Long.parseLong(k))); break; } if (examItem.getIsCorrect() == true) { flag = false; list.add(new TopicAnswer(List.of(examItem.getValue()), Long.parseLong(k))); } } if (flag) { int choose = (int) (Math.random() * v.getItem().size()) + 0; list.add(new TopicAnswer(List.of(v.getItem().get(choose).getValue()), Long.parseLong(k))); } }); ExamSubmitResponse examSubmitResponse = null; while ((examSubmitResponse = ExamAction.submitExam(user, topicRequest)) == null) ; if (examSubmitResponse.getCode() != 0) { log.info("{}:课程:{}考试失败!对应考试试卷{},失败原因:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), startExam.getMsg()); continue; } log.info("{}:课程:{}考试成功!对应考试试卷{},服务器信息:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), examSubmitResponse.getMsg()); } break; } } }).start(); } private void update() { //详细页面获取进度并赋值-------------------------- CourseDetailData courseDetail = null; while ((courseDetail = CourseAction.getCourseDetail(user, myCourse.getCourse().getId())) == null) ; //章节 if (courseDetail.getChapters() != null)
package com.cbq.yatori.core.action.canghui; @Slf4j public class CourseStudyAction implements Runnable { private User user; private MyCourse myCourse; //当前课程的对象 //视屏 // private VideoRouter videoRouter; private Map<Long, RouterDatum> map = new HashMap<>(); private boolean newThread;//是否线程堵塞 private long studyInterval = 5; //单次提交学习时长 private Long accoVideo = 0L;//统计观看视屏数 public void toStudy() { CoursesCostom coursesCostom = user.getCoursesCostom(); //视屏刷课模式 switch (coursesCostom.getVideoModel()) { case 0 -> { accoVideo = (long) map.keySet().size(); } //普通模式 case 1 -> { if (newThread) { new Thread(this).start(); } else { log.info("{}:正在学习课程>>>{}", user.getAccount(), myCourse.getCourse().getTitle()); study1(); log.info("{}:{}学习完毕!", user.getAccount(), myCourse.getCourse().getTitle()); } } //暴力模式 case 2 -> { log.info("{}:正在学习课程>>>{}", user.getAccount(), myCourse.getCourse().getTitle()); study2(); } } //自动考试模式 switch (coursesCostom.getAutoExam()) { case 1 -> { autoExamAction(); } } } /** * 普通一个一个刷版本 */ public void study1() { AccountCacheCangHui cache = (AccountCacheCangHui) user.getCache(); Iterator<Long> iterator = map.keySet().iterator(); Long arr[] = map.keySet().toArray(new Long[0]); Arrays.sort(arr); for (int i = 0; i < arr.length; ++i) { Long videoId = arr[i]; RouterDatum routerDatum = map.get(videoId); long studyTime = routerDatum.getProgress();//当前学习时间 long videoDuration = routerDatum.getVideoDuration();//视屏总时长 String title = routerDatum.getName();//视屏名称 //循环开始学习 while (studyTime < videoDuration) { //这里根据账号账号登录状态进行策划行为 switch (cache.getStatus()) {//未登录则跳出 case 0 -> { log.info("账号未登录,禁止刷课!"); return; } case 2 -> {//如果登录超时,则堵塞等待 studyTime -= studyInterval; continue; } } SubmitStudyTimeRequest submitStudyTimeRequest = CourseAction.submitLearnTime(user, myCourse, videoId, studyTime); try { if (submitStudyTimeRequest != null) { if (submitStudyTimeRequest.getMsg().contains("登录超时")) { cache.setStatus(2); studyTime -= studyInterval; continue; } //成功提交 log.info("\n服务器端信息:>>>{}\n学习账号>>>{}\n学习平台>>>{}\n视屏名称>>>{}\n视屏总长度>>>{}\n当前学时>>>{}", ConverterSubmitStudyTime.toJsonString(submitStudyTimeRequest), user.getAccount(), user.getAccountType().name(), title, videoDuration, studyTime); } if (studyTime < videoDuration) { Thread.sleep(1000 * studyInterval); } } catch (JsonProcessingException e) { log.error(""); e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException(e); } //添加学时 studyTime += studyInterval; //更新数据 if (studyTime >= videoDuration) { if (submitStudyTimeRequest == null) studyTime -= studyInterval; else { // update(); Map<Long, RouterDatum> resRouterDatum = getNewRouterDatum(); studyTime = resRouterDatum.get(videoId).getProgress(); } } } addAcco(); } } /** * 暴力模式 */ public void study2() { AccountCacheCangHui cache = (AccountCacheCangHui) user.getCache(); Long arr[] = map.keySet().toArray(new Long[0]); for (int i = 0; i < arr.length; ++i) { Long videoId = arr[i]; new Thread(() -> { long resVideoId = videoId; RouterDatum routerDatum = map.get(resVideoId); long studyTime = routerDatum.getProgress() == 0 ? studyInterval : routerDatum.getProgress();//当前学习时间 long videoDuration = routerDatum.getVideoDuration();//视屏总时长 String title = routerDatum.getName();//视屏名称 //循环开始学习 while (studyTime < videoDuration) { //这里根据账号账号登录状态进行策划行为 switch (cache.getStatus()) {//未登录则跳出 case 0 -> { log.info("账号未登录,禁止刷课!"); return; } case 2 -> {//如果登录超时,则堵塞等待 studyTime -= studyInterval; continue; } } //添加学时 studyTime += studyInterval; SubmitStudyTimeRequest submitStudyTimeRequest = CourseAction.submitLearnTime(user, myCourse, resVideoId, studyTime); try { if (submitStudyTimeRequest != null) { if (submitStudyTimeRequest.getMsg().contains("登录超时")) { cache.setStatus(2); studyTime -= studyInterval; continue; } //成功提交 log.info("\n服务器端信息:>>>{}\n学习账号>>>{}\n学习平台>>>{}\n视屏名称>>>{}\n视屏总长度>>>{}\n当前学时>>>{}", ConverterSubmitStudyTime.toJsonString(submitStudyTimeRequest), user.getAccount(), user.getAccountType().name(), title, videoDuration, studyTime); } if (studyTime < videoDuration) { Thread.sleep(1000 * studyInterval); } } catch (JsonProcessingException e) { log.error(""); e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException(e); } //更新数据 if (studyTime >= videoDuration) { if (submitStudyTimeRequest == null) { studyTime -= studyInterval; }else{ //这一步进行网页视屏课程时长获取并赋值同步赋值 Map<Long, RouterDatum> newRouterDatum = getNewRouterDatum(); RouterDatum resRouterDatum = newRouterDatum.get(resVideoId); studyTime = resRouterDatum.getProgress(); } } } addAcco(); //判断是否刷课完成 if (getAcco() == arr.length) { log.info("{}:{}学习完毕!", user.getAccount(), myCourse.getCourse().getTitle()); } }).start(); } } /** * 自动考试 */ public void autoExamAction() { new Thread(() -> { Long arr[] = map.keySet().toArray(new Long[0]); while (true) { //判断是否刷课完成 long nowLen = getAcco(); if (nowLen == arr.length) { log.info("{}:正在考试课程>>>{}", user.getAccount(), myCourse.getCourse().getTitle()); AccountCacheCangHui cacheCangHui = (AccountCacheCangHui) user.getCache(); //获取考试 ExamJson examList = null; while ((examList = ExamAction.getExamList(user, String.valueOf(myCourse.getCourseId()))) == null) ; cacheCangHui.setExamJson(examList); for (ExamCourse examCours : examList.getExamCourses()) { boolean interceptFlag = false; //是否拦截,true为拦截,反之不拦截 if (user.getCoursesCostom() != null) {//是否配置了课程定制 if (user.getCoursesCostom().getCoursesSettings() != null) { //是否配置了指定课程配置文件 ArrayList<CoursesSetting> coursesSettings = user.getCoursesCostom().getCoursesSettings(); for (CoursesSetting coursesSetting : coursesSettings) { if (!coursesSetting.getName().equals(myCourse.getCourse().getTitle())) //是否有匹配的定制配置 continue; //是否包含指定考试 Set<String> includeExams = coursesSetting.getIncludeExams(); if (includeExams != null) { if (includeExams.size() != 0) { boolean resState = false;//标记 for (String includeExam : includeExams) { if (includeExam.equals(examCours.getTitle())) { //判断是否与当前考试标签相等 resState = true; break; } } interceptFlag = resState ? false : true; } } //是否包含排除指定考试 Set<String> excludeExams = coursesSetting.getExcludeExams(); if (excludeExams != null) { if (excludeExams.size() != 0) { boolean resState = false;//标记 for (String excludeExam : excludeExams) { if (excludeExam.equals(examCours.getTitle())) { //判断是否与当前考试标签相等 resState = true; break; } } interceptFlag = resState ? true : false; } } } } } if (interceptFlag)//是否触发拦截 continue; Integer id = examCours.getId(); StartExam startExam = null; while ((startExam = ExamAction.startExam(user, String.valueOf(id))) == null) ; if (startExam.getCode() == -1) {//代表考试考过了 log.info("{}:课程:{}考试失败!对应考试试卷{},失败原因:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), startExam.getMsg()); continue; } TopicRequest topicRequest = new TopicRequest(); topicRequest.setId(String.valueOf(id)); topicRequest.setExamId(String.valueOf(id)); List<TopicAnswer> list = new ArrayList<>(); topicRequest.setAnswers(list); //获取对应考试题目 LinkedHashMap<String, ExamTopic> examTopics = examCours.getExamTopics(); //答案装载 examTopics.forEach((k, v) -> { boolean flag = true; for (ExamItem examItem : v.getItem()) { if (v.getType() == 5) { flag = false; list.add(new TopicAnswer(List.of(examItem.getKey()), Long.parseLong(k))); break; } if (examItem.getIsCorrect() == true) { flag = false; list.add(new TopicAnswer(List.of(examItem.getValue()), Long.parseLong(k))); } } if (flag) { int choose = (int) (Math.random() * v.getItem().size()) + 0; list.add(new TopicAnswer(List.of(v.getItem().get(choose).getValue()), Long.parseLong(k))); } }); ExamSubmitResponse examSubmitResponse = null; while ((examSubmitResponse = ExamAction.submitExam(user, topicRequest)) == null) ; if (examSubmitResponse.getCode() != 0) { log.info("{}:课程:{}考试失败!对应考试试卷{},失败原因:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), startExam.getMsg()); continue; } log.info("{}:课程:{}考试成功!对应考试试卷{},服务器信息:{}", user.getAccount(), myCourse.getCourse().getTitle(), examCours.getTitle(), examSubmitResponse.getMsg()); } break; } } }).start(); } private void update() { //详细页面获取进度并赋值-------------------------- CourseDetailData courseDetail = null; while ((courseDetail = CourseAction.getCourseDetail(user, myCourse.getCourse().getId())) == null) ; //章节 if (courseDetail.getChapters() != null)
for (Chapter chapter : courseDetail.getChapters()) {
0
2023-10-30 04:15:41+00:00
8k
hezean/sustc
sustc-runner/src/main/java/io/sustc/command/DatabaseCommand.java
[ { "identifier": "BenchmarkService", "path": "sustc-runner/src/main/java/io/sustc/benchmark/BenchmarkService.java", "snippet": "@Service\n@Slf4j\npublic class BenchmarkService {\n\n @Autowired\n private BenchmarkConfig config;\n\n @Autowired\n private DatabaseService databaseService;\n\n @...
import io.sustc.benchmark.BenchmarkService; import io.sustc.service.DatabaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import java.util.List;
6,949
package io.sustc.command; @ShellComponent @ConditionalOnBean(DatabaseService.class) public class DatabaseCommand { @Autowired private DatabaseService databaseService; @Autowired
package io.sustc.command; @ShellComponent @ConditionalOnBean(DatabaseService.class) public class DatabaseCommand { @Autowired private DatabaseService databaseService; @Autowired
private BenchmarkService benchmarkService;
0
2023-10-27 03:27:20+00:00
8k
sgware/sabre
src/edu/uky/cs/nil/sabre/logic/Negation.java
[ { "identifier": "Settings", "path": "src/edu/uky/cs/nil/sabre/Settings.java", "snippet": "public class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final Str...
import java.util.function.Function; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.State; import edu.uky.cs.nil.sabre.Utilities;
5,512
package edu.uky.cs.nil.sabre.logic; /** * A negation is {@link Proposition proposition} whose value is the opposite of * its single {@code boolean} {@link #argument argument}. * * @author Stephen G. Ware */ public class Negation implements Proposition { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The argument whose value this negation will be the opposite of */ public final Expression argument; /** * Constructs a negation. * * @param argument the argument whose value this negation will be the * opposite of * @throws edu.uky.cs.nil.sabre.FormatException if the argument is not of * type {@code boolean} */ public Negation(Expression argument) { argument.mustBeBoolean(); this.argument = argument; } @Override public boolean equals(Object other) { if(getClass().equals(other.getClass())) return argument.equals(((Negation) other).argument); return false; } @Override public int hashCode() {
package edu.uky.cs.nil.sabre.logic; /** * A negation is {@link Proposition proposition} whose value is the opposite of * its single {@code boolean} {@link #argument argument}. * * @author Stephen G. Ware */ public class Negation implements Proposition { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The argument whose value this negation will be the opposite of */ public final Expression argument; /** * Constructs a negation. * * @param argument the argument whose value this negation will be the * opposite of * @throws edu.uky.cs.nil.sabre.FormatException if the argument is not of * type {@code boolean} */ public Negation(Expression argument) { argument.mustBeBoolean(); this.argument = argument; } @Override public boolean equals(Object other) { if(getClass().equals(other.getClass())) return argument.equals(((Negation) other).argument); return false; } @Override public int hashCode() {
return Utilities.hashCode(getClass(), argument);
2
2023-10-26 18:14:19+00:00
8k
sngular/pact-annotation-processor
src/main/java/com/sngular/annotation/processor/PactDslProcessor.java
[ { "identifier": "PactProcessorException", "path": "src/main/java/com/sngular/annotation/processor/exception/PactProcessorException.java", "snippet": "public class PactProcessorException extends RuntimeException {\n\n private static final String ERROR_MESSAGE = \"Error processing element %s\";\n\n publ...
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableMap; import com.sngular.annotation.pact.DslExclude; import com.sngular.annotation.pact.Example; import com.sngular.annotation.pact.PactDslBodyBuilder; import com.sngular.annotation.processor.exception.PactProcessorException; import com.sngular.annotation.processor.exception.TemplateFactoryException; import com.sngular.annotation.processor.exception.TemplateGenerationException; import com.sngular.annotation.processor.mapping.BigDecimalMapping; import com.sngular.annotation.processor.mapping.BigIntegerMapping; import com.sngular.annotation.processor.mapping.BooleanMapping; import com.sngular.annotation.processor.mapping.ByteMapping; import com.sngular.annotation.processor.mapping.CharMapping; import com.sngular.annotation.processor.mapping.DateMapping; import com.sngular.annotation.processor.mapping.DoubleMapping; import com.sngular.annotation.processor.mapping.FloatMapping; import com.sngular.annotation.processor.mapping.IntegerMapping; import com.sngular.annotation.processor.mapping.LongMapping; import com.sngular.annotation.processor.mapping.ShortMapping; import com.sngular.annotation.processor.mapping.StringMapping; import com.sngular.annotation.processor.mapping.TypeMapping; import com.sngular.annotation.processor.mapping.ZonedDateTimeMapping; import com.sngular.annotation.processor.model.ClassBuilderTemplate; import com.sngular.annotation.processor.model.DslComplexField; import com.sngular.annotation.processor.model.DslComplexTypeEnum; import com.sngular.annotation.processor.model.DslField; import com.sngular.annotation.processor.model.DslSimpleField; import com.sngular.annotation.processor.model.FieldValidations; import com.sngular.annotation.processor.template.ClasspathTemplateLoader; import com.sngular.annotation.processor.template.TemplateFactory; import freemarker.template.TemplateException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IterableUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; import org.jetbrains.annotations.NotNull;
5,800
/* * 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 com.sngular.annotation.processor; @Slf4j @AutoService(Processor.class) @SupportedAnnotationTypes("com.sngular.annotation.pact.PactDslBodyBuilder") public class PactDslProcessor extends AbstractProcessor {
/* * 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 com.sngular.annotation.processor; @Slf4j @AutoService(Processor.class) @SupportedAnnotationTypes("com.sngular.annotation.pact.PactDslBodyBuilder") public class PactDslProcessor extends AbstractProcessor {
static final Map<String, TypeMapping<?>> TYPE_MAPPING = ImmutableMap.<String, TypeMapping<?>>builder()
15
2023-10-25 14:36:38+00:00
8k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/command/argument/WorldArgument.java
[ { "identifier": "Sender", "path": "core/src/main/java/net/pl3x/map/core/command/Sender.java", "snippet": "public abstract class Sender implements ForwardingAudience.Single {\n private final Object sender;\n\n public <T> Sender(@NotNull T sender) {\n this.sender = sender;\n }\n\n @Supp...
import net.pl3x.map.core.command.exception.WorldParseException; import net.pl3x.map.core.player.Player; import net.pl3x.map.core.world.World; import org.jetbrains.annotations.NotNull; import cloud.commandframework.ArgumentDescription; import cloud.commandframework.arguments.CommandArgument; import cloud.commandframework.context.CommandContext; import java.util.List; import java.util.function.BiFunction; import net.pl3x.map.core.command.Sender; import net.pl3x.map.core.command.argument.parser.WorldParser;
6,142
/* * 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.argument; /** * A {@link World} argument that belongs to a command. * * @param <C> command sender type */ @SuppressWarnings("unused") public class WorldArgument<C> extends CommandArgument<@NotNull C, @NotNull World> { protected WorldArgument(boolean required, @NotNull String name, @NotNull String defaultValue, @NotNull BiFunction<@NotNull CommandContext<@NotNull C>, @NotNull String, @NotNull List<@NotNull String>> suggestionsProvider, @NotNull ArgumentDescription defaultDescription) { super(required, name, new WorldParser<>(), defaultValue, World.class, suggestionsProvider, defaultDescription); } /** * Create a new {@link WorldArgument} builder. * * @param name argument name * @return new world argument builder */ public static <C> CommandArgument.@NotNull Builder<@NotNull C, @NotNull World> builder(@NotNull String name) { return new WorldArgument.Builder<>(name); } /** * Create a required {@link WorldArgument}. * * @param name argument name * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> of(@NotNull String name) { return WorldArgument.<@NotNull C>builder(name).asRequired().build(); } /** * Create an optional {@link WorldArgument}. * <p> * All arguments prior to any other required argument must also be required. * * @param name argument name * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> optional(@NotNull String name) { return WorldArgument.<@NotNull C>builder(name).asOptional().build(); } /** * Create an optional {@link WorldArgument} with a default value. * <p> * All arguments prior to any other required argument must also be required. * * @param name argument name * @param defaultValue default value that will be used if none was supplied * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> optional(@NotNull String name, @NotNull String defaultValue) { return WorldArgument.<@NotNull C>builder(name).asOptionalWithDefault(defaultValue).build(); } /** * Resolve {@link World} from command context. * <p> * If context does not contain a {@link World} and the sender is a {@link Player} then the player's world will be used. * * @param context command context * @param name argument name * @return world * @throws WorldParseException if context did not contain a {@link World} * and the sender is not a {@link Player}, or * the world is not enabled */
/* * 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.argument; /** * A {@link World} argument that belongs to a command. * * @param <C> command sender type */ @SuppressWarnings("unused") public class WorldArgument<C> extends CommandArgument<@NotNull C, @NotNull World> { protected WorldArgument(boolean required, @NotNull String name, @NotNull String defaultValue, @NotNull BiFunction<@NotNull CommandContext<@NotNull C>, @NotNull String, @NotNull List<@NotNull String>> suggestionsProvider, @NotNull ArgumentDescription defaultDescription) { super(required, name, new WorldParser<>(), defaultValue, World.class, suggestionsProvider, defaultDescription); } /** * Create a new {@link WorldArgument} builder. * * @param name argument name * @return new world argument builder */ public static <C> CommandArgument.@NotNull Builder<@NotNull C, @NotNull World> builder(@NotNull String name) { return new WorldArgument.Builder<>(name); } /** * Create a required {@link WorldArgument}. * * @param name argument name * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> of(@NotNull String name) { return WorldArgument.<@NotNull C>builder(name).asRequired().build(); } /** * Create an optional {@link WorldArgument}. * <p> * All arguments prior to any other required argument must also be required. * * @param name argument name * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> optional(@NotNull String name) { return WorldArgument.<@NotNull C>builder(name).asOptional().build(); } /** * Create an optional {@link WorldArgument} with a default value. * <p> * All arguments prior to any other required argument must also be required. * * @param name argument name * @param defaultValue default value that will be used if none was supplied * @return constructed world argument */ public static <C> @NotNull CommandArgument<@NotNull C, @NotNull World> optional(@NotNull String name, @NotNull String defaultValue) { return WorldArgument.<@NotNull C>builder(name).asOptionalWithDefault(defaultValue).build(); } /** * Resolve {@link World} from command context. * <p> * If context does not contain a {@link World} and the sender is a {@link Player} then the player's world will be used. * * @param context command context * @param name argument name * @return world * @throws WorldParseException if context did not contain a {@link World} * and the sender is not a {@link Player}, or * the world is not enabled */
public static @NotNull World resolve(@NotNull CommandContext<@NotNull Sender> context, @NotNull String name) {
0
2023-10-26 01:14:31+00:00
8k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/score/SqlScoreServiceDefault.java
[ { "identifier": "SqlAnalysisResult", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysisResult.java", "snippet": "public class SqlAnalysisResult {\n\n /**\n * 执行序号\n */\n private Long id;\n\n /**\n * 查询类型\n */\n private String selectType;\n\n /**\n...
import com.jd.sql.analysis.analysis.SqlAnalysisResult; import com.jd.sql.analysis.analysis.SqlAnalysisResultList; import com.jd.sql.analysis.config.SqlAnalysisConfig; import com.jd.sql.analysis.rule.SqlScoreRule; import com.jd.sql.analysis.util.GsonUtil; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
4,402
package com.jd.sql.analysis.score; /** * @Author huhaitao21 * @Description 评分服务默认实现 * @Date 20:43 2022/11/1 **/ @Deprecated public class SqlScoreServiceDefault implements SqlScoreService { private static Logger logger = LoggerFactory.getLogger(SqlScoreServiceDefault.class); private static final Integer WARN_SCORE = 80; @Override public SqlScoreResult score(SqlAnalysisResultList sqlAnalysisResultList) { if (sqlAnalysisResultList == null || CollectionUtils.isEmpty(sqlAnalysisResultList.getResultList())) { return null; } //默认100分,扣分制 Integer score = 100; SqlScoreResult scoreResult = new SqlScoreResult(); List<SqlScoreResultDetail> analysisResults = new ArrayList<>(); //遍历分析结果,匹配评分规则 for (SqlAnalysisResult result : sqlAnalysisResultList.getResultList()) { List<SqlScoreResultDetail> detail = matchRule(result); if (CollectionUtils.isNotEmpty(detail)) { analysisResults.addAll(detail); } } //综合评分计算 for (SqlScoreResultDetail detail : analysisResults) { score = score - detail.getScoreDeduction(); if (score < 0) { //防止出现负分 score = 0; } if (score < WARN_SCORE) { scoreResult.setNeedWarn(true); } else { scoreResult.setNeedWarn(false); } } scoreResult.setScore(score); scoreResult.setAnalysisResults(analysisResults); logger.info("sql analysis result = " + GsonUtil.bean2Json(scoreResult)); return scoreResult; } /** * 规则匹配 返回 计算明细 * * @param result * @return */ private List<SqlScoreResultDetail> matchRule(SqlAnalysisResult result) { List<SqlScoreResultDetail> detailList = new ArrayList<>(); if (CollectionUtils.isEmpty(SqlAnalysisConfig.getRuleList())) { return null; }
package com.jd.sql.analysis.score; /** * @Author huhaitao21 * @Description 评分服务默认实现 * @Date 20:43 2022/11/1 **/ @Deprecated public class SqlScoreServiceDefault implements SqlScoreService { private static Logger logger = LoggerFactory.getLogger(SqlScoreServiceDefault.class); private static final Integer WARN_SCORE = 80; @Override public SqlScoreResult score(SqlAnalysisResultList sqlAnalysisResultList) { if (sqlAnalysisResultList == null || CollectionUtils.isEmpty(sqlAnalysisResultList.getResultList())) { return null; } //默认100分,扣分制 Integer score = 100; SqlScoreResult scoreResult = new SqlScoreResult(); List<SqlScoreResultDetail> analysisResults = new ArrayList<>(); //遍历分析结果,匹配评分规则 for (SqlAnalysisResult result : sqlAnalysisResultList.getResultList()) { List<SqlScoreResultDetail> detail = matchRule(result); if (CollectionUtils.isNotEmpty(detail)) { analysisResults.addAll(detail); } } //综合评分计算 for (SqlScoreResultDetail detail : analysisResults) { score = score - detail.getScoreDeduction(); if (score < 0) { //防止出现负分 score = 0; } if (score < WARN_SCORE) { scoreResult.setNeedWarn(true); } else { scoreResult.setNeedWarn(false); } } scoreResult.setScore(score); scoreResult.setAnalysisResults(analysisResults); logger.info("sql analysis result = " + GsonUtil.bean2Json(scoreResult)); return scoreResult; } /** * 规则匹配 返回 计算明细 * * @param result * @return */ private List<SqlScoreResultDetail> matchRule(SqlAnalysisResult result) { List<SqlScoreResultDetail> detailList = new ArrayList<>(); if (CollectionUtils.isEmpty(SqlAnalysisConfig.getRuleList())) { return null; }
for (SqlScoreRule sqlScoreRule : SqlAnalysisConfig.getRuleList()) {
3
2023-10-25 08:59:26+00:00
8k
easy-do/dnf-admin
be/src/main/java/plus/easydo/dnf/service/impl/DaChannelServiceImpl.java
[ { "identifier": "DebugFridaDto", "path": "be/src/main/java/plus/easydo/dnf/dto/DebugFridaDto.java", "snippet": "@Data\npublic class DebugFridaDto {\n\n private Long channelId;\n\n private String debugData;\n}" }, { "identifier": "UpdateScriptDto", "path": "be/src/main/java/plus/easydo/...
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.json.JSONUtil; import com.mybatisflex.core.paginate.Page; import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.spring.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import plus.easydo.dnf.dto.DebugFridaDto; import plus.easydo.dnf.dto.UpdateScriptDto; import plus.easydo.dnf.entity.DaChannel; import plus.easydo.dnf.enums.FridaMessageTypeEnum; import plus.easydo.dnf.exception.BaseException; import plus.easydo.dnf.mapper.DaChannelMapper; import plus.easydo.dnf.qo.ChannelQo; import plus.easydo.dnf.service.IDaChannelService; import plus.easydo.dnf.util.DockerUtil; import plus.easydo.dnf.vo.FcResult; import plus.easydo.dnf.websocket.FcWebSocketHandler; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static plus.easydo.dnf.entity.table.DaChannelTableDef.DA_CHANNEL;
6,679
package plus.easydo.dnf.service.impl; /** * 频道信息 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Slf4j @Service public class DaChannelServiceImpl extends ServiceImpl<DaChannelMapper, DaChannel> implements IDaChannelService { @Override public Page<DaChannel> pageChannel(ChannelQo channelQo) { QueryWrapper query = query() .select(DA_CHANNEL.ID, DA_CHANNEL.PID, DA_CHANNEL.CHANNEL_NAME, DA_CHANNEL.CHANNEL_STATUS, DA_CHANNEL.FRIDA_STATUS) .and(DA_CHANNEL.CHANNEL_NAME.like(channelQo.getChannelName())) .and(DA_CHANNEL.PID.like(channelQo.getPid())) .and(DA_CHANNEL.CHANNEL_STATUS.eq(channelQo.getChannelStatus())) .and(DA_CHANNEL.FRIDA_STATUS.eq(channelQo.getFridaStatus())); return page(new Page<>(channelQo.getCurrent(), channelQo.getPageSize()), query); } @Override public List<String> updateJs(UpdateScriptDto updateScriptDto) { DaChannel channel = getById(updateScriptDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } DaChannel entity = new DaChannel(); entity.setId(updateScriptDto.getChannelId()); entity.setScriptContext(updateScriptDto.getContext()); boolean updateResult = updateById(entity); if (updateResult && updateScriptDto.getRestartFrida()) { List<String> result = new ArrayList<>(); channel = getById(updateScriptDto.getChannelId()); List<String> removeRes = stopFrida(channel); result.addAll(removeRes); List<String> startResult = restartFrida(channel); result.addAll(startResult); return result; } return ListUtil.empty(); } @Override public List<String> updatePythonScript(UpdateScriptDto updateScriptDto) { DaChannel channel = getById(updateScriptDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } DaChannel entity = new DaChannel(); entity.setId(updateScriptDto.getChannelId()); entity.setMainPython(updateScriptDto.getContext()); boolean updateResult = updateById(entity); if (updateResult && updateScriptDto.getRestartFrida()) { List<String> result = new ArrayList<>(); channel = getById(updateScriptDto.getChannelId()); List<String> removeRes = stopFrida(channel); result.addAll(removeRes); List<String> startResult = restartFrida(channel); result.addAll(startResult); return result; } return ListUtil.empty(); } @Override public List<String> getFridaLog(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } return DockerUtil.getFridaClientLogs(channel.getChannelName()); } @Override public List<DaChannel> onlineList() { QueryWrapper queryWrapper = query().and(DA_CHANNEL.CHANNEL_STATUS.eq(true)).and(DA_CHANNEL.FRIDA_STATUS.eq(true)); return list(queryWrapper); } @Override public List<String> restartFrida(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } stopFrida(channel); return restartFrida(channel); } @Override public List<String> stopFrida(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } return stopFrida(channel); } @Override public void debugFrida(DebugFridaDto debugFridaDto) { DaChannel channel = getById(debugFridaDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } FcResult r = FcResult.builder().type(FridaMessageTypeEnum.DEBUG.getCode()).data(debugFridaDto.getDebugData()).build();
package plus.easydo.dnf.service.impl; /** * 频道信息 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Slf4j @Service public class DaChannelServiceImpl extends ServiceImpl<DaChannelMapper, DaChannel> implements IDaChannelService { @Override public Page<DaChannel> pageChannel(ChannelQo channelQo) { QueryWrapper query = query() .select(DA_CHANNEL.ID, DA_CHANNEL.PID, DA_CHANNEL.CHANNEL_NAME, DA_CHANNEL.CHANNEL_STATUS, DA_CHANNEL.FRIDA_STATUS) .and(DA_CHANNEL.CHANNEL_NAME.like(channelQo.getChannelName())) .and(DA_CHANNEL.PID.like(channelQo.getPid())) .and(DA_CHANNEL.CHANNEL_STATUS.eq(channelQo.getChannelStatus())) .and(DA_CHANNEL.FRIDA_STATUS.eq(channelQo.getFridaStatus())); return page(new Page<>(channelQo.getCurrent(), channelQo.getPageSize()), query); } @Override public List<String> updateJs(UpdateScriptDto updateScriptDto) { DaChannel channel = getById(updateScriptDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } DaChannel entity = new DaChannel(); entity.setId(updateScriptDto.getChannelId()); entity.setScriptContext(updateScriptDto.getContext()); boolean updateResult = updateById(entity); if (updateResult && updateScriptDto.getRestartFrida()) { List<String> result = new ArrayList<>(); channel = getById(updateScriptDto.getChannelId()); List<String> removeRes = stopFrida(channel); result.addAll(removeRes); List<String> startResult = restartFrida(channel); result.addAll(startResult); return result; } return ListUtil.empty(); } @Override public List<String> updatePythonScript(UpdateScriptDto updateScriptDto) { DaChannel channel = getById(updateScriptDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } DaChannel entity = new DaChannel(); entity.setId(updateScriptDto.getChannelId()); entity.setMainPython(updateScriptDto.getContext()); boolean updateResult = updateById(entity); if (updateResult && updateScriptDto.getRestartFrida()) { List<String> result = new ArrayList<>(); channel = getById(updateScriptDto.getChannelId()); List<String> removeRes = stopFrida(channel); result.addAll(removeRes); List<String> startResult = restartFrida(channel); result.addAll(startResult); return result; } return ListUtil.empty(); } @Override public List<String> getFridaLog(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } return DockerUtil.getFridaClientLogs(channel.getChannelName()); } @Override public List<DaChannel> onlineList() { QueryWrapper queryWrapper = query().and(DA_CHANNEL.CHANNEL_STATUS.eq(true)).and(DA_CHANNEL.FRIDA_STATUS.eq(true)); return list(queryWrapper); } @Override public List<String> restartFrida(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } stopFrida(channel); return restartFrida(channel); } @Override public List<String> stopFrida(Long id) { DaChannel channel = getById(id); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } return stopFrida(channel); } @Override public void debugFrida(DebugFridaDto debugFridaDto) { DaChannel channel = getById(debugFridaDto.getChannelId()); if (Objects.isNull(channel)) { throw new BaseException("频道不存在"); } FcResult r = FcResult.builder().type(FridaMessageTypeEnum.DEBUG.getCode()).data(debugFridaDto.getDebugData()).build();
FcWebSocketHandler.sendMessage(channel.getChannelName(), JSONUtil.toJsonStr(r));
10
2023-10-29 03:26:16+00:00
8k
d0ge/sessionless
src/main/java/one/d4d/sessionless/itsdangerous/model/DjangoSignedToken.java
[ { "identifier": "Algorithms", "path": "src/main/java/one/d4d/sessionless/itsdangerous/Algorithms.java", "snippet": "public enum Algorithms {\n @Expose @SerializedName(\"1\") SHA1(\"HmacSHA1\"),\n @Expose @SerializedName(\"2\") SHA224(\"HmacSHA224\"),\n @Expose @SerializedName(\"3\") SHA256(\"Hm...
import one.d4d.sessionless.itsdangerous.Algorithms; import one.d4d.sessionless.itsdangerous.Derivation; import one.d4d.sessionless.itsdangerous.MessageDerivation; import one.d4d.sessionless.itsdangerous.MessageDigestAlgorithm; import one.d4d.sessionless.utils.Utils;
3,862
package one.d4d.sessionless.itsdangerous.model; public class DjangoSignedToken extends DangerousSignedToken { public DjangoSignedToken(byte separator, String payload, String timestamp, String signature) {
package one.d4d.sessionless.itsdangerous.model; public class DjangoSignedToken extends DangerousSignedToken { public DjangoSignedToken(byte separator, String payload, String timestamp, String signature) {
super(separator, payload, timestamp, signature, Algorithms.SHA1, Derivation.DJANGO, MessageDerivation.NONE, MessageDigestAlgorithm.SHA1);
2
2023-10-30 09:12:06+00:00
8k
ballerina-platform/module-ballerinax-ibm.ibmmq
native/src/main/java/io/ballerina/lib/ibm.ibmmq/CommonUtils.java
[ { "identifier": "MQRFH2Header", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/headers/MQRFH2Header.java", "snippet": "public class MQRFH2Header {\n\n private static final BString FIELD_VALUES_FIELD = StringUtils.fromString(\"fieldValues\");\n private static final BString FOLDER_STRINGS_...
import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPropertyDescriptor; import com.ibm.mq.headers.MQHeaderList; import io.ballerina.lib.ibm.ibmmq.headers.MQRFH2Header; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.Runtime; import io.ballerina.runtime.api.creators.ErrorCreator; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Objects; import java.util.Optional; import static io.ballerina.lib.ibm.ibmmq.Constants.CORRELATION_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.BPROPERTY; import static io.ballerina.lib.ibm.ibmmq.Constants.BMESSAGE_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_COMPLETION_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_DETAILS; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_ERROR_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_REASON_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.EXPIRY_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FORMAT_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.IBMMQ_ERROR; import static io.ballerina.lib.ibm.ibmmq.Constants.MQCIH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQIIH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH2_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_HEADERS; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PAYLOAD; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PROPERTY; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PROPERTIES; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_TYPE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_CONTEXT; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_COPY_OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_SUPPORT; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_VERSION; import static io.ballerina.lib.ibm.ibmmq.Constants.PERSISTENCE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.PRIORITY_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.PROPERTY_DESCRIPTOR; import static io.ballerina.lib.ibm.ibmmq.Constants.PROPERTY_VALUE; import static io.ballerina.lib.ibm.ibmmq.Constants.PUT_APPLICATION_TYPE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.REPLY_TO_QM_NAME_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.REPLY_TO_QUEUE_NAME_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.WAIT_INTERVAL; import static io.ballerina.lib.ibm.ibmmq.ModuleUtils.getModule; import static io.ballerina.lib.ibm.ibmmq.headers.MQCIHHeader.createMQCIHHeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQIIHHeader.createMQIIHHeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQRFH2Header.createMQRFH2HeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQRFHHeader.createMQRFHHeaderFromBHeader;
6,569
BMap<BString, Object> properties = ValueCreator.createMapValue(TypeCreator .createMapType(TypeCreator.createRecordType(BPROPERTY, getModule(), 0, false, 0))); Enumeration<String> propertyNames = mqMessage.getPropertyNames("%"); for (String propertyName : Collections.list(propertyNames)) { BMap<BString, Object> property = ValueCreator.createRecordValue(getModule(), BPROPERTY); MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); Object propertyObject = mqMessage.getObjectProperty(propertyName, propertyDescriptor); if (propertyObject instanceof Integer intProperty) { property.put(PROPERTY_VALUE, intProperty.longValue()); } else if (propertyObject instanceof String stringProperty) { property.put(PROPERTY_VALUE, StringUtils.fromString(stringProperty)); } else if (propertyObject instanceof byte[] bytesProperty) { property.put(PROPERTY_VALUE, ValueCreator.createArrayValue(bytesProperty)); } else { property.put(PROPERTY_VALUE, propertyObject); } property.put(PROPERTY_DESCRIPTOR, populateDescriptorFromMQPropertyDescriptor(propertyDescriptor)); properties.put(StringUtils.fromString(propertyName), property); } return properties; } private static void populateMQProperties(BMap<BString, Object> properties, MQMessage mqMessage) { for (BString key : properties.getKeys()) { try { handlePropertyValue(properties, mqMessage, key); } catch (MQException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while setting message properties: %s", e.getMessage()), e); } } } @SuppressWarnings("unchecked") private static void handlePropertyValue(BMap<BString, Object> properties, MQMessage mqMessage, BString key) throws MQException { BMap<BString, Object> property = (BMap<BString, Object>) properties.getMapValue(key); MQPropertyDescriptor propertyDescriptor = defaultPropertyDescriptor; if (property.containsKey(PROPERTY_DESCRIPTOR)) { propertyDescriptor = getMQPropertyDescriptor( (BMap<BString, Object>) properties.getMapValue(PROPERTY_DESCRIPTOR)); } Object value = property.get(PROPERTY_VALUE); if (value instanceof Long longValue) { mqMessage.setIntProperty(key.getValue(), propertyDescriptor, longValue.intValue()); } else if (value instanceof Boolean booleanValue) { mqMessage.setBooleanProperty(key.getValue(), propertyDescriptor, booleanValue); } else if (value instanceof Byte byteValue) { mqMessage.setByteProperty(key.getValue(), propertyDescriptor, byteValue); } else if (value instanceof byte[] bytesValue) { mqMessage.setBytesProperty(key.getValue(), propertyDescriptor, bytesValue); } else if (value instanceof Float floatValue) { mqMessage.setFloatProperty(key.getValue(), propertyDescriptor, floatValue); } else if (value instanceof Double doubleValue) { mqMessage.setDoubleProperty(key.getValue(), propertyDescriptor, doubleValue); } else if (value instanceof BString stringValue) { mqMessage.setStringProperty(key.getValue(), propertyDescriptor, stringValue.getValue()); } } private static void assignOptionalFieldsToMqMessage(BMap<BString, Object> bMessage, MQMessage mqMessage) { if (bMessage.containsKey(FORMAT_FIELD)) { mqMessage.format = bMessage.getStringValue(FORMAT_FIELD).getValue(); } if (bMessage.containsKey(MESSAGE_ID_FIELD)) { mqMessage.messageId = bMessage.getArrayValue(MESSAGE_ID_FIELD).getByteArray(); } if (bMessage.containsKey(CORRELATION_ID_FIELD)) { mqMessage.correlationId = bMessage.getArrayValue(CORRELATION_ID_FIELD).getByteArray(); } if (bMessage.containsKey(EXPIRY_FIELD)) { mqMessage.expiry = bMessage.getIntValue(EXPIRY_FIELD).intValue(); } if (bMessage.containsKey(PRIORITY_FIELD)) { mqMessage.priority = bMessage.getIntValue(PRIORITY_FIELD).intValue(); } if (bMessage.containsKey(PERSISTENCE_FIELD)) { mqMessage.persistence = bMessage.getIntValue(PERSISTENCE_FIELD).intValue(); } if (bMessage.containsKey(MESSAGE_TYPE_FIELD)) { mqMessage.messageType = bMessage.getIntValue(MESSAGE_TYPE_FIELD).intValue(); } if (bMessage.containsKey(PUT_APPLICATION_TYPE_FIELD)) { mqMessage.putApplicationType = bMessage.getIntValue(PUT_APPLICATION_TYPE_FIELD).intValue(); } if (bMessage.containsKey(REPLY_TO_QUEUE_NAME_FIELD)) { mqMessage.replyToQueueName = bMessage.getStringValue(REPLY_TO_QUEUE_NAME_FIELD).getValue(); } if (bMessage.containsKey(REPLY_TO_QM_NAME_FIELD)) { mqMessage.replyToQueueManagerName = bMessage.getStringValue(REPLY_TO_QM_NAME_FIELD).getValue(); } } private static MQPropertyDescriptor getMQPropertyDescriptor(BMap<BString, Object> descriptor) { MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); if (descriptor.containsKey(PD_VERSION)) { propertyDescriptor.version = ((Long) descriptor.get(PD_VERSION)).intValue(); } if (descriptor.containsKey(PD_COPY_OPTIONS)) { propertyDescriptor.copyOptions = ((Long) descriptor.get(PD_COPY_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_OPTIONS)) { propertyDescriptor.options = ((Long) descriptor.get(PD_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_SUPPORT)) { propertyDescriptor.support = ((Long) descriptor.get(PD_SUPPORT)).intValue(); } if (descriptor.containsKey(PD_CONTEXT)) { propertyDescriptor.context = ((Long) descriptor.get(PD_CONTEXT)).intValue(); } return propertyDescriptor; } private static void populateMQHeaders(BArray bHeaders, MQMessage mqMessage) { MQHeaderList headerList = new MQHeaderList(); for (int i = 0; i < bHeaders.size(); i++) { BMap<BString, Object> bHeader = (BMap) bHeaders.get(i); HeaderType headerType = HeaderType.valueOf(bHeader.getType().getName()); switch (headerType) {
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.ibm.ibmmq; /** * {@code CommonUtils} contains the common utility functions for the Ballerina IBM MQ connector. */ public class CommonUtils { private static final MQPropertyDescriptor defaultPropertyDescriptor = new MQPropertyDescriptor(); private static final ArrayType BHeaderUnionType = TypeCreator.createArrayType( TypeCreator.createUnionType(List.of( TypeCreator.createRecordType(MQRFH2_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQRFH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQCIH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQIIH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0)))); public static MQMessage getMqMessageFromBMessage(BMap<BString, Object> bMessage) { MQMessage mqMessage = new MQMessage(); BMap<BString, Object> properties = (BMap<BString, Object>) bMessage.getMapValue(MESSAGE_PROPERTIES); if (Objects.nonNull(properties)) { populateMQProperties(properties, mqMessage); } BArray headers = bMessage.getArrayValue(MESSAGE_HEADERS); if (Objects.nonNull(headers)) { populateMQHeaders(headers, mqMessage); } byte[] payload = bMessage.getArrayValue(MESSAGE_PAYLOAD).getBytes(); assignOptionalFieldsToMqMessage(bMessage, mqMessage); try { mqMessage.write(payload); } catch (IOException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while populating payload: %s", e.getMessage()), e); } return mqMessage; } public static BMap<BString, Object> getBMessageFromMQMessage(Runtime runtime, MQMessage mqMessage) { BMap<BString, Object> bMessage = ValueCreator.createRecordValue(getModule(), BMESSAGE_NAME); try { bMessage.put(MESSAGE_HEADERS, getBHeaders(runtime, mqMessage)); bMessage.put(MESSAGE_PROPERTY, getBProperties(mqMessage)); bMessage.put(FORMAT_FIELD, StringUtils.fromString(mqMessage.format)); bMessage.put(MESSAGE_ID_FIELD, ValueCreator.createArrayValue(mqMessage.messageId)); bMessage.put(CORRELATION_ID_FIELD, ValueCreator.createArrayValue((mqMessage.correlationId))); bMessage.put(EXPIRY_FIELD, mqMessage.expiry); bMessage.put(PRIORITY_FIELD, mqMessage.priority); bMessage.put(PERSISTENCE_FIELD, mqMessage.persistence); bMessage.put(MESSAGE_TYPE_FIELD, mqMessage.messageType); bMessage.put(PUT_APPLICATION_TYPE_FIELD, mqMessage.putApplicationType); bMessage.put(REPLY_TO_QUEUE_NAME_FIELD, StringUtils.fromString(mqMessage.replyToQueueName.strip())); bMessage.put(REPLY_TO_QM_NAME_FIELD, StringUtils.fromString(mqMessage.replyToQueueManagerName.strip())); byte[] payload = mqMessage.readStringOfByteLength(mqMessage.getDataLength()) .getBytes(StandardCharsets.UTF_8); bMessage.put(MESSAGE_PAYLOAD, ValueCreator.createArrayValue(payload)); return bMessage; } catch (MQException | IOException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while reading the message: %s", e.getMessage()), e); } } private static BMap<BString, Object> getBProperties(MQMessage mqMessage) throws MQException { BMap<BString, Object> properties = ValueCreator.createMapValue(TypeCreator .createMapType(TypeCreator.createRecordType(BPROPERTY, getModule(), 0, false, 0))); Enumeration<String> propertyNames = mqMessage.getPropertyNames("%"); for (String propertyName : Collections.list(propertyNames)) { BMap<BString, Object> property = ValueCreator.createRecordValue(getModule(), BPROPERTY); MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); Object propertyObject = mqMessage.getObjectProperty(propertyName, propertyDescriptor); if (propertyObject instanceof Integer intProperty) { property.put(PROPERTY_VALUE, intProperty.longValue()); } else if (propertyObject instanceof String stringProperty) { property.put(PROPERTY_VALUE, StringUtils.fromString(stringProperty)); } else if (propertyObject instanceof byte[] bytesProperty) { property.put(PROPERTY_VALUE, ValueCreator.createArrayValue(bytesProperty)); } else { property.put(PROPERTY_VALUE, propertyObject); } property.put(PROPERTY_DESCRIPTOR, populateDescriptorFromMQPropertyDescriptor(propertyDescriptor)); properties.put(StringUtils.fromString(propertyName), property); } return properties; } private static void populateMQProperties(BMap<BString, Object> properties, MQMessage mqMessage) { for (BString key : properties.getKeys()) { try { handlePropertyValue(properties, mqMessage, key); } catch (MQException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while setting message properties: %s", e.getMessage()), e); } } } @SuppressWarnings("unchecked") private static void handlePropertyValue(BMap<BString, Object> properties, MQMessage mqMessage, BString key) throws MQException { BMap<BString, Object> property = (BMap<BString, Object>) properties.getMapValue(key); MQPropertyDescriptor propertyDescriptor = defaultPropertyDescriptor; if (property.containsKey(PROPERTY_DESCRIPTOR)) { propertyDescriptor = getMQPropertyDescriptor( (BMap<BString, Object>) properties.getMapValue(PROPERTY_DESCRIPTOR)); } Object value = property.get(PROPERTY_VALUE); if (value instanceof Long longValue) { mqMessage.setIntProperty(key.getValue(), propertyDescriptor, longValue.intValue()); } else if (value instanceof Boolean booleanValue) { mqMessage.setBooleanProperty(key.getValue(), propertyDescriptor, booleanValue); } else if (value instanceof Byte byteValue) { mqMessage.setByteProperty(key.getValue(), propertyDescriptor, byteValue); } else if (value instanceof byte[] bytesValue) { mqMessage.setBytesProperty(key.getValue(), propertyDescriptor, bytesValue); } else if (value instanceof Float floatValue) { mqMessage.setFloatProperty(key.getValue(), propertyDescriptor, floatValue); } else if (value instanceof Double doubleValue) { mqMessage.setDoubleProperty(key.getValue(), propertyDescriptor, doubleValue); } else if (value instanceof BString stringValue) { mqMessage.setStringProperty(key.getValue(), propertyDescriptor, stringValue.getValue()); } } private static void assignOptionalFieldsToMqMessage(BMap<BString, Object> bMessage, MQMessage mqMessage) { if (bMessage.containsKey(FORMAT_FIELD)) { mqMessage.format = bMessage.getStringValue(FORMAT_FIELD).getValue(); } if (bMessage.containsKey(MESSAGE_ID_FIELD)) { mqMessage.messageId = bMessage.getArrayValue(MESSAGE_ID_FIELD).getByteArray(); } if (bMessage.containsKey(CORRELATION_ID_FIELD)) { mqMessage.correlationId = bMessage.getArrayValue(CORRELATION_ID_FIELD).getByteArray(); } if (bMessage.containsKey(EXPIRY_FIELD)) { mqMessage.expiry = bMessage.getIntValue(EXPIRY_FIELD).intValue(); } if (bMessage.containsKey(PRIORITY_FIELD)) { mqMessage.priority = bMessage.getIntValue(PRIORITY_FIELD).intValue(); } if (bMessage.containsKey(PERSISTENCE_FIELD)) { mqMessage.persistence = bMessage.getIntValue(PERSISTENCE_FIELD).intValue(); } if (bMessage.containsKey(MESSAGE_TYPE_FIELD)) { mqMessage.messageType = bMessage.getIntValue(MESSAGE_TYPE_FIELD).intValue(); } if (bMessage.containsKey(PUT_APPLICATION_TYPE_FIELD)) { mqMessage.putApplicationType = bMessage.getIntValue(PUT_APPLICATION_TYPE_FIELD).intValue(); } if (bMessage.containsKey(REPLY_TO_QUEUE_NAME_FIELD)) { mqMessage.replyToQueueName = bMessage.getStringValue(REPLY_TO_QUEUE_NAME_FIELD).getValue(); } if (bMessage.containsKey(REPLY_TO_QM_NAME_FIELD)) { mqMessage.replyToQueueManagerName = bMessage.getStringValue(REPLY_TO_QM_NAME_FIELD).getValue(); } } private static MQPropertyDescriptor getMQPropertyDescriptor(BMap<BString, Object> descriptor) { MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); if (descriptor.containsKey(PD_VERSION)) { propertyDescriptor.version = ((Long) descriptor.get(PD_VERSION)).intValue(); } if (descriptor.containsKey(PD_COPY_OPTIONS)) { propertyDescriptor.copyOptions = ((Long) descriptor.get(PD_COPY_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_OPTIONS)) { propertyDescriptor.options = ((Long) descriptor.get(PD_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_SUPPORT)) { propertyDescriptor.support = ((Long) descriptor.get(PD_SUPPORT)).intValue(); } if (descriptor.containsKey(PD_CONTEXT)) { propertyDescriptor.context = ((Long) descriptor.get(PD_CONTEXT)).intValue(); } return propertyDescriptor; } private static void populateMQHeaders(BArray bHeaders, MQMessage mqMessage) { MQHeaderList headerList = new MQHeaderList(); for (int i = 0; i < bHeaders.size(); i++) { BMap<BString, Object> bHeader = (BMap) bHeaders.get(i); HeaderType headerType = HeaderType.valueOf(bHeader.getType().getName()); switch (headerType) {
case MQRFH2 -> headerList.add(createMQRFH2HeaderFromBHeader(bHeader));
4
2023-10-27 05:54:44+00:00
8k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/core/PlayerAgent.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 net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.api.math.vector.Vector3d; import net.leawind.mc.util.math.LMath; import net.leawind.mc.util.math.smoothvalue.SmoothDouble; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; import net.minecraft.client.player.LocalPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.item.Items; import org.apache.logging.log4j.util.PerformanceSensitive; import org.jetbrains.annotations.NotNull;
4,886
package net.leawind.mc.thirdperson.core; public final class PlayerAgent { public static final @NotNull Vector2d impulseHorizon = Vector2d.of(0); public static final @NotNull Vector3d impulse = Vector3d.of(0); public static final @NotNull SmoothDouble smoothXRot = new SmoothDouble(d -> d); public static boolean wasInterecting = false; public static boolean wasAiming = false; public static void updateSmoothRotations (double period) { } public static void applySmoothRotations () { LocalPlayer player = Minecraft.getInstance().player; if (player != null) { player.setXRot(player.xRotO = (float)smoothXRot.get(ThirdPerson.lastPartialTick)); } } public static void reset () { Minecraft mc = Minecraft.getInstance(); ThirdPerson.lastPartialTick = mc.getFrameTime(); if (mc.cameraEntity != null) { // 将虚拟球心放在实体眼睛处 CameraAgent.smoothEyePosition.set(LMath.toVector3d(mc.cameraEntity.getEyePosition(ThirdPerson.lastPartialTick))); if (mc.player != null) { resetSmoothRotations(); } } } public static void resetSmoothRotations () { Minecraft mc = Minecraft.getInstance(); if (mc.player != null) { smoothXRot.set(mc.player.getXRot()); } } /** * 玩家移动时自动转向移动方向 */ @PerformanceSensitive public static void onServerAiStep () { Minecraft mc = Minecraft.getInstance();
package net.leawind.mc.thirdperson.core; public final class PlayerAgent { public static final @NotNull Vector2d impulseHorizon = Vector2d.of(0); public static final @NotNull Vector3d impulse = Vector3d.of(0); public static final @NotNull SmoothDouble smoothXRot = new SmoothDouble(d -> d); public static boolean wasInterecting = false; public static boolean wasAiming = false; public static void updateSmoothRotations (double period) { } public static void applySmoothRotations () { LocalPlayer player = Minecraft.getInstance().player; if (player != null) { player.setXRot(player.xRotO = (float)smoothXRot.get(ThirdPerson.lastPartialTick)); } } public static void reset () { Minecraft mc = Minecraft.getInstance(); ThirdPerson.lastPartialTick = mc.getFrameTime(); if (mc.cameraEntity != null) { // 将虚拟球心放在实体眼睛处 CameraAgent.smoothEyePosition.set(LMath.toVector3d(mc.cameraEntity.getEyePosition(ThirdPerson.lastPartialTick))); if (mc.player != null) { resetSmoothRotations(); } } } public static void resetSmoothRotations () { Minecraft mc = Minecraft.getInstance(); if (mc.player != null) { smoothXRot.set(mc.player.getXRot()); } } /** * 玩家移动时自动转向移动方向 */ @PerformanceSensitive public static void onServerAiStep () { Minecraft mc = Minecraft.getInstance();
Config config = ThirdPerson.getConfig();
1
2023-10-31 05:52:36+00:00
8k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/consumers/MediaObjectTransferListenerTest.java
[ { "identifier": "MediaController", "path": "backend/src/main/java/com/example/mediaarchival/controllers/MediaController.java", "snippet": "@RestController\n@RequestMapping(\"/api/media-objects\")\npublic class MediaController {\n private final MediaRepository mediaRepository;\n\n private final JmsTemp...
import static org.mockito.Mockito.*; import com.example.mediaarchival.controllers.MediaController; import com.example.mediaarchival.enums.ArchivedStatus; import com.example.mediaarchival.models.MediaModel; import com.example.mediaarchival.repositories.MediaRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import software.amazon.awssdk.transfer.s3.progress.TransferListener; import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
6,482
package com.example.mediaarchival.consumers; public class MediaObjectTransferListenerTest { @Mock private MediaRepository mediaRepository; @Mock private MediaController mediaController;
package com.example.mediaarchival.consumers; public class MediaObjectTransferListenerTest { @Mock private MediaRepository mediaRepository; @Mock private MediaController mediaController;
@Mock private MediaModel mediaObject;
2
2023-10-27 01:54:57+00:00
8k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/controller/admin/AdminGoodsSpecificationController.java
[ { "identifier": "GoodsSpecificationService", "path": "siam-goods/goods-provider/src/main/java/com/siam/package_goods/service/GoodsSpecificationService.java", "snippet": "public interface GoodsSpecificationService {\n int countByExample(GoodsSpecificationExample example);\n\n void deleteByPrimaryKe...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_goods.service.GoodsSpecificationService; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_goods.entity.GoodsSpecification; import com.siam.package_goods.model.example.GoodsSpecificationExample; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
5,502
package com.siam.package_goods.controller.admin; @RestController @RequestMapping(value = "/rest/admin/goodsSpecification") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商品规格模块相关接口", description = "AdminGoodsSpecificationController") public class AdminGoodsSpecificationController { @Autowired private GoodsSpecificationService goodsSpecificationService; @ApiOperation(value = "商品规格列表") @PostMapping(value = "/list")
package com.siam.package_goods.controller.admin; @RestController @RequestMapping(value = "/rest/admin/goodsSpecification") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商品规格模块相关接口", description = "AdminGoodsSpecificationController") public class AdminGoodsSpecificationController { @Autowired private GoodsSpecificationService goodsSpecificationService; @ApiOperation(value = "商品规格列表") @PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) GoodsSpecification param){
4
2023-10-26 10:45:10+00:00
8k
SealParadise/Andrade-S-AES
Code/S-AES/src/main/java/org/aes/controller/IndexController.java
[ { "identifier": "CBC", "path": "Code/S-AES/src/main/java/org/aes/cipher/CBC.java", "snippet": "public class CBC {\r\n //初始化编码器\r\n Encoder encoder = new Encoder();\r\n //初始化解码器\r\n Decoder decoder = new Decoder();\r\n //初始化通用操作对象\r\n Common common = new Common();\r\n\r\n /*\r\n C...
import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import org.aes.cipher.CBC; import org.aes.cipher.Decoder; import org.aes.cipher.Encoder; import org.aes.cipher.MeetInTheMid; import org.aes.commen.Common; import java.util.ArrayList; import java.util.List;
5,629
package org.aes.controller; public class IndexController { //初始化通用操作对象 Common common = new Common(); //初始化解码器
package org.aes.controller; public class IndexController { //初始化通用操作对象 Common common = new Common(); //初始化解码器
Decoder decoder = new Decoder();
1
2023-10-27 09:38:12+00:00
8k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/hardwarekeyboard/HardwareKeyboardSpecification.java
[ { "identifier": "KeyEventInterface", "path": "app/src/main/java/sh/eliza/japaneseinput/KeycodeConverter.java", "snippet": "public interface KeyEventInterface {\n int getKeyCode();\n\n Optional<android.view.KeyEvent> getNativeEvent();\n}" }, { "identifier": "MozcLog", "path": "app/src/main/...
import android.content.SharedPreferences; import android.content.res.Configuration; import android.view.KeyEvent; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.KeyEvent.ModifierKey; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.KeyEvent.SpecialKey; import sh.eliza.japaneseinput.KeycodeConverter.KeyEventInterface; import sh.eliza.japaneseinput.MozcLog; import sh.eliza.japaneseinput.hardwarekeyboard.HardwareKeyboard.CompositionSwitchMode; import sh.eliza.japaneseinput.hardwarekeyboard.KeyEventMapperFactory.KeyEventMapper; import sh.eliza.japaneseinput.keyboard.Keyboard.KeyboardSpecification; import sh.eliza.japaneseinput.preference.ClientSidePreference.HardwareKeyMap; import sh.eliza.japaneseinput.preference.PreferenceUtil;
4,085
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 sh.eliza.japaneseinput.hardwarekeyboard; /** * Converts Hardware KeyEvent to Mozc's KeyEvent * * <p>Android OS's keyboard management is like following; * * <ol> * <li>Android OS receives LKC (Linux Key Code, ≒ scan code) from the keyboard. * <li>Android OS converts LKC into AKC (Android Key Code) using key layout file (.kl). A * user/developer cannot override this behavior. * <li>Android OS converts AKC into a tuple of (AKC, unicode character) using key character * mapping file (.kcm). * <ul> * <li>Given AKC might be converted into another AKC (e.g. KEYCODE_GRAVE might be converted * into KEYCODE_ZENKAKU_HANKAKU). * <li>Since API Level 16 a user/developer has been able to override the behavior. * </ul> * </ol> * * To use Japanese keyboard, the default behavior is not sufficient. * * <ul> * <li>Even the latest OS (API Level 19) Japanese key character mapping is not shipped by default. * <li>There are Japanese unique AKC (e.g. KEYCODE_ZENKAKU_HANKAKU) but they are available since * API Level 16. (Note since API Level 16 some Japanese unique ones (e.g. KEYCODE_RO) can be * sent though Japanese KCM is not supported) * </ul> * * The main responsibility of this class is to convert android's KeyEvent into Mozc's KeyEvent. To * do this above behavior must be respected. CompactKeyEvent (and its internal KeyEventMapper) does * this. */ public enum HardwareKeyboardSpecification { /** System key map. */ DEFAULT( HardwareKeyMap.DEFAULT, KeyEventMapperFactory.DEFAULT_KEYBOARD_MAPPER, KeyboardSpecification.HARDWARE_QWERTY_KANA, KeyboardSpecification.HARDWARE_QWERTY_ALPHABET), /** Represents Japanese 109 Keyboard */ JAPANESE109A( HardwareKeyMap.JAPANESE109A, KeyEventMapperFactory.JAPANESE_KEYBOARD_MAPPER, KeyboardSpecification.HARDWARE_QWERTY_KANA, KeyboardSpecification.HARDWARE_QWERTY_ALPHABET); /** * Returns true if the given {@code codepoint} is printable. * * <p>{@link KeyEvent#isPrintingKey()} cannot be used for this purpose as the method doesn't take * codepoint but keycode. */ private static boolean isPrintable(int codepoint) { Preconditions.checkArgument(codepoint >= 0); if (Character.isISOControl(codepoint)) { return false; } Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); return block != null && block != Character.UnicodeBlock.SPECIALS; } /** Returns true if composition mode should be changed. */ private static boolean isKeyForCompositinoModeChange(int keyCode, int metaState) { boolean shift = (metaState & KeyEvent.META_SHIFT_MASK) != 0; boolean alt = (metaState & KeyEvent.META_ALT_MASK) != 0; boolean ctrl = (metaState & KeyEvent.META_CTRL_MASK) != 0; boolean meta = (metaState & KeyEvent.META_META_MASK) != 0; // ZEN/HAN with no modifier. if (keyCode == KeyEvent.KEYCODE_ZENKAKU_HANKAKU && !shift && !alt && !ctrl && !meta) { return true; } // GRAVE with ALT. return keyCode == KeyEvent.KEYCODE_GRAVE && !shift && alt && !ctrl && !meta; } private final HardwareKeyMap hardwareKeyMap; private final KeyboardSpecification kanaKeyboardSpecification; private final KeyboardSpecification alphabetKeyboardSpecification;
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 sh.eliza.japaneseinput.hardwarekeyboard; /** * Converts Hardware KeyEvent to Mozc's KeyEvent * * <p>Android OS's keyboard management is like following; * * <ol> * <li>Android OS receives LKC (Linux Key Code, ≒ scan code) from the keyboard. * <li>Android OS converts LKC into AKC (Android Key Code) using key layout file (.kl). A * user/developer cannot override this behavior. * <li>Android OS converts AKC into a tuple of (AKC, unicode character) using key character * mapping file (.kcm). * <ul> * <li>Given AKC might be converted into another AKC (e.g. KEYCODE_GRAVE might be converted * into KEYCODE_ZENKAKU_HANKAKU). * <li>Since API Level 16 a user/developer has been able to override the behavior. * </ul> * </ol> * * To use Japanese keyboard, the default behavior is not sufficient. * * <ul> * <li>Even the latest OS (API Level 19) Japanese key character mapping is not shipped by default. * <li>There are Japanese unique AKC (e.g. KEYCODE_ZENKAKU_HANKAKU) but they are available since * API Level 16. (Note since API Level 16 some Japanese unique ones (e.g. KEYCODE_RO) can be * sent though Japanese KCM is not supported) * </ul> * * The main responsibility of this class is to convert android's KeyEvent into Mozc's KeyEvent. To * do this above behavior must be respected. CompactKeyEvent (and its internal KeyEventMapper) does * this. */ public enum HardwareKeyboardSpecification { /** System key map. */ DEFAULT( HardwareKeyMap.DEFAULT, KeyEventMapperFactory.DEFAULT_KEYBOARD_MAPPER, KeyboardSpecification.HARDWARE_QWERTY_KANA, KeyboardSpecification.HARDWARE_QWERTY_ALPHABET), /** Represents Japanese 109 Keyboard */ JAPANESE109A( HardwareKeyMap.JAPANESE109A, KeyEventMapperFactory.JAPANESE_KEYBOARD_MAPPER, KeyboardSpecification.HARDWARE_QWERTY_KANA, KeyboardSpecification.HARDWARE_QWERTY_ALPHABET); /** * Returns true if the given {@code codepoint} is printable. * * <p>{@link KeyEvent#isPrintingKey()} cannot be used for this purpose as the method doesn't take * codepoint but keycode. */ private static boolean isPrintable(int codepoint) { Preconditions.checkArgument(codepoint >= 0); if (Character.isISOControl(codepoint)) { return false; } Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); return block != null && block != Character.UnicodeBlock.SPECIALS; } /** Returns true if composition mode should be changed. */ private static boolean isKeyForCompositinoModeChange(int keyCode, int metaState) { boolean shift = (metaState & KeyEvent.META_SHIFT_MASK) != 0; boolean alt = (metaState & KeyEvent.META_ALT_MASK) != 0; boolean ctrl = (metaState & KeyEvent.META_CTRL_MASK) != 0; boolean meta = (metaState & KeyEvent.META_META_MASK) != 0; // ZEN/HAN with no modifier. if (keyCode == KeyEvent.KEYCODE_ZENKAKU_HANKAKU && !shift && !alt && !ctrl && !meta) { return true; } // GRAVE with ALT. return keyCode == KeyEvent.KEYCODE_GRAVE && !shift && alt && !ctrl && !meta; } private final HardwareKeyMap hardwareKeyMap; private final KeyboardSpecification kanaKeyboardSpecification; private final KeyboardSpecification alphabetKeyboardSpecification;
private final KeyEventMapper keyEventMapper;
3
2023-10-25 07:33:25+00:00
8k
Lyn4ever29/halo-plugin-export-md
src/main/java/cn/lyn4ever/export2md/rest/ExportController.java
[ { "identifier": "ExportLogSchema", "path": "src/main/java/cn/lyn4ever/export2md/schema/ExportLogSchema.java", "snippet": "@Data\n@ToString\n@EqualsAndHashCode(callSuper = true)\n@GVK(kind = \"ExportLog\", group = \"cn.lyn4ever.export2doc\",\n version = \"v1alpha1\", singular = \"exportLog\", plural =...
import cn.lyn4ever.export2md.schema.ExportLogSchema; import cn.lyn4ever.export2md.service.impl.ExportServiceImpl; import cn.lyn4ever.export2md.util.FileUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ZeroCopyHttpOutputMessage; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import run.halo.app.extension.ExtensionClient; import run.halo.app.extension.Metadata; import run.halo.app.extension.ReactiveExtensionClient; import run.halo.app.plugin.ApiVersion; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Arrays; import java.util.Date;
4,172
package cn.lyn4ever.export2md.rest; /** * 自定义导出接口 * * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/11/1 */ @ApiVersion("v1alpha1") @RequestMapping("/doExport") @RestController @Slf4j public class ExportController { // /apis/plugin.api.halo.run/v1alpha1/plugins/export-anything/doExport/** private final String EXPORT_ONE_DIR = "markdown_post"; @Autowired private ExportServiceImpl exportService; @Autowired private ReactiveExtensionClient reactiveClient; @Autowired private ExtensionClient commonClient; @PostMapping("/export") public Mono<ExportLogSchema> export(@RequestBody final ExportLogSchema exportLogSchema) { exportLogSchema.setCreateTime(new Date()); exportLogSchema.setStatus("b"); //设置元数据才能保存 exportLogSchema.setMetadata(new Metadata()); exportLogSchema.getMetadata().setName(exportLogSchema.getName()); return reactiveClient.create(exportLogSchema).doOnSuccess( exportLogSchema1 -> { Thread t = new Thread(() -> { exportService.runTask(exportLogSchema); }); t.start(); } ); } /** * 导出单篇文章 * * @param name * @return */ @GetMapping("/export_one/{name}") public Mono<Void> fetchHeadContent(@PathVariable("name") String name, ServerHttpResponse response) throws UnsupportedEncodingException { return Mono.fromCallable(() -> { //写文件 String fileName = exportService.writePost(name, EXPORT_ONE_DIR); File file = new File(fileName); ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response; HttpHeaders headers = zeroCopyResponse.getHeaders(); headers.set("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8)); headers.set("file-name", URLEncoder.encode(file.getName(), StandardCharsets.UTF_8)); headers.set("Access-Control-Allow-Origin", "*"); MediaType application = new MediaType("application", "octet-stream", StandardCharsets.UTF_8); headers.setContentType(application); zeroCopyResponse.writeWith(file, 0, file.length()).subscribe(); return ""; }) .publishOn(Schedulers.boundedElastic()).then(); } @PostMapping("/del") public Mono<Void> delete(@RequestBody String[] names) { Arrays.stream(names).parallel().forEach(name -> reactiveClient.fetch(ExportLogSchema.class, name) .publishOn(Schedulers.boundedElastic()) .doOnSuccess(exportLogSchema -> { reactiveClient.delete(exportLogSchema).doOnSuccess(exportLogSchema1 -> { //删除文件 exportService.delete(name); }).subscribe(); }).subscribe()); return Mono.empty(); } @GetMapping("/down/{path}") public Mono<Void> down(@PathVariable("path") String path, ServerHttpResponse response) { if (StringUtils.isBlank(path)) { return Mono.empty(); } if (path.split("\\.").length > 2) { //包含太多.的路径,不可下载 return Mono.empty(); }
package cn.lyn4ever.export2md.rest; /** * 自定义导出接口 * * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/11/1 */ @ApiVersion("v1alpha1") @RequestMapping("/doExport") @RestController @Slf4j public class ExportController { // /apis/plugin.api.halo.run/v1alpha1/plugins/export-anything/doExport/** private final String EXPORT_ONE_DIR = "markdown_post"; @Autowired private ExportServiceImpl exportService; @Autowired private ReactiveExtensionClient reactiveClient; @Autowired private ExtensionClient commonClient; @PostMapping("/export") public Mono<ExportLogSchema> export(@RequestBody final ExportLogSchema exportLogSchema) { exportLogSchema.setCreateTime(new Date()); exportLogSchema.setStatus("b"); //设置元数据才能保存 exportLogSchema.setMetadata(new Metadata()); exportLogSchema.getMetadata().setName(exportLogSchema.getName()); return reactiveClient.create(exportLogSchema).doOnSuccess( exportLogSchema1 -> { Thread t = new Thread(() -> { exportService.runTask(exportLogSchema); }); t.start(); } ); } /** * 导出单篇文章 * * @param name * @return */ @GetMapping("/export_one/{name}") public Mono<Void> fetchHeadContent(@PathVariable("name") String name, ServerHttpResponse response) throws UnsupportedEncodingException { return Mono.fromCallable(() -> { //写文件 String fileName = exportService.writePost(name, EXPORT_ONE_DIR); File file = new File(fileName); ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response; HttpHeaders headers = zeroCopyResponse.getHeaders(); headers.set("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8)); headers.set("file-name", URLEncoder.encode(file.getName(), StandardCharsets.UTF_8)); headers.set("Access-Control-Allow-Origin", "*"); MediaType application = new MediaType("application", "octet-stream", StandardCharsets.UTF_8); headers.setContentType(application); zeroCopyResponse.writeWith(file, 0, file.length()).subscribe(); return ""; }) .publishOn(Schedulers.boundedElastic()).then(); } @PostMapping("/del") public Mono<Void> delete(@RequestBody String[] names) { Arrays.stream(names).parallel().forEach(name -> reactiveClient.fetch(ExportLogSchema.class, name) .publishOn(Schedulers.boundedElastic()) .doOnSuccess(exportLogSchema -> { reactiveClient.delete(exportLogSchema).doOnSuccess(exportLogSchema1 -> { //删除文件 exportService.delete(name); }).subscribe(); }).subscribe()); return Mono.empty(); } @GetMapping("/down/{path}") public Mono<Void> down(@PathVariable("path") String path, ServerHttpResponse response) { if (StringUtils.isBlank(path)) { return Mono.empty(); } if (path.split("\\.").length > 2) { //包含太多.的路径,不可下载 return Mono.empty(); }
Path docFile = FileUtil.getDocFile(FileUtil.DirPath.EXPORT);
2
2023-10-29 16:01:45+00:00
8k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/TempleClient.java
[ { "identifier": "AnnotatedEventManager", "path": "src/main/java/team/stiff/pomelo/impl/annotated/AnnotatedEventManager.java", "snippet": "public final class AnnotatedEventManager implements EventManager {\n /**\n * Listener scanner implementation used to find all listeners inside\n * of a spe...
import net.minecraft.client.Minecraft; import net.minecraft.util.Session; import net.minecraftforge.client.event.ClientChatEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.Display; import team.stiff.pomelo.impl.annotated.AnnotatedEventManager; import xyz.templecheats.templeclient.api.cape.CapeManager; import xyz.templecheats.templeclient.api.config.ShutdownHook; import xyz.templecheats.templeclient.api.config.rewrite.ConfigManager; import xyz.templecheats.templeclient.api.event.EventManager; import xyz.templecheats.templeclient.api.util.keys.key; import xyz.templecheats.templeclient.impl.command.CommandManager; import xyz.templecheats.templeclient.impl.gui.clickgui.ClickGuiManager; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.SettingsManager; import xyz.templecheats.templeclient.impl.gui.font.FontUtils; import xyz.templecheats.templeclient.impl.gui.menu.GuiEventsListener; import xyz.templecheats.templeclient.impl.gui.ui.watermark; import java.lang.reflect.Field;
5,133
package xyz.templecheats.templeclient; @Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION) public class TempleClient { public static String name = "Temple Client 1.8.2"; public static final String MODID = "templeclient"; public static final String NAME = "Temple Client"; public static final String VERSION = "1.8.2"; public static AnnotatedEventManager eventBus; public static SettingsManager settingsManager; public static ModuleManager moduleManager; public static EventManager clientEventManager; public static CommandManager commandManager; public static ClickGuiManager clickGui; public static ConfigManager configManager; public static CapeManager capeManager; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + name); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { Display.setTitle(name); MinecraftForge.EVENT_BUS.register(new TempleClient()); eventBus = new AnnotatedEventManager(); clientEventManager = new EventManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); settingsManager = new SettingsManager(); (TempleClient.moduleManager = new ModuleManager()).initMods(); logger.info("Module Manager Loaded."); (TempleClient.commandManager = new CommandManager()).commandInit(); logger.info("Commands Loaded."); capeManager = new CapeManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); MinecraftForge.EVENT_BUS.register(commandManager);
package xyz.templecheats.templeclient; @Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION) public class TempleClient { public static String name = "Temple Client 1.8.2"; public static final String MODID = "templeclient"; public static final String NAME = "Temple Client"; public static final String VERSION = "1.8.2"; public static AnnotatedEventManager eventBus; public static SettingsManager settingsManager; public static ModuleManager moduleManager; public static EventManager clientEventManager; public static CommandManager commandManager; public static ClickGuiManager clickGui; public static ConfigManager configManager; public static CapeManager capeManager; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + name); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { Display.setTitle(name); MinecraftForge.EVENT_BUS.register(new TempleClient()); eventBus = new AnnotatedEventManager(); clientEventManager = new EventManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); settingsManager = new SettingsManager(); (TempleClient.moduleManager = new ModuleManager()).initMods(); logger.info("Module Manager Loaded."); (TempleClient.commandManager = new CommandManager()).commandInit(); logger.info("Commands Loaded."); capeManager = new CapeManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); MinecraftForge.EVENT_BUS.register(commandManager);
MinecraftForge.EVENT_BUS.register(new key());
5
2023-10-28 12:03:50+00:00
8k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/handler/ModelsAddedCallbackHandler.java
[ { "identifier": "ModelsAddedCallback", "path": "src/main/java/me/pepperbell/continuity/client/event/ModelsAddedCallback.java", "snippet": "public interface ModelsAddedCallback {\n\tEvent<ModelsAddedCallback> EVENT = EventFactory.createArrayBacked(ModelsAddedCallback.class,\n\t\t\tlisteners -> (modelLoad...
import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import com.mojang.datafixers.util.Pair; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArraySet; import it.unimi.dsi.fastutil.objects.ObjectIterator; import me.pepperbell.continuity.client.event.ModelsAddedCallback; import me.pepperbell.continuity.client.model.CTMUnbakedModel; import me.pepperbell.continuity.client.resource.CTMLoadingContainer; import me.pepperbell.continuity.client.resource.CTMPropertiesLoader; import me.pepperbell.continuity.client.util.VoidSet; import net.minecraft.block.BlockState; import net.minecraft.client.render.model.ModelLoader; import net.minecraft.client.render.model.UnbakedModel; import net.minecraft.client.util.ModelIdentifier; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import net.minecraft.util.profiler.Profiler;
4,161
package me.pepperbell.continuity.client.handler; public class ModelsAddedCallbackHandler implements ModelsAddedCallback { private final Map<ModelIdentifier, BlockState> modelId2StateMap;
package me.pepperbell.continuity.client.handler; public class ModelsAddedCallbackHandler implements ModelsAddedCallback { private final Map<ModelIdentifier, BlockState> modelId2StateMap;
private final Map<ModelIdentifier, List<CTMLoadingContainer<?>>> modelId2ContainersMap;
2
2023-10-29 00:08:50+00:00
8k
BBMQyyds/Bright-Light-Building-Dreams
children/src/main/java/com/blbd/children/controller/TaskChildController.java
[ { "identifier": "HttpResponseEntity", "path": "children/src/main/java/com/blbd/children/beans/HttpResponseEntity.java", "snippet": "@Repository\npublic class HttpResponseEntity {\n private String code;//状态码\n private Object data;//数据\n private String message;//消息\n\n public HttpResponseEntit...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.blbd.children.beans.HttpResponseEntity; import com.blbd.children.dao.dto.MyTaskDTO; import com.blbd.children.dao.dto.TaskDTO; import com.blbd.children.dao.entity.Task; import com.blbd.children.dao.entity.TaskChild; import com.blbd.children.dao.entity.TaskVolunteer; import com.blbd.children.mapper.TaskChildMapper; import com.blbd.children.mapper.TaskMapper; import com.blbd.children.mapper.TaskVolunteerMapper; import com.blbd.children.service.TaskChildService; import com.blbd.children.service.TaskService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
4,340
response.put("message", "无法统计:待批改的任务数量,已批改但未通过的任务数量,已批改并且通过的任务数量"); response.put("data", null); return ResponseEntity.ok(response); } } /** * 显示待完成的所有任务 * @param childId * @return */ @GetMapping("/viewRemainingTasks/{childId}") public ResponseEntity<Map<String, Object>> viewRemainingTasks(@PathVariable("childId") String childId) { QueryWrapper<TaskChild> taskChildQueryWrapper = new QueryWrapper<>(); taskChildQueryWrapper.eq("child_id", childId) .eq("is_completed", 1); // 过滤已完成的任务 List<TaskChild> completedTasksList = taskChildService.list(taskChildQueryWrapper); QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>(); List<Task> allTasksList = taskService.list(taskQueryWrapper); List<Task> remainingTasksList = new ArrayList<>(allTasksList); for (TaskChild completedTask : completedTasksList) { remainingTasksList.removeIf(task -> task.getId().equals(completedTask.getTaskId())); } List<TaskDTO> taskDTOS = new ArrayList<>(); for (Task task : remainingTasksList) { TaskDTO taskDTO = new TaskDTO(); taskDTO.setTask(task); LambdaQueryWrapper<TaskVolunteer> volunteerWrapper = new LambdaQueryWrapper<>(); volunteerWrapper.select(TaskVolunteer::getGetScore); volunteerWrapper.eq(TaskVolunteer::getTaskId, task.getId()); volunteerWrapper.orderByDesc(TaskVolunteer::getGetScore); volunteerWrapper.last("LIMIT 1"); List<TaskVolunteer> taskVolunteers = taskVolunteerMapper.selectList(volunteerWrapper); TaskVolunteer taskVolunteer = null; if (!taskVolunteers.isEmpty()) { taskVolunteer = taskVolunteers.get(0); } if (taskVolunteer != null) { Integer maxScore = taskVolunteer.getGetScore(); taskDTO.setHighestScore(maxScore); } else{ taskDTO.setHighestScore(0); } taskDTOS.add(taskDTO); } for (Task task : remainingTasksList) { TaskDTO taskDTO = new TaskDTO(); taskDTO.setTask(task); LambdaQueryWrapper<TaskVolunteer> volunteerWrapper = new LambdaQueryWrapper<>(); volunteerWrapper.select(TaskVolunteer::getGetScore); volunteerWrapper.eq(TaskVolunteer::getTaskId, task.getId()); volunteerWrapper.orderByDesc(TaskVolunteer::getGetScore); volunteerWrapper.last("LIMIT 1"); List<TaskVolunteer> taskVolunteers = taskVolunteerMapper.selectList(volunteerWrapper); TaskVolunteer taskVolunteer = null; if (!taskVolunteers.isEmpty()) { taskVolunteer = taskVolunteers.get(0); } if (taskVolunteer != null) { Integer maxScore = taskVolunteer.getGetScore(); taskDTO.setHighestScore(maxScore); } else{ taskDTO.setHighestScore(0); } taskDTOS.add(taskDTO); } int remainingTasks = remainingTasksList.size(); HashMap<String, Object> response = new HashMap<>(); if (remainingTasks > 0) { response.put("success", true); response.put("message", "获取剩余任务成功"); response.put("data", taskDTOS); response.put("tasks", remainingTasksList); response.put("num",remainingTasks); return ResponseEntity.ok(response); } else { response.put("success", false); response.put("message", "无剩余任务"); response.put("data", null); return ResponseEntity.ok(response); } } /** *看我的任务 */ @GetMapping("/viewMyTasks/{childId}") public ResponseEntity<Map<String, Object>> viewMyTasks(@PathVariable("childId") String childId) { QueryWrapper<TaskChild> taskChildQueryWrapper = new QueryWrapper<>(); taskChildQueryWrapper.eq("child_id", childId) .eq("is_completed", 1); List<TaskChild> completedTasksList = taskChildService.list(taskChildQueryWrapper); List<String> taskIds = completedTasksList.stream() .map(TaskChild::getTaskId) .collect(Collectors.toList());
package com.blbd.children.controller; /** * <p> * 任务与孩子关联信息 前端控制器 * </p> * * @author sq * @since 2023-11-01 */ @RestController @RequestMapping("/children/task-child") public class TaskChildController { @Autowired private TaskChildService taskChildService; @Autowired private TaskService taskService; @Autowired private TaskVolunteerMapper taskVolunteerMapper; //获取孩子的已提交未批改任务 @GetMapping("/submitted-uncorrected/{childId}") public ResponseEntity<Map<String, Object>> submittedUncorrectedList(@PathVariable String childId) { List<Task> tasks = taskChildService.getSubmittedUncorrectedTasksByChildId(childId); Map<String, Object> response = new HashMap<>(); if (tasks != null && !tasks.isEmpty()) { response.put("success", true); response.put("message", "该儿童已提交的未批改任务已成功检索"); response.put("data", tasks); //创建一个 HTTP 200(OK)的成功响应,并将 response 对象作为响应体返回 return ResponseEntity.ok(response); } else { response.put("success", false); response.put("message", "该儿童没有已提交的未批改任务"); response.put("data", null); //用于创建一个 HTTP 响应,状态码为 404(Not Found),表示未找到所请求的资源。 //return ResponseEntity.notFound().build(); //没有满足条件的数据不代表404 return ResponseEntity.ok(response); } } //获取孩子的已批改任务 @GetMapping("/corrected/{childId}") public ResponseEntity<Map<String,Object>> CorrectedList(@PathVariable String childId){ List<Task> tasks = taskChildService.getCorrectedTasks(childId); HashMap<String, Object> response = new HashMap<>(); if (tasks!= null && !tasks.isEmpty()){ response.put("success",true); response.put("message","该儿童已提交的已批改任务已成功检索"); response.put("data",tasks); return ResponseEntity.ok(response); } else { response.put("success",false); response.put("message", "该儿童没有已提交的已批改任务"); response.put("data", null); return ResponseEntity.ok(response); } } /** * 待批改的任务数量 * 已批改但未通过的任务数量 * 已批改且已通过的任务数量 * @param childId * @return */ @GetMapping("/count/{childId}") public ResponseEntity<Map<String, Object>> getTaskStats(@PathVariable String childId) { // 待批改的任务数量 int pendingTasks = Math.toIntExact(taskChildService.lambdaQuery() .eq(TaskChild::getChildId, childId) .eq(TaskChild::getIsCorrected, 0) .count()); // 已批改但未通过的任务数量 int notPassedTasks = Math.toIntExact(taskChildService.lambdaQuery() .eq(TaskChild::getChildId, childId) .eq(TaskChild::getIsCorrected, 1) .count()); // 已批改且已通过的任务数量 int passedTasks = Math.toIntExact(taskChildService.lambdaQuery() .eq(TaskChild::getChildId, childId) .eq(TaskChild::getIsCorrected, 2) .count()); Map<String, Integer> counts = new HashMap<>(); counts.put("pendingTasks", pendingTasks); counts.put("notPassedTasks", notPassedTasks); counts.put("passedTasks", passedTasks); HashMap<String, Object> response = new HashMap<>(); if (counts!= null && !counts.isEmpty()){ response.put("success",true); response.put("message","待批改的任务数量,已批改但未通过的任务数量,已批改并且通过的任务数量统计成功"); response.put("data",counts); return ResponseEntity.ok(response); } else { response.put("success",false); response.put("message", "无法统计:待批改的任务数量,已批改但未通过的任务数量,已批改并且通过的任务数量"); response.put("data", null); return ResponseEntity.ok(response); } } /** * 显示待完成的所有任务 * @param childId * @return */ @GetMapping("/viewRemainingTasks/{childId}") public ResponseEntity<Map<String, Object>> viewRemainingTasks(@PathVariable("childId") String childId) { QueryWrapper<TaskChild> taskChildQueryWrapper = new QueryWrapper<>(); taskChildQueryWrapper.eq("child_id", childId) .eq("is_completed", 1); // 过滤已完成的任务 List<TaskChild> completedTasksList = taskChildService.list(taskChildQueryWrapper); QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>(); List<Task> allTasksList = taskService.list(taskQueryWrapper); List<Task> remainingTasksList = new ArrayList<>(allTasksList); for (TaskChild completedTask : completedTasksList) { remainingTasksList.removeIf(task -> task.getId().equals(completedTask.getTaskId())); } List<TaskDTO> taskDTOS = new ArrayList<>(); for (Task task : remainingTasksList) { TaskDTO taskDTO = new TaskDTO(); taskDTO.setTask(task); LambdaQueryWrapper<TaskVolunteer> volunteerWrapper = new LambdaQueryWrapper<>(); volunteerWrapper.select(TaskVolunteer::getGetScore); volunteerWrapper.eq(TaskVolunteer::getTaskId, task.getId()); volunteerWrapper.orderByDesc(TaskVolunteer::getGetScore); volunteerWrapper.last("LIMIT 1"); List<TaskVolunteer> taskVolunteers = taskVolunteerMapper.selectList(volunteerWrapper); TaskVolunteer taskVolunteer = null; if (!taskVolunteers.isEmpty()) { taskVolunteer = taskVolunteers.get(0); } if (taskVolunteer != null) { Integer maxScore = taskVolunteer.getGetScore(); taskDTO.setHighestScore(maxScore); } else{ taskDTO.setHighestScore(0); } taskDTOS.add(taskDTO); } for (Task task : remainingTasksList) { TaskDTO taskDTO = new TaskDTO(); taskDTO.setTask(task); LambdaQueryWrapper<TaskVolunteer> volunteerWrapper = new LambdaQueryWrapper<>(); volunteerWrapper.select(TaskVolunteer::getGetScore); volunteerWrapper.eq(TaskVolunteer::getTaskId, task.getId()); volunteerWrapper.orderByDesc(TaskVolunteer::getGetScore); volunteerWrapper.last("LIMIT 1"); List<TaskVolunteer> taskVolunteers = taskVolunteerMapper.selectList(volunteerWrapper); TaskVolunteer taskVolunteer = null; if (!taskVolunteers.isEmpty()) { taskVolunteer = taskVolunteers.get(0); } if (taskVolunteer != null) { Integer maxScore = taskVolunteer.getGetScore(); taskDTO.setHighestScore(maxScore); } else{ taskDTO.setHighestScore(0); } taskDTOS.add(taskDTO); } int remainingTasks = remainingTasksList.size(); HashMap<String, Object> response = new HashMap<>(); if (remainingTasks > 0) { response.put("success", true); response.put("message", "获取剩余任务成功"); response.put("data", taskDTOS); response.put("tasks", remainingTasksList); response.put("num",remainingTasks); return ResponseEntity.ok(response); } else { response.put("success", false); response.put("message", "无剩余任务"); response.put("data", null); return ResponseEntity.ok(response); } } /** *看我的任务 */ @GetMapping("/viewMyTasks/{childId}") public ResponseEntity<Map<String, Object>> viewMyTasks(@PathVariable("childId") String childId) { QueryWrapper<TaskChild> taskChildQueryWrapper = new QueryWrapper<>(); taskChildQueryWrapper.eq("child_id", childId) .eq("is_completed", 1); List<TaskChild> completedTasksList = taskChildService.list(taskChildQueryWrapper); List<String> taskIds = completedTasksList.stream() .map(TaskChild::getTaskId) .collect(Collectors.toList());
List<MyTaskDTO> taskList = new ArrayList<>();
1
2023-10-30 12:49:28+00:00
8k
oghenevovwerho/yaa
src/main/java/yaa/ast/Group.java
[ { "identifier": "FileState", "path": "src/main/java/yaa/pojos/FileState.java", "snippet": "public abstract class FileState {\r\n public final List<Stmt> stmts;\r\n public final String path;\r\n public Map<Stmt, YaaTable> tables = new HashMap<>();\r\n public YaaTable table;\r\n\r\n public FileState(...
import yaa.pojos.FileState; import yaa.pojos.YaaInfo;
3,767
package yaa.ast; public class Group extends Stmt { public Stmt e; public Group(Stmt e) { this.e = e; } @Override public String toString() { return e.toString(); } @Override
package yaa.ast; public class Group extends Stmt { public Stmt e; public Group(Stmt e) { this.e = e; } @Override public String toString() { return e.toString(); } @Override
public YaaInfo visit(FileState fs) {
1
2023-10-26 17:41:13+00:00
8k
echcz/web-service
src/main/jooq/cn/echcz/webservice/adapter/repository/tables/ActionLogTable.java
[ { "identifier": "DefaultSchema", "path": "src/main/jooq/cn/echcz/webservice/adapter/repository/DefaultSchema.java", "snippet": "@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class DefaultSchema extends SchemaImpl {\n\n private static final long serialVersionUID = 1L;\n\n /**\...
import cn.echcz.webservice.adapter.repository.DefaultSchema; import cn.echcz.webservice.adapter.repository.Indexes; import cn.echcz.webservice.adapter.repository.Keys; import cn.echcz.webservice.adapter.repository.tables.records.ActionLogRecord; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Row9; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.TableOptions; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; import org.jooq.impl.TableImpl;
4,387
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository.tables; /** * 操作日志 */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ActionLogTable extends TableImpl<ActionLogRecord> { private static final long serialVersionUID = 1L; /** * The reference instance of <code>action_log</code> */ public static final ActionLogTable ACTION_LOG = new ActionLogTable(); /** * The class holding records for this type */ @Override public Class<ActionLogRecord> getRecordType() { return ActionLogRecord.class; } /** * The column <code>action_log.id</code>. 主键 */ public final TableField<ActionLogRecord, Long> ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).identity(true), this, "主键"); /** * The column <code>action_log.tenant_name</code>. 租户名 */ public final TableField<ActionLogRecord, String> TENANT_NAME = createField(DSL.name("tenant_name"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "租户名"); /** * The column <code>action_log.actor_name</code>. 操作者名 */ public final TableField<ActionLogRecord, String> ACTOR_NAME = createField(DSL.name("actor_name"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作者名"); /** * The column <code>action_log.actor_roles</code>. 操作者拥有的角色,用逗号分隔 */ public final TableField<ActionLogRecord, String> ACTOR_ROLES = createField(DSL.name("actor_roles"), SQLDataType.VARCHAR(255).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作者拥有的角色,用逗号分隔"); /** * The column <code>action_log.group</code>. 操作组 */ public final TableField<ActionLogRecord, String> GROUP = createField(DSL.name("group"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作组"); /** * The column <code>action_log.name</code>. 操作名 */ public final TableField<ActionLogRecord, String> NAME = createField(DSL.name("name"), SQLDataType.VARCHAR(100).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作名"); /** * The column <code>action_log.type</code>. 操作类型 */ public final TableField<ActionLogRecord, String> TYPE = createField(DSL.name("type"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("COMMAND", SQLDataType.VARCHAR)), this, "操作类型"); /** * The column <code>action_log.content</code>. 操作内容 */ public final TableField<ActionLogRecord, String> CONTENT = createField(DSL.name("content"), SQLDataType.CLOB, this, "操作内容"); /** * The column <code>action_log.action_time</code>. 操作时间 */ public final TableField<ActionLogRecord, LocalDateTime> ACTION_TIME = createField(DSL.name("action_time"), SQLDataType.LOCALDATETIME(0).nullable(false).defaultValue(DSL.field("CURRENT_TIMESTAMP", SQLDataType.LOCALDATETIME)), this, "操作时间"); private ActionLogTable(Name alias, Table<ActionLogRecord> aliased) { this(alias, aliased, null); } private ActionLogTable(Name alias, Table<ActionLogRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("操作日志"), TableOptions.table()); } /** * Create an aliased <code>action_log</code> table reference */ public ActionLogTable(String alias) { this(DSL.name(alias), ACTION_LOG); } /** * Create an aliased <code>action_log</code> table reference */ public ActionLogTable(Name alias) { this(alias, ACTION_LOG); } /** * Create a <code>action_log</code> table reference */ public ActionLogTable() { this(DSL.name("action_log"), null); } public <O extends Record> ActionLogTable(Table<O> child, ForeignKey<O, ActionLogRecord> key) { super(child, key, ACTION_LOG); } @Override public Schema getSchema() { return DefaultSchema.DEFAULT_SCHEMA; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.ACTION_LOG_IDX_TENANT_ACTION_TIME); } @Override public Identity<ActionLogRecord, Long> getIdentity() { return (Identity<ActionLogRecord, Long>) super.getIdentity(); } @Override public UniqueKey<ActionLogRecord> getPrimaryKey() {
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository.tables; /** * 操作日志 */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ActionLogTable extends TableImpl<ActionLogRecord> { private static final long serialVersionUID = 1L; /** * The reference instance of <code>action_log</code> */ public static final ActionLogTable ACTION_LOG = new ActionLogTable(); /** * The class holding records for this type */ @Override public Class<ActionLogRecord> getRecordType() { return ActionLogRecord.class; } /** * The column <code>action_log.id</code>. 主键 */ public final TableField<ActionLogRecord, Long> ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).identity(true), this, "主键"); /** * The column <code>action_log.tenant_name</code>. 租户名 */ public final TableField<ActionLogRecord, String> TENANT_NAME = createField(DSL.name("tenant_name"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "租户名"); /** * The column <code>action_log.actor_name</code>. 操作者名 */ public final TableField<ActionLogRecord, String> ACTOR_NAME = createField(DSL.name("actor_name"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作者名"); /** * The column <code>action_log.actor_roles</code>. 操作者拥有的角色,用逗号分隔 */ public final TableField<ActionLogRecord, String> ACTOR_ROLES = createField(DSL.name("actor_roles"), SQLDataType.VARCHAR(255).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作者拥有的角色,用逗号分隔"); /** * The column <code>action_log.group</code>. 操作组 */ public final TableField<ActionLogRecord, String> GROUP = createField(DSL.name("group"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作组"); /** * The column <code>action_log.name</code>. 操作名 */ public final TableField<ActionLogRecord, String> NAME = createField(DSL.name("name"), SQLDataType.VARCHAR(100).nullable(false).defaultValue(DSL.inline("", SQLDataType.VARCHAR)), this, "操作名"); /** * The column <code>action_log.type</code>. 操作类型 */ public final TableField<ActionLogRecord, String> TYPE = createField(DSL.name("type"), SQLDataType.VARCHAR(50).nullable(false).defaultValue(DSL.inline("COMMAND", SQLDataType.VARCHAR)), this, "操作类型"); /** * The column <code>action_log.content</code>. 操作内容 */ public final TableField<ActionLogRecord, String> CONTENT = createField(DSL.name("content"), SQLDataType.CLOB, this, "操作内容"); /** * The column <code>action_log.action_time</code>. 操作时间 */ public final TableField<ActionLogRecord, LocalDateTime> ACTION_TIME = createField(DSL.name("action_time"), SQLDataType.LOCALDATETIME(0).nullable(false).defaultValue(DSL.field("CURRENT_TIMESTAMP", SQLDataType.LOCALDATETIME)), this, "操作时间"); private ActionLogTable(Name alias, Table<ActionLogRecord> aliased) { this(alias, aliased, null); } private ActionLogTable(Name alias, Table<ActionLogRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("操作日志"), TableOptions.table()); } /** * Create an aliased <code>action_log</code> table reference */ public ActionLogTable(String alias) { this(DSL.name(alias), ACTION_LOG); } /** * Create an aliased <code>action_log</code> table reference */ public ActionLogTable(Name alias) { this(alias, ACTION_LOG); } /** * Create a <code>action_log</code> table reference */ public ActionLogTable() { this(DSL.name("action_log"), null); } public <O extends Record> ActionLogTable(Table<O> child, ForeignKey<O, ActionLogRecord> key) { super(child, key, ACTION_LOG); } @Override public Schema getSchema() { return DefaultSchema.DEFAULT_SCHEMA; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.ACTION_LOG_IDX_TENANT_ACTION_TIME); } @Override public Identity<ActionLogRecord, Long> getIdentity() { return (Identity<ActionLogRecord, Long>) super.getIdentity(); } @Override public UniqueKey<ActionLogRecord> getPrimaryKey() {
return Keys.KEY_ACTION_LOG_PRIMARY;
2
2023-10-30 18:55:49+00:00
8k
tom5454/Toms-Peripherals
Forge/src/platform-shared/java/com/tom/peripherals/block/RedstonePortBlock.java
[ { "identifier": "Content", "path": "Forge/src/platform-shared/java/com/tom/peripherals/Content.java", "snippet": "public class Content {\n\tpublic static final GameObject<GPUBlock> gpu = blockWithItem(\"gpu\", GPUBlock::new);\n\tpublic static final GameObject<MonitorBlock> monitor = blockWithItem(\"moni...
import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import com.tom.peripherals.Content; import com.tom.peripherals.block.entity.RedstonePortBlockEntity; import com.tom.peripherals.client.ClientUtil; import com.tom.peripherals.util.TickerUtil; import dan200.computercraft.shared.common.IBundledRedstoneBlock;
4,273
package com.tom.peripherals.block; public class RedstonePortBlock extends Block implements EntityBlock, IForgeBlock, IBundledRedstoneBlock { public RedstonePortBlock() { super(Block.Properties.of().mapColor(DyeColor.RED).sound(SoundType.METAL).strength(5).isRedstoneConductor((a, b, c) -> false)); } @Override public BlockEntity newBlockEntity(BlockPos p_153215_, BlockState p_153216_) { return Content.redstonePortBE.get().create(p_153215_, p_153216_); } @Override public final void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighbourBlock, BlockPos neighbourPos, boolean isMoving) { var be = world.getBlockEntity(pos); if (be instanceof RedstonePortBlockEntity te) te.neighborChanged(neighbourPos); } @Override public final void onNeighborChange(BlockState state, LevelReader world, BlockPos pos, BlockPos neighbour) { var be = world.getBlockEntity(pos); if (be instanceof RedstonePortBlockEntity te) te.neighborChanged(neighbour); } @Override public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { return true; } @Override public boolean isSignalSource(BlockState state) { return true; } @Override public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction incomingSide) { var entity = world.getBlockEntity(pos); if (!(entity instanceof RedstonePortBlockEntity te)) return 0; return te.getExternalRedstoneOutput(incomingSide.getOpposite()); } @Override public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction incomingSide) { return getDirectSignal(state, world, pos, incomingSide); } @Override public int getBundledRedstoneOutput(Level world, BlockPos pos, Direction side) { var entity = world.getBlockEntity(pos); if (!(entity instanceof RedstonePortBlockEntity te)) return 0; return te.getExternalBundledRedstoneOutput(side); } @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level world, BlockState state, BlockEntityType<T> type) {
package com.tom.peripherals.block; public class RedstonePortBlock extends Block implements EntityBlock, IForgeBlock, IBundledRedstoneBlock { public RedstonePortBlock() { super(Block.Properties.of().mapColor(DyeColor.RED).sound(SoundType.METAL).strength(5).isRedstoneConductor((a, b, c) -> false)); } @Override public BlockEntity newBlockEntity(BlockPos p_153215_, BlockState p_153216_) { return Content.redstonePortBE.get().create(p_153215_, p_153216_); } @Override public final void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighbourBlock, BlockPos neighbourPos, boolean isMoving) { var be = world.getBlockEntity(pos); if (be instanceof RedstonePortBlockEntity te) te.neighborChanged(neighbourPos); } @Override public final void onNeighborChange(BlockState state, LevelReader world, BlockPos pos, BlockPos neighbour) { var be = world.getBlockEntity(pos); if (be instanceof RedstonePortBlockEntity te) te.neighborChanged(neighbour); } @Override public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { return true; } @Override public boolean isSignalSource(BlockState state) { return true; } @Override public int getDirectSignal(BlockState state, BlockGetter world, BlockPos pos, Direction incomingSide) { var entity = world.getBlockEntity(pos); if (!(entity instanceof RedstonePortBlockEntity te)) return 0; return te.getExternalRedstoneOutput(incomingSide.getOpposite()); } @Override public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction incomingSide) { return getDirectSignal(state, world, pos, incomingSide); } @Override public int getBundledRedstoneOutput(Level world, BlockPos pos, Direction side) { var entity = world.getBlockEntity(pos); if (!(entity instanceof RedstonePortBlockEntity te)) return 0; return te.getExternalBundledRedstoneOutput(side); } @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level world, BlockState state, BlockEntityType<T> type) {
return TickerUtil.createTicker(world, false, true);
3
2023-10-30 17:05:11+00:00
8k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/factory/testcase/parameter/ChronicleVariableContainer.java
[ { "identifier": "DataEventWithSessionId", "path": "src/main/java/com/insidious/plugin/client/pojo/DataEventWithSessionId.java", "snippet": "@DatabaseTable(tableName = \"data_event\")\npublic class DataEventWithSessionId implements Serializable, BytesMarshallable {\n\n @DatabaseField\n private long...
import com.insidious.plugin.client.pojo.DataEventWithSessionId; import com.insidious.plugin.pojo.Parameter; import com.insidious.plugin.util.LoggerUtil; import com.intellij.openapi.diagnostic.Logger; import net.openhft.chronicle.map.ChronicleMap; import java.util.Collection;
3,798
package com.insidious.plugin.factory.testcase.parameter; public class ChronicleVariableContainer { private static final Logger logger = LoggerUtil.getInstance(ChronicleVariableContainer.class);
package com.insidious.plugin.factory.testcase.parameter; public class ChronicleVariableContainer { private static final Logger logger = LoggerUtil.getInstance(ChronicleVariableContainer.class);
final ChronicleMap<Long, Parameter> parameterMap;
1
2023-10-31 09:07:46+00:00
8k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/item/gem/GemAMVampirism.java
[ { "identifier": "GemAttributes", "path": "src/main/java/mixac1/dangerrpg/capability/GemAttributes.java", "snippet": "public abstract class GemAttributes {\n\n public static final IAStrUUID UUID = new IAStrUUID(\"uuid\");\n\n public static final IADynamic AMOUNT = new IADynamic(\"amount\") {\n\n ...
import mixac1.dangerrpg.capability.GemAttributes; import mixac1.dangerrpg.capability.data.RPGItemRegister.RPGItemData; import mixac1.dangerrpg.init.RPGConfig.MainConfig; import mixac1.dangerrpg.util.IMultiplier.MultiplierAdd; import mixac1.dangerrpg.util.RPGHelper; import mixac1.dangerrpg.util.Tuple.Stub; import mixac1.dangerrpg.util.Utils; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import java.util.HashSet;
5,117
package mixac1.dangerrpg.item.gem; public class GemAMVampirism extends GemAttackModifier { public GemAMVampirism(String name) { super(name); } @Override public void registerAttributes(Item item, RPGItemData map) { super.registerAttributes(item, map); map.registerIADynamic(GemAttributes.PERCENT, 0.10f, new MultiplierAdd(0.05f)); } @Override public void onEntityHit(ItemStack gem, EntityPlayer player, EntityLivingBase target, Stub<Float> damage, HashSet<Class<? extends GemAttackModifier>> disableSet) {} @Override public void onDealtDamage(ItemStack gem, EntityPlayer player, EntityLivingBase target, Stub<Float> damage, HashSet<Class<? extends GemAttackModifier>> disableSet) { if (GemAttributes.PERCENT.hasIt(gem)) { float tmp = player.getMaxHealth() - player.getHealth(); if (tmp > 0) {
package mixac1.dangerrpg.item.gem; public class GemAMVampirism extends GemAttackModifier { public GemAMVampirism(String name) { super(name); } @Override public void registerAttributes(Item item, RPGItemData map) { super.registerAttributes(item, map); map.registerIADynamic(GemAttributes.PERCENT, 0.10f, new MultiplierAdd(0.05f)); } @Override public void onEntityHit(ItemStack gem, EntityPlayer player, EntityLivingBase target, Stub<Float> damage, HashSet<Class<? extends GemAttackModifier>> disableSet) {} @Override public void onDealtDamage(ItemStack gem, EntityPlayer player, EntityLivingBase target, Stub<Float> damage, HashSet<Class<? extends GemAttackModifier>> disableSet) { if (GemAttributes.PERCENT.hasIt(gem)) { float tmp = player.getMaxHealth() - player.getHealth(); if (tmp > 0) {
float value = Utils.alignment(damage.value1 * GemAttributes.PERCENT.get(gem, player), 0, tmp);
6
2023-10-31 21:00:14+00:00
8k
Tamiflu233/DingVideo
dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/LikeServiceImpl.java
[ { "identifier": "Comment", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/Comment.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Document(collection = com.dataispower.dingvideobackend.common.TableColumns.COMMENT)\npublic class Comment implements Seri...
import com.dataispower.dingvideobackend.entity.Comment; import com.dataispower.dingvideobackend.entity.UserLike; import com.dataispower.dingvideobackend.entity.Video; import com.dataispower.dingvideobackend.repository.LikeRepository; import com.dataispower.dingvideobackend.repository.UserRepository; import com.dataispower.dingvideobackend.repository.VideoRepository; import com.dataispower.dingvideobackend.service.interfaces.CommentService; import com.dataispower.dingvideobackend.service.interfaces.LikeService; import com.dataispower.dingvideobackend.service.interfaces.RedisLikeService; import com.dataispower.dingvideobackend.service.interfaces.VideoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*;
3,980
package com.dataispower.dingvideobackend.service; /** * author:heroding * date:2023/11/6 16:06 * description:点赞服务类 **/ @Service public class LikeServiceImpl implements LikeService { @Autowired private LikeRepository userLikeRepository; @Autowired private RedisLikeService redisLikeService; @Autowired private VideoRepository videoRepository; @Autowired private UserRepository userRepository; @Lazy @Autowired private VideoService videoService; @Autowired
package com.dataispower.dingvideobackend.service; /** * author:heroding * date:2023/11/6 16:06 * description:点赞服务类 **/ @Service public class LikeServiceImpl implements LikeService { @Autowired private LikeRepository userLikeRepository; @Autowired private RedisLikeService redisLikeService; @Autowired private VideoRepository videoRepository; @Autowired private UserRepository userRepository; @Lazy @Autowired private VideoService videoService; @Autowired
private CommentService commentService;
6
2023-10-25 07:16:43+00:00
8k
MiguelPereiraDantas/E-commerce-Java
src/main/java/br/com/fourstore/controller/SaleController.java
[ { "identifier": "ServiceSale", "path": "src/main/java/br/com/fourstore/service/ServiceSale.java", "snippet": "@Service\npublic class ServiceSale {\n\t\n\t@Autowired\n\tServiceProduct serviceProduct;\n\t\n\t@Autowired\n\tServiceHistoric serviceHistoric;\n\t\n\tprivate static List<Product> cart = new Arra...
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.fourstore.service.ServiceSale; import br.com.fourstore.model.Credit; import br.com.fourstore.model.Debit; import br.com.fourstore.model.Money; import br.com.fourstore.model.Pix; import br.com.fourstore.model.Product; import br.com.fourstore.model.Sale;
5,195
package br.com.fourstore.controller; @RestController @RequestMapping("/sale") public class SaleController { @Autowired ServiceSale serviceSale; @GetMapping("/cart") public List<Product> getCart(){ return serviceSale.getCart(); } @GetMapping("/cart/{sku}") public Product getProductInCart(@PathVariable("sku") String sku) { return serviceSale.searchProductBySkuInCart(sku); } @PostMapping("/cart/add/{sku}/{theAmount}") public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) { return serviceSale.addProductToCart(sku, theAmount); } @DeleteMapping("/cart/delete/{sku}/{theAmount}") public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) { return serviceSale.removeProductFromCart(sku, theAmount); } @DeleteMapping("/cart/empty") public String deleteCart() { return serviceSale.emptyCart(); } @GetMapping("/cart/total") public Double getTotal() { return serviceSale.purchaseTotal(); } @GetMapping("/cart/checkcart") public List<Product> getCheckCart(){ return serviceSale.checkCart(); } @PostMapping("/cart/finalizar/credit")
package br.com.fourstore.controller; @RestController @RequestMapping("/sale") public class SaleController { @Autowired ServiceSale serviceSale; @GetMapping("/cart") public List<Product> getCart(){ return serviceSale.getCart(); } @GetMapping("/cart/{sku}") public Product getProductInCart(@PathVariable("sku") String sku) { return serviceSale.searchProductBySkuInCart(sku); } @PostMapping("/cart/add/{sku}/{theAmount}") public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) { return serviceSale.addProductToCart(sku, theAmount); } @DeleteMapping("/cart/delete/{sku}/{theAmount}") public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) { return serviceSale.removeProductFromCart(sku, theAmount); } @DeleteMapping("/cart/empty") public String deleteCart() { return serviceSale.emptyCart(); } @GetMapping("/cart/total") public Double getTotal() { return serviceSale.purchaseTotal(); } @GetMapping("/cart/checkcart") public List<Product> getCheckCart(){ return serviceSale.checkCart(); } @PostMapping("/cart/finalizar/credit")
public Sale postHistoricCredit(@RequestBody Credit credit) {
1
2023-10-26 15:48:53+00:00
8k
thinhunan/wonder8-promotion-rule
java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/Strategy.java
[ { "identifier": "Item", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/Item.java", "snippet": "public class Item {\n String category;\n String SPU;\n String SKU;\n String seat;\n\n /// 单位:分 (by cent)\n int price;\n\n public Item(){}\n\n /*\n * @...
import com.github.thinhunan.wonder8.promotion.rule.model.Item; import com.github.thinhunan.wonder8.promotion.rule.model.P; import com.github.thinhunan.wonder8.promotion.rule.model.Rule; import com.github.thinhunan.wonder8.promotion.rule.model.SimplexRule; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Calculator; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType; import com.github.thinhunan.wonder8.promotion.rule.model.validate.RuleValidateResult; import java.util.*;
6,703
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) {
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) {
BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting);
5
2023-10-28 09:03:45+00:00
8k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/IObjectSupport.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.CollectionUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.page.Page; import java.util.Collection; import java.util.List;
6,951
package org.tinycloud.jdbc.support; /** * <p> * 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作, * 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段 * 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口 * </p> * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public interface IObjectSupport<T, ID> { /** * 持久化插入给定的实例(默认忽略null值) * * @param entity 实例 * @return int 受影响的行数 */ int insert(T entity); /** * 持久化插入给定的实例 * * @param entity 实例 * @param ignoreNulls 是否忽略null值,true忽略,false不忽略 * @return int 受影响的行数 */ int insert(T entity, boolean ignoreNulls); /** * 持久化插入给定的实例,并且返回自增主键 * * @param entity 实例 * @return Integer 返回主键 */ Long insertReturnAutoIncrement(T entity); /** * 持久化更新给定的实例(默认忽略null值),根据主键值更新 * * @param entity 实例 * @return int 受影响的行数 */ int updateById(T entity); /** * 持久化更新给定的实例,根据主键值更新 * * @param entity 实例 * @param ignoreNulls 是否忽略null值,true忽略,false不忽略 * @return int 受影响的行数 */ int updateById(T entity, boolean ignoreNulls); /** * 持久化更新给定的实例(默认忽略null值) * * @param criteria 条件构造器 * @return int 受影响的行数 */
package org.tinycloud.jdbc.support; /** * <p> * 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作, * 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段 * 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口 * </p> * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public interface IObjectSupport<T, ID> { /** * 持久化插入给定的实例(默认忽略null值) * * @param entity 实例 * @return int 受影响的行数 */ int insert(T entity); /** * 持久化插入给定的实例 * * @param entity 实例 * @param ignoreNulls 是否忽略null值,true忽略,false不忽略 * @return int 受影响的行数 */ int insert(T entity, boolean ignoreNulls); /** * 持久化插入给定的实例,并且返回自增主键 * * @param entity 实例 * @return Integer 返回主键 */ Long insertReturnAutoIncrement(T entity); /** * 持久化更新给定的实例(默认忽略null值),根据主键值更新 * * @param entity 实例 * @return int 受影响的行数 */ int updateById(T entity); /** * 持久化更新给定的实例,根据主键值更新 * * @param entity 实例 * @param ignoreNulls 是否忽略null值,true忽略,false不忽略 * @return int 受影响的行数 */ int updateById(T entity, boolean ignoreNulls); /** * 持久化更新给定的实例(默认忽略null值) * * @param criteria 条件构造器 * @return int 受影响的行数 */
int update(T entity, boolean ignoreNulls, Criteria criteria);
0
2023-10-25 14:44:59+00:00
8k