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
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerGetChatEmojiListCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler;
19,897
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetChatEmojiListCsReq) public class HandlerGetChatEmojiListCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetChatEmojiListCsReq) public class HandlerGetChatEmojiListCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
0
2023-12-08 14:13:04+00:00
24k
quentin452/Garden-Stuff-Continuation
src/main/java/com/jaquadro/minecraft/gardencontainers/client/renderer/MediumPotRenderer.java
[ { "identifier": "BlockMediumPot", "path": "src/main/java/com/jaquadro/minecraft/gardencontainers/block/BlockMediumPot.java", "snippet": "public abstract class BlockMediumPot extends BlockGardenContainer implements IChainAttachable {\n\n private static final Vec3[] chainAttachPoints = new Vec3[] { Vec...
import com.jaquadro.minecraft.gardencontainers.block.BlockMediumPot; import com.jaquadro.minecraft.gardencontainers.block.tile.TileEntityMediumPot; import com.jaquadro.minecraft.gardencontainers.core.ClientProxy; import com.jaquadro.minecraft.gardencore.client.renderer.support.ModularBoxRenderer; import com.jaquadro.minecraft.gardencore.util.RenderHelper; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.util.IIcon; import net.minecraft.world.ColorizerGrass; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11;
20,759
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class MediumPotRenderer implements ISimpleBlockRenderingHandler { private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); private float[] colorScratch = new float[3]; public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class MediumPotRenderer implements ISimpleBlockRenderingHandler { private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); private float[] colorScratch = new float[3]; public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {
if (block instanceof BlockMediumPot) {
0
2023-12-12 08:13:16+00:00
24k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/stages/GameStage.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import static com.senetboom.game.SenetBoom.*; import static com.senetboom.game.backend.Board.getBoard; import static com.senetboom.game.backend.Board.setAllowedTile;
19,929
displayHelp = !displayHelp; } }); exitTable.add(helpButton).padBottom(tileSize/4); // in the same row, add a hint button TextButton hintButton = new TextButton("HINT", skin); hintButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHint = !displayHint; needRender = true; } }); exitTable.add(hintButton).padBottom(tileSize/4).padLeft(tileSize/8); exitTable.row(); // add a skipTurn button TextButton skipTurnButton = new TextButton("END TURN", skin); skipTurnButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { skipTurn = true; } }); exitTable.add(skipTurnButton).padBottom(tileSize/4); exitTable.row(); // add the Options button TextButton optionsButton = new TextButton("OPTIONS", skin); optionsButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { // TODO } }); exitTable.add(optionsButton).padBottom(tileSize/4); exitTable.row(); // add the exit button TextButton exitButton = new TextButton("EXIT", skin); exitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createMenu(); } }); exitTable.add(exitButton).padBottom(tileSize/4); exitTable.setPosition(Gdx.graphics.getWidth()-tileSize*3, tileSize*1.5f); stage.addActor(exitTable); return stage; } public static void createStacks(final Tile[] board, Table pawnRoot, final int i){ final Tile tile = board[i]; // ----------------- Pawn Stack ----------------- // for the stack above being the pawn on the tile final Stack pawnStack = new Stack(); pawnStack.setSize(80, 80); // EMPTY Texture Image empty = new Image(emptyTexture); empty.setSize(80, 80); pawnStack.addActor(empty); // if the tile has a piece, draw the piece if(tile.hasPiece()) { if(!(emptyVariable == tile.getPosition())) { // if tile not the empty currently bot move pawn position Image piece; if(tile.getPiece().getColour() == Piece.Color.BLACK) { // draw a black piece to the stack piece = new Image(blackpiece); } else { // draw a white piece to the stack piece = new Image(whitepiece); } piece.setSize(80, 80); pawnStack.addActor(piece); } } // check if tile has protection if(tile.hasPiece() && tile.getPiece().hasProtection()) { // draw a protection to the stack Image protection = new Image(rebirthProtection); protection.setSize(80, 80); pawnStack.addActor(protection); } if(tile.hasPiece() && tile.getPiece().getColour() == getTurn()){ // drag and drop listeners pawnStack.addListener(new DragListener() { @Override public void dragStart(InputEvent event, float x, float y, int pointer) { // Code runs when dragging starts: System.out.println("Started dragging the Pawn!\n"); // Get the team color of the current tile Tile[] gameBoard = getBoard(); Piece.Color teamColor = gameBoard[i].getPiece().getColour(); // If it's not the current team's turn, cancel the drag and return if (!(teamColor == getTurn())) { event.cancel(); System.out.println("It's not your turn!\n"); renderBoard(); return; } System.out.println("Current Stick Value: " + currentStickValue + "\n"); System.out.println("Current Tile: " + board[i].getPosition() + "\n"); System.out.println("Current Team" + teamColor + "\n"); if(board[i].isMoveValid(board[i].getPosition(), currentStickValue)){ System.out.println("Move for this piece valid. Setting allowed tile.");
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createMapStacks(board, root, i); } root.row(); // second row for(int i=19; i>=10; i--) { createMapStacks(board, root, i); } root.row(); // third row for(int i=20; i<30; i++) { createMapStacks(board, root, i); } stage.addActor(root); return stage; } public static Stage drawBoard() { inGame = true; Stage stage = new Stage(); // create a root table for the pawns Table pawnRoot = new Table(); pawnRoot.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // second row for(int i=19; i>=10; i--) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // third row for(int i=20; i<30; i++) { createStacks(board, pawnRoot, i); } stage.addActor(pawnRoot); // add a Table with a single EXIT and OPTION Button Table exitTable = new Table(); // HELP BUTTON THAT SWITCHES THE BOOLEAN displayHelp TextButton helpButton = new TextButton("HELP", skin); helpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHelp = !displayHelp; } }); exitTable.add(helpButton).padBottom(tileSize/4); // in the same row, add a hint button TextButton hintButton = new TextButton("HINT", skin); hintButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHint = !displayHint; needRender = true; } }); exitTable.add(hintButton).padBottom(tileSize/4).padLeft(tileSize/8); exitTable.row(); // add a skipTurn button TextButton skipTurnButton = new TextButton("END TURN", skin); skipTurnButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { skipTurn = true; } }); exitTable.add(skipTurnButton).padBottom(tileSize/4); exitTable.row(); // add the Options button TextButton optionsButton = new TextButton("OPTIONS", skin); optionsButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { // TODO } }); exitTable.add(optionsButton).padBottom(tileSize/4); exitTable.row(); // add the exit button TextButton exitButton = new TextButton("EXIT", skin); exitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createMenu(); } }); exitTable.add(exitButton).padBottom(tileSize/4); exitTable.setPosition(Gdx.graphics.getWidth()-tileSize*3, tileSize*1.5f); stage.addActor(exitTable); return stage; } public static void createStacks(final Tile[] board, Table pawnRoot, final int i){ final Tile tile = board[i]; // ----------------- Pawn Stack ----------------- // for the stack above being the pawn on the tile final Stack pawnStack = new Stack(); pawnStack.setSize(80, 80); // EMPTY Texture Image empty = new Image(emptyTexture); empty.setSize(80, 80); pawnStack.addActor(empty); // if the tile has a piece, draw the piece if(tile.hasPiece()) { if(!(emptyVariable == tile.getPosition())) { // if tile not the empty currently bot move pawn position Image piece; if(tile.getPiece().getColour() == Piece.Color.BLACK) { // draw a black piece to the stack piece = new Image(blackpiece); } else { // draw a white piece to the stack piece = new Image(whitepiece); } piece.setSize(80, 80); pawnStack.addActor(piece); } } // check if tile has protection if(tile.hasPiece() && tile.getPiece().hasProtection()) { // draw a protection to the stack Image protection = new Image(rebirthProtection); protection.setSize(80, 80); pawnStack.addActor(protection); } if(tile.hasPiece() && tile.getPiece().getColour() == getTurn()){ // drag and drop listeners pawnStack.addListener(new DragListener() { @Override public void dragStart(InputEvent event, float x, float y, int pointer) { // Code runs when dragging starts: System.out.println("Started dragging the Pawn!\n"); // Get the team color of the current tile Tile[] gameBoard = getBoard(); Piece.Color teamColor = gameBoard[i].getPiece().getColour(); // If it's not the current team's turn, cancel the drag and return if (!(teamColor == getTurn())) { event.cancel(); System.out.println("It's not your turn!\n"); renderBoard(); return; } System.out.println("Current Stick Value: " + currentStickValue + "\n"); System.out.println("Current Tile: " + board[i].getPosition() + "\n"); System.out.println("Current Team" + teamColor + "\n"); if(board[i].isMoveValid(board[i].getPosition(), currentStickValue)){ System.out.println("Move for this piece valid. Setting allowed tile.");
setAllowedTile(board[i].getPosition()+currentStickValue);
7
2023-12-05 22:19:00+00:00
24k
sinbad-navigator/erp-crm
erp/src/main/java/com/ec/erp/controller/ErpOrderController.java
[ { "identifier": "BaseController", "path": "common/src/main/java/com/ec/common/core/controller/BaseController.java", "snippet": "public class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBi...
import com.ec.common.annotation.Log; import com.ec.common.core.controller.BaseController; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.page.TableDataInfo; import com.ec.common.enums.BusinessType; import com.ec.common.utils.poi.ExcelUtil; import com.ec.erp.domain.ErpOrder; import com.ec.erp.service.IErpClientService; import com.ec.erp.service.IErpOrderService; import com.ec.erp.service.IErpStorageFlowService; import com.ec.erp.service.IErpTaxInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List;
15,414
package com.ec.erp.controller; /** * 库存销售订单Controller * * @author xxx * @date xxxx-xx-xx */ @RestController @RequestMapping("/erp/order") public class ErpOrderController extends BaseController { @Autowired private IErpOrderService erpOrderService; @Autowired private IErpClientService erpClientService; @Autowired private IErpTaxInfoService erpTaxInfoService; @Autowired private IErpStorageFlowService erpStorageFlowService; /** * 查询库存销售订单列表 */ @PreAuthorize("@ss.hasPermi('erp:order:list')") @GetMapping("/list") public TableDataInfo list(ErpOrder erpOrder) { startPage(); List<ErpOrder> list = erpOrderService.selectErpOrderList(erpOrder); return getDataTable(list); } /** * 导出库存销售订单列表 */ @PreAuthorize("@ss.hasPermi('erp:order:export')")
package com.ec.erp.controller; /** * 库存销售订单Controller * * @author xxx * @date xxxx-xx-xx */ @RestController @RequestMapping("/erp/order") public class ErpOrderController extends BaseController { @Autowired private IErpOrderService erpOrderService; @Autowired private IErpClientService erpClientService; @Autowired private IErpTaxInfoService erpTaxInfoService; @Autowired private IErpStorageFlowService erpStorageFlowService; /** * 查询库存销售订单列表 */ @PreAuthorize("@ss.hasPermi('erp:order:list')") @GetMapping("/list") public TableDataInfo list(ErpOrder erpOrder) { startPage(); List<ErpOrder> list = erpOrderService.selectErpOrderList(erpOrder); return getDataTable(list); } /** * 导出库存销售订单列表 */ @PreAuthorize("@ss.hasPermi('erp:order:export')")
@Log(title = "库存销售订单", businessType = BusinessType.EXPORT)
3
2023-12-07 14:23:12+00:00
24k
Crydsch/the-one
src/routing/ProphetRouterWithEstimation.java
[ { "identifier": "RoutingInfo", "path": "src/routing/util/RoutingInfo.java", "snippet": "public class RoutingInfo {\n\tprivate String text;\n\tprivate List<RoutingInfo> moreInfo = null;\n\n\t/**\n\t * Creates a routing info based on a text.\n\t * @param infoText The text of the info\n\t */\n\tpublic Rout...
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock;
19,126
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */
double currentTime = SimClock.getTime();
6
2023-12-10 15:51:41+00:00
24k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java
[ { "identifier": "DialogHelper", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java", "snippet": "public class DialogHelper {\n\n\tpublic static int savedDialog = DialogHelper.DIALOG_NONE;\n\n\tpublic final static int DIALOG_NONE = -1;\n\tpublic final static in...
import android.content.Intent; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.util.Size; import android.view.View; import android.widget.Toast; import com.seleuco.mame4droid.helpers.DialogHelper; import com.seleuco.mame4droid.helpers.PrefsHelper; import com.seleuco.mame4droid.helpers.SAFHelper; import com.seleuco.mame4droid.input.TouchController; import com.seleuco.mame4droid.views.EmulatorViewGL; import java.io.File; import java.nio.ByteBuffer;
21,304
public static ByteBuffer getScreenBuffer() { return screenBuff; } public static void setMAME4droid(MAME4droid mm) { Emulator.mm = mm; } //VIDEO public static void setWindowSize(int w, int h) { //System.out.println("window size "+w+" "+h); window_width = w; window_height = h; if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) return; mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height)); } //synchronized static void bitblt(ByteBuffer sScreenBuff) { //Log.d("Thread Video", "fuera lock"); synchronized (lock1) { try { //Log.d("Thread Video", "dentro lock"); screenBuff = sScreenBuff; Emulator.inMenu = Emulator.getValue(Emulator.IN_MENU) == 1; if (inMenu != oldInMenu) { if(!inMenu && isSaveorload()) setSaveorload(false); final View v = mm.getInputView(); if (v != null) { mm.runOnUiThread(new Runnable() { public void run() { v.invalidate(); } }); } } oldInMenu = inMenu; if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) { ((EmulatorViewGL) mm.getEmuView()).requestRender(); } else { Log.e("Thread Video", "Renderer not supported."); } //Log.d("Thread Video", "fin lock"); } catch (/*Throwable*/NullPointerException t) { Log.getStackTraceString(t); t.printStackTrace(); } } } //synchronized static public void changeVideo(final int newWidth, final int newHeight) { Log.d("Thread Video", "changeVideo emu_width:"+emu_width+" emu_height: "+emu_height+" newWidth:"+newWidth+" newHeight: "+newHeight); synchronized (lock1) { mm.getInputHandler().resetInput(); warnResChanged = emu_width != newWidth || emu_height != newHeight; //if(emu_width!=newWidth || emu_height!=newHeight) //{ emu_width = newWidth; emu_height = newHeight; mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height)); if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) { GLRenderer r = (GLRenderer) ((EmulatorViewGL) mm.getEmuView()).getRender(); if (r != null) r.changedEmulatedSize(); } else { Log.e("Thread Video", "Error renderer not supported"); } mm.getMainHelper().updateEmuValues(); mm.runOnUiThread(new Runnable() { public void run() { //Toast.makeText(mm, "changeVideo newWidth:"+newWidth+" newHeight:"+newHeight+" newVisWidth:"+newVisWidth+" newVisHeight:"+newVisHeight,Toast.LENGTH_SHORT).show(); mm.overridePendingTransition(0, 0); /* if (warnResChanged && videoRenderMode == PrefsHelper.PREF_RENDER_GL && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) mm.getEmuView().setVisibility(View.INVISIBLE); */ mm.getMainHelper().updateMAME4droid(); if (mm.getEmuView().getVisibility() != View.VISIBLE) mm.getEmuView().setVisibility(View.VISIBLE); } }); //} } } static public void initInput() { Log.d("initInput","initInput isInGame:"+isInGame()+" isInMenu:"+isInMenu()); mm.runOnUiThread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } if ( /*Emulator.getValue(Emulator.IN_GAME) == 1 && Emulator.getValue(Emulator.IN_MENU) == 0 &&*/ (((mm.getPrefsHelper().isTouchLightgun() || mm.getPrefsHelper().isTouchGameMouse()) && mm.getInputHandler()
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid; public class Emulator { //gets final static public int IN_MENU = 1; final static public int IN_GAME = 2; final static public int NUMBTNS = 3; final static public int NUMWAYS = 4; final static public int IS_LIGHTGUN = 5; //sets final static public int EXIT_GAME = 1; final static public int EXIT_PAUSE = 2; final static public int SHOW_FPS = 3; final static public int AUTO_FRAMESKIP = 4; final static public int CHEATS = 5; final static public int SKIP_GAMEINFO = 6; final static public int DISABLE_DRC = 7; final static public int DRC_USE_C = 8; final static public int SIMPLE_UI = 9; final static public int PAUSE = 11; final static public int SOUND_VALUE = 13; final static public int AUTOSAVE = 16; final static public int SAVESTATE = 17; final static public int LOADSTATE = 18; final static public int OSD_RESOLUTION = 20; final static public int EMU_RESOLUTION = 21; final static public int ZOOM_TO_WINDOW = 22; final static public int DOUBLE_BUFFER = 23; final static public int PXASP1 = 24; final static public int VBEAM2X = 34; final static public int VFLICKER = 36; final static public int SOUND_OPTIMAL_FRAMES = 48; final static public int SOUND_OPTIMAL_SAMPLERATE = 49; final static public int SOUND_ENGINE = 50; final static public int MOUSE = 60; final static public int REFRESH = 61; final static public int USING_SAF = 62; final static public int SAVESATES_IN_ROM_PATH = 63; final static public int WARN_ON_EXIT = 64; final static public int IS_MOUSE = 65; final static public int KEYBOARD = 66; final static public int ONE_PROCESSOR = 67; final static public int NODEADZONEANDSAT = 68; final static public int MAMEINI = 69; //set str final static public int SAF_PATH = 1; final static public int ROM_NAME = 2; final static public int VERSION = 3; final static public int OVERLAY_EFECT = 4; //get str final static public int MAME_VERSION = 1; //KEYS ACTIONS final static public int KEY_DOWN = 1; final static public int KEY_UP = 2; //MOUSE ACTIONS final static public int MOUSE_MOVE = 1; final static public int MOUSE_BTN_DOWN = 2; final static public int MOUSE_BTN_UP = 3; private static MAME4droid mm = null; private static boolean isEmulating = false; public static boolean isEmulating() { return isEmulating; } private static Object lock1 = new Object(); private static ByteBuffer screenBuff = null; private static boolean emuFiltering = false; public static boolean isEmuFiltering() { return emuFiltering; } public static void setEmuFiltering(boolean value) { emuFiltering = value; } private static Paint debugPaint = new Paint(); private static Matrix mtx = new Matrix(); private static int window_width = 320; public static int getWindow_width() { return window_width; } private static int window_height = 240; public static int getWindow_height() { return window_height; } private static int emu_width = 320; private static int emu_height = 240; private static AudioTrack audioTrack = null; private static boolean isDebug = false; private static int videoRenderMode = PrefsHelper.PREF_RENDER_GL; private static boolean inMenu = false; private static boolean oldInMenu = false; public static boolean isInGame() { return Emulator.getValue(Emulator.IN_GAME) == 1; } public static boolean isInMenu() { return inMenu; } public static boolean isInGameButNotInMenu() { return isInGame() && !isInMenu(); } private static boolean saveorload = false; public static void setSaveorload(boolean value){saveorload=value;} public static boolean isSaveorload(){return saveorload;}; private static boolean inOptions = false; public static void setInOptions(boolean value){ inOptions =value;} public static boolean isInOptions(){return inOptions;}; private static boolean needsRestart = false; public static void setNeedRestart(boolean value) { needsRestart = value; } public static boolean isRestartNeeded() { return needsRestart; } private static boolean warnResChanged = false; public static boolean isWarnResChanged() { return warnResChanged; } public static void setWarnResChanged(boolean warnResChanged) { Emulator.warnResChanged = warnResChanged; } private static boolean paused = true; public static boolean isPaused() { return paused; } private static boolean portraitFull = false; public static boolean isPortraitFull() { return portraitFull; } public static void setPortraitFull(boolean portraitFull) { Emulator.portraitFull = portraitFull; } static { try { System.loadLibrary("mame4droid-jni"); } catch (java.lang.Error e) { e.printStackTrace(); } debugPaint.setARGB(255, 255, 255, 255); debugPaint.setStyle(Style.STROKE); debugPaint.setTextSize(16); } public static int getEmulatedWidth() { return emu_width; } public static int getEmulatedHeight() { return emu_height; } public static boolean isDebug() { return isDebug; } public static void setDebug(boolean isDebug) { Emulator.isDebug = isDebug; } public static int getVideoRenderMode() { return Emulator.videoRenderMode; } public static void setVideoRenderMode(int videoRenderMode) { Emulator.videoRenderMode = videoRenderMode; } public static Paint getDebugPaint() { return debugPaint; } public static Matrix getMatrix() { return mtx; } //synchronized public static ByteBuffer getScreenBuffer() { return screenBuff; } public static void setMAME4droid(MAME4droid mm) { Emulator.mm = mm; } //VIDEO public static void setWindowSize(int w, int h) { //System.out.println("window size "+w+" "+h); window_width = w; window_height = h; if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) return; mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height)); } //synchronized static void bitblt(ByteBuffer sScreenBuff) { //Log.d("Thread Video", "fuera lock"); synchronized (lock1) { try { //Log.d("Thread Video", "dentro lock"); screenBuff = sScreenBuff; Emulator.inMenu = Emulator.getValue(Emulator.IN_MENU) == 1; if (inMenu != oldInMenu) { if(!inMenu && isSaveorload()) setSaveorload(false); final View v = mm.getInputView(); if (v != null) { mm.runOnUiThread(new Runnable() { public void run() { v.invalidate(); } }); } } oldInMenu = inMenu; if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) { ((EmulatorViewGL) mm.getEmuView()).requestRender(); } else { Log.e("Thread Video", "Renderer not supported."); } //Log.d("Thread Video", "fin lock"); } catch (/*Throwable*/NullPointerException t) { Log.getStackTraceString(t); t.printStackTrace(); } } } //synchronized static public void changeVideo(final int newWidth, final int newHeight) { Log.d("Thread Video", "changeVideo emu_width:"+emu_width+" emu_height: "+emu_height+" newWidth:"+newWidth+" newHeight: "+newHeight); synchronized (lock1) { mm.getInputHandler().resetInput(); warnResChanged = emu_width != newWidth || emu_height != newHeight; //if(emu_width!=newWidth || emu_height!=newHeight) //{ emu_width = newWidth; emu_height = newHeight; mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height)); if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) { GLRenderer r = (GLRenderer) ((EmulatorViewGL) mm.getEmuView()).getRender(); if (r != null) r.changedEmulatedSize(); } else { Log.e("Thread Video", "Error renderer not supported"); } mm.getMainHelper().updateEmuValues(); mm.runOnUiThread(new Runnable() { public void run() { //Toast.makeText(mm, "changeVideo newWidth:"+newWidth+" newHeight:"+newHeight+" newVisWidth:"+newVisWidth+" newVisHeight:"+newVisHeight,Toast.LENGTH_SHORT).show(); mm.overridePendingTransition(0, 0); /* if (warnResChanged && videoRenderMode == PrefsHelper.PREF_RENDER_GL && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) mm.getEmuView().setVisibility(View.INVISIBLE); */ mm.getMainHelper().updateMAME4droid(); if (mm.getEmuView().getVisibility() != View.VISIBLE) mm.getEmuView().setVisibility(View.VISIBLE); } }); //} } } static public void initInput() { Log.d("initInput","initInput isInGame:"+isInGame()+" isInMenu:"+isInMenu()); mm.runOnUiThread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } if ( /*Emulator.getValue(Emulator.IN_GAME) == 1 && Emulator.getValue(Emulator.IN_MENU) == 0 &&*/ (((mm.getPrefsHelper().isTouchLightgun() || mm.getPrefsHelper().isTouchGameMouse()) && mm.getInputHandler()
.getTouchController().getState() != TouchController.STATE_SHOWING_NONE) || mm
3
2023-12-18 11:16:18+00:00
24k
Swofty-Developments/HypixelSkyBlock
type-island/src/main/java/net/swofty/type/island/gui/GUIMinion.java
[ { "identifier": "DataHandler", "path": "generic/src/main/java/net/swofty/types/generic/data/DataHandler.java", "snippet": "public class DataHandler {\n public static Map<UUID, DataHandler> userCache = new HashMap<>();\n @Getter\n private UUID uuid;\n private final Map<String, Datapoint> data...
import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.data.DataHandler; import net.swofty.types.generic.data.datapoints.DatapointMinionData; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.RefreshingGUI; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.inventories.GUIMinionRecipes; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.gui.inventory.item.GUIItem; import net.swofty.types.generic.item.MaterialQuantifiable; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.updater.NonPlayerItemUpdater; import net.swofty.types.generic.minion.IslandMinionData; import net.swofty.types.generic.minion.SkyBlockMinion; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.utility.StringUtility; import java.util.ArrayList; import java.util.List;
20,014
"§eClick to pickup!"); } }); set(new GUIClickableItem(48) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { if (minion.getItemsInMinion().isEmpty()) { player.sendMessage("§cThis Minion does not have any items stored!"); return; } minion.getItemsInMinion().forEach(item -> { player.addAndUpdateItem(new SkyBlockItem(item.getMaterial(), item.getAmount())); }); minion.setItemsInMinion(new ArrayList<>()); refreshItems(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aCollect All", Material.CHEST, 1, "§eClick to collect all items!"); } }); set(new GUIClickableItem(3) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aIdeal Layout", Material.REDSTONE_TORCH, 1, "§7View the most efficient spot for this", "§7minion to be placed in.", " ", "§eClick to view!"); } }); set(new GUIClickableItem(5) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { new GUIMinionRecipes(minion.getMinion(), GUIMinion.this).open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { List<SkyBlockMinion.MinionTier> minionTiers = minion.getMinion().asSkyBlockMinion().getTiers(); return ItemStackCreator.getStack("§aNext Tier", Material.GOLD_INGOT, 1, "§7View the items required to upgrade", "§7this minion to the next tier.", " ", "§7Time Between Actions: §8" + minionTiers.get(minion.getTier() - 1).timeBetweenActions() + "s" + " §l> §a" + minionTiers.get(minion.getTier()).timeBetweenActions() + "s", "§7Max Storage: §8" + minionTiers.get(minion.getTier() - 1).storage() + " §l> " + "§e" + minionTiers.get(minion.getTier()).storage(), " ", "§eClick to view!"); } }); SkyBlockMinion.MinionTier minionTier = minion.getMinion().asSkyBlockMinion().getTiers().get( minion.getTier() - 1 ); int i = 0; for (int slot : SLOTS) { i++; boolean unlocked = minionTier.getSlots() >= i; set(new GUIItem(slot) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return unlocked ? ItemStack.builder(Material.AIR) : ItemStackCreator.createNamedItemStack(Material.WHITE_STAINED_GLASS_PANE); } }); } } @Override public void refreshItems(SkyBlockPlayer player) { if (!player.getSkyBlockIsland().getMinionData().getMinions().contains(minion)) { player.closeInventory(); return; } SkyBlockMinion.MinionTier minionTier = minion.getMinion().asSkyBlockMinion().getTiers().get( minion.getTier() - 1 ); int i = 0; for (int slot : SLOTS) { i++; boolean unlocked = minionTier.getSlots() >= i; int finalI = i; set(new GUIClickableItem(slot) { @Override public boolean canPickup() { return true; } @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { if (!e.getCursorItem().isAir()) { player.sendMessage("§cYou can't put items in this inventory!"); e.setCancelled(true); return; } if (!unlocked) return; if (minion.getItemsInMinion().size() < finalI) return;
package net.swofty.type.island.gui; public class GUIMinion extends SkyBlockInventoryGUI implements RefreshingGUI { private static final int[] SLOTS = new int[]{ 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 39, 40, 41, 42, 43 }; private final IslandMinionData.IslandMinion minion; public GUIMinion(IslandMinionData.IslandMinion minion) { super(minion.getMinion().getDisplay() + " " + StringUtility.getAsRomanNumeral(minion.getTier()), InventoryType.CHEST_6_ROW); this.minion = minion; } @Override public void onOpen(InventoryGUIOpenEvent e) { fill(Material.BLACK_STAINED_GLASS_PANE, ""); set(new GUIClickableItem(53) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { player.closeInventory(); player.addAndUpdateItem(minion.asSkyBlockItem()); minion.removeMinion(); player.getSkyBlockIsland().getMinionData().getMinions().remove(minion); player.sendMessage("§aYou picked up a minion! You currently have " + player.getSkyBlockIsland().getMinionData().getMinions().size() + " out of a maximum of " + player.getDataHandler().get( DataHandler.Data.MINION_DATA, DatapointMinionData.class).getValue().getSlots() + " minions placed."); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aPickup Minion", Material.BEDROCK, 1, "§eClick to pickup!"); } }); set(new GUIClickableItem(48) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { if (minion.getItemsInMinion().isEmpty()) { player.sendMessage("§cThis Minion does not have any items stored!"); return; } minion.getItemsInMinion().forEach(item -> { player.addAndUpdateItem(new SkyBlockItem(item.getMaterial(), item.getAmount())); }); minion.setItemsInMinion(new ArrayList<>()); refreshItems(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aCollect All", Material.CHEST, 1, "§eClick to collect all items!"); } }); set(new GUIClickableItem(3) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aIdeal Layout", Material.REDSTONE_TORCH, 1, "§7View the most efficient spot for this", "§7minion to be placed in.", " ", "§eClick to view!"); } }); set(new GUIClickableItem(5) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { new GUIMinionRecipes(minion.getMinion(), GUIMinion.this).open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { List<SkyBlockMinion.MinionTier> minionTiers = minion.getMinion().asSkyBlockMinion().getTiers(); return ItemStackCreator.getStack("§aNext Tier", Material.GOLD_INGOT, 1, "§7View the items required to upgrade", "§7this minion to the next tier.", " ", "§7Time Between Actions: §8" + minionTiers.get(minion.getTier() - 1).timeBetweenActions() + "s" + " §l> §a" + minionTiers.get(minion.getTier()).timeBetweenActions() + "s", "§7Max Storage: §8" + minionTiers.get(minion.getTier() - 1).storage() + " §l> " + "§e" + minionTiers.get(minion.getTier()).storage(), " ", "§eClick to view!"); } }); SkyBlockMinion.MinionTier minionTier = minion.getMinion().asSkyBlockMinion().getTiers().get( minion.getTier() - 1 ); int i = 0; for (int slot : SLOTS) { i++; boolean unlocked = minionTier.getSlots() >= i; set(new GUIItem(slot) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return unlocked ? ItemStack.builder(Material.AIR) : ItemStackCreator.createNamedItemStack(Material.WHITE_STAINED_GLASS_PANE); } }); } } @Override public void refreshItems(SkyBlockPlayer player) { if (!player.getSkyBlockIsland().getMinionData().getMinions().contains(minion)) { player.closeInventory(); return; } SkyBlockMinion.MinionTier minionTier = minion.getMinion().asSkyBlockMinion().getTiers().get( minion.getTier() - 1 ); int i = 0; for (int slot : SLOTS) { i++; boolean unlocked = minionTier.getSlots() >= i; int finalI = i; set(new GUIClickableItem(slot) { @Override public boolean canPickup() { return true; } @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { if (!e.getCursorItem().isAir()) { player.sendMessage("§cYou can't put items in this inventory!"); e.setCancelled(true); return; } if (!unlocked) return; if (minion.getItemsInMinion().size() < finalI) return;
MaterialQuantifiable item = minion.getItemsInMinion().get(finalI - 1);
8
2023-12-14 09:51:15+00:00
24k
Tianscar/uxgl
desktop/src/test/java/org/example/desktop/foreign/LibraryMapping.java
[ { "identifier": "Pointer", "path": "base/src/main/java/unrefined/nio/Pointer.java", "snippet": "public abstract class Pointer implements Closeable, Duplicatable {\n\n public static final Pointer NULL = Pointer.wrap(0);\n \n private final Allocator allocator;\n\n /**\n * Wraps a Java {@co...
import unrefined.nio.Pointer; import unrefined.runtime.DesktopRuntime; import unrefined.util.UnexpectedError; import unrefined.util.foreign.Foreign; import unrefined.util.foreign.Library; import java.io.IOException; import java.util.Random; import java.util.concurrent.ThreadLocalRandom;
15,962
package org.example.desktop.foreign; /** * UXGL "Library Mapping"! Dynamic proxy objects, working just like JNA! * Note that type mapping as the same of UXGL "Handle Mapping", different from JNA. */ public class LibraryMapping { public interface CLibrary extends Library { void printf(long format, int... args); // Varargs supported! } public static void main(String[] args) { DesktopRuntime.setup(args); // Initialize the UXGL runtime environment
package org.example.desktop.foreign; /** * UXGL "Library Mapping"! Dynamic proxy objects, working just like JNA! * Note that type mapping as the same of UXGL "Handle Mapping", different from JNA. */ public class LibraryMapping { public interface CLibrary extends Library { void printf(long format, int... args); // Varargs supported! } public static void main(String[] args) { DesktopRuntime.setup(args); // Initialize the UXGL runtime environment
Foreign foreign = Foreign.getInstance(); // Get the platform-dependent FFI factory
3
2023-12-15 19:03:31+00:00
24k
litongjava/next-jfinal
src/main/java/com/litongjava/tio/boot/context/JFinalApplicationContext.java
[ { "identifier": "Aop", "path": "src/main/java/com/jfinal/aop/Aop.java", "snippet": "public class Aop {\n\n static AopFactory aopFactory = new AopFactory();\n\n public static <T> T get(Class<T> targetClass) {\n return aopFactory.get(targetClass);\n }\n\n /**\n * 如果需要被注入的成员是一个接口类,从mapping中查找实现类,找...
import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadPoolExecutor; import com.jfinal.aop.Aop; import com.jfinal.aop.AopManager; import com.jfinal.aop.annotation.Import; import com.jfinal.config.JFinalConfig; import com.jfinal.core.JFinal; import com.jfinal.handler.Handler; import com.jfinal.servlet.ServletContext; import com.litongjava.tio.boot.constatns.ConfigKeys; import com.litongjava.tio.boot.http.handler.JFinalHttpRequestHandler; import com.litongjava.tio.boot.http.handler.TioBootHttpRoutes; import com.litongjava.tio.boot.http.interceptor.DefaultHttpServerInterceptor; import com.litongjava.tio.boot.server.TioBootServer; import com.litongjava.tio.boot.server.TioBootServerHandler; import com.litongjava.tio.boot.server.TioBootServerHandlerListener; import com.litongjava.tio.boot.server.TioBootServerListener; import com.litongjava.tio.boot.tcp.ServerHanlderListener; import com.litongjava.tio.boot.tcp.ServerTcpHandler; import com.litongjava.tio.boot.websocket.handler.DefaultWebSocketHandler; import com.litongjava.tio.http.common.HttpConfig; import com.litongjava.tio.http.common.TioConfigKey; import com.litongjava.tio.http.common.handler.HttpRequestHandler; import com.litongjava.tio.http.common.session.id.impl.UUIDSessionIdGenerator; import com.litongjava.tio.server.ServerTioConfig; import com.litongjava.tio.server.TioServer; import com.litongjava.tio.server.intf.ServerAioListener; import com.litongjava.tio.utils.Threads; import com.litongjava.tio.utils.cache.caffeine.CaffeineCache; import com.litongjava.tio.utils.enviorment.EnviormentUtils; import com.litongjava.tio.utils.enviorment.PropUtils; import com.litongjava.tio.utils.thread.pool.SynThreadPoolExecutor; import com.litongjava.tio.websocket.common.WsTioUuid; import com.litongjava.tio.websocket.server.WsServerConfig; import cn.hutool.core.io.resource.ResourceUtil; import lombok.extern.slf4j.Slf4j;
15,046
package com.litongjava.tio.boot.context; @Slf4j public class JFinalApplicationContext implements Context { private TioBootServer tioBootServer; private StartupCallback beforeStart; private StartedCallBack afterStarted; private ShutdownCallback beforeStop; private ShutCallback afterStoped; private JFinal jfinal; /** * 1.服务启动前配置 * 2.启动服务器 * 3.初始配置类 * 4.初始化组件类 * 5.添加JFinal路由 */ @Override public Context run(Class<?>[] primarySources, String[] args) { long scanClassStartTime = System.currentTimeMillis(); long serverStartTime = System.currentTimeMillis(); EnviormentUtils.buildCmdArgsMap(args); String env = EnviormentUtils.get("app.env"); if (ResourceUtil.getResource(ConfigKeys.defaultConfigFileName) != null) { PropUtils.use(ConfigKeys.defaultConfigFileName, env); } else { if (env != null) { PropUtils.use("app-" + env + ".properties"); } } List<Class<?>> scannedClasses = null; // 执行组件扫描 try { scannedClasses = Aop.scan(primarySources); } catch (Exception e1) { e1.printStackTrace(); } // 添加@Improt的类 for (Class<?> primarySource : primarySources) { Import importAnnotaion = primarySource.getAnnotation(Import.class); if (importAnnotaion != null) { Class<?>[] value = importAnnotaion.value(); for (Class<?> clazzz : value) { scannedClasses.add(clazzz); } } } scannedClasses = this.processBeforeStartConfiguration(scannedClasses); long scanClassEndTime = System.currentTimeMillis();
package com.litongjava.tio.boot.context; @Slf4j public class JFinalApplicationContext implements Context { private TioBootServer tioBootServer; private StartupCallback beforeStart; private StartedCallBack afterStarted; private ShutdownCallback beforeStop; private ShutCallback afterStoped; private JFinal jfinal; /** * 1.服务启动前配置 * 2.启动服务器 * 3.初始配置类 * 4.初始化组件类 * 5.添加JFinal路由 */ @Override public Context run(Class<?>[] primarySources, String[] args) { long scanClassStartTime = System.currentTimeMillis(); long serverStartTime = System.currentTimeMillis(); EnviormentUtils.buildCmdArgsMap(args); String env = EnviormentUtils.get("app.env"); if (ResourceUtil.getResource(ConfigKeys.defaultConfigFileName) != null) { PropUtils.use(ConfigKeys.defaultConfigFileName, env); } else { if (env != null) { PropUtils.use("app-" + env + ".properties"); } } List<Class<?>> scannedClasses = null; // 执行组件扫描 try { scannedClasses = Aop.scan(primarySources); } catch (Exception e1) { e1.printStackTrace(); } // 添加@Improt的类 for (Class<?> primarySource : primarySources) { Import importAnnotaion = primarySource.getAnnotation(Import.class); if (importAnnotaion != null) { Class<?>[] value = importAnnotaion.value(); for (Class<?> clazzz : value) { scannedClasses.add(clazzz); } } } scannedClasses = this.processBeforeStartConfiguration(scannedClasses); long scanClassEndTime = System.currentTimeMillis();
TioBootServerListener serverListener = AopManager.me().getAopFactory().getOnly(TioBootServerListener.class);
1
2023-12-19 10:58:33+00:00
24k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/player/AutoFish.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.S2APacketParticles; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.StringUtils; import net.minecraft.util.Vec3; import net.minecraft.world.World; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Disable; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; 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.settings.ModeSetting; import xyz.apfelmus.cheeto.client.utils.client.ChadUtils; import xyz.apfelmus.cheeto.client.utils.client.ChatUtils; import xyz.apfelmus.cheeto.client.utils.client.JsonUtils; import xyz.apfelmus.cheeto.client.utils.client.KeybindUtils; import xyz.apfelmus.cheeto.client.utils.client.Rotation; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.fishing.FishingJson; import xyz.apfelmus.cheeto.client.utils.fishing.Location; import xyz.apfelmus.cheeto.client.utils.fishing.PathPoint; import xyz.apfelmus.cheeto.client.utils.math.RandomUtil; import xyz.apfelmus.cheeto.client.utils.math.TimeHelper; import xyz.apfelmus.cheeto.client.utils.math.VecUtils; import xyz.apfelmus.cheeto.client.utils.render.Render3DUtils; import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils;
17,007
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.block.Block * net.minecraft.client.Minecraft * net.minecraft.client.entity.EntityOtherPlayerMP * net.minecraft.client.gui.GuiChat * net.minecraft.client.settings.KeyBinding * net.minecraft.entity.Entity * net.minecraft.entity.item.EntityArmorStand * net.minecraft.entity.player.EntityPlayer * net.minecraft.entity.projectile.EntityFishHook * net.minecraft.init.Blocks * net.minecraft.init.Items * net.minecraft.item.Item * net.minecraft.item.ItemStack * net.minecraft.network.play.server.S2APacketParticles * net.minecraft.util.BlockPos * net.minecraft.util.EnumParticleTypes * net.minecraft.util.StringUtils * net.minecraft.util.Vec3 * net.minecraft.world.World */ package xyz.apfelmus.cheeto.client.modules.player; @Module(name="AutoFish", category=Category.PLAYER) public class AutoFish { private static FishingJson fishingJson = JsonUtils.getFishingJson(); @Setting(name="FishingSpot", description="Spot to fish at, requires Etherwarp") private ModeSetting fishingSpot = new ModeSetting("None", this.getFishingSpotNames()); @Setting(name="RecastDelay") private IntegerSetting recastDelay = new IntegerSetting(250, 0, 2000); @Setting(name="AntiAfk") private BooleanSetting antiAfk = new BooleanSetting(true); @Setting(name="RodSlot") private IntegerSetting rodSlot = new IntegerSetting(0, 0, 8); @Setting(name="WhipSlot", description="Configure for Automatic SC Killing") private IntegerSetting whipSlot = new IntegerSetting(0, 0, 8); @Setting(name="KillMode", description="Left or Right Click") private ModeSetting killMode = new ModeSetting("Right", Arrays.asList("Left", "Right")); @Setting(name="KillPrio", description="Kill SC before Re-casting (Sword)") private BooleanSetting killPrio = new BooleanSetting(false); @Setting(name="SCRange", description="Range for Sea Creature Killing") private IntegerSetting scRange = new IntegerSetting(10, 0, 20); @Setting(name="PetSwap", description="Activates PetSwap on bobber in water") private BooleanSetting petSwap = new BooleanSetting(false); @Setting(name="AotvSlot") private IntegerSetting aotvSlot = new IntegerSetting(0, 0, 8); @Setting(name="WarpLookTime", description="Set higher if low mana or bad ping") private IntegerSetting warpLookTime = new IntegerSetting(500, 0, 2500); @Setting(name="WarpTime", description="Set higher if low mana or bad ping") private IntegerSetting warpTime = new IntegerSetting(250, 0, 1000); @Setting(name="MaxPlayerRange", description="Range the bot will warp out at") private IntegerSetting maxPlayerRange = new IntegerSetting(5, 0, 10); @Setting(name="Sneak", description="Makes the player sneak while fishing") private BooleanSetting sneak = new BooleanSetting(false); @Setting(name="Ungrab", description="Automatically tabs out") private BooleanSetting ungrab = new BooleanSetting(true); private static Minecraft mc = Minecraft.func_71410_x(); private static List<String> fishingMobs = JsonUtils.getListFromUrl("https://gist.githubusercontent.com/Apfelmus1337/da641d3805bddf800eef170cbb0068ec/raw", "mobs"); private static TimeHelper warpTimer = new TimeHelper(); private static TimeHelper throwTimer = new TimeHelper(); private static TimeHelper inWaterTimer = new TimeHelper(); private static TimeHelper killTimer = new TimeHelper(); private static TimeHelper recoverTimer = new TimeHelper(); private static EntityArmorStand curScStand = null; private static Entity curSc = null; private static boolean killing = false; private static Location currentLocation = null; private static List<PathPoint> path = null; private static BlockPos oldPos = null; private static double oldBobberPosY = 0.0; private static boolean oldBobberInWater = false; private static int ticks = 0; private static Vec3 startPos = null; private static Rotation startRot = null; private static List<ParticleEntry> particleList = new ArrayList<ParticleEntry>(); private AutoFishState afs = AutoFishState.THROWING; private WarpState warpState = WarpState.SETUP; private AAState aaState = AAState.AWAY; @Enable public void onEnable() { this.afs = AutoFishState.THROWING; this.aaState = AAState.AWAY; throwTimer.reset(); inWaterTimer.reset(); warpTimer.reset(); ticks = 0; oldBobberPosY = 0.0; oldBobberInWater = false; curScStand = null; curSc = null; killing = true; particleList.clear();
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.block.Block * net.minecraft.client.Minecraft * net.minecraft.client.entity.EntityOtherPlayerMP * net.minecraft.client.gui.GuiChat * net.minecraft.client.settings.KeyBinding * net.minecraft.entity.Entity * net.minecraft.entity.item.EntityArmorStand * net.minecraft.entity.player.EntityPlayer * net.minecraft.entity.projectile.EntityFishHook * net.minecraft.init.Blocks * net.minecraft.init.Items * net.minecraft.item.Item * net.minecraft.item.ItemStack * net.minecraft.network.play.server.S2APacketParticles * net.minecraft.util.BlockPos * net.minecraft.util.EnumParticleTypes * net.minecraft.util.StringUtils * net.minecraft.util.Vec3 * net.minecraft.world.World */ package xyz.apfelmus.cheeto.client.modules.player; @Module(name="AutoFish", category=Category.PLAYER) public class AutoFish { private static FishingJson fishingJson = JsonUtils.getFishingJson(); @Setting(name="FishingSpot", description="Spot to fish at, requires Etherwarp") private ModeSetting fishingSpot = new ModeSetting("None", this.getFishingSpotNames()); @Setting(name="RecastDelay") private IntegerSetting recastDelay = new IntegerSetting(250, 0, 2000); @Setting(name="AntiAfk") private BooleanSetting antiAfk = new BooleanSetting(true); @Setting(name="RodSlot") private IntegerSetting rodSlot = new IntegerSetting(0, 0, 8); @Setting(name="WhipSlot", description="Configure for Automatic SC Killing") private IntegerSetting whipSlot = new IntegerSetting(0, 0, 8); @Setting(name="KillMode", description="Left or Right Click") private ModeSetting killMode = new ModeSetting("Right", Arrays.asList("Left", "Right")); @Setting(name="KillPrio", description="Kill SC before Re-casting (Sword)") private BooleanSetting killPrio = new BooleanSetting(false); @Setting(name="SCRange", description="Range for Sea Creature Killing") private IntegerSetting scRange = new IntegerSetting(10, 0, 20); @Setting(name="PetSwap", description="Activates PetSwap on bobber in water") private BooleanSetting petSwap = new BooleanSetting(false); @Setting(name="AotvSlot") private IntegerSetting aotvSlot = new IntegerSetting(0, 0, 8); @Setting(name="WarpLookTime", description="Set higher if low mana or bad ping") private IntegerSetting warpLookTime = new IntegerSetting(500, 0, 2500); @Setting(name="WarpTime", description="Set higher if low mana or bad ping") private IntegerSetting warpTime = new IntegerSetting(250, 0, 1000); @Setting(name="MaxPlayerRange", description="Range the bot will warp out at") private IntegerSetting maxPlayerRange = new IntegerSetting(5, 0, 10); @Setting(name="Sneak", description="Makes the player sneak while fishing") private BooleanSetting sneak = new BooleanSetting(false); @Setting(name="Ungrab", description="Automatically tabs out") private BooleanSetting ungrab = new BooleanSetting(true); private static Minecraft mc = Minecraft.func_71410_x(); private static List<String> fishingMobs = JsonUtils.getListFromUrl("https://gist.githubusercontent.com/Apfelmus1337/da641d3805bddf800eef170cbb0068ec/raw", "mobs"); private static TimeHelper warpTimer = new TimeHelper(); private static TimeHelper throwTimer = new TimeHelper(); private static TimeHelper inWaterTimer = new TimeHelper(); private static TimeHelper killTimer = new TimeHelper(); private static TimeHelper recoverTimer = new TimeHelper(); private static EntityArmorStand curScStand = null; private static Entity curSc = null; private static boolean killing = false; private static Location currentLocation = null; private static List<PathPoint> path = null; private static BlockPos oldPos = null; private static double oldBobberPosY = 0.0; private static boolean oldBobberInWater = false; private static int ticks = 0; private static Vec3 startPos = null; private static Rotation startRot = null; private static List<ParticleEntry> particleList = new ArrayList<ParticleEntry>(); private AutoFishState afs = AutoFishState.THROWING; private WarpState warpState = WarpState.SETUP; private AAState aaState = AAState.AWAY; @Enable public void onEnable() { this.afs = AutoFishState.THROWING; this.aaState = AAState.AWAY; throwTimer.reset(); inWaterTimer.reset(); warpTimer.reset(); ticks = 0; oldBobberPosY = 0.0; oldBobberInWater = false; curScStand = null; curSc = null; killing = true; particleList.clear();
RotationUtils.reset();
13
2023-12-21 16:22:25+00:00
24k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/writer/builder/BuilderClassPool.java
[ { "identifier": "DebugItemType", "path": "app/src/main/java/org/jf/dexlib2/DebugItemType.java", "snippet": "public final class DebugItemType {\n // The debug items that directly correspond with one of the dexlib2.iface.debug interfaces\n public static final int START_LOCAL = 0x03;\n public stat...
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import org.jf.dexlib2.DebugItemType; import org.jf.dexlib2.builder.MutableMethodImplementation; import org.jf.dexlib2.iface.ExceptionHandler; import org.jf.dexlib2.iface.Field; import org.jf.dexlib2.iface.MethodImplementation; import org.jf.dexlib2.iface.TryBlock; import org.jf.dexlib2.iface.debug.DebugItem; import org.jf.dexlib2.iface.debug.EndLocal; import org.jf.dexlib2.iface.debug.LineNumber; import org.jf.dexlib2.iface.debug.RestartLocal; import org.jf.dexlib2.iface.debug.SetSourceFile; import org.jf.dexlib2.iface.debug.StartLocal; import org.jf.dexlib2.iface.instruction.Instruction; import org.jf.dexlib2.iface.reference.StringReference; import org.jf.dexlib2.iface.reference.TypeReference; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.util.EncodedValueUtils; import org.jf.dexlib2.writer.ClassSection; import org.jf.dexlib2.writer.DebugWriter; import org.jf.dexlib2.writer.builder.BuilderEncodedValues.BuilderEncodedValue; import org.jf.util.AbstractForwardSequentialList; import org.jf.util.CollectionUtils; import org.jf.util.ExceptionWithContext; import java.io.IOException; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.concurrent.ConcurrentMap;
20,334
if (lastIndex > -1) { return new AbstractCollection<BuilderEncodedValue>() { @NonNull @Override public Iterator<BuilderEncodedValue> iterator() { return FluentIterable.from(sortedStaticFields) .limit(lastIndex + 1) .transform(GET_INITIAL_VALUE).iterator(); } @Override public int size() { return lastIndex + 1; } }; } return null; } @NonNull @Override public Collection<? extends BuilderField> getSortedStaticFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getStaticFields(); } @NonNull @Override public Collection<? extends BuilderField> getSortedInstanceFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getInstanceFields(); } @NonNull @Override public Collection<? extends BuilderField> getSortedFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getFields(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedDirectMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getDirectMethods(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedVirtualMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getVirtualMethods(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getMethods(); } @Override public int getFieldAccessFlags(@NonNull BuilderField builderField) { return builderField.accessFlags; } @Override public int getMethodAccessFlags(@NonNull BuilderMethod builderMethod) { return builderMethod.accessFlags; } @Nullable @Override public BuilderAnnotationSet getClassAnnotations(@NonNull BuilderClassDef builderClassDef) { if (builderClassDef.annotations.isEmpty()) { return null; } return builderClassDef.annotations; } @Nullable @Override public BuilderAnnotationSet getFieldAnnotations(@NonNull BuilderField builderField) { if (builderField.annotations.isEmpty()) { return null; } return builderField.annotations; } @Nullable @Override public BuilderAnnotationSet getMethodAnnotations(@NonNull BuilderMethod builderMethod) { if (builderMethod.annotations.isEmpty()) { return null; } return builderMethod.annotations; } @Nullable @Override public List<? extends BuilderAnnotationSet> getParameterAnnotations( @NonNull final BuilderMethod method) { final List<? extends BuilderMethodParameter> parameters = method.getParameters(); boolean hasParameterAnnotations = Iterables.any(parameters, HAS_PARAMETER_ANNOTATIONS); if (hasParameterAnnotations) { return new AbstractForwardSequentialList<BuilderAnnotationSet>() { @NonNull @Override public Iterator<BuilderAnnotationSet> iterator() { return FluentIterable.from(parameters) .transform(PARAMETER_ANNOTATIONS).iterator(); } @Override public int size() { return parameters.size(); } }; } return null; } @Nullable @Override public Iterable<? extends DebugItem> getDebugItems(@NonNull BuilderMethod builderMethod) {
/* * 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 class BuilderClassPool extends BaseBuilderPool implements ClassSection<BuilderStringReference, BuilderTypeReference, BuilderTypeList, BuilderClassDef, BuilderField, BuilderMethod, BuilderAnnotationSet, BuilderEncodedValue> { private static final Predicate<Field> HAS_INITIALIZER = new Predicate<Field>() { @Override public boolean apply(Field input) { EncodedValue encodedValue = input.getInitialValue(); return encodedValue != null && !EncodedValueUtils.isDefaultValue(encodedValue); } }; private static final Function<BuilderField, BuilderEncodedValue> GET_INITIAL_VALUE = new Function<BuilderField, BuilderEncodedValue>() { @Override public BuilderEncodedValue apply(BuilderField input) { BuilderEncodedValue initialValue = input.getInitialValue(); if (initialValue == null) { return BuilderEncodedValues.defaultValueForType(input.getType()); } return initialValue; } }; private static final Predicate<BuilderMethodParameter> HAS_PARAMETER_ANNOTATIONS = new Predicate<BuilderMethodParameter>() { @Override public boolean apply(BuilderMethodParameter input) { return input.getAnnotations().size() > 0; } }; private static final Function<BuilderMethodParameter, BuilderAnnotationSet> PARAMETER_ANNOTATIONS = new Function<BuilderMethodParameter, BuilderAnnotationSet>() { @Override public BuilderAnnotationSet apply(BuilderMethodParameter input) { return input.getAnnotations(); } }; @NonNull private final ConcurrentMap<String, BuilderClassDef> internedItems = Maps.newConcurrentMap(); private ImmutableList<BuilderClassDef> sortedClasses = null; public BuilderClassPool(@NonNull DexBuilder dexBuilder) { super(dexBuilder); } @NonNull BuilderClassDef internClass(@NonNull BuilderClassDef classDef) { BuilderClassDef prev = internedItems.put(classDef.getType(), classDef); if (prev != null) { throw new ExceptionWithContext("Class %s has already been interned", classDef.getType()); } return classDef; } @NonNull @Override public Collection<? extends BuilderClassDef> getSortedClasses() { if (sortedClasses == null) { sortedClasses = Ordering.natural().immutableSortedCopy(internedItems.values()); } return sortedClasses; } @Nullable @Override public Entry<? extends BuilderClassDef, Integer> getClassEntryByType(@Nullable BuilderTypeReference type) { if (type == null) { return null; } final BuilderClassDef classDef = internedItems.get(type.getType()); if (classDef == null) { return null; } return new Map.Entry<BuilderClassDef, Integer>() { @Override public BuilderClassDef getKey() { return classDef; } @Override public Integer getValue() { return classDef.classDefIndex; } @Override public Integer setValue(Integer value) { return classDef.classDefIndex = value; } }; } @NonNull @Override public BuilderTypeReference getType(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.type; } @Override public int getAccessFlags(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.accessFlags; } @Nullable @Override public BuilderTypeReference getSuperclass(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.superclass; } @Nullable @Override public BuilderTypeList getInterfaces(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.interfaces; } @Nullable @Override public BuilderStringReference getSourceFile(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.sourceFile; } @Nullable @Override public Collection<? extends BuilderEncodedValue> getStaticInitializers(@NonNull BuilderClassDef classDef) { final SortedSet<BuilderField> sortedStaticFields = classDef.getStaticFields(); final int lastIndex = CollectionUtils.lastIndexOf(sortedStaticFields, HAS_INITIALIZER); if (lastIndex > -1) { return new AbstractCollection<BuilderEncodedValue>() { @NonNull @Override public Iterator<BuilderEncodedValue> iterator() { return FluentIterable.from(sortedStaticFields) .limit(lastIndex + 1) .transform(GET_INITIAL_VALUE).iterator(); } @Override public int size() { return lastIndex + 1; } }; } return null; } @NonNull @Override public Collection<? extends BuilderField> getSortedStaticFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getStaticFields(); } @NonNull @Override public Collection<? extends BuilderField> getSortedInstanceFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getInstanceFields(); } @NonNull @Override public Collection<? extends BuilderField> getSortedFields(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getFields(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedDirectMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getDirectMethods(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedVirtualMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getVirtualMethods(); } @NonNull @Override public Collection<? extends BuilderMethod> getSortedMethods(@NonNull BuilderClassDef builderClassDef) { return builderClassDef.getMethods(); } @Override public int getFieldAccessFlags(@NonNull BuilderField builderField) { return builderField.accessFlags; } @Override public int getMethodAccessFlags(@NonNull BuilderMethod builderMethod) { return builderMethod.accessFlags; } @Nullable @Override public BuilderAnnotationSet getClassAnnotations(@NonNull BuilderClassDef builderClassDef) { if (builderClassDef.annotations.isEmpty()) { return null; } return builderClassDef.annotations; } @Nullable @Override public BuilderAnnotationSet getFieldAnnotations(@NonNull BuilderField builderField) { if (builderField.annotations.isEmpty()) { return null; } return builderField.annotations; } @Nullable @Override public BuilderAnnotationSet getMethodAnnotations(@NonNull BuilderMethod builderMethod) { if (builderMethod.annotations.isEmpty()) { return null; } return builderMethod.annotations; } @Nullable @Override public List<? extends BuilderAnnotationSet> getParameterAnnotations( @NonNull final BuilderMethod method) { final List<? extends BuilderMethodParameter> parameters = method.getParameters(); boolean hasParameterAnnotations = Iterables.any(parameters, HAS_PARAMETER_ANNOTATIONS); if (hasParameterAnnotations) { return new AbstractForwardSequentialList<BuilderAnnotationSet>() { @NonNull @Override public Iterator<BuilderAnnotationSet> iterator() { return FluentIterable.from(parameters) .transform(PARAMETER_ANNOTATIONS).iterator(); } @Override public int size() { return parameters.size(); } }; } return null; } @Nullable @Override public Iterable<? extends DebugItem> getDebugItems(@NonNull BuilderMethod builderMethod) {
MethodImplementation impl = builderMethod.getImplementation();
4
2023-12-16 11:11:16+00:00
24k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/level/tile/a.java
[ { "identifier": "Vector3DCreator", "path": "src/com/mojang/minecraft/Vector3DCreator.java", "snippet": "public final class Vector3DCreator {\r\n\r\n public Vector3DCreator(int var1, int var2, int var3, int var4, Vector3D var5) {\r\n new Vector3D(var5.x, var5.y, var5.z);\r\n }\r\n}\r" }, { ...
import com.mojang.minecraft.Vector3DCreator; import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.LiquidType; import com.mojang.minecraft.level.tile.Tile$SoundType; import com.mojang.minecraft.level.tile.c; import com.mojang.minecraft.level.tile.d; import com.mojang.minecraft.level.tile.e; import com.mojang.minecraft.level.tile.f; import com.mojang.minecraft.level.tile.g; import com.mojang.minecraft.level.tile.h; import com.mojang.minecraft.level.tile.i; import com.mojang.minecraft.level.tile.j; import com.mojang.minecraft.level.tile.k; import com.mojang.minecraft.level.tile.l; import com.mojang.minecraft.level.tile.m; import com.mojang.minecraft.level.tile.n; import com.mojang.minecraft.level.tile.o; import com.mojang.minecraft.level.tile.p; import com.mojang.minecraft.level.tile.q; import com.mojang.minecraft.level.tile.r; import com.mojang.minecraft.level.tile.s; import com.mojang.minecraft.level.tile.t; import com.mojang.minecraft.model.Vector3D; import com.mojang.minecraft.phys.AABB; import java.util.Random;
19,285
package com.mojang.minecraft.level.tile; public class a { protected static Random a = new Random(); public static final a[] b = new a[256]; public static final boolean[] c = new boolean[256]; private static boolean[] ad = new boolean[256]; private static boolean[] ae = new boolean[256]; public static final boolean[] d = new boolean[256]; private static int[] af = new int[256]; public static final a e; public static final a f;
package com.mojang.minecraft.level.tile; public class a { protected static Random a = new Random(); public static final a[] b = new a[256]; public static final boolean[] c = new boolean[256]; private static boolean[] ad = new boolean[256]; private static boolean[] ae = new boolean[256]; public static final boolean[] d = new boolean[256]; private static int[] af = new int[256]; public static final a e; public static final a f;
public static final a g;
8
2023-12-18 15:38:59+00:00
24k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AcquistoController.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.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.TitoloViaggioService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.VoucherService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.CorsaSingola; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.TipoTitoloViaggio; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import it.unipv.po.aioobe.trenissimo.view.HomePage; import it.unipv.po.aioobe.trenissimo.view.ViaggioControl; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.net.URL; import java.util.*;
17,253
if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception { TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity; titoloViaggioEntity = titoloViaggioService.findById(a.getId()); if (a.getId().startsWith("CS")) titoloViaggio = new TicketBuilder(titoloViaggioEntity.getStazionePartenza(), titoloViaggioEntity.getStazioneArrivo(), titoloViaggioEntity.getDataPartenza().toString(), titoloViaggioEntity.getDataArrivo().toString(), titoloViaggioEntity.getOraPartenza().toString(), titoloViaggioEntity.getOraArrivo().toString(), txtNome.getText(), txtCognome.getText(), dtpDataNascita.getValue().toString(), a.getId(), String.valueOf(a.getPrezzo()), String.valueOf(_viaggi.get(0).getNumAdulti()), String.valueOf(_viaggi.get(0).getNumRagazzi()), String.valueOf(_viaggi.get(0).getNumBambini()), String.valueOf(_viaggi.get(0).getNumAnimali())); titoloViaggio.createPdf(a.getId()); } /** * Gestisce il riscatto del voucher * * @throws Exception * @see VoucherService * @see Utils * @see Task * @see Thread */ @FXML protected void onRiscatta() throws Exception {
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per acquistoView.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.acquistoView * @see javafx.fxml.Initializable */ public class AcquistoController implements Initializable { @FXML private BorderPane root; @FXML private VBox boxViaggi; @FXML private Button btnAcquisto; @FXML private TextField txtNumCarta; @FXML private TextField txtDataScadenza; @FXML private TextField txtCVV; @FXML private Label lblRiscattoOK; @FXML private Label lblErroreRiscatto; @FXML private Button btnRiscatta; @FXML private TextField txtVoucher; @FXML private Label lblSubtotale; @FXML private Label lblIVA; @FXML private Label lblSconto; @FXML private Label lblTotale; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Button btnAggiungiPagamento; @FXML private Label lblErroreNumCarta; @FXML private Label lblErroreData; @FXML private Label lblErroreCVV; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; private ObservableList<Viaggio> _viaggi; private TicketBuilder titoloViaggio; private boolean isIdVoucherOK; private Double subtotale; private Double iva; private boolean acquistoSoloVoucher; private boolean isRiscattoUsed; private File biglietto; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkIdRealTime() * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account * @see ViaggioControl */ @Override public void initialize(URL location, ResourceBundle resources) { _viaggi = FXCollections.observableArrayList(); _viaggi.addListener((ListChangeListener<Viaggio>) c -> { boxViaggi.getChildren().setAll(_viaggi.stream().map(x -> new ViaggioControl(x, null)).toList()); }); this.subtotale = 0.0; this.iva = 0.0; this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception { TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity; titoloViaggioEntity = titoloViaggioService.findById(a.getId()); if (a.getId().startsWith("CS")) titoloViaggio = new TicketBuilder(titoloViaggioEntity.getStazionePartenza(), titoloViaggioEntity.getStazioneArrivo(), titoloViaggioEntity.getDataPartenza().toString(), titoloViaggioEntity.getDataArrivo().toString(), titoloViaggioEntity.getOraPartenza().toString(), titoloViaggioEntity.getOraArrivo().toString(), txtNome.getText(), txtCognome.getText(), dtpDataNascita.getValue().toString(), a.getId(), String.valueOf(a.getPrezzo()), String.valueOf(_viaggi.get(0).getNumAdulti()), String.valueOf(_viaggi.get(0).getNumRagazzi()), String.valueOf(_viaggi.get(0).getNumBambini()), String.valueOf(_viaggi.get(0).getNumAnimali())); titoloViaggio.createPdf(a.getId()); } /** * Gestisce il riscatto del voucher * * @throws Exception * @see VoucherService * @see Utils * @see Task * @see Thread */ @FXML protected void onRiscatta() throws Exception {
VoucherService voucherService = new VoucherService();
4
2023-12-21 10:41:11+00:00
24k
green-code-initiative/ecoCode-java
src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java
[ { "identifier": "ArrayCopyCheck", "path": "src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java", "snippet": "@Rule(key = \"EC27\")\n@DeprecatedRuleKey(repositoryKey = \"greencodeinitiative-java\", ruleKey = \"GRPS0027\")\npublic class ArrayCopyCheck extends IssuableSubscriptionVisitor {...
import java.util.Collections; import java.util.List; import fr.greencodeinitiative.java.checks.ArrayCopyCheck; import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; import fr.greencodeinitiative.java.checks.IncrementCheck; import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; import fr.greencodeinitiative.java.checks.UseCorrectForLoop; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide;
14,735
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * 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 <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class, AvoidConcatenateStringsInLoop.class, AvoidUsageOfStaticCollections.class, AvoidGettingSizeCollectionInLoop.class, AvoidRegexPatternNotStatic.class,
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * 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 <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class, AvoidConcatenateStringsInLoop.class, AvoidUsageOfStaticCollections.class, AvoidGettingSizeCollectionInLoop.class, AvoidRegexPatternNotStatic.class,
NoFunctionCallWhenDeclaringForLoop.class,
15
2023-12-19 20:38:40+00:00
24k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/GunMod.java
[ { "identifier": "ClientHandler", "path": "src/main/java/com/mrcrayfish/guns/client/ClientHandler.java", "snippet": "@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT)\npublic class ClientHandler\n{\n private static Field mouseOptionsField;\n\n public static void setup()\n {\...
import com.mrcrayfish.framework.api.FrameworkAPI; import com.mrcrayfish.framework.api.client.FrameworkClientAPI; import com.mrcrayfish.guns.client.ClientHandler; import com.mrcrayfish.guns.client.CustomGunManager; import com.mrcrayfish.guns.client.KeyBinds; import com.mrcrayfish.guns.client.MetaLoader; import com.mrcrayfish.guns.client.SpecialModels; import com.mrcrayfish.guns.client.handler.CrosshairHandler; import com.mrcrayfish.guns.common.BoundingBoxManager; import com.mrcrayfish.guns.common.NetworkGunManager; import com.mrcrayfish.guns.common.ProjectileManager; import com.mrcrayfish.guns.crafting.WorkbenchIngredient; import com.mrcrayfish.guns.datagen.BlockTagGen; import com.mrcrayfish.guns.datagen.GunGen; import com.mrcrayfish.guns.datagen.ItemTagGen; import com.mrcrayfish.guns.datagen.LanguageGen; import com.mrcrayfish.guns.datagen.LootTableGen; import com.mrcrayfish.guns.datagen.RecipeGen; import com.mrcrayfish.guns.enchantment.EnchantmentTypes; import com.mrcrayfish.guns.entity.GrenadeEntity; import com.mrcrayfish.guns.entity.MissileEntity; import com.mrcrayfish.guns.init.*; import com.mrcrayfish.guns.network.PacketHandler; import net.minecraft.core.NonNullList; import net.minecraft.data.DataGenerator; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
19,875
package com.mrcrayfish.guns; @Mod(Reference.MOD_ID) public class GunMod { public static boolean debugging = false; public static boolean controllableLoaded = false; public static boolean backpackedLoaded = false; public static boolean playerReviveLoaded = false; public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); public static final CreativeModeTab GROUP = new CreativeModeTab(Reference.MOD_ID) { @Override public ItemStack makeIcon() { ItemStack stack = new ItemStack(ModItems.PISTOL.get()); stack.getOrCreateTag().putInt("AmmoCount", ModItems.PISTOL.get().getGun().getGeneral().getMaxAmmo()); return stack; } @Override public void fillItemList(NonNullList<ItemStack> items) { super.fillItemList(items); CustomGunManager.fill(items); } }.setEnchantmentCategories(EnchantmentTypes.GUN, EnchantmentTypes.SEMI_AUTO_GUN); public GunMod() { ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.clientSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.commonSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.serverSpec); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); ModBlocks.REGISTER.register(bus); ModContainers.REGISTER.register(bus); ModEffects.REGISTER.register(bus); ModEnchantments.REGISTER.register(bus); ModEntities.REGISTER.register(bus); ModItems.REGISTER.register(bus); ModParticleTypes.REGISTER.register(bus); ModRecipeSerializers.REGISTER.register(bus); ModRecipeTypes.REGISTER.register(bus); ModSounds.REGISTER.register(bus); ModTileEntities.REGISTER.register(bus); bus.addListener(this::onCommonSetup); bus.addListener(this::onClientSetup); bus.addListener(this::onGatherData); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { FrameworkClientAPI.registerDataLoader(MetaLoader.getInstance()); bus.addListener(KeyBinds::registerKeyMappings);
package com.mrcrayfish.guns; @Mod(Reference.MOD_ID) public class GunMod { public static boolean debugging = false; public static boolean controllableLoaded = false; public static boolean backpackedLoaded = false; public static boolean playerReviveLoaded = false; public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); public static final CreativeModeTab GROUP = new CreativeModeTab(Reference.MOD_ID) { @Override public ItemStack makeIcon() { ItemStack stack = new ItemStack(ModItems.PISTOL.get()); stack.getOrCreateTag().putInt("AmmoCount", ModItems.PISTOL.get().getGun().getGeneral().getMaxAmmo()); return stack; } @Override public void fillItemList(NonNullList<ItemStack> items) { super.fillItemList(items); CustomGunManager.fill(items); } }.setEnchantmentCategories(EnchantmentTypes.GUN, EnchantmentTypes.SEMI_AUTO_GUN); public GunMod() { ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.clientSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.commonSpec); ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.serverSpec); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); ModBlocks.REGISTER.register(bus); ModContainers.REGISTER.register(bus); ModEffects.REGISTER.register(bus); ModEnchantments.REGISTER.register(bus); ModEntities.REGISTER.register(bus); ModItems.REGISTER.register(bus); ModParticleTypes.REGISTER.register(bus); ModRecipeSerializers.REGISTER.register(bus); ModRecipeTypes.REGISTER.register(bus); ModSounds.REGISTER.register(bus); ModTileEntities.REGISTER.register(bus); bus.addListener(this::onCommonSetup); bus.addListener(this::onClientSetup); bus.addListener(this::onGatherData); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { FrameworkClientAPI.registerDataLoader(MetaLoader.getInstance()); bus.addListener(KeyBinds::registerKeyMappings);
bus.addListener(CrosshairHandler::onConfigReload);
5
2023-12-18 15:04:35+00:00
24k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/module/app/SystemFramework.java
[ { "identifier": "logLevelDesc", "path": "app/src/main/java/com/sevtinge/hyperceiler/utils/log/LogManager.java", "snippet": "public static String logLevelDesc() {\n return switch (logLevel) {\n case 0 -> (\"Disable\");\n case 1 -> (\"Error\");\n case 2 -> (\"Warn\");\n case...
import static com.sevtinge.hyperceiler.utils.api.VoyagerApisKt.isPad; import static com.sevtinge.hyperceiler.utils.devicesdk.SystemSDKKt.isMoreAndroidVersion; import static com.sevtinge.hyperceiler.utils.log.LogManager.logLevelDesc; import com.sevtinge.hyperceiler.module.base.BaseModule; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouch; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouchForU; import com.sevtinge.hyperceiler.module.hook.systemframework.AppLinkVerify; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanOpenMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanShareMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.ClipboardWhitelist; import com.sevtinge.hyperceiler.module.hook.systemframework.DeleteOnPostNotification; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableCleaner; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableFreeformBlackList; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableLowApiCheckForU; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableMiuiLite; import com.sevtinge.hyperceiler.module.hook.systemframework.DisablePinVerifyPer72h; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableVerifyCanBeDisabled; import com.sevtinge.hyperceiler.module.hook.systemframework.FlagSecure; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeFormCount; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeformBubble; import com.sevtinge.hyperceiler.module.hook.systemframework.HookEntry; import com.sevtinge.hyperceiler.module.hook.systemframework.MultiFreeFormSupported; import com.sevtinge.hyperceiler.module.hook.systemframework.PackagePermissions; import com.sevtinge.hyperceiler.module.hook.systemframework.QuickScreenshot; import com.sevtinge.hyperceiler.module.hook.systemframework.RemoveSmallWindowRestrictions; import com.sevtinge.hyperceiler.module.hook.systemframework.ScreenRotation; import com.sevtinge.hyperceiler.module.hook.systemframework.SpeedInstall; import com.sevtinge.hyperceiler.module.hook.systemframework.StickyFloatingWindows; import com.sevtinge.hyperceiler.module.hook.systemframework.ThermalBrightness; import com.sevtinge.hyperceiler.module.hook.systemframework.UseOriginalAnimation; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDefaultStream; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDisableSafe; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeFirstPress; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeMediaSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSeparateControl; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.corepatch.BypassSignCheckForT; import com.sevtinge.hyperceiler.module.hook.systemframework.display.AllDarkMode; import com.sevtinge.hyperceiler.module.hook.systemframework.display.DisplayCutout; import com.sevtinge.hyperceiler.module.hook.systemframework.display.ToastTime; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.OpenAppInFreeForm; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.UnForegroundPin; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.IgnoreStylusKeyGesture; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.NoMagicPointer; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RemoveStylusBluetoothRestriction; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RestoreEsc; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.SetGestureNeedFingerNum; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualNRSupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualSASupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N1Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N28Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N5N8Band; import com.sevtinge.hyperceiler.module.hook.various.NoAccessDeviceLogsRequest; import de.robv.android.xposed.XposedBridge;
19,630
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); initHook(new FlagSecure(), mPrefsMap.getBoolean("system_other_flag_secure")); initHook(new AppLinkVerify(), mPrefsMap.getBoolean("system_framework_disable_app_link_verify")); initHook(new UseOriginalAnimation(), mPrefsMap.getBoolean("system_framework_other_use_original_animation")); initHook(new SpeedInstall(), mPrefsMap.getBoolean("system_framework_other_speed_install")); initHook(DeleteOnPostNotification.INSTANCE, mPrefsMap.getBoolean("system_other_delete_on_post_notification")); initHook(NoAccessDeviceLogsRequest.INSTANCE, mPrefsMap.getBoolean("various_disable_access_device_logs")); initHook(new DisableMiuiLite(), mPrefsMap.getBoolean("system_framework_disablt_miuilite_check"));
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); initHook(new FlagSecure(), mPrefsMap.getBoolean("system_other_flag_secure")); initHook(new AppLinkVerify(), mPrefsMap.getBoolean("system_framework_disable_app_link_verify")); initHook(new UseOriginalAnimation(), mPrefsMap.getBoolean("system_framework_other_use_original_animation")); initHook(new SpeedInstall(), mPrefsMap.getBoolean("system_framework_other_speed_install")); initHook(DeleteOnPostNotification.INSTANCE, mPrefsMap.getBoolean("system_other_delete_on_post_notification")); initHook(NoAccessDeviceLogsRequest.INSTANCE, mPrefsMap.getBoolean("various_disable_access_device_logs")); initHook(new DisableMiuiLite(), mPrefsMap.getBoolean("system_framework_disablt_miuilite_check"));
initHook(new HookEntry(), mPrefsMap.getBoolean("system_framework_hook_entry"));
15
2023-10-27 17:17:42+00:00
24k
sgware/sabre
src/edu/uky/cs/nil/sabre/logic/Conditional.java
[ { "identifier": "Exceptions", "path": "src/edu/uky/cs/nil/sabre/Exceptions.java", "snippet": "public class Exceptions {\n\t\n\t/**\n\t * Thrown any time an index in a list, array, etc. is accessed which does\n\t * not exist.\n\t * \n\t * @param index the index\n\t * @return an IndexOutOfBoundsException\...
import java.util.ArrayList; import java.util.function.Function; import edu.uky.cs.nil.sabre.Exceptions; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.State; import edu.uky.cs.nil.sabre.Type; import edu.uky.cs.nil.sabre.Utilities; import edu.uky.cs.nil.sabre.util.ImmutableArray;
16,386
package edu.uky.cs.nil.sabre.logic; /** * A conditional is a {@link Expression logical expression} which can have one * of several possible {@link #branches values} depending on which of its * Boolean {@link #conditions conditions} evaluates to {@link True true}. A * conditional defines some number of condition/branch pairs. {@link * #conditions Conditions} must be of type {@code boolean}, but {@link * #branches branches} can be of any type. The first condition is paired with * the first branch, the second condition with the second branch, and so on. * A conditional evaluates its conditions in order; once a condition which * evaluates to {@link True true} is found, the corresponding branch is * evaluated and that value returned. There should always be exactly one more * branch than condition; the condition for the last branch is implicitly * {@link True true} in order to ensure that some condition will always hold. * A conditional can be thought of as an {@code if / else if ... / else} * statement in a programming language where the {@code else} branch is * mandatory. * <p> * A trivial conditional has zero conditions and one branch (whose condition * is implicitly {@link True true}). A trivial conditional is logically * equivalent to its only branch. * <p> * The return value of {@link Expression#toValued()} is a conditional whose * conditions are in {@link Expression#toPrecondition() disjunctive normal * form} and whose branches are {@link Expression#isValued() valued * expressions}. A conditional is not a valued expression, but removing * conditionals from inside an expression and converting it to potentially * many branches is an important step in converting an expression {@link * Expression#toValued() to a valued expression}. The {@link * Expression#toValued()} method of expressions which do not contain any * conditionals should return a trivial conditional. * <p> * When a conditional effect is converted to {@link #toPrecondition() * disjunctive normal form as a precondition} the ordering of the conditions * may no longer be enforced, so the conditions are serialized. This means the * first condition is unchanged, but the second condition includes a negation * of the first condition, and the third condition includes a negation of the * first and second conditions, etc. The same is true when converting to {@link * #toEffect() disjunctive normal form as an effect}, since the conditional * will becomes a series of {@link Effect conditional effects} whose order can * no longer be enforced; the conditions will be serialized to preserve the * effects of the original ordering of the conditions. * * @param <E> the type of expression of this conditional's condition; this type * must be compatible with {@link True true}, since the last condition of every * conditional is implicitly {@link True true} * @author Stephen G. Ware */ public class Conditional<E extends Expression> implements Expression { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * The conditions that will be checked in order (the first condition is * paired with the first branch, the second with the second branch, etc.) */ public final ImmutableArray<E> conditions; /** * The expressions which will be evaluated if their corresponding conditions * evaluate to true */ public final ImmutableArray<Expression> branches; /** * Constructs a new conditional with the given {@link ImmutableArray * immutable arrays} of conditions and branches. * * @param conditions the Boolean conditions, in the order they should be * evaluated * @param branches exactly one more branch than conditions, where the first * branch is paired with the first condition, the second branch with the * second condition, etc., and the last branch implicitly has a condition * of {@link True true} * @throws edu.uky.cs.nil.sabre.FormatException if any condition is not of * type {@code boolean} * @throws edu.uky.cs.nil.sabre.FormatException if the number of branches * is not exactly the number of conditions plus one */ public Conditional(ImmutableArray<E> conditions, ImmutableArray<Expression> branches) { if(conditions.size() != branches.size() - 1) throw Exceptions.conditionBranchCount(conditions.size(), branches.size()); for(int i=0; i<conditions.size(); i++) conditions.get(i).mustBeBoolean(); this.conditions = conditions; this.branches = branches; } /** * Constructs a new conditional with the given arrays of conditions and * branches. See {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param conditions the conditions * @param branches the branches */ public Conditional(E[] conditions, Expression[] branches) { this(new ImmutableArray<>(conditions), new ImmutableArray<>(branches)); } /** * Constructs a new conditional with the given {@link Iterable iterables} * of conditions and branches. See * {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param conditions the conditions * @param branches the branches */ public Conditional(Iterable<E> conditions, Iterable<Expression> branches) { this(new ImmutableArray<>(conditions), new ImmutableArray<>(branches)); } /** * Constructs a conditional with a single condition and two branches. See * {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param condition the single condition * @param positive the branch that will be evaluated if the condition is * {@link True true} * @param negative the branch that will be evaluated if the condition is * {@link False false} * @throws edu.uky.cs.nil.sabre.FormatException if the condition is not of * type {@code boolean} */ public Conditional(E condition, Expression positive, Expression negative) { this(new ImmutableArray<>(condition), new ImmutableArray<>(positive, negative)); } /** * Constructs a trivial conditional whose implicit condition is {@link True * true} and which will always evaluate to the value of its only branch. * * @param branch the branch that will always be evaluated */ public Conditional(Expression branch) { this(new ImmutableArray<>(), new ImmutableArray<>(branch)); } @Override public boolean equals(Object other) { if(getClass().equals(other.getClass())) { Conditional<?> otherConditional = (Conditional<?>) other; return conditions.equals(otherConditional.conditions) && branches.equals(otherConditional.branches); } return false; } @Override public int hashCode() {
package edu.uky.cs.nil.sabre.logic; /** * A conditional is a {@link Expression logical expression} which can have one * of several possible {@link #branches values} depending on which of its * Boolean {@link #conditions conditions} evaluates to {@link True true}. A * conditional defines some number of condition/branch pairs. {@link * #conditions Conditions} must be of type {@code boolean}, but {@link * #branches branches} can be of any type. The first condition is paired with * the first branch, the second condition with the second branch, and so on. * A conditional evaluates its conditions in order; once a condition which * evaluates to {@link True true} is found, the corresponding branch is * evaluated and that value returned. There should always be exactly one more * branch than condition; the condition for the last branch is implicitly * {@link True true} in order to ensure that some condition will always hold. * A conditional can be thought of as an {@code if / else if ... / else} * statement in a programming language where the {@code else} branch is * mandatory. * <p> * A trivial conditional has zero conditions and one branch (whose condition * is implicitly {@link True true}). A trivial conditional is logically * equivalent to its only branch. * <p> * The return value of {@link Expression#toValued()} is a conditional whose * conditions are in {@link Expression#toPrecondition() disjunctive normal * form} and whose branches are {@link Expression#isValued() valued * expressions}. A conditional is not a valued expression, but removing * conditionals from inside an expression and converting it to potentially * many branches is an important step in converting an expression {@link * Expression#toValued() to a valued expression}. The {@link * Expression#toValued()} method of expressions which do not contain any * conditionals should return a trivial conditional. * <p> * When a conditional effect is converted to {@link #toPrecondition() * disjunctive normal form as a precondition} the ordering of the conditions * may no longer be enforced, so the conditions are serialized. This means the * first condition is unchanged, but the second condition includes a negation * of the first condition, and the third condition includes a negation of the * first and second conditions, etc. The same is true when converting to {@link * #toEffect() disjunctive normal form as an effect}, since the conditional * will becomes a series of {@link Effect conditional effects} whose order can * no longer be enforced; the conditions will be serialized to preserve the * effects of the original ordering of the conditions. * * @param <E> the type of expression of this conditional's condition; this type * must be compatible with {@link True true}, since the last condition of every * conditional is implicitly {@link True true} * @author Stephen G. Ware */ public class Conditional<E extends Expression> implements Expression { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * The conditions that will be checked in order (the first condition is * paired with the first branch, the second with the second branch, etc.) */ public final ImmutableArray<E> conditions; /** * The expressions which will be evaluated if their corresponding conditions * evaluate to true */ public final ImmutableArray<Expression> branches; /** * Constructs a new conditional with the given {@link ImmutableArray * immutable arrays} of conditions and branches. * * @param conditions the Boolean conditions, in the order they should be * evaluated * @param branches exactly one more branch than conditions, where the first * branch is paired with the first condition, the second branch with the * second condition, etc., and the last branch implicitly has a condition * of {@link True true} * @throws edu.uky.cs.nil.sabre.FormatException if any condition is not of * type {@code boolean} * @throws edu.uky.cs.nil.sabre.FormatException if the number of branches * is not exactly the number of conditions plus one */ public Conditional(ImmutableArray<E> conditions, ImmutableArray<Expression> branches) { if(conditions.size() != branches.size() - 1) throw Exceptions.conditionBranchCount(conditions.size(), branches.size()); for(int i=0; i<conditions.size(); i++) conditions.get(i).mustBeBoolean(); this.conditions = conditions; this.branches = branches; } /** * Constructs a new conditional with the given arrays of conditions and * branches. See {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param conditions the conditions * @param branches the branches */ public Conditional(E[] conditions, Expression[] branches) { this(new ImmutableArray<>(conditions), new ImmutableArray<>(branches)); } /** * Constructs a new conditional with the given {@link Iterable iterables} * of conditions and branches. See * {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param conditions the conditions * @param branches the branches */ public Conditional(Iterable<E> conditions, Iterable<Expression> branches) { this(new ImmutableArray<>(conditions), new ImmutableArray<>(branches)); } /** * Constructs a conditional with a single condition and two branches. See * {@link #Conditional(ImmutableArray, ImmutableArray)}. * * @param condition the single condition * @param positive the branch that will be evaluated if the condition is * {@link True true} * @param negative the branch that will be evaluated if the condition is * {@link False false} * @throws edu.uky.cs.nil.sabre.FormatException if the condition is not of * type {@code boolean} */ public Conditional(E condition, Expression positive, Expression negative) { this(new ImmutableArray<>(condition), new ImmutableArray<>(positive, negative)); } /** * Constructs a trivial conditional whose implicit condition is {@link True * true} and which will always evaluate to the value of its only branch. * * @param branch the branch that will always be evaluated */ public Conditional(Expression branch) { this(new ImmutableArray<>(), new ImmutableArray<>(branch)); } @Override public boolean equals(Object other) { if(getClass().equals(other.getClass())) { Conditional<?> otherConditional = (Conditional<?>) other; return conditions.equals(otherConditional.conditions) && branches.equals(otherConditional.branches); } return false; } @Override public int hashCode() {
return Utilities.hashCode(getClass(), conditions.hashCode(), branches.hashCode());
4
2023-10-26 18:14:19+00:00
24k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/world/World.java
[ { "identifier": "Keyed", "path": "core/src/main/java/net/pl3x/map/core/Keyed.java", "snippet": "public abstract class Keyed {\n private final String key;\n\n /**\n * Create a new key identified object.\n *\n * @param key key for object\n */\n public Keyed(@NotNull String key) {\...
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import javax.imageio.ImageIO; import net.pl3x.map.core.Keyed; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.configuration.PlayersLayerConfig; import net.pl3x.map.core.configuration.SpawnLayerConfig; import net.pl3x.map.core.configuration.WorldBorderLayerConfig; import net.pl3x.map.core.configuration.WorldConfig; import net.pl3x.map.core.image.IconImage; import net.pl3x.map.core.log.Logger; import net.pl3x.map.core.markers.Point; import net.pl3x.map.core.markers.area.Area; import net.pl3x.map.core.markers.layer.CustomLayer; import net.pl3x.map.core.markers.layer.Layer; import net.pl3x.map.core.markers.layer.PlayersLayer; import net.pl3x.map.core.markers.layer.SpawnLayer; import net.pl3x.map.core.markers.layer.WorldBorderLayer; import net.pl3x.map.core.player.Player; import net.pl3x.map.core.registry.BiomeRegistry; import net.pl3x.map.core.registry.Registry; import net.pl3x.map.core.renderer.Renderer; import net.pl3x.map.core.renderer.task.UpdateMarkerData; import net.pl3x.map.core.util.FileUtil; import net.pl3x.map.core.util.Mathf; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
21,461
/* * 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.world; public abstract class World extends Keyed { public static final PathMatcher JSON_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*.json"); public static final PathMatcher MCA_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/r.*.*.mca"); public static final PathMatcher PNG_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*_*.png"); private final Path customMarkersDirectory; private final Path markersDirectory; private final Path regionDirectory; private final Path tilesDirectory; private final WorldConfig worldConfig; private final long seed; private final Point spawn; private final Type type; private final BiomeManager biomeManager; private final BiomeRegistry biomeRegistry; private final Registry<@NotNull Layer> layerRegistry; private final LoadingCache<@NotNull Long, @NotNull Region> regionCache; private final RegionModifiedState regionModifiedState; //private final RegionFileWatcher regionFileWatcher; private final UpdateMarkerData markerTask; private final Map<@NotNull String, Renderer.@NotNull Builder> renderers = new LinkedHashMap<>(); public World(@NotNull String name, long seed, @NotNull Point spawn, @NotNull Type type, @NotNull Path regionDirectory) { super(name); this.seed = seed; this.spawn = spawn; this.type = type; String safeNameForDirectories = name.replace(":", "-"); this.regionDirectory = regionDirectory; this.tilesDirectory = FileUtil.getTilesDir().resolve(safeNameForDirectories); this.customMarkersDirectory = Pl3xMap.api().getMainDir().resolve("markers").resolve(safeNameForDirectories); this.markersDirectory = getTilesDirectory().resolve("markers"); FileUtil.createDirs(this.regionDirectory); FileUtil.createDirs(this.tilesDirectory); FileUtil.createDirs(this.customMarkersDirectory); FileUtil.createDirs(this.markersDirectory); this.worldConfig = new WorldConfig(this); this.biomeManager = new BiomeManager(hashSeed(getSeed())); this.biomeRegistry = new BiomeRegistry(); this.layerRegistry = new Registry<>(); this.regionCache = Caffeine.newBuilder() .expireAfterWrite(1, TimeUnit.MINUTES) .maximumSize(100) .build(this::loadRegion); this.regionModifiedState = new RegionModifiedState(this); //this.regionFileWatcher = new RegionFileWatcher(this); this.markerTask = new UpdateMarkerData(this); } protected void init() { if (!isEnabled()) { return; } getBiomeRegistry().init(this); //this.regionFileWatcher.start(); getConfig().RENDER_RENDERERS.forEach((id, icon) -> { Renderer.Builder renderer = Pl3xMap.api().getRendererRegistry().get(id); if (renderer == null) { return; } Path path = FileUtil.getWebDir().resolve("images/icon/" + icon + ".png"); try { IconImage image = new IconImage(icon, ImageIO.read(path.toFile()), "png"); Pl3xMap.api().getIconRegistry().register(image); } catch (IOException e) { Logger.severe("Cannot load world renderer icon " + path, e); } this.renderers.put(renderer.getKey(), renderer); }); if (WorldBorderLayerConfig.ENABLED) { Logger.debug("Registering world border layer"); getLayerRegistry().register(WorldBorderLayer.KEY, new WorldBorderLayer(this)); } if (SpawnLayerConfig.ENABLED) { Logger.debug("Registering spawn layer"); getLayerRegistry().register(SpawnLayer.KEY, new SpawnLayer(this)); } if (PlayersLayerConfig.ENABLED) { Logger.debug("Registering player tracker layer"); getLayerRegistry().register(PlayersLayer.KEY, new PlayersLayer(this)); } Logger.debug("Checking all region files"); Pl3xMap.api().getRegionProcessor().addRegions(this, listRegions(false)); Logger.debug("Starting marker task"); Pl3xMap.api().getScheduler().addTask(1, true, this.markerTask); // load up custom markers Logger.debug("Loading custom markers for " + getName()); for (Path file : getCustomMarkerFiles()) {
/* * 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.world; public abstract class World extends Keyed { public static final PathMatcher JSON_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*.json"); public static final PathMatcher MCA_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/r.*.*.mca"); public static final PathMatcher PNG_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*_*.png"); private final Path customMarkersDirectory; private final Path markersDirectory; private final Path regionDirectory; private final Path tilesDirectory; private final WorldConfig worldConfig; private final long seed; private final Point spawn; private final Type type; private final BiomeManager biomeManager; private final BiomeRegistry biomeRegistry; private final Registry<@NotNull Layer> layerRegistry; private final LoadingCache<@NotNull Long, @NotNull Region> regionCache; private final RegionModifiedState regionModifiedState; //private final RegionFileWatcher regionFileWatcher; private final UpdateMarkerData markerTask; private final Map<@NotNull String, Renderer.@NotNull Builder> renderers = new LinkedHashMap<>(); public World(@NotNull String name, long seed, @NotNull Point spawn, @NotNull Type type, @NotNull Path regionDirectory) { super(name); this.seed = seed; this.spawn = spawn; this.type = type; String safeNameForDirectories = name.replace(":", "-"); this.regionDirectory = regionDirectory; this.tilesDirectory = FileUtil.getTilesDir().resolve(safeNameForDirectories); this.customMarkersDirectory = Pl3xMap.api().getMainDir().resolve("markers").resolve(safeNameForDirectories); this.markersDirectory = getTilesDirectory().resolve("markers"); FileUtil.createDirs(this.regionDirectory); FileUtil.createDirs(this.tilesDirectory); FileUtil.createDirs(this.customMarkersDirectory); FileUtil.createDirs(this.markersDirectory); this.worldConfig = new WorldConfig(this); this.biomeManager = new BiomeManager(hashSeed(getSeed())); this.biomeRegistry = new BiomeRegistry(); this.layerRegistry = new Registry<>(); this.regionCache = Caffeine.newBuilder() .expireAfterWrite(1, TimeUnit.MINUTES) .maximumSize(100) .build(this::loadRegion); this.regionModifiedState = new RegionModifiedState(this); //this.regionFileWatcher = new RegionFileWatcher(this); this.markerTask = new UpdateMarkerData(this); } protected void init() { if (!isEnabled()) { return; } getBiomeRegistry().init(this); //this.regionFileWatcher.start(); getConfig().RENDER_RENDERERS.forEach((id, icon) -> { Renderer.Builder renderer = Pl3xMap.api().getRendererRegistry().get(id); if (renderer == null) { return; } Path path = FileUtil.getWebDir().resolve("images/icon/" + icon + ".png"); try { IconImage image = new IconImage(icon, ImageIO.read(path.toFile()), "png"); Pl3xMap.api().getIconRegistry().register(image); } catch (IOException e) { Logger.severe("Cannot load world renderer icon " + path, e); } this.renderers.put(renderer.getKey(), renderer); }); if (WorldBorderLayerConfig.ENABLED) { Logger.debug("Registering world border layer"); getLayerRegistry().register(WorldBorderLayer.KEY, new WorldBorderLayer(this)); } if (SpawnLayerConfig.ENABLED) { Logger.debug("Registering spawn layer"); getLayerRegistry().register(SpawnLayer.KEY, new SpawnLayer(this)); } if (PlayersLayerConfig.ENABLED) { Logger.debug("Registering player tracker layer"); getLayerRegistry().register(PlayersLayer.KEY, new PlayersLayer(this)); } Logger.debug("Checking all region files"); Pl3xMap.api().getRegionProcessor().addRegions(this, listRegions(false)); Logger.debug("Starting marker task"); Pl3xMap.api().getScheduler().addTask(1, true, this.markerTask); // load up custom markers Logger.debug("Loading custom markers for " + getName()); for (Path file : getCustomMarkerFiles()) {
CustomLayer.load(this, file);
9
2023-10-26 01:14:31+00:00
24k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/MediaArchivalApplicationTests.java
[ { "identifier": "MediaObjectTransferListenerTest", "path": "backend/src/test/java/com/example/mediaarchival/consumers/MediaObjectTransferListenerTest.java", "snippet": "public class MediaObjectTransferListenerTest {\n\n @Mock private MediaRepository mediaRepository;\n\n @Mock private MediaController m...
import com.example.mediaarchival.consumers.MediaObjectTransferListenerTest; import com.example.mediaarchival.controllers.LibraryControllerTest; import com.example.mediaarchival.controllers.MediaControllerTest; import com.example.mediaarchival.controllers.UserControllerTest; import com.example.mediaarchival.converters.StringToArchivedStatusConverterTest; import com.example.mediaarchival.converters.StringToMediaTypeConverterTest; import com.example.mediaarchival.deserializers.ArchivedStatusDeserializerTest; import com.example.mediaarchival.deserializers.MediaCategoryDeserializerTest; import com.example.mediaarchival.filters.JwtValidationFilterTest; import com.example.mediaarchival.tasks.S3CleanupTaskTest; import com.example.mediaarchival.tasks.StartupResetTasksTest; import com.example.mediaarchival.utils.TarUtilsTest; import com.example.mediaarchival.utils.TokenUtilsTest; import com.example.mediaarchival.tasks.RestoreCheckerTest; import com.example.mediaarchival.utils.DirectoryUtilsTest; import com.example.mediaarchival.consumers.LibraryUpdateConsumerTest; import com.example.mediaarchival.consumers.RestoreConsumerTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance;
17,124
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TokenUtilsTests extends TokenUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TarUtilsTests extends TarUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaObjectTransferListenerTests extends MediaObjectTransferListenerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_METHOD) class S3CleanupTaskTests extends S3CleanupTaskTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_METHOD) class RestoreCheckerTests extends RestoreCheckerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StartupResetTasksTests extends StartupResetTasksTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TokenUtilsTests extends TokenUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TarUtilsTests extends TarUtilsTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaObjectTransferListenerTests extends MediaObjectTransferListenerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_METHOD) class S3CleanupTaskTests extends S3CleanupTaskTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_METHOD) class RestoreCheckerTests extends RestoreCheckerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StartupResetTasksTests extends StartupResetTasksTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DirectoryUtilsTests extends DirectoryUtilsTest {}
14
2023-10-27 01:54:57+00:00
24k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/controller/merchant/MerchantGoodsController.java
[ { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.annoation.MerchantPermission; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.constant.Quantity; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.OSSUtils; import com.siam.package_goods.entity.Goods; import com.siam.package_goods.entity.MenuGoodsRelation; import com.siam.package_goods.model.dto.GoodsMenuDto; import com.siam.package_goods.model.example.MenuGoodsRelationExample; import com.siam.package_goods.service.*; import com.siam.package_merchant.auth.cache.MerchantSessionManager; import com.siam.package_merchant.entity.Merchant; import com.siam.package_promotion.feign.CouponsFeignApi; import com.siam.package_promotion.feign.CouponsGoodsRelationFeignApi; import com.siam.package_user.util.TokenUtil; import com.siam.package_util.entity.PictureUploadRecord; import com.siam.package_util.feign.PictureUploadRecordFeignApi; import com.siam.package_util.model.example.PictureUploadRecordExample; import com.siam.package_util.model.param.PictureUploadRecordParam; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; 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; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.Map;
17,394
package com.siam.package_goods.controller.merchant; @RestController @RequestMapping(value = "/rest/merchant/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "商家端商品模块相关接口", description = "MerchantGoodsController") public class MerchantGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; // @Autowired // private MerchantService merchantService; @Autowired private PictureUploadRecordFeignApi pictureUploadRecordFeignApi; @Autowired private MerchantSessionManager merchantSessionManager; @ApiOperation(value = "商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "商品表主键id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "name", value = "商品名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuName", value = "菜单名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "pageNo", value = "页码(值为-1不分页)", required = true, paramType = "query", dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "页数", required = true, paramType = "query", dataType = "int", defaultValue = "20"), }) @PostMapping(value = "/list")
package com.siam.package_goods.controller.merchant; @RestController @RequestMapping(value = "/rest/merchant/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "商家端商品模块相关接口", description = "MerchantGoodsController") public class MerchantGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; // @Autowired // private MerchantService merchantService; @Autowired private PictureUploadRecordFeignApi pictureUploadRecordFeignApi; @Autowired private MerchantSessionManager merchantSessionManager; @ApiOperation(value = "商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "商品表主键id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "name", value = "商品名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuName", value = "菜单名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "pageNo", value = "页码(值为-1不分页)", required = true, paramType = "query", dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "页数", required = true, paramType = "query", dataType = "int", defaultValue = "20"), }) @PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) GoodsMenuDto goodsMenuDto, HttpServletRequest request){
3
2023-10-26 10:45:10+00:00
24k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/CandidateWordView.java
[ { "identifier": "BackgroundDrawableFactory", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public class BackgroundDrawableFactory {\n /** Drawable to create. */\n public enum DrawableType {\n // Key background for twelvekeys layout.\n TWE...
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.widget.EdgeEffect; import androidx.core.view.ViewCompat; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateList; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import sh.eliza.japaneseinput.accessibility.CandidateWindowAccessibilityDelegate; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.ui.CandidateLayout; import sh.eliza.japaneseinput.ui.CandidateLayout.Row; import sh.eliza.japaneseinput.ui.CandidateLayout.Span; import sh.eliza.japaneseinput.ui.CandidateLayoutRenderer; import sh.eliza.japaneseinput.ui.CandidateLayouter; import sh.eliza.japaneseinput.ui.SnapScroller; import sh.eliza.japaneseinput.view.Skin;
14,989
} return true; case MotionEvent.ACTION_CANCEL: if (pressedCandidate != null) { reset(); invalidate(); } return true; case MotionEvent.ACTION_UP: if (pressedCandidate != null) { if (candidateRect.contains(scrolledX, scrolledY) && candidateSelectListener != null) { candidateSelectListener.onCandidateSelected( CandidateWordView.this, pressedCandidate, pressedRowIndex); } reset(); invalidate(); } return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?).
// 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; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); } private void pressCandidate(int rowIndex, Span span) { Row row = calculatedLayout.getRowList().get(rowIndex); pressedRowIndex = Optional.of(rowIndex); pressedCandidate = span.getCandidateWord().orNull(); // TODO(yamaguchi):maybe better to make this rect larger by several pixels to avoid that // users fail to select a candidate by unconscious small movement of tap point. // (i.e. give hysterisis for noise reduction) // Needs UX study. candidateRect.set( span.getLeft(), row.getTop(), span.getRight(), row.getTop() + row.getHeight()); } void reset() { pressedCandidate = null; pressedRowIndex = Optional.absent(); // NOTE: candidateRect doesn't need reset. } CandidateWord getPressedCandidate() { return pressedCandidate; } /** * Checks if a down event is fired inside a candidate rectangle. If so, begin pressing it. * * <p>It is assumed that rows are stored in up-to-down order, and spans are in left-to-right * order. * * @param scrolledX X coordinate of down event point including scroll offset * @param scrolledY Y coordinate of down event point including scroll offset * @return true if the down event is fired inside a candidate rectangle. */ private boolean findCandidateAndPress(float scrolledX, float scrolledY) { if (calculatedLayout == null) { return false; } for (int rowIndex = 0; rowIndex < calculatedLayout.getRowList().size(); ++rowIndex) { Row row = calculatedLayout.getRowList().get(rowIndex); if (scrolledY < row.getTop()) { break; } if (scrolledY >= row.getTop() + row.getHeight()) { continue; } for (Span span : row.getSpanList()) { if (scrolledX < span.getLeft()) { break; } if (scrolledX >= span.getRight()) { continue; } pressCandidate(rowIndex, span); invalidate(); return true; } return false; } return false; } boolean onTouchEvent(MotionEvent event) { // Before delegation to gesture detector, handle ACTION_UP event // in order to release edge effect. if (event.getAction() == MotionEvent.ACTION_UP) { topEdgeEffect.onRelease(); bottomEdgeEffect.onRelease(); invalidate(); } if (gestureDetector.onTouchEvent(event)) { return true; } float scrolledX = event.getX() + getScrollX(); float scrolledY = event.getY() + getScrollY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: findCandidateAndPress(scrolledX, scrolledY); scroller.stopScrolling(); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); invalidate(); } if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); invalidate(); } return true; case MotionEvent.ACTION_MOVE: if (pressedCandidate != null) { // Turn off highlighting if contact point gets out of the candidate. if (!candidateRect.contains(scrolledX, scrolledY)) { reset(); invalidate(); } } return true; case MotionEvent.ACTION_CANCEL: if (pressedCandidate != null) { reset(); invalidate(); } return true; case MotionEvent.ACTION_UP: if (pressedCandidate != null) { if (candidateRect.contains(scrolledX, scrolledY) && candidateSelectListener != null) { candidateSelectListener.onCandidateSelected( CandidateWordView.this, pressedCandidate, pressedRowIndex); } reset(); invalidate(); } return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?).
protected final SnapScroller scroller = new SnapScroller();
6
2023-10-25 07:33:25+00:00
24k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs5/F5NClass.java
[ { "identifier": "NewClass", "path": "src/main/java/yaa/ast/NewClass.java", "snippet": "public class NewClass extends Stmt {\r\n public List<TypeParam> typeParams = new ArrayList<>(1);\r\n public List<RunBlock> runBlocks = new ArrayList<>(1);\r\n public Map<String, List<NewFun>> parentMtds = Map.of();...
import yaa.ast.NewClass; import yaa.pojos.YaaClz; import yaa.pojos.YaaError; import yaa.semantic.handlers.MetaCallOp; import yaa.semantic.handlers.OpUtils; import java.lang.annotation.ElementType; import java.util.ArrayList; import static yaa.pojos.GlobalData.*; import static yaa.pojos.TypeCategory.*;
16,923
package yaa.semantic.passes.fs5; public class F5NClass { public static void newType(NewClass newClass) { fs5.pushTable(newClass); var currentClz = (YaaClz) fs5.getSymbol(newClass.placeOfUse()); topClz.push(currentClz); if (newClass.metaCalls != null && newClass.metaCalls.size() > 0) {
package yaa.semantic.passes.fs5; public class F5NClass { public static void newType(NewClass newClass) { fs5.pushTable(newClass); var currentClz = (YaaClz) fs5.getSymbol(newClass.placeOfUse()); topClz.push(currentClz); if (newClass.metaCalls != null && newClass.metaCalls.size() > 0) {
currentClz.metas = MetaCallOp.metaCalls(newClass.metaCalls, ElementType.TYPE);
3
2023-10-26 17:41:13+00:00
24k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/pojo/MethodCallExpression.java
[ { "identifier": "ParameterNameFactory", "path": "src/main/java/com/insidious/plugin/client/ParameterNameFactory.java", "snippet": "public class ParameterNameFactory {\n\n private final Map<String, String> nameByIdMap = new HashMap<>();\n private final Map<String, Parameter> nameToParameterMap = ne...
import com.insidious.common.weaver.DataInfo; import com.insidious.common.weaver.EventType; import com.insidious.plugin.client.ParameterNameFactory; import com.insidious.plugin.client.pojo.DataEventWithSessionId; import com.insidious.plugin.factory.testcase.TestGenerationState; import com.insidious.plugin.factory.testcase.expression.Expression; import com.insidious.plugin.factory.testcase.parameter.VariableContainer; import com.insidious.plugin.util.ClassTypeUtils; import com.insidious.plugin.factory.testcase.writer.ObjectRoutineScript; import com.insidious.plugin.factory.testcase.writer.PendingStatement; import com.insidious.plugin.ui.TestCaseGenerationConfiguration; import com.insidious.plugin.util.LoggerUtil; import com.intellij.openapi.diagnostic.Logger; import org.objectweb.asm.Opcodes; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
17,869
public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public boolean getUsesFields() { return usesFields; } public void setUsesFields(boolean b) { this.usesFields = b; } public int getCallStack() { return callStack; } public void setCallStack(int callStack) { this.callStack = callStack; } public DataInfo getEntryProbeInfo() { return entryProbeInfo; } public void setEntryProbeInfo(DataInfo entryProbeInfo) { this.entryProbeInfo = entryProbeInfo; } public Parameter getSubject() { return subject; } public void setSubject(Parameter testSubject) { this.subject = testSubject; } public List<Parameter> getArguments() { return arguments; } public void setArguments(List<Parameter> arguments) { this.arguments = arguments; } public Parameter getReturnValue() { return returnValue; } public void setReturnValue(Parameter returnValue) { this.returnValue = returnValue; } public String getMethodName() { return methodName; } /* if the name is already used in the script and, if the parameter type and template map are not equal then Generates a New Name, */ public Parameter generateParameterName(Parameter parameter, ObjectRoutineScript ors) { ParameterNameFactory nameFactory = ors.getTestGenerationState().getParameterNameFactory(); String lhsExprName = nameFactory.getNameForUse(parameter, this.methodName); Parameter variableExistingParameter = ors.getCreatedVariables() .getParameterByNameAndType(lhsExprName, parameter); Parameter sameNameParamExisting = ors.getCreatedVariables() .getParameterByName(lhsExprName); // If the type and the template map does not match // then We should have a new name for the variable, // and it should be redeclared => // eg "String var" instead of "var" if (sameNameParamExisting != null && variableExistingParameter == null) { // generate a next name from existing name //eg: name => name0 => name1 String oldName = nameFactory.getNameForUse(sameNameParamExisting, null); String newName = generateNextName(ors, oldName); parameter.getNamesList().remove(newName); parameter.getNamesList().remove(oldName); parameter.setName(newName); } return parameter; } // eg: name => name0 => name1 ... so on private String generateNextName(ObjectRoutineScript ors, String name) { for (int i = 0; i < 100; i++) { if (!ors.getCreatedVariables() .contains(name + i)) { return name + i; } } return "thisNeverHappened"; } public Parameter getException() { if (returnValue != null && returnValue.isException()) { return returnValue; } return null; } @Override public void writeTo( ObjectRoutineScript objectRoutineScript, TestCaseGenerationConfiguration testConfiguration,
package com.insidious.plugin.pojo; public class MethodCallExpression implements Expression, Serializable { private static final Logger logger = LoggerUtil.getInstance(MethodCallExpression.class); private int callStack; private List<Parameter> arguments; private String methodName; private boolean isStaticCall; private Parameter subject; private DataInfo entryProbeInfo; private Parameter returnValue; private DataEventWithSessionId entryProbe; private int methodAccess; private long id; private int threadId; private long parentId = -1; private List<DataEventWithSessionId> argumentProbes = new ArrayList<>(); private DataEventWithSessionId returnDataEvent; private boolean usesFields; private int methodDefinitionId; public MethodCallExpression() { } @Override public boolean equals(Object obj) { if (!(obj instanceof MethodCallExpression)) { return false; } MethodCallExpression mceObject = (MethodCallExpression) obj; return mceObject.id == this.id; } public MethodCallExpression( String methodName, Parameter subject, List<Parameter> arguments, Parameter returnValue, int callStack) { this.methodName = methodName; this.subject = subject; this.arguments = arguments; this.returnValue = returnValue; this.callStack = callStack; } public MethodCallExpression(MethodCallExpression original) { methodName = original.methodName; subject = new Parameter(original.subject); arguments = original.arguments.stream().map(Parameter::new).collect(Collectors.toList()); methodAccess = original.methodAccess; returnValue = new Parameter(original.returnValue); callStack = original.callStack; threadId = original.threadId; parentId = original.parentId; id = original.id; isStaticCall = original.isStaticCall; entryProbeInfo = original.entryProbeInfo; entryProbe = original.entryProbe; returnDataEvent = original.returnDataEvent; methodDefinitionId = original.methodDefinitionId; usesFields = original.usesFields; argumentProbes = original.argumentProbes; } public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public boolean getUsesFields() { return usesFields; } public void setUsesFields(boolean b) { this.usesFields = b; } public int getCallStack() { return callStack; } public void setCallStack(int callStack) { this.callStack = callStack; } public DataInfo getEntryProbeInfo() { return entryProbeInfo; } public void setEntryProbeInfo(DataInfo entryProbeInfo) { this.entryProbeInfo = entryProbeInfo; } public Parameter getSubject() { return subject; } public void setSubject(Parameter testSubject) { this.subject = testSubject; } public List<Parameter> getArguments() { return arguments; } public void setArguments(List<Parameter> arguments) { this.arguments = arguments; } public Parameter getReturnValue() { return returnValue; } public void setReturnValue(Parameter returnValue) { this.returnValue = returnValue; } public String getMethodName() { return methodName; } /* if the name is already used in the script and, if the parameter type and template map are not equal then Generates a New Name, */ public Parameter generateParameterName(Parameter parameter, ObjectRoutineScript ors) { ParameterNameFactory nameFactory = ors.getTestGenerationState().getParameterNameFactory(); String lhsExprName = nameFactory.getNameForUse(parameter, this.methodName); Parameter variableExistingParameter = ors.getCreatedVariables() .getParameterByNameAndType(lhsExprName, parameter); Parameter sameNameParamExisting = ors.getCreatedVariables() .getParameterByName(lhsExprName); // If the type and the template map does not match // then We should have a new name for the variable, // and it should be redeclared => // eg "String var" instead of "var" if (sameNameParamExisting != null && variableExistingParameter == null) { // generate a next name from existing name //eg: name => name0 => name1 String oldName = nameFactory.getNameForUse(sameNameParamExisting, null); String newName = generateNextName(ors, oldName); parameter.getNamesList().remove(newName); parameter.getNamesList().remove(oldName); parameter.setName(newName); } return parameter; } // eg: name => name0 => name1 ... so on private String generateNextName(ObjectRoutineScript ors, String name) { for (int i = 0; i < 100; i++) { if (!ors.getCreatedVariables() .contains(name + i)) { return name + i; } } return "thisNeverHappened"; } public Parameter getException() { if (returnValue != null && returnValue.isException()) { return returnValue; } return null; } @Override public void writeTo( ObjectRoutineScript objectRoutineScript, TestCaseGenerationConfiguration testConfiguration,
TestGenerationState testGenerationState) {
2
2023-10-31 09:07:46+00:00
24k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/event/EventHandlerItem.java
[ { "identifier": "DangerRPG", "path": "src/main/java/mixac1/dangerrpg/DangerRPG.java", "snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"...
import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mixac1.dangerrpg.DangerRPG; import mixac1.dangerrpg.api.event.ItemStackEvent.DealtDamageEvent; import mixac1.dangerrpg.api.event.ItemStackEvent.HitEntityEvent; import mixac1.dangerrpg.api.event.ItemStackEvent.StackChangedEvent; import mixac1.dangerrpg.api.event.ItemStackEvent.UpMaxLevelEvent; import mixac1.dangerrpg.api.item.GemType; import mixac1.dangerrpg.capability.GemTypes; import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.PlayerAttributes; import mixac1.dangerrpg.capability.RPGItemHelper; import mixac1.dangerrpg.init.RPGCapability; import mixac1.dangerrpg.init.RPGOther.RPGUUIDs; import mixac1.dangerrpg.util.RPGHelper; import mixac1.dangerrpg.util.Tuple.Stub; import mixac1.dangerrpg.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MovingObjectPosition; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set;
15,649
if (!list.isEmpty()) { map.put(gemType, list); } } if (!map.isEmpty()) { e.toolTip.add(""); for (Entry<GemType, List<ItemStack>> entry : map.entrySet()) { e.toolTip.add( Utils.toString( entry.getKey() .getDispayName(), ":")); for (ItemStack it : entry.getValue()) { e.toolTip.add( Utils.toString(" - ", it.getDisplayName(), " (", (int) ItemAttributes.LEVEL.get(it), ")")); } } } } } @SideOnly(Side.CLIENT) @SubscribeEvent public void onPlayerTickClient(TickEvent.PlayerTickEvent e) { Minecraft m; if (e.phase == TickEvent.Phase.END) { if (e.player.swingProgressInt == 1) { ItemStack stack = e.player.getCurrentEquippedItem(); if (stack != null && ItemAttributes.REACH.hasIt(stack)) { MovingObjectPosition object = RPGHelper.getMouseOver(0, ItemAttributes.REACH.get(stack) + 4); if (object != null && object.entityHit != null && object.entityHit != e.player && object.entityHit.hurtResistantTime == 0) { FMLClientHandler.instance() .getClient().playerController.attackEntity(e.player, object.entityHit); } } } } } @SubscribeEvent public void onBreakSpeed(BreakSpeed e) { if (ForgeHooks.canToolHarvestBlock(e.block, e.metadata, e.entityPlayer.inventory.getCurrentItem())) { e.newSpeed += PlayerAttributes.EFFICIENCY.getValue(e.entityPlayer); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onDealtDamagePre(DealtDamageEvent e) { if (!e.player.worldObj.isRemote && e.stack != null && RPGItemHelper.isRPGable(e.stack)) { Stub<Float> damage = Stub.create(e.damage); GemTypes.AM.activate2All(e.stack, e.player, e.target, damage); e.damage = damage.value1; } } @SubscribeEvent public void onEntityDeath(LivingDeathEvent event) { if (event.source.getEntity() instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.source.getEntity(); ItemStack heldItem = player.getHeldItem(); if (RPGItemHelper.isRPGable(heldItem)) { EntityLivingBase entity = event.entityLiving; int maxHealth = (int) entity.getMaxHealth(); float xp = maxHealth / 8f; RPGItemHelper.upEquipment(player, heldItem, xp, false); } } } @SubscribeEvent public void onBreak(BreakEvent e) { RPGItemHelper.upEquipment( e.getPlayer(), e.getPlayer() .getCurrentEquippedItem(), e.block.getBlockHardness(e.world, e.x, e.y, e.z), true); } @SubscribeEvent public void onStackChangedEvent(StackChangedEvent e) { if (e.oldStack != null) { GemTypes.PA.activate2All(e.oldStack, e.player); } if (e.stack != null) { GemTypes.PA.activate1All(e.stack, e.player); } } @SubscribeEvent public void onlivingUpdate(LivingEvent.LivingUpdateEvent e) { if (e.entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) e.entityLiving; IAttributeInstance attr = player.getEntityAttribute(SharedMonsterAttributes.attackDamage); AttributeModifier mod = attr.getModifier(RPGUUIDs.ADD_STR_DAMAGE); if (mod != null) { attr.removeModifier(mod); } ItemStack heldItem = player.getHeldItem(); if (heldItem != null && RPGItemHelper.isRPGable(heldItem) && ItemAttributes.STR_MUL.hasIt(heldItem)) { double newModifierValue = PlayerAttributes.STRENGTH.getValue(player) * ItemAttributes.STR_MUL.get(heldItem) * 2; AttributeModifier newMod = new AttributeModifier( RPGUUIDs.ADD_STR_DAMAGE, "Strength damage", newModifierValue, 0).setSaved(true); attr.applyModifier(newMod); } } } @SubscribeEvent
package mixac1.dangerrpg.event; public class EventHandlerItem { @SubscribeEvent(priority = EventPriority.HIGHEST) public void onHitEntityPre(HitEntityEvent e) { if (e.attacker instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) e.attacker; if (RPGItemHelper.isRPGable(e.stack)) { if (!e.isRangeed) { float speed = ItemAttributes.MELEE_SPEED.getSafe(e.stack, player, 10f); PlayerAttributes.SPEED_COUNTER.setValue(speed < 0 ? 0 : speed, player); } else { e.newDamage += PlayerAttributes.STRENGTH.getValue(player) * ItemAttributes.STR_MUL.getSafe(e.stack, player, 0); } e.entity.hurtResistantTime = 0; e.knockback += ItemAttributes.KNOCKBACK.getSafe(e.stack, player, 0); } } } @SubscribeEvent(priority = EventPriority.LOWEST) public void onHitEntityPost(HitEntityEvent e) { if (e.attacker != null && !e.attacker.worldObj.isRemote && e.attacker instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) e.attacker; if (RPGItemHelper.isRPGable(e.stack)) { Stub<Float> damage = Stub.create(e.newDamage); GemTypes.AM.activate1All(e.stack, player, e.entity, damage); e.newDamage = damage.value1; } } } @SubscribeEvent @SideOnly(Side.CLIENT) public void addInformation(ItemTooltipEvent e) { if (RPGItemHelper.isRPGable(e.itemStack)) { Item item = e.itemStack.getItem(); e.toolTip.add(""); e.toolTip.add( Utils.toString( EnumChatFormatting.GOLD, ItemAttributes.LEVEL.getDispayName(), ": ", (int) ItemAttributes.LEVEL.get(e.itemStack))); if (ItemAttributes.LEVEL.isMax(e.itemStack)) { e.toolTip.add(Utils.toString(EnumChatFormatting.GRAY, DangerRPG.trans("rpgstr.max"))); } else { if (ItemAttributes.MAX_EXP.hasIt(e.itemStack)) { e.toolTip.add( Utils.toString( EnumChatFormatting.GRAY, ItemAttributes.CURR_EXP.getDispayName(), ": ", (int) ItemAttributes.CURR_EXP.get(e.itemStack), "/", (int) ItemAttributes.MAX_EXP.get(e.itemStack))); } } HashMap<GemType, List<ItemStack>> map = new HashMap<GemType, List<ItemStack>>(); Set<GemType> set = RPGCapability.rpgItemRegistr.get(item).gems.keySet(); for (GemType gemType : set) { List<ItemStack> list = gemType.get(e.itemStack); if (!list.isEmpty()) { map.put(gemType, list); } } if (!map.isEmpty()) { e.toolTip.add(""); for (Entry<GemType, List<ItemStack>> entry : map.entrySet()) { e.toolTip.add( Utils.toString( entry.getKey() .getDispayName(), ":")); for (ItemStack it : entry.getValue()) { e.toolTip.add( Utils.toString(" - ", it.getDisplayName(), " (", (int) ItemAttributes.LEVEL.get(it), ")")); } } } } } @SideOnly(Side.CLIENT) @SubscribeEvent public void onPlayerTickClient(TickEvent.PlayerTickEvent e) { Minecraft m; if (e.phase == TickEvent.Phase.END) { if (e.player.swingProgressInt == 1) { ItemStack stack = e.player.getCurrentEquippedItem(); if (stack != null && ItemAttributes.REACH.hasIt(stack)) { MovingObjectPosition object = RPGHelper.getMouseOver(0, ItemAttributes.REACH.get(stack) + 4); if (object != null && object.entityHit != null && object.entityHit != e.player && object.entityHit.hurtResistantTime == 0) { FMLClientHandler.instance() .getClient().playerController.attackEntity(e.player, object.entityHit); } } } } } @SubscribeEvent public void onBreakSpeed(BreakSpeed e) { if (ForgeHooks.canToolHarvestBlock(e.block, e.metadata, e.entityPlayer.inventory.getCurrentItem())) { e.newSpeed += PlayerAttributes.EFFICIENCY.getValue(e.entityPlayer); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onDealtDamagePre(DealtDamageEvent e) { if (!e.player.worldObj.isRemote && e.stack != null && RPGItemHelper.isRPGable(e.stack)) { Stub<Float> damage = Stub.create(e.damage); GemTypes.AM.activate2All(e.stack, e.player, e.target, damage); e.damage = damage.value1; } } @SubscribeEvent public void onEntityDeath(LivingDeathEvent event) { if (event.source.getEntity() instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.source.getEntity(); ItemStack heldItem = player.getHeldItem(); if (RPGItemHelper.isRPGable(heldItem)) { EntityLivingBase entity = event.entityLiving; int maxHealth = (int) entity.getMaxHealth(); float xp = maxHealth / 8f; RPGItemHelper.upEquipment(player, heldItem, xp, false); } } } @SubscribeEvent public void onBreak(BreakEvent e) { RPGItemHelper.upEquipment( e.getPlayer(), e.getPlayer() .getCurrentEquippedItem(), e.block.getBlockHardness(e.world, e.x, e.y, e.z), true); } @SubscribeEvent public void onStackChangedEvent(StackChangedEvent e) { if (e.oldStack != null) { GemTypes.PA.activate2All(e.oldStack, e.player); } if (e.stack != null) { GemTypes.PA.activate1All(e.stack, e.player); } } @SubscribeEvent public void onlivingUpdate(LivingEvent.LivingUpdateEvent e) { if (e.entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) e.entityLiving; IAttributeInstance attr = player.getEntityAttribute(SharedMonsterAttributes.attackDamage); AttributeModifier mod = attr.getModifier(RPGUUIDs.ADD_STR_DAMAGE); if (mod != null) { attr.removeModifier(mod); } ItemStack heldItem = player.getHeldItem(); if (heldItem != null && RPGItemHelper.isRPGable(heldItem) && ItemAttributes.STR_MUL.hasIt(heldItem)) { double newModifierValue = PlayerAttributes.STRENGTH.getValue(player) * ItemAttributes.STR_MUL.get(heldItem) * 2; AttributeModifier newMod = new AttributeModifier( RPGUUIDs.ADD_STR_DAMAGE, "Strength damage", newModifierValue, 0).setSaved(true); attr.applyModifier(newMod); } } } @SubscribeEvent
public void onUpMaxLevel(UpMaxLevelEvent e) {
4
2023-10-31 21:00:14+00:00
24k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/AbstractSqlSupport.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.jdbc.core.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.page.IPageHandle; import org.tinycloud.jdbc.page.Page; import org.tinycloud.jdbc.sql.SqlGenerator; import org.tinycloud.jdbc.sql.SqlProvider; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*;
16,162
String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, params, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param clazz 实体类型 * @param page 分页参数 * @param params ?参数 * @return Page<F> */ @Override public <F> Page<F> paginate(String sql, Class<F> clazz, Page<F> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<F> resultList = getJdbcTemplate().query(selectSql, params, new BeanPropertyRowMapper<>(clazz)); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 执行删除,插入,更新操作 * * @param sql 要执行的SQL * @param params 要绑定到SQL的参数 * @return 成功的条数 */ @Override public int execute(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int insert(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int update(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int delete(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } /** * 使用 in 进行批量操作,比如批量启用,批量禁用,批量删除等 -- 更灵活的就需要自己写了 * * @param sql 示例: update s_url_map set del_flag = '1' where id in (:idList) * @param idList 一般为 List<String> 或 List<Integer> * @return 执行的结果条数 */ @Override public int batchOpera(String sql, List<Object> idList) { if (idList == null || idList.size() == 0) { throw new JdbcException("batchOpera idList cannot be null or empty"); } NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); Map<String, Object> param = new HashMap<>(); param.put("idList", idList); return namedJdbcTemplate.update(sql, param); } // ---------------------------------ISqlSupport结束--------------------------------- // ---------------------------------IObjectSupport开始--------------------------------- @Override public T selectById(ID id) { if (id == null) { throw new JdbcException("selectById id cannot be null"); }
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override public Page<T> paginate(String sql, Page<T> page) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param page 分页参数 * @param params ?参数 * @return Page<T> */ @Override public Page<T> paginate(String sql, Page<T> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<T> resultList = getJdbcTemplate().query(selectSql, params, rowMapper); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 分页查询(带参数) * * @param sql 要执行的SQL * @param clazz 实体类型 * @param page 分页参数 * @param params ?参数 * @return Page<F> */ @Override public <F> Page<F> paginate(String sql, Class<F> clazz, Page<F> page, final Object... params) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) { throw new JdbcException("paginate page cannot be null"); } if (page.getPageNum() <= 0) { throw new JdbcException("当前页数必须大于1"); } if (page.getPageSize() <= 0) { throw new JdbcException("每页大小必须大于1"); } String selectSql = getPageHandle().handlerPagingSQL(sql, page.getPageNum(), page.getPageSize()); String countSql = getPageHandle().handlerCountSQL(sql); // 查询数据列表 List<F> resultList = getJdbcTemplate().query(selectSql, params, new BeanPropertyRowMapper<>(clazz)); // 查询总共数量 int totalSize = getJdbcTemplate().queryForObject(countSql, params, Integer.class); page.setRecords(resultList); page.setTotal(totalSize); return page; } /** * 执行删除,插入,更新操作 * * @param sql 要执行的SQL * @param params 要绑定到SQL的参数 * @return 成功的条数 */ @Override public int execute(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int insert(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int update(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } @Override public int delete(String sql, final Object... params) { int num = 0; if (params == null || params.length == 0) { num = getJdbcTemplate().update(sql); } else { num = getJdbcTemplate().update(sql, params); } return num; } /** * 使用 in 进行批量操作,比如批量启用,批量禁用,批量删除等 -- 更灵活的就需要自己写了 * * @param sql 示例: update s_url_map set del_flag = '1' where id in (:idList) * @param idList 一般为 List<String> 或 List<Integer> * @return 执行的结果条数 */ @Override public int batchOpera(String sql, List<Object> idList) { if (idList == null || idList.size() == 0) { throw new JdbcException("batchOpera idList cannot be null or empty"); } NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); Map<String, Object> param = new HashMap<>(); param.put("idList", idList); return namedJdbcTemplate.update(sql, param); } // ---------------------------------ISqlSupport结束--------------------------------- // ---------------------------------IObjectSupport开始--------------------------------- @Override public T selectById(ID id) { if (id == null) { throw new JdbcException("selectById id cannot be null"); }
SqlProvider sqlProvider = SqlGenerator.selectByIdSql(id, entityClass);
6
2023-10-25 14:44:59+00:00
24k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/emsi/Event.java
[ { "identifier": "Casualties", "path": "src/main/java/com/hubsante/model/emsi/Casualties.java", "snippet": "@JsonPropertyOrder({Casualties.JSON_PROPERTY_C_O_N_T_E_X_T,\n Casualties.JSON_PROPERTY_D_A_T_I_M_E,\n Casualties.JSON_PROPERTY_D_E_C_O_N_T,\n ...
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.emsi.Casualties; import com.hubsante.model.emsi.Egeo; import com.hubsante.model.emsi.Etype; import com.hubsante.model.emsi.Evac; import com.hubsante.model.emsi.Reference; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty;
16,629
@JsonCreator public static SCALEEnum fromValue(String value) { for (SCALEEnum b : SCALEEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_C_A_L_E = "SCALE"; private SCALEEnum SCALE; public static final String JSON_PROPERTY_C_E_R_T_A_I_N_T_Y = "CERTAINTY"; private Integer CERTAINTY; public static final String JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E = "DECL_DATIME"; private OffsetDateTime DECL_DATIME; public static final String JSON_PROPERTY_O_C_C_D_A_T_I_M_E = "OCC_DATIME"; private OffsetDateTime OCC_DATIME; public static final String JSON_PROPERTY_O_B_S_D_A_T_I_M_E = "OBS_DATIME"; private OffsetDateTime OBS_DATIME; /** * Permet de décrire le status de l&#39;affaire en cours. Ce champ suit une * nomenclature EMSI. (COM &#x3D; event complete, IPR &#x3D; event in * progress, NST &#x3D; event not started, STOP &#x3D; STOP &#x3D; event under * control, no need for additional resource) Dans le cadre d&#39;une opération * : - si l&#39;opération est encore en cours : rensigner &#39;IPR&#39;, - si * le dispatching de moyens est encore en cours ou que seulement des * qualifications d&#39;alertes ont été échangées sans aucune décision de * régulation &#39;NST&#39;, - si l&#39;opération est en pause/veille : * &#39;STOP&#39; - si le message d&#39;échange opérationnel décrit une fin * d&#39;opération, à renseigner avec &#39;COM&#39; Un message EMSI-EO sans * RESSOURCE ni */ public enum STATUSEnum { COM("COM"), IPR("IPR"), NST("NST"), STOP("STOP"); private String value; STATUSEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static STATUSEnum fromValue(String value) { for (STATUSEnum b : STATUSEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_T_A_T_U_S = "STATUS"; private STATUSEnum STATUS; /** * Optionnel */ public enum RISKASSESMENTEnum { NCREA("NCREA"), DECREA("DECREA"), STABLE("STABLE"); private String value; RISKASSESMENTEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static RISKASSESMENTEnum fromValue(String value) { for (RISKASSESMENTEnum b : RISKASSESMENTEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T = "RISK_ASSESMENT"; private RISKASSESMENTEnum RISK_ASSESMENT; public static final String JSON_PROPERTY_R_E_F_E_R_E_N_C_E = "REFERENCE"; private List<Reference> REFERENCE; public static final String JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S = "CASUALTIES";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.emsi; /** * Event */ @JsonPropertyOrder( {Event.JSON_PROPERTY_I_D, Event.JSON_PROPERTY_N_A_M_E, Event.JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D, Event.JSON_PROPERTY_E_T_Y_P_E, Event.JSON_PROPERTY_S_O_U_R_C_E, Event.JSON_PROPERTY_S_C_A_L_E, Event.JSON_PROPERTY_C_E_R_T_A_I_N_T_Y, Event.JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E, Event.JSON_PROPERTY_O_C_C_D_A_T_I_M_E, Event.JSON_PROPERTY_O_B_S_D_A_T_I_M_E, Event.JSON_PROPERTY_S_T_A_T_U_S, Event.JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T, Event.JSON_PROPERTY_R_E_F_E_R_E_N_C_E, Event.JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S, Event.JSON_PROPERTY_E_V_A_C, Event.JSON_PROPERTY_E_G_E_O, Event.JSON_PROPERTY_C_A_U_S_E, Event.JSON_PROPERTY_F_R_E_E_T_E_X_T}) @JsonTypeName("event") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Event { public static final String JSON_PROPERTY_I_D = "ID"; private String ID; public static final String JSON_PROPERTY_N_A_M_E = "NAME"; private String NAME; public static final String JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D = "MAIN_EVENT_ID"; private String MAIN_EVENT_ID; public static final String JSON_PROPERTY_E_T_Y_P_E = "ETYPE"; private Etype ETYPE; /** * Optionnel */ public enum SOURCEEnum { COMFOR("COMFOR"), HUMDED("HUMDED"), HUMOBS("HUMOBS"), SENSOR("SENSOR"); private String value; SOURCEEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static SOURCEEnum fromValue(String value) { for (SOURCEEnum b : SOURCEEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_O_U_R_C_E = "SOURCE"; private SOURCEEnum SOURCE; /** * Optionnel, Niveau de criticité de l&#39;opération */ public enum SCALEEnum { _1("1"), _2("2"), _3("3"), _4("4"), _5("5"); private String value; SCALEEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static SCALEEnum fromValue(String value) { for (SCALEEnum b : SCALEEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_C_A_L_E = "SCALE"; private SCALEEnum SCALE; public static final String JSON_PROPERTY_C_E_R_T_A_I_N_T_Y = "CERTAINTY"; private Integer CERTAINTY; public static final String JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E = "DECL_DATIME"; private OffsetDateTime DECL_DATIME; public static final String JSON_PROPERTY_O_C_C_D_A_T_I_M_E = "OCC_DATIME"; private OffsetDateTime OCC_DATIME; public static final String JSON_PROPERTY_O_B_S_D_A_T_I_M_E = "OBS_DATIME"; private OffsetDateTime OBS_DATIME; /** * Permet de décrire le status de l&#39;affaire en cours. Ce champ suit une * nomenclature EMSI. (COM &#x3D; event complete, IPR &#x3D; event in * progress, NST &#x3D; event not started, STOP &#x3D; STOP &#x3D; event under * control, no need for additional resource) Dans le cadre d&#39;une opération * : - si l&#39;opération est encore en cours : rensigner &#39;IPR&#39;, - si * le dispatching de moyens est encore en cours ou que seulement des * qualifications d&#39;alertes ont été échangées sans aucune décision de * régulation &#39;NST&#39;, - si l&#39;opération est en pause/veille : * &#39;STOP&#39; - si le message d&#39;échange opérationnel décrit une fin * d&#39;opération, à renseigner avec &#39;COM&#39; Un message EMSI-EO sans * RESSOURCE ni */ public enum STATUSEnum { COM("COM"), IPR("IPR"), NST("NST"), STOP("STOP"); private String value; STATUSEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static STATUSEnum fromValue(String value) { for (STATUSEnum b : STATUSEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_T_A_T_U_S = "STATUS"; private STATUSEnum STATUS; /** * Optionnel */ public enum RISKASSESMENTEnum { NCREA("NCREA"), DECREA("DECREA"), STABLE("STABLE"); private String value; RISKASSESMENTEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static RISKASSESMENTEnum fromValue(String value) { for (RISKASSESMENTEnum b : RISKASSESMENTEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T = "RISK_ASSESMENT"; private RISKASSESMENTEnum RISK_ASSESMENT; public static final String JSON_PROPERTY_R_E_F_E_R_E_N_C_E = "REFERENCE"; private List<Reference> REFERENCE; public static final String JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S = "CASUALTIES";
private List<Casualties> CASUALTIES;
0
2023-10-25 14:24:31+00:00
24k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/Application.java
[ { "identifier": "ConfigReader", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/core/ConfigReader.java", "snippet": "public class ConfigReader {\n\n private static final ConfigReader INSTANCE = new ConfigReader();\n\n private final Properties properties;\n\n private ConfigReader() {\n ...
import java.util.ArrayList; import java.util.List; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import ua.ivanzaitsev.bot.core.ConfigReader; import ua.ivanzaitsev.bot.core.TelegramBot; import ua.ivanzaitsev.bot.handlers.ActionHandler; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.handlers.commands.CartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.CatalogCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderConfirmCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterAddressCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterCityCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterNameCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterPhoneNumberCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepCancelCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepPreviousCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.StartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistryDefault; import ua.ivanzaitsev.bot.repositories.CartRepository; import ua.ivanzaitsev.bot.repositories.CategoryRepository; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository; import ua.ivanzaitsev.bot.repositories.ClientRepository; import ua.ivanzaitsev.bot.repositories.OrderRepository; import ua.ivanzaitsev.bot.repositories.ProductRepository; import ua.ivanzaitsev.bot.repositories.database.CategoryRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ClientRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.OrderRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ProductRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.CartRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientActionRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientCommandStateRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientOrderStateRepositoryDefault; import ua.ivanzaitsev.bot.services.MessageService; import ua.ivanzaitsev.bot.services.NotificationService; import ua.ivanzaitsev.bot.services.impl.MessageServiceDefault; import ua.ivanzaitsev.bot.services.impl.NotificationServiceDefault;
19,636
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository; private CategoryRepository categoryRepository; private ProductRepository productRepository; private OrderRepository orderRepository; private ClientRepository clientRepository; private MessageService messageService; private NotificationService notificationService; private CommandHandlerRegistry commandHandlerRegistry; private List<CommandHandler> commandHandlers; private List<UpdateHandler> updateHandlers; private List<ActionHandler> actionHandlers; private void initializeRepositories() { clientActionRepository = new ClientActionRepositoryDefault(); clientCommandStateRepository = new ClientCommandStateRepositoryDefault(); clientOrderStateRepository = new ClientOrderStateRepositoryDefault(); cartRepository = new CartRepositoryDefault(); categoryRepository = new CategoryRepositoryDefault(); productRepository = new ProductRepositoryDefault(); orderRepository = new OrderRepositoryDefault(); clientRepository = new ClientRepositoryDefault(); } private void initializeServices() { messageService = new MessageServiceDefault(); notificationService = new NotificationServiceDefault(configReader); } private void initializeCommandHandlers() { commandHandlerRegistry = new CommandHandlerRegistryDefault(); commandHandlers = new ArrayList<>(); commandHandlers.add(new CatalogCommandHandler(commandHandlerRegistry, categoryRepository, productRepository, cartRepository, messageService)); commandHandlers.add(new CartCommandHandler(commandHandlerRegistry, clientCommandStateRepository, clientOrderStateRepository, cartRepository, clientRepository, messageService)); commandHandlers.add(new OrderEnterNameCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterCityCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterAddressCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderConfirmCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository, cartRepository, orderRepository, clientRepository, messageService, notificationService)); commandHandlerRegistry.setCommandHandlers(commandHandlers); } private void initializeUpdateHandlers() { updateHandlers = new ArrayList<>(); updateHandlers.add(new StartCommandHandler(clientRepository, messageService)); updateHandlers.add(new CatalogCommandHandler(commandHandlerRegistry, categoryRepository, productRepository, cartRepository, messageService)); updateHandlers.add(new CartCommandHandler(commandHandlerRegistry, clientCommandStateRepository, clientOrderStateRepository, cartRepository, clientRepository, messageService)); updateHandlers.add(new OrderStepCancelCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); updateHandlers.add(new OrderStepPreviousCommandHandler(commandHandlerRegistry, clientCommandStateRepository)); updateHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); } private void initializeActionHandlers() { actionHandlers = new ArrayList<>(); actionHandlers.add(new OrderEnterNameCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterCityCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterAddressCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderConfirmCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository, cartRepository, orderRepository, clientRepository, messageService, notificationService)); } public static void main(String[] args) throws TelegramApiException { Application application = new Application(); application.initializeRepositories(); application.initializeServices(); application.initializeCommandHandlers(); application.initializeUpdateHandlers(); application.initializeActionHandlers();
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository; private CategoryRepository categoryRepository; private ProductRepository productRepository; private OrderRepository orderRepository; private ClientRepository clientRepository; private MessageService messageService; private NotificationService notificationService; private CommandHandlerRegistry commandHandlerRegistry; private List<CommandHandler> commandHandlers; private List<UpdateHandler> updateHandlers; private List<ActionHandler> actionHandlers; private void initializeRepositories() { clientActionRepository = new ClientActionRepositoryDefault(); clientCommandStateRepository = new ClientCommandStateRepositoryDefault(); clientOrderStateRepository = new ClientOrderStateRepositoryDefault(); cartRepository = new CartRepositoryDefault(); categoryRepository = new CategoryRepositoryDefault(); productRepository = new ProductRepositoryDefault(); orderRepository = new OrderRepositoryDefault(); clientRepository = new ClientRepositoryDefault(); } private void initializeServices() { messageService = new MessageServiceDefault(); notificationService = new NotificationServiceDefault(configReader); } private void initializeCommandHandlers() { commandHandlerRegistry = new CommandHandlerRegistryDefault(); commandHandlers = new ArrayList<>(); commandHandlers.add(new CatalogCommandHandler(commandHandlerRegistry, categoryRepository, productRepository, cartRepository, messageService)); commandHandlers.add(new CartCommandHandler(commandHandlerRegistry, clientCommandStateRepository, clientOrderStateRepository, cartRepository, clientRepository, messageService)); commandHandlers.add(new OrderEnterNameCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterCityCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderEnterAddressCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); commandHandlers.add(new OrderConfirmCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository, cartRepository, orderRepository, clientRepository, messageService, notificationService)); commandHandlerRegistry.setCommandHandlers(commandHandlers); } private void initializeUpdateHandlers() { updateHandlers = new ArrayList<>(); updateHandlers.add(new StartCommandHandler(clientRepository, messageService)); updateHandlers.add(new CatalogCommandHandler(commandHandlerRegistry, categoryRepository, productRepository, cartRepository, messageService)); updateHandlers.add(new CartCommandHandler(commandHandlerRegistry, clientCommandStateRepository, clientOrderStateRepository, cartRepository, clientRepository, messageService)); updateHandlers.add(new OrderStepCancelCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); updateHandlers.add(new OrderStepPreviousCommandHandler(commandHandlerRegistry, clientCommandStateRepository)); updateHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); } private void initializeActionHandlers() { actionHandlers = new ArrayList<>(); actionHandlers.add(new OrderEnterNameCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterPhoneNumberCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterCityCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderEnterAddressCommandHandler(commandHandlerRegistry, clientActionRepository, clientCommandStateRepository, clientOrderStateRepository)); actionHandlers.add(new OrderConfirmCommandHandler(clientActionRepository, clientCommandStateRepository, clientOrderStateRepository, cartRepository, orderRepository, clientRepository, messageService, notificationService)); } public static void main(String[] args) throws TelegramApiException { Application application = new Application(); application.initializeRepositories(); application.initializeServices(); application.initializeCommandHandlers(); application.initializeUpdateHandlers(); application.initializeActionHandlers();
TelegramBot telegramBot = new TelegramBot(application.configReader, application.clientActionRepository,
1
2023-10-29 15:49:41+00:00
24k
Java-Game-Engine-Merger/Libgdx-Processing
framework/src/main/java/pama1234/gdx/util/app/UtilScreenCore.java
[ { "identifier": "floor", "path": "server-framework/src/main/java/pama1234/math/UtilMath.java", "snippet": "public static int floor(float in) {\n return (int)Math.floor(in);\n}" }, { "identifier": "max", "path": "server-framework/src/main/java/pama1234/math/UtilMath.java", "snippet": "pu...
import static pama1234.math.UtilMath.floor; import static pama1234.math.UtilMath.max; import static pama1234.math.UtilMath.min; import pama1234.gdx.game.ui.element.Button; import pama1234.gdx.game.ui.element.TextButton; import pama1234.gdx.util.cam.CameraController; import pama1234.gdx.util.element.FontStyle; import pama1234.gdx.util.font.MultiChunkFont; import pama1234.gdx.util.graphics.ShapeRendererBase.ShapeType; import pama1234.gdx.util.graphics.UtilPolygonSpriteBatch; import pama1234.gdx.util.graphics.UtilShapeRenderer; import pama1234.gdx.util.info.MouseInfo; import pama1234.gdx.util.info.TouchInfo; import pama1234.gdx.util.input.UtilInputProcesser; import pama1234.gdx.util.listener.EntityListener; import pama1234.gdx.util.listener.EntityNeoListener; import pama1234.gdx.util.listener.InputListener; import pama1234.gdx.util.listener.SystemListener; import pama1234.gdx.util.wrapper.AutoEntityManager; import pama1234.gdx.util.wrapper.DisplayEntity.DisplayWithCam; import pama1234.gdx.util.wrapper.EntityCenter; import pama1234.gdx.util.wrapper.EntityNeoCenter; import pama1234.util.UtilServer; import pama1234.util.listener.LifecycleListener; import pama1234.util.listener.ServerEntityListener; import pama1234.util.wrapper.Center; import pama1234.util.wrapper.ServerEntityCenter; import java.util.Random; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.viewport.Viewport; import dev.lyze.gdxtinyvg.drawers.TinyVGShapeDrawer; import hhs.gdx.hslib.tools.LoopThread;
18,436
package pama1234.gdx.util.app; /** * UtilScreen太大了,因此抽离了一部分内容到此类,抽离的规则未确定 * * @see UtilScreen */ public abstract class UtilScreenCore implements Screen,InputListener,LifecycleListener,SystemListener{ public final float fontGridSize=4; public boolean flip=true; public int width,height; public int frameCount; public float frameRate; public boolean doUpdateThread; public LoopThread updateThread; // public float frameDelta; //--------------------------------------------------------------------------- public boolean mouseMoved; public MouseInfo mouse; public Vector3 vectorCache; public int touchCount; public TouchInfo[] touches=new TouchInfo[16]; public boolean grabCursor; public boolean is3d; //--------------------------------------------------------------------------- public boolean keyPressed; /** normally "a" and "A" will be treat as 'A' */ public char key; /** see {@link com.badlogic.gdx.Input.Keys gdx.Input.Keys} for keyCodes */ public int keyCode; public boolean shift,ctrl,alt; public IntArray keyPressedArray; public boolean focus; public CameraController cam; public OrthographicCamera screenCam; public Camera usedCamera; public SpriteBatch fontBatch,imageBatch; public TinyVGShapeDrawer tvgDrawer; public MultiChunkFont font; //--------------------------------------------------------------------------- public FontStyle fontStyle=new FontStyle(); public Color textColor,fillColor,strokeColor; public boolean fill=true,stroke=true; public float defaultStrokeWeight,strokeWeight; public UtilShapeRenderer rFill,rStroke; public UtilPolygonSpriteBatch pFill; public boolean background=true; public Color backgroundColor; /** * 仅会执行存放在list中的所有实体的update方法和监听事件,不会执行display方法 * * @webref UtilScreen:center * @webBrief EntityCenter containing EntityListeners */ public EntityCenter<UtilScreen,EntityListener> center; /** * 执行update和display方法,以相机视角为坐标变幻标准 * </p> * TODO 应当改为更高效的实现 */ public EntityCenter<UtilScreen,EntityListener> centerCam; /** * 执行update和display方法,以屏幕为坐标变幻标准 * </p> * TODO 应当改为更高效的实现 */ public EntityCenter<UtilScreen,EntityListener> centerScreen; /** * {@link UtilScreenCore#centerScreen} 加上 {@link DisplayWithCam} */ public EntityNeoCenter<UtilScreen,EntityNeoListener> centerNeo; /** 类似center但是存放的是ServerEntityListener */ public ServerEntityCenter<UtilServer,ServerEntityListener> serverCenter; /** 自动注册和删除实体 */ public AutoEntityManager<UtilScreen> auto; /** 监听系统事件 */
package pama1234.gdx.util.app; /** * UtilScreen太大了,因此抽离了一部分内容到此类,抽离的规则未确定 * * @see UtilScreen */ public abstract class UtilScreenCore implements Screen,InputListener,LifecycleListener,SystemListener{ public final float fontGridSize=4; public boolean flip=true; public int width,height; public int frameCount; public float frameRate; public boolean doUpdateThread; public LoopThread updateThread; // public float frameDelta; //--------------------------------------------------------------------------- public boolean mouseMoved; public MouseInfo mouse; public Vector3 vectorCache; public int touchCount; public TouchInfo[] touches=new TouchInfo[16]; public boolean grabCursor; public boolean is3d; //--------------------------------------------------------------------------- public boolean keyPressed; /** normally "a" and "A" will be treat as 'A' */ public char key; /** see {@link com.badlogic.gdx.Input.Keys gdx.Input.Keys} for keyCodes */ public int keyCode; public boolean shift,ctrl,alt; public IntArray keyPressedArray; public boolean focus; public CameraController cam; public OrthographicCamera screenCam; public Camera usedCamera; public SpriteBatch fontBatch,imageBatch; public TinyVGShapeDrawer tvgDrawer; public MultiChunkFont font; //--------------------------------------------------------------------------- public FontStyle fontStyle=new FontStyle(); public Color textColor,fillColor,strokeColor; public boolean fill=true,stroke=true; public float defaultStrokeWeight,strokeWeight; public UtilShapeRenderer rFill,rStroke; public UtilPolygonSpriteBatch pFill; public boolean background=true; public Color backgroundColor; /** * 仅会执行存放在list中的所有实体的update方法和监听事件,不会执行display方法 * * @webref UtilScreen:center * @webBrief EntityCenter containing EntityListeners */ public EntityCenter<UtilScreen,EntityListener> center; /** * 执行update和display方法,以相机视角为坐标变幻标准 * </p> * TODO 应当改为更高效的实现 */ public EntityCenter<UtilScreen,EntityListener> centerCam; /** * 执行update和display方法,以屏幕为坐标变幻标准 * </p> * TODO 应当改为更高效的实现 */ public EntityCenter<UtilScreen,EntityListener> centerScreen; /** * {@link UtilScreenCore#centerScreen} 加上 {@link DisplayWithCam} */ public EntityNeoCenter<UtilScreen,EntityNeoListener> centerNeo; /** 类似center但是存放的是ServerEntityListener */ public ServerEntityCenter<UtilServer,ServerEntityListener> serverCenter; /** 自动注册和删除实体 */ public AutoEntityManager<UtilScreen> auto; /** 监听系统事件 */
public Center<SystemListener> centerSys;
25
2023-10-27 05:47:39+00:00
24k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/ingresar/Login.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.context.SesionUsuario; import com.context.StateColors; import com.helper.AsistenteHelper; import com.helper.DoctorHelper; import com.k33ptoo.components.KGradientPanel; import com.model.AsistenteModel; import com.model.Registro; import com.utils.Styles; import com.utils.Tools; import java.awt.Font; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.MatteBorder;
17,219
package com.view.ingresar; /** * * @author Daniel Batres * @version 1.0.0 * @since 17/09/22 */ public class Login extends Styles { private boolean eye = false; private boolean stateCorreoLogin; private boolean stateContrasenaLogin; private String actualCorreoDoctor; private final ArrayList<Registro> DOCTORES; private final ArrayList<Registro> ASISTENTES; /** * Creates new form Login */ public Login() { initComponents(); initStyles(); DOCTORES = DoctorHelper.readDoctorsRegister(); ASISTENTES = AsistenteHelper.readAsistentesRegister(); } private void validateComplete(ArrayList<Registro> registros, String usuarioSesion) { paintOneContainer(container1, StateColors.getDanger()); advertenciaCorreo.setForeground(StateColors.getDanger()); advertenciaCorreo.setText("Correo inv\u00e1lido"); textField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger())); paintOneContainer(container2, StateColors.getDanger()); advertenciaContrasena.setForeground(StateColors.getDanger()); advertenciaContrasena.setText("Contrase\u00f1a inv\u00e1lida"); passwordField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger())); String correoElectronico = textField.getText(); String contrasena = new String(passwordField.getPassword()); for (Registro registro : registros) { if (correoElectronico.equals(registro.getCorreElectronico())) { actualCorreoDoctor = correoElectronico; stateCorreoLogin = true; advertenciaCorreo.setText(""); paintOneContainer(container1, ChoosedPalette.getWHITE_PALETTE().getGray()); textField.setBorder(new MatteBorder(1, 0, 1, 0, ChoosedPalette.getWHITE_PALETTE().getGray())); } if (registro.getContrasena().equals(contrasena)) { stateContrasenaLogin = true; } if (stateCorreoLogin && stateContrasenaLogin) { switch (usuarioSesion) { case "doctor":
package com.view.ingresar; /** * * @author Daniel Batres * @version 1.0.0 * @since 17/09/22 */ public class Login extends Styles { private boolean eye = false; private boolean stateCorreoLogin; private boolean stateContrasenaLogin; private String actualCorreoDoctor; private final ArrayList<Registro> DOCTORES; private final ArrayList<Registro> ASISTENTES; /** * Creates new form Login */ public Login() { initComponents(); initStyles(); DOCTORES = DoctorHelper.readDoctorsRegister(); ASISTENTES = AsistenteHelper.readAsistentesRegister(); } private void validateComplete(ArrayList<Registro> registros, String usuarioSesion) { paintOneContainer(container1, StateColors.getDanger()); advertenciaCorreo.setForeground(StateColors.getDanger()); advertenciaCorreo.setText("Correo inv\u00e1lido"); textField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger())); paintOneContainer(container2, StateColors.getDanger()); advertenciaContrasena.setForeground(StateColors.getDanger()); advertenciaContrasena.setText("Contrase\u00f1a inv\u00e1lida"); passwordField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger())); String correoElectronico = textField.getText(); String contrasena = new String(passwordField.getPassword()); for (Registro registro : registros) { if (correoElectronico.equals(registro.getCorreElectronico())) { actualCorreoDoctor = correoElectronico; stateCorreoLogin = true; advertenciaCorreo.setText(""); paintOneContainer(container1, ChoosedPalette.getWHITE_PALETTE().getGray()); textField.setBorder(new MatteBorder(1, 0, 1, 0, ChoosedPalette.getWHITE_PALETTE().getGray())); } if (registro.getContrasena().equals(contrasena)) { stateContrasenaLogin = true; } if (stateCorreoLogin && stateContrasenaLogin) { switch (usuarioSesion) { case "doctor":
ApplicationContext.sesionUsuario = new SesionUsuario(DoctorHelper.listDoctor(registro.getIdUser()));
0
2023-10-26 19:35:40+00:00
24k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/ENTSOEHistoricalDataRetrieval.java
[ { "identifier": "CSVGenerator", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/CSVGenerator.java", "snippet": "public class CSVGenerator {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVGenerator.class);\n \n private static record ColumnBlock(List<ColumnD...
import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import tech.inceptive.ai4czc.entsoedataretrieval.csv.CSVGenerator; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.CSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.GLDocumentCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.PublicationDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.UnavailabilityDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.ENTSOEDataFetcher; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.tools.DateTimeDivider;
21,420
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */ public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set<Area> targetAreas, Area mainFlowsArea, Duration maxTimeDuration) { List<CSVTransformer> transformers = new ArrayList<>(columnType.size()); List<LocalDateTime> splits; if (Duration.ofDays(365).minus(maxTimeDuration).isNegative()) { throw new DataRetrievalError("Maximal duration can not be bigger than 365 days"); } if (columnType.contains(ColumnType.ACTUAL_LOAD)) { // split request depending on stard and end date splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchActualLoad(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.DAY_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(24, ChronoUnit.HOURS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchDayAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.WEAK_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(7, ChronoUnit.DAYS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchWeekAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.AGGREGATED_GENERATION_TYPE)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchAggregatedGenerationType(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.PHYSICAL_FLOW)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<PublicationMarketDocument> opt = fetcher.fetchPhysicalFlows(targetArea, mainFlowsArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } opt = fetcher.fetchPhysicalFlows(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } } } } if (columnType.contains(ColumnType.TRANSMISSION_OUTAGE)) { if (mainFlowsArea == null) { throw new DataRetrievalError("Please fix the main flows are when retriving data from transmission " + "outages (article 10.1.A&B)"); } splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { // TODO : check if we need to do both sides List<UnavailabilityMarketDocument> outages = fetcher.fetchTransmissionGridOutages(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); transformers.addAll(outages.stream().
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */ public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set<Area> targetAreas, Area mainFlowsArea, Duration maxTimeDuration) { List<CSVTransformer> transformers = new ArrayList<>(columnType.size()); List<LocalDateTime> splits; if (Duration.ofDays(365).minus(maxTimeDuration).isNegative()) { throw new DataRetrievalError("Maximal duration can not be bigger than 365 days"); } if (columnType.contains(ColumnType.ACTUAL_LOAD)) { // split request depending on stard and end date splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchActualLoad(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.DAY_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(24, ChronoUnit.HOURS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchDayAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.WEAK_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(7, ChronoUnit.DAYS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchWeekAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.AGGREGATED_GENERATION_TYPE)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchAggregatedGenerationType(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.PHYSICAL_FLOW)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<PublicationMarketDocument> opt = fetcher.fetchPhysicalFlows(targetArea, mainFlowsArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } opt = fetcher.fetchPhysicalFlows(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } } } } if (columnType.contains(ColumnType.TRANSMISSION_OUTAGE)) { if (mainFlowsArea == null) { throw new DataRetrievalError("Please fix the main flows are when retriving data from transmission " + "outages (article 10.1.A&B)"); } splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { // TODO : check if we need to do both sides List<UnavailabilityMarketDocument> outages = fetcher.fetchTransmissionGridOutages(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); transformers.addAll(outages.stream().
map(doc -> (CSVTransformer) new UnavailabilityDocCSVTransformer(doc, csvSeparator, csvEscapeChar)).
4
2023-10-30 09:09:53+00:00
24k
EricFan2002/SC2002
src/app/ui/camp/enquiriesview/OverlayCampInfoDisplayEnquiriesCommittee.java
[ { "identifier": "CampEnquiryController", "path": "src/app/controller/camp/CampEnquiryController.java", "snippet": "public class CampEnquiryController {\n /**\n * Private constructor to prevent instantiation.\n */\n private CampEnquiryController() {\n }\n\n /*\n * Creates a new en...
import app.controller.camp.CampEnquiryController; import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.enquiry.Enquiry; import app.entity.enquiry.EnquiryList; import app.entity.user.Student; import app.ui.camp.infomationview.OverlayCampInfoDisplayView; import app.ui.overlayactions.OverlayChooseBox; import app.ui.overlayactions.OverlayTextInputAction; import app.ui.widgets.*; import app.ui.windows.ICallBack; import app.ui.windows.Window; import java.util.ArrayList;
15,128
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiriesCommittee extends OverlayCampInfoDisplayView and implements ICallBack. * Manages the display and interaction with camp enquiries within an overlay view for committee members. */ public class OverlayCampInfoDisplayEnquiriesCommittee extends OverlayCampInfoDisplayView implements ICallBack { protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean replyEnq = false; public OverlayCampInfoDisplayEnquiriesCommittee(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); // .filterBySender(student); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 34, "Reply Participant Enquires:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(labelParticipants); participantsView = new WidgetPageSelection(3, 16, getLenX() - 6, getLenY() / 2 + 4, "Participants", enqList, OverlayCampInfoDisplayEnquiriesCommittee.this); addWidget(participantsView); textBoxCName.setSkipSelection(true); textBoxCName.setSkipSelection(true); textBoxDescription.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxDStart.setSkipSelection(true); textBoxDEnd.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxSchool.setSkipSelection(true); textBoxLocation.setSkipSelection(true); textBoxSlots.setSkipSelection(true); textBoxSlotsC.setSkipSelection(true); textBoxVis.setSkipSelection(true); removeWidget(exitButton); addWidget(exitButton); } /** * Updates the list of camp enquiries displayed in the overlay. */ public void updateEnquiries() { ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); enquiryList.clear(); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } participantsView.updateList(enqList); } /** * The main message loop handling user interactions within the camp enquiries overlay. * Manages actions based on button presses and user selections. */ public void messageLoop() { super.messageLoop(); if (participantsView.getSelectedOption() != -1) { selectedEnq = enquiryList.get(participantsView.getSelectedOption()); if (selectedEnq != null) { ArrayList<String> options = new ArrayList<>(); if(selectedEnq.getAnswer() == null || selectedEnq.getAnswer().equals("")) options.add("Reply Enquiry"); options.add("Cancel"); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiriesCommittee.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } } if (replyEnq) { replyEnq = false;
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiriesCommittee extends OverlayCampInfoDisplayView and implements ICallBack. * Manages the display and interaction with camp enquiries within an overlay view for committee members. */ public class OverlayCampInfoDisplayEnquiriesCommittee extends OverlayCampInfoDisplayView implements ICallBack { protected Camp camp; protected Student student; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean replyEnq = false; public OverlayCampInfoDisplayEnquiriesCommittee(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Student student, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.student = student; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); // .filterBySender(student); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 34, "Reply Participant Enquires:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(labelParticipants); participantsView = new WidgetPageSelection(3, 16, getLenX() - 6, getLenY() / 2 + 4, "Participants", enqList, OverlayCampInfoDisplayEnquiriesCommittee.this); addWidget(participantsView); textBoxCName.setSkipSelection(true); textBoxCName.setSkipSelection(true); textBoxDescription.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxDStart.setSkipSelection(true); textBoxDEnd.setSkipSelection(true); textBoxDClose.setSkipSelection(true); textBoxSchool.setSkipSelection(true); textBoxLocation.setSkipSelection(true); textBoxSlots.setSkipSelection(true); textBoxSlotsC.setSkipSelection(true); textBoxVis.setSkipSelection(true); removeWidget(exitButton); addWidget(exitButton); } /** * Updates the list of camp enquiries displayed in the overlay. */ public void updateEnquiries() { ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); enquiryList.clear(); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(student)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } participantsView.updateList(enqList); } /** * The main message loop handling user interactions within the camp enquiries overlay. * Manages actions based on button presses and user selections. */ public void messageLoop() { super.messageLoop(); if (participantsView.getSelectedOption() != -1) { selectedEnq = enquiryList.get(participantsView.getSelectedOption()); if (selectedEnq != null) { ArrayList<String> options = new ArrayList<>(); if(selectedEnq.getAnswer() == null || selectedEnq.getAnswer().equals("")) options.add("Reply Enquiry"); options.add("Cancel"); WidgetButton buttonPosition = participantsView.getSelectionsButton() .get(participantsView.getSelectedOption()).get(0); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(30, buttonPosition.getY(), getX() + buttonPosition.getX() + (getLenX() / 2 - 15), "Actions", options, OverlayCampInfoDisplayEnquiriesCommittee.this); mainWindow.addOverlay(overlayChooseBox); participantsView.clearSelectedOption(); } } if (replyEnq) { replyEnq = false;
OverlayTextInputAction overlayTextInputAction = new OverlayTextInputAction(60, getY() / 2 - 8, getX() + getX() / 2 - 30,
8
2023-11-01 05:18:29+00:00
24k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/BMDEntities.java
[ { "identifier": "PauseAnimationTimer", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/animation/PauseAnimationTimer.java", "snippet": "public class PauseAnimationTimer implements IAnimationTimer {\n private final Supplier<Double> sysTimeProvider;\n private final Supplier<Boolean> isP...
import com.cerbon.bosses_of_mass_destruction.animation.PauseAnimationTimer; import com.cerbon.bosses_of_mass_destruction.client.render.*; import com.cerbon.bosses_of_mass_destruction.config.BMDConfig; import com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.lich.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithArmorRenderer; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithBoneLight; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithEntity; import com.cerbon.bosses_of_mass_destruction.entity.custom.void_blossom.*; import com.cerbon.bosses_of_mass_destruction.entity.util.SimpleLivingGeoRenderer; import com.cerbon.bosses_of_mass_destruction.item.custom.ChargedEnderPearlEntity; import com.cerbon.bosses_of_mass_destruction.item.custom.SoulStarEntity; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.particle.ParticleFactories; import com.cerbon.bosses_of_mass_destruction.projectile.MagicMissileProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.PetalBladeProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.SporeBallProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometCodeAnimations; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometProjectile; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import com.cerbon.cerbons_api.api.general.data.WeakHashPredicate; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.Vec3Colors; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.mojang.blaze3d.Blaze3D; import me.shedaniel.autoconfig.AutoConfig; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.client.renderer.entity.ThrownItemRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject;
17,312
package com.cerbon.bosses_of_mass_destruction.entity; public class BMDEntities { public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig(); public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID); public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register("lich", () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER) .sized(1.8f, 3.0f) .updateInterval(1) .build(new ResourceLocation(BMDConstants.MOD_ID, "lich").toString())); public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register("blue_fireball", () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "blue_fireball").toString()));
package com.cerbon.bosses_of_mass_destruction.entity; public class BMDEntities { public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig(); public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID); public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register("lich", () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER) .sized(1.8f, 3.0f) .updateInterval(1) .build(new ResourceLocation(BMDConstants.MOD_ID, "lich").toString())); public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register("blue_fireball", () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "blue_fireball").toString()));
public static final RegistryObject<EntityType<CometProjectile>> COMET = ENTITY_TYPES.register("comet",
14
2023-10-25 16:28:17+00:00
24k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/adapters/converters/DeliveryReportDtoConverter.java
[ { "identifier": "DeliveryReportBatch", "path": "client/src/main/com/sinch/sdk/domains/sms/models/DeliveryReportBatch.java", "snippet": "public abstract class DeliveryReportBatch extends BaseDeliveryReport {\n\n private final Collection<DeliveryReportStatusDetails> statuses;\n private final Integer tot...
import com.sinch.sdk.domains.sms.models.DeliveryReportBatch; import com.sinch.sdk.domains.sms.models.DeliveryReportBatchMMS; import com.sinch.sdk.domains.sms.models.DeliveryReportBatchSMS; import com.sinch.sdk.domains.sms.models.DeliveryReportErrorCode; import com.sinch.sdk.domains.sms.models.DeliveryReportRecipient; import com.sinch.sdk.domains.sms.models.DeliveryReportRecipientEncoding; import com.sinch.sdk.domains.sms.models.DeliveryReportRecipientMMS; import com.sinch.sdk.domains.sms.models.DeliveryReportRecipientSMS; import com.sinch.sdk.domains.sms.models.DeliveryReportStatus; import com.sinch.sdk.domains.sms.models.DeliveryReportStatusDetails; import com.sinch.sdk.domains.sms.models.dto.v1.DeliveryReportDto; import com.sinch.sdk.domains.sms.models.dto.v1.DeliveryReportListDto; import com.sinch.sdk.domains.sms.models.dto.v1.MessageDeliveryStatusDto; import com.sinch.sdk.domains.sms.models.dto.v1.RecipientDeliveryReportDto; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import java.util.stream.Collectors;
16,715
package com.sinch.sdk.domains.sms.adapters.converters; public class DeliveryReportDtoConverter { public static DeliveryReportBatch convert(DeliveryReportDto dto) { DeliveryReportBatch.Builder<?> builder; if (Objects.equals(dto.getType(), DeliveryReportDto.TypeEnum.MMS.getValue())) { builder = DeliveryReportBatchMMS.builder(); } else if (Objects.equals(dto.getType(), DeliveryReportDto.TypeEnum.SMS.getValue())) { builder = DeliveryReportBatchSMS.builder(); } else { return null; } return builder .setBatchId(dto.getBatchId()) .setClientReference(dto.getClientReference()) .setStatuses( null != dto.getStatuses() ? dto.getStatuses().stream() .map(DeliveryReportDtoConverter::convert) .collect(Collectors.toList()) : null) .setTotalMessageCount(dto.getTotalMessageCount()) .build(); } public static DeliveryReportRecipient convert(RecipientDeliveryReportDto dto) { DeliveryReportRecipient.Builder<?> builder; if (Objects.equals(dto.getType(), RecipientDeliveryReportDto.TypeEnum.MMS.getValue())) { builder = DeliveryReportRecipientMMS.builder(); } else if (Objects.equals(dto.getType(), RecipientDeliveryReportDto.TypeEnum.SMS.getValue())) { builder = DeliveryReportRecipientSMS.builder(); } else { return null; } return builder .setBatchId(dto.getBatchId()) .setClientReference(dto.getClientReference()) .setAt(null != dto.getAt() ? dto.getAt().toInstant() : null) .setCode(DeliveryReportErrorCode.from(dto.getCode())) .setRecipient(dto.getRecipient()) .setStatus(DeliveryReportStatus.from(dto.getStatus())) .setAppliedOriginator(dto.getAppliedOriginator()) .setEncoding(DeliveryReportRecipientEncoding.from(dto.getEncoding())) .setNumberOfMessageParts(dto.getNumberOfMessageParts()) .setOperator(dto.getOperator()) .setOperatorStatusAt( null != dto.getOperatorStatusAt() ? dto.getOperatorStatusAt().toInstant() : null) .build(); }
package com.sinch.sdk.domains.sms.adapters.converters; public class DeliveryReportDtoConverter { public static DeliveryReportBatch convert(DeliveryReportDto dto) { DeliveryReportBatch.Builder<?> builder; if (Objects.equals(dto.getType(), DeliveryReportDto.TypeEnum.MMS.getValue())) { builder = DeliveryReportBatchMMS.builder(); } else if (Objects.equals(dto.getType(), DeliveryReportDto.TypeEnum.SMS.getValue())) { builder = DeliveryReportBatchSMS.builder(); } else { return null; } return builder .setBatchId(dto.getBatchId()) .setClientReference(dto.getClientReference()) .setStatuses( null != dto.getStatuses() ? dto.getStatuses().stream() .map(DeliveryReportDtoConverter::convert) .collect(Collectors.toList()) : null) .setTotalMessageCount(dto.getTotalMessageCount()) .build(); } public static DeliveryReportRecipient convert(RecipientDeliveryReportDto dto) { DeliveryReportRecipient.Builder<?> builder; if (Objects.equals(dto.getType(), RecipientDeliveryReportDto.TypeEnum.MMS.getValue())) { builder = DeliveryReportRecipientMMS.builder(); } else if (Objects.equals(dto.getType(), RecipientDeliveryReportDto.TypeEnum.SMS.getValue())) { builder = DeliveryReportRecipientSMS.builder(); } else { return null; } return builder .setBatchId(dto.getBatchId()) .setClientReference(dto.getClientReference()) .setAt(null != dto.getAt() ? dto.getAt().toInstant() : null) .setCode(DeliveryReportErrorCode.from(dto.getCode())) .setRecipient(dto.getRecipient()) .setStatus(DeliveryReportStatus.from(dto.getStatus())) .setAppliedOriginator(dto.getAppliedOriginator()) .setEncoding(DeliveryReportRecipientEncoding.from(dto.getEncoding())) .setNumberOfMessageParts(dto.getNumberOfMessageParts()) .setOperator(dto.getOperator()) .setOperatorStatusAt( null != dto.getOperatorStatusAt() ? dto.getOperatorStatusAt().toInstant() : null) .build(); }
public static Collection<DeliveryReportRecipient> convert(DeliveryReportListDto dto) {
11
2023-10-31 08:32:59+00:00
24k
SpCoGov/SpCoBot
src/main/java/top/spco/util/builder/ReflectionToStringBuilder.java
[ { "identifier": "ArrayUtils", "path": "src/main/java/top/spco/util/ArrayUtils.java", "snippet": "public class ArrayUtils {\n\n /**\n * An empty immutable {@link String} array.\n */\n public static final String[] EMPTY_STRING_ARRAY = {};\n\n /**\n * The index value when an element is...
import top.spco.util.ArrayUtils; import top.spco.util.ClassUtils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Objects;
19,337
/* * 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 top.spco.util.builder; /** * @since 0.3.1 */ public class ReflectionToStringBuilder extends ToStringBuilder { /** * Builds a {@code toString} value using the default {@link ToStringStyle} through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. * </p> * * @param object the Object to be output * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object) { return toString(object, null, false, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object or {@link ToStringStyle} is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object, final ToStringStyle style) { return toString(object, style, false, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient members will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * Static fields will not be included. Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { return toString(object, style, outputTransients, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Static fields will not be included. Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { return toString(object, style, outputTransients, outputStatics, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as * {@code java.lang.Object}. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param <T> the type of the object * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param excludeNullValues whether to exclude fields whose values are null * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static <T> String toString( final T object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics, final boolean excludeNullValues, final Class<? super T> reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics, excludeNullValues) .toString(); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as * {@code java.lang.Object}. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param <T> the type of the object * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static <T> String toString( final T object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics, final Class<? super T> reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) .toString(); } /** * Whether or not to append static fields. */ private boolean appendStatics; /** * Whether or not to append transient fields. */ private boolean appendTransients; /** * Whether or not to append fields that are null. */ private boolean excludeNullValues; /** * Which field names to exclude from output. Intended for fields like {@code "password"}. * * @since 0.3.1 */ protected String[] excludeFieldNames; /** * Field names that will be included in the output. All fields are included by default. * * @since 0.3.1 */ protected String[] includeFieldNames; /** * The last super class to stop appending fields for. */ private Class<?> upToClass; /** * Constructs a new instance. * * @param <T> the type of the object * @param object the Object to build a {@code toString} for * @param style the style of the {@code toString} to create, may be {@code null} * @param buffer the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @since 0.3.1 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { super(Objects.requireNonNull(object, "obj"), style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); this.setAppendStatics(outputStatics); } /** * Constructs a new instance. * * @param <T> the type of the object * @param object the Object to build a {@code toString} for * @param style the style of the {@code toString} to create, may be {@code null} * @param buffer the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param excludeNullValues whether to exclude fields who value is null * @since 0.3.1 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics, final boolean excludeNullValues) { super(Objects.requireNonNull(object, "obj"), style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); this.setAppendStatics(outputStatics); this.setExcludeNullValues(excludeNullValues); } /** * Returns whether or not to append the given {@link Field}. * <ul> * <li>Transient fields are appended only if {@link #isAppendTransients()} returns {@code true}. * <li>Static fields are appended only if {@link #isAppendStatics()} returns {@code true}. * <li>Inner class fields are not appended.</li> * </ul> * * @param field The Field to test. * @return Whether or not to append the given {@link Field}. */ protected boolean accept(final Field field) {
/* * 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 top.spco.util.builder; /** * @since 0.3.1 */ public class ReflectionToStringBuilder extends ToStringBuilder { /** * Builds a {@code toString} value using the default {@link ToStringStyle} through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. * </p> * * @param object the Object to be output * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object) { return toString(object, null, false, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object or {@link ToStringStyle} is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object, final ToStringStyle style) { return toString(object, style, false, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient members will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * Static fields will not be included. Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary */ public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { return toString(object, style, outputTransients, false, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Static fields will not be included. Superclass fields will be appended. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { return toString(object, style, outputTransients, outputStatics, null); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as * {@code java.lang.Object}. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param <T> the type of the object * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param excludeNullValues whether to exclude fields whose values are null * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static <T> String toString( final T object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics, final boolean excludeNullValues, final Class<? super T> reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics, excludeNullValues) .toString(); } /** * Builds a {@code toString} value through reflection. * * <p> * It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. * </p> * * <p> * If the {@code outputTransients} is {@code true}, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. * </p> * * <p> * If the {@code outputStatics} is {@code true}, static fields will be output, otherwise they are * ignored. * </p> * * <p> * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as * {@code java.lang.Object}. * </p> * * <p> * If the style is {@code null}, the default {@link ToStringStyle} is used. * </p> * * @param <T> the type of the object * @param object the Object to be output * @param style the style of the {@code toString} to create, may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @return the String result * @throws IllegalArgumentException if the Object is {@code null} * @see ToStringExclude * @see ToStringSummary * @since 0.3.1 */ public static <T> String toString( final T object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics, final Class<? super T> reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) .toString(); } /** * Whether or not to append static fields. */ private boolean appendStatics; /** * Whether or not to append transient fields. */ private boolean appendTransients; /** * Whether or not to append fields that are null. */ private boolean excludeNullValues; /** * Which field names to exclude from output. Intended for fields like {@code "password"}. * * @since 0.3.1 */ protected String[] excludeFieldNames; /** * Field names that will be included in the output. All fields are included by default. * * @since 0.3.1 */ protected String[] includeFieldNames; /** * The last super class to stop appending fields for. */ private Class<?> upToClass; /** * Constructs a new instance. * * @param <T> the type of the object * @param object the Object to build a {@code toString} for * @param style the style of the {@code toString} to create, may be {@code null} * @param buffer the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @since 0.3.1 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { super(Objects.requireNonNull(object, "obj"), style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); this.setAppendStatics(outputStatics); } /** * Constructs a new instance. * * @param <T> the type of the object * @param object the Object to build a {@code toString} for * @param style the style of the {@code toString} to create, may be {@code null} * @param buffer the {@link StringBuffer} to populate, may be {@code null} * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null} * @param outputTransients whether to include transient fields * @param outputStatics whether to include static fields * @param excludeNullValues whether to exclude fields who value is null * @since 0.3.1 */ public <T> ReflectionToStringBuilder( final T object, final ToStringStyle style, final StringBuffer buffer, final Class<? super T> reflectUpToClass, final boolean outputTransients, final boolean outputStatics, final boolean excludeNullValues) { super(Objects.requireNonNull(object, "obj"), style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); this.setAppendStatics(outputStatics); this.setExcludeNullValues(excludeNullValues); } /** * Returns whether or not to append the given {@link Field}. * <ul> * <li>Transient fields are appended only if {@link #isAppendTransients()} returns {@code true}. * <li>Static fields are appended only if {@link #isAppendStatics()} returns {@code true}. * <li>Inner class fields are not appended.</li> * </ul> * * @param field The Field to test. * @return Whether or not to append the given {@link Field}. */ protected boolean accept(final Field field) {
if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
1
2023-10-26 10:27:47+00:00
24k
Melledy/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerGetDailyActiveInfoCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler; import emu.lunarcore.server.packet.send.PacketGetDailyActiveInfoScRsp;
20,198
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetDailyActiveInfoCsReq) public class HandlerGetDailyActiveInfoCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception {
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetDailyActiveInfoCsReq) public class HandlerGetDailyActiveInfoCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception {
session.send(new PacketGetDailyActiveInfoScRsp(session.getPlayer()));
3
2023-10-10 12:57:35+00:00
24k
jar-analyzer/jar-analyzer
src/main/java/me/n1ar4/jar/analyzer/core/DatabaseManager.java
[ { "identifier": "SpringController", "path": "src/main/java/me/n1ar4/jar/analyzer/analyze/spring/SpringController.java", "snippet": "@SuppressWarnings(\"all\")\npublic class SpringController {\n private boolean isRest;\n private String basePath;\n private ClassReference.Handle className;\n pr...
import me.n1ar4.jar.analyzer.analyze.spring.SpringController; import me.n1ar4.jar.analyzer.analyze.spring.SpringMapping; import me.n1ar4.jar.analyzer.core.mapper.*; import me.n1ar4.jar.analyzer.entity.*; import me.n1ar4.jar.analyzer.gui.MainForm; import me.n1ar4.jar.analyzer.gui.util.LogUtil; import me.n1ar4.jar.analyzer.utils.OSUtil; import me.n1ar4.jar.analyzer.utils.PartitionUtils; import me.n1ar4.log.LogManager; import me.n1ar4.log.Logger; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.*;
21,045
package me.n1ar4.jar.analyzer.core; public class DatabaseManager { private static final Logger logger = LogManager.getLogger(); private static final SqlSession session; private static final ClassMapper classMapper; private static final MemberMapper memberMapper; private static final JarMapper jarMapper; private static final AnnoMapper annoMapper; private static final MethodMapper methodMapper; private static final StringMapper stringMapper; private static final InterfaceMapper interfaceMapper; private static final ClassFileMapper classFileMapper; private static final MethodImplMapper methodImplMapper; private static final MethodCallMapper methodCallMapper; private static final SpringControllerMapper springCMapper; private static final SpringMethodMapper springMMapper; static { logger.info("init database"); LogUtil.log("init database"); SqlSessionFactory factory = SqlSessionFactoryUtil.sqlSessionFactory; session = factory.openSession(true); classMapper = session.getMapper(ClassMapper.class); jarMapper = session.getMapper(JarMapper.class); annoMapper = session.getMapper(AnnoMapper.class); methodMapper = session.getMapper(MethodMapper.class); memberMapper = session.getMapper(MemberMapper.class); stringMapper = session.getMapper(StringMapper.class); classFileMapper = session.getMapper(ClassFileMapper.class); interfaceMapper = session.getMapper(InterfaceMapper.class); methodCallMapper = session.getMapper(MethodCallMapper.class); methodImplMapper = session.getMapper(MethodImplMapper.class); springCMapper = session.getMapper(SpringControllerMapper.class); springMMapper = session.getMapper(SpringMethodMapper.class); InitMapper initMapper = session.getMapper(InitMapper.class); initMapper.createJarTable(); initMapper.createClassTable(); initMapper.createClassFileTable(); initMapper.createMemberTable(); initMapper.createMethodTable(); initMapper.createAnnoTable(); initMapper.createInterfaceTable(); initMapper.createMethodCallTable(); initMapper.createMethodImplTable(); initMapper.createStringTable(); initMapper.createSpringControllerTable(); initMapper.createSpringMappingTable(); logger.info("create database finish"); LogUtil.log("create database finish"); } public static void saveJar(String jarPath) { JarEntity en = new JarEntity(); en.setJarAbsPath(jarPath); if (OSUtil.isWindows()) { String[] temp = jarPath.split("\\\\"); en.setJarName(temp[temp.length - 1]); } else { String[] temp = jarPath.split("/"); en.setJarName(temp[temp.length - 1]); } List<JarEntity> js = new ArrayList<>(); js.add(en); int i = jarMapper.insertJar(js); if (i != 0) { logger.debug("save jar finish"); } } public static void saveClassFiles(Set<ClassFileEntity> classFileList) { logger.info("total class file: {}", classFileList.size()); List<ClassFileEntity> list = new ArrayList<>(); for (ClassFileEntity classFile : classFileList) { classFile.setPathStr(classFile.getPath().toAbsolutePath().toString()); list.add(classFile); } List<List<ClassFileEntity>> partition = PartitionUtils.partition(list, 100); for (List<ClassFileEntity> data : partition) { int a = classFileMapper.insertClassFile(data); if (a == 0) { logger.warn("save error"); } } logger.info("save class file finish"); } public static void saveClassInfo(Set<ClassReference> discoveredClasses) { logger.info("total class: {}", discoveredClasses.size());
package me.n1ar4.jar.analyzer.core; public class DatabaseManager { private static final Logger logger = LogManager.getLogger(); private static final SqlSession session; private static final ClassMapper classMapper; private static final MemberMapper memberMapper; private static final JarMapper jarMapper; private static final AnnoMapper annoMapper; private static final MethodMapper methodMapper; private static final StringMapper stringMapper; private static final InterfaceMapper interfaceMapper; private static final ClassFileMapper classFileMapper; private static final MethodImplMapper methodImplMapper; private static final MethodCallMapper methodCallMapper; private static final SpringControllerMapper springCMapper; private static final SpringMethodMapper springMMapper; static { logger.info("init database"); LogUtil.log("init database"); SqlSessionFactory factory = SqlSessionFactoryUtil.sqlSessionFactory; session = factory.openSession(true); classMapper = session.getMapper(ClassMapper.class); jarMapper = session.getMapper(JarMapper.class); annoMapper = session.getMapper(AnnoMapper.class); methodMapper = session.getMapper(MethodMapper.class); memberMapper = session.getMapper(MemberMapper.class); stringMapper = session.getMapper(StringMapper.class); classFileMapper = session.getMapper(ClassFileMapper.class); interfaceMapper = session.getMapper(InterfaceMapper.class); methodCallMapper = session.getMapper(MethodCallMapper.class); methodImplMapper = session.getMapper(MethodImplMapper.class); springCMapper = session.getMapper(SpringControllerMapper.class); springMMapper = session.getMapper(SpringMethodMapper.class); InitMapper initMapper = session.getMapper(InitMapper.class); initMapper.createJarTable(); initMapper.createClassTable(); initMapper.createClassFileTable(); initMapper.createMemberTable(); initMapper.createMethodTable(); initMapper.createAnnoTable(); initMapper.createInterfaceTable(); initMapper.createMethodCallTable(); initMapper.createMethodImplTable(); initMapper.createStringTable(); initMapper.createSpringControllerTable(); initMapper.createSpringMappingTable(); logger.info("create database finish"); LogUtil.log("create database finish"); } public static void saveJar(String jarPath) { JarEntity en = new JarEntity(); en.setJarAbsPath(jarPath); if (OSUtil.isWindows()) { String[] temp = jarPath.split("\\\\"); en.setJarName(temp[temp.length - 1]); } else { String[] temp = jarPath.split("/"); en.setJarName(temp[temp.length - 1]); } List<JarEntity> js = new ArrayList<>(); js.add(en); int i = jarMapper.insertJar(js); if (i != 0) { logger.debug("save jar finish"); } } public static void saveClassFiles(Set<ClassFileEntity> classFileList) { logger.info("total class file: {}", classFileList.size()); List<ClassFileEntity> list = new ArrayList<>(); for (ClassFileEntity classFile : classFileList) { classFile.setPathStr(classFile.getPath().toAbsolutePath().toString()); list.add(classFile); } List<List<ClassFileEntity>> partition = PartitionUtils.partition(list, 100); for (List<ClassFileEntity> data : partition) { int a = classFileMapper.insertClassFile(data); if (a == 0) { logger.warn("save error"); } } logger.info("save class file finish"); } public static void saveClassInfo(Set<ClassReference> discoveredClasses) { logger.info("total class: {}", discoveredClasses.size());
MainForm.getInstance().getTotalClassVal().setText(String.valueOf(discoveredClasses.size()));
2
2023-10-07 15:42:35+00:00
24k
lunasaw/gb28181-proxy
gb28181-test/src/test/java/io/github/lunasaw/gbproxy/test/invite/ClientInviteTest.java
[ { "identifier": "ClientSendCmd", "path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/cmd/ClientSendCmd.java", "snippet": "public class ClientSendCmd {\n /**\n * 告警上报\n * \n * @param fromDevice\n * @param toDevice\n * @param deviceAlarmNotify\n * @re...
import javax.sip.message.Request; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import io.github.lunasaw.gbproxy.client.transmit.cmd.ClientSendCmd; import io.github.lunasaw.gbproxy.test.Gb28181ApplicationTest; import io.github.lunasaw.gbproxy.test.config.DeviceConfig; import io.github.lunasaw.gbproxy.test.user.client.DefaultRegisterProcessorClient; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.SipSender; import io.github.lunasaw.sip.common.transmit.request.SipRequestProvider; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.extern.slf4j.Slf4j;
17,447
package io.github.lunasaw.gbproxy.test.invite; /** * @author luna * @date 2023/10/12 */ @Slf4j @SpringBootTest(classes = Gb28181ApplicationTest.class) public class ClientInviteTest { @Autowired @Qualifier("clientFrom") private Device fromDevice; @Autowired @Qualifier("clientTo") private Device toDevice; @Autowired private SipLayer sipLayer; @AfterAll public static void after() { while (true) { } } @BeforeEach public void before() { // 本地端口监听 log.info("before::客户端初始化 fromDevice.ip : {} , fromDevice.port : {}", fromDevice.getIp(), fromDevice.getPort()); sipLayer.addListeningPoint(DeviceConfig.LOOP_IP, fromDevice.getPort()); // 模拟平台添加 DeviceConfig.DEVICE_CLIENT_VIEW_MAP.put(toDevice.getUserId(), toDevice); } @Test public void test_register_client() { String callId = SipRequestUtils.getNewCallId();
package io.github.lunasaw.gbproxy.test.invite; /** * @author luna * @date 2023/10/12 */ @Slf4j @SpringBootTest(classes = Gb28181ApplicationTest.class) public class ClientInviteTest { @Autowired @Qualifier("clientFrom") private Device fromDevice; @Autowired @Qualifier("clientTo") private Device toDevice; @Autowired private SipLayer sipLayer; @AfterAll public static void after() { while (true) { } } @BeforeEach public void before() { // 本地端口监听 log.info("before::客户端初始化 fromDevice.ip : {} , fromDevice.port : {}", fromDevice.getIp(), fromDevice.getPort()); sipLayer.addListeningPoint(DeviceConfig.LOOP_IP, fromDevice.getPort()); // 模拟平台添加 DeviceConfig.DEVICE_CLIENT_VIEW_MAP.put(toDevice.getUserId(), toDevice); } @Test public void test_register_client() { String callId = SipRequestUtils.getNewCallId();
Request registerRequest = SipRequestProvider.createRegisterRequest((FromDevice)fromDevice, (ToDevice)toDevice, 300, callId);
6
2023-10-11 06:56:28+00:00
24k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/SWMPlugin.java
[ { "identifier": "SlimePlugin", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/SlimePlugin.java", "snippet": "public interface SlimePlugin {\n\n /**\n * Returns the {@link ConfigManager} of the plugin.\n * This can be used to retrieve the {@link net.swofty.swm.api.world.data....
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import net.swofty.swm.api.SlimePlugin; import net.swofty.swm.api.events.PostGenerateWorldEvent; import net.swofty.swm.api.events.PreGenerateWorldEvent; import net.swofty.swm.api.exceptions.*; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.world.SlimeWorld; import net.swofty.swm.api.world.data.WorldData; import net.swofty.swm.api.world.data.WorldsConfig; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.nms.SlimeNMS; import net.swofty.swm.plugin.commands.CommandLoader; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.loader.LoaderUtils; import net.swofty.swm.plugin.log.Logging; import net.swofty.swm.plugin.world.WorldUnlocker; import net.swofty.swm.plugin.world.importer.WorldImporter; import lombok.Getter; import net.swofty.swm.plugin.config.ConfigManager; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.bukkit.*; import org.bukkit.command.CommandMap; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.java.JavaPlugin; import org.reflections.Reflections; import java.io.*; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors;
18,561
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try { ConfigManager.initialize(); } catch (NullPointerException | IOException | ObjectMappingException ex) { Logging.error("Failed to load config files:"); ex.printStackTrace(); return; } LoaderUtils.registerLoaders(); /* Initialize NMS bridge */ try { nms = getNMSBridge(); } catch (InvalidVersionException ex) { Logging.error(ex.getMessage()); return; } /* Initialize commands */ try { Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap"); f.setAccessible(true); commandMap = (CommandMap) f.get(Bukkit.getServer()); } catch (IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } cl = new CommandLoader(); SWMCommand.register(); Reflections reflection = new Reflections("net.swofty.swm.plugin.commands.subtypes"); for(Class<? extends SWMCommand> l:reflection.getSubTypesOf(SWMCommand.class)) { try { SWMCommand command = l.newInstance(); cl.register(command); } catch (InstantiationException | IllegalAccessException ex) { ex.printStackTrace(); } } /* Load worlds */ List<String> erroredWorlds = loadWorlds(); try { Properties props = new Properties(); props.load(new FileInputStream("server.properties")); String defaultWorldName = props.getProperty("level-name"); if (erroredWorlds.contains(defaultWorldName)) { Logging.error("Shutting down server, as the default world could not be loaded."); System.exit(1); } else if (getServer().getAllowNether() && erroredWorlds.contains(defaultWorldName + "_nether")) { Logging.error("Shutting down server, as the default nether world could not be loaded."); System.exit(1); } else if (getServer().getAllowEnd() && erroredWorlds.contains(defaultWorldName + "_the_end")) { Logging.error("Shutting down server, as the default end world could not be loaded."); System.exit(1); } Map<String, SlimeWorld> loadedWorlds = getSlimeWorlds(); SlimeWorld defaultWorld = loadedWorlds.get(defaultWorldName); SlimeWorld netherWorld = getServer().getAllowNether() ? loadedWorlds.get(defaultWorldName + "_nether") : null; SlimeWorld endWorld = getServer().getAllowEnd() ? loadedWorlds.get(defaultWorldName + "_the_end") : null; nms.setDefaultWorlds(defaultWorld, netherWorld, endWorld); } catch (IOException ex) { Logging.error("Failed to retrieve default world name:"); ex.printStackTrace(); } } @Override public void onEnable() { if (nms == null) { this.setEnabled(false); return; } getServer().getPluginManager().registerEvents(new WorldUnlocker(), this); toGenerate.forEach(this::generateWorld); } @Override public void onDisable() { Bukkit.getWorlds().stream() .map(world -> getNms().getSlimeWorld(world)) .filter(Objects::nonNull) .forEach(world -> { world.unloadWorld(true); try { world.getLoader().unlockWorld(world.getName()); } catch (UnknownWorldException | IOException e) { throw new RuntimeException(e); } }); } private SlimeNMS getNMSBridge() throws InvalidVersionException { return new SlimeNMS(); } private List<String> loadWorlds() { List<String> erroredWorlds = new ArrayList<>(); WorldsConfig config = getConfigManager().getWorldConfig(); for (Map.Entry<String, WorldData> entry : config.getWorlds().entrySet()) { String worldName = entry.getKey(); WorldData worldData = entry.getValue(); if (worldData.isLoadOnStartup()) { try { SlimeLoader loader = getLoader(worldData.getDataSource()); if (loader == null) { throw new IllegalArgumentException("invalid data source " + worldData.getDataSource() + ""); }
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try { ConfigManager.initialize(); } catch (NullPointerException | IOException | ObjectMappingException ex) { Logging.error("Failed to load config files:"); ex.printStackTrace(); return; } LoaderUtils.registerLoaders(); /* Initialize NMS bridge */ try { nms = getNMSBridge(); } catch (InvalidVersionException ex) { Logging.error(ex.getMessage()); return; } /* Initialize commands */ try { Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap"); f.setAccessible(true); commandMap = (CommandMap) f.get(Bukkit.getServer()); } catch (IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } cl = new CommandLoader(); SWMCommand.register(); Reflections reflection = new Reflections("net.swofty.swm.plugin.commands.subtypes"); for(Class<? extends SWMCommand> l:reflection.getSubTypesOf(SWMCommand.class)) { try { SWMCommand command = l.newInstance(); cl.register(command); } catch (InstantiationException | IllegalAccessException ex) { ex.printStackTrace(); } } /* Load worlds */ List<String> erroredWorlds = loadWorlds(); try { Properties props = new Properties(); props.load(new FileInputStream("server.properties")); String defaultWorldName = props.getProperty("level-name"); if (erroredWorlds.contains(defaultWorldName)) { Logging.error("Shutting down server, as the default world could not be loaded."); System.exit(1); } else if (getServer().getAllowNether() && erroredWorlds.contains(defaultWorldName + "_nether")) { Logging.error("Shutting down server, as the default nether world could not be loaded."); System.exit(1); } else if (getServer().getAllowEnd() && erroredWorlds.contains(defaultWorldName + "_the_end")) { Logging.error("Shutting down server, as the default end world could not be loaded."); System.exit(1); } Map<String, SlimeWorld> loadedWorlds = getSlimeWorlds(); SlimeWorld defaultWorld = loadedWorlds.get(defaultWorldName); SlimeWorld netherWorld = getServer().getAllowNether() ? loadedWorlds.get(defaultWorldName + "_nether") : null; SlimeWorld endWorld = getServer().getAllowEnd() ? loadedWorlds.get(defaultWorldName + "_the_end") : null; nms.setDefaultWorlds(defaultWorld, netherWorld, endWorld); } catch (IOException ex) { Logging.error("Failed to retrieve default world name:"); ex.printStackTrace(); } } @Override public void onEnable() { if (nms == null) { this.setEnabled(false); return; } getServer().getPluginManager().registerEvents(new WorldUnlocker(), this); toGenerate.forEach(this::generateWorld); } @Override public void onDisable() { Bukkit.getWorlds().stream() .map(world -> getNms().getSlimeWorld(world)) .filter(Objects::nonNull) .forEach(world -> { world.unloadWorld(true); try { world.getLoader().unlockWorld(world.getName()); } catch (UnknownWorldException | IOException e) { throw new RuntimeException(e); } }); } private SlimeNMS getNMSBridge() throws InvalidVersionException { return new SlimeNMS(); } private List<String> loadWorlds() { List<String> erroredWorlds = new ArrayList<>(); WorldsConfig config = getConfigManager().getWorldConfig(); for (Map.Entry<String, WorldData> entry : config.getWorlds().entrySet()) { String worldName = entry.getKey(); WorldData worldData = entry.getValue(); if (worldData.isLoadOnStartup()) { try { SlimeLoader loader = getLoader(worldData.getDataSource()); if (loader == null) { throw new IllegalArgumentException("invalid data source " + worldData.getDataSource() + ""); }
SlimePropertyMap propertyMap = worldData.toPropertyMap();
7
2023-10-08 10:54:28+00:00
24k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/runner/MethodRunner.java
[ { "identifier": "PromptConstructor", "path": "src/main/java/zju/cst/aces/api/PromptConstructor.java", "snippet": "public interface PromptConstructor {\n\n List<Message> generate();\n\n}" }, { "identifier": "Repair", "path": "src/main/java/zju/cst/aces/api/Repair.java", "snippet": "pub...
import lombok.Data; import okhttp3.Response; import org.junit.platform.launcher.listeners.TestExecutionSummary; import zju.cst.aces.api.PromptConstructor; import zju.cst.aces.api.Repair; import zju.cst.aces.api.Validator; import zju.cst.aces.api.config.Config; import zju.cst.aces.api.impl.ChatGenerator; import zju.cst.aces.api.impl.PromptConstructorImpl; import zju.cst.aces.api.impl.RepairImpl; import zju.cst.aces.api.impl.obfuscator.Obfuscator; import zju.cst.aces.dto.*; import zju.cst.aces.util.CodeExtractor; import zju.cst.aces.util.TestProcessor; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.stream.Collectors;
14,534
package zju.cst.aces.runner; public class MethodRunner extends ClassRunner { public MethodInfo methodInfo; public MethodRunner(Config config, String fullClassName, MethodInfo methodInfo) throws IOException { super(config, fullClassName); this.methodInfo = methodInfo; } @Override public void start() throws IOException { if (!config.isStopWhenSuccess() && config.isEnableMultithreading()) { ExecutorService executor = Executors.newFixedThreadPool(config.getTestNumber()); List<Future<String>> futures = new ArrayList<>(); for (int num = 0; num < config.getTestNumber(); num++) { int finalNum = num; Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { startRounds(finalNum); return ""; } }; Future<String> future = executor.submit(callable); futures.add(future); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { executor.shutdownNow(); } }); for (Future<String> future : futures) { try { String result = future.get(); System.out.println(result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); } else { for (int num = 0; num < config.getTestNumber(); num++) { if (startRounds(num) && config.isStopWhenSuccess()) { break; } } } } public boolean startRounds(final int num) throws IOException { String testName = className + separator + methodInfo.methodName + separator + classInfo.methodSigs.get(methodInfo.methodSignature) + separator + num + separator + "Test"; String fullTestName = fullClassName + separator + methodInfo.methodName + separator + classInfo.methodSigs.get(methodInfo.methodSignature) + separator + num + separator + "Test"; config.getLog().info("\n==========================\n[ChatUniTest] Generating test for method < " + methodInfo.methodName + " > number " + num + "...\n"); ChatGenerator generator = new ChatGenerator(config); PromptConstructorImpl pc = new PromptConstructorImpl(config); RepairImpl repair = new RepairImpl(config, pc); if (methodInfo.dependentMethods.size() > 0) { pc.setPromptInfoWithDep(classInfo, methodInfo); } else { pc.setPromptInfoWithoutDep(classInfo, methodInfo); } pc.setFullTestName(fullTestName); pc.setTestName(testName); PromptInfo promptInfo = pc.getPromptInfo(); promptInfo.setFullTestName(fullTestName); Path savePath = config.getTestOutput().resolve(fullTestName.replace(".", File.separator) + ".java"); promptInfo.setTestPath(savePath); for (int rounds = 0; rounds < config.getMaxRounds(); rounds++) { if (rounds == 0) { config.getLog().info("Generating test for method < " + methodInfo.methodName + " > round " + rounds + " ..."); } else { config.getLog().info("Fixing test for method < " + methodInfo.methodName + " > round " + rounds + " ..."); } promptInfo.addRecord(new RoundRecord(rounds)); RoundRecord record = promptInfo.getRecords().get(rounds); record.setAttempt(num); if (generateTest(generator, pc, repair, record)) { exportRecord(promptInfo, classInfo, record.getAttempt()); return true; } } exportRecord(pc.getPromptInfo(), classInfo, num); return false; } public boolean generateTest(ChatGenerator generator, PromptConstructorImpl pc, RepairImpl repair, RoundRecord record) throws IOException { PromptInfo promptInfo = pc.getPromptInfo();
package zju.cst.aces.runner; public class MethodRunner extends ClassRunner { public MethodInfo methodInfo; public MethodRunner(Config config, String fullClassName, MethodInfo methodInfo) throws IOException { super(config, fullClassName); this.methodInfo = methodInfo; } @Override public void start() throws IOException { if (!config.isStopWhenSuccess() && config.isEnableMultithreading()) { ExecutorService executor = Executors.newFixedThreadPool(config.getTestNumber()); List<Future<String>> futures = new ArrayList<>(); for (int num = 0; num < config.getTestNumber(); num++) { int finalNum = num; Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { startRounds(finalNum); return ""; } }; Future<String> future = executor.submit(callable); futures.add(future); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { executor.shutdownNow(); } }); for (Future<String> future : futures) { try { String result = future.get(); System.out.println(result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); } else { for (int num = 0; num < config.getTestNumber(); num++) { if (startRounds(num) && config.isStopWhenSuccess()) { break; } } } } public boolean startRounds(final int num) throws IOException { String testName = className + separator + methodInfo.methodName + separator + classInfo.methodSigs.get(methodInfo.methodSignature) + separator + num + separator + "Test"; String fullTestName = fullClassName + separator + methodInfo.methodName + separator + classInfo.methodSigs.get(methodInfo.methodSignature) + separator + num + separator + "Test"; config.getLog().info("\n==========================\n[ChatUniTest] Generating test for method < " + methodInfo.methodName + " > number " + num + "...\n"); ChatGenerator generator = new ChatGenerator(config); PromptConstructorImpl pc = new PromptConstructorImpl(config); RepairImpl repair = new RepairImpl(config, pc); if (methodInfo.dependentMethods.size() > 0) { pc.setPromptInfoWithDep(classInfo, methodInfo); } else { pc.setPromptInfoWithoutDep(classInfo, methodInfo); } pc.setFullTestName(fullTestName); pc.setTestName(testName); PromptInfo promptInfo = pc.getPromptInfo(); promptInfo.setFullTestName(fullTestName); Path savePath = config.getTestOutput().resolve(fullTestName.replace(".", File.separator) + ".java"); promptInfo.setTestPath(savePath); for (int rounds = 0; rounds < config.getMaxRounds(); rounds++) { if (rounds == 0) { config.getLog().info("Generating test for method < " + methodInfo.methodName + " > round " + rounds + " ..."); } else { config.getLog().info("Fixing test for method < " + methodInfo.methodName + " > round " + rounds + " ..."); } promptInfo.addRecord(new RoundRecord(rounds)); RoundRecord record = promptInfo.getRecords().get(rounds); record.setAttempt(num); if (generateTest(generator, pc, repair, record)) { exportRecord(promptInfo, classInfo, record.getAttempt()); return true; } } exportRecord(pc.getPromptInfo(), classInfo, num); return false; } public boolean generateTest(ChatGenerator generator, PromptConstructorImpl pc, RepairImpl repair, RoundRecord record) throws IOException { PromptInfo promptInfo = pc.getPromptInfo();
Obfuscator obfuscator = new Obfuscator(config);
7
2023-10-14 07:15:10+00:00
24k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/web/WomClient.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import com.google.gson.Gson; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.GroupInfoWithMemberships; import net.wiseoldman.beans.NameChangeEntry; import net.wiseoldman.beans.ParticipantWithStanding; import net.wiseoldman.beans.WomStatus; import net.wiseoldman.beans.ParticipantWithCompetition; import net.wiseoldman.beans.GroupMemberAddition; import net.wiseoldman.beans.Member; import net.wiseoldman.beans.GroupMemberRemoval; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.WomPlayerUpdate; import net.wiseoldman.events.WomOngoingPlayerCompetitionsFetched; import net.wiseoldman.events.WomUpcomingPlayerCompetitionsFetched; import net.wiseoldman.ui.WomIconHandler; import net.wiseoldman.WomUtilsConfig; import net.wiseoldman.events.WomGroupMemberAdded; import net.wiseoldman.events.WomGroupMemberRemoved; import net.wiseoldman.events.WomGroupSynced; import java.awt.Color; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.MessageNode; import net.runelite.api.events.ChatMessage; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.eventbus.EventBus; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
15,963
{ return requestBuilder.put(body).build(); } else if (httpMethod == HttpMethod.DELETE) { return requestBuilder.delete(body).build(); } return requestBuilder.post(body).build(); } private Request createRequest(String... pathSegments) { HttpUrl url = buildUrl(pathSegments); return new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url) .build(); } private HttpUrl buildUrl(String[] pathSegments) { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme("https") .host("api.wiseoldman.net") .addPathSegment(this.plugin.isSeasonal ? "league" : "v2"); for (String pathSegment : pathSegments) { if (pathSegment.startsWith("?")) { // A query param String[] kv = pathSegment.substring(1).split("="); urlBuilder.addQueryParameter(kv[0], kv[1]); } else { urlBuilder.addPathSegment(pathSegment); } } return urlBuilder.build(); } public void importGroupMembers() { if (config.groupId() > 0) { Request request = createRequest("groups", "" + config.groupId()); sendRequest(request, this::importMembersCallback); } } private void importMembersCallback(Response response) { if (!response.isSuccessful()) { return; } GroupInfoWithMemberships groupInfo = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(groupInfo, true)); } private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) {
package net.wiseoldman.web; @Slf4j public class WomClient { @Inject private OkHttpClient okHttpClient; private Gson gson; @Inject private WomIconHandler iconHandler; @Inject private Client client; @Inject private WomUtilsConfig config; @Inject private ChatMessageManager chatMessageManager; @Inject private ClientThread clientThread; @Inject private EventBus eventBus; private static final Color SUCCESS = new Color(170, 255, 40); private static final Color ERROR = new Color(204, 66, 66); private static final DecimalFormat NUMBER_FORMAT = new DecimalFormat("#.##"); private final WomUtilsPlugin plugin; private final String leagueError = " You are currently in a League world. Your group configurations might be for the main game."; @Inject public WomClient(Gson gson, WomUtilsPlugin plugin) { this.gson = gson.newBuilder() .setDateFormat(DateFormat.FULL, DateFormat.FULL) .create(); this.plugin = plugin; } public void submitNameChanges(NameChangeEntry[] changes) { Request request = createRequest(changes, HttpMethod.POST, "names", "bulk"); sendRequest(request); log.info("Submitted {} name changes to WOM", changes.length); } void sendRequest(Request request) { sendRequest(request, r -> {}); } void sendRequest(Request request, Consumer<Response> consumer) { sendRequest(request, new WomCallback(consumer)); } void sendRequest(Request request, Consumer<Response> consumer, Consumer<Exception> exceptionConsumer) { sendRequest(request, new WomCallback(consumer, exceptionConsumer)); } void sendRequest(Request request, Callback callback) { okHttpClient.newCall(request).enqueue(callback); } private Request createRequest(Object payload, String... pathSegments) { return createRequest(payload, HttpMethod.POST, pathSegments); } private Request createRequest(Object payload, HttpMethod httpMethod, String... pathSegments) { HttpUrl url = buildUrl(pathSegments); RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), gson.toJson(payload) ); Request.Builder requestBuilder = new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url); if (httpMethod == HttpMethod.PUT) { return requestBuilder.put(body).build(); } else if (httpMethod == HttpMethod.DELETE) { return requestBuilder.delete(body).build(); } return requestBuilder.post(body).build(); } private Request createRequest(String... pathSegments) { HttpUrl url = buildUrl(pathSegments); return new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url) .build(); } private HttpUrl buildUrl(String[] pathSegments) { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme("https") .host("api.wiseoldman.net") .addPathSegment(this.plugin.isSeasonal ? "league" : "v2"); for (String pathSegment : pathSegments) { if (pathSegment.startsWith("?")) { // A query param String[] kv = pathSegment.substring(1).split("="); urlBuilder.addQueryParameter(kv[0], kv[1]); } else { urlBuilder.addPathSegment(pathSegment); } } return urlBuilder.build(); } public void importGroupMembers() { if (config.groupId() > 0) { Request request = createRequest("groups", "" + config.groupId()); sendRequest(request, this::importMembersCallback); } } private void importMembersCallback(Response response) { if (!response.isSuccessful()) { return; } GroupInfoWithMemberships groupInfo = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(groupInfo, true)); } private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) {
ParticipantWithStanding[] comps = parseResponse(response, ParticipantWithStanding[].class);
3
2023-10-09 14:23:06+00:00
24k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/renderer/Frustum.java
[ { "identifier": "AABB", "path": "src/main/java/com/mojang/minecraft/phys/AABB.java", "snippet": "public class AABB implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tprivate float epsilon = 0.0F;\n\tpublic float x0;\n\tpublic float y0;\n\tpublic float z0;\n\tpublic float x1;...
import com.mojang.minecraft.phys.AABB; import java.nio.FloatBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11;
16,688
package com.mojang.minecraft.renderer; public final class Frustum { private float[][] m_Frustum = new float[6][4]; private static Frustum frustum = new Frustum(); private FloatBuffer _proj = BufferUtils.createFloatBuffer(16); private FloatBuffer _modl = BufferUtils.createFloatBuffer(16); private FloatBuffer _clip = BufferUtils.createFloatBuffer(16); private float[] proj = new float[16]; private float[] modl = new float[16]; private float[] clip = new float[16]; public static Frustum getFrustum() { Frustum var0 = frustum; var0._proj.clear(); var0._modl.clear(); var0._clip.clear(); GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, var0._proj); GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, var0._modl); var0._proj.flip().limit(16); var0._proj.get(var0.proj); var0._modl.flip().limit(16); var0._modl.get(var0.modl); var0.clip[0] = var0.modl[0] * var0.proj[0] + var0.modl[1] * var0.proj[4] + var0.modl[2] * var0.proj[8] + var0.modl[3] * var0.proj[12]; var0.clip[1] = var0.modl[0] * var0.proj[1] + var0.modl[1] * var0.proj[5] + var0.modl[2] * var0.proj[9] + var0.modl[3] * var0.proj[13]; var0.clip[2] = var0.modl[0] * var0.proj[2] + var0.modl[1] * var0.proj[6] + var0.modl[2] * var0.proj[10] + var0.modl[3] * var0.proj[14]; var0.clip[3] = var0.modl[0] * var0.proj[3] + var0.modl[1] * var0.proj[7] + var0.modl[2] * var0.proj[11] + var0.modl[3] * var0.proj[15]; var0.clip[4] = var0.modl[4] * var0.proj[0] + var0.modl[5] * var0.proj[4] + var0.modl[6] * var0.proj[8] + var0.modl[7] * var0.proj[12]; var0.clip[5] = var0.modl[4] * var0.proj[1] + var0.modl[5] * var0.proj[5] + var0.modl[6] * var0.proj[9] + var0.modl[7] * var0.proj[13]; var0.clip[6] = var0.modl[4] * var0.proj[2] + var0.modl[5] * var0.proj[6] + var0.modl[6] * var0.proj[10] + var0.modl[7] * var0.proj[14]; var0.clip[7] = var0.modl[4] * var0.proj[3] + var0.modl[5] * var0.proj[7] + var0.modl[6] * var0.proj[11] + var0.modl[7] * var0.proj[15]; var0.clip[8] = var0.modl[8] * var0.proj[0] + var0.modl[9] * var0.proj[4] + var0.modl[10] * var0.proj[8] + var0.modl[11] * var0.proj[12]; var0.clip[9] = var0.modl[8] * var0.proj[1] + var0.modl[9] * var0.proj[5] + var0.modl[10] * var0.proj[9] + var0.modl[11] * var0.proj[13]; var0.clip[10] = var0.modl[8] * var0.proj[2] + var0.modl[9] * var0.proj[6] + var0.modl[10] * var0.proj[10] + var0.modl[11] * var0.proj[14]; var0.clip[11] = var0.modl[8] * var0.proj[3] + var0.modl[9] * var0.proj[7] + var0.modl[10] * var0.proj[11] + var0.modl[11] * var0.proj[15]; var0.clip[12] = var0.modl[12] * var0.proj[0] + var0.modl[13] * var0.proj[4] + var0.modl[14] * var0.proj[8] + var0.modl[15] * var0.proj[12]; var0.clip[13] = var0.modl[12] * var0.proj[1] + var0.modl[13] * var0.proj[5] + var0.modl[14] * var0.proj[9] + var0.modl[15] * var0.proj[13]; var0.clip[14] = var0.modl[12] * var0.proj[2] + var0.modl[13] * var0.proj[6] + var0.modl[14] * var0.proj[10] + var0.modl[15] * var0.proj[14]; var0.clip[15] = var0.modl[12] * var0.proj[3] + var0.modl[13] * var0.proj[7] + var0.modl[14] * var0.proj[11] + var0.modl[15] * var0.proj[15]; var0.m_Frustum[0][0] = var0.clip[3] - var0.clip[0]; var0.m_Frustum[0][1] = var0.clip[7] - var0.clip[4]; var0.m_Frustum[0][2] = var0.clip[11] - var0.clip[8]; var0.m_Frustum[0][3] = var0.clip[15] - var0.clip[12]; normalizePlane(var0.m_Frustum, 0); var0.m_Frustum[1][0] = var0.clip[3] + var0.clip[0]; var0.m_Frustum[1][1] = var0.clip[7] + var0.clip[4]; var0.m_Frustum[1][2] = var0.clip[11] + var0.clip[8]; var0.m_Frustum[1][3] = var0.clip[15] + var0.clip[12]; normalizePlane(var0.m_Frustum, 1); var0.m_Frustum[2][0] = var0.clip[3] + var0.clip[1]; var0.m_Frustum[2][1] = var0.clip[7] + var0.clip[5]; var0.m_Frustum[2][2] = var0.clip[11] + var0.clip[9]; var0.m_Frustum[2][3] = var0.clip[15] + var0.clip[13]; normalizePlane(var0.m_Frustum, 2); var0.m_Frustum[3][0] = var0.clip[3] - var0.clip[1]; var0.m_Frustum[3][1] = var0.clip[7] - var0.clip[5]; var0.m_Frustum[3][2] = var0.clip[11] - var0.clip[9]; var0.m_Frustum[3][3] = var0.clip[15] - var0.clip[13]; normalizePlane(var0.m_Frustum, 3); var0.m_Frustum[4][0] = var0.clip[3] - var0.clip[2]; var0.m_Frustum[4][1] = var0.clip[7] - var0.clip[6]; var0.m_Frustum[4][2] = var0.clip[11] - var0.clip[10]; var0.m_Frustum[4][3] = var0.clip[15] - var0.clip[14]; normalizePlane(var0.m_Frustum, 4); var0.m_Frustum[5][0] = var0.clip[3] + var0.clip[2]; var0.m_Frustum[5][1] = var0.clip[7] + var0.clip[6]; var0.m_Frustum[5][2] = var0.clip[11] + var0.clip[10]; var0.m_Frustum[5][3] = var0.clip[15] + var0.clip[14]; normalizePlane(var0.m_Frustum, 5); return frustum; } private static void normalizePlane(float[][] var0, int var1) { float var2 = (float)Math.sqrt((double)(var0[var1][0] * var0[var1][0] + var0[var1][1] * var0[var1][1] + var0[var1][2] * var0[var1][2])); var0[var1][0] /= var2; var0[var1][1] /= var2; var0[var1][2] /= var2; var0[var1][3] /= var2; } public final boolean cubeInFrustum(float var1, float var2, float var3, float var4, float var5, float var6) { for(int var7 = 0; var7 < 6; ++var7) { if(this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F) { return false; } } return true; }
package com.mojang.minecraft.renderer; public final class Frustum { private float[][] m_Frustum = new float[6][4]; private static Frustum frustum = new Frustum(); private FloatBuffer _proj = BufferUtils.createFloatBuffer(16); private FloatBuffer _modl = BufferUtils.createFloatBuffer(16); private FloatBuffer _clip = BufferUtils.createFloatBuffer(16); private float[] proj = new float[16]; private float[] modl = new float[16]; private float[] clip = new float[16]; public static Frustum getFrustum() { Frustum var0 = frustum; var0._proj.clear(); var0._modl.clear(); var0._clip.clear(); GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, var0._proj); GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, var0._modl); var0._proj.flip().limit(16); var0._proj.get(var0.proj); var0._modl.flip().limit(16); var0._modl.get(var0.modl); var0.clip[0] = var0.modl[0] * var0.proj[0] + var0.modl[1] * var0.proj[4] + var0.modl[2] * var0.proj[8] + var0.modl[3] * var0.proj[12]; var0.clip[1] = var0.modl[0] * var0.proj[1] + var0.modl[1] * var0.proj[5] + var0.modl[2] * var0.proj[9] + var0.modl[3] * var0.proj[13]; var0.clip[2] = var0.modl[0] * var0.proj[2] + var0.modl[1] * var0.proj[6] + var0.modl[2] * var0.proj[10] + var0.modl[3] * var0.proj[14]; var0.clip[3] = var0.modl[0] * var0.proj[3] + var0.modl[1] * var0.proj[7] + var0.modl[2] * var0.proj[11] + var0.modl[3] * var0.proj[15]; var0.clip[4] = var0.modl[4] * var0.proj[0] + var0.modl[5] * var0.proj[4] + var0.modl[6] * var0.proj[8] + var0.modl[7] * var0.proj[12]; var0.clip[5] = var0.modl[4] * var0.proj[1] + var0.modl[5] * var0.proj[5] + var0.modl[6] * var0.proj[9] + var0.modl[7] * var0.proj[13]; var0.clip[6] = var0.modl[4] * var0.proj[2] + var0.modl[5] * var0.proj[6] + var0.modl[6] * var0.proj[10] + var0.modl[7] * var0.proj[14]; var0.clip[7] = var0.modl[4] * var0.proj[3] + var0.modl[5] * var0.proj[7] + var0.modl[6] * var0.proj[11] + var0.modl[7] * var0.proj[15]; var0.clip[8] = var0.modl[8] * var0.proj[0] + var0.modl[9] * var0.proj[4] + var0.modl[10] * var0.proj[8] + var0.modl[11] * var0.proj[12]; var0.clip[9] = var0.modl[8] * var0.proj[1] + var0.modl[9] * var0.proj[5] + var0.modl[10] * var0.proj[9] + var0.modl[11] * var0.proj[13]; var0.clip[10] = var0.modl[8] * var0.proj[2] + var0.modl[9] * var0.proj[6] + var0.modl[10] * var0.proj[10] + var0.modl[11] * var0.proj[14]; var0.clip[11] = var0.modl[8] * var0.proj[3] + var0.modl[9] * var0.proj[7] + var0.modl[10] * var0.proj[11] + var0.modl[11] * var0.proj[15]; var0.clip[12] = var0.modl[12] * var0.proj[0] + var0.modl[13] * var0.proj[4] + var0.modl[14] * var0.proj[8] + var0.modl[15] * var0.proj[12]; var0.clip[13] = var0.modl[12] * var0.proj[1] + var0.modl[13] * var0.proj[5] + var0.modl[14] * var0.proj[9] + var0.modl[15] * var0.proj[13]; var0.clip[14] = var0.modl[12] * var0.proj[2] + var0.modl[13] * var0.proj[6] + var0.modl[14] * var0.proj[10] + var0.modl[15] * var0.proj[14]; var0.clip[15] = var0.modl[12] * var0.proj[3] + var0.modl[13] * var0.proj[7] + var0.modl[14] * var0.proj[11] + var0.modl[15] * var0.proj[15]; var0.m_Frustum[0][0] = var0.clip[3] - var0.clip[0]; var0.m_Frustum[0][1] = var0.clip[7] - var0.clip[4]; var0.m_Frustum[0][2] = var0.clip[11] - var0.clip[8]; var0.m_Frustum[0][3] = var0.clip[15] - var0.clip[12]; normalizePlane(var0.m_Frustum, 0); var0.m_Frustum[1][0] = var0.clip[3] + var0.clip[0]; var0.m_Frustum[1][1] = var0.clip[7] + var0.clip[4]; var0.m_Frustum[1][2] = var0.clip[11] + var0.clip[8]; var0.m_Frustum[1][3] = var0.clip[15] + var0.clip[12]; normalizePlane(var0.m_Frustum, 1); var0.m_Frustum[2][0] = var0.clip[3] + var0.clip[1]; var0.m_Frustum[2][1] = var0.clip[7] + var0.clip[5]; var0.m_Frustum[2][2] = var0.clip[11] + var0.clip[9]; var0.m_Frustum[2][3] = var0.clip[15] + var0.clip[13]; normalizePlane(var0.m_Frustum, 2); var0.m_Frustum[3][0] = var0.clip[3] - var0.clip[1]; var0.m_Frustum[3][1] = var0.clip[7] - var0.clip[5]; var0.m_Frustum[3][2] = var0.clip[11] - var0.clip[9]; var0.m_Frustum[3][3] = var0.clip[15] - var0.clip[13]; normalizePlane(var0.m_Frustum, 3); var0.m_Frustum[4][0] = var0.clip[3] - var0.clip[2]; var0.m_Frustum[4][1] = var0.clip[7] - var0.clip[6]; var0.m_Frustum[4][2] = var0.clip[11] - var0.clip[10]; var0.m_Frustum[4][3] = var0.clip[15] - var0.clip[14]; normalizePlane(var0.m_Frustum, 4); var0.m_Frustum[5][0] = var0.clip[3] + var0.clip[2]; var0.m_Frustum[5][1] = var0.clip[7] + var0.clip[6]; var0.m_Frustum[5][2] = var0.clip[11] + var0.clip[10]; var0.m_Frustum[5][3] = var0.clip[15] + var0.clip[14]; normalizePlane(var0.m_Frustum, 5); return frustum; } private static void normalizePlane(float[][] var0, int var1) { float var2 = (float)Math.sqrt((double)(var0[var1][0] * var0[var1][0] + var0[var1][1] * var0[var1][1] + var0[var1][2] * var0[var1][2])); var0[var1][0] /= var2; var0[var1][1] /= var2; var0[var1][2] /= var2; var0[var1][3] /= var2; } public final boolean cubeInFrustum(float var1, float var2, float var3, float var4, float var5, float var6) { for(int var7 = 0; var7 < 6; ++var7) { if(this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var3 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var2 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var1 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F && this.m_Frustum[var7][0] * var4 + this.m_Frustum[var7][1] * var5 + this.m_Frustum[var7][2] * var6 + this.m_Frustum[var7][3] <= 0.0F) { return false; } } return true; }
public final boolean isVisible(AABB var1) {
0
2023-10-10 17:10:45+00:00
24k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/singleelement/cube/Auto_Statebarrier_1cone1cube_red_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.bling.SubSys_Bling; import frc.robot.chargedup.subsystems.bling.SubSys_Bling_Constants; import frc.robot.chargedup.subsystems.bling.commands.Cmd_SubSys_Bling_SetColorValue; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
15,483
// 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.chargedup.commands.auto.singleelement.cube; // For information see slides linked below // Link For PathPlaner // https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_0 public class Auto_Statebarrier_1cone1cube_red_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand;
// 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.chargedup.commands.auto.singleelement.cube; // For information see slides linked below // Link For PathPlaner // https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_0 public class Auto_Statebarrier_1cone1cube_red_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand;
private final SubSys_Bling blingSubSys;
3
2023-10-09 00:27:11+00:00
24k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/handler/LogRecordsHandler.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import com.monitor.agent.server.FileState; import com.monitor.agent.server.FileWatcher; import com.monitor.agent.server.Registrar; import com.monitor.agent.server.Section; import com.monitor.agent.server.Server; import com.monitor.agent.server.filter.Filter; import com.monitor.agent.server.piped.ParserPipedOutputStream; import com.monitor.agent.server.piped.ParserPipedStream; import com.monitor.parser.ParserParameters; import com.monitor.parser.reader.ParserFileReader; import com.monitor.parser.reader.ParserListStorage; import com.monitor.parser.reader.ParserRecordsStorage; import com.monitor.parser.reader.ParserStreamStorage; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD.Response; import fi.iki.elonen.router.RouterNanoHTTPD; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map;
15,926
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public class LogRecordsHandler extends DefaultResponder { private static final int PARSE_EXEC_TIMEOUT = 10 * 60 * 1000; // 10 минут @Override @SuppressWarnings({"Convert2Lambda", "UseSpecificCatch"}) public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы ParserPipedStream pipe; try { pipe = new ParserPipedStream(PARSE_EXEC_TIMEOUT); (new Thread() { @Override @SuppressWarnings("UseSpecificCatch") public void run() { ParserFileReader reader = null; ParserPipedOutputStream output = pipe.getOutput(); try { ParserRecordsStorage storage = new ParserStreamStorage(output); RequestParameters parameters = getParameters(); // получаем признак "чернового" чтения - данные читаются с самого начала, // позиция завершения чтения не запоминается // boolean draft = !"false".equalsIgnoreCase((String) parameters.get("draft", "false")); // получаем максимальное количество записей лога, которые нужно // вернуть клиенту; если не указано - берём из глобальных настроек // int maxRecords = Integer.parseInt((String) parameters.get("max", String.valueOf(server.getSpoolSize()))); // получаем глобальный фильтр значений записей лог-файлов; он будет // комбинироваться с фильтрами, указанными в конфигурационном файле // сервера // Filter filter = null; Object filterValue = parameters.get("filter", null); if (filterValue != null) { if (filterValue instanceof String) { filter = Filter.fromJson((String) filterValue); } else if (Map.class.isAssignableFrom(filterValue.getClass())) { filter = Filter.fromMap((Map<String, Object>) filterValue); } } // получаем признак чтения полных данных по блокировкам для лог-файлов // технологического журнала: если не нужны подробные данные по блокировкам, // то можно сократить объём передаваемых клиенту данных // String strExcludes = (String) parameters.get("exclude-data", ""); HashSet<String> excludes = new HashSet<>(); excludes.addAll(Arrays.asList(strExcludes.replaceAll(" ", "").split(","))); // получаем максимальную длину токена, которую агент будет возвращать клиенту; // в случае, если в файле токен (значение параметра) будет более указанной длины // в символах, то вернётся значение в виде "значение-параметра-(... ещё N симв.)"; // используем значение 0 для указания того, что ограничений на длину нет // int maxTokenLen = Integer.parseInt((String) parameters.get("max-token-length", "-1")); maxTokenLen = (maxTokenLen == -1) ? 1024 * 32 : maxTokenLen; // получаем задержку времени, которую можно использовать для уменьшения нагрузки // на процессор при разборе файлов лога - чем больше задержка, тем меньше нагрузка, // но и скорость разбора увеличивается; задержка = 0 - то же самое, что без задержки, // задержка более 5мс опасна - производительность резко падает // int delay = Integer.parseInt((String) parameters.get("delay", "0")); // создаём структуру с дополнительными данными, которую можно // передать парсеру // ParserParameters parserParams = new ParserParameters(); parserParams.setExcludeData(excludes); parserParams.setMaxTokenLength(maxTokenLen); parserParams.setDelay(delay); // получаем секцию, в пределах которой нужно получать данные из лог-файлов // String sectionName = (String) parameters.get("section", (String) null); Section section = Section.byName(sectionName); // агент блокирует параллельный доступ к одной и той же секции данных из разных запросов; // если требуется установить глобальный запрет на параллельную обработку даже разных // секций, то используется параметр "global-lock" // boolean globalLock = !"false".equalsIgnoreCase((String) parameters.get("global-lock", "false")); Object sectionLock = (section == null || globalLock) ? server : section; synchronized (sectionLock) { Collection<FileWatcher> watchers = server.getWatchers(section); // подтверждаем факт успешного приёма предыдущей порции данных: // переустанавливаем указатели файлов в рабочее положение // if (!"false".equalsIgnoreCase((String) parameters.get("ack", "false"))) { for (FileWatcher watcher : watchers) { synchronized (watcher) { Collection<FileState> states = watcher.getWatched(); for (FileState state : states) { state.setPointer(state.getNewPointer()); }
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public class LogRecordsHandler extends DefaultResponder { private static final int PARSE_EXEC_TIMEOUT = 10 * 60 * 1000; // 10 минут @Override @SuppressWarnings({"Convert2Lambda", "UseSpecificCatch"}) public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы ParserPipedStream pipe; try { pipe = new ParserPipedStream(PARSE_EXEC_TIMEOUT); (new Thread() { @Override @SuppressWarnings("UseSpecificCatch") public void run() { ParserFileReader reader = null; ParserPipedOutputStream output = pipe.getOutput(); try { ParserRecordsStorage storage = new ParserStreamStorage(output); RequestParameters parameters = getParameters(); // получаем признак "чернового" чтения - данные читаются с самого начала, // позиция завершения чтения не запоминается // boolean draft = !"false".equalsIgnoreCase((String) parameters.get("draft", "false")); // получаем максимальное количество записей лога, которые нужно // вернуть клиенту; если не указано - берём из глобальных настроек // int maxRecords = Integer.parseInt((String) parameters.get("max", String.valueOf(server.getSpoolSize()))); // получаем глобальный фильтр значений записей лог-файлов; он будет // комбинироваться с фильтрами, указанными в конфигурационном файле // сервера // Filter filter = null; Object filterValue = parameters.get("filter", null); if (filterValue != null) { if (filterValue instanceof String) { filter = Filter.fromJson((String) filterValue); } else if (Map.class.isAssignableFrom(filterValue.getClass())) { filter = Filter.fromMap((Map<String, Object>) filterValue); } } // получаем признак чтения полных данных по блокировкам для лог-файлов // технологического журнала: если не нужны подробные данные по блокировкам, // то можно сократить объём передаваемых клиенту данных // String strExcludes = (String) parameters.get("exclude-data", ""); HashSet<String> excludes = new HashSet<>(); excludes.addAll(Arrays.asList(strExcludes.replaceAll(" ", "").split(","))); // получаем максимальную длину токена, которую агент будет возвращать клиенту; // в случае, если в файле токен (значение параметра) будет более указанной длины // в символах, то вернётся значение в виде "значение-параметра-(... ещё N симв.)"; // используем значение 0 для указания того, что ограничений на длину нет // int maxTokenLen = Integer.parseInt((String) parameters.get("max-token-length", "-1")); maxTokenLen = (maxTokenLen == -1) ? 1024 * 32 : maxTokenLen; // получаем задержку времени, которую можно использовать для уменьшения нагрузки // на процессор при разборе файлов лога - чем больше задержка, тем меньше нагрузка, // но и скорость разбора увеличивается; задержка = 0 - то же самое, что без задержки, // задержка более 5мс опасна - производительность резко падает // int delay = Integer.parseInt((String) parameters.get("delay", "0")); // создаём структуру с дополнительными данными, которую можно // передать парсеру // ParserParameters parserParams = new ParserParameters(); parserParams.setExcludeData(excludes); parserParams.setMaxTokenLength(maxTokenLen); parserParams.setDelay(delay); // получаем секцию, в пределах которой нужно получать данные из лог-файлов // String sectionName = (String) parameters.get("section", (String) null); Section section = Section.byName(sectionName); // агент блокирует параллельный доступ к одной и той же секции данных из разных запросов; // если требуется установить глобальный запрет на параллельную обработку даже разных // секций, то используется параметр "global-lock" // boolean globalLock = !"false".equalsIgnoreCase((String) parameters.get("global-lock", "false")); Object sectionLock = (section == null || globalLock) ? server : section; synchronized (sectionLock) { Collection<FileWatcher> watchers = server.getWatchers(section); // подтверждаем факт успешного приёма предыдущей порции данных: // переустанавливаем указатели файлов в рабочее положение // if (!"false".equalsIgnoreCase((String) parameters.get("ack", "false"))) { for (FileWatcher watcher : watchers) { synchronized (watcher) { Collection<FileState> states = watcher.getWatched(); for (FileState state : states) { state.setPointer(state.getNewPointer()); }
Registrar.writeStateToJson(watcher.getSincedbFile(), states);
2
2023-10-11 20:25:12+00:00
24k
giteecode/bookmanage2-public
nhXJH-system/src/main/java/com/nhXJH/system/service/impl/SysRoleServiceImpl.java
[ { "identifier": "UserConstants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/UserConstants.java", "snippet": "public class UserConstants {\n /**\n * 平台内系统用户的唯一标志\n */\n public static final String SYS_USER = \"SYS_USER\";\n\n /** 正常状态 */\n public static final String ...
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nhXJH.common.annotation.DataScope; import com.nhXJH.common.constant.UserConstants; import com.nhXJH.common.core.domain.entity.SysRole; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.exception.ServiceException; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.spring.SpringUtils; import com.nhXJH.system.domain.SysRoleDept; import com.nhXJH.system.domain.SysRoleMenu; import com.nhXJH.system.domain.SysUserRole; import com.nhXJH.system.mapper.SysRoleDeptMapper; import com.nhXJH.system.mapper.SysRoleMapper; import com.nhXJH.system.mapper.SysRoleMenuMapper; import com.nhXJH.system.mapper.SysUserRoleMapper; import com.nhXJH.system.service.ISysRoleService;
14,472
package com.nhXJH.system.service.impl; /** * 角色 业务层处理 * * @author nhXJH */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d") public List<SysRole> selectRoleList(SysRole role) { return roleMapper.selectRoleList(role); } /** * 根据用户ID查询角色 * * @param userId 用户ID * @return 角色列表 */ @Override public List<SysRole> selectRolesByUserId(Long userId) { List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId); List<SysRole> roles = selectRoleAll(); for (SysRole role : roles) { for (SysRole userRole : userRoles) { if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { role.setFlag(true); break; } } } return roles; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectRolePermissionByUserId(Long userId) { List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId); Set<String> permsSet = new HashSet<>(); for (SysRole perm : perms) { if (StringUtils.isNotNull(perm)) { permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); } } return permsSet; } /** * 查询所有角色 * * @return 角色列表 */ @Override public List<SysRole> selectRoleAll() { return SpringUtils.getAopProxy(this).selectRoleList(new SysRole()); } /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ @Override public List<Long> selectRoleListByUserId(Long userId) { return roleMapper.selectRoleListByUserId(userId); } /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ @Override public SysRole selectRoleById(Long roleId) { return roleMapper.selectRoleById(roleId); } /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ @Override public String checkRoleNameUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
package com.nhXJH.system.service.impl; /** * 角色 业务层处理 * * @author nhXJH */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d") public List<SysRole> selectRoleList(SysRole role) { return roleMapper.selectRoleList(role); } /** * 根据用户ID查询角色 * * @param userId 用户ID * @return 角色列表 */ @Override public List<SysRole> selectRolesByUserId(Long userId) { List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId); List<SysRole> roles = selectRoleAll(); for (SysRole role : roles) { for (SysRole userRole : userRoles) { if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { role.setFlag(true); break; } } } return roles; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectRolePermissionByUserId(Long userId) { List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId); Set<String> permsSet = new HashSet<>(); for (SysRole perm : perms) { if (StringUtils.isNotNull(perm)) { permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); } } return permsSet; } /** * 查询所有角色 * * @return 角色列表 */ @Override public List<SysRole> selectRoleAll() { return SpringUtils.getAopProxy(this).selectRoleList(new SysRole()); } /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ @Override public List<Long> selectRoleListByUserId(Long userId) { return roleMapper.selectRoleListByUserId(userId); } /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ @Override public SysRole selectRoleById(Long roleId) { return roleMapper.selectRoleById(roleId); } /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ @Override public String checkRoleNameUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return UserConstants.NOT_UNIQUE;
0
2023-10-13 07:19:20+00:00
24k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/client/models/doors/PoliceBoxCoralDoorModel.java
[ { "identifier": "DoorAnimations", "path": "src/main/java/mdteam/ait/client/animation/exterior/door/DoorAnimations.java", "snippet": "public class DoorAnimations {\n\n //THIS IS FOR THE EXTERIOR\n public static final Animation EXTERIOR_FIRST_OPEN_ANIMATION = Animation.Builder.create(0.875f)\n ...
import mdteam.ait.client.animation.exterior.door.DoorAnimations; import mdteam.ait.core.blockentities.DoorBlockEntity; import mdteam.ait.tardis.handler.DoorHandler; import net.minecraft.client.model.*; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.entity.animation.Animation; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.util.math.RotationAxis;
16,048
package mdteam.ait.client.models.doors; public class PoliceBoxCoralDoorModel extends DoorModel { private final ModelPart TARDIS; public PoliceBoxCoralDoorModel(ModelPart root) { super(RenderLayer::getEntityCutoutNoCull); this.TARDIS = root.getChild("TARDIS"); } public static TexturedModelData getTexturedModelData() { ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); ModelPartData TARDIS = modelPartData.addChild("TARDIS", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 28.0F, 0.0F)); ModelPartData Posts = TARDIS.addChild("Posts", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData cube_r1 = Posts.addChild("cube_r1", ModelPartBuilder.create().uv(236, 42).cuboid(-18.0F, -60.0F, -17.0F, 4.0F, 56.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, -32.0F, 0.0F, 1.5708F, 0.0F)); ModelPartData cube_r2 = Posts.addChild("cube_r2", ModelPartBuilder.create().uv(236, 102).cuboid(-2.0F, -30.0F, 17.0F, 3.0F, 30.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -34.5F, -18.0F, -1.5708F, 1.4835F, -1.5708F)); ModelPartData cube_r3 = Posts.addChild("cube_r3", ModelPartBuilder.create().uv(236, 127).cuboid(-2.0F, 0.0F, 17.0F, 3.0F, 31.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -34.6743F, -18.0F, 1.5708F, 1.4835F, 1.5708F)); ModelPartData cube_r4 = Posts.addChild("cube_r4", ModelPartBuilder.create().uv(251, 127).cuboid(-2.0F, 0.0F, 17.0F, 3.0F, 31.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(-38.0F, -34.6743F, -18.0F, 1.5708F, 1.4835F, 1.5708F)); ModelPartData cube_r5 = Posts.addChild("cube_r5", ModelPartBuilder.create().uv(251, 102).cuboid(-2.0F, -30.0F, 17.0F, 3.0F, 30.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(-38.0F, -34.5F, -18.0F, -1.5708F, 1.4835F, -1.5708F)); ModelPartData cube_r6 = Posts.addChild("cube_r6", ModelPartBuilder.create().uv(251, 41).cuboid(-17.0F, -60.0F, -18.0F, 3.0F, 56.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, -32.0F, -3.1416F, 0.0F, 3.1416F)); ModelPartData Doors = TARDIS.addChild("Doors", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData right_door = Doors.addChild("right_door", ModelPartBuilder.create().uv(181, 177).cuboid(0.5F, -29.5F, -0.5F, 13.0F, 55.0F, 1.0F, new Dilation(0.0F)) .uv(0, 198).cuboid(0.5F, -29.5F, -1.0F, 14.0F, 55.0F, 0.0F, new Dilation(0.0F)) .uv(0, 10).cuboid(9.5F, -9.5F, -1.5F, 1.0F, 2.0F, 1.0F, new Dilation(0.0F)) .uv(5, 51).cuboid(2.5F, -9.5F, -1.5F, 1.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(-13.5F, -29.5F, -15.5F)); ModelPartData phone = right_door.addChild("phone", ModelPartBuilder.create().uv(268, 37).cuboid(-3.75F, -40.0F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(268, 37).cuboid(-3.75F, -39.8F, -13.5F, 2.0F, 0.0F, 2.0F, new Dilation(0.0F)) .uv(268, 43).cuboid(-3.75F, -37.75F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.5F)) .uv(265, 25).cuboid(-8.5F, -40.0F, -13.5F, 5.0F, 6.0F, 2.0F, new Dilation(0.0F)) .uv(268, 34).cuboid(-7.0F, -39.5F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)) .uv(259, 35).cuboid(-5.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)) .uv(259, 35).cuboid(-8.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)) .uv(250, 35).cuboid(-5.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.2F)) .uv(250, 35).cuboid(-8.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.2F)) .uv(250, 25).cuboid(-9.0F, -41.5F, -14.5F, 6.0F, 8.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(12.5F, 28.5F, 14.5F)); ModelPartData phone_t = right_door.addChild("phone_t", ModelPartBuilder.create().uv(266, 74).cuboid(-9.25F, -40.0F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(266, 74).cuboid(-9.25F, -39.8F, -13.5F, 2.0F, 0.0F, 2.0F, new Dilation(0.0F)) .uv(266, 80).cuboid(-9.0F, -37.75F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.5F)) .uv(266, 60).cuboid(-7.5F, -41.0F, -14.5F, 3.0F, 7.0F, 3.0F, new Dilation(0.0F)) .uv(266, 71).cuboid(-7.0F, -40.0F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)) .uv(266, 71).cuboid(-7.0F, -37.0F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)), ModelTransform.pivot(13.25F, 28.5F, 14.5F)); ModelPartData left_door = Doors.addChild("left_door", ModelPartBuilder.create().uv(189, 41).cuboid(-13.5F, -29.5F, -0.5F, 13.0F, 55.0F, 1.0F, new Dilation(0.0F)) .uv(0, 0).cuboid(-12.5F, -10.5F, -1.5F, 1.0F, 4.0F, 1.0F, new Dilation(0.0F)) .uv(0, 51).cuboid(-12.5F, -4.5F, -1.5F, 1.0F, 4.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(13.5F, -29.5F, -15.5F)); ModelPartData Walls = TARDIS.addChild("Walls", ModelPartBuilder.create().uv(63, 227).cuboid(-14.0F, -60.0F, -16.0F, 1.0F, 56.0F, 1.0F, new Dilation(0.0F)) .uv(116, 170).cuboid(13.0F, -60.0F, -16.0F, 1.0F, 56.0F, 1.0F, new Dilation(0.0F)) .uv(115, 0).cuboid(-13.0F, -60.0F, -16.0F, 26.0F, 1.0F, 1.0F, new Dilation(0.0F)) .uv(59, 113).cuboid(13.0F, -60.0F, -16.5F, 1.0F, 56.0F, 0.0F, new Dilation(0.0F)) .uv(115, 3).cuboid(-13.0F, -60.0F, -16.5F, 26.0F, 1.0F, 0.0F, new Dilation(0.0F)) .uv(62, 113).cuboid(-14.0F, -60.0F, -16.5F, 1.0F, 56.0F, 0.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData PCB = TARDIS.addChild("PCB", ModelPartBuilder.create().uv(241, 2).cuboid(-17.0F, -64.0F, -19.0F, 34.0F, 5.0F, 6.0F, new Dilation(0.0F)) .uv(243, 3).cuboid(-16.0F, -60.0F, -17.0F, 32.0F, 0.0F, 4.0F, new Dilation(0.0F)) .uv(241, 14).cuboid(-16.0F, -63.0F, -17.0F, 32.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(241, 18).cuboid(-1.0F, -63.0F, -14.0F, 2.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(243, 5).cuboid(16.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(277, 5).cuboid(-16.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(243, 3).cuboid(-16.0F, -63.0F, -17.0F, 32.0F, 0.0F, 4.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -1.0F, 0.0F)); ModelPartData lights = PCB.addChild("lights", ModelPartBuilder.create().uv(241, 28).cuboid(10.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(10.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 22).cuboid(4.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(4.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-6.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-6.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-12.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-12.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); ModelPartData TARDIS_t = TARDIS.addChild("TARDIS_t", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData PCB_t = TARDIS_t.addChild("PCB_t", ModelPartBuilder.create().uv(0, 434).cuboid(-17.0F, -64.0F, -19.0F, 34.0F, 5.0F, 6.0F, new Dilation(0.0F)) .uv(8, 435).cuboid(-11.0F, -60.0F, -17.0F, 22.0F, 0.0F, 4.0F, new Dilation(0.0F)) .uv(0, 446).cuboid(-11.0F, -63.0F, -17.0F, 22.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(0, 450).cuboid(-1.0F, -63.0F, -14.0F, 2.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(0, 437).cuboid(11.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(38, 437).cuboid(-11.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(21, 435).cuboid(-11.0F, -63.0F, -17.0F, 22.0F, 0.0F, 4.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -1.0F, 0.0F)); ModelPartData lights2 = PCB_t.addChild("lights2", ModelPartBuilder.create().uv(241, 28).cuboid(10.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(10.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 22).cuboid(4.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(4.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-6.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-6.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-12.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-12.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); ModelPartData lights_t2 = PCB_t.addChild("lights_t2", ModelPartBuilder.create().uv(267, 55).cuboid(7.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(7.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 49).cuboid(1.75F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(1.75F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(-3.75F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(-3.75F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(-9.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(-9.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); return TexturedModelData.of(modelData, 512, 512); } @Override public void render(MatrixStack matrices, VertexConsumer vertexConsumer, int light, int overlay, float red, float green, float blue, float alpha) { TARDIS.render(matrices, vertexConsumer, light, overlay, red, green, blue, alpha); } @Override public void renderWithAnimations(DoorBlockEntity doorEntity, ModelPart root, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float pAlpha) { /*this.TARDIS.getChild("Doors").getChild("right_door").yaw = -doorEntity.getRightDoorRotation(); this.TARDIS.getChild("Doors").getChild("left_door").yaw = doorEntity.getLeftDoorRotation();*/ DoorHandler door = doorEntity.getTardis().getDoor(); this.TARDIS.getChild("Doors").getChild("left_door").yaw = (door.isLeftOpen() || door.isOpen()) ? -5F : 0.0F; this.TARDIS.getChild("Doors").getChild("right_door").yaw = (door.isRightOpen() || door.isBothOpen()) ? 5F : 0.0F; matrices.push(); matrices.scale(0.631F, 0.631F, 0.631F); matrices.translate(0, -1.5f, -0.35); matrices.multiply(RotationAxis.NEGATIVE_Y.rotationDegrees(180)); super.renderWithAnimations(doorEntity, root, matrices, vertices, light, overlay, red, green, blue, pAlpha); matrices.pop(); } @Override public Animation getAnimationForDoorState(DoorHandler.DoorStateEnum state) { return switch (state) {
package mdteam.ait.client.models.doors; public class PoliceBoxCoralDoorModel extends DoorModel { private final ModelPart TARDIS; public PoliceBoxCoralDoorModel(ModelPart root) { super(RenderLayer::getEntityCutoutNoCull); this.TARDIS = root.getChild("TARDIS"); } public static TexturedModelData getTexturedModelData() { ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); ModelPartData TARDIS = modelPartData.addChild("TARDIS", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 28.0F, 0.0F)); ModelPartData Posts = TARDIS.addChild("Posts", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData cube_r1 = Posts.addChild("cube_r1", ModelPartBuilder.create().uv(236, 42).cuboid(-18.0F, -60.0F, -17.0F, 4.0F, 56.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, -32.0F, 0.0F, 1.5708F, 0.0F)); ModelPartData cube_r2 = Posts.addChild("cube_r2", ModelPartBuilder.create().uv(236, 102).cuboid(-2.0F, -30.0F, 17.0F, 3.0F, 30.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -34.5F, -18.0F, -1.5708F, 1.4835F, -1.5708F)); ModelPartData cube_r3 = Posts.addChild("cube_r3", ModelPartBuilder.create().uv(236, 127).cuboid(-2.0F, 0.0F, 17.0F, 3.0F, 31.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -34.6743F, -18.0F, 1.5708F, 1.4835F, 1.5708F)); ModelPartData cube_r4 = Posts.addChild("cube_r4", ModelPartBuilder.create().uv(251, 127).cuboid(-2.0F, 0.0F, 17.0F, 3.0F, 31.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(-38.0F, -34.6743F, -18.0F, 1.5708F, 1.4835F, 1.5708F)); ModelPartData cube_r5 = Posts.addChild("cube_r5", ModelPartBuilder.create().uv(251, 102).cuboid(-2.0F, -30.0F, 17.0F, 3.0F, 30.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(-38.0F, -34.5F, -18.0F, -1.5708F, 1.4835F, -1.5708F)); ModelPartData cube_r6 = Posts.addChild("cube_r6", ModelPartBuilder.create().uv(251, 41).cuboid(-17.0F, -60.0F, -18.0F, 3.0F, 56.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, -32.0F, -3.1416F, 0.0F, 3.1416F)); ModelPartData Doors = TARDIS.addChild("Doors", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData right_door = Doors.addChild("right_door", ModelPartBuilder.create().uv(181, 177).cuboid(0.5F, -29.5F, -0.5F, 13.0F, 55.0F, 1.0F, new Dilation(0.0F)) .uv(0, 198).cuboid(0.5F, -29.5F, -1.0F, 14.0F, 55.0F, 0.0F, new Dilation(0.0F)) .uv(0, 10).cuboid(9.5F, -9.5F, -1.5F, 1.0F, 2.0F, 1.0F, new Dilation(0.0F)) .uv(5, 51).cuboid(2.5F, -9.5F, -1.5F, 1.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(-13.5F, -29.5F, -15.5F)); ModelPartData phone = right_door.addChild("phone", ModelPartBuilder.create().uv(268, 37).cuboid(-3.75F, -40.0F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(268, 37).cuboid(-3.75F, -39.8F, -13.5F, 2.0F, 0.0F, 2.0F, new Dilation(0.0F)) .uv(268, 43).cuboid(-3.75F, -37.75F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.5F)) .uv(265, 25).cuboid(-8.5F, -40.0F, -13.5F, 5.0F, 6.0F, 2.0F, new Dilation(0.0F)) .uv(268, 34).cuboid(-7.0F, -39.5F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)) .uv(259, 35).cuboid(-5.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)) .uv(259, 35).cuboid(-8.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)) .uv(250, 35).cuboid(-5.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.2F)) .uv(250, 35).cuboid(-8.5F, -42.0F, -13.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.2F)) .uv(250, 25).cuboid(-9.0F, -41.5F, -14.5F, 6.0F, 8.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(12.5F, 28.5F, 14.5F)); ModelPartData phone_t = right_door.addChild("phone_t", ModelPartBuilder.create().uv(266, 74).cuboid(-9.25F, -40.0F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(266, 74).cuboid(-9.25F, -39.8F, -13.5F, 2.0F, 0.0F, 2.0F, new Dilation(0.0F)) .uv(266, 80).cuboid(-9.0F, -37.75F, -13.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.5F)) .uv(266, 60).cuboid(-7.5F, -41.0F, -14.5F, 3.0F, 7.0F, 3.0F, new Dilation(0.0F)) .uv(266, 71).cuboid(-7.0F, -40.0F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)) .uv(266, 71).cuboid(-7.0F, -37.0F, -11.25F, 2.0F, 2.0F, 0.0F, new Dilation(0.0F)), ModelTransform.pivot(13.25F, 28.5F, 14.5F)); ModelPartData left_door = Doors.addChild("left_door", ModelPartBuilder.create().uv(189, 41).cuboid(-13.5F, -29.5F, -0.5F, 13.0F, 55.0F, 1.0F, new Dilation(0.0F)) .uv(0, 0).cuboid(-12.5F, -10.5F, -1.5F, 1.0F, 4.0F, 1.0F, new Dilation(0.0F)) .uv(0, 51).cuboid(-12.5F, -4.5F, -1.5F, 1.0F, 4.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(13.5F, -29.5F, -15.5F)); ModelPartData Walls = TARDIS.addChild("Walls", ModelPartBuilder.create().uv(63, 227).cuboid(-14.0F, -60.0F, -16.0F, 1.0F, 56.0F, 1.0F, new Dilation(0.0F)) .uv(116, 170).cuboid(13.0F, -60.0F, -16.0F, 1.0F, 56.0F, 1.0F, new Dilation(0.0F)) .uv(115, 0).cuboid(-13.0F, -60.0F, -16.0F, 26.0F, 1.0F, 1.0F, new Dilation(0.0F)) .uv(59, 113).cuboid(13.0F, -60.0F, -16.5F, 1.0F, 56.0F, 0.0F, new Dilation(0.0F)) .uv(115, 3).cuboid(-13.0F, -60.0F, -16.5F, 26.0F, 1.0F, 0.0F, new Dilation(0.0F)) .uv(62, 113).cuboid(-14.0F, -60.0F, -16.5F, 1.0F, 56.0F, 0.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData PCB = TARDIS.addChild("PCB", ModelPartBuilder.create().uv(241, 2).cuboid(-17.0F, -64.0F, -19.0F, 34.0F, 5.0F, 6.0F, new Dilation(0.0F)) .uv(243, 3).cuboid(-16.0F, -60.0F, -17.0F, 32.0F, 0.0F, 4.0F, new Dilation(0.0F)) .uv(241, 14).cuboid(-16.0F, -63.0F, -17.0F, 32.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(241, 18).cuboid(-1.0F, -63.0F, -14.0F, 2.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(243, 5).cuboid(16.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(277, 5).cuboid(-16.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(243, 3).cuboid(-16.0F, -63.0F, -17.0F, 32.0F, 0.0F, 4.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -1.0F, 0.0F)); ModelPartData lights = PCB.addChild("lights", ModelPartBuilder.create().uv(241, 28).cuboid(10.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(10.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 22).cuboid(4.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(4.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-6.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-6.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-12.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-12.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); ModelPartData TARDIS_t = TARDIS.addChild("TARDIS_t", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); ModelPartData PCB_t = TARDIS_t.addChild("PCB_t", ModelPartBuilder.create().uv(0, 434).cuboid(-17.0F, -64.0F, -19.0F, 34.0F, 5.0F, 6.0F, new Dilation(0.0F)) .uv(8, 435).cuboid(-11.0F, -60.0F, -17.0F, 22.0F, 0.0F, 4.0F, new Dilation(0.0F)) .uv(0, 446).cuboid(-11.0F, -63.0F, -17.0F, 22.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(0, 450).cuboid(-1.0F, -63.0F, -14.0F, 2.0F, 3.0F, 0.0F, new Dilation(0.0F)) .uv(0, 437).cuboid(11.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(38, 437).cuboid(-11.0F, -63.0F, -17.0F, 0.0F, 3.0F, 4.0F, new Dilation(0.0F)) .uv(21, 435).cuboid(-11.0F, -63.0F, -17.0F, 22.0F, 0.0F, 4.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -1.0F, 0.0F)); ModelPartData lights2 = PCB_t.addChild("lights2", ModelPartBuilder.create().uv(241, 28).cuboid(10.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(10.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 22).cuboid(4.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(4.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-6.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-6.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(241, 22).cuboid(-12.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(241, 28).cuboid(-12.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); ModelPartData lights_t2 = PCB_t.addChild("lights_t2", ModelPartBuilder.create().uv(267, 55).cuboid(7.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(7.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 49).cuboid(1.75F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(1.75F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(-3.75F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(-3.75F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)) .uv(267, 49).cuboid(-9.0F, -60.4F, -16.5F, 2.0F, 3.0F, 2.0F, new Dilation(-0.3F)) .uv(267, 55).cuboid(-9.0F, -59.3F, -16.5F, 2.0F, 2.0F, 2.0F, new Dilation(-0.15F)), ModelTransform.pivot(0.0F, -3.0F, 0.0F)); return TexturedModelData.of(modelData, 512, 512); } @Override public void render(MatrixStack matrices, VertexConsumer vertexConsumer, int light, int overlay, float red, float green, float blue, float alpha) { TARDIS.render(matrices, vertexConsumer, light, overlay, red, green, blue, alpha); } @Override public void renderWithAnimations(DoorBlockEntity doorEntity, ModelPart root, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float pAlpha) { /*this.TARDIS.getChild("Doors").getChild("right_door").yaw = -doorEntity.getRightDoorRotation(); this.TARDIS.getChild("Doors").getChild("left_door").yaw = doorEntity.getLeftDoorRotation();*/ DoorHandler door = doorEntity.getTardis().getDoor(); this.TARDIS.getChild("Doors").getChild("left_door").yaw = (door.isLeftOpen() || door.isOpen()) ? -5F : 0.0F; this.TARDIS.getChild("Doors").getChild("right_door").yaw = (door.isRightOpen() || door.isBothOpen()) ? 5F : 0.0F; matrices.push(); matrices.scale(0.631F, 0.631F, 0.631F); matrices.translate(0, -1.5f, -0.35); matrices.multiply(RotationAxis.NEGATIVE_Y.rotationDegrees(180)); super.renderWithAnimations(doorEntity, root, matrices, vertices, light, overlay, red, green, blue, pAlpha); matrices.pop(); } @Override public Animation getAnimationForDoorState(DoorHandler.DoorStateEnum state) { return switch (state) {
case CLOSED -> DoorAnimations.INTERIOR_BOTH_CLOSE_ANIMATION;
0
2023-10-08 00:38:53+00:00
24k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/LibraryAuthController.java
[ { "identifier": "StatusEnums", "path": "nhXJH-common/src/main/java/com/nhXJH/common/enums/application/StatusEnums.java", "snippet": "public enum StatusEnums {\n NEG_ONE(-1, \"-1\"),\n ONE(1, \"1\"),\n ZERO(0, \"0\"),\n TWO(2, \"2\"),\n ;\n\n /**\n * 编码\n */\n private Integer...
import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSONArray; import com.nhXJH.common.enums.application.StatusEnums; import com.nhXJH.common.enums.application.TableTypeEnums; import com.nhXJH.web.domain.AttachFile; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryAuth; import com.nhXJH.web.domain.LibraryBook; import com.nhXJH.web.domain.entity.SysFile; import com.nhXJH.web.domain.param.AuthParam; import com.nhXJH.web.domain.vo.AuthVO; import com.nhXJH.web.domain.vo.FileVo; import com.nhXJH.web.service.IBaseFileService; import com.nhXJH.web.service.ILibraryAuthService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo;
17,692
package com.nhXJH.web.controller.appllication; /** * 作信息者Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/auth") @Api(tags = {"作信息者"})
package com.nhXJH.web.controller.appllication; /** * 作信息者Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/auth") @Api(tags = {"作信息者"})
public class LibraryAuthController extends BaseController {
10
2023-10-14 04:57:42+00:00
24k
codegrits/CodeGRITS
src/main/java/actions/StartStopTrackingAction.java
[ { "identifier": "ConfigDialog", "path": "src/main/java/components/ConfigDialog.java", "snippet": "public class ConfigDialog extends DialogWrapper {\n\n private List<JCheckBox> checkBoxes;\n\n private final JPanel panel = new JPanel();\n private static List<JTextField> labelAreas = new ArrayList...
import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import components.ConfigDialog; import entity.Config; import org.jetbrains.annotations.NotNull; import trackers.EyeTracker; import trackers.IDETracker; import trackers.ScreenRecorder; import utils.AvailabilityChecker; import javax.swing.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.util.Objects;
17,603
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */ private static EyeTracker eyeTracker; /** * This variable is the screen recorder. */
private final ScreenRecorder screenRecorder = ScreenRecorder.getInstance();
4
2023-10-12 15:40:39+00:00
24k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/monitor/job/controller/JobLogController.java
[ { "identifier": "StringUtils", "path": "src/main/java/com/ruoyi/common/utils/StringUtils.java", "snippet": "public class StringUtils extends org.apache.commons.lang3.StringUtils\n{\n /** 空字符串 */\n private static final String NULLSTR = \"\";\n\n /** 下划线 */\n private static final char SEPARATO...
import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.aspectj.lang.annotation.Log; import com.ruoyi.framework.aspectj.lang.enums.BusinessType; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.project.monitor.job.domain.Job; import com.ruoyi.project.monitor.job.domain.JobLog; import com.ruoyi.project.monitor.job.service.IJobLogService; import com.ruoyi.project.monitor.job.service.IJobService;
21,004
package com.ruoyi.project.monitor.job.controller; /** * 调度日志操作处理 * * @author ruoyi */ @Controller @RequestMapping("/monitor/jobLog") public class JobLogController extends BaseController { private String prefix = "monitor/job"; @Autowired
package com.ruoyi.project.monitor.job.controller; /** * 调度日志操作处理 * * @author ruoyi */ @Controller @RequestMapping("/monitor/jobLog") public class JobLogController extends BaseController { private String prefix = "monitor/job"; @Autowired
private IJobService jobService;
9
2023-10-14 02:27:47+00:00
24k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
14,524
diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); } settings.add(new SpaceAdder());
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor()); settings.add(new OperatorUnifier()); if (this.oldSyntax) { // settings.add(new CommasAdder()); settings.add(new JoinCombiner()); settings.add(new SelectCombiner()); // settings.add(new EscapingAdder()); } settings.add(new SpaceAdder());
settings.add(new ConditionAligner());
3
2023-10-10 18:56:27+00:00
24k
Spider-Admin/Frost
src/main/java/frost/messaging/frost/gui/unsentmessages/UnsentMessagesPanel.java
[ { "identifier": "Core", "path": "src/main/java/frost/Core.java", "snippet": "public class Core {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Core.class);\r\n\r\n // Core instanciates itself, frostSettings must be created before instance=Core() !\r\n public static final Se...
import frost.SettingsClass; import frost.messaging.frost.FrostUnsentMessageObject; import frost.util.gui.translation.Language; import frost.util.gui.translation.LanguageEvent; import frost.util.gui.translation.LanguageListener; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import frost.Core;
20,505
/* UnsentMessagesPanel.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.frost.gui.unsentmessages; @SuppressWarnings("serial") public class UnsentMessagesPanel extends JPanel implements LanguageListener { Language language = Language.getInstance(); private UnsentMessagesTable unsentMessagesTable; private JLabel unsentMsgsLabel; private JCheckBox disableMessageUpload; private boolean isShown = false; public UnsentMessagesPanel() { super(); language.addLanguageListener(this); initialize(); refreshLanguage(); } public synchronized void prepareForShow() { loadTableModel(); isShown = true; } public boolean isShown() { return isShown; } public synchronized void cleanupAfterLeave() { clearTableModel(); isShown = false; } public synchronized void addUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.addUnsentMessage(i); } } public synchronized void removeUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.removeUnsentMessage(i); } } public synchronized void updateUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.updateUnsentMessage(i); } } public void updateUnsentMessagesCount() { refreshLanguage(); } public void clearTableModel() { unsentMessagesTable.clearTableModel(); } public void loadTableModel() { unsentMessagesTable.loadTableModel(); } public void saveTableFormat() { unsentMessagesTable.saveTableFormat(); } public void refreshLanguage() { unsentMsgsLabel.setText( language.getString("UnsentMessages.label") + " ("+unsentMessagesTable.getRowCount()+")"); disableMessageUpload.setText( language.getString("UnsentMessages.disableMessageUpload") ); } public void languageChanged(LanguageEvent event) { refreshLanguage(); } private void initialize() { this.setLayout(new BorderLayout()); unsentMsgsLabel = new JLabel(); unsentMsgsLabel.setBorder(BorderFactory.createEmptyBorder(2,4,2,2)); disableMessageUpload = new JCheckBox(); disableMessageUpload.setBorder(BorderFactory.createEmptyBorder(2,16,2,2));
/* UnsentMessagesPanel.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.frost.gui.unsentmessages; @SuppressWarnings("serial") public class UnsentMessagesPanel extends JPanel implements LanguageListener { Language language = Language.getInstance(); private UnsentMessagesTable unsentMessagesTable; private JLabel unsentMsgsLabel; private JCheckBox disableMessageUpload; private boolean isShown = false; public UnsentMessagesPanel() { super(); language.addLanguageListener(this); initialize(); refreshLanguage(); } public synchronized void prepareForShow() { loadTableModel(); isShown = true; } public boolean isShown() { return isShown; } public synchronized void cleanupAfterLeave() { clearTableModel(); isShown = false; } public synchronized void addUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.addUnsentMessage(i); } } public synchronized void removeUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.removeUnsentMessage(i); } } public synchronized void updateUnsentMessage(FrostUnsentMessageObject i) { if( isShown ) { unsentMessagesTable.updateUnsentMessage(i); } } public void updateUnsentMessagesCount() { refreshLanguage(); } public void clearTableModel() { unsentMessagesTable.clearTableModel(); } public void loadTableModel() { unsentMessagesTable.loadTableModel(); } public void saveTableFormat() { unsentMessagesTable.saveTableFormat(); } public void refreshLanguage() { unsentMsgsLabel.setText( language.getString("UnsentMessages.label") + " ("+unsentMessagesTable.getRowCount()+")"); disableMessageUpload.setText( language.getString("UnsentMessages.disableMessageUpload") ); } public void languageChanged(LanguageEvent event) { refreshLanguage(); } private void initialize() { this.setLayout(new BorderLayout()); unsentMsgsLabel = new JLabel(); unsentMsgsLabel.setBorder(BorderFactory.createEmptyBorder(2,4,2,2)); disableMessageUpload = new JCheckBox(); disableMessageUpload.setBorder(BorderFactory.createEmptyBorder(2,16,2,2));
disableMessageUpload.setSelected(Core.frostSettings.getBoolValue(SettingsClass.MESSAGE_UPLOAD_DISABLED));
0
2023-10-07 22:25:20+00:00
24k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/PlayerResource.java
[ { "identifier": "CourseDataConstraint", "path": "core/src/bms/player/beatoraja/CourseData.java", "snippet": "public enum CourseDataConstraint {\n\t/**\n\t * 段位\n\t */\n CLASS(\"grade\", 0),\n\t/**\n\t * 段位(ミラーOK)\n\t */\n MIRROR(\"grade_mirror\", 0),\n\t/**\n\t * 段位(ランダムOK)\n\t */\n RANDOM(\"gr...
import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.logging.Logger; import com.badlogic.gdx.utils.*; import bms.model.*; import bms.player.beatoraja.CourseData.CourseDataConstraint; import bms.player.beatoraja.TableData.TableFolder; import bms.player.beatoraja.audio.AudioDriver; import bms.player.beatoraja.ir.RankingData; import bms.player.beatoraja.play.BMSPlayerRule; import bms.player.beatoraja.play.GrooveGauge; import bms.player.beatoraja.play.bga.BGAProcessor; import bms.player.beatoraja.song.SongData;
15,463
package bms.player.beatoraja; /** * プレイヤーのコンポーネント間でデータをやり取りするためのクラス * * @author exch */ public class PlayerResource { /** * 選曲中のBMS */ private BMSModel model; private long marginTime; /** * 選択中のBMSの情報 */ private SongData songdata; /** * BMSModelの元々のモード */ private bms.model.Mode orgmode; private PlayerData playerdata = new PlayerData(); private Config config; private PlayerConfig pconfig; /** * プレイモード */ private BMSPlayerMode mode; private BMSResource bmsresource; /** * スコア */ private ScoreData score; /** * ライバルスコア */ private ScoreData rscore;
package bms.player.beatoraja; /** * プレイヤーのコンポーネント間でデータをやり取りするためのクラス * * @author exch */ public class PlayerResource { /** * 選曲中のBMS */ private BMSModel model; private long marginTime; /** * 選択中のBMSの情報 */ private SongData songdata; /** * BMSModelの元々のモード */ private bms.model.Mode orgmode; private PlayerData playerdata = new PlayerData(); private Config config; private PlayerConfig pconfig; /** * プレイモード */ private BMSPlayerMode mode; private BMSResource bmsresource; /** * スコア */ private ScoreData score; /** * ライバルスコア */ private ScoreData rscore;
private RankingData ranking;
3
2023-12-02 23:41:17+00:00
24k
parttimenerd/hello-ebpf
bcc/src/main/java/me/bechberger/ebpf/samples/chapter2/ex/HelloBufferEvenOdd.java
[ { "identifier": "BPF", "path": "bcc/src/main/java/me/bechberger/ebpf/bcc/BPF.java", "snippet": "public class BPF implements AutoCloseable {\n\n static {\n try {\n System.loadLibrary(\"bcc\");\n } catch (UnsatisfiedLinkError e) {\n try {\n System.load...
import static me.bechberger.ebpf.samples.chapter2.HelloBuffer.DATA_TYPE; import me.bechberger.ebpf.bcc.BPF; import me.bechberger.ebpf.bcc.BPFTable; import me.bechberger.ebpf.samples.chapter2.HelloBuffer;
20,952
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello");
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello");
BPFTable.PerfEventArray.EventCallback<HelloBuffer.Data> print_event = (array, cpu, data, size) -> {
1
2023-12-01 20:24:28+00:00
24k
WiIIiam278/HuskClaims
bukkit/src/main/java/net/william278/huskclaims/hook/BukkitGriefPreventionImporter.java
[ { "identifier": "BukkitHuskClaims", "path": "bukkit/src/main/java/net/william278/huskclaims/BukkitHuskClaims.java", "snippet": "@NoArgsConstructor\n@Getter\npublic class BukkitHuskClaims extends JavaPlugin implements HuskClaims, BukkitTask.Supplier, BukkitBlockProvider,\n BukkitEventDispatcher, B...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import net.william278.huskclaims.BukkitHuskClaims; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.trust.Trustable; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.Preferences; import net.william278.huskclaims.user.User; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.stream.IntStream;
16,009
// Get the claim world final Optional<ClaimWorld> optionalWorld = plugin.getClaimWorld(world); if (optionalWorld.isEmpty()) { plugin.log(Level.WARNING, "Skipped claim at %s on missing world %s".formatted(gpc.lesserCorner, world)); return; } final ClaimWorld claimWorld = optionalWorld.get(); // Add the claim world to the list of worlds, then cache the claim owner/trustees claimWorlds.add(claimWorld); hcc.getOwner().flatMap(owner -> users.stream().filter(gpu -> gpu.uuid.equals(owner)).findFirst()) .ifPresent(user -> claimWorld.cacheUser(user.toUser())); hcc.getTrustedUsers().keySet().forEach(u -> users.stream().filter(gpu -> gpu.uuid.equals(u)) .findFirst().ifPresent(user -> claimWorld.cacheUser(user.toUser()))); // Add the claim to either its parent or the claim world if (gpc.isChildClaim()) { allClaims.entrySet().stream() .filter(entry -> entry.getValue().id == gpc.parentId) .map(Map.Entry::getKey).findFirst() .ifPresent(parent -> { parent.getOwner().ifPresent(hcc::setOwner); parent.getChildren().add(hcc); }); } else { claimWorld.getClaims().add(hcc); } if (amount.incrementAndGet() % CLAIMS_PER_PAGE == 0) { log(executor, Level.INFO, "Saved %s claims...".formatted(amount.get())); } }); // Save claim worlds plugin.clearAllMapMarkers(); log(executor, Level.INFO, "Saving %s claim worlds...".formatted(claimWorlds.size())); final List<CompletableFuture<Void>> claimWorldFutures = Lists.newArrayList(); claimWorlds.forEach(claimWorld -> claimWorldFutures.add( CompletableFuture.runAsync(() -> plugin.getDatabase().updateClaimWorld(claimWorld), pool) )); CompletableFuture.allOf(claimWorldFutures.toArray(CompletableFuture[]::new)).join(); plugin.markAllClaims(); return amount.get(); } private int getTotalUsers() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_playerdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total user count from DB database", e); } return 0; } private int getTotalClaims() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_claimdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total claim count from DB database", e); } return 0; } private CompletableFuture<List<GriefPreventionClaim>> getClaimPage(int page) { final List<GriefPreventionClaim> claims = Lists.newArrayList(); return CompletableFuture.supplyAsync(() -> { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT * FROM griefprevention_claimdata LIMIT ?, ?;""")) { statement.setInt(1, (page - 1) * CLAIMS_PER_PAGE); statement.setInt(2, CLAIMS_PER_PAGE); final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { claims.add(new GriefPreventionClaim( resultSet.getInt("id"), resultSet.getString("owner"), resultSet.getString("lessercorner"), resultSet.getString("greatercorner"), parseTrusted(resultSet.getString("builders")), parseTrusted(resultSet.getString("containers")), parseTrusted(resultSet.getString("accessors")), parseTrusted(resultSet.getString("managers")), resultSet.getBoolean("inheritnothing"), resultSet.getInt("parentid") )); } return claims; } catch (Throwable e) { plugin.log(Level.WARNING, "Exception getting claim page #%s from GP database".formatted(page), e); } return claims; }, pool); } @NotNull private List<String> parseTrusted(@NotNull String names) { return Arrays.stream(names.split(";")) .filter(s -> !s.isEmpty()) .toList(); }
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.hook; public class BukkitGriefPreventionImporter extends Importer { // Parameters for the GP database private static final int USERS_PER_PAGE = 500; private static final int CLAIMS_PER_PAGE = 500; private static final String GP_PUBLIC_STRING = "public"; private HikariDataSource dataSource; private ExecutorService pool; private List<GriefPreventionUser> users; public BukkitGriefPreventionImporter(@NotNull BukkitHuskClaims plugin) { super( "GriefPrevention", List.of(ImportData.USERS, ImportData.CLAIMS), plugin, Map.of( "uri", true, "username", true, "password", false ), Map.of( "password", "" ) ); } @Override public void prepare() throws IllegalArgumentException { final String uri = configParameters.get("uri"); final String username = configParameters.get("username"); final String password = configParameters.get("password"); if (uri == null || username == null) { throw new IllegalArgumentException("Missing required config parameters"); } // Setup GriefPrevention database connection final HikariConfig config = new HikariConfig(); config.setJdbcUrl(uri); config.setUsername(username); if (password != null) { config.setPassword(password); } config.setMaximumPoolSize(1); config.setConnectionTimeout(30000); config.setPoolName(String.format("HuskClaims-%s-Importer", getName())); config.setReadOnly(true); this.dataSource = new HikariDataSource(config); this.pool = Executors.newFixedThreadPool(20); } @Override public void finish() { if (dataSource != null) { dataSource.close(); } if (pool != null) { pool.shutdown(); } this.configParameters = Maps.newHashMap(defaultParameters); this.users = Lists.newArrayList(); } @Override protected int importData(@NotNull ImportData importData, @NotNull CommandUser executor) { return switch (importData) { case USERS -> importUsers(); case CLAIMS -> importClaims(executor); }; } private int importUsers() { final int totalUsers = getTotalUsers(); final int totalPages = (int) Math.ceil(totalUsers / (double) USERS_PER_PAGE); final List<CompletableFuture<List<GriefPreventionUser>>> userPages = IntStream.rangeClosed(1, totalPages) .mapToObj(this::getUserPage).toList(); CompletableFuture.allOf(userPages.toArray(CompletableFuture[]::new)).join(); users = Lists.newArrayList(); userPages.stream().map(CompletableFuture::join).forEach(users::addAll); return users.size(); } private int importClaims(@NotNull CommandUser executor) { if (users == null) { throw new IllegalStateException("Users must be imported before claims"); } final int totalClaims = getTotalClaims(); final int totalPages = (int) Math.ceil(totalClaims / (double) CLAIMS_PER_PAGE); final List<CompletableFuture<List<GriefPreventionClaim>>> claimPages = IntStream.rangeClosed(1, totalPages) .mapToObj(this::getClaimPage).toList(); CompletableFuture.allOf(claimPages.toArray(CompletableFuture[]::new)).join(); final List<GriefPreventionClaim> claims = claimPages.stream() .map(CompletableFuture::join) .toList().stream() .flatMap(Collection::stream) .toList(); log(executor, Level.INFO, "Adjusting claim block balances for %s users...".formatted(users.size())); final List<CompletableFuture<Void>> saveFutures = Lists.newArrayList(); final AtomicInteger amount = new AtomicInteger(); users.forEach(user -> { // Update claim blocks final int totalArea = claims.stream() .filter(c -> c.owner.equals(user.uuid.toString())) .mapToInt(c -> { final String[] lesserCorner = c.lesserCorner.split(";"); final String[] greaterCorner = c.greaterCorner.split(";"); int x1 = Integer.parseInt(lesserCorner[1]); int z1 = Integer.parseInt(lesserCorner[3]); int x2 = Integer.parseInt(greaterCorner[1]); int z2 = Integer.parseInt(greaterCorner[3]); int x = Math.abs(x1 - x2) + 1; int z = Math.abs(z1 - z2) + 1; return x * z; }) .sum(); user.claimBlocks = Math.max(0, user.claimBlocks - totalArea); saveFutures.add(CompletableFuture.runAsync( () -> { plugin.getDatabase().createOrUpdateUser( user.uuid, user.name, user.claimBlocks, user.getLastLogin(), Preferences.IMPORTED ); plugin.invalidateClaimListCache(user.uuid); if (amount.incrementAndGet() % USERS_PER_PAGE == 0) { log(executor, Level.INFO, "Adjusted %s users...".formatted(amount.get())); } }, pool )); }); // Wait for all users to be saved CompletableFuture.allOf(saveFutures.toArray(CompletableFuture[]::new)).join(); plugin.invalidateAdminClaimListCache(); // Adding admin claims & child claims log(executor, Level.INFO, "Converting %s claims...".formatted(claims.size())); final Map<Claim, GriefPreventionClaim> allClaims = Maps.newHashMap(); claims.forEach(gpc -> allClaims.put(gpc.toClaim(this), gpc)); // Convert child claims and save to claim worlds log(executor, Level.INFO, "Saving %s claims...".formatted(amount.getAndSet(0))); final Set<ClaimWorld> claimWorlds = Sets.newHashSet(); allClaims.forEach((hcc, gpc) -> { final String world = gpc.lesserCorner.split(";")[0]; // Get the claim world final Optional<ClaimWorld> optionalWorld = plugin.getClaimWorld(world); if (optionalWorld.isEmpty()) { plugin.log(Level.WARNING, "Skipped claim at %s on missing world %s".formatted(gpc.lesserCorner, world)); return; } final ClaimWorld claimWorld = optionalWorld.get(); // Add the claim world to the list of worlds, then cache the claim owner/trustees claimWorlds.add(claimWorld); hcc.getOwner().flatMap(owner -> users.stream().filter(gpu -> gpu.uuid.equals(owner)).findFirst()) .ifPresent(user -> claimWorld.cacheUser(user.toUser())); hcc.getTrustedUsers().keySet().forEach(u -> users.stream().filter(gpu -> gpu.uuid.equals(u)) .findFirst().ifPresent(user -> claimWorld.cacheUser(user.toUser()))); // Add the claim to either its parent or the claim world if (gpc.isChildClaim()) { allClaims.entrySet().stream() .filter(entry -> entry.getValue().id == gpc.parentId) .map(Map.Entry::getKey).findFirst() .ifPresent(parent -> { parent.getOwner().ifPresent(hcc::setOwner); parent.getChildren().add(hcc); }); } else { claimWorld.getClaims().add(hcc); } if (amount.incrementAndGet() % CLAIMS_PER_PAGE == 0) { log(executor, Level.INFO, "Saved %s claims...".formatted(amount.get())); } }); // Save claim worlds plugin.clearAllMapMarkers(); log(executor, Level.INFO, "Saving %s claim worlds...".formatted(claimWorlds.size())); final List<CompletableFuture<Void>> claimWorldFutures = Lists.newArrayList(); claimWorlds.forEach(claimWorld -> claimWorldFutures.add( CompletableFuture.runAsync(() -> plugin.getDatabase().updateClaimWorld(claimWorld), pool) )); CompletableFuture.allOf(claimWorldFutures.toArray(CompletableFuture[]::new)).join(); plugin.markAllClaims(); return amount.get(); } private int getTotalUsers() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_playerdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total user count from DB database", e); } return 0; } private int getTotalClaims() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_claimdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total claim count from DB database", e); } return 0; } private CompletableFuture<List<GriefPreventionClaim>> getClaimPage(int page) { final List<GriefPreventionClaim> claims = Lists.newArrayList(); return CompletableFuture.supplyAsync(() -> { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT * FROM griefprevention_claimdata LIMIT ?, ?;""")) { statement.setInt(1, (page - 1) * CLAIMS_PER_PAGE); statement.setInt(2, CLAIMS_PER_PAGE); final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { claims.add(new GriefPreventionClaim( resultSet.getInt("id"), resultSet.getString("owner"), resultSet.getString("lessercorner"), resultSet.getString("greatercorner"), parseTrusted(resultSet.getString("builders")), parseTrusted(resultSet.getString("containers")), parseTrusted(resultSet.getString("accessors")), parseTrusted(resultSet.getString("managers")), resultSet.getBoolean("inheritnothing"), resultSet.getInt("parentid") )); } return claims; } catch (Throwable e) { plugin.log(Level.WARNING, "Exception getting claim page #%s from GP database".formatted(page), e); } return claims; }, pool); } @NotNull private List<String> parseTrusted(@NotNull String names) { return Arrays.stream(names.split(";")) .filter(s -> !s.isEmpty()) .toList(); }
private void setTrust(@NotNull String id, @NotNull TrustLevel level, @NotNull Map<Trustable, TrustLevel> map) {
6
2023-11-28 01:09:43+00:00
24k
Manzzx/multi-channel-message-reach
metax-modules/metax-system/src/main/java/com/metax/system/controller/SysLogininforController.java
[ { "identifier": "CacheConstants", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/CacheConstants.java", "snippet": "public class CacheConstants\n{\n /**\n * 缓存有效期,默认720(分钟)\n */\n public final static long EXPIRATION = 720;\n\n /**\n * 缓存刷新时间,默认12...
import java.util.List; import javax.servlet.http.HttpServletResponse; 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 com.metax.common.core.constant.CacheConstants; import com.metax.common.core.utils.poi.ExcelUtil; import com.metax.common.core.web.controller.BaseController; import com.metax.common.core.web.domain.AjaxResult; import com.metax.common.core.web.page.TableDataInfo; import com.metax.common.log.annotation.Log; import com.metax.common.log.enums.BusinessType; import com.metax.common.redis.service.RedisService; import com.metax.common.security.annotation.InnerAuth; import com.metax.common.security.annotation.RequiresPermissions; import com.metax.system.api.domain.SysLogininfor; import com.metax.system.service.ISysLogininforService;
17,467
package com.metax.system.controller; /** * 系统访问记录 * * @author ruoyi */ @RestController @RequestMapping("/logininfor") public class SysLogininforController extends BaseController { @Autowired private ISysLogininforService logininforService; @Autowired private RedisService redisService; @RequiresPermissions("system:logininfor:list") @GetMapping("/list")
package com.metax.system.controller; /** * 系统访问记录 * * @author ruoyi */ @RestController @RequestMapping("/logininfor") public class SysLogininforController extends BaseController { @Autowired private ISysLogininforService logininforService; @Autowired private RedisService redisService; @RequiresPermissions("system:logininfor:list") @GetMapping("/list")
public TableDataInfo list(SysLogininfor logininfor)
7
2023-12-04 05:10:13+00:00
24k
ydb-platform/yoj-project
repository-inmemory/src/main/java/tech/ydb/yoj/repository/test/inmemory/InMemoryTable.java
[ { "identifier": "FilterExpression", "path": "databind/src/main/java/tech/ydb/yoj/databind/expression/FilterExpression.java", "snippet": "public interface FilterExpression<T> {\n <V> V visit(@NonNull Visitor<T, V> visitor);\n\n Schema<T> getSchema();\n\n Type getType();\n\n <U> FilterExpressi...
import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import tech.ydb.yoj.databind.expression.FilterExpression; import tech.ydb.yoj.databind.expression.OrderExpression; import tech.ydb.yoj.databind.schema.ObjectSchema; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntityExpressions; import tech.ydb.yoj.repository.db.EntityIdSchema; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.db.Range; import tech.ydb.yoj.repository.db.Table; import tech.ydb.yoj.repository.db.ViewSchema; import tech.ydb.yoj.repository.db.cache.FirstLevelCache; import tech.ydb.yoj.repository.db.exception.IllegalTransactionIsolationLevelException; import tech.ydb.yoj.repository.db.list.InMemoryQueries; import tech.ydb.yoj.repository.db.readtable.ReadTableParams; import tech.ydb.yoj.repository.db.statement.Changeset; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toUnmodifiableMap; import static java.util.stream.Collectors.toUnmodifiableSet;
19,096
package tech.ydb.yoj.repository.test.inmemory; public class InMemoryTable<T extends Entity<T>> implements Table<T> { private final Class<T> type; private final EntitySchema<T> schema; private final InMemoryRepositoryTransaction transaction; public InMemoryTable(DbMemory<T> memory) { this.type = memory.type(); this.schema = EntitySchema.of(type); this.transaction = memory.transaction(); } @Override public List<T> findAll() { transaction.getWatcher().markTableRead(type); return findAll0(); } @Override public <V extends View> List<V> findAll(Class<V> viewType) { return findAll().stream() .map(entity -> toView(viewType, schema, entity)) .collect(toList()); } @Override public long countAll() { return findAll().size(); } @Override public long count(String indexName, FilterExpression<T> filter) { return find(indexName, filter, null, null, null).size(); } @Override @Deprecated public void update(Entity.Id<T> id, Changeset changeset) { T found = find(id); if (found == null) { return; } Map<String, Object> cells = new HashMap<>(schema.flatten(found)); changeset.toMap().forEach((k, v) -> { cells.putAll(schema.flattenOneField(k, v)); }); T newInstance = schema.newInstance(cells); save(newInstance); } @Override public List<T> find( @Nullable String indexName, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { // NOTE: InMemoryTable doesn't handle index. return InMemoryQueries.find(() -> findAll().stream(), filter, orderBy, limit, offset); } @Override public <V extends View> List<V> find( Class<V> viewType, @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset, boolean distinct ) { Stream<V> stream = find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> toView(viewType, schema, entity)); if (distinct) { stream = stream.distinct(); } return stream.collect(toList()); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds( @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { return find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> (ID) entity.getId()) .collect(toList()); } @Override
package tech.ydb.yoj.repository.test.inmemory; public class InMemoryTable<T extends Entity<T>> implements Table<T> { private final Class<T> type; private final EntitySchema<T> schema; private final InMemoryRepositoryTransaction transaction; public InMemoryTable(DbMemory<T> memory) { this.type = memory.type(); this.schema = EntitySchema.of(type); this.transaction = memory.transaction(); } @Override public List<T> findAll() { transaction.getWatcher().markTableRead(type); return findAll0(); } @Override public <V extends View> List<V> findAll(Class<V> viewType) { return findAll().stream() .map(entity -> toView(viewType, schema, entity)) .collect(toList()); } @Override public long countAll() { return findAll().size(); } @Override public long count(String indexName, FilterExpression<T> filter) { return find(indexName, filter, null, null, null).size(); } @Override @Deprecated public void update(Entity.Id<T> id, Changeset changeset) { T found = find(id); if (found == null) { return; } Map<String, Object> cells = new HashMap<>(schema.flatten(found)); changeset.toMap().forEach((k, v) -> { cells.putAll(schema.flattenOneField(k, v)); }); T newInstance = schema.newInstance(cells); save(newInstance); } @Override public List<T> find( @Nullable String indexName, @Nullable FilterExpression<T> filter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { // NOTE: InMemoryTable doesn't handle index. return InMemoryQueries.find(() -> findAll().stream(), filter, orderBy, limit, offset); } @Override public <V extends View> List<V> find( Class<V> viewType, @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset, boolean distinct ) { Stream<V> stream = find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> toView(viewType, schema, entity)); if (distinct) { stream = stream.distinct(); } return stream.collect(toList()); } @Override @SuppressWarnings("unchecked") public <ID extends Entity.Id<T>> List<ID> findIds( @Nullable String indexName, @Nullable FilterExpression<T> finalFilter, @Nullable OrderExpression<T> orderBy, @Nullable Integer limit, @Nullable Long offset ) { return find(indexName, finalFilter, orderBy, limit, offset).stream() .map(entity -> (ID) entity.getId()) .collect(toList()); } @Override
public <ID extends Entity.Id<T>> Stream<T> readTable(ReadTableParams<ID> params) {
14
2023-12-05 15:57:58+00:00
24k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/FileSelectorFragment.java
[ { "identifier": "FileListView", "path": "app_pojavlauncher/src/main/java/com/kdt/pickafile/FileListView.java", "snippet": "public class FileListView extends LinearLayout\n{\n //For list view:\n private File fullPath;\n private ListView mainLv;\n private Context context;\n\n //For File sel...
import android.app.AlertDialog; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.kdt.pickafile.FileListView; import com.kdt.pickafile.FileSelectedListener; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import java.io.File;
15,301
package net.kdt.pojavlaunch.fragments; public class FileSelectorFragment extends Fragment { public static final String TAG = "FileSelectorFragment"; public static final String BUNDLE_SELECT_FOLDER = "select_folder"; public static final String BUNDLE_SHOW_FILE = "show_file"; public static final String BUNDLE_SHOW_FOLDER = "show_folder"; public static final String BUNDLE_ROOT_PATH = "root_path"; private Button mSelectFolderButton, mCreateFolderButton; private FileListView mFileListView; private TextView mFilePathView; private boolean mSelectFolder = true; private boolean mShowFiles = true; private boolean mShowFolders = true; private String mRootPath = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? Tools.DIR_GAME_NEW : Environment.getExternalStorageDirectory().getAbsolutePath(); public FileSelectorFragment(){ super(R.layout.fragment_file_selector); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { bindViews(view); parseBundle(); if(!mSelectFolder) mSelectFolderButton.setVisibility(View.GONE); else mSelectFolderButton.setVisibility(View.VISIBLE); mFileListView.setShowFiles(mShowFiles); mFileListView.setShowFolders(mShowFolders); mFileListView.lockPathAt(new File(mRootPath)); mFileListView.setDialogTitleListener((title)->mFilePathView.setText(removeLockPath(title))); mFileListView.refreshPath(); mCreateFolderButton.setOnClickListener(v -> { final EditText editText = new EditText(getContext()); new AlertDialog.Builder(getContext()) .setTitle(R.string.folder_dialog_insert_name) .setView(editText) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.folder_dialog_create, (dialog, which) -> { File folder = new File(mFileListView.getFullPath(), editText.getText().toString()); boolean success = folder.mkdir(); if(success){ mFileListView.listFileAt(new File(mFileListView.getFullPath(),editText.getText().toString())); }else{ mFileListView.refreshPath(); } }).show(); }); mSelectFolderButton.setOnClickListener(v -> { ExtraCore.setValue(ExtraConstants.FILE_SELECTOR, removeLockPath(mFileListView.getFullPath().getAbsolutePath())); Tools.removeCurrentFragment(requireActivity()); });
package net.kdt.pojavlaunch.fragments; public class FileSelectorFragment extends Fragment { public static final String TAG = "FileSelectorFragment"; public static final String BUNDLE_SELECT_FOLDER = "select_folder"; public static final String BUNDLE_SHOW_FILE = "show_file"; public static final String BUNDLE_SHOW_FOLDER = "show_folder"; public static final String BUNDLE_ROOT_PATH = "root_path"; private Button mSelectFolderButton, mCreateFolderButton; private FileListView mFileListView; private TextView mFilePathView; private boolean mSelectFolder = true; private boolean mShowFiles = true; private boolean mShowFolders = true; private String mRootPath = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? Tools.DIR_GAME_NEW : Environment.getExternalStorageDirectory().getAbsolutePath(); public FileSelectorFragment(){ super(R.layout.fragment_file_selector); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { bindViews(view); parseBundle(); if(!mSelectFolder) mSelectFolderButton.setVisibility(View.GONE); else mSelectFolderButton.setVisibility(View.VISIBLE); mFileListView.setShowFiles(mShowFiles); mFileListView.setShowFolders(mShowFolders); mFileListView.lockPathAt(new File(mRootPath)); mFileListView.setDialogTitleListener((title)->mFilePathView.setText(removeLockPath(title))); mFileListView.refreshPath(); mCreateFolderButton.setOnClickListener(v -> { final EditText editText = new EditText(getContext()); new AlertDialog.Builder(getContext()) .setTitle(R.string.folder_dialog_insert_name) .setView(editText) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.folder_dialog_create, (dialog, which) -> { File folder = new File(mFileListView.getFullPath(), editText.getText().toString()); boolean success = folder.mkdir(); if(success){ mFileListView.listFileAt(new File(mFileListView.getFullPath(),editText.getText().toString())); }else{ mFileListView.refreshPath(); } }).show(); }); mSelectFolderButton.setOnClickListener(v -> { ExtraCore.setValue(ExtraConstants.FILE_SELECTOR, removeLockPath(mFileListView.getFullPath().getAbsolutePath())); Tools.removeCurrentFragment(requireActivity()); });
mFileListView.setFileSelectedListener(new FileSelectedListener() {
1
2023-12-01 16:16:12+00:00
24k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/worldGeneration/step/StepFeatures.java
[ { "identifier": "ChunkWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/chunk/ChunkWrapper.java", "snippet": "public class ChunkWrapper implements IChunkWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger();\n\t\n\t/** useful for debugging, but c...
import net.minecraft.world.level.chunk.ProtoChunk; import net.minecraft.world.level.levelgen.Heightmap; import java.util.ArrayList; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.common.wrappers.worldGeneration.ThreadedParameters; import com.seibel.distanthorizons.common.wrappers.worldGeneration.mimicObject.DhLitWorldGenRegion; import com.seibel.distanthorizons.core.util.gridList.ArrayGridList; import net.minecraft.ReportedException; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkStatus;
14,965
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.worldGeneration.step; #if POST_MC_1_18_2 #endif public final class StepFeatures { public static final ChunkStatus STATUS = ChunkStatus.FEATURES; private final BatchGenerationEnvironment environment; public StepFeatures(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup(
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.worldGeneration.step; #if POST_MC_1_18_2 #endif public final class StepFeatures { public static final ChunkStatus STATUS = ChunkStatus.FEATURES; private final BatchGenerationEnvironment environment; public StepFeatures(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public void generateGroup(
ThreadedParameters tParams, DhLitWorldGenRegion worldGenRegion,
2
2023-12-04 11:41:46+00:00
24k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/ui/history/HistoryActivity.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import android.app.LoaderManager; import android.app.SearchManager; import android.content.AsyncQueryHandler; import android.content.ContentProviderClient; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.cursoradapter.widget.CursorAdapter; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.TextView; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.R; import de.rampro.activitydiary.db.ActivityDiaryContentProvider; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.ui.generic.BaseActivity; import de.rampro.activitydiary.ui.generic.DetailRecyclerViewAdapter; import de.rampro.activitydiary.ui.generic.EditActivity; import de.rampro.activitydiary.ui.main.NoteEditDialog;
21,368
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Bc. Ondrej Janitor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.history; /* * Show the history of the Diary. * */ public class HistoryActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>, NoteEditDialog.NoteEditDialogListener, HistoryRecyclerViewAdapter.SelectListener, SearchView.OnCloseListener, SearchView.OnQueryTextListener { private static final String[] PROJECTION = new String[]{
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Bc. Ondrej Janitor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.history; /* * Show the history of the Diary. * */ public class HistoryActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor>, NoteEditDialog.NoteEditDialogListener, HistoryRecyclerViewAdapter.SelectListener, SearchView.OnCloseListener, SearchView.OnQueryTextListener { private static final String[] PROJECTION = new String[]{
ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary._ID,
2
2023-12-02 12:36:40+00:00
24k
Ethylene9160/Chess
src/chess/web/ChessChannel.java
[ { "identifier": "WebPanel", "path": "src/chess/panels/WebPanel.java", "snippet": "public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener {\n public final static String SIGN_SPLIT = \"&\", LINE_SPLIT = \"#\";\n public final static char SIGN_SPLIT_CHAR = '&', L...
import chess.panels.WebPanel; import chess.util.CloseUtil; import chess.util.Constants; import chess.util.RegisterUtil; import javax.swing.text.html.CSS; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Map; import static chess.panels.WebPanel.*;
19,741
package chess.web; /** * 每一个客户都是一条路 * 输入流 * 输出流 * 接收数据 * 发送数据 * <p> * 通过“#”来分割消息内容。 */ public class ChessChannel implements Runnable{ public static final int APPLY = 13, REGISTER = 12, CHANGE_NAME = 10, CHANGE_PASSWARD = 16, FIND_YOU = 17, FIND_OPPONENT = 18, CHANGE_HEAD = 19, FIND_PASSWARD = 20, RESET_PASSWARD = 21, SET_SIGN = 22, SHENGWANG_SHOP=23, MONEY = 24, UPDATE_VIP = -1, DECREASE_MONEY = -2 ; private DataInputStream inputStream; private DataOutputStream outputStream; private boolean flag = true, isRegistered = false; private Socket clientSocekt; private String name = "default", password; private int allTimes, winTimes; private double winRate; public int ownID, targetID, findID; public int getOwnID(){ return this.ownID; } public int getWinTime(){ return this.winTimes; } public int getAllTimes(){ return this.allTimes; } public String getName(){ return this.name; } public String getAllInfoOfAll(){ StringBuilder str = new StringBuilder(); for(Integer key : ChessServer.listMap.keySet()){ if(key != ownID) str.append(ChessServer.listMap.get(key).ownID).append("#").append(ChessServer.listMap.get(key).getName()).append("&"); } return str.toString(); } public ChessChannel(Socket clientSocket, int owmID) { this.clientSocekt = clientSocket; try{ inputStream = new DataInputStream(clientSocket.getInputStream()); outputStream = new DataOutputStream(clientSocket.getOutputStream()); this.ownID = owmID; }catch (IOException e){ flag = false;
package chess.web; /** * 每一个客户都是一条路 * 输入流 * 输出流 * 接收数据 * 发送数据 * <p> * 通过“#”来分割消息内容。 */ public class ChessChannel implements Runnable{ public static final int APPLY = 13, REGISTER = 12, CHANGE_NAME = 10, CHANGE_PASSWARD = 16, FIND_YOU = 17, FIND_OPPONENT = 18, CHANGE_HEAD = 19, FIND_PASSWARD = 20, RESET_PASSWARD = 21, SET_SIGN = 22, SHENGWANG_SHOP=23, MONEY = 24, UPDATE_VIP = -1, DECREASE_MONEY = -2 ; private DataInputStream inputStream; private DataOutputStream outputStream; private boolean flag = true, isRegistered = false; private Socket clientSocekt; private String name = "default", password; private int allTimes, winTimes; private double winRate; public int ownID, targetID, findID; public int getOwnID(){ return this.ownID; } public int getWinTime(){ return this.winTimes; } public int getAllTimes(){ return this.allTimes; } public String getName(){ return this.name; } public String getAllInfoOfAll(){ StringBuilder str = new StringBuilder(); for(Integer key : ChessServer.listMap.keySet()){ if(key != ownID) str.append(ChessServer.listMap.get(key).ownID).append("#").append(ChessServer.listMap.get(key).getName()).append("&"); } return str.toString(); } public ChessChannel(Socket clientSocket, int owmID) { this.clientSocekt = clientSocket; try{ inputStream = new DataInputStream(clientSocket.getInputStream()); outputStream = new DataOutputStream(clientSocket.getOutputStream()); this.ownID = owmID; }catch (IOException e){ flag = false;
CloseUtil.closeAll(inputStream, outputStream);
1
2023-12-01 02:33:32+00:00
24k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/App.java
[ { "identifier": "CodeBase", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/CodeBase.java", "snippet": "public class CodeBase {\n \n private final FunctionStatement[] functions;\n\n public CodeBase(FunctionStatement[] functions) {\n this.functions = functions;\n }\n\n p...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.compiler.Chunk; import org.vectorlang.compiler.compiler.Compiler; import org.vectorlang.compiler.compiler.Linker; import org.vectorlang.compiler.compiler.Pruner; import org.vectorlang.compiler.compiler.TypeFailure; import org.vectorlang.compiler.compiler.Typer; import org.vectorlang.compiler.parser.Lexer; import org.vectorlang.compiler.parser.Parser; import org.vectorlang.compiler.parser.Token;
15,393
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex();
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex();
Parser parser = new Parser();
7
2023-11-30 04:22:36+00:00
24k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
15,251
protected T queryForObject(String sql, HashMap<String, ?> params) throws DataException { return queryForObject(sql, params, true); } protected T queryForObject(String sql, HashMap<String, ?> params, boolean loadAll) throws DataException { T object; try { object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException { return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz()); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException { return queryForObject(sql, params, clazz, true); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException { Object object; try { object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return (I) object; } private AbstractRowMapper rowMapper(final Class clazz) { return JdbcCache.rowMapper(clazz, false); } private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) { return JdbcCache.rowMapper(clazz, loadAll); } protected int update(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().update(sql, params); } @Override public int update(T object) throws DataException { return updateAny(object); } protected int updateAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } List<String> primaryKeys = Arrays.asList(table.keys()); HashMap<String, Object> params = prepareParams(Operation.UPDATE, object); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(table.name()); sql.append(" SET "); boolean firstElement = true; for (String key : params.keySet()) { if (primaryKeys.contains(key)) { continue; } sql.append(!firstElement ? "," : ""); sql.append(key).append("=:").append(key); firstElement = false; } sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name());
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override public int deleteByID(ID id) throws DataException { return deleteByID(getGenericTypeClass(), id); } protected int deleteByID(Class clazz, ID key) throws DataException { return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected int deleteByID(Class clazz, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same amount keys to remove the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM ").append(table.name()).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return update(sql.toString(), params); } protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); Map<String, Object> out = sjc.execute(in); Map.Entry<String, Object> entry = out.entrySet().iterator().next(); if (entry.getValue() instanceof List<?>) { List<?> tempList = (List<?>) entry.getValue(); if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) { return (List<T>) entry.getValue(); } } return new ArrayList<>(); } protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); sjc.execute(in); } protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); return sjc.executeFunction(returnType, params); } protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); sjc.execute(params); } protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); Map<String, Object> out = sjc.execute(params); return out; } @Override public List<T> findAll() throws DataException { Table table = getTableName(getGenericTypeClass()); SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass()); if (!"[unassigned]".equals(table.defaultOrderBy())) { sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING); } return (List<T>) AbstractDAO.this.find(sqlQuery); } public List findAll(Class<? extends Mapping> aClass) throws DataException { return findAll(aClass, false); } public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException { //@TODO: implementar defaultOrderBy List list; try { String sql = JdbcCache.sqlBase(aClass, loadAll); list = getJdbcTemplate().query(sql, rowMapper(aClass, loadAll)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } catch (DataException de) { throw de; } catch (Exception ex) { throw new DataException(ex.getMessage(), ex); } return list; } @Override public List<T> findTop(int limit, SortOrder sortOrder) throws DataException { Table table = getTableName(getGenericTypeClass()); StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(getGenericTypeClass())); if (table.keys() != null) { sql.append(" ORDER BY "); for (String s : table.keys()) { sql.append(s); } sql.append(sortOrder == SortOrder.DESCENDING ? " DESC" : " ASC"); } StringBuilder customSql = getCustom().createSqlPagination(sql.toString(), limit, 0); return AbstractDAO.this.find(customSql.toString()); } public Iterator findQueryIterator(SQLQueryDynamic sqlQuery) { int limit = Utils.defaultValue(sqlQuery.getLimit(), 2500); if (!sqlQuery.isSorted()) { throw new DataException("It is necessary to specify a sort with identifier to be able to iterate over the records."); } return new QueryIterator<Map<String, Object>>(limit) { @Override public List getData(int limit, int offset) { sqlQuery.setLimit(limit); sqlQuery.setOffset(offset); List records = null; if (sqlQuery.getClazz() != null) { records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(sqlQuery.getClazz(), sqlQuery.isLoadAll())); } else { records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); } sqlQuery.setTotalResultCount(sqlQuery.getTotalResultCount() + records.size()); return records; } }; } protected List<T> find(String sql) throws DataException { List list; try { list = getJdbcTemplate().query(sql, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<T> find(String sql, HashMap<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().query(sqlPagination, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(SQLQueryDynamic sqlQuery) throws DataException { return find(sqlQuery, sqlQuery.getClazz()); } protected List find(SQLQueryDynamic sqlQuery, Class<? extends Mapping> clazz) throws DataException { List records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(clazz, sqlQuery.isLoadAll())); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } return records; } protected Paginator findPaginator(SQLQueryDynamic sqlQuery) throws DataException { List records = find(sqlQuery, sqlQuery.getClazz()); Paginator paginator = new Paginator(); paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); return paginator; } protected Paginator<Map<String, Object>> findMaps(SQLQueryDynamic sqlQuery) throws DataException { Paginator paginator = new Paginator(); try { List records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); } catch (EmptyResultDataAccessException e) { paginator.setRecords(new ArrayList<>()); paginator.setTotalRecords(0); } return paginator; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Long> findLongs(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } @Override public long generateID() throws DataException { Table table = getTableName(getGenericTypeClass()); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } protected long generateAnyID(Class<? extends Mapping> clazz) throws DataException { Table table = getTableName(clazz); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } @Override public T getByID(ID id) throws DataException { return (T) getByID(getGenericTypeClass(), id); } @Override public T getByID(ID key, boolean loadAll) throws DataException { return (T) getByID(getGenericTypeClass(), loadAll, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, ID key) throws DataException { return getByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, Object... keys) throws DataException { return getByID(clazz, false, keys); } protected <T extends Mapping> T getByID(Class<T> clazz, boolean loadAll, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same keys to identify the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(clazz, true)).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return (T) queryForObject(sql.toString(), params, rowMapper(clazz, loadAll)); } private Class<T> getGenericTypeClass() { return genericTypeClass; } @Override public void persist(T object) throws DataException { persistAny(object); } protected void persistAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); HashMap<String, Object> params = prepareParams(Operation.PERSIST, object); StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(table.name()); sql.append("("); boolean firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(key); firstElement = false; } sql.append(") VALUES"); sql.append("("); firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(":").append(key); firstElement = false; } sql.append(")"); update(sql.toString(), params); } protected String queryForString(String sql, HashMap<String, ?> params) throws DataException { String object; try { object = getJdbcTemplate().queryForObject(sql, params, String.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected byte[] queryForBytes(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().queryForObject(sql, params, byte[].class); } protected Integer queryForInteger(String sql) throws DataException { return queryForInteger(sql, null); } protected Integer queryForInteger(String sql, HashMap<String, ?> params) throws DataException { Integer object; try { object = getJdbcTemplate().queryForObject(sql, params, Integer.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected Long queryForLong(String sql) throws DataException { return queryForLong(sql, null); } protected Long queryForLong(String sql, HashMap<String, ?> params) throws DataException { Long object; try { object = getJdbcTemplate().queryForObject(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } private T queryForObject(String sql, HashMap<String, ?> params, AbstractRowMapper<T> rowMapper) throws DataException { T mapping; try { mapping = getJdbcTemplate().queryForObject(sql, params, rowMapper); } catch (EmptyResultDataAccessException e) { mapping = null; } return mapping; } protected T queryForObject(String sql, HashMap<String, ?> params) throws DataException { return queryForObject(sql, params, true); } protected T queryForObject(String sql, HashMap<String, ?> params, boolean loadAll) throws DataException { T object; try { object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException { return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz()); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException { return queryForObject(sql, params, clazz, true); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException { Object object; try { object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return (I) object; } private AbstractRowMapper rowMapper(final Class clazz) { return JdbcCache.rowMapper(clazz, false); } private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) { return JdbcCache.rowMapper(clazz, loadAll); } protected int update(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().update(sql, params); } @Override public int update(T object) throws DataException { return updateAny(object); } protected int updateAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } List<String> primaryKeys = Arrays.asList(table.keys()); HashMap<String, Object> params = prepareParams(Operation.UPDATE, object); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(table.name()); sql.append(" SET "); boolean firstElement = true; for (String key : params.keySet()) { if (primaryKeys.contains(key)) { continue; } sql.append(!firstElement ? "," : ""); sql.append(key).append("=:").append(key); firstElement = false; } sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name());
} else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) {
15
2023-11-27 18:25:00+00:00
24k
aliyun/aliyun-pairec-config-java-sdk
src/main/java/com/aliyun/openservices/pairec/ExperimentClient.java
[ { "identifier": "ApiClient", "path": "src/main/java/com/aliyun/openservices/pairec/api/ApiClient.java", "snippet": "public class ApiClient {\n private Configuration configuration;\n Client client;\n\n private CrowdApi crowdApi;\n\n private SceneApi sceneApi;\n\n private ExperimentRoomApi ...
import com.aliyun.openservices.pairec.api.ApiClient; import com.aliyun.openservices.pairec.common.Constants; import com.aliyun.openservices.pairec.model.DefaultSceneParams; import com.aliyun.openservices.pairec.model.EmptySceneParams; import com.aliyun.openservices.pairec.model.Experiment; import com.aliyun.openservices.pairec.model.ExperimentContext; import com.aliyun.openservices.pairec.model.ExperimentGroup; import com.aliyun.openservices.pairec.model.ExperimentResult; import com.aliyun.openservices.pairec.model.ExperimentRoom; import com.aliyun.openservices.pairec.model.Layer; import com.aliyun.openservices.pairec.model.Param; import com.aliyun.openservices.pairec.model.Scene; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.aliyun.openservices.pairec.model.SceneParams; import com.aliyun.openservices.pairec.util.FNV; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
17,459
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) {
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) {
List<ExperimentRoom> experimentRooms = apiClient.getExperimentRoomApi().listExperimentRooms(apiClient.getConfiguration().getEnvironment(),
8
2023-11-29 06:27:36+00:00
24k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/oj/PassportManager.java
[ { "identifier": "StatusAccessDeniedException", "path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusAccessDeniedException.java", "snippet": "public class StatusAccessDeniedException extends Exception {\n\n public StatusAccessDeniedException() {\n }\n\n public StatusAccessDenie...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Validator; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import top.hcode.hoj.common.exception.StatusAccessDeniedException; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.manager.email.EmailManager; import top.hcode.hoj.manager.msg.NoticeManager; import top.hcode.hoj.pojo.bo.EmailRuleBo; import top.hcode.hoj.pojo.dto.LoginDto; import top.hcode.hoj.pojo.dto.RegisterDto; import top.hcode.hoj.pojo.dto.ApplyResetPasswordDto; import top.hcode.hoj.pojo.dto.ResetPasswordDto; import top.hcode.hoj.pojo.entity.user.*; import top.hcode.hoj.pojo.vo.ConfigVo; import top.hcode.hoj.pojo.vo.RegisterCodeVo; import top.hcode.hoj.pojo.vo.UserInfoVo; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.dao.user.SessionEntityService; import top.hcode.hoj.dao.user.UserInfoEntityService; import top.hcode.hoj.dao.user.UserRecordEntityService; import top.hcode.hoj.dao.user.UserRoleEntityService; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.IpUtils; import top.hcode.hoj.utils.JwtUtils; import top.hcode.hoj.utils.RedisUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.stream.Collectors;
16,910
if (tryLoginCount != null) { redisUtils.del(key); } // 异步检查是否异地登录 sessionEntityService.checkRemoteLogin(userRolesVo.getUid()); UserInfoVo userInfoVo = new UserInfoVo(); BeanUtil.copyProperties(userRolesVo, userInfoVo, "roles"); userInfoVo.setRoleList(userRolesVo.getRoles() .stream() .map(Role::getRole) .collect(Collectors.toList())); return userInfoVo; } public RegisterCodeVo getRegisterCode(String email) throws StatusAccessDeniedException, StatusFailException, StatusForbiddenException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } if (!emailManager.isOk()) { throw new StatusAccessDeniedException("对不起!本站邮箱系统未配置,暂不支持注册!"); } email = email.trim(); boolean isEmail = Validator.isEmail(email); if (!isEmail) { throw new StatusFailException("对不起!您的邮箱格式不正确!"); } boolean isBlackEmail = emailRuleBo.getBlackList().stream().anyMatch(email::endsWith); if (isBlackEmail) { throw new StatusForbiddenException("对不起!您的邮箱无法注册本网站!"); } String lockKey = Constants.Email.REGISTER_EMAIL_LOCK + email; if (redisUtils.hasKey(lockKey)) { throw new StatusFailException("对不起,您的操作频率过快,请在" + redisUtils.getExpire(lockKey) + "秒后再次发送注册邮件!"); } QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("email", email); UserInfo userInfo = userInfoEntityService.getOne(queryWrapper, false); if (userInfo != null) { throw new StatusFailException("对不起!该邮箱已被注册,请更换新的邮箱!"); } String numbers = RandomUtil.randomNumbers(6); // 随机生成6位数字的组合 redisUtils.set(Constants.Email.REGISTER_KEY_PREFIX.getValue() + email, numbers, 5 * 60);//默认验证码有效5分钟 emailManager.sendCode(email, numbers); redisUtils.set(lockKey, 0, 60); RegisterCodeVo registerCodeVo = new RegisterCodeVo(); registerCodeVo.setEmail(email); registerCodeVo.setExpire(5 * 60); return registerCodeVo; } @Transactional(rollbackFor = Exception.class) public void register(RegisterDto registerDto) throws StatusAccessDeniedException, StatusFailException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } String codeKey = Constants.Email.REGISTER_KEY_PREFIX.getValue() + registerDto.getEmail(); if (!redisUtils.hasKey(codeKey)) { throw new StatusFailException("验证码不存在或已过期"); } if (!redisUtils.get(codeKey).equals(registerDto.getCode())) { //验证码判断 throw new StatusFailException("验证码不正确"); } if (StringUtils.isEmpty(registerDto.getPassword())) { throw new StatusFailException("密码不能为空"); } if (registerDto.getPassword().length() < 6 || registerDto.getPassword().length() > 20) { throw new StatusFailException("密码长度应该为6~20位!"); } if (StringUtils.isEmpty(registerDto.getUsername())) { throw new StatusFailException("用户名不能为空"); } if (registerDto.getUsername().length() > 20) { throw new StatusFailException("用户名长度不能超过20位!"); } String uuid = IdUtil.simpleUUID(); //为新用户设置uuid registerDto.setUuid(uuid); registerDto.setPassword(SecureUtil.md5(registerDto.getPassword().trim())); // 将密码MD5加密写入数据库 registerDto.setUsername(registerDto.getUsername().trim()); registerDto.setEmail(registerDto.getEmail().trim()); //往user_info表插入数据 boolean addUser = userInfoEntityService.addUser(registerDto); //往user_role表插入数据 boolean addUserRole = userRoleEntityService.save(new UserRole().setRoleId(1002L).setUid(uuid)); //往user_record表插入数据 boolean addUserRecord = userRecordEntityService.save(new UserRecord().setUid(uuid)); if (addUser && addUserRole && addUserRecord) { redisUtils.del(registerDto.getEmail()); noticeManager.syncNoticeToNewRegisterUser(uuid); } else { throw new StatusFailException("注册失败,请稍后重新尝试!"); } }
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 16:46 * @Description: */ @Component public class PassportManager { @Resource private RedisUtils redisUtils; @Resource private JwtUtils jwtUtils; @Resource private ConfigVo configVo; @Resource private EmailRuleBo emailRuleBo; @Resource private UserInfoEntityService userInfoEntityService; @Resource private UserRoleEntityService userRoleEntityService; @Resource private UserRecordEntityService userRecordEntityService; @Resource private SessionEntityService sessionEntityService; @Resource private EmailManager emailManager; @Resource private NoticeManager noticeManager; public UserInfoVo login(LoginDto loginDto, HttpServletResponse response, HttpServletRequest request) throws StatusFailException { // 去掉账号密码首尾的空格 loginDto.setPassword(loginDto.getPassword().trim()); loginDto.setUsername(loginDto.getUsername().trim()); if (StringUtils.isEmpty(loginDto.getUsername()) || StringUtils.isEmpty(loginDto.getPassword())) { throw new StatusFailException("用户名或密码不能为空!"); } if (loginDto.getPassword().length() < 6 || loginDto.getPassword().length() > 20) { throw new StatusFailException("密码长度应该为6~20位!"); } if (loginDto.getUsername().length() > 20) { throw new StatusFailException("用户名长度不能超过20位!"); } String userIpAddr = IpUtils.getUserIpAddr(request); String key = Constants.Account.TRY_LOGIN_NUM.getCode() + loginDto.getUsername() + "_" + userIpAddr; Integer tryLoginCount = (Integer) redisUtils.get(key); if (tryLoginCount != null && tryLoginCount >= 20) { throw new StatusFailException("对不起!登录失败次数过多!您的账号有风险,半个小时内暂时无法登录!"); } UserRolesVo userRolesVo = userRoleEntityService.getUserRoles(null, loginDto.getUsername()); if (userRolesVo == null) { throw new StatusFailException("用户名或密码错误!请注意大小写!"); } if (!userRolesVo.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) { if (tryLoginCount == null) { redisUtils.set(key, 1, 60 * 30); // 三十分钟不尝试,该限制会自动清空消失 } else { redisUtils.set(key, tryLoginCount + 1, 60 * 30); } throw new StatusFailException("用户名或密码错误!请注意大小写!"); } if (userRolesVo.getStatus() != 0) { throw new StatusFailException("该账户已被封禁,请联系管理员进行处理!"); } String jwt = jwtUtils.generateToken(userRolesVo.getUid()); response.setHeader("Authorization", jwt); //放到信息头部 response.setHeader("Access-Control-Expose-Headers", "Authorization"); // 会话记录 sessionEntityService.save(new Session() .setUid(userRolesVo.getUid()) .setIp(IpUtils.getUserIpAddr(request)) .setUserAgent(request.getHeader("User-Agent"))); // 登录成功,清除锁定限制 if (tryLoginCount != null) { redisUtils.del(key); } // 异步检查是否异地登录 sessionEntityService.checkRemoteLogin(userRolesVo.getUid()); UserInfoVo userInfoVo = new UserInfoVo(); BeanUtil.copyProperties(userRolesVo, userInfoVo, "roles"); userInfoVo.setRoleList(userRolesVo.getRoles() .stream() .map(Role::getRole) .collect(Collectors.toList())); return userInfoVo; } public RegisterCodeVo getRegisterCode(String email) throws StatusAccessDeniedException, StatusFailException, StatusForbiddenException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } if (!emailManager.isOk()) { throw new StatusAccessDeniedException("对不起!本站邮箱系统未配置,暂不支持注册!"); } email = email.trim(); boolean isEmail = Validator.isEmail(email); if (!isEmail) { throw new StatusFailException("对不起!您的邮箱格式不正确!"); } boolean isBlackEmail = emailRuleBo.getBlackList().stream().anyMatch(email::endsWith); if (isBlackEmail) { throw new StatusForbiddenException("对不起!您的邮箱无法注册本网站!"); } String lockKey = Constants.Email.REGISTER_EMAIL_LOCK + email; if (redisUtils.hasKey(lockKey)) { throw new StatusFailException("对不起,您的操作频率过快,请在" + redisUtils.getExpire(lockKey) + "秒后再次发送注册邮件!"); } QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("email", email); UserInfo userInfo = userInfoEntityService.getOne(queryWrapper, false); if (userInfo != null) { throw new StatusFailException("对不起!该邮箱已被注册,请更换新的邮箱!"); } String numbers = RandomUtil.randomNumbers(6); // 随机生成6位数字的组合 redisUtils.set(Constants.Email.REGISTER_KEY_PREFIX.getValue() + email, numbers, 5 * 60);//默认验证码有效5分钟 emailManager.sendCode(email, numbers); redisUtils.set(lockKey, 0, 60); RegisterCodeVo registerCodeVo = new RegisterCodeVo(); registerCodeVo.setEmail(email); registerCodeVo.setExpire(5 * 60); return registerCodeVo; } @Transactional(rollbackFor = Exception.class) public void register(RegisterDto registerDto) throws StatusAccessDeniedException, StatusFailException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } String codeKey = Constants.Email.REGISTER_KEY_PREFIX.getValue() + registerDto.getEmail(); if (!redisUtils.hasKey(codeKey)) { throw new StatusFailException("验证码不存在或已过期"); } if (!redisUtils.get(codeKey).equals(registerDto.getCode())) { //验证码判断 throw new StatusFailException("验证码不正确"); } if (StringUtils.isEmpty(registerDto.getPassword())) { throw new StatusFailException("密码不能为空"); } if (registerDto.getPassword().length() < 6 || registerDto.getPassword().length() > 20) { throw new StatusFailException("密码长度应该为6~20位!"); } if (StringUtils.isEmpty(registerDto.getUsername())) { throw new StatusFailException("用户名不能为空"); } if (registerDto.getUsername().length() > 20) { throw new StatusFailException("用户名长度不能超过20位!"); } String uuid = IdUtil.simpleUUID(); //为新用户设置uuid registerDto.setUuid(uuid); registerDto.setPassword(SecureUtil.md5(registerDto.getPassword().trim())); // 将密码MD5加密写入数据库 registerDto.setUsername(registerDto.getUsername().trim()); registerDto.setEmail(registerDto.getEmail().trim()); //往user_info表插入数据 boolean addUser = userInfoEntityService.addUser(registerDto); //往user_role表插入数据 boolean addUserRole = userRoleEntityService.save(new UserRole().setRoleId(1002L).setUid(uuid)); //往user_record表插入数据 boolean addUserRecord = userRecordEntityService.save(new UserRecord().setUid(uuid)); if (addUser && addUserRole && addUserRecord) { redisUtils.del(registerDto.getEmail()); noticeManager.syncNoticeToNewRegisterUser(uuid); } else { throw new StatusFailException("注册失败,请稍后重新尝试!"); } }
public void applyResetPassword(ApplyResetPasswordDto applyResetPasswordDto) throws StatusFailException {
8
2023-12-03 14:15:51+00:00
24k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/ControlRoomController.java
[ { "identifier": "App", "path": "src/main/java/nz/ac/auckland/se206/App.java", "snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController...
import java.io.IOException; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import javafx.util.Duration; import nz.ac.auckland.se206.App; import nz.ac.auckland.se206.GameState; import nz.ac.auckland.se206.SceneManager.AppUi; import nz.ac.auckland.se206.TextToSpeechManager; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.GptPromptEngineering; import nz.ac.auckland.se206.gpt.openai.ApiProxyException; import nz.ac.auckland.se206.gpt.openai.ChatCompletionRequest; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice;
16,465
package nz.ac.auckland.se206.controllers; /** Controller class for the Control Room. */ public class ControlRoomController { static ControlRoomController instance; @FXML private AnchorPane contentPane; @FXML private ImageView computer; @FXML private ImageView keypad; @FXML private ImageView exitDoor; @FXML private ImageView rightArrow; @FXML private ImageView rightGlowArrow; @FXML private ImageView leftArrow; @FXML private ImageView leftGlowArrow; @FXML private ImageView computerGlow; @FXML private ImageView exitGlow; @FXML private ImageView keypadGlow; @FXML private ImageView character; @FXML private ImageView running; @FXML private AnchorPane room; @FXML private HBox dialogueHorizontalBox; @FXML private Pane inventoryPane; @FXML private VBox hintVerticalBox; @FXML private VBox bottomVerticalBox; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Circle rightDoorMarker; @FXML private Circle leftDoorMarker; @FXML private Circle computerMarker; @FXML private Circle keypadMarker; @FXML private Circle centerDoorMarker; @FXML private Button muteButton; // elements of keypad @FXML private AnchorPane keyPadAnchorPane; @FXML private TextField codeText; // elements of computer @FXML private AnchorPane computerAnchorPane; @FXML private AnchorPane computerLoginAnchorPane; @FXML private Label gptLabel; @FXML private Button enterButton; @FXML private TextField inputText; @FXML private AnchorPane computerSignedInAnchorPane; @FXML private ImageView computerDocumentIcon; @FXML private ImageView computerPrintIcon; @FXML private ImageView computerCatsIcon; @FXML private Image document = new Image("images/Computer/document.png"); @FXML private Image print = new Image("images/Computer/printer.png"); @FXML private Image cats = new Image("images/Computer/image.png"); @FXML private Image documentHover = new Image("images/Computer/document_hover.png"); @FXML private Image printHover = new Image("images/Computer/printer_hover.png"); @FXML private Image catsHover = new Image("images/Computer/image_hover.png"); @FXML private AnchorPane computerPrintWindowAnchorPane; @FXML private ImageView printIcon; @FXML private ImageView printIconComplete; @FXML private Button printButton; @FXML private Label printLabel; @FXML private AnchorPane computerTextWindowAnchorPane; @FXML private TextArea computerDoorCodeTextArea; @FXML private AnchorPane computerImageWindowAnchorPane; @FXML private Label riddleLabel; private String code = ""; private ChatCompletionRequest endingChatCompletionRequest; private ChatCompletionRequest computerChatCompletionRequest; private boolean firstOpeningTextFile; /** This method initializes the control room for when the user first enters it. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // computer initialization firstOpeningTextFile = true; try { computerChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); runGpt( new ChatMessage("user", GptPromptEngineering.getRiddle(GameState.getRiddleAnswer())), true); computerDoorCodeTextArea.setText( "TOP SECRET DOOR CODE: \n\n__" + GameState.getSecondDigits() + "__\n\n\n\n" + "(If only I could remember the other four digits)"); } catch (Exception e) { e.printStackTrace(); } GameState.goToInstant( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); instance = this; } /** * Handles the click event on the computer. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML private void clickComputer(MouseEvent event) throws IOException { System.out.println("computer clicked"); try { // move character to clicked location GameState.goTo(computerMarker.getLayoutX(), computerMarker.getLayoutY(), character, running); // flag the current puzzle as the computer puzzle for hints // set root to the computer // enable movement after delay Runnable accessComputer = () -> { GameState.setPuzzleComputer(); computerAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessComputer); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to computer when hover @FXML private void onComputerHovered(MouseEvent event) { computerGlow.setVisible(true); } @FXML private void onComputerUnhovered(MouseEvent event) { computerGlow.setVisible(false); } /** * Handles the click event on the exit door. * * @param event the mouse event */ @FXML private void clickExit(MouseEvent event) { try { // move character to center door marker position GameState.goTo( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); Runnable leaveRoom = () -> { System.out.println("exit door clicked"); if (GameState.isExitUnlocked) { // if the exit is unlocked, fade to black for ending scene
package nz.ac.auckland.se206.controllers; /** Controller class for the Control Room. */ public class ControlRoomController { static ControlRoomController instance; @FXML private AnchorPane contentPane; @FXML private ImageView computer; @FXML private ImageView keypad; @FXML private ImageView exitDoor; @FXML private ImageView rightArrow; @FXML private ImageView rightGlowArrow; @FXML private ImageView leftArrow; @FXML private ImageView leftGlowArrow; @FXML private ImageView computerGlow; @FXML private ImageView exitGlow; @FXML private ImageView keypadGlow; @FXML private ImageView character; @FXML private ImageView running; @FXML private AnchorPane room; @FXML private HBox dialogueHorizontalBox; @FXML private Pane inventoryPane; @FXML private VBox hintVerticalBox; @FXML private VBox bottomVerticalBox; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Circle rightDoorMarker; @FXML private Circle leftDoorMarker; @FXML private Circle computerMarker; @FXML private Circle keypadMarker; @FXML private Circle centerDoorMarker; @FXML private Button muteButton; // elements of keypad @FXML private AnchorPane keyPadAnchorPane; @FXML private TextField codeText; // elements of computer @FXML private AnchorPane computerAnchorPane; @FXML private AnchorPane computerLoginAnchorPane; @FXML private Label gptLabel; @FXML private Button enterButton; @FXML private TextField inputText; @FXML private AnchorPane computerSignedInAnchorPane; @FXML private ImageView computerDocumentIcon; @FXML private ImageView computerPrintIcon; @FXML private ImageView computerCatsIcon; @FXML private Image document = new Image("images/Computer/document.png"); @FXML private Image print = new Image("images/Computer/printer.png"); @FXML private Image cats = new Image("images/Computer/image.png"); @FXML private Image documentHover = new Image("images/Computer/document_hover.png"); @FXML private Image printHover = new Image("images/Computer/printer_hover.png"); @FXML private Image catsHover = new Image("images/Computer/image_hover.png"); @FXML private AnchorPane computerPrintWindowAnchorPane; @FXML private ImageView printIcon; @FXML private ImageView printIconComplete; @FXML private Button printButton; @FXML private Label printLabel; @FXML private AnchorPane computerTextWindowAnchorPane; @FXML private TextArea computerDoorCodeTextArea; @FXML private AnchorPane computerImageWindowAnchorPane; @FXML private Label riddleLabel; private String code = ""; private ChatCompletionRequest endingChatCompletionRequest; private ChatCompletionRequest computerChatCompletionRequest; private boolean firstOpeningTextFile; /** This method initializes the control room for when the user first enters it. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // computer initialization firstOpeningTextFile = true; try { computerChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); runGpt( new ChatMessage("user", GptPromptEngineering.getRiddle(GameState.getRiddleAnswer())), true); computerDoorCodeTextArea.setText( "TOP SECRET DOOR CODE: \n\n__" + GameState.getSecondDigits() + "__\n\n\n\n" + "(If only I could remember the other four digits)"); } catch (Exception e) { e.printStackTrace(); } GameState.goToInstant( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); instance = this; } /** * Handles the click event on the computer. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML private void clickComputer(MouseEvent event) throws IOException { System.out.println("computer clicked"); try { // move character to clicked location GameState.goTo(computerMarker.getLayoutX(), computerMarker.getLayoutY(), character, running); // flag the current puzzle as the computer puzzle for hints // set root to the computer // enable movement after delay Runnable accessComputer = () -> { GameState.setPuzzleComputer(); computerAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessComputer); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to computer when hover @FXML private void onComputerHovered(MouseEvent event) { computerGlow.setVisible(true); } @FXML private void onComputerUnhovered(MouseEvent event) { computerGlow.setVisible(false); } /** * Handles the click event on the exit door. * * @param event the mouse event */ @FXML private void clickExit(MouseEvent event) { try { // move character to center door marker position GameState.goTo( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); Runnable leaveRoom = () -> { System.out.println("exit door clicked"); if (GameState.isExitUnlocked) { // if the exit is unlocked, fade to black for ending scene
TextToSpeechManager.cutOff();
3
2023-12-02 04:57:43+00:00
24k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkServiceImpl.java
[ { "identifier": "ClientException", "path": "project/src/main/java/com/nageoffer/shortlink/project/common/convention/exception/ClientException.java", "snippet": "public class ClientException extends AbstractException {\n\n public ClientException(IErrorCode errorCode) {\n this(null, null, errorC...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.Week; import cn.hutool.core.lang.UUID; import cn.hutool.core.text.StrBuilder; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.nageoffer.shortlink.project.common.convention.exception.ClientException; import com.nageoffer.shortlink.project.common.convention.exception.ServiceException; import com.nageoffer.shortlink.project.common.enums.VailDateTypeEnum; import com.nageoffer.shortlink.project.config.GotoDomainWhiteListConfiguration; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkBrowserStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkOsStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkStatsTodayDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkGotoDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkStatsTodayMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkGotoMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkMapper; import com.nageoffer.shortlink.project.dto.biz.ShortLinkStatsRecordDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkBatchCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkPageReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkUpdateReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBaseInfoRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBatchCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkGroupCountQueryRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.project.mq.producer.DelayShortLinkStatsProducer; import com.nageoffer.shortlink.project.service.LinkStatsTodayService; import com.nageoffer.shortlink.project.service.ShortLinkService; import com.nageoffer.shortlink.project.toolkit.HashUtil; import com.nageoffer.shortlink.project.toolkit.LinkUtil; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.redisson.api.RBloomFilter; import org.redisson.api.RLock; import org.redisson.api.RReadWriteLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DuplicateKeyException; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_IS_NULL_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GID_UPDATE_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.ShortLinkConstant.AMAP_REMOTE_URL;
17,618
.originUrl(requestParam.getOriginUrl()) .gid(requestParam.getGid()) .build(); } @Override public ShortLinkBatchCreateRespDTO batchCreateShortLink(ShortLinkBatchCreateReqDTO requestParam) { List<String> originUrls = requestParam.getOriginUrls(); List<String> describes = requestParam.getDescribes(); List<ShortLinkBaseInfoRespDTO> result = new ArrayList<>(); for (int i = 0; i < originUrls.size(); i++) { ShortLinkCreateReqDTO shortLinkCreateReqDTO = BeanUtil.toBean(requestParam, ShortLinkCreateReqDTO.class); shortLinkCreateReqDTO.setOriginUrl(originUrls.get(i)); shortLinkCreateReqDTO.setDescribe(describes.get(i)); try { ShortLinkCreateRespDTO shortLink = createShortLink(shortLinkCreateReqDTO); ShortLinkBaseInfoRespDTO linkBaseInfoRespDTO = ShortLinkBaseInfoRespDTO.builder() .fullShortUrl(shortLink.getFullShortUrl()) .originUrl(shortLink.getOriginUrl()) .describe(describes.get(i)) .build(); result.add(linkBaseInfoRespDTO); } catch (Throwable ex) { log.error("批量创建短链接失败,原始参数:{}", originUrls.get(i)); } } return ShortLinkBatchCreateRespDTO.builder() .total(result.size()) .baseLinkInfos(result) .build(); } @Transactional(rollbackFor = Exception.class) @Override public void updateShortLink(ShortLinkUpdateReqDTO requestParam) { verificationWhitelist(requestParam.getOriginUrl()); LambdaQueryWrapper<ShortLinkDO> queryWrapper = Wrappers.lambdaQuery(ShortLinkDO.class) .eq(ShortLinkDO::getGid, requestParam.getOriginGid()) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getEnableStatus, 0); ShortLinkDO hasShortLinkDO = baseMapper.selectOne(queryWrapper); if (hasShortLinkDO == null) { throw new ClientException("短链接记录不存在"); } if (Objects.equals(hasShortLinkDO.getGid(), requestParam.getGid())) { LambdaUpdateWrapper<ShortLinkDO> updateWrapper = Wrappers.lambdaUpdate(ShortLinkDO.class) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getGid, requestParam.getGid()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getEnableStatus, 0) .set(Objects.equals(requestParam.getValidDateType(), VailDateTypeEnum.PERMANENT.getType()), ShortLinkDO::getValidDate, null); ShortLinkDO shortLinkDO = ShortLinkDO.builder() .domain(hasShortLinkDO.getDomain()) .shortUri(hasShortLinkDO.getShortUri()) .favicon(hasShortLinkDO.getFavicon()) .createdType(hasShortLinkDO.getCreatedType()) .gid(requestParam.getGid()) .originUrl(requestParam.getOriginUrl()) .describe(requestParam.getDescribe()) .validDateType(requestParam.getValidDateType()) .validDate(requestParam.getValidDate()) .build(); baseMapper.update(shortLinkDO, updateWrapper); } else { RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(String.format(LOCK_GID_UPDATE_KEY, requestParam.getFullShortUrl())); RLock rLock = readWriteLock.writeLock(); if (!rLock.tryLock()) { throw new ServiceException("短链接正在被访问,请稍后再试..."); } try { LambdaUpdateWrapper<ShortLinkDO> linkUpdateWrapper = Wrappers.lambdaUpdate(ShortLinkDO.class) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getGid, hasShortLinkDO.getGid()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getDelTime, 0L) .eq(ShortLinkDO::getEnableStatus, 0); ShortLinkDO delShortLinkDO = ShortLinkDO.builder() .delTime(System.currentTimeMillis()) .build(); delShortLinkDO.setDelFlag(1); baseMapper.update(delShortLinkDO, linkUpdateWrapper); ShortLinkDO shortLinkDO = ShortLinkDO.builder() .domain(createShortLinkDefaultDomain) .originUrl(requestParam.getOriginUrl()) .gid(requestParam.getGid()) .createdType(hasShortLinkDO.getCreatedType()) .validDateType(requestParam.getValidDateType()) .validDate(requestParam.getValidDate()) .describe(requestParam.getDescribe()) .shortUri(hasShortLinkDO.getShortUri()) .enableStatus(hasShortLinkDO.getEnableStatus()) .totalPv(hasShortLinkDO.getTotalPv()) .totalUv(hasShortLinkDO.getTotalUv()) .totalUip(hasShortLinkDO.getTotalUip()) .fullShortUrl(hasShortLinkDO.getFullShortUrl()) .favicon(getFavicon(requestParam.getOriginUrl())) .delTime(0L) .build(); baseMapper.insert(shortLinkDO); LambdaQueryWrapper<LinkStatsTodayDO> statsTodayQueryWrapper = Wrappers.lambdaQuery(LinkStatsTodayDO.class) .eq(LinkStatsTodayDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(LinkStatsTodayDO::getGid, hasShortLinkDO.getGid()) .eq(LinkStatsTodayDO::getDelFlag, 0); List<LinkStatsTodayDO> linkStatsTodayDOList = linkStatsTodayMapper.selectList(statsTodayQueryWrapper); if (CollUtil.isNotEmpty(linkStatsTodayDOList)) { linkStatsTodayMapper.deleteBatchIds(linkStatsTodayDOList.stream() .map(LinkStatsTodayDO::getId) .toList() ); linkStatsTodayDOList.forEach(each -> each.setGid(requestParam.getGid())); linkStatsTodayService.saveBatch(linkStatsTodayDOList); } LambdaQueryWrapper<ShortLinkGotoDO> linkGotoQueryWrapper = Wrappers.lambdaQuery(ShortLinkGotoDO.class) .eq(ShortLinkGotoDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkGotoDO::getGid, hasShortLinkDO.getGid()); ShortLinkGotoDO shortLinkGotoDO = shortLinkGotoMapper.selectOne(linkGotoQueryWrapper); shortLinkGotoMapper.deleteById(shortLinkGotoDO.getId()); shortLinkGotoDO.setGid(requestParam.getGid()); shortLinkGotoMapper.insert(shortLinkGotoDO);
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService { private final RBloomFilter<String> shortUriCreateCachePenetrationBloomFilter; private final ShortLinkGotoMapper shortLinkGotoMapper; private final StringRedisTemplate stringRedisTemplate; private final RedissonClient redissonClient; private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; private final LinkStatsTodayMapper linkStatsTodayMapper; private final LinkStatsTodayService linkStatsTodayService; private final DelayShortLinkStatsProducer delayShortLinkStatsProducer; private final GotoDomainWhiteListConfiguration gotoDomainWhiteListConfiguration; @Value("${short-link.stats.locale.amap-key}") private String statsLocaleAmapKey; @Value("${short-link.domain.default}") private String createShortLinkDefaultDomain; @Override public ShortLinkCreateRespDTO createShortLink(ShortLinkCreateReqDTO requestParam) { verificationWhitelist(requestParam.getOriginUrl()); String shortLinkSuffix = generateSuffix(requestParam); String fullShortUrl = StrBuilder.create(createShortLinkDefaultDomain) .append("/") .append(shortLinkSuffix) .toString(); ShortLinkDO shortLinkDO = ShortLinkDO.builder() .domain(createShortLinkDefaultDomain) .originUrl(requestParam.getOriginUrl()) .gid(requestParam.getGid()) .createdType(requestParam.getCreatedType()) .validDateType(requestParam.getValidDateType()) .validDate(requestParam.getValidDate()) .describe(requestParam.getDescribe()) .shortUri(shortLinkSuffix) .enableStatus(0) .totalPv(0) .totalUv(0) .totalUip(0) .delTime(0L) .fullShortUrl(fullShortUrl) .favicon(getFavicon(requestParam.getOriginUrl())) .build(); ShortLinkGotoDO linkGotoDO = ShortLinkGotoDO.builder() .fullShortUrl(fullShortUrl) .gid(requestParam.getGid()) .build(); try { baseMapper.insert(shortLinkDO); shortLinkGotoMapper.insert(linkGotoDO); } catch (DuplicateKeyException ex) { LambdaQueryWrapper<ShortLinkDO> queryWrapper = Wrappers.lambdaQuery(ShortLinkDO.class) .eq(ShortLinkDO::getFullShortUrl, fullShortUrl); ShortLinkDO hasShortLinkDO = baseMapper.selectOne(queryWrapper); if (hasShortLinkDO != null) { log.warn("短链接:{} 重复入库", fullShortUrl); throw new ServiceException("短链接生成重复"); } } stringRedisTemplate.opsForValue().set( String.format(GOTO_SHORT_LINK_KEY, fullShortUrl), requestParam.getOriginUrl(), LinkUtil.getLinkCacheValidTime(requestParam.getValidDate()), TimeUnit.MILLISECONDS ); shortUriCreateCachePenetrationBloomFilter.add(fullShortUrl); return ShortLinkCreateRespDTO.builder() .fullShortUrl("http://" + shortLinkDO.getFullShortUrl()) .originUrl(requestParam.getOriginUrl()) .gid(requestParam.getGid()) .build(); } @Override public ShortLinkBatchCreateRespDTO batchCreateShortLink(ShortLinkBatchCreateReqDTO requestParam) { List<String> originUrls = requestParam.getOriginUrls(); List<String> describes = requestParam.getDescribes(); List<ShortLinkBaseInfoRespDTO> result = new ArrayList<>(); for (int i = 0; i < originUrls.size(); i++) { ShortLinkCreateReqDTO shortLinkCreateReqDTO = BeanUtil.toBean(requestParam, ShortLinkCreateReqDTO.class); shortLinkCreateReqDTO.setOriginUrl(originUrls.get(i)); shortLinkCreateReqDTO.setDescribe(describes.get(i)); try { ShortLinkCreateRespDTO shortLink = createShortLink(shortLinkCreateReqDTO); ShortLinkBaseInfoRespDTO linkBaseInfoRespDTO = ShortLinkBaseInfoRespDTO.builder() .fullShortUrl(shortLink.getFullShortUrl()) .originUrl(shortLink.getOriginUrl()) .describe(describes.get(i)) .build(); result.add(linkBaseInfoRespDTO); } catch (Throwable ex) { log.error("批量创建短链接失败,原始参数:{}", originUrls.get(i)); } } return ShortLinkBatchCreateRespDTO.builder() .total(result.size()) .baseLinkInfos(result) .build(); } @Transactional(rollbackFor = Exception.class) @Override public void updateShortLink(ShortLinkUpdateReqDTO requestParam) { verificationWhitelist(requestParam.getOriginUrl()); LambdaQueryWrapper<ShortLinkDO> queryWrapper = Wrappers.lambdaQuery(ShortLinkDO.class) .eq(ShortLinkDO::getGid, requestParam.getOriginGid()) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getEnableStatus, 0); ShortLinkDO hasShortLinkDO = baseMapper.selectOne(queryWrapper); if (hasShortLinkDO == null) { throw new ClientException("短链接记录不存在"); } if (Objects.equals(hasShortLinkDO.getGid(), requestParam.getGid())) { LambdaUpdateWrapper<ShortLinkDO> updateWrapper = Wrappers.lambdaUpdate(ShortLinkDO.class) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getGid, requestParam.getGid()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getEnableStatus, 0) .set(Objects.equals(requestParam.getValidDateType(), VailDateTypeEnum.PERMANENT.getType()), ShortLinkDO::getValidDate, null); ShortLinkDO shortLinkDO = ShortLinkDO.builder() .domain(hasShortLinkDO.getDomain()) .shortUri(hasShortLinkDO.getShortUri()) .favicon(hasShortLinkDO.getFavicon()) .createdType(hasShortLinkDO.getCreatedType()) .gid(requestParam.getGid()) .originUrl(requestParam.getOriginUrl()) .describe(requestParam.getDescribe()) .validDateType(requestParam.getValidDateType()) .validDate(requestParam.getValidDate()) .build(); baseMapper.update(shortLinkDO, updateWrapper); } else { RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(String.format(LOCK_GID_UPDATE_KEY, requestParam.getFullShortUrl())); RLock rLock = readWriteLock.writeLock(); if (!rLock.tryLock()) { throw new ServiceException("短链接正在被访问,请稍后再试..."); } try { LambdaUpdateWrapper<ShortLinkDO> linkUpdateWrapper = Wrappers.lambdaUpdate(ShortLinkDO.class) .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkDO::getGid, hasShortLinkDO.getGid()) .eq(ShortLinkDO::getDelFlag, 0) .eq(ShortLinkDO::getDelTime, 0L) .eq(ShortLinkDO::getEnableStatus, 0); ShortLinkDO delShortLinkDO = ShortLinkDO.builder() .delTime(System.currentTimeMillis()) .build(); delShortLinkDO.setDelFlag(1); baseMapper.update(delShortLinkDO, linkUpdateWrapper); ShortLinkDO shortLinkDO = ShortLinkDO.builder() .domain(createShortLinkDefaultDomain) .originUrl(requestParam.getOriginUrl()) .gid(requestParam.getGid()) .createdType(hasShortLinkDO.getCreatedType()) .validDateType(requestParam.getValidDateType()) .validDate(requestParam.getValidDate()) .describe(requestParam.getDescribe()) .shortUri(hasShortLinkDO.getShortUri()) .enableStatus(hasShortLinkDO.getEnableStatus()) .totalPv(hasShortLinkDO.getTotalPv()) .totalUv(hasShortLinkDO.getTotalUv()) .totalUip(hasShortLinkDO.getTotalUip()) .fullShortUrl(hasShortLinkDO.getFullShortUrl()) .favicon(getFavicon(requestParam.getOriginUrl())) .delTime(0L) .build(); baseMapper.insert(shortLinkDO); LambdaQueryWrapper<LinkStatsTodayDO> statsTodayQueryWrapper = Wrappers.lambdaQuery(LinkStatsTodayDO.class) .eq(LinkStatsTodayDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(LinkStatsTodayDO::getGid, hasShortLinkDO.getGid()) .eq(LinkStatsTodayDO::getDelFlag, 0); List<LinkStatsTodayDO> linkStatsTodayDOList = linkStatsTodayMapper.selectList(statsTodayQueryWrapper); if (CollUtil.isNotEmpty(linkStatsTodayDOList)) { linkStatsTodayMapper.deleteBatchIds(linkStatsTodayDOList.stream() .map(LinkStatsTodayDO::getId) .toList() ); linkStatsTodayDOList.forEach(each -> each.setGid(requestParam.getGid())); linkStatsTodayService.saveBatch(linkStatsTodayDOList); } LambdaQueryWrapper<ShortLinkGotoDO> linkGotoQueryWrapper = Wrappers.lambdaQuery(ShortLinkGotoDO.class) .eq(ShortLinkGotoDO::getFullShortUrl, requestParam.getFullShortUrl()) .eq(ShortLinkGotoDO::getGid, hasShortLinkDO.getGid()); ShortLinkGotoDO shortLinkGotoDO = shortLinkGotoMapper.selectOne(linkGotoQueryWrapper); shortLinkGotoMapper.deleteById(shortLinkGotoDO.getId()); shortLinkGotoDO.setGid(requestParam.getGid()); shortLinkGotoMapper.insert(shortLinkGotoDO);
LambdaUpdateWrapper<LinkAccessStatsDO> linkAccessStatsUpdateWrapper = Wrappers.lambdaUpdate(LinkAccessStatsDO.class)
5
2023-11-19 16:04:32+00:00
24k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/ParamParser.java
[ { "identifier": "ProxyConfigLoader", "path": "src/main/java/com/ly/ckibana/configure/config/ProxyConfigLoader.java", "snippet": "@Component\n@Slf4j\npublic class ProxyConfigLoader {\n\n private ProxyConfig proxyConfig;\n\n @Getter\n private RestClient metadataRestClient;\n\n private String k...
import com.alibaba.fastjson2.JSONObject; import com.google.common.base.Strings; import com.ly.ckibana.configure.config.ProxyConfigLoader; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.model.compute.Range; import com.ly.ckibana.model.compute.aggregation.AggsParam; import com.ly.ckibana.model.compute.indexpattern.IndexPattern; import com.ly.ckibana.model.enums.AggBucketsName; import com.ly.ckibana.model.enums.AggType; import com.ly.ckibana.model.exception.UnSupportAggsTypeException; import com.ly.ckibana.model.property.KibanaItemProperty; import com.ly.ckibana.model.property.QueryProperty; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.model.request.RequestContext; import com.ly.ckibana.model.response.IndexPatternFields; import com.ly.ckibana.service.CkService; import com.ly.ckibana.strategy.aggs.Aggregation; import com.ly.ckibana.strategy.aggs.helper.FiltersAggsStrategyHelpler; import com.ly.ckibana.util.DateUtils; import com.ly.ckibana.util.JSONUtils; import com.ly.ckibana.util.ProxyUtils; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import ru.yandex.clickhouse.BalancedClickhouseDataSource; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
18,899
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.parser; /** * 解析参数类. * * @author quzhihao */ @Slf4j @Service public class ParamParser { private static final String KEYED = "keyed"; private static final String FIELD = "field"; @Resource private ProxyConfigLoader proxyConfigLoader; @Resource private CkService ckService; @Resource private List<Aggregation> aggStrategyList; @Resource private FiltersAggsStrategyHelpler filtersAggsStrategyHelpler; @Setter private Map<AggType, Aggregation> aggStrategyMap; @PostConstruct public void init() { aggStrategyMap = new HashMap<>(aggStrategyList.size()); aggStrategyList.forEach(each -> aggStrategyMap.put(each.getAggType(), each)); } /** * 基于入口参数,解析indexPattern信息. * 远程集群名(数据库__集群业务名称):索引名 如businesslog__log:anquan_dns-* * 兼容原有es业务,需要default库名 */
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.parser; /** * 解析参数类. * * @author quzhihao */ @Slf4j @Service public class ParamParser { private static final String KEYED = "keyed"; private static final String FIELD = "field"; @Resource private ProxyConfigLoader proxyConfigLoader; @Resource private CkService ckService; @Resource private List<Aggregation> aggStrategyList; @Resource private FiltersAggsStrategyHelpler filtersAggsStrategyHelpler; @Setter private Map<AggType, Aggregation> aggStrategyMap; @PostConstruct public void init() { aggStrategyMap = new HashMap<>(aggStrategyList.size()); aggStrategyList.forEach(each -> aggStrategyMap.put(each.getAggType(), each)); } /** * 基于入口参数,解析indexPattern信息. * 远程集群名(数据库__集群业务名称):索引名 如businesslog__log:anquan_dns-* * 兼容原有es业务,需要default库名 */
public IndexPattern buildIndexPattern(RequestContext context) {
4
2023-11-21 09:12:07+00:00
24k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/poptables/PopConfirmLoad.java
[ { "identifier": "Listeners", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/Listeners.java", "snippet": "public class Listeners {\n public static SystemCursorListener handListener;\n public static SystemCursorListener handListenerIgnoreDisabled;\n public static SystemCursorListener ibe...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle; import com.badlogic.gdx.utils.Align; import com.ray3k.gdxparticleeditor.Listeners; import com.ray3k.gdxparticleeditor.Utils; import com.ray3k.stripe.PopTable; import static com.ray3k.gdxparticleeditor.Core.foregroundStage; import static com.ray3k.gdxparticleeditor.Core.skin; import static com.ray3k.gdxparticleeditor.Listeners.*; import static com.ray3k.gdxparticleeditor.Listeners.addHandListener; import static com.ray3k.gdxparticleeditor.Listeners.onChange;
16,543
package com.ray3k.gdxparticleeditor.widgets.poptables; /** * PopTable used to display errors during runtime that can be recovered from. These are typically file errors when * saving or opening particles and images. A link to the log directory enables users to retrieve the crash log file * through their OS file explorer. */ public class PopConfirmLoad extends PopTable { private final InputProcessor previousInputProcessor; private Runnable runnableSave; private Runnable runnableDiscard; public PopConfirmLoad(Runnable runnableSave, Runnable runnableDiscard) {
package com.ray3k.gdxparticleeditor.widgets.poptables; /** * PopTable used to display errors during runtime that can be recovered from. These are typically file errors when * saving or opening particles and images. A link to the log directory enables users to retrieve the crash log file * through their OS file explorer. */ public class PopConfirmLoad extends PopTable { private final InputProcessor previousInputProcessor; private Runnable runnableSave; private Runnable runnableDiscard; public PopConfirmLoad(Runnable runnableSave, Runnable runnableDiscard) {
super(skin.get(WindowStyle.class));
4
2023-11-24 15:58:20+00:00
24k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/service_impl/internal/PointsMallGoodsSpecificationServiceImpl.java
[ { "identifier": "PointsMallGoodsSpecification", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/entity/internal/PointsMallGoodsSpecification.java", "snippet": "@Data\n@TableName(\"tb_points_mall_goods_specification\")\n@ApiModel(value = \"商品规格表\")\npublic class Points...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecification; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecificationOption; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationMapper; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationOptionMapper; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationDto; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationOptionDto; import com.siam.system.modular.package_goods.model.example.internal.PointsMallGoodsSpecificationExample; import com.siam.system.modular.package_goods.service.internal.PointsMallGoodsSpecificationService; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationMapper; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationOptionMapper; import com.siam.system.modular.package_goods.service.internal.PointsMallGoodsSpecificationService; import com.siam.package_common.exception.StoneCustomerException; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationDto; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationOptionDto; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecification; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecificationOption; import com.siam.system.modular.package_goods.model.example.internal.PointsMallGoodsSpecificationExample; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map;
19,115
package com.siam.system.modular.package_goods.service_impl.internal; @Service public class PointsMallGoodsSpecificationServiceImpl implements PointsMallGoodsSpecificationService { @Autowired private PointsMallGoodsSpecificationMapper goodsSpecificationMapper; @Autowired private PointsMallGoodsSpecificationOptionMapper goodsSpecificationOptionMapper; public int countByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.countByExample(example); } public void deleteByPrimaryKey(Integer id){ goodsSpecificationMapper.deleteByPrimaryKey(id); } public void insertSelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.insertSelective(record); } public List<PointsMallGoodsSpecification> selectByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.selectByExample(example); } public PointsMallGoodsSpecification selectByPrimaryKey(Integer id){ return goodsSpecificationMapper.selectByPrimaryKey(id); } public void updateByExampleSelective(PointsMallGoodsSpecification record, PointsMallGoodsSpecificationExample example){ goodsSpecificationMapper.updateByExampleSelective(record, example); } public void updateByPrimaryKeySelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.updateByPrimaryKeySelective(record); } public Page<PointsMallGoodsSpecification> getListByPage(int pageNo, int pageSize, PointsMallGoodsSpecification goodsSpecification) { Page<PointsMallGoodsSpecification> page = goodsSpecificationMapper.getListByPage(new Page(pageNo, pageSize), goodsSpecification); return page; } @Override public Page<Map<String, Object>> getListByPageJoinPointsMallGoods(int pageNo, int pageSize, PointsMallGoodsSpecificationDto goodsSpecificationDto) { Page<Map<String, Object>> page = goodsSpecificationMapper.getListByPageJoinPointsMallGoods(goodsSpecificationDto); return page; } @Override public int selectMaxSortNumberByPointsMallGoodsId(Integer goodsId) { return goodsSpecificationMapper.selectMaxSortNumberByPointsMallGoodsId(goodsId); } @Override public PointsMallGoodsSpecification selectByPointsMallGoodsIdAndName(Integer goodsId, String name) { return goodsSpecificationMapper.selectByPointsMallGoodsIdAndName(goodsId, name); } @Override public void insertPublicGoodsSpecification(int goodsId) { //如果商品已经有规格,则不能生成,避免重复插入 PointsMallGoodsSpecificationExample goodsSpecificationExample = new PointsMallGoodsSpecificationExample(); goodsSpecificationExample.createCriteria().andPointsMallGoodsIdEqualTo(goodsId); int result = goodsSpecificationMapper.countByExample(goodsSpecificationExample); if(result > 0){
package com.siam.system.modular.package_goods.service_impl.internal; @Service public class PointsMallGoodsSpecificationServiceImpl implements PointsMallGoodsSpecificationService { @Autowired private PointsMallGoodsSpecificationMapper goodsSpecificationMapper; @Autowired private PointsMallGoodsSpecificationOptionMapper goodsSpecificationOptionMapper; public int countByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.countByExample(example); } public void deleteByPrimaryKey(Integer id){ goodsSpecificationMapper.deleteByPrimaryKey(id); } public void insertSelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.insertSelective(record); } public List<PointsMallGoodsSpecification> selectByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.selectByExample(example); } public PointsMallGoodsSpecification selectByPrimaryKey(Integer id){ return goodsSpecificationMapper.selectByPrimaryKey(id); } public void updateByExampleSelective(PointsMallGoodsSpecification record, PointsMallGoodsSpecificationExample example){ goodsSpecificationMapper.updateByExampleSelective(record, example); } public void updateByPrimaryKeySelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.updateByPrimaryKeySelective(record); } public Page<PointsMallGoodsSpecification> getListByPage(int pageNo, int pageSize, PointsMallGoodsSpecification goodsSpecification) { Page<PointsMallGoodsSpecification> page = goodsSpecificationMapper.getListByPage(new Page(pageNo, pageSize), goodsSpecification); return page; } @Override public Page<Map<String, Object>> getListByPageJoinPointsMallGoods(int pageNo, int pageSize, PointsMallGoodsSpecificationDto goodsSpecificationDto) { Page<Map<String, Object>> page = goodsSpecificationMapper.getListByPageJoinPointsMallGoods(goodsSpecificationDto); return page; } @Override public int selectMaxSortNumberByPointsMallGoodsId(Integer goodsId) { return goodsSpecificationMapper.selectMaxSortNumberByPointsMallGoodsId(goodsId); } @Override public PointsMallGoodsSpecification selectByPointsMallGoodsIdAndName(Integer goodsId, String name) { return goodsSpecificationMapper.selectByPointsMallGoodsIdAndName(goodsId, name); } @Override public void insertPublicGoodsSpecification(int goodsId) { //如果商品已经有规格,则不能生成,避免重复插入 PointsMallGoodsSpecificationExample goodsSpecificationExample = new PointsMallGoodsSpecificationExample(); goodsSpecificationExample.createCriteria().andPointsMallGoodsIdEqualTo(goodsId); int result = goodsSpecificationMapper.countByExample(goodsSpecificationExample); if(result > 0){
throw new StoneCustomerException("商品已存在其他规格,生成失败");
11
2023-11-26 12:41:06+00:00
24k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/building/BuildingRoomAdapter.java
[ { "identifier": "AbstractUnoccupiedSpaceAdapter", "path": "citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/core/AbstractUnoccupiedSpaceAdapter.java", "snippet": "public abstract class AbstractUnoccupiedSpaceAdapter<T extends AbstractUnoccupiedSpace> extends AbstractPhysicalSpaceAdapter<T> ...
import org.citydb.io.citygml.adapter.core.AbstractUnoccupiedSpaceAdapter; import org.citydb.io.citygml.adapter.geometry.builder.Lod; import org.citydb.io.citygml.adapter.geometry.serializer.MultiSurfacePropertyAdapter; import org.citydb.io.citygml.adapter.geometry.serializer.SolidPropertyAdapter; import org.citydb.io.citygml.annotation.DatabaseType; import org.citydb.io.citygml.builder.ModelBuildException; import org.citydb.io.citygml.reader.ModelBuilderHelper; import org.citydb.io.citygml.serializer.ModelSerializeException; import org.citydb.io.citygml.writer.ModelSerializerHelper; import org.citydb.model.common.Name; import org.citydb.model.common.Namespaces; import org.citydb.model.feature.Feature; import org.citydb.model.feature.FeatureType; import org.citydb.model.property.Attribute; import org.citydb.model.property.FeatureProperty; import org.citydb.model.property.GeometryProperty; import org.citygml4j.core.model.CityGMLVersion; import org.citygml4j.core.model.building.BuildingFurnitureProperty; import org.citygml4j.core.model.building.BuildingInstallationProperty; import org.citygml4j.core.model.building.BuildingRoom; import org.citygml4j.core.model.building.RoomHeightProperty; import org.citygml4j.core.model.deprecated.building.DeprecatedPropertiesOfBuildingRoom;
19,409
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.building; @DatabaseType(name = "BuildingRoom", namespace = Namespaces.BUILDING) public class BuildingRoomAdapter extends AbstractUnoccupiedSpaceAdapter<BuildingRoom> { @Override public Feature createModel(BuildingRoom source) throws ModelBuildException { return Feature.of(FeatureType.BUILDING_ROOM); } @Override
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.building; @DatabaseType(name = "BuildingRoom", namespace = Namespaces.BUILDING) public class BuildingRoomAdapter extends AbstractUnoccupiedSpaceAdapter<BuildingRoom> { @Override public Feature createModel(BuildingRoom source) throws ModelBuildException { return Feature.of(FeatureType.BUILDING_ROOM); } @Override
public void build(BuildingRoom source, Feature target, ModelBuilderHelper helper) throws ModelBuildException {
5
2023-11-19 12:29:54+00:00
24k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/craftbukkit/v1_12_R1/inventory/CraftMetaKnowledgeBook.java
[ { "identifier": "Material", "path": "src/main/java/org/bukkit/Material.java", "snippet": "public enum Material {\n AIR(0, 0),\n STONE(1),\n GRASS(2),\n DIRT(3),\n COBBLESTONE(4),\n WOOD(5, Wood.class),\n SAPLING(6, Sapling.class),\n BEDROCK(7),\n WATER(8, MaterialData.class),\...
import com.google.common.collect.ImmutableMap.Builder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.v1_12_R1.util.CraftNamespacedKey; import org.bukkit.inventory.meta.KnowledgeBookMeta;
15,036
package org.bukkit.craftbukkit.v1_12_R1.inventory; @DelegateDeserialization(CraftMetaItem.SerializableMeta.class) public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBookMeta { static final ItemMetaKey BOOK_RECIPES = new ItemMetaKey("Recipes"); static final int MAX_RECIPES = Short.MAX_VALUE; protected List<NamespacedKey> recipes = new ArrayList<NamespacedKey>(); CraftMetaKnowledgeBook(CraftMetaItem meta) { super(meta); if (meta instanceof CraftMetaKnowledgeBook) { CraftMetaKnowledgeBook bookMeta = (CraftMetaKnowledgeBook) meta; this.recipes.addAll(bookMeta.recipes); } } CraftMetaKnowledgeBook(NBTTagCompound tag) { super(tag); if (tag.hasKey(BOOK_RECIPES.NBT)) { NBTTagList pages = tag.getTagList(BOOK_RECIPES.NBT, 8); for (int i = 0; i < pages.tagCount(); i++) { String recipe = pages.getStringTagAt(i);
package org.bukkit.craftbukkit.v1_12_R1.inventory; @DelegateDeserialization(CraftMetaItem.SerializableMeta.class) public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBookMeta { static final ItemMetaKey BOOK_RECIPES = new ItemMetaKey("Recipes"); static final int MAX_RECIPES = Short.MAX_VALUE; protected List<NamespacedKey> recipes = new ArrayList<NamespacedKey>(); CraftMetaKnowledgeBook(CraftMetaItem meta) { super(meta); if (meta instanceof CraftMetaKnowledgeBook) { CraftMetaKnowledgeBook bookMeta = (CraftMetaKnowledgeBook) meta; this.recipes.addAll(bookMeta.recipes); } } CraftMetaKnowledgeBook(NBTTagCompound tag) { super(tag); if (tag.hasKey(BOOK_RECIPES.NBT)) { NBTTagList pages = tag.getTagList(BOOK_RECIPES.NBT, 8); for (int i = 0; i < pages.tagCount(); i++) { String recipe = pages.getStringTagAt(i);
addRecipe(CraftNamespacedKey.fromString(recipe));
2
2023-11-22 11:25:51+00:00
24k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityCrystallizationCrucible.java
[ { "identifier": "EPRecipeMaps", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/EPRecipeMaps.java", "snippet": "@ZenClass(\"mods.epimorphism.recipe.RecipeMaps\")\n@ZenRegister\npublic class EPRecipeMaps {\n\n // Singleblock Machine Recipemap\n @ZenProperty\n public static final Re...
import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import cn.gtcommunity.epimorphism.client.renderer.texture.EPTextures; import cn.gtcommunity.epimorphism.common.metatileentities.EPMetaTileEntities; import gregicality.multiblocks.common.block.GCYMMetaBlocks; import gregicality.multiblocks.common.block.blocks.BlockUniqueCasing; import gregtech.api.GTValues; import gregtech.api.capability.IHeatingCoil; import gregtech.api.capability.impl.HeatingCoilRecipeLogic; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.MultiMapMultiblockController; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.pattern.MultiblockShapeInfo; import gregtech.api.pattern.PatternMatchContext; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.recipeproperties.TemperatureProperty; import gregtech.api.util.GTUtility; import gregtech.client.renderer.ICubeRenderer; import gregtech.client.renderer.texture.Textures; import gregtech.client.renderer.texture.cube.OrientedOverlayRenderer; import gregtech.common.ConfigHolder; import gregtech.common.blocks.BlockMetalCasing; import gregtech.common.blocks.BlockWireCoil.CoilType; import gregtech.common.blocks.MetaBlocks; import gregtech.common.metatileentities.MetaTileEntities; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.I18n; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import static gregtech.api.unification.material.Materials.Titanium;
20,090
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCrystallizationCrucible extends MultiMapMultiblockController implements IHeatingCoil { private int temperature; public EPMetaTileEntityCrystallizationCrucible(ResourceLocation metaTileEntityId) { super(metaTileEntityId, new RecipeMap[]{ EPRecipeMaps.CRYSTALLIZATION_RECIPES, EPRecipeMaps.CRYSTALLIZER_RECIPES}); this.recipeMapWorkable = new HeatingCoilRecipeLogic(this); } @Override public MetaTileEntity createMetaTileEntity(IGregTechTileEntity holder) { return new EPMetaTileEntityCrystallizationCrucible(metaTileEntityId); } @Override protected void addDisplayText(List<ITextComponent> textList) { if (isStructureFormed()) { textList.add(new TextComponentTranslation("gregtech.multiblock.blast_furnace.max_temperature", TextFormatting.RED + GTUtility.formatNumbers(temperature) + "K")); } super.addDisplayText(textList); } @Override protected void formStructure(PatternMatchContext context) { super.formStructure(context); Object type = context.get("CoilType"); if (type instanceof CoilType) this.temperature = ((CoilType) type).getCoilTemperature(); else this.temperature = CoilType.CUPRONICKEL.getCoilTemperature(); this.temperature += 100 * Math.max(0, GTUtility.getTierByVoltage(getEnergyContainer().getInputVoltage()) - GTValues.MV); } @Override public void invalidateStructure() { super.invalidateStructure(); this.temperature = 0; } @Override public boolean checkRecipe(@Nonnull Recipe recipe, boolean consumeIfSuccess) { return this.temperature >= recipe.getProperty(TemperatureProperty.getInstance(), 0); } @Nonnull @Override protected BlockPattern createStructurePattern() { return FactoryBlockPattern.start() .aisle("XXXXX", "G###G", "G###G", "XXXXX") .aisle("XXXXX", "#VCV#", "#VCV#", "XXXXX") .aisle("XXXXX", "#CAC#", "#CAC#", "XXMXX") .aisle("XXXXX", "#VCV#", "#VCV#", "XXXXX") .aisle("XXSXX", "G###G", "G###G", "XXXXX") .where('S', selfPredicate()) .where('X', states(getCasingState()).setMinGlobalLimited(32) .or(autoAbilities(true, true, true, true, true, false, false))) .where('C', heatingCoils()) .where('M', abilities(MultiblockAbility.MUFFLER_HATCH)) .where('G', states(getFrameState())) .where('V', states(getVentState())) .where('A', air()) .where('#', any()) .build(); } @Nonnull private static IBlockState getCasingState() { return MetaBlocks.METAL_CASING.getState(BlockMetalCasing.MetalCasingType.TITANIUM_STABLE); } @Nonnull private static IBlockState getFrameState() { return MetaBlocks.FRAMES.get(Titanium).getBlock(Titanium); } @Nonnull private static IBlockState getVentState() { return GCYMMetaBlocks.UNIQUE_CASING.getState(BlockUniqueCasing.UniqueCasingType.HEAT_VENT); } @Override public void addInformation(ItemStack stack, @Nullable World player, List<String> tooltip, boolean advanced) { super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.1")); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.2")); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.3")); } @SideOnly(Side.CLIENT) @Override public ICubeRenderer getBaseTexture(IMultiblockPart iMultiblockPart) { return Textures.STABLE_TITANIUM_CASING; } @SideOnly(Side.CLIENT) @Nonnull @Override protected OrientedOverlayRenderer getFrontOverlay() {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCrystallizationCrucible extends MultiMapMultiblockController implements IHeatingCoil { private int temperature; public EPMetaTileEntityCrystallizationCrucible(ResourceLocation metaTileEntityId) { super(metaTileEntityId, new RecipeMap[]{ EPRecipeMaps.CRYSTALLIZATION_RECIPES, EPRecipeMaps.CRYSTALLIZER_RECIPES}); this.recipeMapWorkable = new HeatingCoilRecipeLogic(this); } @Override public MetaTileEntity createMetaTileEntity(IGregTechTileEntity holder) { return new EPMetaTileEntityCrystallizationCrucible(metaTileEntityId); } @Override protected void addDisplayText(List<ITextComponent> textList) { if (isStructureFormed()) { textList.add(new TextComponentTranslation("gregtech.multiblock.blast_furnace.max_temperature", TextFormatting.RED + GTUtility.formatNumbers(temperature) + "K")); } super.addDisplayText(textList); } @Override protected void formStructure(PatternMatchContext context) { super.formStructure(context); Object type = context.get("CoilType"); if (type instanceof CoilType) this.temperature = ((CoilType) type).getCoilTemperature(); else this.temperature = CoilType.CUPRONICKEL.getCoilTemperature(); this.temperature += 100 * Math.max(0, GTUtility.getTierByVoltage(getEnergyContainer().getInputVoltage()) - GTValues.MV); } @Override public void invalidateStructure() { super.invalidateStructure(); this.temperature = 0; } @Override public boolean checkRecipe(@Nonnull Recipe recipe, boolean consumeIfSuccess) { return this.temperature >= recipe.getProperty(TemperatureProperty.getInstance(), 0); } @Nonnull @Override protected BlockPattern createStructurePattern() { return FactoryBlockPattern.start() .aisle("XXXXX", "G###G", "G###G", "XXXXX") .aisle("XXXXX", "#VCV#", "#VCV#", "XXXXX") .aisle("XXXXX", "#CAC#", "#CAC#", "XXMXX") .aisle("XXXXX", "#VCV#", "#VCV#", "XXXXX") .aisle("XXSXX", "G###G", "G###G", "XXXXX") .where('S', selfPredicate()) .where('X', states(getCasingState()).setMinGlobalLimited(32) .or(autoAbilities(true, true, true, true, true, false, false))) .where('C', heatingCoils()) .where('M', abilities(MultiblockAbility.MUFFLER_HATCH)) .where('G', states(getFrameState())) .where('V', states(getVentState())) .where('A', air()) .where('#', any()) .build(); } @Nonnull private static IBlockState getCasingState() { return MetaBlocks.METAL_CASING.getState(BlockMetalCasing.MetalCasingType.TITANIUM_STABLE); } @Nonnull private static IBlockState getFrameState() { return MetaBlocks.FRAMES.get(Titanium).getBlock(Titanium); } @Nonnull private static IBlockState getVentState() { return GCYMMetaBlocks.UNIQUE_CASING.getState(BlockUniqueCasing.UniqueCasingType.HEAT_VENT); } @Override public void addInformation(ItemStack stack, @Nullable World player, List<String> tooltip, boolean advanced) { super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.1")); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.2")); tooltip.add(I18n.format("gregtech.machine.electric_blast_furnace.tooltip.3")); } @SideOnly(Side.CLIENT) @Override public ICubeRenderer getBaseTexture(IMultiblockPart iMultiblockPart) { return Textures.STABLE_TITANIUM_CASING; } @SideOnly(Side.CLIENT) @Nonnull @Override protected OrientedOverlayRenderer getFrontOverlay() {
return EPTextures.CRYSTALLIZATION_CRUCIBLE_OVERLAY;
1
2023-11-26 01:56:35+00:00
24k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/GUIHandler/Menus/FoundShopsMenu.java
[ { "identifier": "ConfigProvider", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigProvider.java", "snippet": "public class ConfigProvider {\n\n public final String PLUGIN_PREFIX = ColorTranslator.translateColorCodes(ConfigSetup.get().getString(\"plugin-prefix\"));\n public fina...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigProvider; import io.myzticbean.finditemaddon.Dependencies.EssentialsXPlugin; import io.myzticbean.finditemaddon.Dependencies.PlayerWarpsPlugin; import io.myzticbean.finditemaddon.Dependencies.WGPlugin; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PaginatedMenu; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PlayerMenuUtility; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.Defaults.ShopLorePlaceholders; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.ShopSearchActivityStorageUtil; import io.myzticbean.finditemaddon.Utils.LocationUtils; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.EssentialWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.PlayerWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.WGRegionUtils; import io.papermc.lib.PaperLib; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects;
15,816
package io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus; /** * Handler class for FoundShops GUI * @author ronsane */ public class FoundShopsMenu extends PaginatedMenu { private final String NO_WARP_NEAR_SHOP_ERROR_MSG = "No Warp near this shop"; private final String NO_WG_REGION_NEAR_SHOP_ERROR_MSG = "No WG Region near this shop"; public FoundShopsMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility, searchResult); } @Override public String getMenuName() { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE)) { return ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE); } else { return ColorTranslator.translateColorCodes("&l» &rShops"); } } @Override public int getSlots() { return 54; } @Override public void handleMenu(InventoryClickEvent event) { if(event.getSlot() == 45) { handleMenuClickForNavToPrevPage(event); } else if(event.getSlot() == 53) { handleMenuClickForNavToNextPage(event); } // Issue #31: Removing condition 'event.getCurrentItem().getType().equals(Material.BARRIER)' else if(event.getSlot() == 49) { event.getWhoClicked().closeInventory(); } else if(event.getCurrentItem().getType().equals(Material.AIR)) { // do nothing LoggerUtils.logDebugInfo(event.getWhoClicked().getName() + " just clicked on AIR!"); } else { Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); ItemMeta meta = item.getItemMeta(); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); if(!meta.getPersistentDataContainer().isEmpty() && meta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { String locData = meta.getPersistentDataContainer().get(key, PersistentDataType.STRING); List<String> locDataList = Arrays.asList(locData.split("\\s*,\\s*")); if(FindItemAddOn.getConfigProvider().TP_PLAYER_DIRECTLY_TO_SHOP) { if(playerMenuUtility.getOwner().hasPermission(PlayerPerms.FINDITEM_SHOPTP.value())) { World world = Bukkit.getWorld(locDataList.get(0)); int locX = Integer.parseInt(locDataList.get(1)), locY = Integer.parseInt(locDataList.get(2)), locZ = Integer.parseInt(locDataList.get(3)); Location shopLocation = new Location(world, locX, locY, locZ); Location locToTeleport = LocationUtils.findSafeLocationAroundShop(shopLocation); if(locToTeleport != null) { // Add Player Visit Entry ShopSearchActivityStorageUtil.addPlayerVisitEntryAsync(shopLocation, player); // Add Short Blindness effect... maybe? /** * @// TODO: 16/06/22 Make this an option in config */ // player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10, 0, false, false, false)); // Teleport // If EssentialsX is enabled, register last location before teleporting to make /back work
package io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus; /** * Handler class for FoundShops GUI * @author ronsane */ public class FoundShopsMenu extends PaginatedMenu { private final String NO_WARP_NEAR_SHOP_ERROR_MSG = "No Warp near this shop"; private final String NO_WG_REGION_NEAR_SHOP_ERROR_MSG = "No WG Region near this shop"; public FoundShopsMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility, searchResult); } @Override public String getMenuName() { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE)) { return ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE); } else { return ColorTranslator.translateColorCodes("&l» &rShops"); } } @Override public int getSlots() { return 54; } @Override public void handleMenu(InventoryClickEvent event) { if(event.getSlot() == 45) { handleMenuClickForNavToPrevPage(event); } else if(event.getSlot() == 53) { handleMenuClickForNavToNextPage(event); } // Issue #31: Removing condition 'event.getCurrentItem().getType().equals(Material.BARRIER)' else if(event.getSlot() == 49) { event.getWhoClicked().closeInventory(); } else if(event.getCurrentItem().getType().equals(Material.AIR)) { // do nothing LoggerUtils.logDebugInfo(event.getWhoClicked().getName() + " just clicked on AIR!"); } else { Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); ItemMeta meta = item.getItemMeta(); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); if(!meta.getPersistentDataContainer().isEmpty() && meta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { String locData = meta.getPersistentDataContainer().get(key, PersistentDataType.STRING); List<String> locDataList = Arrays.asList(locData.split("\\s*,\\s*")); if(FindItemAddOn.getConfigProvider().TP_PLAYER_DIRECTLY_TO_SHOP) { if(playerMenuUtility.getOwner().hasPermission(PlayerPerms.FINDITEM_SHOPTP.value())) { World world = Bukkit.getWorld(locDataList.get(0)); int locX = Integer.parseInt(locDataList.get(1)), locY = Integer.parseInt(locDataList.get(2)), locZ = Integer.parseInt(locDataList.get(3)); Location shopLocation = new Location(world, locX, locY, locZ); Location locToTeleport = LocationUtils.findSafeLocationAroundShop(shopLocation); if(locToTeleport != null) { // Add Player Visit Entry ShopSearchActivityStorageUtil.addPlayerVisitEntryAsync(shopLocation, player); // Add Short Blindness effect... maybe? /** * @// TODO: 16/06/22 Make this an option in config */ // player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10, 0, false, false, false)); // Teleport // If EssentialsX is enabled, register last location before teleporting to make /back work
if(EssentialsXPlugin.isEnabled()) {
1
2023-11-22 11:36:01+00:00
24k
estkme-group/infineon-lpa-mirror
app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java
[ { "identifier": "LocalProfileAssistantCoreImpl", "path": "core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java", "snippet": "public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore {\n private static final String TAG = LocalProfileAssistantCoreImpl....
import androidx.lifecycle.MutableLiveData; import com.infineon.esim.lpa.core.LocalProfileAssistantCoreImpl; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.data.StatusAndEventHandler; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.euicc.base.EuiccConnection; import com.infineon.esim.lpa.euicc.base.EuiccConnectionConsumer; import com.infineon.esim.lpa.lpa.task.AuthenticateTask; import com.infineon.esim.lpa.lpa.task.CancelSessionTask; import com.infineon.esim.lpa.lpa.task.DownloadTask; import com.infineon.esim.lpa.lpa.task.GetEuiccInfoTask; import com.infineon.esim.lpa.lpa.task.GetProfileListTask; import com.infineon.esim.lpa.lpa.task.HandleAndClearAllNotificationsTask; import com.infineon.esim.lpa.lpa.task.ProfileActionTask; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.InternetConnectionConsumer; import com.infineon.esim.lpa.util.threading.TaskRunner; import com.infineon.esim.util.Log;
14,756
public void refreshEuiccInfo() { Log.debug(TAG, "Refreshing eUICC info."); statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED); new TaskRunner().executeAsync(new GetEuiccInfoTask(this), result -> { euiccInfo = result; statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of eUICC info.", e.getMessage()))); } public void enableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED); if(profile.isEnabled()) { Log.debug(TAG, "Profile already enabled!"); statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_ENABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during enabling profile.", e.getMessage()))); } public void disableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED); if(!profile.isEnabled()) { Log.debug(TAG, "Profile already disabled!"); statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DISABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during disabling of profile.", e.getMessage()))); } public void deleteProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED); new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DELETE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during deleting of profile.", e.getMessage()))); } public void setNickname(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED); ProfileActionTask profileActionTask = new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_SET_NICKNAME, profile); new TaskRunner().executeAsync(profileActionTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during setting nickname of profile.", e.getMessage()))); } public void handleAndClearAllNotifications() { statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED); HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this); new TaskRunner().executeAsync(handleAndClearAllNotificationsTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during clearing of all eUICC notifications.", e.getMessage()))); } public void startAuthentication(ActivationCode activationCode) { authenticateResult = null; statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED); AuthenticateTask authenticateTask = new AuthenticateTask( this, activationCode); new TaskRunner().executeAsync(authenticateTask, authenticateResult -> { postProcessAuthenticate(authenticateResult); statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Error authentication of profile download.", e.getMessage()))); } public void postProcessAuthenticate(AuthenticateResult authenticateResult) { this.authenticateResult = authenticateResult; if(authenticateResult.getSuccess()) { // Check if there is a matching profile already installed ProfileMetadata newProfile = authenticateResult.getProfileMetadata(); ProfileMetadata matchingProfile = null; if (newProfile != null) { ProfileList profileList = this.profileList.getValue(); if(profileList != null) { matchingProfile = profileList.findMatchingProfile(newProfile.getIccid()); } if ((matchingProfile != null) && (matchingProfile.getNickname() != null)) { Log.debug(TAG, "Profile already installed: " + matchingProfile.getNickname()); String errorMessage = "Profile with this ICCID already installed: " + matchingProfile.getNickname(); statusAndEventHandler.onError(new Error("Profile already installed!", errorMessage)); } } } } public void startProfileDownload(String confirmationCode) { downloadResult = null; statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_STARTED); new TaskRunner().executeAsync(
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver; private EuiccConnection euiccConnection; private EuiccInfo euiccInfo; private AuthenticateResult authenticateResult; private DownloadResult downloadResult; private CancelSessionResult cancelSessionResult; public LocalProfileAssistant(EuiccManager euiccManager, StatusAndEventHandler statusAndEventHandler) { super(); Log.debug(TAG,"Creating LocalProfileAssistant..."); this.networkStatusBroadcastReceiver = new NetworkStatusBroadcastReceiver(this); this.statusAndEventHandler = statusAndEventHandler; this.profileList = new MutableLiveData<>(); networkStatusBroadcastReceiver.registerReceiver(); euiccManager.setEuiccConnectionConsumer(this); } public MutableLiveData<ProfileList> getProfileListLiveData() { return profileList; } public EuiccInfo getEuiccInfo() { return euiccInfo; } public AuthenticateResult getAuthenticateResult() { return authenticateResult; } public DownloadResult getDownloadResult() { return downloadResult; } public CancelSessionResult getCancelSessionResult() { return cancelSessionResult; } public Boolean resetEuicc() throws Exception { if(euiccConnection == null) { throw new Exception("Error: eUICC connection not available to LPA."); } else { return euiccConnection.resetEuicc(); } } public void refreshProfileList() { Log.debug(TAG,"Refreshing profile list."); statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_STARTED); new TaskRunner().executeAsync(new GetProfileListTask(this), result -> { statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_FINISHED); profileList.setValue(result); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of profile list.", e.getMessage()))); } public void refreshEuiccInfo() { Log.debug(TAG, "Refreshing eUICC info."); statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED); new TaskRunner().executeAsync(new GetEuiccInfoTask(this), result -> { euiccInfo = result; statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Exception during getting of eUICC info.", e.getMessage()))); } public void enableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED); if(profile.isEnabled()) { Log.debug(TAG, "Profile already enabled!"); statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_ENABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during enabling profile.", e.getMessage()))); } public void disableProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED); if(!profile.isEnabled()) { Log.debug(TAG, "Profile already disabled!"); statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED); return; } new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DISABLE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during disabling of profile.", e.getMessage()))); } public void deleteProfile(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED); new TaskRunner().executeAsync(new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_DELETE, profile), result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during deleting of profile.", e.getMessage()))); } public void setNickname(ProfileMetadata profile) { statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED); ProfileActionTask profileActionTask = new ProfileActionTask(this, ProfileActionType.PROFILE_ACTION_SET_NICKNAME, profile); new TaskRunner().executeAsync(profileActionTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during setting nickname of profile.", e.getMessage()))); } public void handleAndClearAllNotifications() { statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED); HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this); new TaskRunner().executeAsync(handleAndClearAllNotificationsTask, result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED), e -> statusAndEventHandler.onError(new Error("Error during clearing of all eUICC notifications.", e.getMessage()))); } public void startAuthentication(ActivationCode activationCode) { authenticateResult = null; statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED); AuthenticateTask authenticateTask = new AuthenticateTask( this, activationCode); new TaskRunner().executeAsync(authenticateTask, authenticateResult -> { postProcessAuthenticate(authenticateResult); statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_FINISHED); }, e -> statusAndEventHandler.onError(new Error("Error authentication of profile download.", e.getMessage()))); } public void postProcessAuthenticate(AuthenticateResult authenticateResult) { this.authenticateResult = authenticateResult; if(authenticateResult.getSuccess()) { // Check if there is a matching profile already installed ProfileMetadata newProfile = authenticateResult.getProfileMetadata(); ProfileMetadata matchingProfile = null; if (newProfile != null) { ProfileList profileList = this.profileList.getValue(); if(profileList != null) { matchingProfile = profileList.findMatchingProfile(newProfile.getIccid()); } if ((matchingProfile != null) && (matchingProfile.getNickname() != null)) { Log.debug(TAG, "Profile already installed: " + matchingProfile.getNickname()); String errorMessage = "Profile with this ICCID already installed: " + matchingProfile.getNickname(); statusAndEventHandler.onError(new Error("Profile already installed!", errorMessage)); } } } } public void startProfileDownload(String confirmationCode) { downloadResult = null; statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_STARTED); new TaskRunner().executeAsync(
new DownloadTask(this, confirmationCode),
15
2023-11-22 07:46:30+00:00
24k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/order/FinalizeOrderEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.api.endpoints.objects.Identifier; import de.morihofi.acmeserver.certificate.acme.api.endpoints.order.objects.ACMEOrderResponse; import de.morihofi.acmeserver.certificate.acme.api.endpoints.order.objects.FinalizeOrderRequestPayload; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.database.objects.ACMEAccount; import de.morihofi.acmeserver.database.objects.ACMEIdentifier; import de.morihofi.acmeserver.exception.exceptions.ACMEBadCsrException; import de.morihofi.acmeserver.tools.base64.Base64Tools; import de.morihofi.acmeserver.tools.certificate.PemUtil; import de.morihofi.acmeserver.tools.certificate.dataExtractor.CsrDataExtractor; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.dateAndTime.DateTools; import de.morihofi.acmeserver.tools.certificate.generator.ServerCertificateGenerator; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.io.pem.PemObject; import java.math.BigInteger; import java.security.cert.X509Certificate; import java.sql.Timestamp; import java.util.List; import java.util.stream.Collectors;
18,822
package de.morihofi.acmeserver.certificate.acme.api.endpoints.order; public class FinalizeOrderEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); /** * ACME Endpoint for finalize an order * * @param provisioner Provisioner instance */ @SuppressFBWarnings("EI_EXPOSE_REP2") public FinalizeOrderEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String orderId = ctx.pathParam("orderId"); ACMEAccount account = Database.getAccountByOrderId(orderId); // Check signature and nonce assert account != null; performSignatureAndNonceCheck(ctx, account, acmeRequestBody); //After check parse payload FinalizeOrderRequestPayload reqBodyPayloadObj = gson.fromJson(acmeRequestBody.getDecodedPayload(), FinalizeOrderRequestPayload.class); String csr = reqBodyPayloadObj.getCsr(); List<String> csrDomainNames = CsrDataExtractor.getDomainsFromCSR(csr); if (csrDomainNames.isEmpty()) {
package de.morihofi.acmeserver.certificate.acme.api.endpoints.order; public class FinalizeOrderEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); /** * ACME Endpoint for finalize an order * * @param provisioner Provisioner instance */ @SuppressFBWarnings("EI_EXPOSE_REP2") public FinalizeOrderEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String orderId = ctx.pathParam("orderId"); ACMEAccount account = Database.getAccountByOrderId(orderId); // Check signature and nonce assert account != null; performSignatureAndNonceCheck(ctx, account, acmeRequestBody); //After check parse payload FinalizeOrderRequestPayload reqBodyPayloadObj = gson.fromJson(acmeRequestBody.getDecodedPayload(), FinalizeOrderRequestPayload.class); String csr = reqBodyPayloadObj.getCsr(); List<String> csrDomainNames = CsrDataExtractor.getDomainsFromCSR(csr); if (csrDomainNames.isEmpty()) {
throw new ACMEBadCsrException("CSR does not contain any domain names");
9
2023-11-22 15:54:36+00:00
24k
NBHZW/hnustDatabaseCourseDesign
ruoyi-admin/src/main/java/com/ruoyi/web/controller/studentInformation/PunishmentController.java
[ { "identifier": "StudentMapper", "path": "ruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/mapper/StudentMapper.java", "snippet": "public interface StudentMapper\n{\n /**\n * 查询学生信息\n *\n * @param id 学生信息主键\n * @return 学生信息\n */\n public Student selectStudent...
import java.util.List; import javax.servlet.http.HttpServletResponse; import com.ruoyi.studentInformation.mapper.StudentMapper; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.studentInformation.domain.Punishment; import com.ruoyi.studentInformation.service.IPunishmentService; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo;
17,727
package com.ruoyi.web.controller.studentInformation; /** * 处罚表Controller * * @author ruoyi * @date 2023-11-06 */ @RestController @RequestMapping("/system/punishment") public class PunishmentController extends BaseController { @Autowired private IPunishmentService punishmentService; @Autowired private StudentMapper studentMapper; /** * 查询处罚表列表 */ @PreAuthorize("@ss.hasPermi('system:punishment:list')") @GetMapping("/list")
package com.ruoyi.web.controller.studentInformation; /** * 处罚表Controller * * @author ruoyi * @date 2023-11-06 */ @RestController @RequestMapping("/system/punishment") public class PunishmentController extends BaseController { @Autowired private IPunishmentService punishmentService; @Autowired private StudentMapper studentMapper; /** * 查询处罚表列表 */ @PreAuthorize("@ss.hasPermi('system:punishment:list')") @GetMapping("/list")
public TableDataInfo list(Punishment punishment)
4
2023-11-25 02:50:45+00:00
24k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jei/JEICategories.java
[ { "identifier": "JustEnoughMagiculture", "path": "src/main/java/com/invadermonky/justenoughmagiculture/JustEnoughMagiculture.java", "snippet": "@Mod(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustEnoughMagiculture.MOD_NAME,\n version = JustEnoughMagiculture.MOD_VERSION,\n ...
import com.invadermonky.justenoughmagiculture.JustEnoughMagiculture; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.init.InitIntegration; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagCategory; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagEntry; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagWrapper; import com.invadermonky.justenoughmagiculture.integrations.jei.mods.JEIErebusPlugin; import com.invadermonky.justenoughmagiculture.integrations.jer.mods.JERAtum; import com.invadermonky.justenoughmagiculture.registry.LootBagRegistry; import com.invadermonky.justenoughmagiculture.util.ModIds; import mezz.jei.api.*; import mezz.jei.api.recipe.IRecipeCategoryRegistration;
14,924
package com.invadermonky.justenoughmagiculture.integrations.jei; @JEIPlugin public class JEICategories implements IModPlugin { public static final String LOOT_BAG = JustEnoughMagiculture.MOD_ID + ".loot_bag"; private static IJeiHelpers jeiHelpers; private static IJeiRuntime jeiRuntime; @Override public void register(IModRegistry registry) { InitIntegration.jeiInit(); if(JEMConfig.MODULE_JEI.enableLootBagCategory) { registry.handleRecipes(LootBagEntry.class, LootBagWrapper::new, LOOT_BAG);
package com.invadermonky.justenoughmagiculture.integrations.jei; @JEIPlugin public class JEICategories implements IModPlugin { public static final String LOOT_BAG = JustEnoughMagiculture.MOD_ID + ".loot_bag"; private static IJeiHelpers jeiHelpers; private static IJeiRuntime jeiRuntime; @Override public void register(IModRegistry registry) { InitIntegration.jeiInit(); if(JEMConfig.MODULE_JEI.enableLootBagCategory) { registry.handleRecipes(LootBagEntry.class, LootBagWrapper::new, LOOT_BAG);
registry.addRecipes(LootBagRegistry.getInstance().getAllLootBags(), LOOT_BAG);
8
2023-11-19 23:09:14+00:00
24k
codingmiao/hppt
cs/src/main/java/org/wowtools/hppt/cs/servlet/TalkServlet.java
[ { "identifier": "ProtoMessage", "path": "common/src/main/java/org/wowtools/hppt/common/protobuf/ProtoMessage.java", "snippet": "public final class ProtoMessage {\n private ProtoMessage() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistryLite registry) {\n }\n\...
import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.cs.StartCs; import org.wowtools.hppt.cs.service.ClientService; import org.wowtools.hppt.cs.service.ServerSessionService; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
16,576
package org.wowtools.hppt.cs.servlet; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setHeader("Server", "hppt"); String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+"); ClientService.Client client = ClientService.getClient(loginCode); if (null == client) { log.warn("not_login: {}", loginCode); resp.setHeader("err", "not_login"); return; } String clientId = client.clientId; //读请求体里带过来的bytes byte[] bytes; try (InputStream inputStream = req.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } bytes = byteArrayOutputStream.toByteArray(); } //解密、解压
package org.wowtools.hppt.cs.servlet; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setHeader("Server", "hppt"); String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+"); ClientService.Client client = ClientService.getClient(loginCode); if (null == client) { log.warn("not_login: {}", loginCode); resp.setHeader("err", "not_login"); return; } String clientId = client.clientId; //读请求体里带过来的bytes byte[] bytes; try (InputStream inputStream = req.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } bytes = byteArrayOutputStream.toByteArray(); } //解密、解压
if (StartCs.config.enableEncrypt) {
2
2023-12-22 14:14:27+00:00
24k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/services/BlockPlacer.java
[ { "identifier": "CrystalPosition", "path": "src/main/java/me/earth/phobot/damagecalc/CrystalPosition.java", "snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\npublic class CrystalPosition extends MutPos {\n public static final long MAX_DEATHTIME = 100L;\n private final Entity[] crystals = new...
import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import me.earth.phobot.damagecalc.CrystalPosition; import me.earth.phobot.damagecalc.DamageCalculator; import me.earth.phobot.event.PostMotionPlayerUpdateEvent; import me.earth.phobot.event.PreMotionPlayerUpdateEvent; import me.earth.phobot.modules.ChecksBlockPlacingValidity; import me.earth.phobot.modules.client.anticheat.AntiCheat; import me.earth.phobot.modules.combat.autocrystal.CrystalPlacer; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.services.inventory.InventoryService; import me.earth.phobot.util.math.RaytraceUtil; import me.earth.phobot.util.math.RotationUtil; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.phobot.util.world.PredictionUtil; import me.earth.pingbypass.api.event.SubscriberImpl; import me.earth.pingbypass.commons.event.SafeListener; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.protocol.game.ServerboundInteractPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.NotNull; import java.util.*; import static me.earth.phobot.services.inventory.InventoryContext.*;
17,787
player.connection.send(new ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.RELEASE_SHIFT_KEY)); } if (failedActions.isEmpty()) { completed = true; } } if (clear) { customBlockStateLevel = null; collisionContext = null; actions.clear(); crystal = null; inTick = false; } } public DamageCalculator getDamageCalculator() { return antiCheat.getDamageCalculator(); } public interface PlacesBlocks extends Comparable<PlacesBlocks> { int getPriority(); void update(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode); default boolean isActive() { return true; } @Override default int compareTo(@NotNull BlockPlacer.PlacesBlocks o) { return Integer.compare(o.getPriority(), this.getPriority()); } } @Data public static class Action implements ChecksBlockPlacingValidity { private final Object module; @EqualsAndHashCode.Exclude private final Set<Action> dependencies = new HashSet<>(); private final BlockPos placeOn; private final BlockPos pos; private final Direction direction; private final Item item; private final boolean shouldSetBlock; private final boolean usingSetCarried; private final boolean packetRotations; private final BlockPlacer blockPlacer; private final boolean requiresExactDirection; public boolean execute(Set<Action> completedActions, InventoryContext context, LocalPlayer player, ClientLevel level) { if (blockPlacer.getAntiCheat().isAboveBuildHeight(pos.getY())) { return false; } BlockStateLevel.Delegating stateLevel = Objects.requireNonNull(blockPlacer.getCustomBlockStateLevel(), "BlockPlace.stateLevel was null!"); Player rotationPlayer = blockPlacer.getLocalPlayerPositionService().getPlayerOnLastPosition(player); if (isOutsideRange(placeOn, rotationPlayer)) { return false; } if (!stateLevel.getBlockState(pos).canBeReplaced()) { return false; } BlockHitResult hitResult = null; if (blockPlacer.getAntiCheat().getBlockRotations().getValue()) { boolean invert = blockPlacer.getAntiCheat().getOpposite().getValue(); Player finalRotationPlayer = rotationPlayer; hitResult = requiresExactDirection ? (strictDirectionCheck(placeOn, direction, stateLevel, rotationPlayer) ? RaytraceUtil.raytrace(rotationPlayer, stateLevel, placeOn, direction, invert) : null) : RaytraceUtil.raytraceToPlaceTarget(rotationPlayer, stateLevel, pos, (p,d) -> strictDirectionCheck(p, d, stateLevel, finalRotationPlayer), invert); if (hitResult == null || !hitResult.getBlockPos().relative(hitResult.getDirection()).equals(pos)) { if (!blockPlacer.getMinecraft().isSameThread()) { return false; } boolean fail = true; MotionUpdateService motionUpdateService = blockPlacer.motionUpdateService; if (packetRotations && !motionUpdateService.isInPreUpdate()) { float[] rotations = RotationUtil.getRotations(rotationPlayer, stateLevel, placeOn, direction); player.connection.send(new ServerboundMovePlayerPacket.Rot(rotations[0], rotations[1], rotationPlayer.onGround())); rotationPlayer = blockPlacer.getLocalPlayerPositionService().getPlayerOnLastPosition(player); // update, player has new rotation hitResult = new BlockHitResult(RotationUtil.getHitVec(placeOn, stateLevel, direction), direction, placeOn, false); fail = false; } else if ((dependencies.isEmpty() || completedActions.containsAll(dependencies)) && !motionUpdateService.isSpoofing() && motionUpdateService.isInPreUpdate()) { float[] rotations = RotationUtil.getRotations(player, stateLevel, placeOn, direction); motionUpdateService.rotate(player, rotations[0], rotations[1]); } if (fail) { return false; } } } else if (!strictDirectionCheck(placeOn, direction, stateLevel, rotationPlayer)) { return false; } InventoryContext.SwitchResult switchResult = context.switchTo(item, PREFER_MAINHAND | SWITCH_BACK | (usingSetCarried ? SET_CARRIED_ITEM : 0)); if (switchResult == null) { return false; } if (hitResult == null) { VoxelShape shape = stateLevel.getBlockState(placeOn).getCollisionShape(level, placeOn); Vec3 hitVec = new Vec3(direction.getStepX() + pos.getX(), direction.getStepY() + pos.getY(), direction.getStepZ() + pos.getZ()); for (AABB bb : shape.toAabbs()) { // not really optimal... double x = direction.getAxis() == Direction.Axis.X ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxX : bb.minX) : bb.minX + (bb.maxX - bb.minX) / 2.0; double y = direction.getAxis() == Direction.Axis.Y ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxY : bb.minY) : bb.minY + (bb.maxY - bb.minY) / 2.0; double z = direction.getAxis() == Direction.Axis.Z ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxZ : bb.minZ) : bb.minZ + (bb.maxZ - bb.minZ) / 2.0; hitVec = new Vec3(x + placeOn.getX(), y + placeOn.getY(), z + placeOn.getZ()); break; } hitResult = new BlockHitResult(hitVec, direction, placeOn, false); } BlockHitResult finalHitResult = hitResult; Player finalRotationPlayer = rotationPlayer;
package me.earth.phobot.services; @Getter public class BlockPlacer extends SubscriberImpl { public static final int PRIORITY = 10_000; private final Queue<PlacesBlocks> modules = new PriorityQueue<>(); private final List<Action> actions = new ArrayList<>(); private final LocalPlayerPositionService localPlayerPositionService; private final MotionUpdateService motionUpdateService; private final AntiCheat antiCheat; private final Minecraft minecraft; private CollisionContext collisionContext = CollisionContext.empty(); private BlockStateLevel.Delegating customBlockStateLevel = null; @Setter private EndCrystal crystal; private boolean attacked = false; private boolean completed = false; private volatile boolean inTick = false; public BlockPlacer(LocalPlayerPositionService localPlayerPositionService, MotionUpdateService motionUpdateService, InventoryService inventoryService, Minecraft minecraft, AntiCheat antiCheat) { this.localPlayerPositionService = localPlayerPositionService; this.motionUpdateService = motionUpdateService; this.antiCheat = antiCheat; this.minecraft = minecraft; listen(new SafeListener<PreMotionPlayerUpdateEvent>(minecraft, -PRIORITY) { @Override public void onEvent(PreMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { inventoryService.use(context -> { startTick(player, level); for (PlacesBlocks module : modules) { if (module.isActive()) { module.update(context, player, level, gameMode); } } if (antiCheat.getBlockRotations().getValue() && !actions.isEmpty()) { boolean spoofing = motionUpdateService.spoofing; motionUpdateService.spoofing = false; // end the tick before we sent our rotation and position to the server, so we can place blocks that rely on the last rotation sent endTick(context, player, level, false); motionUpdateService.spoofing = spoofing || motionUpdateService.spoofing; } }); } }); listen(new SafeListener<PostMotionPlayerUpdateEvent>(minecraft, PRIORITY) { @Override public void onEvent(PostMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { inventoryService.use(context -> endTick(context, player, level)); } }); } public void addAction(Action action) { actions.add(action); } public void startTick(LocalPlayer player, ClientLevel level) { customBlockStateLevel = new BlockStateLevel.Delegating(level); collisionContext = CollisionContext.of(player); actions.clear(); crystal = null; attacked = false; completed = false; inTick = true; } public void breakCrystal(LocalPlayer player) { if (crystal != null && !attacked) { // TODO: use attacking service with InventoryContext!!!! // TODO: only break crystal if the action is actually going to be executed player.connection.send(ServerboundInteractPacket.createAttackPacket(crystal, false)); player.swing(InteractionHand.MAIN_HAND); attacked = true; } } public void endTick(InventoryContext context, LocalPlayer player, ClientLevel level) { endTick(context, player, level, true); } private void endTick(InventoryContext context, LocalPlayer player, ClientLevel level, boolean clear) { if (!actions.isEmpty()) { breakCrystal(player); boolean shiftKey = player.isShiftKeyDown(); // TODO: better way to detect if the server knows this?! if (!shiftKey) { // the players pose only gets updated every server tick, so this does not matter for rotations! player.connection.send(new ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.PRESS_SHIFT_KEY)); } List<Action> failedActions = new ArrayList<>(actions.size()); Set<Action> completedActions = new HashSet<>(actions.size()); for (int i = 0; i < actions.size() && i < antiCheat.getActions().getValue(); i++) { // TODO: If we sent rotations send less packets! Action action = actions.get(i); if (failedActions.stream().anyMatch(action.dependencies::contains) || !action.execute(completedActions, context, player, level)) { failedActions.add(action); } else { completedActions.add(action); } } actions.removeIf(completedActions::contains); if (!shiftKey) { player.connection.send(new ServerboundPlayerCommandPacket(player, ServerboundPlayerCommandPacket.Action.RELEASE_SHIFT_KEY)); } if (failedActions.isEmpty()) { completed = true; } } if (clear) { customBlockStateLevel = null; collisionContext = null; actions.clear(); crystal = null; inTick = false; } } public DamageCalculator getDamageCalculator() { return antiCheat.getDamageCalculator(); } public interface PlacesBlocks extends Comparable<PlacesBlocks> { int getPriority(); void update(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode); default boolean isActive() { return true; } @Override default int compareTo(@NotNull BlockPlacer.PlacesBlocks o) { return Integer.compare(o.getPriority(), this.getPriority()); } } @Data public static class Action implements ChecksBlockPlacingValidity { private final Object module; @EqualsAndHashCode.Exclude private final Set<Action> dependencies = new HashSet<>(); private final BlockPos placeOn; private final BlockPos pos; private final Direction direction; private final Item item; private final boolean shouldSetBlock; private final boolean usingSetCarried; private final boolean packetRotations; private final BlockPlacer blockPlacer; private final boolean requiresExactDirection; public boolean execute(Set<Action> completedActions, InventoryContext context, LocalPlayer player, ClientLevel level) { if (blockPlacer.getAntiCheat().isAboveBuildHeight(pos.getY())) { return false; } BlockStateLevel.Delegating stateLevel = Objects.requireNonNull(blockPlacer.getCustomBlockStateLevel(), "BlockPlace.stateLevel was null!"); Player rotationPlayer = blockPlacer.getLocalPlayerPositionService().getPlayerOnLastPosition(player); if (isOutsideRange(placeOn, rotationPlayer)) { return false; } if (!stateLevel.getBlockState(pos).canBeReplaced()) { return false; } BlockHitResult hitResult = null; if (blockPlacer.getAntiCheat().getBlockRotations().getValue()) { boolean invert = blockPlacer.getAntiCheat().getOpposite().getValue(); Player finalRotationPlayer = rotationPlayer; hitResult = requiresExactDirection ? (strictDirectionCheck(placeOn, direction, stateLevel, rotationPlayer) ? RaytraceUtil.raytrace(rotationPlayer, stateLevel, placeOn, direction, invert) : null) : RaytraceUtil.raytraceToPlaceTarget(rotationPlayer, stateLevel, pos, (p,d) -> strictDirectionCheck(p, d, stateLevel, finalRotationPlayer), invert); if (hitResult == null || !hitResult.getBlockPos().relative(hitResult.getDirection()).equals(pos)) { if (!blockPlacer.getMinecraft().isSameThread()) { return false; } boolean fail = true; MotionUpdateService motionUpdateService = blockPlacer.motionUpdateService; if (packetRotations && !motionUpdateService.isInPreUpdate()) { float[] rotations = RotationUtil.getRotations(rotationPlayer, stateLevel, placeOn, direction); player.connection.send(new ServerboundMovePlayerPacket.Rot(rotations[0], rotations[1], rotationPlayer.onGround())); rotationPlayer = blockPlacer.getLocalPlayerPositionService().getPlayerOnLastPosition(player); // update, player has new rotation hitResult = new BlockHitResult(RotationUtil.getHitVec(placeOn, stateLevel, direction), direction, placeOn, false); fail = false; } else if ((dependencies.isEmpty() || completedActions.containsAll(dependencies)) && !motionUpdateService.isSpoofing() && motionUpdateService.isInPreUpdate()) { float[] rotations = RotationUtil.getRotations(player, stateLevel, placeOn, direction); motionUpdateService.rotate(player, rotations[0], rotations[1]); } if (fail) { return false; } } } else if (!strictDirectionCheck(placeOn, direction, stateLevel, rotationPlayer)) { return false; } InventoryContext.SwitchResult switchResult = context.switchTo(item, PREFER_MAINHAND | SWITCH_BACK | (usingSetCarried ? SET_CARRIED_ITEM : 0)); if (switchResult == null) { return false; } if (hitResult == null) { VoxelShape shape = stateLevel.getBlockState(placeOn).getCollisionShape(level, placeOn); Vec3 hitVec = new Vec3(direction.getStepX() + pos.getX(), direction.getStepY() + pos.getY(), direction.getStepZ() + pos.getZ()); for (AABB bb : shape.toAabbs()) { // not really optimal... double x = direction.getAxis() == Direction.Axis.X ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxX : bb.minX) : bb.minX + (bb.maxX - bb.minX) / 2.0; double y = direction.getAxis() == Direction.Axis.Y ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxY : bb.minY) : bb.minY + (bb.maxY - bb.minY) / 2.0; double z = direction.getAxis() == Direction.Axis.Z ? (direction.getAxisDirection() == Direction.AxisDirection.POSITIVE ? bb.maxZ : bb.minZ) : bb.minZ + (bb.maxZ - bb.minZ) / 2.0; hitVec = new Vec3(x + placeOn.getX(), y + placeOn.getY(), z + placeOn.getZ()); break; } hitResult = new BlockHitResult(hitVec, direction, placeOn, false); } BlockHitResult finalHitResult = hitResult; Player finalRotationPlayer = rotationPlayer;
PredictionUtil.predict(level, seq -> {
11
2023-12-22 14:32:16+00:00
24k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/gui/WaypointsGUI.java
[ { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatT...
import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import io.github.quantizr.handlers.ConfigHandler; import io.github.quantizr.handlers.TextRenderer; import io.github.quantizr.utils.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
15,741
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close); if (Utils.inDungeons) { if (Waypoints.secretNum > 0) { if (Waypoints.secretNum <= 5) { for (int i = 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum)) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } else { for (int i = 1; i <= (int) Math.ceil((double) Waypoints.secretNum / 2); i++) { int adjustPos = (-40 * ((int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } for (int i = (int) Math.ceil((double) Waypoints.secretNum / 2) + 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum - (int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * (i-(int) Math.ceil((double) Waypoints.secretNum / 2))); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 200, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } } } } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText = "FakepixelDungeonHelper Waypoints:"; int displayWidth = mc.fontRendererObj.getStringWidth(displayText); TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 - 20, 1D, false); String subtext1 = "Toggle Room Specific Waypoints:"; int subtext1Width = mc.fontRendererObj.getStringWidth(subtext1); TextRenderer.drawText(mc, subtext1, width / 2 - subtext1Width / 2, height / 6 + 140, 1D, false); String subtext2 = "(You can also press the # key matching the secret instead)"; int subtext2Width = mc.fontRendererObj.getStringWidth(subtext2); TextRenderer.drawText(mc, EnumChatFormatting.GRAY + subtext2, width / 2 - subtext2Width / 2, height / 6 + 150, 1D, false); if (!Utils.inDungeons) { String subtext3 = "Not in dungeons"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } else if (Waypoints.secretNum == 0) { String subtext3 = "No secrets in this room"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } super.drawScreen(mouseX, mouseY, partialTicks); } @Override public void actionPerformed(GuiButton button) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; if (button == waypointsEnabled) { Waypoints.enabled = !Waypoints.enabled;
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close); if (Utils.inDungeons) { if (Waypoints.secretNum > 0) { if (Waypoints.secretNum <= 5) { for (int i = 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum)) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } else { for (int i = 1; i <= (int) Math.ceil((double) Waypoints.secretNum / 2); i++) { int adjustPos = (-40 * ((int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * i); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 170, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } for (int i = (int) Math.ceil((double) Waypoints.secretNum / 2) + 1; i <= Waypoints.secretNum; i++) { int adjustPos = (-40 * (Waypoints.secretNum - (int) Math.ceil((double) Waypoints.secretNum / 2))) - 70 + (80 * (i-(int) Math.ceil((double) Waypoints.secretNum / 2))); secretButtonList.set(i - 1, new GuiButton(10 + i, (width / 2) + adjustPos, height / 6 + 200, 60, 20, i + ": " + getOnOff(Waypoints.secretsList.get(i - 1)))); this.buttonList.add(secretButtonList.get(i - 1)); } } } } } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText = "FakepixelDungeonHelper Waypoints:"; int displayWidth = mc.fontRendererObj.getStringWidth(displayText); TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 - 20, 1D, false); String subtext1 = "Toggle Room Specific Waypoints:"; int subtext1Width = mc.fontRendererObj.getStringWidth(subtext1); TextRenderer.drawText(mc, subtext1, width / 2 - subtext1Width / 2, height / 6 + 140, 1D, false); String subtext2 = "(You can also press the # key matching the secret instead)"; int subtext2Width = mc.fontRendererObj.getStringWidth(subtext2); TextRenderer.drawText(mc, EnumChatFormatting.GRAY + subtext2, width / 2 - subtext2Width / 2, height / 6 + 150, 1D, false); if (!Utils.inDungeons) { String subtext3 = "Not in dungeons"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } else if (Waypoints.secretNum == 0) { String subtext3 = "No secrets in this room"; int subtext3Width = mc.fontRendererObj.getStringWidth(subtext3); TextRenderer.drawText(mc, EnumChatFormatting.RED + subtext3, width / 2 - subtext3Width / 2, height / 6 + 170, 1D, false); } super.drawScreen(mouseX, mouseY, partialTicks); } @Override public void actionPerformed(GuiButton button) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; if (button == waypointsEnabled) { Waypoints.enabled = !Waypoints.enabled;
ConfigHandler.writeBooleanConfig("toggles", "waypointsToggled", Waypoints.enabled);
2
2023-12-22 04:44:39+00:00
24k
psobiech/opengr8on
vclu/src/test/java/pl/psobiech/opengr8on/vclu/ServerCommandTest.java
[ { "identifier": "CLUClient", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java", "snippet": "public class CLUClient extends Client implements Closeable {\n private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class);\n\n private static final Duration DEFAULT_...
import java.net.Inet4Address; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import io.jstach.jstachio.JStachio; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import pl.psobiech.opengr8on.client.CLUClient; import pl.psobiech.opengr8on.client.CLUFiles; import pl.psobiech.opengr8on.client.CipherKey; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.tftp.TFTPServer; import pl.psobiech.opengr8on.tftp.TFTPServer.ServerMode; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.HexUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.ResourceUtil; import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
15,411
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; @Execution(ExecutionMode.CONCURRENT) class ServerCommandTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private static ExecutorService executor = Executors.newCachedThreadPool(); private static Path rootDirectory; private static Path aDriveDirectory; private static UDPSocket broadcastSocket; private static UDPSocket socket; private static TFTPServer tftpServer; private static CipherKey projectCipherKey; private static CLUDevice cluDevice; private static Server server; private static Future<Void> serverFuture; private static CLUClient client; private static CLUClient broadcastClient; @BeforeAll static void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); aDriveDirectory = rootDirectory.resolve("a"); FileUtil.mkdir(aDriveDirectory); broadcastSocket = new UDPSocket(LOCALHOST, 0, false); socket = new UDPSocket(LOCALHOST, 0, false); tftpServer = new TFTPServer(LOCALHOST, 0, ServerMode.GET_AND_REPLACE, rootDirectory); projectCipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); cluDevice = new CLUDevice(
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; @Execution(ExecutionMode.CONCURRENT) class ServerCommandTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private static ExecutorService executor = Executors.newCachedThreadPool(); private static Path rootDirectory; private static Path aDriveDirectory; private static UDPSocket broadcastSocket; private static UDPSocket socket; private static TFTPServer tftpServer; private static CipherKey projectCipherKey; private static CLUDevice cluDevice; private static Server server; private static Future<Void> serverFuture; private static CLUClient client; private static CLUClient broadcastClient; @BeforeAll static void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); aDriveDirectory = rootDirectory.resolve("a"); FileUtil.mkdir(aDriveDirectory); broadcastSocket = new UDPSocket(LOCALHOST, 0, false); socket = new UDPSocket(LOCALHOST, 0, false); tftpServer = new TFTPServer(LOCALHOST, 0, ServerMode.GET_AND_REPLACE, rootDirectory); projectCipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); cluDevice = new CLUDevice(
HexUtil.asLong(RandomUtil.hexString(8)),
8
2023-12-23 09:56:14+00:00
24k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/skills/AlchemyHelper.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import cc.polyfrost.oneconfig.utils.Multithreading; import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.ClickEvent; import com.github.may2beez.mayobees.event.ContainerClosedEvent; import com.github.may2beez.mayobees.event.DrawScreenAfterEvent; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.util.InventoryUtils; import com.github.may2beez.mayobees.util.LogUtils; import com.github.may2beez.mayobees.util.RenderUtils; import com.github.may2beez.mayobees.util.helper.Clock; import lombok.Getter; import lombok.Setter; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.inventory.Slot; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.ArrayList; import java.util.Optional; import java.util.concurrent.TimeUnit;
15,870
package com.github.may2beez.mayobees.module.impl.skills; public class AlchemyHelper implements IModule { private static AlchemyHelper instance; public static AlchemyHelper getInstance() { if (instance == null) { instance = new AlchemyHelper(); } return instance; } @Override public String getName() { return "Alchemy Helper"; } private final Minecraft mc = Minecraft.getMinecraft(); private final int POTION_SLOT_1 = 38; private final int POTION_SLOT_2 = 40; private final int POTION_SLOT_3 = 42; private final int INGREDIENT_SLOT = 13; private final int TIME_SLOT = 22; private BlockPos lastClickedBrewingStand; private final Clock delay = new Clock(); private final ArrayList<BrewingStand> brewingStands = new ArrayList<>(); private BrewingStand currentBrewingStand; @Setter @Getter private boolean sellingPotions = false; @Override public boolean isRunning() { return MayOBeesConfig.alchemyHelper; } @SubscribeEvent public void onContainerClosedEvent(ContainerClosedEvent event) { if (!isRunning()) return; if (GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.PRIVATE_ISLAND) return; if (lastClickedBrewingStand == null) return; lastClickedBrewingStand = null; currentBrewingStand = null; } @SubscribeEvent public void onRightClick(ClickEvent.Right event) { if (!isRunning()) return; if (GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.PRIVATE_ISLAND) return; if (event.blockPos == null) return; if (event.block.equals(Blocks.brewing_stand)) { lastClickedBrewingStand = event.blockPos; Optional<BrewingStand> brewingStand = brewingStands.stream().filter(bs -> bs.getPos().equals(event.blockPos)).findFirst(); delay.schedule(300 + (int) (Math.random() * 250)); if (!brewingStand.isPresent()) { BrewingStand bs = new BrewingStand(event.blockPos); brewingStands.add(bs); currentBrewingStand = bs; } else { currentBrewingStand = brewingStand.get(); } } } @SubscribeEvent
package com.github.may2beez.mayobees.module.impl.skills; public class AlchemyHelper implements IModule { private static AlchemyHelper instance; public static AlchemyHelper getInstance() { if (instance == null) { instance = new AlchemyHelper(); } return instance; } @Override public String getName() { return "Alchemy Helper"; } private final Minecraft mc = Minecraft.getMinecraft(); private final int POTION_SLOT_1 = 38; private final int POTION_SLOT_2 = 40; private final int POTION_SLOT_3 = 42; private final int INGREDIENT_SLOT = 13; private final int TIME_SLOT = 22; private BlockPos lastClickedBrewingStand; private final Clock delay = new Clock(); private final ArrayList<BrewingStand> brewingStands = new ArrayList<>(); private BrewingStand currentBrewingStand; @Setter @Getter private boolean sellingPotions = false; @Override public boolean isRunning() { return MayOBeesConfig.alchemyHelper; } @SubscribeEvent public void onContainerClosedEvent(ContainerClosedEvent event) { if (!isRunning()) return; if (GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.PRIVATE_ISLAND) return; if (lastClickedBrewingStand == null) return; lastClickedBrewingStand = null; currentBrewingStand = null; } @SubscribeEvent public void onRightClick(ClickEvent.Right event) { if (!isRunning()) return; if (GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.PRIVATE_ISLAND) return; if (event.blockPos == null) return; if (event.block.equals(Blocks.brewing_stand)) { lastClickedBrewingStand = event.blockPos; Optional<BrewingStand> brewingStand = brewingStands.stream().filter(bs -> bs.getPos().equals(event.blockPos)).findFirst(); delay.schedule(300 + (int) (Math.random() * 250)); if (!brewingStand.isPresent()) { BrewingStand bs = new BrewingStand(event.blockPos); brewingStands.add(bs); currentBrewingStand = bs; } else { currentBrewingStand = brewingStand.get(); } } } @SubscribeEvent
public void onGuiDraw(DrawScreenAfterEvent event) {
3
2023-12-24 15:39:11+00:00
24k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/fragments/CarContentFragment.java
[ { "identifier": "CarInputActivity", "path": "app/src/main/java/de/anipe/verbrauchsapp/CarInputActivity.java", "snippet": "public class CarInputActivity extends AppCompatActivity {\n\n private ConsumptionDataSource dataSource;\n private FileSystemAccessor accessor;\n private long carId;\n pri...
import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.fragment.app.Fragment; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DecimalFormat; import de.anipe.verbrauchsapp.CarInputActivity; import de.anipe.verbrauchsapp.ConsumptionInputActivity; import de.anipe.verbrauchsapp.ConsumptionListActivity; import de.anipe.verbrauchsapp.GDriveStoreActivity; import de.anipe.verbrauchsapp.GraphViewPlot; import de.anipe.verbrauchsapp.ImportActivity; import de.anipe.verbrauchsapp.MainActivity; import de.anipe.verbrauchsapp.PictureImportActivity; import de.anipe.verbrauchsapp.R; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.objects.Car;
18,709
break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() { Car car = dataSource.getCarForId(carId); TextView header = rootView.findViewById(R.id.fullscreen_car_content); header.setText(car.getBrand().value() + " " + car.getType()); TextView startkm = rootView.findViewById(R.id.startkmValueLine); startkm.setText(String.valueOf(car.getStartKm())); TextView actualkm = rootView.findViewById(R.id.actualkmValueLine); int mileage = dataSource.getMileageForCar(carId); actualkm.setText(String.valueOf(mileage)); TextView consumption = rootView.findViewById(R.id.consumptionValueLine); consumption.setText(new DecimalFormat("#.00").format(dataSource .getOverallConsumptionForCar(carId)) + " l/100km"); TextView overallKm = rootView.findViewById(R.id.drivenKmValueLine); overallKm.setText(String.valueOf(mileage - car.getStartKm())); TextView overallCosts = rootView.findViewById(R.id.overallCostsValueLine); overallCosts.setText(new DecimalFormat("#0.00").format(dataSource .getOverallCostsForCar(carId)) + " \u20ac"); if (car.getImage() != null) { ImageView image = rootView.findViewById(R.id.pictureLine); image.setImageBitmap(car.getImage()); } } @SuppressWarnings("unused") private void exportData() { Car car = dataSource.getCarForId(carId); XMLHandler handler = new XMLHandler(null, car, dataSource.getOverallConsumptionForCar(carId), dataSource.getConsumptionCycles(carId)); try { accessor.writeXMLFileToStorage(getActivity(), handler.createConsumptionDocument(),
package de.anipe.verbrauchsapp.fragments; /** * */ public class CarContentFragment extends Fragment { private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private long carId; private View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { carId = getArguments().getLong("carid"); // The last two arguments ensure LayoutParams are inflated properly. rootView = inflater.inflate(R.layout.activity_car_content, container, false); FloatingActionButton btn = rootView.findViewById(R.id.float_add); btn.setOnClickListener(clickListener); return rootView; } @Override public void onResume() { updateView(); super.onResume(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.car_menubar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() { Car car = dataSource.getCarForId(carId); TextView header = rootView.findViewById(R.id.fullscreen_car_content); header.setText(car.getBrand().value() + " " + car.getType()); TextView startkm = rootView.findViewById(R.id.startkmValueLine); startkm.setText(String.valueOf(car.getStartKm())); TextView actualkm = rootView.findViewById(R.id.actualkmValueLine); int mileage = dataSource.getMileageForCar(carId); actualkm.setText(String.valueOf(mileage)); TextView consumption = rootView.findViewById(R.id.consumptionValueLine); consumption.setText(new DecimalFormat("#.00").format(dataSource .getOverallConsumptionForCar(carId)) + " l/100km"); TextView overallKm = rootView.findViewById(R.id.drivenKmValueLine); overallKm.setText(String.valueOf(mileage - car.getStartKm())); TextView overallCosts = rootView.findViewById(R.id.overallCostsValueLine); overallCosts.setText(new DecimalFormat("#0.00").format(dataSource .getOverallCostsForCar(carId)) + " \u20ac"); if (car.getImage() != null) { ImageView image = rootView.findViewById(R.id.pictureLine); image.setImageBitmap(car.getImage()); } } @SuppressWarnings("unused") private void exportData() { Car car = dataSource.getCarForId(carId); XMLHandler handler = new XMLHandler(null, car, dataSource.getOverallConsumptionForCar(carId), dataSource.getConsumptionCycles(carId)); try { accessor.writeXMLFileToStorage(getActivity(), handler.createConsumptionDocument(),
MainActivity.STORAGE_DIR,
6
2023-12-28 12:33:52+00:00
24k
strokegmd/StrokeClient
stroke/client/modules/ModuleManager.java
[ { "identifier": "AntiKnockback", "path": "stroke/client/modules/combat/AntiKnockback.java", "snippet": "public class AntiKnockback extends BaseModule {\r\n\tpublic static AntiKnockback instance;\r\n\t\r\n\tpublic AntiKnockback() {\r\n\t\tsuper(\"AntiKnockBack\", \"Disables knockback\", 0x00, ModuleCateg...
import java.util.ArrayList; import java.util.Comparator; import net.minecraft.client.Minecraft; import net.stroke.client.modules.combat.AntiKnockback; import net.stroke.client.modules.combat.AutoArmor; import net.stroke.client.modules.combat.AutoGApple; import net.stroke.client.modules.combat.AutoTotem; import net.stroke.client.modules.combat.Criticals; import net.stroke.client.modules.combat.CrystalAura; import net.stroke.client.modules.combat.KillAura; import net.stroke.client.modules.fun.HalalMode; import net.stroke.client.modules.misc.DiscordRPCModule; import net.stroke.client.modules.misc.MCF; import net.stroke.client.modules.misc.MigrationCape; import net.stroke.client.modules.misc.SelfDestruct; import net.stroke.client.modules.misc.Spammer; import net.stroke.client.modules.misc.StashLogger; import net.stroke.client.modules.movement.AirJump; import net.stroke.client.modules.movement.AutoJump; import net.stroke.client.modules.movement.EntitySpeed; import net.stroke.client.modules.movement.Flight; import net.stroke.client.modules.movement.InventoryMove; import net.stroke.client.modules.movement.NoSlowDown; import net.stroke.client.modules.movement.SafeWalk; import net.stroke.client.modules.movement.Sprint; import net.stroke.client.modules.movement.Step; import net.stroke.client.modules.player.Blink; import net.stroke.client.modules.player.ChestStealer; import net.stroke.client.modules.player.FastPlace; import net.stroke.client.modules.player.Freecam; import net.stroke.client.modules.player.NoFall; import net.stroke.client.modules.player.Portals; import net.stroke.client.modules.player.Timer; import net.stroke.client.modules.render.AntiOverlay; import net.stroke.client.modules.render.BlockHitAnim; import net.stroke.client.modules.render.ClickGui; import net.stroke.client.modules.render.FullBright; import net.stroke.client.modules.render.Hud; import net.stroke.client.modules.render.NameTags; import net.stroke.client.modules.render.NoScoreBoard; import net.stroke.client.modules.render.NoWeather; import net.stroke.client.modules.render.PlayerESP; import net.stroke.client.modules.render.StorageESP; import net.stroke.client.modules.render.TargetHUD; import net.stroke.client.modules.render.Tracers; import net.stroke.client.modules.render.ViewModel; import net.stroke.client.modules.render.Wallhack; import net.stroke.client.modules.render.XRay;
16,543
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather()); ModuleManager.addModule(new PlayerESP()); ModuleManager.addModule(new StorageESP()); ModuleManager.addModule(new TargetHUD()); ModuleManager.addModule(new Tracers()); ModuleManager.addModule(new ViewModel());
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather()); ModuleManager.addModule(new PlayerESP()); ModuleManager.addModule(new StorageESP()); ModuleManager.addModule(new TargetHUD()); ModuleManager.addModule(new Tracers()); ModuleManager.addModule(new ViewModel());
ModuleManager.addModule(new Wallhack());
43
2023-12-31 10:56:59+00:00
24k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/promotion/serviceimpl/KanjiaActivityLogServiceImpl.java
[ { "identifier": "ResultCode", "path": "framework/src/main/java/cn/lili/common/enums/ResultCode.java", "snippet": "public enum ResultCode {\n\n /**\n * 成功状态码\n */\n SUCCESS(200, \"成功\"),\n\n /**\n * 失败返回码\n */\n ERROR(400, \"服务器繁忙,请稍后重试\"),\n\n /**\n * 失败返回码\n */\n ...
import cn.lili.common.enums.ResultCode; import cn.lili.common.exception.ServiceException; import cn.lili.common.security.context.UserContext; import cn.lili.common.utils.BeanUtil; import cn.lili.common.vo.PageVO; import cn.lili.modules.promotion.entity.dos.KanjiaActivity; import cn.lili.modules.promotion.entity.dos.KanjiaActivityGoods; import cn.lili.modules.promotion.entity.dos.KanjiaActivityLog; import cn.lili.modules.promotion.entity.dto.KanjiaActivityDTO; import cn.lili.modules.promotion.entity.dto.search.KanJiaActivityLogQuery; import cn.lili.modules.promotion.entity.enums.PromotionsStatusEnum; import cn.lili.modules.promotion.mapper.KanJiaActivityLogMapper; import cn.lili.modules.promotion.service.KanjiaActivityGoodsService; import cn.lili.modules.promotion.service.KanjiaActivityLogService; import cn.lili.modules.promotion.service.KanjiaActivityService; import cn.lili.mybatis.util.PageUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
15,139
package cn.lili.modules.promotion.serviceimpl; /** * 砍价活动日志业务层实现 * * @author qiuqiu * @date 2021/7/1 */ @Service public class KanjiaActivityLogServiceImpl extends ServiceImpl<KanJiaActivityLogMapper, KanjiaActivityLog> implements KanjiaActivityLogService { @Autowired private KanjiaActivityGoodsService kanJiaActivityGoodsService; @Autowired
package cn.lili.modules.promotion.serviceimpl; /** * 砍价活动日志业务层实现 * * @author qiuqiu * @date 2021/7/1 */ @Service public class KanjiaActivityLogServiceImpl extends ServiceImpl<KanJiaActivityLogMapper, KanjiaActivityLog> implements KanjiaActivityLogService { @Autowired private KanjiaActivityGoodsService kanJiaActivityGoodsService; @Autowired
private KanjiaActivityService kanJiaActivityService;
14
2023-12-24 19:45:18+00:00
24k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/common/security/scram/internals/ScramSaslServer.java
[ { "identifier": "AuthenticationException", "path": "clients/src/main/java/org/apache/kafka/common/errors/AuthenticationException.java", "snippet": "public class AuthenticationException extends ApiException {\n\n private static final long serialVersionUID = 1L;\n\n public AuthenticationException(St...
import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.apache.kafka.common.errors.SaslAuthenticationException; import org.apache.kafka.common.security.authenticator.SaslInternalConfigs; import org.apache.kafka.common.security.scram.ScramCredential; import org.apache.kafka.common.security.scram.ScramCredentialCallback; import org.apache.kafka.common.security.scram.ScramLoginModule; import org.apache.kafka.common.security.scram.internals.ScramMessages.ClientFinalMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ClientFirstMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ServerFinalMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ServerFirstMessage; import org.apache.kafka.common.security.token.delegation.internals.DelegationTokenCredentialCallback; import org.apache.kafka.common.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
16,196
/* * 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.apache.kafka.common.security.scram.internals; /** * SaslServer implementation for SASL/SCRAM. This server is configured with a callback * handler for integration with a credential manager. Kafka brokers provide callbacks * based on a Zookeeper-based password store. * * @see <a href="https://tools.ietf.org/html/rfc5802">RFC 5802</a> */ public class ScramSaslServer implements SaslServer { private static final Logger log = LoggerFactory.getLogger(ScramSaslServer.class); private static final Set<String> SUPPORTED_EXTENSIONS = Utils.mkSet(ScramLoginModule.TOKEN_AUTH_CONFIG); enum State { RECEIVE_CLIENT_FIRST_MESSAGE, RECEIVE_CLIENT_FINAL_MESSAGE, COMPLETE, FAILED } private final ScramMechanism mechanism; private final ScramFormatter formatter; private final CallbackHandler callbackHandler; private State state; private String username; private ClientFirstMessage clientFirstMessage; private ServerFirstMessage serverFirstMessage; private ScramExtensions scramExtensions; private ScramCredential scramCredential; private String authorizationId; private Long tokenExpiryTimestamp; public ScramSaslServer(ScramMechanism mechanism, Map<String, ?> props, CallbackHandler callbackHandler) throws NoSuchAlgorithmException { this.mechanism = mechanism; this.formatter = new ScramFormatter(mechanism); this.callbackHandler = callbackHandler; setState(State.RECEIVE_CLIENT_FIRST_MESSAGE); } /** * @throws SaslAuthenticationException if the requested authorization id is not the same as username. * <p> * <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages * to clients. But care should be taken to avoid including any information in the exception message that * should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in * most cases so that a standard error message is returned to clients. * </p> */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { try { switch (state) { case RECEIVE_CLIENT_FIRST_MESSAGE: this.clientFirstMessage = new ClientFirstMessage(response); this.scramExtensions = clientFirstMessage.extensions(); if (!SUPPORTED_EXTENSIONS.containsAll(scramExtensions.map().keySet())) { log.debug("Unsupported extensions will be ignored, supported {}, provided {}", SUPPORTED_EXTENSIONS, scramExtensions.map().keySet()); } String serverNonce = formatter.secureRandomString(); try { String saslName = clientFirstMessage.saslName(); this.username = ScramFormatter.username(saslName); NameCallback nameCallback = new NameCallback("username", 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.apache.kafka.common.security.scram.internals; /** * SaslServer implementation for SASL/SCRAM. This server is configured with a callback * handler for integration with a credential manager. Kafka brokers provide callbacks * based on a Zookeeper-based password store. * * @see <a href="https://tools.ietf.org/html/rfc5802">RFC 5802</a> */ public class ScramSaslServer implements SaslServer { private static final Logger log = LoggerFactory.getLogger(ScramSaslServer.class); private static final Set<String> SUPPORTED_EXTENSIONS = Utils.mkSet(ScramLoginModule.TOKEN_AUTH_CONFIG); enum State { RECEIVE_CLIENT_FIRST_MESSAGE, RECEIVE_CLIENT_FINAL_MESSAGE, COMPLETE, FAILED } private final ScramMechanism mechanism; private final ScramFormatter formatter; private final CallbackHandler callbackHandler; private State state; private String username; private ClientFirstMessage clientFirstMessage; private ServerFirstMessage serverFirstMessage; private ScramExtensions scramExtensions; private ScramCredential scramCredential; private String authorizationId; private Long tokenExpiryTimestamp; public ScramSaslServer(ScramMechanism mechanism, Map<String, ?> props, CallbackHandler callbackHandler) throws NoSuchAlgorithmException { this.mechanism = mechanism; this.formatter = new ScramFormatter(mechanism); this.callbackHandler = callbackHandler; setState(State.RECEIVE_CLIENT_FIRST_MESSAGE); } /** * @throws SaslAuthenticationException if the requested authorization id is not the same as username. * <p> * <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages * to clients. But care should be taken to avoid including any information in the exception message that * should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in * most cases so that a standard error message is returned to clients. * </p> */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { try { switch (state) { case RECEIVE_CLIENT_FIRST_MESSAGE: this.clientFirstMessage = new ClientFirstMessage(response); this.scramExtensions = clientFirstMessage.extensions(); if (!SUPPORTED_EXTENSIONS.containsAll(scramExtensions.map().keySet())) { log.debug("Unsupported extensions will be ignored, supported {}, provided {}", SUPPORTED_EXTENSIONS, scramExtensions.map().keySet()); } String serverNonce = formatter.secureRandomString(); try { String saslName = clientFirstMessage.saslName(); this.username = ScramFormatter.username(saslName); NameCallback nameCallback = new NameCallback("username", username);
ScramCredentialCallback credentialCallback;
5
2023-12-23 07:12:18+00:00
24k
qiusunshine/xiu
app/src/main/java/org/mozilla/xiu/browser/webextension/Detector.java
[ { "identifier": "UrlDetector", "path": "app/src/main/java/org/mozilla/xiu/browser/download/UrlDetector.java", "snippet": "public class UrlDetector {\n\n private static List<String> apps = CollectionUtil.asList(\".css\", \".html\", \".js\", \".apk\", \".apks\", \".apk.1\", \".exe\", \".zip\", \".rar\"...
import org.json.JSONArray; import org.json.JSONObject; import org.mozilla.xiu.browser.download.UrlDetector; import org.mozilla.xiu.browser.session.SessionDelegate; import org.mozilla.xiu.browser.utils.CollectionUtil; import org.mozilla.xiu.browser.utils.FileUtil; import org.mozilla.xiu.browser.utils.HttpParser; import org.mozilla.xiu.browser.utils.StringUtil; import java.util.List;
19,111
package org.mozilla.xiu.browser.webextension; /** * 作者:By 15968 * 日期:On 2023/10/17 * 时间:At 14:03 */ public class Detector { private static List<String> videos = CollectionUtil.asList(".mp4", ".MP4", ".m3u8", ".flv", ".avi", ".3gp", "mpeg", ".wmv", ".mov", ".MOV", "rmvb", ".dat", ".mkv", "qqBFdownload", "mime=video%2F", "=video_mp4"); public static boolean hasVideoTag(String url) { if (url == null || url.isEmpty()) return false; if (!url.contains("#ignoreVideo=true#")) { for (String music : videos) { if (url.contains(music)) { return true; } } } return false; } private DetectorListener detectorListener; public void generateTypeAndSize(SessionDelegate sessionDelegate, TabRequest request) { try { //Log.d("test", "generateTypeAndSize: " + request.getUrl() + ", method: " + request.getMethod()); if ("get".equalsIgnoreCase(request.getMethod())) { boolean hasM3u8 = request.getUrl() != null && request.getUrl().contains(".m3u8"); String type = hasM3u8 ? TabRequest.VIDEO : TabRequest.OTHER; String size = null; JSONArray responseHeaders = request.getResponseHeaders(); if (responseHeaders != null) { for (int i = 0; i < responseHeaders.length(); i++) { JSONObject header = responseHeaders.optJSONObject(i); if (header == null) { continue; } if ("content-type".equalsIgnoreCase(header.optString("name"))) { String contentType = header.optString("value"); if (StringUtil.isNotEmpty(contentType)) { if (contentType.startsWith("video/")) { if ((request.getUrl() != null && request.getUrl().contains(".ts")) || "video/mp2t".equals(contentType)) { type = TabRequest.OTHER; } else { type = TabRequest.VIDEO; } } else if (contentType.startsWith("audio/")) { type = TabRequest.AUDIO; } else if (contentType.startsWith("image/")) { if (hasM3u8) { //fuckImage type = TabRequest.VIDEO; } else { type = TabRequest.IMAGE; } } else if (contentType.startsWith("text/")) { // if (hasM3u8 && !request.getUrl().contains("url=http")) { // type = TabRequest.VIDEO; // } if (hasM3u8) { type = TabRequest.VIDEO; } else { type = TabRequest.OTHER; } } else { if ("application/vnd.apple.mpegurl".equals(contentType) || hasM3u8) { type = TabRequest.VIDEO; } else if (isStream(contentType) && hasVideoTag(request.getUrl())) { type = TabRequest.VIDEO; } else { type = TabRequest.OTHER; } } } } else if ("content-length".equalsIgnoreCase(header.optString("name"))) { size = header.optString("value"); } } } request.setType(type); if (StringUtil.isNotEmpty(size)) { long s = Long.parseLong(size);
package org.mozilla.xiu.browser.webextension; /** * 作者:By 15968 * 日期:On 2023/10/17 * 时间:At 14:03 */ public class Detector { private static List<String> videos = CollectionUtil.asList(".mp4", ".MP4", ".m3u8", ".flv", ".avi", ".3gp", "mpeg", ".wmv", ".mov", ".MOV", "rmvb", ".dat", ".mkv", "qqBFdownload", "mime=video%2F", "=video_mp4"); public static boolean hasVideoTag(String url) { if (url == null || url.isEmpty()) return false; if (!url.contains("#ignoreVideo=true#")) { for (String music : videos) { if (url.contains(music)) { return true; } } } return false; } private DetectorListener detectorListener; public void generateTypeAndSize(SessionDelegate sessionDelegate, TabRequest request) { try { //Log.d("test", "generateTypeAndSize: " + request.getUrl() + ", method: " + request.getMethod()); if ("get".equalsIgnoreCase(request.getMethod())) { boolean hasM3u8 = request.getUrl() != null && request.getUrl().contains(".m3u8"); String type = hasM3u8 ? TabRequest.VIDEO : TabRequest.OTHER; String size = null; JSONArray responseHeaders = request.getResponseHeaders(); if (responseHeaders != null) { for (int i = 0; i < responseHeaders.length(); i++) { JSONObject header = responseHeaders.optJSONObject(i); if (header == null) { continue; } if ("content-type".equalsIgnoreCase(header.optString("name"))) { String contentType = header.optString("value"); if (StringUtil.isNotEmpty(contentType)) { if (contentType.startsWith("video/")) { if ((request.getUrl() != null && request.getUrl().contains(".ts")) || "video/mp2t".equals(contentType)) { type = TabRequest.OTHER; } else { type = TabRequest.VIDEO; } } else if (contentType.startsWith("audio/")) { type = TabRequest.AUDIO; } else if (contentType.startsWith("image/")) { if (hasM3u8) { //fuckImage type = TabRequest.VIDEO; } else { type = TabRequest.IMAGE; } } else if (contentType.startsWith("text/")) { // if (hasM3u8 && !request.getUrl().contains("url=http")) { // type = TabRequest.VIDEO; // } if (hasM3u8) { type = TabRequest.VIDEO; } else { type = TabRequest.OTHER; } } else { if ("application/vnd.apple.mpegurl".equals(contentType) || hasM3u8) { type = TabRequest.VIDEO; } else if (isStream(contentType) && hasVideoTag(request.getUrl())) { type = TabRequest.VIDEO; } else { type = TabRequest.OTHER; } } } } else if ("content-length".equalsIgnoreCase(header.optString("name"))) { size = header.optString("value"); } } } request.setType(type); if (StringUtil.isNotEmpty(size)) { long s = Long.parseLong(size);
request.setSize(FileUtil.getFormatedFileSize(s));
2
2023-11-10 14:28:40+00:00
24k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/ShrineCommandExecutor.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.managers.DevotionManager; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.managers.ShrineManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Formatter; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Location; import org.bukkit.block.Block; 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 org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.jetbrains.annotations.NotNull; import java.util.*;
15,542
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId()); if (favorManager == null || favorManager.getDeity() == null) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_FOLLOW_DEITY_TO_DESIGNATE); return true; } // Fetch the deity directly from the player's FavorManager Deity deity = favorManager.getDeity(); pendingShrineDesignations.put(player, deity); Devotions.getInstance().sendMessage(player, Messages.SHRINE_CLICK_BLOCK_TO_DESIGNATE.formatted( Placeholder.unparsed("deity", deity.getName()) )); return true; } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_SET); return false; } return false; } @EventHandler public void onShrineDesignation(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) return; if (pendingShrineDesignations.containsKey(player)) { Block clickedBlock = event.getClickedBlock(); if (clickedBlock != null) {
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId()); if (favorManager == null || favorManager.getDeity() == null) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_FOLLOW_DEITY_TO_DESIGNATE); return true; } // Fetch the deity directly from the player's FavorManager Deity deity = favorManager.getDeity(); pendingShrineDesignations.put(player, deity); Devotions.getInstance().sendMessage(player, Messages.SHRINE_CLICK_BLOCK_TO_DESIGNATE.formatted( Placeholder.unparsed("deity", deity.getName()) )); return true; } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_SET); return false; } return false; } @EventHandler public void onShrineDesignation(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) return; if (pendingShrineDesignations.containsKey(player)) { Block clickedBlock = event.getClickedBlock(); if (clickedBlock != null) {
Shrine existingShrine = shrineManager.getShrineAtLocation(clickedBlock.getLocation());
2
2023-11-10 07:03:24+00:00
24k
SplitfireUptown/datalinkx
flinkx/flinkx-rdb/flinkx-rdb-reader/src/main/java/com.dtstack.flinkx.rdb.inputformat/JdbcInputFormat.java
[ { "identifier": "ConstantValue", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java", "snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final Stri...
import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.constants.Metrics; import com.dtstack.flinkx.enums.ColumnType; import com.dtstack.flinkx.inputformat.BaseRichInputFormat; import com.dtstack.flinkx.rdb.DatabaseInterface; import com.dtstack.flinkx.rdb.datareader.IncrementConfig; import com.dtstack.flinkx.rdb.type.TypeConverterInterface; import com.dtstack.flinkx.rdb.util.DbUtil; import com.dtstack.flinkx.reader.MetaColumn; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ClassUtil; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.FileSystemUtil; import com.dtstack.flinkx.util.GsonUtil; import com.dtstack.flinkx.util.RetryUtil; import com.dtstack.flinkx.util.StringUtil; import com.dtstack.flinkx.util.UrlUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.apache.flink.core.io.InputSplit; import org.apache.flink.types.Row; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.IOUtils; import java.io.IOException; import java.math.BigInteger; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit;
20,943
} String endFilter = buildEndLocationSql(incrementColType, incrementCol, endLocation); if (org.apache.commons.lang.StringUtils.isNotEmpty(endFilter)) { if (filter.length() > 0) { filter.append(" and ").append(endFilter); } else { filter.append(endFilter); } } return filter.toString(); } /** * 构建起始位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param startLocation 开始位置 * @param useMaxFunc 是否保存结束位置数据 * @return */ protected String buildStartLocationSql(String incrementColType, String incrementCol, String startLocation, boolean useMaxFunc) { if (org.apache.commons.lang.StringUtils.isEmpty(startLocation) || DbUtil.NULL_STRING.equalsIgnoreCase(startLocation)) { return null; } String operator = useMaxFunc ? " >= " : " > "; //增量轮询,startLocation使用占位符代替 if (incrementConfig.isPolling()) { return incrementCol + operator + "?"; } return getLocationSql(incrementColType, incrementCol, startLocation, operator); } /** * 构建结束位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param endLocation 结束位置 * @return */ public String buildEndLocationSql(String incrementColType, String incrementCol, String endLocation) { if (org.apache.commons.lang.StringUtils.isEmpty(endLocation) || DbUtil.NULL_STRING.equalsIgnoreCase(endLocation)) { return null; } return getLocationSql(incrementColType, incrementCol, endLocation, " < "); } /** * 构建边界位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param location 边界位置(起始/结束) * @param operator 判断符( >, >=, <) * @return */ protected String getLocationSql(String incrementColType, String incrementCol, String location, String operator) { String endTimeStr; String endLocationSql; if (ColumnType.isTimeType(incrementColType)) { endTimeStr = getTimeStr(Long.parseLong(location), incrementColType); endLocationSql = incrementCol + operator + endTimeStr; } else if (ColumnType.isNumberType(incrementColType)) { endLocationSql = incrementCol + operator + location; } else { endTimeStr = String.format("'%s'", location); endLocationSql = incrementCol + operator + endTimeStr; } return endLocationSql; } /** * 构建时间边界字符串 * * @param location 边界位置(起始/结束) * @param incrementColType 增量字段类型 * @return */ protected String getTimeStr(Long location, String incrementColType) { String timeStr; Timestamp ts = new Timestamp(DbUtil.getMillis(location)); ts.setNanos(DbUtil.getNanos(location)); timeStr = DbUtil.getNanosTimeStr(ts.toString()); timeStr = timeStr.substring(0, 26); timeStr = String.format("'%s'", timeStr); return timeStr; } /** * 边界位置值转字符串 * * @param columnType 边界字段类型 * @param columnVal 边界值 * @return */ private String getLocation(String columnType, Object columnVal) { if (columnVal == null) { return null; } return columnVal.toString(); } /** * 上传累加器数据 * * @throws IOException */ private void uploadMetricData() throws IOException { FSDataOutputStream out = null; try {
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.rdb.inputformat; /** * InputFormat for reading data from a database and generate Rows. * <p> * Company: www.dtstack.com * * @author huyifan.zju@163.com */ public class JdbcInputFormat extends BaseRichInputFormat { public static final long serialVersionUID = 1L; public static final int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; public static int resultSetType = ResultSet.TYPE_FORWARD_ONLY; public DatabaseInterface databaseInterface; public String table; public String queryTemplate; public String customSql; public String querySql; public String splitKey; public int fetchSize = 10000; public int queryTimeOut; public IncrementConfig incrementConfig; public String username; public String password; public String driverName; public String dbUrl; public Properties properties; public transient Connection dbConn; public transient Statement statement; public transient PreparedStatement ps; public transient ResultSet resultSet; public boolean hasNext; public List<MetaColumn> metaColumns; public List<String> columnTypeList; public int columnCount; public MetaColumn restoreColumn; public Row lastRow = null; public long count = 0; public long timestamp = 0; //for postgre public TypeConverterInterface typeConverter; public int numPartitions; public StringAccumulator maxValueAccumulator; public BigIntegerMaximum endLocationAccumulator; public BigIntegerMaximum startLocationAccumulator; //轮询增量标识字段类型 public ColumnType type; //The hadoop config for metric public Map<String, Object> hadoopConfig; @Override public void openInputFormat() throws IOException { super.openInputFormat(); if (restoreConfig == null || !restoreConfig.isRestore()){ return; } if (restoreConfig.getRestoreColumnIndex() == -1) { throw new IllegalArgumentException("Restore column index must specified"); } restoreColumn = metaColumns.get(restoreConfig.getRestoreColumnIndex()); } @Override public void openInternal(InputSplit inputSplit) throws IOException { LOG.info("inputSplit = {}", inputSplit); ClassUtil.forName(driverName, getClass().getClassLoader()); initMetric(inputSplit); if (!canReadData(inputSplit)) { LOG.warn("Not read data when the start location are equal to end location"); hasNext = false; return; } querySql = buildQuerySql(inputSplit); try { executeQuery(((JdbcInputSplit) inputSplit).getStartLocation()); if(!resultSet.isClosed()){ columnCount = resultSet.getMetaData().getColumnCount(); } } catch (SQLException se) { LOG.error("querySql: " + querySql); throw new IllegalArgumentException("open() failed." + se.getMessage(), se); } boolean splitWithRowCol = numPartitions > 1 && StringUtils.isNotEmpty(splitKey) && splitKey.contains("("); if (splitWithRowCol) { columnCount = columnCount - 1; } checkSize(columnCount, metaColumns); columnTypeList = DbUtil.analyzeColumnType(resultSet, metaColumns); LOG.info("JdbcInputFormat[{}]open: end", jobName); } @Override public InputSplit[] createInputSplitsInternal(int minNumSplits) { JdbcInputSplit[] splits = new JdbcInputSplit[minNumSplits]; for (int i = 0; i < minNumSplits; i++) { splits[i] = new JdbcInputSplit(i, numPartitions, i, incrementConfig.getStartLocation(), null); } return splits; } @Override public boolean reachedEnd() throws IOException{ if (hasNext) { return false; } else { if (incrementConfig.isPolling()) { try { TimeUnit.MILLISECONDS.sleep(incrementConfig.getPollingInterval()); //sqlserver、DB2驱动包不支持isValid(),这里先注释掉,后续更换驱动包 //间隔轮询检测数据库连接是否断开,超时时间三秒,断开后自动重连 // if(!dbConn.isValid(3)){ // dbConn = DbUtil.getConnection(dbUrl, username, password); // //重新连接后还是不可用则认为数据库异常,任务失败 // if(!dbConn.isValid(3)){ // String message = String.format("cannot connect to %s, username = %s, please check %s is available.", dbUrl, username, databaseInterface.getDatabaseType()); // LOG.error(message); // throw new RuntimeException(message); // } // } if(!dbConn.getAutoCommit()){ dbConn.setAutoCommit(true); } DbUtil.closeDbResources(resultSet, null, null, false); //此处endLocation理应不会为空 queryForPolling(endLocationAccumulator.getLocalValue().toString()); return false; } catch (InterruptedException e) { LOG.warn("interrupted while waiting for polling, e = {}", ExceptionUtil.getErrorMessage(e)); } catch (SQLException e) { DbUtil.closeDbResources(resultSet, ps, null, false); String message = String.format("error to execute sql = %s, startLocation = %s, e = %s", querySql, endLocationAccumulator.getLocalValue(), ExceptionUtil.getErrorMessage(e)); LOG.error(message); throw new RuntimeException(message, e); } } return true; } } @Override public Row nextRecordInternal(Row row) throws IOException { try { updateColumnCount(); if (!ConstantValue.STAR_SYMBOL.equals(metaColumns.get(0).getName())) { for (int i = 0; i < columnCount; i++) { Object val = row.getField(i); if (val == null && metaColumns.get(i).getValue() != null) { val = metaColumns.get(i).getValue(); } if (val instanceof String) { val = StringUtil.string2col(String.valueOf(val), metaColumns.get(i).getType(), metaColumns.get(i).getTimeFormat()); row.setField(i, val); } } } boolean isUpdateLocation = incrementConfig.isPolling() || (incrementConfig.isIncrement() && !incrementConfig.isUseMaxFunc()); if (isUpdateLocation) { String location = null; Object obj = resultSet.getObject(incrementConfig.getColumnName()); if(obj != null) { if((obj instanceof java.util.Date || obj.getClass().getSimpleName().toUpperCase().contains(ColumnType.TIMESTAMP.name())) ) { obj = resultSet.getTimestamp(incrementConfig.getColumnName()).getTime(); } location = String.valueOf(obj); endLocationAccumulator.add(new BigInteger(location)); } LOG.trace("update endLocationAccumulator, current Location = {}", location); } count++; if (count == fetchSize) { long current = System.currentTimeMillis(); LOG.error(">>>>>>>> jobId: {} end read use time: {} count: {}", jobName, current - timestamp, count); timestamp = current; count = 0; } hasNext = resultSet.next(); if (restoreConfig.isRestore()) { lastRow = row; } return row; } catch (SQLException se) { throw new IOException("Couldn't read data - " + se.getMessage(), se); } catch (Exception npe) { throw new IOException("Couldn't access resultSet", npe); } } @Override public FormatState getFormatState() { super.getFormatState(); if (formatState != null && lastRow != null) { formatState.setState(lastRow.getField(restoreConfig.getRestoreColumnIndex())); } return formatState; } @Override public void closeInternal() throws IOException { if (incrementConfig.isIncrement() && hadoopConfig != null) { uploadMetricData(); } DbUtil.closeDbResources(resultSet, statement, dbConn, true); } /** * 初始化增量或或间隔轮询任务累加器 * * @param inputSplit 数据分片 */ protected void initMetric(InputSplit inputSplit) { if (!incrementConfig.isIncrement()) { return; } //初始化增量、轮询字段类型 type = ColumnType.fromString(incrementConfig.getColumnType()); startLocationAccumulator = new BigIntegerMaximum(); endLocationAccumulator = new BigIntegerMaximum(); String startLocation = StringUtil.stringToTimestampStr(incrementConfig.getStartLocation(), type); if (StringUtils.isNotEmpty(incrementConfig.getStartLocation())) { ((JdbcInputSplit) inputSplit).setStartLocation(startLocation); startLocationAccumulator.add(new BigInteger(startLocation)); } //轮询任务endLocation设置为startLocation的值 if (incrementConfig.isPolling()) { if (StringUtils.isNotEmpty(startLocation)) { endLocationAccumulator.add(new BigInteger(startLocation)); } } else if (incrementConfig.isUseMaxFunc()) { //如果不是轮询任务,则只能是增量任务,若useMaxFunc设置为true,则去数据库查询当前增量字段的最大值 getMaxValue(inputSplit); //endLocation设置为数据库中查询的最大值 String endLocation = ((JdbcInputSplit) inputSplit).getEndLocation(); endLocationAccumulator.add(new BigInteger(StringUtil.stringToTimestampStr(endLocation, type))); }else{ //增量任务,且useMaxFunc设置为false,如果startLocation不为空,则将endLocation初始值设置为startLocation的值,防止数据库无增量数据时下次获取到的startLocation为空 if (StringUtils.isNotEmpty(startLocation)) { endLocationAccumulator.add(new BigInteger(startLocation)); } } //将累加器信息添加至prometheus customPrometheusReporter.registerMetric(startLocationAccumulator, Metrics.START_LOCATION); customPrometheusReporter.registerMetric(endLocationAccumulator, Metrics.END_LOCATION); getRuntimeContext().addAccumulator(Metrics.START_LOCATION, startLocationAccumulator); getRuntimeContext().addAccumulator(Metrics.END_LOCATION, endLocationAccumulator); } /** * 将增量任务的数据最大值设置到累加器中 * * @param inputSplit 数据分片 */ protected void getMaxValue(InputSplit inputSplit) { String maxValue; if (inputSplit.getSplitNumber() == 0) { maxValue = getMaxValueFromDb(); //将累加器信息上传至flink,供其他通道通过flink rest api获取该最大值 maxValueAccumulator = new StringAccumulator(); maxValueAccumulator.add(maxValue); getRuntimeContext().addAccumulator(Metrics.MAX_VALUE, maxValueAccumulator); } else { maxValue = getMaxValueFromApi(); } if (StringUtils.isEmpty(maxValue)) { throw new RuntimeException("Can't get the max value from accumulator"); } ((JdbcInputSplit) inputSplit).setEndLocation(maxValue); } /** * 从数据库中查询增量字段的最大值 * * @return */ private String getMaxValueFromDb() { String maxValue = null; Connection conn = null; Statement st = null; ResultSet rs = null; try { long startTime = System.currentTimeMillis(); String queryMaxValueSql; if (StringUtils.isNotEmpty(customSql)) { queryMaxValueSql = String.format("select max(%s.%s) as max_value from ( %s ) %s", DbUtil.TEMPORARY_TABLE_NAME, databaseInterface.quoteColumn(incrementConfig.getColumnName()), customSql, DbUtil.TEMPORARY_TABLE_NAME); } else { queryMaxValueSql = String.format("select max(%s) as max_value from %s", databaseInterface.quoteColumn(incrementConfig.getColumnName()), databaseInterface.quoteTable(table)); } String startSql = buildStartLocationSql(incrementConfig.getColumnType(), databaseInterface.quoteColumn(incrementConfig.getColumnName()), incrementConfig.getStartLocation(), incrementConfig.isUseMaxFunc()); if (StringUtils.isNotEmpty(startSql)) { queryMaxValueSql += " where " + startSql; } LOG.info(String.format("Query max value sql is '%s'", queryMaxValueSql)); conn = getConnection(); st = conn.createStatement(resultSetType, resultSetConcurrency); rs = st.executeQuery(queryMaxValueSql); if (rs.next()) { switch (type) { case TIMESTAMP: maxValue = String.valueOf(rs.getTimestamp("max_value").getTime()); break; case DATE: maxValue = String.valueOf(rs.getDate("max_value").getTime()); break; default: maxValue = StringUtil.stringToTimestampStr(String.valueOf(rs.getObject("max_value")), type); } } LOG.info(String.format("Takes [%s] milliseconds to get the maximum value [%s]", System.currentTimeMillis() - startTime, maxValue)); return maxValue; } catch (Throwable e) { throw new RuntimeException("Get max value from " + table + " error", e); } finally { DbUtil.closeDbResources(rs, st, conn, false); } } /** * 从flink rest api中获取累加器最大值 * @return */ @SuppressWarnings("unchecked") public String getMaxValueFromApi(){ if(StringUtils.isEmpty(monitorUrls)){ return null; } String url = monitorUrls; if (monitorUrls.startsWith(ConstantValue.PROTOCOL_HTTP)) { url = String.format("%s/jobs/%s/accumulators", monitorUrls, jobId); } //The extra 10 times is to ensure that accumulator is updated int maxAcquireTimes = (queryTimeOut / incrementConfig.getRequestAccumulatorInterval()) + 10; final String[] maxValue = new String[1]; Gson gson = new Gson(); UrlUtil.get(url, incrementConfig.getRequestAccumulatorInterval() * 1000, maxAcquireTimes, new UrlUtil.Callback() { @Override public void call(String response) { Map map = gson.fromJson(response, Map.class); LOG.info("Accumulator data:" + gson.toJson(map)); List<Map> userTaskAccumulators = (List<Map>) map.get("user-task-accumulators"); for (Map accumulator : userTaskAccumulators) { if (Metrics.MAX_VALUE.equals(accumulator.get("name"))) { maxValue[0] = (String) accumulator.get("value"); break; } } } @Override public boolean isReturn() { return StringUtils.isNotEmpty(maxValue[0]); } @Override public void processError(Exception e) { LOG.warn(ExceptionUtil.getErrorMessage(e)); } }); return maxValue[0]; } /** * 判断增量任务是否还能继续读取数据 * 增量任务,startLocation = endLocation且两者都不为null,返回false,其余情况返回true * * @param split 数据分片 * @return */ protected boolean canReadData(InputSplit split) { //只排除增量同步 if (!incrementConfig.isIncrement() || incrementConfig.isPolling()) { return true; } JdbcInputSplit jdbcInputSplit = (JdbcInputSplit) split; if (jdbcInputSplit.getStartLocation() == null && jdbcInputSplit.getEndLocation() == null) { return true; } return !StringUtils.equals(jdbcInputSplit.getStartLocation(), jdbcInputSplit.getEndLocation()); } /** * 构造查询sql * * @param inputSplit 数据切片 * @return 构建的sql字符串 */ protected String buildQuerySql(InputSplit inputSplit) { //QuerySqlBuilder中构建的queryTemplate String querySql = queryTemplate; if (inputSplit == null) { LOG.warn("inputSplit = null, Executing sql is: '{}'", querySql); return querySql; } JdbcInputSplit jdbcInputSplit = (JdbcInputSplit) inputSplit; if (StringUtils.isNotEmpty(splitKey)) { querySql = queryTemplate.replace("${N}", String.valueOf(numPartitions)).replace("${M}", String.valueOf(indexOfSubTask)); } //是否开启断点续传 if (restoreConfig.isRestore()) { if (formatState == null) { querySql = querySql.replace(DbUtil.RESTORE_FILTER_PLACEHOLDER, StringUtils.EMPTY); if (incrementConfig.isIncrement()) { querySql = buildIncrementSql(jdbcInputSplit, querySql); } } else { boolean useMaxFunc = incrementConfig.isUseMaxFunc(); String startLocation = getLocation(restoreColumn.getType(), formatState.getState()); if (StringUtils.isNotBlank(startLocation)) { LOG.info("update startLocation, before = {}, after = {}", jdbcInputSplit.getStartLocation(), startLocation); jdbcInputSplit.setStartLocation(startLocation); useMaxFunc = false; } String restoreFilter = buildIncrementFilter(restoreColumn.getType(), restoreColumn.getName(), jdbcInputSplit.getStartLocation(), jdbcInputSplit.getEndLocation(), customSql, useMaxFunc); if (StringUtils.isNotEmpty(restoreFilter)) { restoreFilter = " and " + restoreFilter; } querySql = querySql.replace(DbUtil.RESTORE_FILTER_PLACEHOLDER, restoreFilter); } querySql = querySql.replace(DbUtil.INCREMENT_FILTER_PLACEHOLDER, StringUtils.EMPTY); } else if (incrementConfig.isIncrement()) { querySql = buildIncrementSql(jdbcInputSplit, querySql); } LOG.warn("Executing sql is: '{}'", querySql); return querySql; } /** * 构造增量任务查询sql * * @param jdbcInputSplit 数据切片 * @param querySql 已经创建的查询sql * @return */ private String buildIncrementSql(JdbcInputSplit jdbcInputSplit, String querySql) { String incrementFilter = buildIncrementFilter(incrementConfig.getColumnType(), incrementConfig.getColumnName(), jdbcInputSplit.getStartLocation(), jdbcInputSplit.getEndLocation(), customSql, incrementConfig.isUseMaxFunc()); if (StringUtils.isNotEmpty(incrementFilter)) { incrementFilter = " and " + incrementFilter; } return querySql.replace(DbUtil.INCREMENT_FILTER_PLACEHOLDER, incrementFilter); } /** * 构建增量任务查询sql的过滤条件 * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param startLocation 开始位置 * @param endLocation 结束位置 * @param customSql 用户自定义sql * @param useMaxFunc 是否保存结束位置数据 * @return */ protected String buildIncrementFilter(String incrementColType, String incrementCol, String startLocation, String endLocation, String customSql, boolean useMaxFunc) { LOG.info("buildIncrementFilter, incrementColType = {}, incrementCol = {}, startLocation = {}, endLocation = {}, customSql = {}, useMaxFunc = {}", incrementColType, incrementCol, startLocation, endLocation, customSql, useMaxFunc); StringBuilder filter = new StringBuilder(128); if (org.apache.commons.lang.StringUtils.isNotEmpty(customSql)) { incrementCol = String.format("%s.%s", DbUtil.TEMPORARY_TABLE_NAME, databaseInterface.quoteColumn(incrementCol)); } else { incrementCol = databaseInterface.quoteColumn(incrementCol); } String startFilter = buildStartLocationSql(incrementColType, incrementCol, startLocation, useMaxFunc); if (org.apache.commons.lang.StringUtils.isNotEmpty(startFilter)) { filter.append(startFilter); } String endFilter = buildEndLocationSql(incrementColType, incrementCol, endLocation); if (org.apache.commons.lang.StringUtils.isNotEmpty(endFilter)) { if (filter.length() > 0) { filter.append(" and ").append(endFilter); } else { filter.append(endFilter); } } return filter.toString(); } /** * 构建起始位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param startLocation 开始位置 * @param useMaxFunc 是否保存结束位置数据 * @return */ protected String buildStartLocationSql(String incrementColType, String incrementCol, String startLocation, boolean useMaxFunc) { if (org.apache.commons.lang.StringUtils.isEmpty(startLocation) || DbUtil.NULL_STRING.equalsIgnoreCase(startLocation)) { return null; } String operator = useMaxFunc ? " >= " : " > "; //增量轮询,startLocation使用占位符代替 if (incrementConfig.isPolling()) { return incrementCol + operator + "?"; } return getLocationSql(incrementColType, incrementCol, startLocation, operator); } /** * 构建结束位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param endLocation 结束位置 * @return */ public String buildEndLocationSql(String incrementColType, String incrementCol, String endLocation) { if (org.apache.commons.lang.StringUtils.isEmpty(endLocation) || DbUtil.NULL_STRING.equalsIgnoreCase(endLocation)) { return null; } return getLocationSql(incrementColType, incrementCol, endLocation, " < "); } /** * 构建边界位置sql * * @param incrementColType 增量字段类型 * @param incrementCol 增量字段名称 * @param location 边界位置(起始/结束) * @param operator 判断符( >, >=, <) * @return */ protected String getLocationSql(String incrementColType, String incrementCol, String location, String operator) { String endTimeStr; String endLocationSql; if (ColumnType.isTimeType(incrementColType)) { endTimeStr = getTimeStr(Long.parseLong(location), incrementColType); endLocationSql = incrementCol + operator + endTimeStr; } else if (ColumnType.isNumberType(incrementColType)) { endLocationSql = incrementCol + operator + location; } else { endTimeStr = String.format("'%s'", location); endLocationSql = incrementCol + operator + endTimeStr; } return endLocationSql; } /** * 构建时间边界字符串 * * @param location 边界位置(起始/结束) * @param incrementColType 增量字段类型 * @return */ protected String getTimeStr(Long location, String incrementColType) { String timeStr; Timestamp ts = new Timestamp(DbUtil.getMillis(location)); ts.setNanos(DbUtil.getNanos(location)); timeStr = DbUtil.getNanosTimeStr(ts.toString()); timeStr = timeStr.substring(0, 26); timeStr = String.format("'%s'", timeStr); return timeStr; } /** * 边界位置值转字符串 * * @param columnType 边界字段类型 * @param columnVal 边界值 * @return */ private String getLocation(String columnType, Object columnVal) { if (columnVal == null) { return null; } return columnVal.toString(); } /** * 上传累加器数据 * * @throws IOException */ private void uploadMetricData() throws IOException { FSDataOutputStream out = null; try {
org.apache.hadoop.conf.Configuration conf = FileSystemUtil.getConfiguration(hadoopConfig, null);
12
2023-11-16 02:22:52+00:00
24k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorArithmetic.java
[ { "identifier": "JNumDataType", "path": "src/main/java/utils/JNumDataType.java", "snippet": "public enum JNumDataType {\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE\n}" }, { "identifier": "NumberUtils", "path": "src/main/java/utils/NumberUtils.java", "snippet": "pu...
import utils.JNumDataType; import utils.NumberUtils; import utils.TypeUtils; import java.util.Arrays; import java.util.Map; import java.util.function.BiFunction;
19,546
package internals; public class TensorArithmetic { static Tensor add(Tensor firstTensor, Tensor secondTensor) {
package internals; public class TensorArithmetic { static Tensor add(Tensor firstTensor, Tensor secondTensor) {
return performOperation(firstTensor, secondTensor, NumberUtils.ADD);
1
2023-11-13 19:53:02+00:00
24k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/menus/FlowerCreationMenu.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowe...
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.data.FlowerGroupData; import com.uroria.betterflowers.flowers.SingleFlower; import com.uroria.betterflowers.flowers.placable.FlowerGroup; import com.uroria.betterflowers.managers.LanguageManager; import com.uroria.betterflowers.utils.BukkitPlayerInventory; import com.uroria.betterflowers.utils.CandleCollection; import com.uroria.betterflowers.utils.FlowerCollection; import com.uroria.betterflowers.data.FlowerData; import com.uroria.betterflowers.utils.ItemBuilder; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
19,807
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager;
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager;
private final List<FlowerData> personalFlower;
7
2023-11-18 16:13:59+00:00
24k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/doc/Examples.java
[ { "identifier": "Asaas", "path": "src/main/java/io/github/jpdev/asaassdk/http/Asaas.java", "snippet": "public class Asaas {\n\n private static final String ENDPOINT_PRODUCTION = \"https://www.asaas.com/api/v3\";\n private static final String ENDPOINT_SANDBOX = \"https://sandbox.asaas.com/api/v3\";...
import io.github.jpdev.asaassdk.http.Asaas; import io.github.jpdev.asaassdk.rest.accounts.Account; import io.github.jpdev.asaassdk.rest.accounts.AccountCreator; import io.github.jpdev.asaassdk.rest.action.ResourceSet; import io.github.jpdev.asaassdk.rest.bill.Bill; import io.github.jpdev.asaassdk.rest.commons.DeletedResource; import io.github.jpdev.asaassdk.rest.customeraccount.CustomerAccount; import io.github.jpdev.asaassdk.rest.finance.FinanceBalance; import io.github.jpdev.asaassdk.rest.financialtransaction.FinancialTransaction; import io.github.jpdev.asaassdk.rest.installment.Installment; import io.github.jpdev.asaassdk.rest.invoice.Invoice; import io.github.jpdev.asaassdk.rest.invoice.Taxes; import io.github.jpdev.asaassdk.rest.myaccount.accountnumber.AccountNumber; import io.github.jpdev.asaassdk.rest.myaccount.commercialinfo.CommercialInfo; import io.github.jpdev.asaassdk.rest.myaccount.fee.AccountFee; import io.github.jpdev.asaassdk.rest.myaccount.status.MyAccountStatus; import io.github.jpdev.asaassdk.rest.notification.NotificationConfig; import io.github.jpdev.asaassdk.rest.payment.Payment; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentLinkChargeType; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentStatus; import io.github.jpdev.asaassdk.rest.payment.identificationfield.PaymentIdentificationField; import io.github.jpdev.asaassdk.rest.payment.status.PaymentStatusData; import io.github.jpdev.asaassdk.rest.paymentlink.PaymentLink; import io.github.jpdev.asaassdk.rest.pix.addresskey.PixAddressKey; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyStatus; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyType; import io.github.jpdev.asaassdk.rest.pix.enums.PixTransactionType; import io.github.jpdev.asaassdk.rest.pix.qrcode.PixQrCode; import io.github.jpdev.asaassdk.rest.pix.qrcode.decode.PixDecodedQrCode; import io.github.jpdev.asaassdk.rest.pix.transaction.PixTransaction; import io.github.jpdev.asaassdk.rest.transfer.Transfer; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountSetting; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountType; import io.github.jpdev.asaassdk.rest.transfer.children.BankSetting; import io.github.jpdev.asaassdk.utils.BillingType; import io.github.jpdev.asaassdk.utils.Money; import java.math.BigDecimal; import java.util.Date;
20,182
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() {
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() {
PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder()
28
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/client/gui/hud/items/HudItemSanity.java
[ { "identifier": "Gui_EventManager", "path": "src/main/java/enviromine/client/gui/Gui_EventManager.java", "snippet": "@SideOnly(Side.CLIENT)\npublic class Gui_EventManager\n{\n\n\tint width, height;\n\n\t//Render HUD\n\t//Render Player\n\n\t// Button Functions\n\tGuiButton enviromine;\n\n\t// Captures th...
import org.lwjgl.opengl.GL11; import enviromine.client.gui.Gui_EventManager; import enviromine.client.gui.UI_Settings; import enviromine.client.gui.hud.HUDRegistry; import enviromine.client.gui.hud.HudItem; import enviromine.core.EM_Settings; import enviromine.utils.Alignment; import enviromine.utils.EnviroUtils; import enviromine.utils.RenderAssist; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector;
18,859
package enviromine.client.gui.hud.items; public class HudItemSanity extends HudItem { @Override public String getName() { return "Sanity"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.sanity"); } @Override public String getButtonLabel() { return getNameLoc() +" Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return (((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return (HUDRegistry.screenHeight - 30); } @Override public int getWidth() {
package enviromine.client.gui.hud.items; public class HudItemSanity extends HudItem { @Override public String getName() { return "Sanity"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.sanity"); } @Override public String getButtonLabel() { return getNameLoc() +" Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return (((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return (HUDRegistry.screenHeight - 30); } @Override public int getWidth() {
return UI_Settings.minimalHud && !rotated ? 0 : 64;
1
2023-11-16 18:15:29+00:00
24k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/mixin/RenderItemMixin.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.world.World; 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 sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.model.IGunModel; import sheridan.gunscraft.render.GenericGunRenderer; import sheridan.gunscraft.render.IGunRender; import sheridan.gunscraft.render.TransformData; import static net.minecraft.client.renderer.model.ItemCameraTransforms.TransformType.GUI;
15,253
package sheridan.gunscraft.mixin; @Mixin(ItemRenderer.class) public class RenderItemMixin { private final IGunRender renderer = ClientProxy.renderer; // all model, ground, gui, other @Inject(at = @At("HEAD"), method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/renderer/model/ItemCameraTransforms$TransformType;ZLcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;IILnet/minecraft/client/renderer/model/IBakedModel;)V", cancellable = true) public void renderItem(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, boolean leftHand, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IBakedModel modelIn, CallbackInfo ci) { if (itemStackIn != null && itemStackIn.getItem() instanceof IGenericGun) { IGunModel model = ClientProxy.gunModelMap.get(itemStackIn.getItem()); if (model != null) {
package sheridan.gunscraft.mixin; @Mixin(ItemRenderer.class) public class RenderItemMixin { private final IGunRender renderer = ClientProxy.renderer; // all model, ground, gui, other @Inject(at = @At("HEAD"), method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/renderer/model/ItemCameraTransforms$TransformType;ZLcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;IILnet/minecraft/client/renderer/model/IBakedModel;)V", cancellable = true) public void renderItem(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, boolean leftHand, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IBakedModel modelIn, CallbackInfo ci) { if (itemStackIn != null && itemStackIn.getItem() instanceof IGenericGun) { IGunModel model = ClientProxy.gunModelMap.get(itemStackIn.getItem()); if (model != null) {
TransformData data = ClientProxy.transformDataMap.get(itemStackIn.getItem());
6
2023-11-14 14:00:55+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/MenuServiceImpl.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.dimple.exception.BadRequestException; import com.dimple.exception.EntityExistException; import com.dimple.modules.system.domain.Menu; import com.dimple.modules.system.domain.Role; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.domain.vo.MenuMetaVO; import com.dimple.modules.system.domain.vo.MenuVO; import com.dimple.modules.system.repository.MenuRepository; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.MenuService; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.dto.MenuDTO; import com.dimple.modules.system.service.dto.MenuQueryCriteria; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.mapstruct.MenuMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors;
15,278
package com.dimple.modules.system.service.impl; /** * @className: MenuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "menu") public class MenuServiceImpl implements MenuService { private final MenuRepository menuRepository; private final UserRepository userRepository; private final MenuMapper menuMapper; private final RoleService roleService; private final RedisUtils redisUtils; @Override
package com.dimple.modules.system.service.impl; /** * @className: MenuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "menu") public class MenuServiceImpl implements MenuService { private final MenuRepository menuRepository; private final UserRepository userRepository; private final MenuMapper menuMapper; private final RoleService roleService; private final RedisUtils redisUtils; @Override
public List<MenuDTO> queryAll(MenuQueryCriteria criteria, Boolean isQuery) throws Exception {
11
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/generalframe/codeshown/CodeGenerationStaticFunction.java
[ { "identifier": "LabelElementName", "path": "database/src/main/java/com/lazycoder/database/common/LabelElementName.java", "snippet": "public class LabelElementName {\n\n\t/**\n\t * 内容输入 t !!\n\t */\n\tpublic static final String TEXT_INPUT = \"textInput\";\n\n\t/**\n\t * 选择 c !!\n\t */\n\tpublic static f...
import com.lazycoder.database.common.LabelElementName; import com.lazycoder.service.vo.element.mark.HarryingMark; import com.lazycoder.service.vo.pathfind.PathFindCell; import com.lazycoder.uicodegeneration.PathFind; import com.lazycoder.uicodegeneration.component.generalframe.codeshown.format.LabelBean; import com.lazycoder.uicodegeneration.component.generalframe.codeshown.format.lable.FunctionAddBean; import com.lazycoder.uicodegeneration.component.operation.component.CodeGenerationComponentInterface; import com.lazycoder.uicodegeneration.component.operation.container.OpratingContainerInterface; import java.util.ArrayList;
14,646
package com.lazycoder.uicodegeneration.component.generalframe.codeshown; /** * 该类填写生成代码所需的静态方法 * * @author admin */ public class CodeGenerationStaticFunction { /** * */ private static final long serialVersionUID = -5995701523843612886L; /** * 把最后一个组件都拿到(添加、更改、删除代码时拿到) * * @param codeList * @param pathFind * @param ii 命令类型调用该方法这里一律传0,格式类型调用该方法传1 * @param indent 一般直接传""即可,添加代码的时候调用此方法才传缩进符 * @return */ public static UpdateCodeTemporaryVariable getLastLabelBeanList(CodeList codeList, PathFind pathFind, int ii, String indent) { int cursorPositionTemp = 0; UpdateCodeTemporaryVariable lastLabelBeanList = new UpdateCodeTemporaryVariable(); PathFindCell pathFindCell = pathFind.getPathList().get(ii); if (ii == pathFind.getPathList().size() - 1) {// 如果到了最后一个,直接获取需要的标签bean lastLabelBeanList = codeList.getLabelBean(pathFindCell); if (LabelElementName.FUNCTION_ADD.equals(pathFindCell.getOpratingLabel().getLabelType())) { FunctionAddBean functionAddBeanTemp; String indentStr;
package com.lazycoder.uicodegeneration.component.generalframe.codeshown; /** * 该类填写生成代码所需的静态方法 * * @author admin */ public class CodeGenerationStaticFunction { /** * */ private static final long serialVersionUID = -5995701523843612886L; /** * 把最后一个组件都拿到(添加、更改、删除代码时拿到) * * @param codeList * @param pathFind * @param ii 命令类型调用该方法这里一律传0,格式类型调用该方法传1 * @param indent 一般直接传""即可,添加代码的时候调用此方法才传缩进符 * @return */ public static UpdateCodeTemporaryVariable getLastLabelBeanList(CodeList codeList, PathFind pathFind, int ii, String indent) { int cursorPositionTemp = 0; UpdateCodeTemporaryVariable lastLabelBeanList = new UpdateCodeTemporaryVariable(); PathFindCell pathFindCell = pathFind.getPathList().get(ii); if (ii == pathFind.getPathList().size() - 1) {// 如果到了最后一个,直接获取需要的标签bean lastLabelBeanList = codeList.getLabelBean(pathFindCell); if (LabelElementName.FUNCTION_ADD.equals(pathFindCell.getOpratingLabel().getLabelType())) { FunctionAddBean functionAddBeanTemp; String indentStr;
for (LabelBean labelBean : lastLabelBeanList.getList()) {
4
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSBatchSwitch.java
[ { "identifier": "ByteArrayBuffer", "path": "app/src/main/java/kr/or/kashi/hde/base/ByteArrayBuffer.java", "snippet": "public final class ByteArrayBuffer {\n private static final int INITIAL_CAPACITY = 16;\n private static final int CAPACITY_INCREMENT = 8;\n\n private byte[] mBuffer;\n privat...
import kr.or.kashi.hde.ksx4506.KSAddress; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import kr.or.kashi.hde.base.ByteArrayBuffer; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyTask; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.BatchSwitch;
16,531
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The batch-switch implementation for BatchSwitch */ public class KSBatchSwitch extends KSDeviceContextBase { private static final String TAG = "KSBatchSwitch"; private static final boolean DBG = true; // [HACK/DEBUG] Some devices doesn't consider the failure cases. public static final boolean HACK_NEVER_FAIL = false; public static final int CMD_FULL_CONTROL_REQ = 0x42; // sub-id : 0F or FF public static final int CMD_SWITCH_SETTING_RESULT_REQ = 0x43; public static final int CMD_SWITCH_SETTING_RESULT_RSP = 0xC3; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_REQ = 0x44; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_RSP = 0xC4; private final Handler mReqTimeoutHandler; private static final long REQ_TIMEOUT = 7 * 1000L; private boolean mGasLockingReqTriggered = false; private boolean mOutingSettingReqTriggered = false; private boolean mElevatorUpCallReqTriggered = false; private boolean mElevatorDownCallReqTriggered = false; private boolean mSavedGasLocking = false; private boolean mSavedOutingSetting = false; public KSBatchSwitch(MainContext mainContext, Map defaultProps) {
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The batch-switch implementation for BatchSwitch */ public class KSBatchSwitch extends KSDeviceContextBase { private static final String TAG = "KSBatchSwitch"; private static final boolean DBG = true; // [HACK/DEBUG] Some devices doesn't consider the failure cases. public static final boolean HACK_NEVER_FAIL = false; public static final int CMD_FULL_CONTROL_REQ = 0x42; // sub-id : 0F or FF public static final int CMD_SWITCH_SETTING_RESULT_REQ = 0x43; public static final int CMD_SWITCH_SETTING_RESULT_RSP = 0xC3; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_REQ = 0x44; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_RSP = 0xC4; private final Handler mReqTimeoutHandler; private static final long REQ_TIMEOUT = 7 * 1000L; private boolean mGasLockingReqTriggered = false; private boolean mOutingSettingReqTriggered = false; private boolean mElevatorUpCallReqTriggered = false; private boolean mElevatorDownCallReqTriggered = false; private boolean mSavedGasLocking = false; private boolean mSavedOutingSetting = false; public KSBatchSwitch(MainContext mainContext, Map defaultProps) {
super(mainContext, defaultProps, BatchSwitch.class);
7
2023-11-10 01:19:44+00:00
24k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/pluginMenu/PluginMenu.java
[ { "identifier": "ScreenWidget", "path": "src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java", "snippet": "public class ScreenWidget implements IWidget {\n /**\n * Flag indicating whether the mouse cursor is inside the widget\n */\n private boolean isWidgetHovered = false;\n\n ...
import imgui.ImGui; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.interfaces.IControlsWidget; import io.xlorey.FluxLoader.plugin.Metadata; import io.xlorey.FluxLoader.plugin.Plugin; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Constants; import zombie.GameWindow; import zombie.core.textures.Texture; import zombie.gameStates.MainScreenState; import java.util.HashSet; import java.util.List; import java.util.Map;
19,228
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */ private final Map<String, Plugin> loadedPlugins = PluginManager.getLoadedClientPlugins(); /** * Initializing the widget */ public PluginMenu(){ if (!loadedPlugins.isEmpty()) { selectedPluginId = loadedPlugins.keySet().iterator().next(); } } /** * Update window state */ @Override public void update() { super.update(); setVisible((GameWindow.states.current instanceof MainScreenState) && isOpened()); } /** * Sets the visibility state of the plugin's menu. * This method allows you to programmatically open or close the plugin menu. * @param open true to open the plugins menu; false to close. */ public static void setOpen(boolean open) { isOpened.set(open); } /** * Returns the current visibility state of the plugin's menu. * This method allows you to determine whether the plugins menu is currently open. * @return true if the plugins menu is open; false if closed. */ public static boolean isOpened() { return isOpened.get(); } /** * Rendering the plugin menu */ @Override public void render() { ImGui.setNextWindowSize(650, 400); ImGui.pushStyleVar(ImGuiStyleVar.WindowRounding, 8); ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 10, 10); ImGui.pushStyleVar(ImGuiStyleVar.ScrollbarSize, 3); ImGui.pushStyleColor(ImGuiCol.WindowBg, 12, 12, 12, 255); ImGui.pushStyleColor(ImGuiCol.TitleBg, 30, 30, 30, 255); ImGui.pushStyleColor(ImGuiCol.TitleBgActive, 30, 30, 30, 255); int emeraldActive = ImGui.getColorU32(0.0f, 0.55f, 0.55f, 1.0f); int emeraldHovered = ImGui.getColorU32(0.0f, 0.65f, 0.65f, 1.0f); int emeraldNormal = ImGui.getColorU32(0.0f, 0.60f, 0.60f, 1.0f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, emeraldActive); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, emeraldHovered); ImGui.pushStyleColor(ImGuiCol.Button, emeraldNormal);
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */ private final Map<String, Plugin> loadedPlugins = PluginManager.getLoadedClientPlugins(); /** * Initializing the widget */ public PluginMenu(){ if (!loadedPlugins.isEmpty()) { selectedPluginId = loadedPlugins.keySet().iterator().next(); } } /** * Update window state */ @Override public void update() { super.update(); setVisible((GameWindow.states.current instanceof MainScreenState) && isOpened()); } /** * Sets the visibility state of the plugin's menu. * This method allows you to programmatically open or close the plugin menu. * @param open true to open the plugins menu; false to close. */ public static void setOpen(boolean open) { isOpened.set(open); } /** * Returns the current visibility state of the plugin's menu. * This method allows you to determine whether the plugins menu is currently open. * @return true if the plugins menu is open; false if closed. */ public static boolean isOpened() { return isOpened.get(); } /** * Rendering the plugin menu */ @Override public void render() { ImGui.setNextWindowSize(650, 400); ImGui.pushStyleVar(ImGuiStyleVar.WindowRounding, 8); ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 10, 10); ImGui.pushStyleVar(ImGuiStyleVar.ScrollbarSize, 3); ImGui.pushStyleColor(ImGuiCol.WindowBg, 12, 12, 12, 255); ImGui.pushStyleColor(ImGuiCol.TitleBg, 30, 30, 30, 255); ImGui.pushStyleColor(ImGuiCol.TitleBgActive, 30, 30, 30, 255); int emeraldActive = ImGui.getColorU32(0.0f, 0.55f, 0.55f, 1.0f); int emeraldHovered = ImGui.getColorU32(0.0f, 0.65f, 0.65f, 1.0f); int emeraldNormal = ImGui.getColorU32(0.0f, 0.60f, 0.60f, 1.0f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, emeraldActive); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, emeraldHovered); ImGui.pushStyleColor(ImGuiCol.Button, emeraldNormal);
ImGui.begin(Constants.FLUX_NAME + " - Plugins", isOpened, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse);
5
2023-11-16 09:05:44+00:00
24k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/events/listeners/UtilityListener.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.api.sequence.Sequence; import com.sweattypalms.skyblock.api.sequence.SequenceAction; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.events.def.SkyblockDeathEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockInteractEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockMobDamagePlayerEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType; import com.sweattypalms.skyblock.core.items.builder.armor.IHeadHelmet; import com.sweattypalms.skyblock.core.items.builder.item.IShortBow; import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonManager; import com.sweattypalms.skyblock.core.mobs.builder.dragons.IEndDragon; import com.sweattypalms.skyblock.core.mobs.builder.dragons.loot.IDragonLoot; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.minecraft.server.v1_8_R3.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEnderDragonPart; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftItem; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.*; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Text; import java.util.List;
16,444
package com.sweattypalms.skyblock.core.events.listeners; public class UtilityListener implements Listener { @NotNull private static SkyblockDeathEvent getSkyblockDeathEvent(LivingEntity livingEntity) { SkyblockDeathEvent.DeathCause reason; EntityDamageEvent lastDamageCause = livingEntity.getLastDamageCause(); if (lastDamageCause == null) { reason = SkyblockDeathEvent.DeathCause.OTHER; } else { reason = SkyblockDeathEvent.DeathCause.getCause(lastDamageCause.getCause()); } SkyblockDeathEvent _event; if (reason == SkyblockDeathEvent.DeathCause.ENTITY) { _event = new SkyblockDeathEvent(livingEntity.getKiller(), livingEntity); } else { _event = new SkyblockDeathEvent(livingEntity, reason); } return _event; } @EventHandler public void onJoin(PlayerJoinEvent event) { String message = "$eWelcome to $cSkyblock$e!"; message = PlaceholderFormatter.format(message); event.getPlayer().sendMessage(message); event.setJoinMessage(null); if (SkyblockPlayer.getSkyblockPlayer(event.getPlayer()) != null) return; new SkyblockPlayer(event.getPlayer()); } @EventHandler(priority = EventPriority.LOW) public void interactEventForwarder(PlayerInteractEvent event) { Player player = event.getPlayer(); SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); TriggerType triggerType = TriggerType.getTriggerType(event.getAction()); if (triggerType == null || triggerType == TriggerType.NONE) return; SkyblockInteractEvent skyblockInteractEvent = new SkyblockInteractEvent(skyblockPlayer, triggerType); if (event.getClickedBlock() != null) { skyblockInteractEvent.setInteractedBlock(event.getClickedBlock()); } SkyBlock.getInstance().getServer().getPluginManager().callEvent(skyblockInteractEvent); if (skyblockInteractEvent.isCancelled()) event.setCancelled(true); } @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand();
package com.sweattypalms.skyblock.core.events.listeners; public class UtilityListener implements Listener { @NotNull private static SkyblockDeathEvent getSkyblockDeathEvent(LivingEntity livingEntity) { SkyblockDeathEvent.DeathCause reason; EntityDamageEvent lastDamageCause = livingEntity.getLastDamageCause(); if (lastDamageCause == null) { reason = SkyblockDeathEvent.DeathCause.OTHER; } else { reason = SkyblockDeathEvent.DeathCause.getCause(lastDamageCause.getCause()); } SkyblockDeathEvent _event; if (reason == SkyblockDeathEvent.DeathCause.ENTITY) { _event = new SkyblockDeathEvent(livingEntity.getKiller(), livingEntity); } else { _event = new SkyblockDeathEvent(livingEntity, reason); } return _event; } @EventHandler public void onJoin(PlayerJoinEvent event) { String message = "$eWelcome to $cSkyblock$e!"; message = PlaceholderFormatter.format(message); event.getPlayer().sendMessage(message); event.setJoinMessage(null); if (SkyblockPlayer.getSkyblockPlayer(event.getPlayer()) != null) return; new SkyblockPlayer(event.getPlayer()); } @EventHandler(priority = EventPriority.LOW) public void interactEventForwarder(PlayerInteractEvent event) { Player player = event.getPlayer(); SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); TriggerType triggerType = TriggerType.getTriggerType(event.getAction()); if (triggerType == null || triggerType == TriggerType.NONE) return; SkyblockInteractEvent skyblockInteractEvent = new SkyblockInteractEvent(skyblockPlayer, triggerType); if (event.getClickedBlock() != null) { skyblockInteractEvent.setInteractedBlock(event.getClickedBlock()); } SkyBlock.getInstance().getServer().getPluginManager().callEvent(skyblockInteractEvent); if (skyblockInteractEvent.isCancelled()) event.setCancelled(true); } @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand();
SkyblockItem skyblockItem = SkyblockItem.fromItemStack(itemInHand);
9
2023-11-15 15:05:58+00:00
24k
Hikaito/Fox-Engine
src/system/project/ProjectManager.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import system.Program; import system.backbone.ColorAdapter; import system.layerTree.RendererTypeAdapter; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.TreeUnit; import system.backbone.FileOperations; import system.backbone.VersionNumber; import system.gui.WarningWindow; import system.project.treeElements.ProjectFolderInterface; import system.project.treeElements.*; import system.gui.project.ProjectEditor; import system.gui.project.ProjectFileSelection; import system.gui.project.ProjectReconciliation; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedList; import java.util.SortedSet; import java.util.TreeSet;
20,227
} // loading function public void loadProject(String path){ String fullpath = Paths.get(path, Program.getProjectFile()).toString(); //generate absolute path to project //load root try { String json = new String(Files.readAllBytes(Paths.get(fullpath))); // read json from file ProjectRoot tempRootLoad = gson.fromJson(json, ProjectRoot.class); // convert json to object of interest Program.log("Project loaded from " + fullpath); // set root path tempRootLoad.setPath(path); // evaluate project number if(!evaluateProjectNumber(Program.getProgramVersion(), tempRootLoad.getProgramVersion())){ WarningWindow.warningWindow("Project version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + tempRootLoad.getProgramVersion()); initializeEmpty(); return; } root = tempRootLoad; // keep load // load project tree ProjectRoot tempRoot = readTree(path); // place SortedSet<ProjectFile> discoveredFiles = new TreeSet<>(); SortedSet<ProjectFile> existingFiles = new TreeSet<>(); //traverse trees fillFileList(tempRoot, discoveredFiles); fillFileList(root, existingFiles); //eliminate common files //common files list exists to prevent concurrent removal and traversal errors SortedSet<ProjectFile> commonFiles = new TreeSet<>(); // find files that are common for(ProjectFile file:existingFiles){ // if a file was found, remove it from both lists if (discoveredFiles.contains(file)){ commonFiles.add(file); //add to common list } } // remove common files for(ProjectFile file:commonFiles){ // if a file was found, remove it from both lists discoveredFiles.remove(file); existingFiles.remove(file); file.setValid(true); } // open reconciliation dialogue // if files remain in either list, open window if (discoveredFiles.size() != 0 || existingFiles.size() != 0){ // dictionary generated on window close ProjectReconciliation window = new ProjectReconciliation(this, existingFiles, discoveredFiles); } else{ root.generateParents(); //generate parents to menu updateDependencies(); // generate dictionary if all is well } // save new location Program.setProjectPath(path); } // return null if no object could be loaded; initialize instead catch (IOException e) { Program.log("Project file could not be read. Source: " + fullpath); initializeProject(path); } } // tree traversal function for collecting files into a sorted list protected void fillFileList(ProjectUnitCore root, SortedSet<ProjectFile> files){ // if file, add to files and return if(root instanceof ProjectFile){ files.add((ProjectFile) root); return; } // if folder, generate children list LinkedList<ProjectUnitCore> children; if (root instanceof ProjectRoot) children = ((ProjectRoot) root).getChildren(); else if (root instanceof ProjectFolder) children = ((ProjectFolder) root).getChildren(); else return; // recurse on children for (ProjectUnitCore child:children){ fillFileList(child, files); } } public String getAbsolutePath(ProjectFile file){ return Paths.get(root.getPath(), file.getPath()).toString(); } public static void mergeFile(ProjectFile keep, ProjectFile flake){ keep.setValid(flake.isValid()); // copy validity keep.setPath(flake.getPath()); // copy path } public void addFile(ProjectFile file){ file.setValid(true); //set valid as true file.setID(root.getNextID()); // assign a proper ID value root.getChildren().addLast(file); // add element to root list file.setParent(root); // register root as parent } public void openEditor(){ try { //generates dictionary on close ProjectEditor window = new ProjectEditor(this); } catch (IOException e) { e.printStackTrace(); } } // selector for layer
package system.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectManager { // UUID methods public String getUUID(){return root.getUUID();} public boolean matchesUUID(String other){ return root.getUUID().equals(other); } public String getTitle(){return root.getTitle();} // reject if program number is lower than project public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){ if(program.compareTo(project) < 0) return false; return true; } // project root protected ProjectRoot root; public ProjectRoot getRoot(){return root;} // tree generation public DefaultMutableTreeNode getTree(){ return root.getTree(); } // updates menu offshoot entities public void updateDependencies(){ buildDictionary(); root.generateMenu(); } //region dictionary---------------------------- // dictionary protected HashMap<Long, ProjectFile> dictionary; //build dictionary public void buildDictionary(){ dictionary = new HashMap<>(); // generate new dictionary addDict(root); // build from root } // build dictionary recursive protected void addDict(ProjectUnitCore root){ // case file: add to dictionary if (root instanceof ProjectFile){ ProjectFile unit = (ProjectFile) root; //cast object dictionary.put(unit.getID(), unit); } //recurse to all children for file types else if (root instanceof ProjectFolderInterface){ ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object for (ProjectUnitCore child: unit.getChildren()){ addDict(child); } } } //query dictionary; returns null if none found public ProjectFile getFile(long code){ // return null if nocode if(code == Program.getDefaultFileCode()) return null; return dictionary.get(code); } // endregion // save file------------------------------------ // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer .registerTypeAdapter(ProjectUnitCore.class, new ProjectTypeAdapter()) // registers abstract classes .create(); // function for saving file public boolean saveFile(){ // derive json String json = gson.toJson(root); //generate absolute path to location String path = Paths.get(root.getPath(), Program.getProjectFile()).toString(); // write json to file try { FileWriter out = new FileWriter(path, false); out.write(json); out.close(); // log action Program.log("File '" + Program.getProjectFile() + "' saved as project file at " + path); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // initialization function---------------------------- public void initializeEmpty(){ root = new ProjectRoot("Null Project"); //create project root Program.log("Project initialized from filesystem."); } public void initializeProject(String fullpath){ // attempt opening ProjectRoot tempRoot = readTree(fullpath); // read file // test version number if(!evaluateProjectNumber(Program.getProgramVersion(), tempRoot.getProgramVersion())){ WarningWindow.warningWindow("Project version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + tempRoot.getProgramVersion()); initializeEmpty(); return; } // open directory root = tempRoot; // if project version acceptible, save project root = readTree(fullpath); Program.log("Project at "+ fullpath + " imported."); // open file editing dialogue // dictionary generated on window close try { ProjectEditor window = new ProjectEditor(this); } catch (IOException e) { e.printStackTrace(); } } protected ProjectRoot readTree(String fullpath){ // open directory File file = new File(fullpath); // create file object to represent path String title = file.getName(); //set project name to folder title ProjectRoot tempRoot = new ProjectRoot(title); //create project root tempRoot.setPath(fullpath); //set directory path // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(tempRoot.getChildren(), child, tempRoot); } // generate parents when complete tempRoot.generateParents(); Program.log("Project at "+ fullpath + " read from filesystem."); return tempRoot; } protected void initializeTree(LinkedList<ProjectUnitCore> folder, File file, ProjectRoot temproot){ //recursive case: folder; repeat call for each file inside if (file.isDirectory()){ // exclude internal folders if(file.getAbsolutePath().endsWith(Program.getSaveFolder()) || file.getAbsolutePath().endsWith(Program.getRenderFolder()) || file.getAbsolutePath().endsWith(Program.getTemplateFolder())){ return; } // create a folder node and add to tree ProjectFolder folderObj = new ProjectFolder(file.getName(), temproot.getNextID()); folder.addLast(folderObj); // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(folderObj.getChildren(), child, temproot); } } // base case: file. add file if a valid file is found else{ // if the file has a valid extension if (FileOperations.validExtension(file.getName(), Program.getFileExtensionLoadImage())) { //create a file node and add to tree ProjectFile newFile = new ProjectFile(FileOperations.trimDirectory(temproot.getPath(),file.getAbsolutePath()).toString(), FileOperations.stripExtension(file.getName(), Program.getFileExtensionLoadImage()), temproot.getNextID()); newFile.setValid(true); folder.addLast(newFile); } } } // loading function: folder selection public void loadProject(){ String text = FileOperations.selectFolder(System.getProperty("user.dir")); // get project, starting at local directory // if a directory was selected if(text != null){ // autosave file Program.generateManagerFile(Program.getAutosavePath("PROJECT_CHANGE")); // autosave layer tree loadProject(text); // load project Program.newFileNoWarning(); // remove null file NOTE it is importannt that this occur after the project change Program.redrawAllRegions(); Program.redrawMenuBar(); Program.setProjectPath(text); // set new project path } } // loading function public void loadProject(String path){ String fullpath = Paths.get(path, Program.getProjectFile()).toString(); //generate absolute path to project //load root try { String json = new String(Files.readAllBytes(Paths.get(fullpath))); // read json from file ProjectRoot tempRootLoad = gson.fromJson(json, ProjectRoot.class); // convert json to object of interest Program.log("Project loaded from " + fullpath); // set root path tempRootLoad.setPath(path); // evaluate project number if(!evaluateProjectNumber(Program.getProgramVersion(), tempRootLoad.getProgramVersion())){ WarningWindow.warningWindow("Project version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + tempRootLoad.getProgramVersion()); initializeEmpty(); return; } root = tempRootLoad; // keep load // load project tree ProjectRoot tempRoot = readTree(path); // place SortedSet<ProjectFile> discoveredFiles = new TreeSet<>(); SortedSet<ProjectFile> existingFiles = new TreeSet<>(); //traverse trees fillFileList(tempRoot, discoveredFiles); fillFileList(root, existingFiles); //eliminate common files //common files list exists to prevent concurrent removal and traversal errors SortedSet<ProjectFile> commonFiles = new TreeSet<>(); // find files that are common for(ProjectFile file:existingFiles){ // if a file was found, remove it from both lists if (discoveredFiles.contains(file)){ commonFiles.add(file); //add to common list } } // remove common files for(ProjectFile file:commonFiles){ // if a file was found, remove it from both lists discoveredFiles.remove(file); existingFiles.remove(file); file.setValid(true); } // open reconciliation dialogue // if files remain in either list, open window if (discoveredFiles.size() != 0 || existingFiles.size() != 0){ // dictionary generated on window close ProjectReconciliation window = new ProjectReconciliation(this, existingFiles, discoveredFiles); } else{ root.generateParents(); //generate parents to menu updateDependencies(); // generate dictionary if all is well } // save new location Program.setProjectPath(path); } // return null if no object could be loaded; initialize instead catch (IOException e) { Program.log("Project file could not be read. Source: " + fullpath); initializeProject(path); } } // tree traversal function for collecting files into a sorted list protected void fillFileList(ProjectUnitCore root, SortedSet<ProjectFile> files){ // if file, add to files and return if(root instanceof ProjectFile){ files.add((ProjectFile) root); return; } // if folder, generate children list LinkedList<ProjectUnitCore> children; if (root instanceof ProjectRoot) children = ((ProjectRoot) root).getChildren(); else if (root instanceof ProjectFolder) children = ((ProjectFolder) root).getChildren(); else return; // recurse on children for (ProjectUnitCore child:children){ fillFileList(child, files); } } public String getAbsolutePath(ProjectFile file){ return Paths.get(root.getPath(), file.getPath()).toString(); } public static void mergeFile(ProjectFile keep, ProjectFile flake){ keep.setValid(flake.isValid()); // copy validity keep.setPath(flake.getPath()); // copy path } public void addFile(ProjectFile file){ file.setValid(true); //set valid as true file.setID(root.getNextID()); // assign a proper ID value root.getChildren().addLast(file); // add element to root list file.setParent(root); // register root as parent } public void openEditor(){ try { //generates dictionary on close ProjectEditor window = new ProjectEditor(this); } catch (IOException e) { e.printStackTrace(); } } // selector for layer
public void openSelector(Layer layer){
4
2023-11-12 21:12:21+00:00
24k
shizotoaster/thaumon
fabric/src/main/java/jdlenl/thaumon/itemgroup/fabric/ThaumonItemGroupFabric.java
[ { "identifier": "Thaumon", "path": "common/src/main/java/jdlenl/thaumon/Thaumon.java", "snippet": "public class Thaumon {\n public static final String MOD_ID = \"thaumon\";\n public static Logger logger = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n ThaumonItems.ini...
import jdlenl.thaumon.Thaumon; import jdlenl.thaumon.block.ThaumonBlocks; import jdlenl.thaumon.item.ThaumonItems; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.text.Text; import net.minecraft.util.Identifier;
17,151
entries.add(ThaumonBlocks.GREATWOOD_WINDOW.get()); entries.add(ThaumonBlocks.GREATWOOD_WINDOW_PANE.get()); entries.add(ThaumonBlocks.EMPTY_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.CLASSIC_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.DUSTY_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.ALCHEMISTS_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_GRIMOIRE_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_BUTTON.get()); entries.add(ThaumonBlocks.GREATWOOD_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG.get()); entries.add(ThaumonBlocks.SILVERWOOD_WOOD.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG_WALL.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG_POST.get()); entries.add(ThaumonBlocks.SILVERWOOD_PLANKS.get()); entries.add(ThaumonBlocks.SILVERWOOD_STAIRS.get()); entries.add(ThaumonBlocks.SILVERWOOD_SLAB.get()); entries.add(ThaumonBlocks.SILVERWOOD_DOOR.get()); entries.add(ThaumonBlocks.SILVERWOOD_TRAPDOOR.get()); entries.add(ThaumonBlocks.SILVERWOOD_FENCE.get()); entries.add(ThaumonBlocks.SILVERWOOD_FENCE_GATE.get()); entries.add(ThaumonBlocks.SILVERWOOD_WINDOW.get()); entries.add(ThaumonBlocks.SILVERWOOD_WINDOW_PANE.get()); entries.add(ThaumonBlocks.EMPTY_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.CLASSIC_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.DUSTY_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.ALCHEMISTS_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_GRIMOIRE_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_BUTTON.get()); entries.add(ThaumonBlocks.SILVERWOOD_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.ARCANE_STONE.get()); entries.add(ThaumonBlocks.ARCANE_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_STONE_SlAB.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WALL.get()); entries.add(ThaumonBlocks.ARCANE_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_WALL.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_STONE_BRICKS.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ARCANE_STONE_TILES.get()); entries.add(ThaumonBlocks.ARCANE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ARCANE_STONE_PILLAR.get()); entries.add(ThaumonBlocks.RUNIC_ARCANE_STONE.get()); entries.add(ThaumonBlocks.TILED_ARCANE_STONE.get()); entries.add(ThaumonBlocks.INLAID_ARCANE_STONE.get()); entries.add(ThaumonBlocks.ARCANE_LANTERN.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ARCANE_STONE_BUTTON.get()); entries.add(ThaumonBlocks.ARCANE_STONE_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WALL.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILES.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_PILLAR.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_CAPSTONE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_FACADE.get()); entries.add(ThaumonBlocks.CHISELED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.CARVED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ENGRAVED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.INLAID_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ELDRITCH_LANTERN.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WALL.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_STAIRS.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILES.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_DOOR.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_PILLAR.get()); entries.add(ThaumonBlocks.ENGRAVED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.CHISELED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.RUNIC_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.TILED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.INLAID_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.ANCIENT_LANTERN.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BUTTON.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.GREATWOOD_LEAVES.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAVES.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAF_POST.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAF_WALL.get()); entries.add(ThaumonBlocks.GRIMOIRE.get()); entries.add(ThaumonBlocks.GRIMOIRE_STACK.get()); entries.add(ThaumonBlocks.RESEARCH_NOTES.get()); entries.add(ThaumonBlocks.CRYSTAL_LAMP.get()); entries.add(ThaumonBlocks.RETORT.get()); entries.add(ThaumonBlocks.VIAL_RACK.get()); entries.add(ThaumonBlocks.CRYSTAL_STAND.get());
package jdlenl.thaumon.itemgroup.fabric; public class ThaumonItemGroupFabric { public static final ItemGroup THAUMON_GROUP = Registry.register(Registries.ITEM_GROUP, new Identifier(Thaumon.MOD_ID, "thaumon_item_group"), FabricItemGroup.builder().displayName(Text.translatable("itemgroup.thaumon.thaumon_item_group")).icon(() -> new ItemStack(ThaumonBlocks.ELDRITCH_LANTERN.get().asItem())) .entries(((displayContext, entries) -> { entries.add(ThaumonBlocks.AMBER.get()); entries.add(ThaumonBlocks.AMBER_STAIRS.get()); entries.add(ThaumonBlocks.AMBER_SLAB.get()); entries.add(ThaumonBlocks.AMBER_BRICKS.get()); entries.add(ThaumonBlocks.AMBER_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.AMBER_BRICK_SLAB.get()); entries.add(ThaumonBlocks.AMBERGLASS.get()); entries.add(ThaumonBlocks.AMBERGLASS_PANE.get()); entries.add(ThaumonBlocks.GREATWOOD_LOG.get()); entries.add(ThaumonBlocks.GREATWOOD_WOOD.get()); entries.add(ThaumonBlocks.GREATWOOD_LOG_WALL.get()); entries.add(ThaumonBlocks.GREATWOOD_LOG_POST.get()); entries.add(ThaumonBlocks.GREATWOOD_PLANKS.get()); entries.add(ThaumonBlocks.GREATWOOD_STAIRS.get()); entries.add(ThaumonBlocks.GREATWOOD_SLAB.get()); entries.add(ThaumonBlocks.GREATWOOD_DOOR.get()); entries.add(ThaumonBlocks.GREATWOOD_TRAPDOOR.get()); entries.add(ThaumonBlocks.GILDED_GREATWOOD_DOOR.get()); entries.add(ThaumonBlocks.GILDED_GREATWOOD_TRAPDOOR.get()); entries.add(ThaumonBlocks.GREATWOOD_FENCE.get()); entries.add(ThaumonBlocks.GREATWOOD_FENCE_GATE.get()); entries.add(ThaumonBlocks.GREATWOOD_WINDOW.get()); entries.add(ThaumonBlocks.GREATWOOD_WINDOW_PANE.get()); entries.add(ThaumonBlocks.EMPTY_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.CLASSIC_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.DUSTY_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.ALCHEMISTS_GREATWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_GRIMOIRE_BOOKSHELF.get()); entries.add(ThaumonBlocks.GREATWOOD_BUTTON.get()); entries.add(ThaumonBlocks.GREATWOOD_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG.get()); entries.add(ThaumonBlocks.SILVERWOOD_WOOD.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG_WALL.get()); entries.add(ThaumonBlocks.SILVERWOOD_LOG_POST.get()); entries.add(ThaumonBlocks.SILVERWOOD_PLANKS.get()); entries.add(ThaumonBlocks.SILVERWOOD_STAIRS.get()); entries.add(ThaumonBlocks.SILVERWOOD_SLAB.get()); entries.add(ThaumonBlocks.SILVERWOOD_DOOR.get()); entries.add(ThaumonBlocks.SILVERWOOD_TRAPDOOR.get()); entries.add(ThaumonBlocks.SILVERWOOD_FENCE.get()); entries.add(ThaumonBlocks.SILVERWOOD_FENCE_GATE.get()); entries.add(ThaumonBlocks.SILVERWOOD_WINDOW.get()); entries.add(ThaumonBlocks.SILVERWOOD_WINDOW_PANE.get()); entries.add(ThaumonBlocks.EMPTY_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.CLASSIC_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.DUSTY_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.ALCHEMISTS_SILVERWOOD_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_GRIMOIRE_BOOKSHELF.get()); entries.add(ThaumonBlocks.SILVERWOOD_BUTTON.get()); entries.add(ThaumonBlocks.SILVERWOOD_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.ARCANE_STONE.get()); entries.add(ThaumonBlocks.ARCANE_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_STONE_SlAB.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WALL.get()); entries.add(ThaumonBlocks.ARCANE_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ARCANE_BRICK_WALL.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_STONE_BRICKS.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ARCANE_STONE_TILES.get()); entries.add(ThaumonBlocks.ARCANE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ARCANE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ARCANE_STONE_PILLAR.get()); entries.add(ThaumonBlocks.RUNIC_ARCANE_STONE.get()); entries.add(ThaumonBlocks.TILED_ARCANE_STONE.get()); entries.add(ThaumonBlocks.INLAID_ARCANE_STONE.get()); entries.add(ThaumonBlocks.ARCANE_LANTERN.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ARCANE_STONE_BUTTON.get()); entries.add(ThaumonBlocks.ARCANE_STONE_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WALL.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILES.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_PILLAR.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_CAPSTONE.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_FACADE.get()); entries.add(ThaumonBlocks.CHISELED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.CARVED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ENGRAVED_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.INLAID_ELDRITCH_STONE.get()); entries.add(ThaumonBlocks.ELDRITCH_LANTERN.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WALL.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_STAIRS.get()); entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICKS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_WALL.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILES.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_STAIRS.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_SLAB.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_DOOR.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_PILLAR.get()); entries.add(ThaumonBlocks.ENGRAVED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.CHISELED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.RUNIC_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.TILED_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.INLAID_ANCIENT_STONE.get()); entries.add(ThaumonBlocks.ANCIENT_LANTERN.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW_PANE.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_BUTTON.get()); entries.add(ThaumonBlocks.ANCIENT_STONE_PRESSURE_PLATE.get()); entries.add(ThaumonBlocks.GREATWOOD_LEAVES.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAVES.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAF_POST.get()); entries.add(ThaumonBlocks.SILVERWOOD_LEAF_WALL.get()); entries.add(ThaumonBlocks.GRIMOIRE.get()); entries.add(ThaumonBlocks.GRIMOIRE_STACK.get()); entries.add(ThaumonBlocks.RESEARCH_NOTES.get()); entries.add(ThaumonBlocks.CRYSTAL_LAMP.get()); entries.add(ThaumonBlocks.RETORT.get()); entries.add(ThaumonBlocks.VIAL_RACK.get()); entries.add(ThaumonBlocks.CRYSTAL_STAND.get());
entries.add(ThaumonItems.MUTAGEN.get());
2
2023-11-16 06:03:29+00:00
24k