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
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/GLDocumentCSVTransformer.java
[ { "identifier": "DataRetrievalError", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalError.java", "snippet": "public class DataRetrievalError extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalError.class);\n\n ...
import java.io.BufferedWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.DocumentType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ProcessType; import static tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ProcessType.REALISED; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.PsrType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.PsrTypesByArea; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument;
7,687
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * Class to generate entries relative to GLDocumentCSVTransformer * * @author Andres Bel Alonso */ public class GLDocumentCSVTransformer extends CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(GLDocumentCSVTransformer.class); private final GLMarketDocument doc; public GLDocumentCSVTransformer(String csvSeparator, String csvEscapeChar, GLMarketDocument doc) { super(csvSeparator, csvEscapeChar); this.doc = doc; } @Override public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) { // start inclusive, end exclusive if (doc.getTimePeriodTimeInterval().getLDTStart().isEqual(timeStamp) || (doc.getTimePeriodTimeInterval().getLDTStart().isBefore(timeStamp) && doc.getTimePeriodTimeInterval().getLDTEnd().isAfter(timeStamp))) { // we asume that the whole information was requested for a single continuos interval List<MarkedTS> timeSeries = getPeriodForTimeStamp(doc.getTimeSeries(),timeStamp); if (timeSeries.isEmpty()) { // probably a missing value, do not write nothing by convention return false; }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * Class to generate entries relative to GLDocumentCSVTransformer * * @author Andres Bel Alonso */ public class GLDocumentCSVTransformer extends CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(GLDocumentCSVTransformer.class); private final GLMarketDocument doc; public GLDocumentCSVTransformer(String csvSeparator, String csvEscapeChar, GLMarketDocument doc) { super(csvSeparator, csvEscapeChar); this.doc = doc; } @Override public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) { // start inclusive, end exclusive if (doc.getTimePeriodTimeInterval().getLDTStart().isEqual(timeStamp) || (doc.getTimePeriodTimeInterval().getLDTStart().isBefore(timeStamp) && doc.getTimePeriodTimeInterval().getLDTEnd().isAfter(timeStamp))) { // we asume that the whole information was requested for a single continuos interval List<MarkedTS> timeSeries = getPeriodForTimeStamp(doc.getTimeSeries(),timeStamp); if (timeSeries.isEmpty()) { // probably a missing value, do not write nothing by convention return false; }
DocumentType docType = DocumentType.fromId(doc.getType());
3
2023-10-30 09:09:53+00:00
12k
EricFan2002/SC2002
src/app/controller/camp/CampEnquiryController.java
[ { "identifier": "EnquiryList", "path": "src/app/entity/enquiry/EnquiryList.java", "snippet": "public class EnquiryList extends RepositoryList<Enquiry> implements IFilterableByID<Enquiry>,\n IFilterableByCamp<Enquiry>, IFilterableByStatus<Enquiry, Boolean>, IFilterableBySender<Enquiry>,\n I...
import app.entity.enquiry.EnquiryList; import app.entity.RepositoryCollection; import app.entity.enquiry.Enquiry; import app.entity.camp.Camp; import app.entity.user.Student; import app.entity.user.User;
7,218
package app.controller.camp; /** * The {@code CampEnquiryController} class manages the operations related to * enquiries within a camp context. * It provides functionalities to create, retrieve, update, and delete * enquiries, along with specific methods * to handle enquiries by camp or user. It also includes a feature to answer an * enquiry and award points to * students for their participation. * * <p> * Methods include: * <ul> * <li>Creating new enquiries. * <li>Retrieving enquiries by ID, camp, or user. * <li>Updating existing enquiries. * <li>Deleting enquiries. * <li>Answering enquiries with an optional reward system for student users. * </ul> * * <p> * This app.controller interacts with the {@code RepositoryCollection} to perform * data operations, * ensuring a separation of concerns between the data layer and business logic. * * @see app.entity.enquiry.Enquiry * @see app.entity.camp.Camp * @see app.entity.user.User */ public class CampEnquiryController { /** * Private constructor to prevent instantiation. */ private CampEnquiryController() { } /* * Creates a new enquiry by inserting it into the enquiry repository. * This method always returns true after the insertion operation. * * @param enquiry The {@link Enquiry} object to be inserted. * * @return boolean True after successful insertion. */ public static boolean createEnquiry(Enquiry enquiry) { RepositoryCollection.getEnquiryRepository().add(enquiry); enquiry.getSender().addEnquiry(enquiry); enquiry.getCamp().addEnquiry(enquiry); return true; } /** * Retrieves an enquiry based on its unique ID. If no enquiry is found with the * given ID, this method returns null. * * @param enquiryID The unique identifier of the enquiry. * * @return Enquiry The enquiry matching the given ID, or null if none found. */ public static Enquiry getEnquiry(String enquiryID) { EnquiryList filteredEnquiries = RepositoryCollection.getEnquiryRepository().filterByID(enquiryID); return filteredEnquiries.size() == 0 ? null : filteredEnquiries.get(0); } /** * Retrieves all enquiries from the enquiry repository. * * @return EnquiryList A list of all enquiries. */ public static EnquiryList getEnquiries() { return RepositoryCollection.getEnquiryRepository(); } /** * Retrieves all enquiries related to a specific camp. * * @param camp The {@link Camp} for which enquiries are to be retrieved. * * @return EnquiryList A list of enquiries related to the specified camp. */
package app.controller.camp; /** * The {@code CampEnquiryController} class manages the operations related to * enquiries within a camp context. * It provides functionalities to create, retrieve, update, and delete * enquiries, along with specific methods * to handle enquiries by camp or user. It also includes a feature to answer an * enquiry and award points to * students for their participation. * * <p> * Methods include: * <ul> * <li>Creating new enquiries. * <li>Retrieving enquiries by ID, camp, or user. * <li>Updating existing enquiries. * <li>Deleting enquiries. * <li>Answering enquiries with an optional reward system for student users. * </ul> * * <p> * This app.controller interacts with the {@code RepositoryCollection} to perform * data operations, * ensuring a separation of concerns between the data layer and business logic. * * @see app.entity.enquiry.Enquiry * @see app.entity.camp.Camp * @see app.entity.user.User */ public class CampEnquiryController { /** * Private constructor to prevent instantiation. */ private CampEnquiryController() { } /* * Creates a new enquiry by inserting it into the enquiry repository. * This method always returns true after the insertion operation. * * @param enquiry The {@link Enquiry} object to be inserted. * * @return boolean True after successful insertion. */ public static boolean createEnquiry(Enquiry enquiry) { RepositoryCollection.getEnquiryRepository().add(enquiry); enquiry.getSender().addEnquiry(enquiry); enquiry.getCamp().addEnquiry(enquiry); return true; } /** * Retrieves an enquiry based on its unique ID. If no enquiry is found with the * given ID, this method returns null. * * @param enquiryID The unique identifier of the enquiry. * * @return Enquiry The enquiry matching the given ID, or null if none found. */ public static Enquiry getEnquiry(String enquiryID) { EnquiryList filteredEnquiries = RepositoryCollection.getEnquiryRepository().filterByID(enquiryID); return filteredEnquiries.size() == 0 ? null : filteredEnquiries.get(0); } /** * Retrieves all enquiries from the enquiry repository. * * @return EnquiryList A list of all enquiries. */ public static EnquiryList getEnquiries() { return RepositoryCollection.getEnquiryRepository(); } /** * Retrieves all enquiries related to a specific camp. * * @param camp The {@link Camp} for which enquiries are to be retrieved. * * @return EnquiryList A list of enquiries related to the specified camp. */
public static EnquiryList getEnquiries(Camp camp) {
3
2023-11-01 05:18:29+00:00
12k
LLNL/response
src/main/java/gov/llnl/gnem/response/TransferFunctionProcessor.java
[ { "identifier": "ChannelMatchPolicy", "path": "src/main/java/com/isti/jevalresp/ChannelMatchPolicy.java", "snippet": "public class ChannelMatchPolicy implements Serializable {\r\n\r\n private static final long serialVersionUID = 6639216586376908870L;\r\n\r\n public static enum Policy {\r\n ...
import com.isti.jevalresp.UnitsStatus; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.measure.Unit; import com.isti.jevalresp.ChannelMatchPolicy; import com.isti.jevalresp.ResponseUnits;
7,305
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class TransferFunctionProcessor { private final SACPZFTransfer sacTransfer; private final EvalrespTransfer evalrespTransfer; private final NDCTransfer ndcTransfer; public TransferFunctionProcessor() { this.sacTransfer = new SACPZFTransfer(); this.evalrespTransfer = new EvalrespTransfer(); this.ndcTransfer = new NDCTransfer(); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, forcedInputUnits); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits) throws IOException {
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class TransferFunctionProcessor { private final SACPZFTransfer sacTransfer; private final EvalrespTransfer evalrespTransfer; private final NDCTransfer ndcTransfer; public TransferFunctionProcessor() { this.sacTransfer = new SACPZFTransfer(); this.evalrespTransfer = new EvalrespTransfer(); this.ndcTransfer = new NDCTransfer(); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, forcedInputUnits); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits) throws IOException {
Unit<?> requestedUnits = ResponseUnits.DEFAULT;
1
2023-10-30 21:06:43+00:00
12k
TNO/PPS
plugins/nl.esi.pps.tmsc.editor/src/nl/esi/pps/tmsc/rendering/plot/EnumRenderingStrategy.java
[ { "identifier": "Dependency", "path": "plugins/nl.esi.pps.tmsc/src-gen/nl/esi/pps/tmsc/Dependency.java", "snippet": "public interface Dependency extends PropertiesContainer, ITimeRange {\n\t/**\n\t * Returns the value of the '<em><b>Tmsc</b></em>' container reference.\n\t * It is bidirectional and its o...
import org.eclipse.trace4cps.common.jfreechart.data.xy.XYEdgeSeries; import org.eclipse.trace4cps.common.jfreechart.data.xy.XYEdgeSeriesCollection; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import nl.esi.pps.tmsc.Dependency; import nl.esi.pps.tmsc.Execution; import nl.esi.pps.tmsc.viewers.plot.DependenciesRenderer; import nl.esi.pps.tmsc.viewers.plot.DependencyAnnotation; import nl.esi.pps.tmsc.viewers.plot.DependencyDataItem; import nl.esi.pps.tmsc.viewers.plot.ExecutionDataItem; import nl.esi.pps.tmsc.viewers.plot.ExecutionsRenderer;
9,015
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.rendering.plot; public abstract class EnumRenderingStrategy<E extends Enum<?>, D extends Enum<?>> extends AbstractRenderingStrategy { /** * Subclasses can use this rendering key if either Executions or Dependency * rendering is not applicable. The overridden {@code getRenderingKey(...)} * method should just return {@code null}. */ public static enum VoidRenderingKey {}; private final Class<E> executionRenderingKeyType; private final Class<D> dependencyRenderingKeyType; public EnumRenderingStrategy(Class<E> executionRenderingKeyType, Class<D> dependencyRenderingKeyType) { this.executionRenderingKeyType = executionRenderingKeyType; this.dependencyRenderingKeyType = dependencyRenderingKeyType; } /** * @return the rendering key for the {@code execution}, {@code null} if not * applicable. */ protected abstract E getRenderingKey(Execution execution); /** * @return the rendering key for the {@code dependency}, {@code null} if not * applicable. */ protected abstract D getRenderingKey(Dependency dependency); protected final int getSeries(Enum<?> renderingKey) { return renderingKey == null ? 0 : renderingKey.ordinal() + 1; } @Override public void preRendering(XYEdgeSeriesCollection dependenciesDataset, DependenciesRenderer dependenciesRenderer, XYIntervalSeriesCollection executionsDataset, ExecutionsRenderer executionsRenderer) { super.preRendering(dependenciesDataset, dependenciesRenderer, executionsDataset, executionsRenderer); // Ensure that the default series are the first in the dataset, // such that other series are visualized over the default series // Also see getSeries(Enum<?>) getDefaultExecutionSeries(executionsDataset); getDefaultDependencySeries(dependenciesDataset); for (E renderingKey : executionRenderingKeyType.getEnumConstants()) { executionsDataset.addSeries(new XYIntervalSeries(renderingKey, false, true)); configureExecutionsSeries(renderingKey, executionsRenderer); } for (D renderingKey : dependencyRenderingKeyType.getEnumConstants()) { dependenciesDataset.addSeries(new XYEdgeSeries(renderingKey)); configureDependenciesSeries(renderingKey, dependenciesRenderer); } } protected void configureExecutionsSeries(E renderingKey, ExecutionsRenderer executionsRenderer) { if (renderingKey instanceof IRenderingSeriesConfigurator) { ((IRenderingSeriesConfigurator) renderingKey).configureExecutionsSeries(executionsRenderer, getSeries(renderingKey), false); } } protected void configureDependenciesSeries(D renderingKey, DependenciesRenderer dependenciesRenderer) { if (renderingKey instanceof IRenderingSeriesConfigurator) { ((IRenderingSeriesConfigurator) renderingKey).configureDependenciesSeries(dependenciesRenderer, getSeries(renderingKey), false); } } @Override
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.rendering.plot; public abstract class EnumRenderingStrategy<E extends Enum<?>, D extends Enum<?>> extends AbstractRenderingStrategy { /** * Subclasses can use this rendering key if either Executions or Dependency * rendering is not applicable. The overridden {@code getRenderingKey(...)} * method should just return {@code null}. */ public static enum VoidRenderingKey {}; private final Class<E> executionRenderingKeyType; private final Class<D> dependencyRenderingKeyType; public EnumRenderingStrategy(Class<E> executionRenderingKeyType, Class<D> dependencyRenderingKeyType) { this.executionRenderingKeyType = executionRenderingKeyType; this.dependencyRenderingKeyType = dependencyRenderingKeyType; } /** * @return the rendering key for the {@code execution}, {@code null} if not * applicable. */ protected abstract E getRenderingKey(Execution execution); /** * @return the rendering key for the {@code dependency}, {@code null} if not * applicable. */ protected abstract D getRenderingKey(Dependency dependency); protected final int getSeries(Enum<?> renderingKey) { return renderingKey == null ? 0 : renderingKey.ordinal() + 1; } @Override public void preRendering(XYEdgeSeriesCollection dependenciesDataset, DependenciesRenderer dependenciesRenderer, XYIntervalSeriesCollection executionsDataset, ExecutionsRenderer executionsRenderer) { super.preRendering(dependenciesDataset, dependenciesRenderer, executionsDataset, executionsRenderer); // Ensure that the default series are the first in the dataset, // such that other series are visualized over the default series // Also see getSeries(Enum<?>) getDefaultExecutionSeries(executionsDataset); getDefaultDependencySeries(dependenciesDataset); for (E renderingKey : executionRenderingKeyType.getEnumConstants()) { executionsDataset.addSeries(new XYIntervalSeries(renderingKey, false, true)); configureExecutionsSeries(renderingKey, executionsRenderer); } for (D renderingKey : dependencyRenderingKeyType.getEnumConstants()) { dependenciesDataset.addSeries(new XYEdgeSeries(renderingKey)); configureDependenciesSeries(renderingKey, dependenciesRenderer); } } protected void configureExecutionsSeries(E renderingKey, ExecutionsRenderer executionsRenderer) { if (renderingKey instanceof IRenderingSeriesConfigurator) { ((IRenderingSeriesConfigurator) renderingKey).configureExecutionsSeries(executionsRenderer, getSeries(renderingKey), false); } } protected void configureDependenciesSeries(D renderingKey, DependenciesRenderer dependenciesRenderer) { if (renderingKey instanceof IRenderingSeriesConfigurator) { ((IRenderingSeriesConfigurator) renderingKey).configureDependenciesSeries(dependenciesRenderer, getSeries(renderingKey), false); } } @Override
public void add(ExecutionDataItem executionDataItem, XYIntervalSeriesCollection executionsDataset,
5
2023-10-30 16:00:25+00:00
12k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/custom/obsidilith/WaveAction.java
[ { "identifier": "IActionWithCooldown", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/action/IActionWithCooldown.java", "snippet": "public interface IActionWithCooldown {\n int perform();\n}" }, { "identifier": "BMDPacketHandler", "path": "src/main/java/com/cerbon/...
import com.cerbon.bosses_of_mass_destruction.entity.ai.action.IActionWithCooldown; import com.cerbon.bosses_of_mass_destruction.packet.BMDPacketHandler; import com.cerbon.bosses_of_mass_destruction.packet.custom.SendDeltaMovementS2CPacket; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.sound.BMDSounds; import com.cerbon.bosses_of_mass_destruction.util.BMDUtils; import com.cerbon.cerbons_api.api.general.event.EventScheduler; import com.cerbon.cerbons_api.api.general.event.TimedEvent; import com.cerbon.cerbons_api.api.static_utilities.MathUtils; import com.cerbon.cerbons_api.api.static_utilities.SoundUtils; import com.cerbon.cerbons_api.capability.CerbonsApiCapabilities; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import java.util.List;
8,766
package com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith; public class WaveAction implements IActionWithCooldown { private final Mob entity; private final List<Vec3> circlePoints; private final Level level; private final EventScheduler eventScheduler; private final double riftRadius = 4.0; public static final int waveDelay = 20; public static final int attackStartDelay = 20; public WaveAction(Mob entity){ this.entity = entity; this.circlePoints = MathUtils.buildBlockCircle(riftRadius); this.level = entity.level(); this.eventScheduler = CerbonsApiCapabilities.getLevelEventScheduler(level); } @Override public int perform() { LivingEntity target = entity.getTarget(); placeRifts(target); return 80; } private void placeRifts(LivingEntity target){ RiftBurst riftBurst = new RiftBurst( entity, (ServerLevel) level, BMDParticles.OBSIDILITH_WAVE_INDICATOR.get(), BMDParticles.OBSIDILITH_WAVE.get(), waveDelay, eventScheduler, this::damageEntity ); SoundUtils.playSound((ServerLevel) level, entity.position(), BMDSounds.OBSIDILITH_PREPARE_ATTACK.get(), SoundSource.HOSTILE, 3.0f, 0.8f, 64, null); eventScheduler.addEvent( new TimedEvent( () -> { Vec3 direction = MathUtils.unNormedDirection(entity.position(), target.position()).normalize().scale(riftRadius); int numRifts = 5; Vec3 startRiftPos = entity.position().add(direction); Vec3 endRiftPos = startRiftPos.add(direction.scale((double) numRifts * 1.5)); MathUtils.lineCallback(startRiftPos, endRiftPos, numRifts, (linePos, i) -> eventScheduler.addEvent( new TimedEvent( () -> { SoundUtils.playSound((ServerLevel) level, linePos, BMDSounds.WAVE_INDICATOR.get(), SoundSource.HOSTILE, 0.7f, 32, null); eventScheduler.addEvent( new TimedEvent( () -> SoundUtils.playSound((ServerLevel) level, linePos, BMDSounds.OBSIDILITH_WAVE.get(), SoundSource.HOSTILE, 1.2f, 32, null), waveDelay, 1, () -> !entity.isAlive() ) ); for (Vec3 point : circlePoints) riftBurst.tryPlaceRift(linePos.add(point)); }, i * 8, 1, () -> !entity.isAlive() ) )); }, attackStartDelay, 1, () -> !entity.isAlive() ) ); } private void damageEntity(LivingEntity livingEntity){ float damage = (float) this.entity.getAttributeValue(Attributes.ATTACK_DAMAGE); if (livingEntity instanceof ServerPlayer serverPlayer) BMDPacketHandler.sendToPlayer(new SendDeltaMovementS2CPacket(new Vec3(livingEntity.getDeltaMovement().x, 0.8, livingEntity.getDeltaMovement().z)), serverPlayer); livingEntity.setSecondsOnFire(5);
package com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith; public class WaveAction implements IActionWithCooldown { private final Mob entity; private final List<Vec3> circlePoints; private final Level level; private final EventScheduler eventScheduler; private final double riftRadius = 4.0; public static final int waveDelay = 20; public static final int attackStartDelay = 20; public WaveAction(Mob entity){ this.entity = entity; this.circlePoints = MathUtils.buildBlockCircle(riftRadius); this.level = entity.level(); this.eventScheduler = CerbonsApiCapabilities.getLevelEventScheduler(level); } @Override public int perform() { LivingEntity target = entity.getTarget(); placeRifts(target); return 80; } private void placeRifts(LivingEntity target){ RiftBurst riftBurst = new RiftBurst( entity, (ServerLevel) level, BMDParticles.OBSIDILITH_WAVE_INDICATOR.get(), BMDParticles.OBSIDILITH_WAVE.get(), waveDelay, eventScheduler, this::damageEntity ); SoundUtils.playSound((ServerLevel) level, entity.position(), BMDSounds.OBSIDILITH_PREPARE_ATTACK.get(), SoundSource.HOSTILE, 3.0f, 0.8f, 64, null); eventScheduler.addEvent( new TimedEvent( () -> { Vec3 direction = MathUtils.unNormedDirection(entity.position(), target.position()).normalize().scale(riftRadius); int numRifts = 5; Vec3 startRiftPos = entity.position().add(direction); Vec3 endRiftPos = startRiftPos.add(direction.scale((double) numRifts * 1.5)); MathUtils.lineCallback(startRiftPos, endRiftPos, numRifts, (linePos, i) -> eventScheduler.addEvent( new TimedEvent( () -> { SoundUtils.playSound((ServerLevel) level, linePos, BMDSounds.WAVE_INDICATOR.get(), SoundSource.HOSTILE, 0.7f, 32, null); eventScheduler.addEvent( new TimedEvent( () -> SoundUtils.playSound((ServerLevel) level, linePos, BMDSounds.OBSIDILITH_WAVE.get(), SoundSource.HOSTILE, 1.2f, 32, null), waveDelay, 1, () -> !entity.isAlive() ) ); for (Vec3 point : circlePoints) riftBurst.tryPlaceRift(linePos.add(point)); }, i * 8, 1, () -> !entity.isAlive() ) )); }, attackStartDelay, 1, () -> !entity.isAlive() ) ); } private void damageEntity(LivingEntity livingEntity){ float damage = (float) this.entity.getAttributeValue(Attributes.ATTACK_DAMAGE); if (livingEntity instanceof ServerPlayer serverPlayer) BMDPacketHandler.sendToPlayer(new SendDeltaMovementS2CPacket(new Vec3(livingEntity.getDeltaMovement().x, 0.8, livingEntity.getDeltaMovement().z)), serverPlayer); livingEntity.setSecondsOnFire(5);
livingEntity.hurt(BMDUtils.shieldPiercing(livingEntity.level(), this.entity), damage);
5
2023-10-25 16:28:17+00:00
12k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/BatchesService.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.domains.sms.models.BaseBatch; import com.sinch.sdk.domains.sms.models.Batch; import com.sinch.sdk.domains.sms.models.DryRun; import com.sinch.sdk.domains.sms.models.requests.BatchesListRequestParameters; import com.sinch.sdk.domains.sms.models.requests.UpdateBaseBatchRequest; import com.sinch.sdk.domains.sms.models.responses.BatchesListResponse; import java.util.Collection;
7,957
package com.sinch.sdk.domains.sms; /** * Batches Service * * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/</a> * @since 1.0 */ public interface BatchesService { /** * Get a batch message <br> * This operation returns a specific batch that matches the provided batch ID. * * @param batchId The batch ID you received from sending a message * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage</a> * @since 1.0 */ <T extends Batch<?>> T get(String batchId) throws ApiException; /** * Send a message or a batch of messages <br> * Depending on the length of the body, one message might be split into multiple parts and charged * accordingly. <br> * Any groups targeted in a scheduled batch will be evaluated at the time of sending. If a group * is deleted between batch creation and scheduled date, it will be considered empty. <br> * Be sure to use the correct region in the server URL. * * @param batch The batch to be created * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS</a> * @since 1.0 */ <T extends Batch<?>> T send(BaseBatch<?> batch) throws ApiException; /** * Dry run <br> * This operation will perform a dry run of a batch which calculates the bodies and number of * parts for all messages in the batch without actually sending any messages. * * @param perRecipient Whether to include per recipient details in the response * @param numberOfRecipient Max number of recipients to include per recipient details for in the * response * @param batch The batch to be send * @return Details about dryRun execution * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run</a> * @since 1.0 */
package com.sinch.sdk.domains.sms; /** * Batches Service * * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/</a> * @since 1.0 */ public interface BatchesService { /** * Get a batch message <br> * This operation returns a specific batch that matches the provided batch ID. * * @param batchId The batch ID you received from sending a message * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage</a> * @since 1.0 */ <T extends Batch<?>> T get(String batchId) throws ApiException; /** * Send a message or a batch of messages <br> * Depending on the length of the body, one message might be split into multiple parts and charged * accordingly. <br> * Any groups targeted in a scheduled batch will be evaluated at the time of sending. If a group * is deleted between batch creation and scheduled date, it will be considered empty. <br> * Be sure to use the correct region in the server URL. * * @param batch The batch to be created * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS</a> * @since 1.0 */ <T extends Batch<?>> T send(BaseBatch<?> batch) throws ApiException; /** * Dry run <br> * This operation will perform a dry run of a batch which calculates the bodies and number of * parts for all messages in the batch without actually sending any messages. * * @param perRecipient Whether to include per recipient details in the response * @param numberOfRecipient Max number of recipients to include per recipient details for in the * response * @param batch The batch to be send * @return Details about dryRun execution * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run</a> * @since 1.0 */
DryRun dryRun(boolean perRecipient, int numberOfRecipient, BaseBatch<?> batch)
3
2023-10-31 08:32:59+00:00
12k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/DataCommand.java
[ { "identifier": "SpCoBot", "path": "src/main/java/top/spco/SpCoBot.java", "snippet": "public class SpCoBot {\n private static SpCoBot instance;\n public static Logger logger;\n public static File dataFolder;\n public static File configFolder;\n public long botId;\n public long botOwner...
import top.spco.SpCoBot; import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.User; import top.spco.api.message.Message; import top.spco.service.command.AbstractCommand; import top.spco.service.command.CommandMeta; import top.spco.service.command.CommandParam; import top.spco.service.command.CommandUsage; import top.spco.user.BotUser; import top.spco.user.UserPermission; import java.sql.SQLException; import java.util.List;
10,727
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands; /** * @author SpCo * @version 1.2.3 * @since 0.1.0 */ public final class DataCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"data"}; } @Override public String getDescriptions() { return "操作数据"; } @Override public List<CommandUsage> getUsages() { return List.of( new CommandUsage("data", "查询记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "get"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待查询的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)), new CommandUsage("data", "编辑记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "set"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待修改的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("新值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public UserPermission needPermission() { return UserPermission.OWNER; } /** * <pre> * 0 1 2 3 4 5 * /data set <表名> <字段名> <记录值> <待修改的字段名> <新值> * /data get <表名> <字段名> <记录值> <待查询的字段名> * </pre> */ @Override
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands; /** * @author SpCo * @version 1.2.3 * @since 0.1.0 */ public final class DataCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"data"}; } @Override public String getDescriptions() { return "操作数据"; } @Override public List<CommandUsage> getUsages() { return List.of( new CommandUsage("data", "查询记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "get"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待查询的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)), new CommandUsage("data", "编辑记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "set"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待修改的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("新值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public UserPermission needPermission() { return UserPermission.OWNER; } /** * <pre> * 0 1 2 3 4 5 * /data set <表名> <字段名> <记录值> <待修改的字段名> <新值> * /data get <表名> <字段名> <记录值> <待查询的字段名> * </pre> */ @Override
public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) {
2
2023-10-26 10:27:47+00:00
12k
cty1928/GreenTravel
src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/maps/MapsFragment.java
[ { "identifier": "DrawerStateListener", "path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/DrawerStateListener.java", "snippet": "public interface DrawerStateListener {\n public void onDrawerSlide(View drawerView, float slideOffset);\n\n public void onDrawerOpened(View drawerVie...
import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.fragment.app.Fragment; import com.amap.api.maps.AMap; import com.amap.api.maps.MapView; import com.amap.api.maps.overlay.PoiOverlay; import com.amap.api.navi.AMapNavi; import com.amap.api.navi.model.NaviLatLng; import com.amap.api.services.core.AMapException; import com.amap.api.services.core.PoiItem; import com.amap.api.services.help.Inputtips; import com.amap.api.services.help.Tip; import org.zarroboogs.maps.DrawerStateListener; import org.zarroboogs.maps.MapsApplication; import org.zarroboogs.maps.beans.PoiSearchTip; import org.zarroboogs.maps.ui.anim.AnimEndListener; import org.zarroboogs.maps.ui.anim.ViewAnimUtils; import org.zarroboogs.maps.ui.poi.PoiSearchAdapter; import org.zarroboogs.maps.R; import org.zarroboogs.maps.ui.navi.NaviRouteActivity; import org.zarroboogs.maps.presenters.iviews.ISearchMapsView; import org.zarroboogs.maps.ui.MapsModule; import org.zarroboogs.maps.presenters.SearchMapsPresenter; import org.zarroboogs.maps.utils.SettingUtils; import org.zarroboogs.maps.utils.ToastUtil; import java.util.ArrayList; import java.util.List;
8,469
package org.zarroboogs.maps.ui.maps; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link MapsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link MapsFragment#newInstance} factory method to * create an instance of this fragment. */ public class MapsFragment extends Fragment implements View.OnClickListener, DrawerStateListener, ISearchMapsView, OnKeyListener { private static final boolean DEBUG = false; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private boolean mLandscape = false; private float mOri = 0; private AMap aMap; private MapView mapView;
package org.zarroboogs.maps.ui.maps; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link MapsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link MapsFragment#newInstance} factory method to * create an instance of this fragment. */ public class MapsFragment extends Fragment implements View.OnClickListener, DrawerStateListener, ISearchMapsView, OnKeyListener { private static final boolean DEBUG = false; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private boolean mLandscape = false; private float mOri = 0; private AMap aMap; private MapView mapView;
private MapsModule mMapsModule;
8
2023-10-31 01:21:54+00:00
12k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java
[ { "identifier": "ServiceException", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/ServiceException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 业...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils; import cn.iocoder.yudao.framework.security.config.SecurityProperties; import cn.iocoder.yudao.framework.security.core.LoginUser; import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils; import cn.iocoder.yudao.framework.web.core.handler.GlobalExceptionHandler; import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils; import cn.iocoder.yudao.service.api.infra.oauth2.OAuth2TokenApi; import cn.iocoder.yudao.service.api.infra.oauth2.dto.OAuth2AccessTokenCheckRespDTO; import lombok.RequiredArgsConstructor; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
7,633
package cn.iocoder.yudao.framework.security.core.filter; /** * Token 过滤器,验证 token 的有效性 * 验证通过后,获得 {@link LoginUser} 信息,并加入到 Spring Security 上下文 * * @author 芋道源码 */ @RequiredArgsConstructor public class TokenAuthenticationFilter extends OncePerRequestFilter { private final SecurityProperties securityProperties; private final GlobalExceptionHandler globalExceptionHandler; private final OAuth2TokenApi oauth2TokenApi; @Override @SuppressWarnings("NullableProblems") protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader()); if (StrUtil.isNotEmpty(token)) { Integer userType = WebFrameworkUtils.getLoginUserType(request); try { // 1.1 基于 token 构建登录用户 LoginUser loginUser = buildLoginUserByToken(token, userType); // 1.2 模拟 Login 功能,方便日常开发调试 if (loginUser == null) { loginUser = mockLoginUser(request, token, userType); } // 2. 设置当前用户 if (loginUser != null) { SecurityFrameworkUtils.setLoginUser(loginUser, request); } } catch (Throwable ex) {
package cn.iocoder.yudao.framework.security.core.filter; /** * Token 过滤器,验证 token 的有效性 * 验证通过后,获得 {@link LoginUser} 信息,并加入到 Spring Security 上下文 * * @author 芋道源码 */ @RequiredArgsConstructor public class TokenAuthenticationFilter extends OncePerRequestFilter { private final SecurityProperties securityProperties; private final GlobalExceptionHandler globalExceptionHandler; private final OAuth2TokenApi oauth2TokenApi; @Override @SuppressWarnings("NullableProblems") protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader()); if (StrUtil.isNotEmpty(token)) { Integer userType = WebFrameworkUtils.getLoginUserType(request); try { // 1.1 基于 token 构建登录用户 LoginUser loginUser = buildLoginUserByToken(token, userType); // 1.2 模拟 Login 功能,方便日常开发调试 if (loginUser == null) { loginUser = mockLoginUser(request, token, userType); } // 2. 设置当前用户 if (loginUser != null) { SecurityFrameworkUtils.setLoginUser(loginUser, request); } } catch (Throwable ex) {
CommonResult<?> result = globalExceptionHandler.allExceptionHandler(request, ex);
1
2023-10-27 06:35:24+00:00
12k
SUFIAG/Hotel-Reservation-System-Java-And-PHP
src/app/src/main/java/com/sameetasadullah/i180479_i180531/dataLayer/writerAndReader.java
[ { "identifier": "Customer", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Customer.java", "snippet": "public class Customer {\n private String name, address, email, password, phoneNo, CNIC, accountNo, dp;\n private int ID;\n\n //constructors\n public Customer(...
import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.sameetasadullah.i180479_i180531.logicLayer.Customer; import com.sameetasadullah.i180479_i180531.logicLayer.HRS; import com.sameetasadullah.i180479_i180531.logicLayer.Hotel; import com.sameetasadullah.i180479_i180531.logicLayer.Reservation; import com.sameetasadullah.i180479_i180531.logicLayer.Room; import com.sameetasadullah.i180479_i180531.logicLayer.Vendor; import com.sameetasadullah.i180479_i180531.presentationLayer.MyDBHelper; import com.sameetasadullah.i180479_i180531.presentationLayer.Reservations_Store; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector;
7,370
package com.sameetasadullah.i180479_i180531.dataLayer; public class writerAndReader { Context context; String directoryUrl = "http://192.168.18.81/PHP_Files/"; public writerAndReader(Context context) { this.context = context; } @NonNull private byte[] getByteArray(Uri image) { Bitmap pic = null; try { pic = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); pic.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); }
package com.sameetasadullah.i180479_i180531.dataLayer; public class writerAndReader { Context context; String directoryUrl = "http://192.168.18.81/PHP_Files/"; public writerAndReader(Context context) { this.context = context; } @NonNull private byte[] getByteArray(Uri image) { Bitmap pic = null; try { pic = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); pic.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); }
public void insertCustomerDataIntoServer(Customer customer, Uri dp, VolleyCallBack volleyCallBack) {
0
2023-10-25 20:58:45+00:00
12k
MachineMC/Cogwheel
cogwheel-core/src/main/java/org/machinemc/cogwheel/serialization/SerializerRegistry.java
[ { "identifier": "Configuration", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/Configuration.java", "snippet": "public interface Configuration {\n\n}" }, { "identifier": "Serializers", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/serialization/Serializers....
import org.machinemc.cogwheel.config.Configuration; import org.machinemc.cogwheel.serialization.Serializers.*; import org.machinemc.cogwheel.util.ArrayUtils; import org.machinemc.cogwheel.util.NumberUtils; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.time.Instant; import java.util.*; import java.util.function.Supplier;
8,350
package org.machinemc.cogwheel.serialization; public class SerializerRegistry { public static final SerializerRegistry DEFAULT_REGISTRY = new DefaultSerializerRegistry(); final Map<Class<?>, SerializerFactory<?>> serializerMap; private final boolean useDefaults; public SerializerRegistry() { this(true); } public SerializerRegistry(boolean useDefaults) { this(HashMap::new, useDefaults); } public SerializerRegistry(Supplier<Map<Class<?>, SerializerFactory<?>>> factory, boolean useDefaults) { this(factory.get(), useDefaults); } public SerializerRegistry(Map<Class<?>, SerializerFactory<?>> serializerMap, boolean useDefaults) { this.serializerMap = serializerMap; this.useDefaults = useDefaults; } @SuppressWarnings("unchecked") public <T> void addSerializer(Class<T> type, Class<? extends T>[] subtypes, Serializer<T> serializer) { addSerializer(type, serializer); for (Class<? extends T> subtype : subtypes) addSerializer((Class<T>) subtype, serializer); } public <T> void addSerializer(Class<T> type, Serializer<T> serializer) { Objects.requireNonNull(serializer, "serializer"); addSerializer(type, SerializerFactory.of(serializer)); } @SuppressWarnings("unchecked") public <T> void addSerializer(Class<T> type, Class<? extends T>[] subtypes, SerializerFactory<T> serializer) { addSerializer(type, serializer); for (Class<? extends T> subtype : subtypes) addSerializer((Class<T>) subtype, serializer); } public <T> void addSerializer(Class<T> type, SerializerFactory<T> serializer) { if (serializerExists(Objects.requireNonNull(type, "type"))) throw new IllegalArgumentException("Type '" + type + "' already has a registered serializer"); serializerMap.put(type, Objects.requireNonNull(serializer, "serializer")); } public boolean serializerExists(Class<?> type) { return serializerMap.containsKey(type); } public <T> Serializer<T> getSerializer(Class<T> type, SerializerContext context) { SerializerFactory<T> factory = getSerializerFactory(type); return factory != null ? factory.newInstance(context) : null; } @SuppressWarnings("unchecked") public <T> SerializerFactory<T> getSerializerFactory(Class<T> type) { if (type == null) return null; SerializerFactory<T> serializer = (SerializerFactory<T>) serializerMap.get(type); if (serializer != null || !useDefaults) return serializer; return DEFAULT_REGISTRY.getSerializerFactory(type); } private static class DefaultSerializerRegistry extends SerializerRegistry { private DefaultSerializerRegistry() { super(false); } private boolean allowRegistration; { allowRegistration = true; addSerializer(Byte.class, new NumberSerializer<>(Byte.class, Number::byteValue)); addSerializer(Short.class, new NumberSerializer<>(Short.class, Number::shortValue)); addSerializer(Integer.class, new NumberSerializer<>(Integer.class, Number::intValue)); addSerializer(Long.class, new NumberSerializer<>(Long.class, Number::longValue)); addSerializer(Float.class, new NumberSerializer<>(Float.class, Number::floatValue)); addSerializer(Double.class, new NumberSerializer<>(Double.class, Number::doubleValue)); addSerializer(BigInteger.class, new NumberSerializer<>(BigInteger.class,
package org.machinemc.cogwheel.serialization; public class SerializerRegistry { public static final SerializerRegistry DEFAULT_REGISTRY = new DefaultSerializerRegistry(); final Map<Class<?>, SerializerFactory<?>> serializerMap; private final boolean useDefaults; public SerializerRegistry() { this(true); } public SerializerRegistry(boolean useDefaults) { this(HashMap::new, useDefaults); } public SerializerRegistry(Supplier<Map<Class<?>, SerializerFactory<?>>> factory, boolean useDefaults) { this(factory.get(), useDefaults); } public SerializerRegistry(Map<Class<?>, SerializerFactory<?>> serializerMap, boolean useDefaults) { this.serializerMap = serializerMap; this.useDefaults = useDefaults; } @SuppressWarnings("unchecked") public <T> void addSerializer(Class<T> type, Class<? extends T>[] subtypes, Serializer<T> serializer) { addSerializer(type, serializer); for (Class<? extends T> subtype : subtypes) addSerializer((Class<T>) subtype, serializer); } public <T> void addSerializer(Class<T> type, Serializer<T> serializer) { Objects.requireNonNull(serializer, "serializer"); addSerializer(type, SerializerFactory.of(serializer)); } @SuppressWarnings("unchecked") public <T> void addSerializer(Class<T> type, Class<? extends T>[] subtypes, SerializerFactory<T> serializer) { addSerializer(type, serializer); for (Class<? extends T> subtype : subtypes) addSerializer((Class<T>) subtype, serializer); } public <T> void addSerializer(Class<T> type, SerializerFactory<T> serializer) { if (serializerExists(Objects.requireNonNull(type, "type"))) throw new IllegalArgumentException("Type '" + type + "' already has a registered serializer"); serializerMap.put(type, Objects.requireNonNull(serializer, "serializer")); } public boolean serializerExists(Class<?> type) { return serializerMap.containsKey(type); } public <T> Serializer<T> getSerializer(Class<T> type, SerializerContext context) { SerializerFactory<T> factory = getSerializerFactory(type); return factory != null ? factory.newInstance(context) : null; } @SuppressWarnings("unchecked") public <T> SerializerFactory<T> getSerializerFactory(Class<T> type) { if (type == null) return null; SerializerFactory<T> serializer = (SerializerFactory<T>) serializerMap.get(type); if (serializer != null || !useDefaults) return serializer; return DEFAULT_REGISTRY.getSerializerFactory(type); } private static class DefaultSerializerRegistry extends SerializerRegistry { private DefaultSerializerRegistry() { super(false); } private boolean allowRegistration; { allowRegistration = true; addSerializer(Byte.class, new NumberSerializer<>(Byte.class, Number::byteValue)); addSerializer(Short.class, new NumberSerializer<>(Short.class, Number::shortValue)); addSerializer(Integer.class, new NumberSerializer<>(Integer.class, Number::intValue)); addSerializer(Long.class, new NumberSerializer<>(Long.class, Number::longValue)); addSerializer(Float.class, new NumberSerializer<>(Float.class, Number::floatValue)); addSerializer(Double.class, new NumberSerializer<>(Double.class, Number::doubleValue)); addSerializer(BigInteger.class, new NumberSerializer<>(BigInteger.class,
number -> NumberUtils.parseInteger(number.toString())));
3
2023-10-25 11:31:02+00:00
12k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/IEXCloudClient.java
[ { "identifier": "CompanyData", "path": "src/main/java/io/github/f4pl0/companydata/CompanyData.java", "snippet": "public class CompanyData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n\n /**\n * Company I...
import io.github.f4pl0.companydata.CompanyData; import io.github.f4pl0.config.ConfigInjector; import io.github.f4pl0.config.IEXCloudConfig; import io.github.f4pl0.equitiesmarketdata.EquitiesMarketData; import io.github.f4pl0.historicaldata.HistoricalData; import io.github.f4pl0.reference.Reference;
7,987
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData; private final Reference reference; private final CompanyData companyData;
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData; private final Reference reference; private final CompanyData companyData;
private final HistoricalData historicalData;
4
2023-10-27 17:56:14+00:00
12k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/util/LogFiles.java
[ { "identifier": "DriveConstants", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/DriveConstants.java", "snippet": "@Config\npublic class DriveConstants {\n\n /*\n * These are motor constants that should be listed online for your motors.\n */\n public static...
import android.annotation.SuppressLint; import android.content.Context; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerImpl; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerNotifier; import com.qualcomm.robotcore.util.RobotLog; import com.qualcomm.robotcore.util.WebHandlerManager; import org.firstinspires.ftc.ftccommon.external.WebHandlerRegistrar; import org.firstinspires.ftc.robotcore.internal.system.AppUtil; import org.firstinspires.ftc.teamcode.RoadRunner.drive.DriveConstants; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleTankDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.StandardTrackingWheelLocalizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import fi.iki.elonen.NanoHTTPD;
7,424
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL; public double mecTransP = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kP; public double mecTransI = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kI; public double mecTransD = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kD; public double mecHeadingP = SampleMecanumDrive.HEADING_PID.kP; public double mecHeadingI = SampleMecanumDrive.HEADING_PID.kI; public double mecHeadingD = SampleMecanumDrive.HEADING_PID.kD; public double mecLateralMultiplier = SampleMecanumDrive.LATERAL_MULTIPLIER;
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL; public double mecTransP = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kP; public double mecTransI = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kI; public double mecTransD = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kD; public double mecHeadingP = SampleMecanumDrive.HEADING_PID.kP; public double mecHeadingI = SampleMecanumDrive.HEADING_PID.kI; public double mecHeadingD = SampleMecanumDrive.HEADING_PID.kD; public double mecLateralMultiplier = SampleMecanumDrive.LATERAL_MULTIPLIER;
public double tankAxialP = SampleTankDrive.AXIAL_PID.kP;
2
2023-10-31 16:06:46+00:00
12k
slatepowered/slate
slate-master/src/main/java/slatepowered/slate/master/Master.java
[ { "identifier": "IntegratedCluster", "path": "slate-master/src/main/java/slatepowered/slate/cluster/IntegratedCluster.java", "snippet": "public class IntegratedCluster extends Cluster<IntegratedClusterInstance> {\r\n\r\n /**\r\n * The master instance.\r\n */\r\n protected final Master mast...
import slatepowered.slate.cluster.IntegratedCluster; import slatepowered.slate.cluster.IntegratedClusterInstance; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.model.MasterManagedNode; import slatepowered.slate.model.MasterNetwork; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.service.ProvidedPackageService; import slatepowered.slate.plugin.SlatePlugin; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.data.Pair; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.stream.Collectors;
8,980
package slatepowered.slate.master; /** * The master bootstrap/network. */ public class Master extends MasterNetwork { /** * The working directory. */ protected final Path directory; /** * The local package manager for locally managing packages. */ protected final PackageManager localPackageManager; /** * The {@link slatepowered.slate.cluster.Cluster} impl of the integrated cluster. */ protected final IntegratedCluster integratedClusterImpl; /** * The integrated cluster instance. */ protected final IntegratedClusterInstance integratedClusterInstance; /** * The plugin manager. */ protected final SlatePluginManager pluginManager; Master(Path directory, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.directory = directory; register(PackageManager.KEY, localPackageManager = new PackageManager(serviceManager(), directory.resolve("packages"))); this.pluginManager = new SlatePluginManager(localPackageManager) { final String[] envNames = new String[] { "master", "controller" }; @Override public String[] getEnvironmentNames() { return envNames; } }; register(SlatePluginManager.KEY, pluginManager); integratedClusterImpl = new IntegratedCluster("master.integrated-cluster", this); integratedClusterInstance = new IntegratedClusterInstance(integratedClusterImpl, communicationKey, communicationStrategy); registerNode(integratedClusterInstance.node()); // add master package provider service
package slatepowered.slate.master; /** * The master bootstrap/network. */ public class Master extends MasterNetwork { /** * The working directory. */ protected final Path directory; /** * The local package manager for locally managing packages. */ protected final PackageManager localPackageManager; /** * The {@link slatepowered.slate.cluster.Cluster} impl of the integrated cluster. */ protected final IntegratedCluster integratedClusterImpl; /** * The integrated cluster instance. */ protected final IntegratedClusterInstance integratedClusterInstance; /** * The plugin manager. */ protected final SlatePluginManager pluginManager; Master(Path directory, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.directory = directory; register(PackageManager.KEY, localPackageManager = new PackageManager(serviceManager(), directory.resolve("packages"))); this.pluginManager = new SlatePluginManager(localPackageManager) { final String[] envNames = new String[] { "master", "controller" }; @Override public String[] getEnvironmentNames() { return envNames; } }; register(SlatePluginManager.KEY, pluginManager); integratedClusterImpl = new IntegratedCluster("master.integrated-cluster", this); integratedClusterInstance = new IntegratedClusterInstance(integratedClusterImpl, communicationKey, communicationStrategy); registerNode(integratedClusterInstance.node()); // add master package provider service
register(ProvidedPackageService.KEY, new ProvidedPackageService() {
8
2023-10-30 08:58:02+00:00
12k
Melledy/LunarCore
src/main/java/emu/lunarcore/game/player/lineup/PlayerExtraLineup.java
[ { "identifier": "GameConstants", "path": "src/main/java/emu/lunarcore/GameConstants.java", "snippet": "public class GameConstants {\n public static String VERSION = \"1.6.0\";\n \n public static final ZoneOffset CURRENT_ZONEOFFSET = ZoneOffset.systemDefault().getRules().getOffset(Instant.now())...
import dev.morphia.annotations.Entity; import emu.lunarcore.GameConstants; import emu.lunarcore.game.player.Player; import emu.lunarcore.server.packet.send.PacketSyncLineupNotify;
8,337
package emu.lunarcore.game.player.lineup; @Entity(value = "lineupsExtra", useDiscriminator = false) public class PlayerExtraLineup extends PlayerLineup { private int mp; @Deprecated // Morphia only! public PlayerExtraLineup() {}
package emu.lunarcore.game.player.lineup; @Entity(value = "lineupsExtra", useDiscriminator = false) public class PlayerExtraLineup extends PlayerLineup { private int mp; @Deprecated // Morphia only! public PlayerExtraLineup() {}
public PlayerExtraLineup(Player player, int extraLineupType) {
1
2023-10-10 12:57:35+00:00
12k
jar-analyzer/jar-analyzer
src/main/java/me/n1ar4/jar/analyzer/gui/MainForm.java
[ { "identifier": "ConfigEngine", "path": "src/main/java/me/n1ar4/jar/analyzer/config/ConfigEngine.java", "snippet": "public class ConfigEngine {\n private static final Logger logger = LogManager.getLogger();\n public static final String CONFIG_FILE_PATH = \".jar-analyzer\";\n\n public static boo...
import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import me.n1ar4.jar.analyzer.config.ConfigEngine; import me.n1ar4.jar.analyzer.config.ConfigFile; import me.n1ar4.jar.analyzer.engine.CoreEngine; import me.n1ar4.jar.analyzer.engine.DecompileEngine; import me.n1ar4.jar.analyzer.entity.ClassResult; import me.n1ar4.jar.analyzer.entity.MethodResult; import me.n1ar4.jar.analyzer.gui.action.*; import me.n1ar4.jar.analyzer.gui.adapter.*; import me.n1ar4.jar.analyzer.gui.font.FontHelper; import me.n1ar4.jar.analyzer.gui.render.AllMethodsRender; import me.n1ar4.jar.analyzer.gui.render.ClassRender; import me.n1ar4.jar.analyzer.gui.render.MethodCallRender; import me.n1ar4.jar.analyzer.gui.render.SpringMethodRender; import me.n1ar4.jar.analyzer.gui.state.State; import me.n1ar4.jar.analyzer.gui.tree.FileTree; import me.n1ar4.jar.analyzer.gui.update.UpdateChecker; import me.n1ar4.jar.analyzer.gui.util.*; import me.n1ar4.jar.analyzer.gui.vul.*; import me.n1ar4.jar.analyzer.starter.Const; import me.n1ar4.jar.analyzer.utils.DirUtil; import me.n1ar4.log.LogManager; import me.n1ar4.log.Logger; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.plaf.FontUIResource; import javax.swing.text.StyleContext; import java.awt.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Locale;
10,542
public JButton getScriptEngineEvalButton() { return scriptEngineEvalButton; } public JButton getSqliteButton() { return sqliteButton; } public JButton getGptButton() { return gptButton; } public JButton getCleanButton() { return cleanButton; } public JButton getShowStringListButton() { return showStringListButton; } public JButton getFastjsonButton() { return fastjsonButton; } public JButton getUnzipButton() { return unzipButton; } public JButton getHessianButton() { return hessianButton; } private void resolveConfig() { if (config != null) { String temp = config.getTempPath(); String db = config.getDbPath(); if (temp == null || db == null) { return; } if (Files.exists(Paths.get(temp)) && Files.exists(Paths.get(db))) { databaseSizeVal.setText(config.getDbSize()); totalClassVal.setText(config.getTotalClass()); totalJarVal.setText(config.getTotalJar()); totalMethodVal.setText(config.getTotalMethod()); fileText.setText(config.getJarPath()); loadDBText.setText(config.getDbPath()); engine = new CoreEngine(config); engineVal.setText("RUNNING"); engineVal.setForeground(Color.GREEN); buildBar.setValue(100); } else { try { Files.delete(Paths.get(ConfigEngine.CONFIG_FILE_PATH)); } catch (Exception ignored) { } try { DirUtil.removeDir(new File(Const.tempDir)); } catch (Exception ignored) { } } } } public MainForm() { logger.info("init main form"); methodDefinitionRadioButton.setSelected(true); fernRadio.setSelected(true); fernRadio.setText(DecompileEngine.INFO); searchStrText.setEnabled(false); deleteTempCheckBox.setSelected(true); LogUtil.setT(logArea); SyntaxAreaHelper.buildJava(codePanel); engineVal.setText("CLOSED"); engineVal.setForeground(Color.RED); autoSaveCheckBox.setSelected(true); if (ConfigEngine.exist()) { config = ConfigEngine.parseConfig(); resolveConfig(); } fileTree.refresh(); allMethodList.setCellRenderer(new AllMethodsRender()); calleeList.setCellRenderer(new MethodCallRender()); callerList.setCellRenderer(new MethodCallRender()); searchList.setCellRenderer(new MethodCallRender()); methodImplList.setCellRenderer(new MethodCallRender()); superImplList.setCellRenderer(new MethodCallRender()); springCList.setCellRenderer(new ClassRender()); springMList.setCellRenderer(new SpringMethodRender()); historyList.setCellRenderer(new MethodCallRender()); historyListData = new DefaultListModel<>(); historyList.setModel(historyListData); prevBtn.setIcon(IconManager.prevIcon); nextBtn.setIcon(IconManager.nextIcon); logoLabel.setIcon(IconManager.showIcon); jreRuntimeLabel.setIcon(IconManager.javaIcon); dbPathLabel.setIcon(IconManager.dbIcon); startEngineButton.setIcon(IconManager.startIcon); curJarLabel.setIcon(IconManager.jarIcon); curClassLabel.setIcon(IconManager.curIcon); curMethodLabel.setIcon(IconManager.curIcon); authorLabel.setIcon(IconManager.auIcon); authorTextLabel.setIcon(IconManager.githubIcon); classBlackListLabel.setIcon(IconManager.whiteIcon); authorTextLabel.addMouseListener(new AuthorAdapter()); blackArea.setText(Const.blackAreaText); classBlackArea.setText(Const.classBlackAreaText); equalsSearchRadioButton.setSelected(true); logger.info("init main form success"); } private static void init() {
package me.n1ar4.jar.analyzer.gui; public class MainForm { private static final Logger logger = LogManager.getLogger(); private JPanel masterPanel; private JTabbedPane tabbedPanel; private JPanel codePanel; private JPanel corePanel; private JPanel startPanel; private JButton choseBtn; private JTextField fileText; private JButton startEngineButton; private JCheckBox resolveJarsInJarCheckBox; private JPanel chosePanel; private JRadioButton fernRadio; private JPanel decompilerPanel; private JProgressBar buildBar; private JPanel infoPanel; private JLabel totalClassLabel; private JLabel totalClassVal; private JLabel totalMethodLabel; private JLabel totalMethodVal; private JLabel totalJarLabel; private JLabel totalJarVal; private JLabel databaseSizeLabel; private JLabel databaseSizeVal; private JRadioButton methodDefinitionRadioButton; private JRadioButton methodCallRadioButton; private JButton startSearchButton; private JRadioButton stringContainsRadioButton; private JRadioButton binarySearchRadioButton; private JTextField searchClassText; private JPanel leftPanel; private JScrollPane treeScrollPanel; private FileTree fileTree; private JPanel logPanel; private JScrollPane logScroll; private JTextArea logArea; private JPanel curMethodPanel; private JScrollPane allMethodScroll; private JList<MethodResult> allMethodList; private JPanel historyPanel; private JPanel advancePanel; private JScrollPane hisScroll; private JList<MethodResult> callerList; private JList<MethodResult> calleeList; private JList<MethodResult> historyList; private JTextField loadDBText; private JLabel dbPathLabel; private JLabel engineVal; private JLabel engineLabel; private JCheckBox autoSaveCheckBox; private JTextField curClassText; private JTextField curMethodText; private JLabel curClassLabel; private JLabel curMethodLabel; private JTextField searchMethodText; private JTextField searchStrText; private JPanel searchResPanel; private JScrollPane searchScroll; private JList<MethodResult> searchList; private JTextField curJarText; private JLabel curJarLabel; private JTextField rtText; private JLabel jreRuntimeLabel; private JCheckBox autoFindRtJarCheckBox; private JCheckBox addRtJarWhenCheckBox; private JButton opcodeBtn; private JButton javaAsmBtn; private JButton JNDIButton; private JButton runtimeExecButton; private JButton processBuilderStartButton; private JButton spELGetValueButton; private JButton readObjectButton; private JButton scriptEngineEvalButton; private JButton BCELLoadClassButton; private JButton defineClassButton; private JButton OGNLGetValueButton; private JPanel javaVulSearchPanel; private JLabel javaVulLabel; private JLabel logoLabel; private JPanel authorPanel; private JLabel authorLabel; private JLabel authorTextLabel; private JPanel curPanel; private JPanel methodImplPanel; private JScrollPane implScroll; private JList<MethodResult> methodImplList; private JCheckBox deleteTempCheckBox; private JPanel callerPanel; private JScrollPane callerScroll; private JPanel calleePanel; private JScrollPane calleeScroll; private JPanel callPanel; private JPanel searchOptionsPanel; private JPanel searchInnerPanel; private JLabel searchClassLabel; private JLabel searchMethodLabel; private JLabel searchStrLabel; private JScrollPane superImplScroll; private JList<MethodResult> superImplList; private JPanel analysis; private JButton cfgBtn; private JLabel cfgLabel; private JLabel frameLabel; private JButton frameBtn; private JButton encoderBtn; private JButton repeaterBtn; private JButton listenerBtn; private JPanel springPanel; private JPanel springCPanel; private JPanel springMPanel; private JScrollPane scScroll; private JScrollPane smScroll; private JList<ClassResult> springCList; private JList<MethodResult> springMList; private JPanel piPanel; private JLabel encoderLabel; private JLabel repeaterLabel; private JLabel listenerLabel; private JButton prevBtn; private JButton nextBtn; private JPanel actionPanel; private JPanel soPanel; private JRadioButton likeSearchRadioButton; private JRadioButton equalsSearchRadioButton; private JPanel blackListPanel; private JScrollPane blackScroll; private JTextArea blackArea; private JTextArea classBlackArea; private JLabel classBlackListLabel; private JScrollPane classBlackPanel; private JLabel classBlackLabel; private JButton simpleFrameButton; private JButton refreshButton; private JLabel springLabel; private JButton sqliteButton; private JLabel sqliteLabel; private JButton gptButton; private JLabel chatGPTLabel; private JButton cleanButton; private JButton showStringListButton; private JButton fastjsonButton; private JButton unzipButton; private JButton hessianButton; private static MainForm instance; private static ConfigFile config; private static CoreEngine engine; private static JTextArea codeArea; private static MethodResult curMethod; private static State prevState; private static State nextState; private static State curState; private static DefaultListModel<MethodResult> historyListData; public static State getPrevState() { return prevState; } public static void setPrevState(State prevState) { MainForm.prevState = prevState; } public static State getNextState() { return nextState; } public static void setNextState(State nextState) { MainForm.nextState = nextState; } public static State getCurState() { return curState; } public static void setCurState(State curState) { MainForm.curState = curState; } public JList<ClassResult> getSpringCList() { return springCList; } public JList<MethodResult> getSpringMList() { return springMList; } public JButton getEncoderBtn() { return encoderBtn; } public JButton getRepeaterBtn() { return repeaterBtn; } public JButton getListenerBtn() { return listenerBtn; } // FOR CLI private static final MainForm fakeInstance = new MainForm(true); public MainForm(boolean fake) { if (fake) { logger.info("init fake instance"); } } public static MainForm getInstance() { if (instance == null) { return fakeInstance; } else { return instance; } } public static void setCodeArea(JTextArea codeArea) { MainForm.codeArea = codeArea; } public static MethodResult getCurMethod() { return curMethod; } public static void setCurMethod(MethodResult curMethod) { MainForm.curMethod = curMethod; } public static JTextArea getCodeArea() { return codeArea; } public FileTree getFileTree() { return fileTree; } public JPanel getMasterPanel() { return masterPanel; } public JButton getChoseBtn() { return choseBtn; } public JButton getStartBuildDatabaseButton() { return startEngineButton; } public JTextField getFileText() { return fileText; } public JProgressBar getBuildBar() { return buildBar; } public JCheckBox getResolveJarsInJarCheckBox() { return resolveJarsInJarCheckBox; } public JLabel getTotalClassVal() { return totalClassVal; } public JLabel getTotalMethodVal() { return totalMethodVal; } public JLabel getTotalJarVal() { return totalJarVal; } public JLabel getDatabaseSizeVal() { return databaseSizeVal; } public static CoreEngine getEngine() { return engine; } public static void setEngine(CoreEngine engine) { MainForm.engine = engine; } public static ConfigFile getConfig() { return config; } public static void setConfig(ConfigFile config) { MainForm.config = config; } public JLabel getEngineVal() { return engineVal; } public JCheckBox getAutoSaveCheckBox() { return autoSaveCheckBox; } public JTextField getLoadDBText() { return loadDBText; } public JList<MethodResult> getAllMethodList() { return allMethodList; } public JTextField getCurClassText() { return curClassText; } public JTextField getCurJarText() { return curJarText; } public JTextField getCurMethodText() { return curMethodText; } public JTextField getSearchClassText() { return searchClassText; } public JButton getStartSearchButton() { return startSearchButton; } public JTextField getSearchMethodText() { return searchMethodText; } public JTextField getSearchStrText() { return searchStrText; } public JRadioButton getMethodDefinitionRadioButton() { return methodDefinitionRadioButton; } public JRadioButton getMethodCallRadioButton() { return methodCallRadioButton; } public JRadioButton getStringContainsRadioButton() { return stringContainsRadioButton; } public JRadioButton getBinarySearchRadioButton() { return binarySearchRadioButton; } public JList<MethodResult> getCallerList() { return callerList; } public JList<MethodResult> getMethodImplList() { return methodImplList; } public JList<MethodResult> getCalleeList() { return calleeList; } public JList<MethodResult> getSearchList() { return searchList; } public JTabbedPane getTabbedPanel() { return tabbedPanel; } public static DefaultListModel<MethodResult> getHistoryListData() { return historyListData; } public JList<MethodResult> getHistoryList() { return historyList; } public JTextField getRtText() { return rtText; } public JCheckBox getAutoFindRtJarCheckBox() { return autoFindRtJarCheckBox; } public JCheckBox getAddRtJarWhenCheckBox() { return addRtJarWhenCheckBox; } public JRadioButton getFernRadio() { return fernRadio; } public JButton getOpcodeBtn() { return opcodeBtn; } public JButton getJavaAsmBtn() { return javaAsmBtn; } public JButton getCfgBtn() { return cfgBtn; } public JButton getFrameBtn() { return frameBtn; } public JButton getSimpleFrameButton() { return simpleFrameButton; } public JCheckBox getDeleteTempCheckBox() { return deleteTempCheckBox; } public JList<MethodResult> getSuperImplList() { return superImplList; } public JButton getPrevBtn() { return prevBtn; } public JButton getNextBtn() { return nextBtn; } public JRadioButton getLikeSearchRadioButton() { return likeSearchRadioButton; } public JRadioButton getEqualsSearchRadioButton() { return equalsSearchRadioButton; } public JTextArea getBlackArea() { return blackArea; } public JTextArea getClassBlackArea() { return classBlackArea; } public JButton getRefreshButton() { return refreshButton; } public JButton getJNDIButton() { return JNDIButton; } public JButton getRuntimeExecButton() { return runtimeExecButton; } public JButton getProcessBuilderStartButton() { return processBuilderStartButton; } public JButton getSpELGetValueButton() { return spELGetValueButton; } public JButton getReadObjectButton() { return readObjectButton; } public JButton getOGNLGetValueButton() { return OGNLGetValueButton; } public JButton getBCELLoadClassButton() { return BCELLoadClassButton; } public JButton getDefineClassButton() { return defineClassButton; } public JButton getScriptEngineEvalButton() { return scriptEngineEvalButton; } public JButton getSqliteButton() { return sqliteButton; } public JButton getGptButton() { return gptButton; } public JButton getCleanButton() { return cleanButton; } public JButton getShowStringListButton() { return showStringListButton; } public JButton getFastjsonButton() { return fastjsonButton; } public JButton getUnzipButton() { return unzipButton; } public JButton getHessianButton() { return hessianButton; } private void resolveConfig() { if (config != null) { String temp = config.getTempPath(); String db = config.getDbPath(); if (temp == null || db == null) { return; } if (Files.exists(Paths.get(temp)) && Files.exists(Paths.get(db))) { databaseSizeVal.setText(config.getDbSize()); totalClassVal.setText(config.getTotalClass()); totalJarVal.setText(config.getTotalJar()); totalMethodVal.setText(config.getTotalMethod()); fileText.setText(config.getJarPath()); loadDBText.setText(config.getDbPath()); engine = new CoreEngine(config); engineVal.setText("RUNNING"); engineVal.setForeground(Color.GREEN); buildBar.setValue(100); } else { try { Files.delete(Paths.get(ConfigEngine.CONFIG_FILE_PATH)); } catch (Exception ignored) { } try { DirUtil.removeDir(new File(Const.tempDir)); } catch (Exception ignored) { } } } } public MainForm() { logger.info("init main form"); methodDefinitionRadioButton.setSelected(true); fernRadio.setSelected(true); fernRadio.setText(DecompileEngine.INFO); searchStrText.setEnabled(false); deleteTempCheckBox.setSelected(true); LogUtil.setT(logArea); SyntaxAreaHelper.buildJava(codePanel); engineVal.setText("CLOSED"); engineVal.setForeground(Color.RED); autoSaveCheckBox.setSelected(true); if (ConfigEngine.exist()) { config = ConfigEngine.parseConfig(); resolveConfig(); } fileTree.refresh(); allMethodList.setCellRenderer(new AllMethodsRender()); calleeList.setCellRenderer(new MethodCallRender()); callerList.setCellRenderer(new MethodCallRender()); searchList.setCellRenderer(new MethodCallRender()); methodImplList.setCellRenderer(new MethodCallRender()); superImplList.setCellRenderer(new MethodCallRender()); springCList.setCellRenderer(new ClassRender()); springMList.setCellRenderer(new SpringMethodRender()); historyList.setCellRenderer(new MethodCallRender()); historyListData = new DefaultListModel<>(); historyList.setModel(historyListData); prevBtn.setIcon(IconManager.prevIcon); nextBtn.setIcon(IconManager.nextIcon); logoLabel.setIcon(IconManager.showIcon); jreRuntimeLabel.setIcon(IconManager.javaIcon); dbPathLabel.setIcon(IconManager.dbIcon); startEngineButton.setIcon(IconManager.startIcon); curJarLabel.setIcon(IconManager.jarIcon); curClassLabel.setIcon(IconManager.curIcon); curMethodLabel.setIcon(IconManager.curIcon); authorLabel.setIcon(IconManager.auIcon); authorTextLabel.setIcon(IconManager.githubIcon); classBlackListLabel.setIcon(IconManager.whiteIcon); authorTextLabel.addMouseListener(new AuthorAdapter()); blackArea.setText(Const.blackAreaText); classBlackArea.setText(Const.classBlackAreaText); equalsSearchRadioButton.setSelected(true); logger.info("init main form success"); } private static void init() {
FontHelper.installFont();
6
2023-10-07 15:42:35+00:00
12k
egorolegovichyakovlev/DroidRec
app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java
[ { "identifier": "OnShakePreferenceChangeEvent", "path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/event/OnShakePreferenceChangeEvent.java", "snippet": "public class OnShakePreferenceChangeEvent {\n private String state;\n public OnShakePreferenceChangeEvent(String state) {\n this.s...
import static java.lang.Math.sqrt; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.yakovlevegor.DroidRec.shake.event.OnShakePreferenceChangeEvent; import com.yakovlevegor.DroidRec.ScreenRecorder; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe;
10,336
package com.yakovlevegor.DroidRec.shake; public class OnShakeEventHelper { private SensorEventListener currentListener; private boolean hasListenerChanged; private Context context;
package com.yakovlevegor.DroidRec.shake; public class OnShakeEventHelper { private SensorEventListener currentListener; private boolean hasListenerChanged; private Context context;
private ScreenRecorder.RecordingBinder recordingBinder;
1
2023-10-09 00:04:13+00:00
12k
lunasaw/gb28181-proxy
gb28181-server/src/main/java/io/github/lunasaw/gbproxy/server/transimit/cmd/ServerSendCmd.java
[ { "identifier": "CmdTypeEnum", "path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/CmdTypeEnum.java", "snippet": "public enum CmdTypeEnum {\n\n /**\n * 请求类型\n */\n DEVICE_INFO(\"DeviceInfo\", \"查询设备信息\"),\n DEVICE_STATUS(\"DeviceStatus\", \"查询设备状态\"),\n ...
import java.util.Date; import java.util.Optional; import javax.sip.address.SipURI; import org.springframework.util.Assert; import com.luna.common.date.DateUtils; import com.luna.common.text.RandomStrUtil; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.gb28181.common.entity.control.*; import io.github.lunasaw.gb28181.common.entity.enums.CmdTypeEnum; import io.github.lunasaw.gb28181.common.entity.notify.DeviceBroadcastNotify; import io.github.lunasaw.gb28181.common.entity.query.*; import io.github.lunasaw.gb28181.common.entity.utils.PtzCmdEnum; import io.github.lunasaw.gb28181.common.entity.utils.PtzUtils; import io.github.lunasaw.gbproxy.server.entity.InviteRequest; import io.github.lunasaw.gbproxy.server.enums.PlayActionEnums; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.gb28181.common.entity.enums.StreamModeEnum; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.transmit.SipSender;
9,530
return SipSender.doMessageRequest(fromDevice, toDevice, deviceControlPosition.toString()); } /** * 看守位控制命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param enable 看守位使能:1 = 开启,0 = 关闭 * @param resetTime 自动归位时间间隔,开启看守位时使用,单位:秒(s) * @param presetIndex 调用预置位编号,开启看守位时使用,取值范围0~255 * @return */ public static String deviceControlAlarm(FromDevice fromDevice, ToDevice toDevice, String enable, String resetTime, String presetIndex) { DeviceControlPosition.HomePosition homePosition = new DeviceControlPosition.HomePosition(enable, resetTime, presetIndex); return deviceControlAlarm(fromDevice, toDevice, homePosition); } /** * 设备配置命令:basicParam * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param name 设备/通道名称(可选) * @param expiration 注册过期时间(可选) * @param heartBeatInterval 心跳间隔时间(可选) * @param heartBeatCount 心跳超时次数(可选) * @return */ public static String deviceConfig(FromDevice fromDevice, ToDevice toDevice, String name, String expiration, String heartBeatInterval, String heartBeatCount) { DeviceConfigControl deviceConfigControl = new DeviceConfigControl(CmdTypeEnum.DEVICE_CONFIG.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceConfigControl.setBasicParam(new DeviceConfigControl.BasicParam(name, expiration, heartBeatInterval, heartBeatCount)); return SipSender.doMessageRequest(fromDevice, toDevice, deviceConfigControl.toString()); } /** * 下载设备配置 * * @param fromDevice * @param toDevice * @param configType 配置类型 * @return */ public static String deviceConfigDownload(FromDevice fromDevice, ToDevice toDevice, String configType) { DeviceConfigDownload deviceConfig = new DeviceConfigDownload(CmdTypeEnum.CONFIG_DOWNLOAD.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceConfig.setConfigType(configType); return SipSender.doMessageRequest(fromDevice, toDevice, deviceConfig.toString()); } /** * 强制关键帧命令,设备收到此命令应立刻发送一个IDR帧 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return */ public static String deviceControlIdr(FromDevice fromDevice, ToDevice toDevice, String cmdStr) { DeviceControlIFame deviceControlIFame = new DeviceControlIFame(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); String cmd = Optional.ofNullable(cmdStr).orElse("Send"); deviceControlIFame.setIFameCmd(cmd); return SipSender.doMessageRequest(fromDevice, toDevice, deviceControlIFame.toString()); } /** * 伸缩控制 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param dragZoom 缩小 * @return */ public static String deviceControlDragOut(FromDevice fromDevice, ToDevice toDevice, DragZoom dragZoom) { DeviceControlDragOut dragZoomOut = new DeviceControlDragOut(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); dragZoomOut.setDragZoomOut(dragZoom); return SipSender.doMessageRequest(fromDevice, toDevice, dragZoomOut.toString()); } /** * 伸缩控制 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param dragZoom 放大 * @return */ public static String deviceControlDragIn(FromDevice fromDevice, ToDevice toDevice, DragZoom dragZoom) { DeviceControlDragIn dragZoomIn = new DeviceControlDragIn(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); dragZoomIn.setDragZoomIn(dragZoom); return SipSender.doMessageRequest(fromDevice, toDevice, dragZoomIn.toString()); } /** * 云台控制命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param ptzCmdEnum 命令 * @param speed 速度 * @return */
package io.github.lunasaw.gbproxy.server.transimit.cmd; /** * @author luna * @date 2023/10/14 */ public class ServerSendCmd { /** * 设备信息查询 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String deviceInfo(FromDevice fromDevice, ToDevice toDevice) { DeviceQuery deviceQuery = new DeviceQuery(CmdTypeEnum.DEVICE_INFO.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceQuery.toString()); } /** * 设备预设位置查询 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String devicePresetQuery(FromDevice fromDevice, ToDevice toDevice) { DeviceQuery deviceQuery = new DeviceQuery(CmdTypeEnum.PRESET_QUERY.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceQuery.toString()); } /** * 查询移动设备位置数据 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String devicePresetQuery(FromDevice fromDevice, ToDevice toDevice, String interval) { DeviceMobileQuery deviceMobileQuery = new DeviceMobileQuery(CmdTypeEnum.MOBILE_POSITION.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); deviceMobileQuery.setInterval(interval); return SipSender.doMessageRequest(fromDevice, toDevice, deviceMobileQuery.toString()); } /** * 订阅移动设备位置数据 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String devicePresetSubscribe(FromDevice fromDevice, ToDevice toDevice, String interval, Integer expires, String eventType, String eventId) { DeviceMobileQuery deviceMobileQuery = new DeviceMobileQuery(CmdTypeEnum.MOBILE_POSITION.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); deviceMobileQuery.setInterval(interval); SubscribeInfo subscribeInfo = new SubscribeInfo(); subscribeInfo.setEventId(eventId); subscribeInfo.setEventType(eventType); subscribeInfo.setExpires(expires); return SipSender.doSubscribeRequest(fromDevice, toDevice, deviceMobileQuery.toString(), subscribeInfo); } /** * 设备状态查询 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String deviceStatusQuery(FromDevice fromDevice, ToDevice toDevice) { DeviceQuery deviceQuery = new DeviceQuery(CmdTypeEnum.DEVICE_STATUS.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceQuery.toString()); } /** * 设备通道列表查询 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String deviceCatalogQuery(FromDevice fromDevice, ToDevice toDevice) { DeviceQuery deviceQuery = new DeviceQuery(CmdTypeEnum.CATALOG.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceQuery.toString()); } public static String deviceRecordInfoQuery(FromDevice fromDevice, ToDevice toDevice, String startTime, String endTime) { return deviceRecordInfoQuery(fromDevice, toDevice, startTime, endTime, null, "all"); } public static String deviceRecordInfoQuery(FromDevice fromDevice, ToDevice toDevice, long startTime, long endTime) { return deviceRecordInfoQuery(fromDevice, toDevice, new Date(startTime), new Date(endTime)); } /** * 查询录像列表 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param startTime 开始时间 ISO8601格式 * @param endTime 结束时间 ISO8601格式 * @param secrecy 保密属性 缺省为0; 0:不涉密, 1:涉密 * @param type all(time 或 alarm 或 manual 或 all) * @return */ public static String deviceRecordInfoQuery(FromDevice fromDevice, ToDevice toDevice, String startTime, String endTime, String secrecy, String type) { DeviceRecordQuery recordQuery = new DeviceRecordQuery(CmdTypeEnum.RECORD_INFO.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); recordQuery.setStartTime(startTime); recordQuery.setEndTime(endTime); recordQuery.setSecrecy(secrecy); recordQuery.setType(type); return SipSender.doMessageRequest(fromDevice, toDevice, recordQuery.toString()); } public static String deviceRecordInfoQuery(FromDevice fromDevice, ToDevice toDevice, Date startTime, Date endTime) { return deviceRecordInfoQuery(fromDevice, toDevice, startTime, endTime, "0", "all"); } /** * 查询录像列表 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return callId */ public static String deviceRecordInfoQuery(FromDevice fromDevice, ToDevice toDevice, Date startTime, Date endTime, String secrecy, String type) { String startTimeStr = DateUtils.formatTime(DateUtils.ISO8601_PATTERN, startTime); String endTimeStr = DateUtils.formatTime(DateUtils.ISO8601_PATTERN, endTime); return deviceRecordInfoQuery(fromDevice, toDevice, startTimeStr, endTimeStr, secrecy, type); } public static String deviceCatalogSubscribe(FromDevice fromDevice, ToDevice toDevice, Integer expires, String eventType) { return deviceCatalogSubscribe(fromDevice, toDevice, expires, eventType, RandomStrUtil.generateNonceStr()); } /** * 会话订阅 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param expires 过期时间 * @param eventType 事件类型 * @return */ public static String deviceCatalogSubscribe(FromDevice fromDevice, ToDevice toDevice, Integer expires, String eventType, String eventId) { DeviceQuery recordQuery = new DeviceQuery(CmdTypeEnum.CATALOG.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); SubscribeInfo subscribeInfo = new SubscribeInfo(); subscribeInfo.setEventId(eventId); subscribeInfo.setEventType(eventType); subscribeInfo.setExpires(expires); return SipSender.doSubscribeRequest(fromDevice, toDevice, recordQuery.toString(), subscribeInfo); } /** * 告警查询 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param startPriority 报警起始级别(可选) * @param endPriority 报警终止级别(可选) * @param alarmMethod 报警方式条件(可选) * @param alarmType 报警类型 * @param startTime 报警发生起始时间(可选) * @param endTime 报警发生终止时间(可选) * @return callId */ public static String deviceAlarmQuery(FromDevice fromDevice, ToDevice toDevice, Date startTime, Date endTime, String startPriority, String endPriority, String alarmMethod, String alarmType) { DeviceAlarmQuery deviceAlarmQuery = new DeviceAlarmQuery(CmdTypeEnum.ALARM.getType(), RandomStrUtil.getValidationCode(), toDevice.getUserId()); deviceAlarmQuery.setStartTime(DateUtils.formatTime(DateUtils.ISO8601_PATTERN, startTime)); deviceAlarmQuery.setEndTime(DateUtils.formatTime(DateUtils.ISO8601_PATTERN, endTime)); deviceAlarmQuery.setStartAlarmPriority(startPriority); deviceAlarmQuery.setEndAlarmPriority(endPriority); deviceAlarmQuery.setAlarmType(alarmType); return SipSender.doMessageRequest(fromDevice, toDevice, deviceAlarmQuery.toString()); } /** * 回复ACK * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return */ public static String deviceAck(FromDevice fromDevice, ToDevice toDevice) { return SipSender.doAckRequest(fromDevice, toDevice); } public static String deviceAck(FromDevice fromDevice, ToDevice toDevice, String callId) { return SipSender.doAckRequest(fromDevice, toDevice, callId); } public static String deviceAck(FromDevice fromDevice, SipURI sipURI, SIPResponse sipResponse) { return SipSender.doAckRequest(fromDevice, sipURI, sipResponse); } /** * 发送BYE * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return */ public static String deviceBye(FromDevice fromDevice, ToDevice toDevice) { return SipSender.doByeRequest(fromDevice, toDevice); } /** * 设备广播 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return */ public static String deviceBroadcast(FromDevice fromDevice, ToDevice toDevice) { DeviceBroadcastNotify deviceBroadcastNotify = new DeviceBroadcastNotify(CmdTypeEnum.BROADCAST.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId(), toDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceBroadcastNotify.toString()); } /** * 报警布防/撤防命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param guardCmdStr "SetGuard"/"ResetGuard" * @return */ public static String deviceControlGuardCmd(FromDevice fromDevice, ToDevice toDevice, String guardCmdStr) { DeviceControlGuard deviceControl = new DeviceControlGuard(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceControl.setGuardCmd(guardCmdStr); return SipSender.doMessageRequest(fromDevice, toDevice, deviceControl.toString()); } /** * 报警复位命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param alarmMethod 方式 * @param alarmType 类型 * @return */ public static String deviceControlAlarm(FromDevice fromDevice, ToDevice toDevice, String alarmMethod, String alarmType) { DeviceControlAlarm deviceControlAlarm = new DeviceControlAlarm(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceControlAlarm.setAlarmCmd("ResetAlarm"); deviceControlAlarm.setAlarmInfo(new DeviceControlAlarm.AlarmInfo(alarmMethod, alarmType)); return SipSender.doMessageRequest(fromDevice, toDevice, deviceControlAlarm.toString()); } public static String deviceControlAlarm(FromDevice fromDevice, ToDevice toDevice, DeviceControlPosition.HomePosition homePosition) { DeviceControlPosition deviceControlPosition = new DeviceControlPosition(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); return SipSender.doMessageRequest(fromDevice, toDevice, deviceControlPosition.toString()); } /** * 看守位控制命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param enable 看守位使能:1 = 开启,0 = 关闭 * @param resetTime 自动归位时间间隔,开启看守位时使用,单位:秒(s) * @param presetIndex 调用预置位编号,开启看守位时使用,取值范围0~255 * @return */ public static String deviceControlAlarm(FromDevice fromDevice, ToDevice toDevice, String enable, String resetTime, String presetIndex) { DeviceControlPosition.HomePosition homePosition = new DeviceControlPosition.HomePosition(enable, resetTime, presetIndex); return deviceControlAlarm(fromDevice, toDevice, homePosition); } /** * 设备配置命令:basicParam * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param name 设备/通道名称(可选) * @param expiration 注册过期时间(可选) * @param heartBeatInterval 心跳间隔时间(可选) * @param heartBeatCount 心跳超时次数(可选) * @return */ public static String deviceConfig(FromDevice fromDevice, ToDevice toDevice, String name, String expiration, String heartBeatInterval, String heartBeatCount) { DeviceConfigControl deviceConfigControl = new DeviceConfigControl(CmdTypeEnum.DEVICE_CONFIG.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceConfigControl.setBasicParam(new DeviceConfigControl.BasicParam(name, expiration, heartBeatInterval, heartBeatCount)); return SipSender.doMessageRequest(fromDevice, toDevice, deviceConfigControl.toString()); } /** * 下载设备配置 * * @param fromDevice * @param toDevice * @param configType 配置类型 * @return */ public static String deviceConfigDownload(FromDevice fromDevice, ToDevice toDevice, String configType) { DeviceConfigDownload deviceConfig = new DeviceConfigDownload(CmdTypeEnum.CONFIG_DOWNLOAD.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); deviceConfig.setConfigType(configType); return SipSender.doMessageRequest(fromDevice, toDevice, deviceConfig.toString()); } /** * 强制关键帧命令,设备收到此命令应立刻发送一个IDR帧 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @return */ public static String deviceControlIdr(FromDevice fromDevice, ToDevice toDevice, String cmdStr) { DeviceControlIFame deviceControlIFame = new DeviceControlIFame(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); String cmd = Optional.ofNullable(cmdStr).orElse("Send"); deviceControlIFame.setIFameCmd(cmd); return SipSender.doMessageRequest(fromDevice, toDevice, deviceControlIFame.toString()); } /** * 伸缩控制 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param dragZoom 缩小 * @return */ public static String deviceControlDragOut(FromDevice fromDevice, ToDevice toDevice, DragZoom dragZoom) { DeviceControlDragOut dragZoomOut = new DeviceControlDragOut(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); dragZoomOut.setDragZoomOut(dragZoom); return SipSender.doMessageRequest(fromDevice, toDevice, dragZoomOut.toString()); } /** * 伸缩控制 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param dragZoom 放大 * @return */ public static String deviceControlDragIn(FromDevice fromDevice, ToDevice toDevice, DragZoom dragZoom) { DeviceControlDragIn dragZoomIn = new DeviceControlDragIn(CmdTypeEnum.DEVICE_CONTROL.getType(), RandomStrUtil.getValidationCode(), fromDevice.getUserId()); dragZoomIn.setDragZoomIn(dragZoom); return SipSender.doMessageRequest(fromDevice, toDevice, dragZoomIn.toString()); } /** * 云台控制命令 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param ptzCmdEnum 命令 * @param speed 速度 * @return */
public static String deviceControlPtzCmd(FromDevice fromDevice, ToDevice toDevice, PtzCmdEnum ptzCmdEnum, Integer speed) {
2
2023-10-11 06:56:28+00:00
12k
1415181920/yamis-admin
cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/controller/admin/view/AdminRolesViewController.java
[ { "identifier": "AdminBaseViewController", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/basic/controller/AdminBaseViewController.java", "snippet": "public class AdminBaseViewController implements AdminBaseViewInterface{\n\n protected HashMap<Object, Object> createButton(AdminBaseViewControl...
import io.xiaoyu.common.basic.controller.AdminBaseViewController; import io.xiaoyu.common.resp.CommonAdminResp; import io.xiaoyu.common.yaims.AmisFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap;
7,217
package io.xiaoyu.sys.modular.admin.controller.admin.view; /** * 视图层控制器 */ @RestController @RequestMapping("/admin-api/sys/admin/admin-roles")
package io.xiaoyu.sys.modular.admin.controller.admin.view; /** * 视图层控制器 */ @RestController @RequestMapping("/admin-api/sys/admin/admin-roles")
public class AdminRolesViewController extends AdminBaseViewController{
0
2023-10-09 06:04:30+00:00
12k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_load.java
[ { "identifier": "CorruptedWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/CorruptedWorldException.java", "snippet": "public class CorruptedWorldException extends SlimeException {\n\n public CorruptedWorldException(String world) {\n this(world, null)...
import net.swofty.swm.api.exceptions.CorruptedWorldException; import net.swofty.swm.api.exceptions.NewerFormatException; import net.swofty.swm.api.exceptions.UnknownWorldException; import net.swofty.swm.api.exceptions.WorldInUseException; 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.plugin.SWMPlugin; import net.swofty.swm.plugin.commands.CommandCooldown; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.log.Logging; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import java.util.List;
9,376
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Loads a world into SWM", inGameOnly = false, permission = "swm.loadworld") public class subCommand_load extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 0; } @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send("§cUsage: /swm load <world>"); return; } String worldName = args[0]; World world = Bukkit.getWorld(worldName); if (world != null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "World " + worldName + " is already loaded!"); return; } WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(worldName); if (worldData == null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to find world " + worldName + " inside the worlds config file."); return; } if (SWMCommand.getWorldsInUse().contains(worldName)) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "World " + worldName + " is already being used on another command! Wait some time and try again."); return; } SWMCommand.getWorldsInUse().add(worldName); sender.send(Logging.COMMAND_PREFIX + ChatColor.GRAY + "Loading world " + ChatColor.YELLOW + worldName + ChatColor.GRAY + "..."); // It's best to load the world async, and then just go back to the server thread and add it to the world list Bukkit.getScheduler().runTaskAsynchronously(SWMPlugin.getInstance(), () -> { try { long start = System.currentTimeMillis(); SlimeLoader loader = SWMPlugin.getInstance().getLoader(worldData.getDataSource()); if (loader == null) { throw new IllegalArgumentException("invalid data source " + worldData.getDataSource()); } SlimeWorld slimeWorld = SWMPlugin.getInstance().loadWorld(loader, worldName, worldData.isReadOnly(), worldData.toPropertyMap()); Bukkit.getScheduler().runTask(SWMPlugin.getInstance(), () -> { try { SWMPlugin.getInstance().generateWorld(slimeWorld); } catch (IllegalArgumentException ex) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to generate world " + worldName + ": " + ex.getMessage() + "."); return; } sender.send(Logging.COMMAND_PREFIX + ChatColor.GREEN + "World " + ChatColor.YELLOW + worldName + ChatColor.GREEN + " loaded and generated in " + (System.currentTimeMillis() - start) + "ms!"); }); } catch (CorruptedWorldException ex) { if (!(sender.getSender() instanceof ConsoleCommandSender)) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to load world " + worldName + ": world seems to be corrupted."); } Logging.error("Failed to load world " + worldName + ": world seems to be corrupted."); ex.printStackTrace();
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Loads a world into SWM", inGameOnly = false, permission = "swm.loadworld") public class subCommand_load extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 0; } @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send("§cUsage: /swm load <world>"); return; } String worldName = args[0]; World world = Bukkit.getWorld(worldName); if (world != null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "World " + worldName + " is already loaded!"); return; } WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(worldName); if (worldData == null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to find world " + worldName + " inside the worlds config file."); return; } if (SWMCommand.getWorldsInUse().contains(worldName)) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "World " + worldName + " is already being used on another command! Wait some time and try again."); return; } SWMCommand.getWorldsInUse().add(worldName); sender.send(Logging.COMMAND_PREFIX + ChatColor.GRAY + "Loading world " + ChatColor.YELLOW + worldName + ChatColor.GRAY + "..."); // It's best to load the world async, and then just go back to the server thread and add it to the world list Bukkit.getScheduler().runTaskAsynchronously(SWMPlugin.getInstance(), () -> { try { long start = System.currentTimeMillis(); SlimeLoader loader = SWMPlugin.getInstance().getLoader(worldData.getDataSource()); if (loader == null) { throw new IllegalArgumentException("invalid data source " + worldData.getDataSource()); } SlimeWorld slimeWorld = SWMPlugin.getInstance().loadWorld(loader, worldName, worldData.isReadOnly(), worldData.toPropertyMap()); Bukkit.getScheduler().runTask(SWMPlugin.getInstance(), () -> { try { SWMPlugin.getInstance().generateWorld(slimeWorld); } catch (IllegalArgumentException ex) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to generate world " + worldName + ": " + ex.getMessage() + "."); return; } sender.send(Logging.COMMAND_PREFIX + ChatColor.GREEN + "World " + ChatColor.YELLOW + worldName + ChatColor.GREEN + " loaded and generated in " + (System.currentTimeMillis() - start) + "ms!"); }); } catch (CorruptedWorldException ex) { if (!(sender.getSender() instanceof ConsoleCommandSender)) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Failed to load world " + worldName + ": world seems to be corrupted."); } Logging.error("Failed to load world " + worldName + ": world seems to be corrupted."); ex.printStackTrace();
} catch (NewerFormatException ex) {
1
2023-10-08 10:54:28+00:00
12k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/client/ui/copenheimer/search/SearchParametersScreen.java
[ { "identifier": "CopeMultiplayerScreen", "path": "src/main/java/fifthcolumn/n/client/ui/copenheimer/servers/CopeMultiplayerScreen.java", "snippet": "public class CopeMultiplayerScreen extends Screen {\n private static final int BUTTON_WIDTH_TOP = 80;\n private static final int BUTTON_WIDTH_BOTTOM = ...
import com.mojang.blaze3d.systems.RenderSystem; import fifthcolumn.n.client.ui.copenheimer.servers.CopeMultiplayerScreen; import fifthcolumn.n.copenheimer.CopeService; import java.util.Objects; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.Element; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.CheckboxWidget; import net.minecraft.client.gui.widget.ClickableWidget; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.render.BufferBuilder; import net.minecraft.client.render.GameRenderer; import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.VertexFormats; import net.minecraft.client.render.VertexFormat.DrawMode; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.apache.commons.lang3.StringUtils;
7,626
package fifthcolumn.n.client.ui.copenheimer.search; public class SearchParametersScreen extends Screen { public static final Identifier OPTIONS_BACKGROUND_TEXTURE = new Identifier("minecraft:textures/block/tnt_side.png"); private final CopeMultiplayerScreen parent; private TextFieldWidget serverNameWidget; private TextFieldWidget serverVersionWidget; private TextFieldWidget serverLangWidget; private CheckboxWidget onlineWidget; private CheckboxWidget crackedWidget;
package fifthcolumn.n.client.ui.copenheimer.search; public class SearchParametersScreen extends Screen { public static final Identifier OPTIONS_BACKGROUND_TEXTURE = new Identifier("minecraft:textures/block/tnt_side.png"); private final CopeMultiplayerScreen parent; private TextFieldWidget serverNameWidget; private TextFieldWidget serverVersionWidget; private TextFieldWidget serverLangWidget; private CheckboxWidget onlineWidget; private CheckboxWidget crackedWidget;
private final CopeService copeService;
1
2023-10-14 19:18:35+00:00
12k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/util/TestClassMerger.java
[ { "identifier": "Config", "path": "src/main/java/zju/cst/aces/api/config/Config.java", "snippet": "@Getter\n@Setter\npublic class Config {\n public String date;\n public Gson GSON;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public Li...
import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.expr.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import zju.cst.aces.api.config.Config; import zju.cst.aces.parser.ProjectParser; import zju.cst.aces.runner.AbstractRunner; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List;
10,771
package zju.cst.aces.util; /** * Merge all test classes with different methods in the same class. * @author <a href="mailto: sjiahui27@gmail.com">songjiahui</a> * @since 2023/7/10 16:47 **/ public class TestClassMerger { private String sourceFullClassName; private String sourceClassName; private String packageName; public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); private String targetClassName;
package zju.cst.aces.util; /** * Merge all test classes with different methods in the same class. * @author <a href="mailto: sjiahui27@gmail.com">songjiahui</a> * @since 2023/7/10 16:47 **/ public class TestClassMerger { private String sourceFullClassName; private String sourceClassName; private String packageName; public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); private String targetClassName;
public Config config;
0
2023-10-14 07:15:10+00:00
12k
jmdevall/opencodeplan
src/test/java/jmdevall/opencodeplan/application/CodePlanTest.java
[ { "identifier": "DependencyGraphConstructorJavaparser", "path": "src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/DependencyGraphConstructorJavaparser.java", "snippet": "public class DependencyGraphConstructorJavaparser implements DependencyGraphConstructor{\n\n\tprivate List<VoidVisitorAdapte...
import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.junit.jupiter.api.Test; import jmdevall.opencodeplan.adapter.out.javaparser.DependencyGraphConstructorJavaparser; import jmdevall.opencodeplan.adapter.out.javaparser.ParserJavaParser; import jmdevall.opencodeplan.adapter.out.llm.cache.LlmEngineCacheAdapter; import jmdevall.opencodeplan.adapter.out.llm.debug.LlmEngineDebugAdapter; import jmdevall.opencodeplan.adapter.out.llm.ooba.LlmEngineOoba; import jmdevall.opencodeplan.adapter.out.llm.openai.LlmEngineOpenai; import jmdevall.opencodeplan.adapter.out.oracle.OracleDefault; import jmdevall.opencodeplan.adapter.out.repository.FiltersFactory; import jmdevall.opencodeplan.adapter.out.repository.RepositoryMulpleFolders; import jmdevall.opencodeplan.application.port.out.llm.LlmEngine; import jmdevall.opencodeplan.application.port.out.oracle.Oracle; import jmdevall.opencodeplan.application.port.out.parser.DependencyGraphConstructor; import jmdevall.opencodeplan.application.port.out.parser.Parser; import jmdevall.opencodeplan.application.port.out.repository.Repository; import jmdevall.opencodeplan.application.port.out.repository.SourceFolder; import jmdevall.opencodeplan.domain.dependencygraph.LineColPos; import jmdevall.opencodeplan.domain.instruction.DeltaSeeds; import jmdevall.opencodeplan.domain.instruction.InstructuionNatural; import jmdevall.opencodeplan.domain.instruction.NodeSearchDescriptor; import jmdevall.opencodeplan.domain.instruction.Seed; import jmdevall.opencodeplan.domain.plangraph.NodeTypeTag; import jmdevall.opencodeplan.domain.promptmaker.InstructionTemplate; import jmdevall.opencodeplan.domain.promptmaker.PromptMaker; import jmdevall.opencodeplan.domain.promptmaker.PromptMakerDefault;
8,442
package jmdevall.opencodeplan.application; public class CodePlanTest { @Test public void testCodePlan() { //initialize default dependencies.... Parser parser=new ParserJavaParser(); PromptMakerDefault promptMaker=new PromptMakerDefault(InstructionTemplate.CHATML); DependencyGraphConstructor dgConstructor=DependencyGraphConstructorJavaparser.newDefault(); Oracle oracle=new OracleDefault(); Llm llm=newTestingLlm(); CodePlan sut =new CodePlan(parser, dgConstructor, promptMaker, oracle,llm); Repository r=RepositoryMulpleFolders.newFromSingleSourceRoot(new File("/home/vicuna/js/nemofinder/src/main/java")); DeltaSeeds deltaSeed=new DeltaSeeds(); Seed initialCommand=Seed.builder() .instruction(new InstructuionNatural("Convierte el HashMap<String, List<String>> en un HashMap que tenga como clave Integer en lugar de String")) .block(NodeSearchDescriptor.builder() .file("/nemofinder/HerigoneSpanish.java")
package jmdevall.opencodeplan.application; public class CodePlanTest { @Test public void testCodePlan() { //initialize default dependencies.... Parser parser=new ParserJavaParser(); PromptMakerDefault promptMaker=new PromptMakerDefault(InstructionTemplate.CHATML); DependencyGraphConstructor dgConstructor=DependencyGraphConstructorJavaparser.newDefault(); Oracle oracle=new OracleDefault(); Llm llm=newTestingLlm(); CodePlan sut =new CodePlan(parser, dgConstructor, promptMaker, oracle,llm); Repository r=RepositoryMulpleFolders.newFromSingleSourceRoot(new File("/home/vicuna/js/nemofinder/src/main/java")); DeltaSeeds deltaSeed=new DeltaSeeds(); Seed initialCommand=Seed.builder() .instruction(new InstructuionNatural("Convierte el HashMap<String, List<String>> en un HashMap que tenga como clave Integer en lugar de String")) .block(NodeSearchDescriptor.builder() .file("/nemofinder/HerigoneSpanish.java")
.nodeTypeTag(NodeTypeTag.BodyOfMethod)
20
2023-10-14 18:27:18+00:00
12k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java
[ { "identifier": "GeneratorContent", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/GeneratorContent.java", "snippet": "@Slf4j\n@Getter\n@Builder\npublic class GeneratorContent {\n\n private final String title;\n\n private final String desc;\n\n private final HttpMeth...
import com.github.eahau.openapi.douyin.generator.GeneratorContent; import com.github.eahau.openapi.douyin.generator.Misc; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenApiListApi.ApiListResponse; import com.github.eahau.openapi.douyin.generator.parser.HtmlParser; import com.github.eahau.openapi.douyin.generator.parser.JsonDocParser; import com.google.common.collect.Lists; import feign.Param; import feign.RequestLine; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.collections4.CollectionUtils; import java.util.Collections; import java.util.List;
10,581
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator.api; public interface DouYinOpenDocApi { @RequestLine("GET {path}?__loader=" + Misc.DOC_LANGUAGE + "/$") DocResponse docs(@Param("path") String path); @Getter @ToString @Setter class DocResponse { /** * content 类型,据观察 2=html. */ private int type; private String title; private String keywords; private String description; private String content; private boolean isShowUpdateTime; private String updateTime; private String arcositeId; public String path; public boolean isJson() { return type == 1; } public boolean isMarkdownHeadHtmlBody() { return type == 2; }
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator.api; public interface DouYinOpenDocApi { @RequestLine("GET {path}?__loader=" + Misc.DOC_LANGUAGE + "/$") DocResponse docs(@Param("path") String path); @Getter @ToString @Setter class DocResponse { /** * content 类型,据观察 2=html. */ private int type; private String title; private String keywords; private String description; private String content; private boolean isShowUpdateTime; private String updateTime; private String arcositeId; public String path; public boolean isJson() { return type == 1; } public boolean isMarkdownHeadHtmlBody() { return type == 2; }
public GeneratorContent toGeneratorContext() {
0
2023-10-07 09:09:15+00:00
12k
Aywen1/wispy
src/fr/nicolas/wispy/Panels/GamePanel.java
[ { "identifier": "Runner", "path": "src/fr/nicolas/wispy/Runner.java", "snippet": "public class Runner implements Runnable {\n\n\tprivate boolean isRunning = false;\n\tprivate GamePanel gamePanel;\n\tprivate int maxFps = 80;\n\tprivate long waitTime = 4;\n\n\tpublic Runner(GamePanel gamePanel) {\n\t\tthi...
import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import fr.nicolas.wispy.Runner; import fr.nicolas.wispy.Frames.MainFrame; import fr.nicolas.wispy.Panels.Components.Game.Player; import fr.nicolas.wispy.Panels.Components.Menu.EscapeMenu; import fr.nicolas.wispy.Panels.Components.Menu.WPanel; import fr.nicolas.wispy.Panels.Fonctions.MapManager; import fr.nicolas.wispy.Panels.Fonctions.MapManager.RefreshPaintMap;
7,555
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps setFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT)); } // Gestion blocs (textures) public enum BlockID { STONE, DIRT, GRASS, SAND; private BufferedImage img = null; public void setImg(BufferedImage img) { this.img = img; } public BufferedImage getImg() { return img; } } private void loadBlockImage(BlockID blockID) { try { blockID.setImg(ImageIO.read( getClass().getResource("Components/Game/res/blocks/" + blockID.toString().toLowerCase() + ".png"))); } catch (IOException e) { e.printStackTrace(); } } // Refresh / Paint methods public void refresh() { if (keyDPressed) { player.setWalking(true); player.setToRight(true); } if (keyQPressed) { player.setWalking(true); player.setToRight(false); } if (!keyQPressed && !keyDPressed) { player.setWalking(false); } if (keySpacePressed) { player.setJumping(true); keySpacePressed = false; } player.refresh(playerX, playerY, playerWidth, playerHeight); } public void paintComponent(Graphics g) { g.drawImage(sky, 0, 0, this.getWidth(), this.getHeight(), null); // Le paint des blocs intègre le test de collision avec le joueur
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps setFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT)); } // Gestion blocs (textures) public enum BlockID { STONE, DIRT, GRASS, SAND; private BufferedImage img = null; public void setImg(BufferedImage img) { this.img = img; } public BufferedImage getImg() { return img; } } private void loadBlockImage(BlockID blockID) { try { blockID.setImg(ImageIO.read( getClass().getResource("Components/Game/res/blocks/" + blockID.toString().toLowerCase() + ".png"))); } catch (IOException e) { e.printStackTrace(); } } // Refresh / Paint methods public void refresh() { if (keyDPressed) { player.setWalking(true); player.setToRight(true); } if (keyQPressed) { player.setWalking(true); player.setToRight(false); } if (!keyQPressed && !keyDPressed) { player.setWalking(false); } if (keySpacePressed) { player.setJumping(true); keySpacePressed = false; } player.refresh(playerX, playerY, playerWidth, playerHeight); } public void paintComponent(Graphics g) { g.drawImage(sky, 0, 0, this.getWidth(), this.getHeight(), null); // Le paint des blocs intègre le test de collision avec le joueur
mapManager.refreshPaintAllDisplayedBlocks(g, RefreshPaintMap.PAINT, this.getWidth(), this.getHeight(),
6
2023-10-13 13:10:56+00:00
12k
PfauMC/CyanWorld
cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/commands/CmdCyan1dex.java
[ { "identifier": "Config", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Config.java", "snippet": "public class Config {\n public static final boolean customtab_enable = Config.getBoolean(\"customtab.enable\");\n public static final String motd = Config.getString(\"fakebutitsrealo...
import com.google.common.collect.Maps; import org.bukkit.Sound; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import ru.cyanworld.cyan1dex.Config; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.CyanEcoManager; import ru.cyanworld.cyan1dex.Utils; import ru.cyanworld.cyan1dex.messages.Msg; import ru.cyanworld.cyan1dex.rcon.RconManager; import ru.cyanworld.cyan1dex.utils.ChatUtils; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.util.Collections; import java.util.List; import java.util.Map;
8,447
Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.playSound(players.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 2.14748365E9f, 1.0f); players.sendTitle("§b" + displayname, "Купил донат!", 10, 100, 10); } ); } catch (Exception ex) { ex.printStackTrace(); } break; } case "cmdall": { try { if (!Cyan1dex.server.getMotd().contains("main")) { return false; } if (sender instanceof Player) { sender.sendMessage(Msg.permdeny); return false; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < args.length; ++i) { stringBuilder.append(args[i]); stringBuilder.append(" "); } String COMMAND = stringBuilder.toString(); System.out.println("[Cyan1dex] Отправляем команду [" + COMMAND + "]..."); Cyan1dex.server.dispatchCommand(Cyan1dex.server.getConsoleSender(), COMMAND); this.rconRequest(35002, COMMAND); this.rconRequest(35003, COMMAND); } catch (Exception ex) { ex.printStackTrace(); } break; } case "viewdistance": { Player player = Cyan1dex.server.getPlayer(args[1]); int distance = Integer.parseInt(args[2]); sender.sendMessage("Установлена дальность прорисовки " + distance + " для игрока " + player.getName()); player.setViewDistance(distance); break; } case "forcechat": { String msg = Utils.readLongString(args, 2); switch (args[1]) { case "@a": { break block11; } case "@a[r=1000]": { Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.chat(msg); } ); break block11; } } Player player = Cyan1dex.server.getPlayer(args[1]); if (!player.isOnline()) { sender.sendMessage("Игрок не онлайн"); return true; } if (player.isOp()) { Player senderplayer = (Player) sender; senderplayer.sendTitle(" ", "Не балуйся", 0, 60, 10); return true; } player.chat(msg); break; } case "eco": { switch (args[1]) { case "add": { if (Config.isMainServer) { if (args[2].contains("-")) { int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(args[2], eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + args[2]); break block11; } String name = args[2].toLowerCase(); String uuid = Cyan1dex.cfguuid.getString(name); int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(uuid, eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + uuid); break block11; } Cyan1dex.mainRcon("cyan1dex eco add " + args[2] + " " + args[3]); } } break; } case "swear": { List swearlist = ChatUtils.swearCfg.getStringList("russian"); if (swearlist.contains(args[1].toLowerCase())) { sender.sendMessage("Это слово уже есть в библиотеке"); break; } swearlist.add(args[1].toLowerCase()); ChatUtils.swearCfg.set("russian", swearlist); Cyan1dex.saveCfg(ChatUtils.swearCfg, "swear.yml"); ChatUtils.loadLib(); sender.sendMessage("Это плохое слово успешно добавлено!"); break; } case "setdata": { String uuid = args[1]; String group = args[2]; int eco = Integer.parseInt(args[3]); Cyan1dex.cfgplayers.set(uuid + ".group", group); Cyan1dex.cfgplayers.set(uuid + ".eco", eco); System.out.println("[Cyan1dex] " + uuid + " группа: " + group + " монетки:" + eco); break; } } return false; } public boolean rconRequest(int port, String command) { String IP = "127.0.0.1"; byte[] PASS = "3CyanPetuh3".getBytes(); try {
package ru.cyanworld.cyan1dex.commands; public class CmdCyan1dex extends Command { public static Map<Integer, String> waitingCommand = Maps.newConcurrentMap(); public CmdCyan1dex() { super("cyan1dex", "Основная команда Cyan1dex", "/cyan1dex", Collections.singletonList("cyan")); Cyan1dex.server.getCommandMap().register(this.getName(), this); Cyan1dex.server.getScheduler().runTaskTimer(Cyan1dex.instance, () -> { if (waitingCommand.isEmpty()) { return; } waitingCommand.forEach((port, command) -> { boolean result = this.rconRequest(port, command); if (result) { waitingCommand.remove(port); } } ); } , 0, 200); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!sender.isOp()) { sender.sendMessage("Эта команда только для администраторов"); return true; } if (args.length == 0) { sender.sendMessage("/cyan1dex setgroup <ник> <группа>\n/cyan1dex cmdall Команда...\n/cyan1dex fakeerror\n/cyan1dex viewdistance <ник> <чанки>\n/cyan1dex eco add <ник> <количество>\n/cyan1dex forcechat <ник> Сообщение...\n/cyan1dex swear <плохое_слово>\n/cyan1dex setdata <UUID> <группа> <монетки>\n"); return true; } block11: switch (args[0]) { case "setgroup": { try { if (sender instanceof Player) { return false; } String uuid = args[1].contains("-") ? args[1] : Cyan1dex.cfguuid.getString(args[1].toLowerCase()); Cyan1dex.cfgplayers.set(uuid + ".group", args[2].toLowerCase()); if (args[2].equalsIgnoreCase("player")) { Cyan1dex.cfgplayers.set(uuid + ".group", null); } Cyan1dex.cfgplayers.save(new File(Cyan1dex.dataFolder, "players.yml")); Player player = Cyan1dex.server.getPlayer(args[1]); if (player != null) { Utils.setPlayerPrefix(player); } String displayname = args[1].contains("-") ? Cyan1dex.cfgplayers.getString(uuid + ".displayname") : args[1]; Cyan1dex.server.broadcastMessage("\n§b" + displayname + " Теперь донатер!\n§bПокупай донат на cyanworld.ru\n "); Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.playSound(players.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 2.14748365E9f, 1.0f); players.sendTitle("§b" + displayname, "Купил донат!", 10, 100, 10); } ); } catch (Exception ex) { ex.printStackTrace(); } break; } case "cmdall": { try { if (!Cyan1dex.server.getMotd().contains("main")) { return false; } if (sender instanceof Player) { sender.sendMessage(Msg.permdeny); return false; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < args.length; ++i) { stringBuilder.append(args[i]); stringBuilder.append(" "); } String COMMAND = stringBuilder.toString(); System.out.println("[Cyan1dex] Отправляем команду [" + COMMAND + "]..."); Cyan1dex.server.dispatchCommand(Cyan1dex.server.getConsoleSender(), COMMAND); this.rconRequest(35002, COMMAND); this.rconRequest(35003, COMMAND); } catch (Exception ex) { ex.printStackTrace(); } break; } case "viewdistance": { Player player = Cyan1dex.server.getPlayer(args[1]); int distance = Integer.parseInt(args[2]); sender.sendMessage("Установлена дальность прорисовки " + distance + " для игрока " + player.getName()); player.setViewDistance(distance); break; } case "forcechat": { String msg = Utils.readLongString(args, 2); switch (args[1]) { case "@a": { break block11; } case "@a[r=1000]": { Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.chat(msg); } ); break block11; } } Player player = Cyan1dex.server.getPlayer(args[1]); if (!player.isOnline()) { sender.sendMessage("Игрок не онлайн"); return true; } if (player.isOp()) { Player senderplayer = (Player) sender; senderplayer.sendTitle(" ", "Не балуйся", 0, 60, 10); return true; } player.chat(msg); break; } case "eco": { switch (args[1]) { case "add": { if (Config.isMainServer) { if (args[2].contains("-")) { int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(args[2], eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + args[2]); break block11; } String name = args[2].toLowerCase(); String uuid = Cyan1dex.cfguuid.getString(name); int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(uuid, eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + uuid); break block11; } Cyan1dex.mainRcon("cyan1dex eco add " + args[2] + " " + args[3]); } } break; } case "swear": { List swearlist = ChatUtils.swearCfg.getStringList("russian"); if (swearlist.contains(args[1].toLowerCase())) { sender.sendMessage("Это слово уже есть в библиотеке"); break; } swearlist.add(args[1].toLowerCase()); ChatUtils.swearCfg.set("russian", swearlist); Cyan1dex.saveCfg(ChatUtils.swearCfg, "swear.yml"); ChatUtils.loadLib(); sender.sendMessage("Это плохое слово успешно добавлено!"); break; } case "setdata": { String uuid = args[1]; String group = args[2]; int eco = Integer.parseInt(args[3]); Cyan1dex.cfgplayers.set(uuid + ".group", group); Cyan1dex.cfgplayers.set(uuid + ".eco", eco); System.out.println("[Cyan1dex] " + uuid + " группа: " + group + " монетки:" + eco); break; } } return false; } public boolean rconRequest(int port, String command) { String IP = "127.0.0.1"; byte[] PASS = "3CyanPetuh3".getBytes(); try {
RconManager rcon = new RconManager("127.0.0.1", port, PASS);
5
2023-10-08 17:50:55+00:00
12k
vaaako/Vakraft
src/main/java/com/magenta/main/Game.java
[ { "identifier": "Camera", "path": "src/main/java/com/magenta/engine/Camera.java", "snippet": "public class Camera {\n\tprivate final Window window;\n\t// private int width, height;\n\n\t// Camera movement vectors\n\tprivate Vector3f position = new Vector3f(0.0f, 0.0f, 0.0f);\n\tprivate Vector3f rotation...
import org.joml.Vector2f; import org.joml.Vector3f; import org.lwjgl.glfw.GLFW; import com.magenta.engine.Camera; import com.magenta.engine.HitRay; import com.magenta.engine.IGameLogic; import com.magenta.engine.KeyboardInput; import com.magenta.engine.Window; import com.magenta.game.World; import com.magenta.game.block.BlocksEnum; import com.magenta.engine.MouseInput;
8,275
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer; private Camera camera; private static MouseInput mouseInput; // World // private HitRay hitRay; private static World world; private final Vector3f cameraInc; // Movement private boolean movimentEnable = false, doubleSpeed = false; private static int holdingBlock = 1; public Game() { cameraInc = new Vector3f(); } @Override
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer; private Camera camera; private static MouseInput mouseInput; // World // private HitRay hitRay; private static World world; private final Vector3f cameraInc; // Movement private boolean movimentEnable = false, doubleSpeed = false; private static int holdingBlock = 1; public Game() { cameraInc = new Vector3f(); } @Override
public void init(Window window, MouseInput mouseInput) throws Exception {
4
2023-10-08 04:08:22+00:00
12k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/autoconfigure/DiscordPropertiesAutoConfig.java
[ { "identifier": "DiscordMjJavaException", "path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java", "snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n ...
import cn.hutool.core.util.StrUtil; import com.github.dmj.error.DiscordMjJavaException; import com.github.dmj.listener.MjMsgNotify; import com.github.dmj.service.DiscordService; import com.github.dmj.service.api.DiscordApi; import com.github.dmj.util.PropertyUtil; import org.jetbrains.annotations.NotNull; import org.springframework.beans.BeansException; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
9,241
package com.github.dmj.autoconfigure; /** * @author ljjy1 * @classname DiscordPropertiesAutoConfig * @description 配置读取装配类 * @date 2023/10/11 9:42 */ @ConditionalOnProperty(name = "discord.enable",havingValue = "true") public class DiscordPropertiesAutoConfig implements ApplicationContextAware , EnvironmentAware { public static ApplicationContext applicationContext; public static DiscordProperties discordProperties; @Override public void setEnvironment(Environment environment) { discordProperties = new DiscordProperties(); String prefix = "discord."; String proxyPrefix = "discord.proxy."; String userKeyList = environment.getProperty(prefix + "userKeyList"); discordProperties.setEnable(Boolean.TRUE); discordProperties.setUserKeyList(userKeyList); assert userKeyList != null; for (String userKey : userKeyList.split(",")) { DiscordAccountProperties discordAccountProperties = PropertyUtil.handle(environment, prefix + userKey, DiscordAccountProperties.class); //判断如果有属性为空 则报错 if(StrUtil.isBlank(discordAccountProperties.getUserKey())){ throw new DiscordMjJavaException("请填写账号key! [Please fill in the userKey]"); } if(StrUtil.isBlank(discordAccountProperties.getUserToken())){ if(StrUtil.hasBlank(discordAccountProperties.getUser(),discordAccountProperties.getPassword())){ throw new DiscordMjJavaException("请填写账号token,或者配置账号密码! [Enter the account token or set the user password ]"); } } if(StrUtil.isBlank(discordAccountProperties.getBotToken())){ throw new DiscordMjJavaException("请填写机器人token! [Please fill in the botToken]"); } if(StrUtil.isBlank(discordAccountProperties.getGuildId())){ throw new DiscordMjJavaException("请填写服务器ID! [Please fill in the guildId]"); } if(StrUtil.isBlank(discordAccountProperties.getChannelId())){ throw new DiscordMjJavaException("请填写频道ID! [Please fill in the channelId]"); } discordProperties.getAccount().put(userKey,discordAccountProperties); } /** * 是否开启代理参数 */ String enableProxyVar = environment.getProperty(proxyPrefix + "enable"); if (StrUtil.isNotBlank(enableProxyVar)) { boolean enableProxy = Boolean.parseBoolean(enableProxyVar); DiscordProxyProperties discordProxyProperties = new DiscordProxyProperties(); if(enableProxy){ discordProxyProperties.setEnable(Boolean.TRUE); String proxyAddress = environment.getProperty(proxyPrefix + "address"); if (StrUtil.isBlank(proxyAddress)) { throw new DiscordMjJavaException("开启了代理,请填写代理IP [if the proxy is enabled, enter the proxy ip address]"); } discordProxyProperties.setAddress(proxyAddress); String proxyPortVar = environment.getProperty(proxyPrefix + "port"); if (StrUtil.isBlank(proxyPortVar)) { throw new DiscordMjJavaException("开启了代理,请填写代理端口 [if the proxy is enabled, enter the proxy port]"); } int proxyPort = Integer.parseInt(proxyPortVar); discordProxyProperties.setPort(proxyPort); } discordProperties.setProxy(discordProxyProperties); } } @Bean("discordService")
package com.github.dmj.autoconfigure; /** * @author ljjy1 * @classname DiscordPropertiesAutoConfig * @description 配置读取装配类 * @date 2023/10/11 9:42 */ @ConditionalOnProperty(name = "discord.enable",havingValue = "true") public class DiscordPropertiesAutoConfig implements ApplicationContextAware , EnvironmentAware { public static ApplicationContext applicationContext; public static DiscordProperties discordProperties; @Override public void setEnvironment(Environment environment) { discordProperties = new DiscordProperties(); String prefix = "discord."; String proxyPrefix = "discord.proxy."; String userKeyList = environment.getProperty(prefix + "userKeyList"); discordProperties.setEnable(Boolean.TRUE); discordProperties.setUserKeyList(userKeyList); assert userKeyList != null; for (String userKey : userKeyList.split(",")) { DiscordAccountProperties discordAccountProperties = PropertyUtil.handle(environment, prefix + userKey, DiscordAccountProperties.class); //判断如果有属性为空 则报错 if(StrUtil.isBlank(discordAccountProperties.getUserKey())){ throw new DiscordMjJavaException("请填写账号key! [Please fill in the userKey]"); } if(StrUtil.isBlank(discordAccountProperties.getUserToken())){ if(StrUtil.hasBlank(discordAccountProperties.getUser(),discordAccountProperties.getPassword())){ throw new DiscordMjJavaException("请填写账号token,或者配置账号密码! [Enter the account token or set the user password ]"); } } if(StrUtil.isBlank(discordAccountProperties.getBotToken())){ throw new DiscordMjJavaException("请填写机器人token! [Please fill in the botToken]"); } if(StrUtil.isBlank(discordAccountProperties.getGuildId())){ throw new DiscordMjJavaException("请填写服务器ID! [Please fill in the guildId]"); } if(StrUtil.isBlank(discordAccountProperties.getChannelId())){ throw new DiscordMjJavaException("请填写频道ID! [Please fill in the channelId]"); } discordProperties.getAccount().put(userKey,discordAccountProperties); } /** * 是否开启代理参数 */ String enableProxyVar = environment.getProperty(proxyPrefix + "enable"); if (StrUtil.isNotBlank(enableProxyVar)) { boolean enableProxy = Boolean.parseBoolean(enableProxyVar); DiscordProxyProperties discordProxyProperties = new DiscordProxyProperties(); if(enableProxy){ discordProxyProperties.setEnable(Boolean.TRUE); String proxyAddress = environment.getProperty(proxyPrefix + "address"); if (StrUtil.isBlank(proxyAddress)) { throw new DiscordMjJavaException("开启了代理,请填写代理IP [if the proxy is enabled, enter the proxy ip address]"); } discordProxyProperties.setAddress(proxyAddress); String proxyPortVar = environment.getProperty(proxyPrefix + "port"); if (StrUtil.isBlank(proxyPortVar)) { throw new DiscordMjJavaException("开启了代理,请填写代理端口 [if the proxy is enabled, enter the proxy port]"); } int proxyPort = Integer.parseInt(proxyPortVar); discordProxyProperties.setPort(proxyPort); } discordProperties.setProxy(discordProxyProperties); } } @Bean("discordService")
public DiscordService discordService() {
2
2023-10-11 01:12:39+00:00
12k
weizen-w/Educational-Management-System-BE
src/main/java/de/ait/ems/controllers/GroupsController.java
[ { "identifier": "GroupsApi", "path": "src/main/java/de/ait/ems/controllers/api/GroupsApi.java", "snippet": "@RequestMapping(\"/api/groups\")\n@Tags(value = {\n @Tag(name = \"Groups\", description = \"This controller realized management of usersgroups\")\n})\n@Validated\npublic interface GroupsApi {\n...
import de.ait.ems.controllers.api.GroupsApi; import de.ait.ems.dto.GroupDto; import de.ait.ems.dto.LessonDto; import de.ait.ems.dto.MaterialDto; import de.ait.ems.dto.NewGroupDto; import de.ait.ems.dto.NewLessonDto; import de.ait.ems.dto.UpdateGroupDto; import de.ait.ems.dto.UserDto; import de.ait.ems.security.details.AuthenticatedUser; import de.ait.ems.services.GroupsService; import de.ait.ems.services.LessonService; import de.ait.ems.services.MaterialsService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.RestController;
7,413
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi {
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi {
private final GroupsService groupsService;
9
2023-10-07 16:00:02+00:00
12k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/objects/ObjectManager.java
[ { "identifier": "levels", "path": "src/Level/levels.java", "snippet": "public class levels {\n\n\tprivate BufferedImage img;\n\tprivate int[][] lvlData;\n\tprivate int lvlTilesWide;\n\tprivate int maxTilesOffset;\n\tprivate int maxLvlOffsetX;\n\tprivate Point playerSpawn;\n\n\tprivate ArrayList<Carnivor...
import java.awt.Graphics; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import Level.levels; import entities.Player; import gamestates.Playing; import main.Game; import utilz.LoadSave; import static utilz.Constants.ObjectConstants.*; import static utilz.HelpMethods.CanCannonSeePlayer; import static utilz.HelpMethods.IsProjectileHittingLevel; import static utilz.Constants.Projectiles.*;
9,853
package objects; public class ObjectManager { private Playing playing; private BufferedImage[][] potionImgs, containerImgs; private BufferedImage spikeImg, cannonBallImg; private BufferedImage[] cannonImgs; private ArrayList<Potion> potions; private ArrayList<GameContainer> containers; private ArrayList<Spike> spikes; private ArrayList<Cannon> cannons; private ArrayList<Projectile> projectiles = new ArrayList<>(); public ObjectManager(Playing playing) { this.playing = playing; loadImgs(); } public void checkSpikesTouched(Player p) { for (Spike s : spikes) if (s.getHitbox().intersects(p.getHitbox())) p.kill(); } public void checkObjectTouched(Rectangle2D.Float hitbox) { for (Potion p : potions) if (p.isActive()) { if (hitbox.intersects(p.getHitbox())) { p.setActive(false); applyEffectToPlayer(p); } } } public void applyEffectToPlayer(Potion p) { if (p.getObjType() == RED_POTION) playing.getPlayer().changeHealth(RED_POTION_VALUE); else playing.getPlayer().changePower(BLUE_POTION_VALUE); } public void checkObjectHit(Rectangle2D.Float attackbox) { for (GameContainer gc : containers) if (gc.isActive()&& !gc.doAnimation) { if (gc.getHitbox().intersects(attackbox)) { gc.setAnimation(true); int type = 0; if (gc.getObjType() == BARREL) type = 1; potions.add(new Potion((int) (gc.getHitbox().x + gc.getHitbox().width / 2), (int) (gc.getHitbox().y - gc.getHitbox().height / 2), type)); return; } } } public void loadObjects(levels newLevel) { potions = new ArrayList<>(newLevel.getPotions()); containers = new ArrayList<>(newLevel.getContainers()); spikes = newLevel.getSpikes(); cannons = newLevel.getCannons(); projectiles.clear(); } private void loadImgs() { BufferedImage potionSprite = LoadSave.GetSpriteAtlas(LoadSave.POTION); potionImgs = new BufferedImage[2][7]; for (int j = 0; j < potionImgs.length; j++) for (int i = 0; i < potionImgs[j].length; i++) potionImgs[j][i] = potionSprite.getSubimage(12 * i, 16 * j, 12, 16); BufferedImage containerSprite = LoadSave.GetSpriteAtlas(LoadSave.CONTAINER); containerImgs = new BufferedImage[2][8]; for (int j = 0; j < containerImgs.length; j++) for (int i = 0; i < containerImgs[j].length; i++) containerImgs[j][i] = containerSprite.getSubimage(40 * i, 30 * j, 40, 30); spikeImg = LoadSave.GetSpriteAtlas(LoadSave.TRAP); cannonImgs = new BufferedImage[7]; BufferedImage temp = LoadSave.GetSpriteAtlas(LoadSave.CANNON_ATLAS); for (int i = 0; i < cannonImgs.length; i++) cannonImgs[i] = temp.getSubimage(i * 40, 0, 40, 26); cannonBallImg = LoadSave.GetSpriteAtlas(LoadSave.CANNON_BALL); } public void update(int[][] lvlData, Player player) { for (Potion p : potions) if (p.isActive()) p.update(); for (GameContainer gc : containers) if (gc.isActive()) gc.update(); updateCannons(lvlData, player); updateProjectiles(lvlData, player); } private void updateProjectiles(int[][] lvlData, Player player) { for (Projectile p : projectiles) if (p.isActive()) { p.updatePos(); if (p.getHitbox().intersects(player.getHitbox())) { player.changeHealth(-25); p.setActive(false); } else if (IsProjectileHittingLevel(p, lvlData)) p.setActive(false); } } private boolean isPlayerInRange(Cannon c, Player player) { int absValue = (int) Math.abs(player.getHitbox().x - c.getHitbox().x);
package objects; public class ObjectManager { private Playing playing; private BufferedImage[][] potionImgs, containerImgs; private BufferedImage spikeImg, cannonBallImg; private BufferedImage[] cannonImgs; private ArrayList<Potion> potions; private ArrayList<GameContainer> containers; private ArrayList<Spike> spikes; private ArrayList<Cannon> cannons; private ArrayList<Projectile> projectiles = new ArrayList<>(); public ObjectManager(Playing playing) { this.playing = playing; loadImgs(); } public void checkSpikesTouched(Player p) { for (Spike s : spikes) if (s.getHitbox().intersects(p.getHitbox())) p.kill(); } public void checkObjectTouched(Rectangle2D.Float hitbox) { for (Potion p : potions) if (p.isActive()) { if (hitbox.intersects(p.getHitbox())) { p.setActive(false); applyEffectToPlayer(p); } } } public void applyEffectToPlayer(Potion p) { if (p.getObjType() == RED_POTION) playing.getPlayer().changeHealth(RED_POTION_VALUE); else playing.getPlayer().changePower(BLUE_POTION_VALUE); } public void checkObjectHit(Rectangle2D.Float attackbox) { for (GameContainer gc : containers) if (gc.isActive()&& !gc.doAnimation) { if (gc.getHitbox().intersects(attackbox)) { gc.setAnimation(true); int type = 0; if (gc.getObjType() == BARREL) type = 1; potions.add(new Potion((int) (gc.getHitbox().x + gc.getHitbox().width / 2), (int) (gc.getHitbox().y - gc.getHitbox().height / 2), type)); return; } } } public void loadObjects(levels newLevel) { potions = new ArrayList<>(newLevel.getPotions()); containers = new ArrayList<>(newLevel.getContainers()); spikes = newLevel.getSpikes(); cannons = newLevel.getCannons(); projectiles.clear(); } private void loadImgs() { BufferedImage potionSprite = LoadSave.GetSpriteAtlas(LoadSave.POTION); potionImgs = new BufferedImage[2][7]; for (int j = 0; j < potionImgs.length; j++) for (int i = 0; i < potionImgs[j].length; i++) potionImgs[j][i] = potionSprite.getSubimage(12 * i, 16 * j, 12, 16); BufferedImage containerSprite = LoadSave.GetSpriteAtlas(LoadSave.CONTAINER); containerImgs = new BufferedImage[2][8]; for (int j = 0; j < containerImgs.length; j++) for (int i = 0; i < containerImgs[j].length; i++) containerImgs[j][i] = containerSprite.getSubimage(40 * i, 30 * j, 40, 30); spikeImg = LoadSave.GetSpriteAtlas(LoadSave.TRAP); cannonImgs = new BufferedImage[7]; BufferedImage temp = LoadSave.GetSpriteAtlas(LoadSave.CANNON_ATLAS); for (int i = 0; i < cannonImgs.length; i++) cannonImgs[i] = temp.getSubimage(i * 40, 0, 40, 26); cannonBallImg = LoadSave.GetSpriteAtlas(LoadSave.CANNON_BALL); } public void update(int[][] lvlData, Player player) { for (Potion p : potions) if (p.isActive()) p.update(); for (GameContainer gc : containers) if (gc.isActive()) gc.update(); updateCannons(lvlData, player); updateProjectiles(lvlData, player); } private void updateProjectiles(int[][] lvlData, Player player) { for (Projectile p : projectiles) if (p.isActive()) { p.updatePos(); if (p.getHitbox().intersects(player.getHitbox())) { player.changeHealth(-25); p.setActive(false); } else if (IsProjectileHittingLevel(p, lvlData)) p.setActive(false); } } private boolean isPlayerInRange(Cannon c, Player player) { int absValue = (int) Math.abs(player.getHitbox().x - c.getHitbox().x);
return absValue <= Game.TILES_SIZE * 5;
3
2023-10-07 12:07:45+00:00
12k
yc-huang/bsdb
src/main/java/tech/bsdb/tools/ParquetBuilder.java
[ { "identifier": "SyncReader", "path": "src/main/java/tech/bsdb/read/SyncReader.java", "snippet": "public class SyncReader extends Reader {\n private KVReader kvReader;\n private final IndexReader idxReader;\n Logger logger = LoggerFactory.getLogger(SyncReader.class);\n\n public SyncReader(Fi...
import it.unimi.dsi.fastutil.io.BinIO; import tech.bsdb.read.SyncReader; import tech.bsdb.serde.Field; import tech.bsdb.serde.ParquetSer; import tech.bsdb.util.Common; import tech.bsdb.write.BSDBWriter; import com.google.common.base.Strings; import org.apache.commons.cli.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong;
9,649
int sampleCount = Integer.parseInt(cmd.getOptionValue("sc", DEFAULT_SAMPLE_COUNT)); int dictSize = Integer.parseInt(cmd.getOptionValue("ds", DEFAULT_DICT_SIZE)) * 1024 * 1024; long passCacheSize = Long.parseLong(cmd.getOptionValue("ps", DEFAULT_PASS_CACHE_SIZE)) * 1024 * 1024; int compressBlockSize = Integer.parseInt(cmd.getOptionValue("bs", "" + Common.DEFAULT_COMPRESS_BLOCK_SIZE)); AtomicLong readCount = new AtomicLong(); AtomicLong writeCount = new AtomicLong(); long start = System.currentTimeMillis(); BSDBWriter rdbWriter = new BSDBWriter(outPath, tempDirFile, checksumBits, passCacheSize, compact, compress, compressBlockSize, dictSize, approximateMode); Path inPath = new Path(inputFile); Configuration config = new Configuration(); String nameNodeUrl = cmd.getOptionValue("nn"); if (!Strings.isNullOrEmpty(nameNodeUrl)) config.set("fs.defaultFS", nameNodeUrl); FileSystem fs = FileSystem.get(config); FileStatus status = fs.getFileStatus(inPath); if (status == null) { System.err.println("input file not exist:" + inputFile); System.exit(1); } List<FileStatus> files = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus sub : fs.listStatus(inPath)) { if (!sub.isDirectory() && sub.getPath().getName().endsWith(".parquet")) { files.add(sub); } } } else { files.add(status); } if (files.isEmpty()) { System.err.println("no valid input file found."); System.exit(1); } ; ParquetSer parquetReader = new ParquetSer(); //save parquet file schema Field[] schema = parquetReader.getSchema(files.get(0), keyFieldName); BinIO.storeObject(schema, new File(outPath, Common.FILE_NAME_VALUE_SCHEMA)); int sampledFiles = Math.min(8, files.size()); //no need to sample too much files sampleCount /= sampledFiles; //sample some records to get statistics information of input KV for (int i = 0; i < sampledFiles; i++) { FileStatus file = files.get(i); long start0 = System.currentTimeMillis(); try { long count = parquetReader.readWithLimit(file, keyFieldName, (key, value) -> { if (key.length > Common.MAX_KEY_SIZE | value.length > Common.MAX_VALUE_SIZE) { logger.warn("record too large, dropped"); return; } rdbWriter.sample(key, value); }, sampleCount); if (!quietMode) { logger.info("sampling {} rows of src file {} cost: {}", count, file, (System.currentTimeMillis() - start0)); } } catch (Throwable e) { logger.error("error when sampling", e); throw new RuntimeException(e); } } rdbWriter.onSampleFinished(); //build database KV file Common.runParallel(Integer.parseInt(System.getProperty("bsdb.build.threads", "8")), (pool, futures) -> { for (FileStatus file : files) { futures.add(pool.submit(() -> { long start0 = System.currentTimeMillis(); try { long count = parquetReader.read(file, keyFieldName, (key, value) -> { readCount.getAndIncrement(); try { if (key.length > Common.MAX_KEY_SIZE | value.length > Common.MAX_VALUE_SIZE) { logger.warn("record too large, dropped"); return; } rdbWriter.put(key, value); writeCount.getAndIncrement(); } catch (Throwable e) { logger.error("error when insert records", e); throw new RuntimeException("error when inserting record.", e); } }); if (!quietMode) { logger.info("read {} rows from src file {} cost: {}", count, file, (System.currentTimeMillis() - start0)); } } catch (Throwable e) { logger.error("error when insert records", e); throw new RuntimeException(e); } })); } }, true); //build database index rdbWriter.build(); if (!quietMode) { logger.info("build cost:{}", (System.currentTimeMillis() - start)); logger.info("read: {}, write: {}", readCount.get(), writeCount.get()); } if (verify) { //integrity verify if (!quietMode) { logger.info("Verifying data integrity..."); } start = System.currentTimeMillis();
package tech.bsdb.tools; public class ParquetBuilder { private static final String STORED_ENCODING = "UTF-8"; private static final String DEFAULT_CHECKSUM_BITS = "4"; private static final String DEFAULT_PASS_CACHE_SIZE = "1024";//1GB private static final String DEFAULT_SAMPLE_COUNT = "10000"; private static final String DEFAULT_DICT_SIZE = "1"; static Logger logger = LoggerFactory.getLogger(ParquetBuilder.class); public static void main(String[] args) throws Exception { CommandLine cmd = parseArgs(args); boolean quietMode = cmd.hasOption("q"); boolean verify = cmd.hasOption("v"); boolean compact = cmd.hasOption("c"); boolean compress = cmd.hasOption("z"); boolean approximateMode = cmd.hasOption("a"); String inputFile = cmd.getOptionValue("i"); String keyFieldName = cmd.getOptionValue("kf", null); if (Objects.isNull(inputFile)) { logger.error("must specify input file."); System.exit(1); } if (Objects.isNull(keyFieldName)) { logger.error("must specify parquet field name for database key."); System.exit(1); } String out = cmd.getOptionValue("o", "./rdb/"); File outPath = new File(out); if (outPath.exists()) { if (outPath.isFile()) { logger.error("output directory exist but not as directory: {}", out); System.exit(1); } } else { outPath.mkdirs(); } String tempDir = cmd.getOptionValue("temp", null); File tempDirFile = Strings.isNullOrEmpty(tempDir) ? null : new File(tempDir); if (tempDirFile != null) { if (tempDirFile.exists()) { if (tempDirFile.isFile()) { logger.error("temp directory exist but not as directory: {}", tempDir); System.exit(1); } } else { tempDirFile.mkdirs(); } } String checksumBitsString = cmd.getOptionValue("cb", DEFAULT_CHECKSUM_BITS); int checksumBits = Integer.parseInt(checksumBitsString); int sampleCount = Integer.parseInt(cmd.getOptionValue("sc", DEFAULT_SAMPLE_COUNT)); int dictSize = Integer.parseInt(cmd.getOptionValue("ds", DEFAULT_DICT_SIZE)) * 1024 * 1024; long passCacheSize = Long.parseLong(cmd.getOptionValue("ps", DEFAULT_PASS_CACHE_SIZE)) * 1024 * 1024; int compressBlockSize = Integer.parseInt(cmd.getOptionValue("bs", "" + Common.DEFAULT_COMPRESS_BLOCK_SIZE)); AtomicLong readCount = new AtomicLong(); AtomicLong writeCount = new AtomicLong(); long start = System.currentTimeMillis(); BSDBWriter rdbWriter = new BSDBWriter(outPath, tempDirFile, checksumBits, passCacheSize, compact, compress, compressBlockSize, dictSize, approximateMode); Path inPath = new Path(inputFile); Configuration config = new Configuration(); String nameNodeUrl = cmd.getOptionValue("nn"); if (!Strings.isNullOrEmpty(nameNodeUrl)) config.set("fs.defaultFS", nameNodeUrl); FileSystem fs = FileSystem.get(config); FileStatus status = fs.getFileStatus(inPath); if (status == null) { System.err.println("input file not exist:" + inputFile); System.exit(1); } List<FileStatus> files = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus sub : fs.listStatus(inPath)) { if (!sub.isDirectory() && sub.getPath().getName().endsWith(".parquet")) { files.add(sub); } } } else { files.add(status); } if (files.isEmpty()) { System.err.println("no valid input file found."); System.exit(1); } ; ParquetSer parquetReader = new ParquetSer(); //save parquet file schema Field[] schema = parquetReader.getSchema(files.get(0), keyFieldName); BinIO.storeObject(schema, new File(outPath, Common.FILE_NAME_VALUE_SCHEMA)); int sampledFiles = Math.min(8, files.size()); //no need to sample too much files sampleCount /= sampledFiles; //sample some records to get statistics information of input KV for (int i = 0; i < sampledFiles; i++) { FileStatus file = files.get(i); long start0 = System.currentTimeMillis(); try { long count = parquetReader.readWithLimit(file, keyFieldName, (key, value) -> { if (key.length > Common.MAX_KEY_SIZE | value.length > Common.MAX_VALUE_SIZE) { logger.warn("record too large, dropped"); return; } rdbWriter.sample(key, value); }, sampleCount); if (!quietMode) { logger.info("sampling {} rows of src file {} cost: {}", count, file, (System.currentTimeMillis() - start0)); } } catch (Throwable e) { logger.error("error when sampling", e); throw new RuntimeException(e); } } rdbWriter.onSampleFinished(); //build database KV file Common.runParallel(Integer.parseInt(System.getProperty("bsdb.build.threads", "8")), (pool, futures) -> { for (FileStatus file : files) { futures.add(pool.submit(() -> { long start0 = System.currentTimeMillis(); try { long count = parquetReader.read(file, keyFieldName, (key, value) -> { readCount.getAndIncrement(); try { if (key.length > Common.MAX_KEY_SIZE | value.length > Common.MAX_VALUE_SIZE) { logger.warn("record too large, dropped"); return; } rdbWriter.put(key, value); writeCount.getAndIncrement(); } catch (Throwable e) { logger.error("error when insert records", e); throw new RuntimeException("error when inserting record.", e); } }); if (!quietMode) { logger.info("read {} rows from src file {} cost: {}", count, file, (System.currentTimeMillis() - start0)); } } catch (Throwable e) { logger.error("error when insert records", e); throw new RuntimeException(e); } })); } }, true); //build database index rdbWriter.build(); if (!quietMode) { logger.info("build cost:{}", (System.currentTimeMillis() - start)); logger.info("read: {}, write: {}", readCount.get(), writeCount.get()); } if (verify) { //integrity verify if (!quietMode) { logger.info("Verifying data integrity..."); } start = System.currentTimeMillis();
SyncReader rdbReader = new SyncReader(outPath, false, false, false, false);
0
2023-10-07 03:32:27+00:00
12k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/controller/UserController.java
[ { "identifier": "BaseController", "path": "src/main/java/io/github/reinershir/boot/common/BaseController.java", "snippet": "@Slf4j\npublic class BaseController {\n\t\n\n\t@InitBinder \n\tpublic void initBinder(WebDataBinder binder){\n\t\t//解除spring mvc list参数限制长度问题\n binder.setAutoGrowCollectionL...
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.util.CollectionUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.github.reinershir.auth.annotation.OptionType; import io.github.reinershir.auth.annotation.Permission; import io.github.reinershir.auth.annotation.PermissionMapping; import io.github.reinershir.auth.core.model.Menu; import io.github.reinershir.auth.core.model.Role; import io.github.reinershir.auth.core.support.AuthorizeManager; import io.github.reinershir.auth.entity.TokenInfo; import io.github.reinershir.boot.common.BaseController; import io.github.reinershir.boot.common.Result; import io.github.reinershir.boot.common.ValidateGroups; import io.github.reinershir.boot.contract.ShirBootContracts; import io.github.reinershir.boot.core.international.IMessager; import io.github.reinershir.boot.core.query.QueryHelper; import io.github.reinershir.boot.dto.req.LoginDTO; import io.github.reinershir.boot.dto.req.ResetPasswordDTO; import io.github.reinershir.boot.dto.req.UpdatePasswordDTO; import io.github.reinershir.boot.dto.req.UserReqDTO; import io.github.reinershir.boot.dto.res.LoginRespDTO; import io.github.reinershir.boot.dto.res.UserInfoDTO; import io.github.reinershir.boot.model.User; import io.github.reinershir.boot.service.impl.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest;
7,621
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login")
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login")
public Result<LoginRespDTO> login(@Validated @RequestBody LoginDTO loginDTO) throws Exception{
10
2023-10-10 13:06:54+00:00
12k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/MiscInfoLabel.java
[ { "identifier": "PlayerBuild", "path": "src/main/java/net/wiseoldman/beans/PlayerBuild.java", "snippet": "@AllArgsConstructor\npublic enum PlayerBuild\n{\n @SerializedName(\"1def\")\n ONE_DEF_PURE(\"1 Def Pure\"),\n\n @SerializedName(\"lvl3\")\n LEVEL_3(\"Level 3\"),\n\n @SerializedName(\...
import net.wiseoldman.beans.PlayerBuild; import net.wiseoldman.ui.CountryIcon; import net.wiseoldman.util.Format; import net.wiseoldman.util.Utils; import net.wiseoldman.beans.PlayerInfo; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import javax.swing.*; import javax.swing.border.EmptyBorder;
7,781
package net.wiseoldman.panel; public class MiscInfoLabel extends JLabel { MiscInfo info; public MiscInfoLabel(MiscInfo info) { this.info = info; setFont(FontManager.getRunescapeSmallFont()); setBorder(new EmptyBorder(5, 10, 5, 5)); setText(info.getDefaultText()); setToolTipText(info.getHoverText()); if (info != MiscInfo.LAST_UPDATED) { setBackground(ColorScheme.DARKER_GRAY_COLOR); setOpaque(true); setIcon(info.getIcon()); } else { setHorizontalAlignment(JLabel.CENTER); } } public void format(PlayerInfo result, boolean relative) { switch (info) { case COUNTRY: String country = result.getCountry(); String countryText = country == null ? "--" : country; String countryCode = country == null ? "default" : country.toLowerCase(); setIcon(CountryIcon.loadSquareImage(countryCode)); setText(countryText); break; case BUILD: PlayerBuild build = result.getBuild(); String buildText = build == null ? PlayerBuild.MAIN.toString() : build.toString(); setText(buildText);
package net.wiseoldman.panel; public class MiscInfoLabel extends JLabel { MiscInfo info; public MiscInfoLabel(MiscInfo info) { this.info = info; setFont(FontManager.getRunescapeSmallFont()); setBorder(new EmptyBorder(5, 10, 5, 5)); setText(info.getDefaultText()); setToolTipText(info.getHoverText()); if (info != MiscInfo.LAST_UPDATED) { setBackground(ColorScheme.DARKER_GRAY_COLOR); setOpaque(true); setIcon(info.getIcon()); } else { setHorizontalAlignment(JLabel.CENTER); } } public void format(PlayerInfo result, boolean relative) { switch (info) { case COUNTRY: String country = result.getCountry(); String countryText = country == null ? "--" : country; String countryCode = country == null ? "default" : country.toLowerCase(); setIcon(CountryIcon.loadSquareImage(countryCode)); setText(countryText); break; case BUILD: PlayerBuild build = result.getBuild(); String buildText = build == null ? PlayerBuild.MAIN.toString() : build.toString(); setText(buildText);
setIcon(Utils.getIcon(result.getType()));
3
2023-10-09 14:23:06+00:00
12k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/level/tile/FallingTile.java
[ { "identifier": "Level", "path": "src/main/java/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tpublic int width;\n\tpublic int height;\n\tpublic int depth;\n\tpublic byte[] blocks;\n\tpublic String na...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.Liquid;
8,444
package com.mojang.minecraft.level.tile; public final class FallingTile extends Tile { public FallingTile(int var1, int var2) { super(var1, var2); }
package com.mojang.minecraft.level.tile; public final class FallingTile extends Tile { public FallingTile(int var1, int var2) { super(var1, var2); }
public final void onBlockAdded(Level var1, int var2, int var3, int var4) {
0
2023-10-10 17:10:45+00:00
12k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/parser/reader/ParserFileReader.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 org.apache.log4j.Logger; import com.monitor.agent.server.FileState; import com.monitor.agent.server.LogFormat; import com.monitor.agent.server.filter.Filter; import com.monitor.parser.PMParser; import com.monitor.parser.TJParser; import com.monitor.parser.LogParser; import com.monitor.parser.ParserParameters; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
7,442
package com.monitor.parser.reader; /* * Copyright 2021 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 ParserFileReader { private static final Logger logger = Logger.getLogger(ParserFileReader.class); protected int spoolSize = 0; private final ParserRecordsStorage records; private Map<File, Long> pointerMap; private int recordsCount; private final HashMap<LogFormat, LogParser> parsers; private final Filter filter; private final boolean draft; private final ParserParameters parserParameters; public ParserFileReader(int spoolSize, Filter filter, boolean draft, ParserParameters parserParameters, ParserRecordsStorage storage) { this.spoolSize = spoolSize; this.records = storage; this.parsers = new HashMap<>(2); this.filter = filter; this.draft = draft; this.parserParameters = parserParameters;
package com.monitor.parser.reader; /* * Copyright 2021 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 ParserFileReader { private static final Logger logger = Logger.getLogger(ParserFileReader.class); protected int spoolSize = 0; private final ParserRecordsStorage records; private Map<File, Long> pointerMap; private int recordsCount; private final HashMap<LogFormat, LogParser> parsers; private final Filter filter; private final boolean draft; private final ParserParameters parserParameters; public ParserFileReader(int spoolSize, Filter filter, boolean draft, ParserParameters parserParameters, ParserRecordsStorage storage) { this.spoolSize = spoolSize; this.records = storage; this.parsers = new HashMap<>(2); this.filter = filter; this.draft = draft; this.parserParameters = parserParameters;
LogParser parser = new TJParser();
4
2023-10-11 20:25:12+00:00
12k
giteecode/bookmanage2-public
nhXJH-common/src/main/java/com/nhXJH/common/utils/file/FileUploadUtils.java
[ { "identifier": "LibraryMSConfig", "path": "nhXJH-common/src/main/java/com/nhXJH/common/config/LibraryMSConfig.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"nhxjh\")\npublic class LibraryMSConfig {\n /** 项目名称 */\n private String name;\n\n /** 版本 */\n private String versi...
import java.io.File; import java.io.IOException; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; import com.nhXJH.common.config.LibraryMSConfig; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.exception.file.FileNameLengthLimitExceededException; import com.nhXJH.common.exception.file.FileSizeLimitExceededException; import com.nhXJH.common.exception.file.InvalidExtensionException; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.uuid.IdUtils;
8,612
package com.nhXJH.common.utils.file; /** * 文件上传工具类 * * @author nhXJH */ public class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 200 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 500; /** * 默认上传的地址 */ private static String defaultBaseDir = LibraryMSConfig.getProfile(); public static void setDefaultBaseDir(String defaultBaseDir) { FileUploadUtils.defaultBaseDir = defaultBaseDir; } public static String getDefaultBaseDir() { return defaultBaseDir; } /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */ public static final String upload(MultipartFile file) throws IOException { try { return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = file.getOriginalFilename().length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } assertAllowed(file, allowedExtension); String fileName = extractFilename(file); File desc = getAbsoluteFile(baseDir, fileName); file.transferTo(desc); String pathFileName = getPathFileName(baseDir, fileName); return pathFileName; } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { String fileName = file.getOriginalFilename(); String extension = getExtension(file); fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; return fileName; } public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc; } public static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = LibraryMSConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
package com.nhXJH.common.utils.file; /** * 文件上传工具类 * * @author nhXJH */ public class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 200 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 500; /** * 默认上传的地址 */ private static String defaultBaseDir = LibraryMSConfig.getProfile(); public static void setDefaultBaseDir(String defaultBaseDir) { FileUploadUtils.defaultBaseDir = defaultBaseDir; } public static String getDefaultBaseDir() { return defaultBaseDir; } /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */ public static final String upload(MultipartFile file) throws IOException { try { return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = file.getOriginalFilename().length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } assertAllowed(file, allowedExtension); String fileName = extractFilename(file); File desc = getAbsoluteFile(baseDir, fileName); file.transferTo(desc); String pathFileName = getPathFileName(baseDir, fileName); return pathFileName; } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { String fileName = file.getOriginalFilename(); String extension = getExtension(file); fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; return fileName; } public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc; } public static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = LibraryMSConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
1
2023-10-13 07:19:20+00:00
12k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/variant/exterior/classic/ClassicBoxVariant.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.tardis.animation.ExteriorAnimation; import mdteam.ait.tardis.animation.PulsatingAnimation; import mdteam.ait.core.blockentities.ExteriorBlockEntity; import mdteam.ait.registry.DoorRegistry; import mdteam.ait.tardis.exterior.ClassicExterior; import mdteam.ait.tardis.variant.door.ClassicDoorVariant; import mdteam.ait.tardis.variant.door.DoorSchema; import mdteam.ait.tardis.variant.exterior.ExteriorVariantSchema; import net.minecraft.util.Identifier; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d;
7,654
package mdteam.ait.tardis.variant.exterior.classic; // a useful class for creating tardim variants as they all have the same filepath you know public abstract class ClassicBoxVariant extends ExteriorVariantSchema { private final String name; protected static final String TEXTURE_PATH = "textures/blockentities/exteriors/classic/classic_"; protected ClassicBoxVariant(String name, String modId) { // idk why i added the modid bit i dont use it later lol super(ClassicExterior.REFERENCE, new Identifier(modId, "exterior/classic/" + name)); this.name = name; } protected ClassicBoxVariant(String name) { this(name, AITMod.MOD_ID); } @Override public ExteriorAnimation animation(ExteriorBlockEntity exterior) { return new PulsatingAnimation(exterior); } @Override public DoorSchema door() {
package mdteam.ait.tardis.variant.exterior.classic; // a useful class for creating tardim variants as they all have the same filepath you know public abstract class ClassicBoxVariant extends ExteriorVariantSchema { private final String name; protected static final String TEXTURE_PATH = "textures/blockentities/exteriors/classic/classic_"; protected ClassicBoxVariant(String name, String modId) { // idk why i added the modid bit i dont use it later lol super(ClassicExterior.REFERENCE, new Identifier(modId, "exterior/classic/" + name)); this.name = name; } protected ClassicBoxVariant(String name) { this(name, AITMod.MOD_ID); } @Override public ExteriorAnimation animation(ExteriorBlockEntity exterior) { return new PulsatingAnimation(exterior); } @Override public DoorSchema door() {
return DoorRegistry.REGISTRY.get(ClassicDoorVariant.REFERENCE);
4
2023-10-08 00:38:53+00:00
12k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/common/CommonController.java
[ { "identifier": "LibraryMSConfig", "path": "nhXJH-common/src/main/java/com/nhXJH/common/config/LibraryMSConfig.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"nhxjh\")\npublic class LibraryMSConfig {\n /** 项目名称 */\n private String name;\n\n /** 版本 */\n private String versi...
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.nhXJH.common.config.LibraryMSConfig; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.file.FileUploadUtils; import com.nhXJH.common.utils.file.FileUtils; import com.nhXJH.framework.config.ServerConfig;
10,394
package com.nhXJH.web.controller.common; /** * 通用请求处理 * * @author nhXJH */ @RestController public class CommonController { private static final Logger log = LoggerFactory.getLogger(CommonController.class); @Autowired private ServerConfig serverConfig; /** * 通用下载请求 * * @param fileName 文件名称 * @param delete 是否删除 */ @GetMapping("/common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) { try {
package com.nhXJH.web.controller.common; /** * 通用请求处理 * * @author nhXJH */ @RestController public class CommonController { private static final Logger log = LoggerFactory.getLogger(CommonController.class); @Autowired private ServerConfig serverConfig; /** * 通用下载请求 * * @param fileName 文件名称 * @param delete 是否删除 */ @GetMapping("/common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) { try {
if (!FileUtils.checkAllowDownload(fileName)) {
5
2023-10-14 04:57:42+00:00
12k
aleksandarsusnjar/paniql
print/src/main/java/net/susnjar/paniql/print/InvoicePrinter.java
[ { "identifier": "ElementModel", "path": "core/src/main/java/net/susnjar/paniql/models/ElementModel.java", "snippet": "public abstract class ElementModel<D extends DirectivesContainer<D>> {\n public static final double LOG_BASE_0_95 = Math.log(0.95d);\n public static final double LOG_BASE_1_9 = Mat...
import net.susnjar.paniql.models.ElementModel; import net.susnjar.paniql.pricing.Bounds; import net.susnjar.paniql.pricing.Invoice; import net.susnjar.paniql.pricing.Price; import net.susnjar.paniql.pricing.WorkType; import java.io.PrintStream; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.function.Function;
7,862
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() { lineWidth = nameWidth + 1 + 3 + WorkType.values().length * columnWidth; doubleHorizontalRule = "=".repeat(lineWidth); singleHorizontalRule = "-".repeat(lineWidth); } public void println(final Invoice invoice) { println(invoice, System.out); } public void println(final Invoice invoice, final PrintStream out) { Price total = Price.FREE; nameWidth = Math.max( nameWidth, 1 + invoice.getResourceCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); nameWidth = Math.max( nameWidth, 1 + invoice.getPartCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); nameWidth = Math.max( nameWidth, 1 + invoice.getFieldCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); recalculate(); total = total.plus(println(out, "Resource", invoice.getResourceCosts())); out.println(); total = total.plus(println(out, "Part", invoice.getPartCosts())); out.println(); total = total.plus(println(out, "Field", invoice.getFieldCosts())); out.println(); out.println(doubleHorizontalRule); printTableHeader(out, "Grand Total".toUpperCase(Locale.ROOT)); printRow(out, "", total, true); out.println(); out.println("LEGEND:"); final int headingWidth = WorkType.getMaxHeadingLength() + 2; for (final WorkType workType: WorkType.values()) { out.println(" - " + pad(workType.getHeading() + ":", headingWidth) + workType.getDescription()); } out.println(" - " + pad("Min:", headingWidth) + "Minimum quantity in normal conditions."); out.println(" - " + pad("Avg:", headingWidth) + "Average quantity in normal conditions."); out.println(" - " + pad("95%:", headingWidth) + "95% percentile, >= 95% of expected values."); out.println(" - " + pad("Max:", headingWidth) + "Maximum, accounting for built-in constraints."); }
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() { lineWidth = nameWidth + 1 + 3 + WorkType.values().length * columnWidth; doubleHorizontalRule = "=".repeat(lineWidth); singleHorizontalRule = "-".repeat(lineWidth); } public void println(final Invoice invoice) { println(invoice, System.out); } public void println(final Invoice invoice, final PrintStream out) { Price total = Price.FREE; nameWidth = Math.max( nameWidth, 1 + invoice.getResourceCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); nameWidth = Math.max( nameWidth, 1 + invoice.getPartCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); nameWidth = Math.max( nameWidth, 1 + invoice.getFieldCosts().keySet().stream().map(t -> t.getFullyQualifiedName().length()).max(Integer::compareTo).orElse(0) ); recalculate(); total = total.plus(println(out, "Resource", invoice.getResourceCosts())); out.println(); total = total.plus(println(out, "Part", invoice.getPartCosts())); out.println(); total = total.plus(println(out, "Field", invoice.getFieldCosts())); out.println(); out.println(doubleHorizontalRule); printTableHeader(out, "Grand Total".toUpperCase(Locale.ROOT)); printRow(out, "", total, true); out.println(); out.println("LEGEND:"); final int headingWidth = WorkType.getMaxHeadingLength() + 2; for (final WorkType workType: WorkType.values()) { out.println(" - " + pad(workType.getHeading() + ":", headingWidth) + workType.getDescription()); } out.println(" - " + pad("Min:", headingWidth) + "Minimum quantity in normal conditions."); out.println(" - " + pad("Avg:", headingWidth) + "Average quantity in normal conditions."); out.println(" - " + pad("95%:", headingWidth) + "95% percentile, >= 95% of expected values."); out.println(" - " + pad("Max:", headingWidth) + "Maximum, accounting for built-in constraints."); }
private <T extends ElementModel> Price println(final PrintStream out, final String title, final Map<T, Price> items) {
0
2023-10-10 01:58:56+00:00
12k
quan100/quan
quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/command/service/SitemapService.java
[ { "identifier": "SitemapAssembler", "path": "quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/command/convert/SitemapAssembler.java", "snippet": "@Mapper\npublic interface SitemapAssembler {\n SitemapAssembler INSTANCE = Mappers.getMapper(SitemapAssembler.class);\n\n String TAG = \":\...
import cn.javaquan.app.pm.bff.command.convert.SitemapAssembler; import cn.javaquan.app.common.module.article.ArticleDTO; import cn.javaquan.app.common.module.auth.convert.AuthAssembler; import cn.javaquan.app.common.module.system.UserPermissionDTO; import cn.javaquan.app.common.module.system.UserPermissionTreeDTO; import cn.javaquan.app.common.util.Validate; import cn.javaquan.common.base.constant.AppTypeEnum; import cn.javaquan.common.base.message.Result; import cn.javaquan.app.pm.bff.command.feign.ArticleSitemapFeign; import cn.javaquan.app.pm.bff.command.feign.PermissionFeign; import cn.javaquan.tools.sitemap.Sitemap; import cn.javaquan.tools.sitemap.SitemapUtil; import cn.javaquan.tools.sitemap.XmlUtil; import lombok.RequiredArgsConstructor; import org.dom4j.Document; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
9,125
package cn.javaquan.app.pm.bff.command.service; /** * @author wangquan */ @RequiredArgsConstructor @Service public class SitemapService { private final PermissionFeign permissionFeign; private final ArticleSitemapFeign articleSitemapFeign; private final static String ARTICLE_CONTENT_NAME = "article_content"; @Value("${quan.site.domain.url:}") private String siteDomainUrl; public Document refreshSitemap() { Sitemap sitemap = new Sitemap(); List<UserPermissionTreeDTO> filterDtos = new ArrayList<>(); // Open角色权限菜单路径 Result<List<UserPermissionTreeDTO>> permissionResult = permissionFeign.getUserPermission(AuthAssembler.INSTANCE.appType(AppTypeEnum.CLIENT_BFF.name())); List<Sitemap.Url> urls = SitemapAssembler.INSTANCE.toSitemapList(siteDomainUrl, permissionResult.getData(), filterDtos); // 文章路径 Map<String, UserPermissionTreeDTO> dtoMap = filterDtos.stream().collect(Collectors.toMap(UserPermissionDTO::getName, (p1) -> p1)); if (dtoMap.containsKey(ARTICLE_CONTENT_NAME)) { // 所有的文章路径 Result<List<ArticleDTO>> result = articleSitemapFeign.getSitemaps(); UserPermissionDTO dto = dtoMap.get(ARTICLE_CONTENT_NAME); String articlePath = dto.getPath();
package cn.javaquan.app.pm.bff.command.service; /** * @author wangquan */ @RequiredArgsConstructor @Service public class SitemapService { private final PermissionFeign permissionFeign; private final ArticleSitemapFeign articleSitemapFeign; private final static String ARTICLE_CONTENT_NAME = "article_content"; @Value("${quan.site.domain.url:}") private String siteDomainUrl; public Document refreshSitemap() { Sitemap sitemap = new Sitemap(); List<UserPermissionTreeDTO> filterDtos = new ArrayList<>(); // Open角色权限菜单路径 Result<List<UserPermissionTreeDTO>> permissionResult = permissionFeign.getUserPermission(AuthAssembler.INSTANCE.appType(AppTypeEnum.CLIENT_BFF.name())); List<Sitemap.Url> urls = SitemapAssembler.INSTANCE.toSitemapList(siteDomainUrl, permissionResult.getData(), filterDtos); // 文章路径 Map<String, UserPermissionTreeDTO> dtoMap = filterDtos.stream().collect(Collectors.toMap(UserPermissionDTO::getName, (p1) -> p1)); if (dtoMap.containsKey(ARTICLE_CONTENT_NAME)) { // 所有的文章路径 Result<List<ArticleDTO>> result = articleSitemapFeign.getSitemaps(); UserPermissionDTO dto = dtoMap.get(ARTICLE_CONTENT_NAME); String articlePath = dto.getPath();
if (Validate.isNotEmpty(result.getData())) {
5
2023-10-08 06:48:41+00:00
12k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java
[ { "identifier": "CommandManager", "path": "src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandManager.java", "snippet": "public interface CommandManager{\n /**\n * This is a interface to allow addons to register the subcommand into quickshop command manager.\n *\n * @param c...
import com.ghostchu.plugins.dodosrv.command.bukkit.CommandManager; import com.ghostchu.plugins.dodosrv.command.bukkit.SimpleCommandManager; import com.ghostchu.plugins.dodosrv.database.DatabaseManager; import com.ghostchu.plugins.dodosrv.dodo.DodoManager; import com.ghostchu.plugins.dodosrv.dodo.UserBindManager; import com.ghostchu.plugins.dodosrv.listener.bukkit.BukkitListener; import com.ghostchu.plugins.dodosrv.listener.dodo.DoDoListener; import com.ghostchu.plugins.dodosrv.text.TextManager; import com.ghostchu.plugins.dodosrv.util.JsonUtil; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.gson.JsonObject; import net.deechael.dodo.API; import net.deechael.dodo.api.Channel; import net.deechael.dodo.api.TextChannel; import net.deechael.dodo.content.Message; import net.deechael.dodo.content.TextMessage; import net.deechael.dodo.gate.Gateway; import net.deechael.dodo.impl.ChannelImpl; import net.deechael.dodo.impl.DodoBot; import net.deechael.dodo.network.Route; import net.deechael.dodo.types.MessageType; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.lang.reflect.Field; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit;
10,030
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot; private DatabaseManager databaseManager;
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot; private DatabaseManager databaseManager;
private UserBindManager userBindManager;
4
2023-10-11 16:16:54+00:00
12k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/controller/MapServerTilesetsRestController.java
[ { "identifier": "MapServerDataCenter", "path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java", "snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n ...
import io.github.qmjy.mapbox.MapServerDataCenter; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.MbtilesOfMerge; import io.github.qmjy.mapbox.model.MbtilesOfMergeProgress; import io.github.qmjy.mapbox.model.MetaData; import io.github.qmjy.mapbox.service.AsyncService; import io.github.qmjy.mapbox.util.ResponseMapUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*;
8,486
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return ResponseEntity.ok().body(ResponseMapUtil.ok(wrapMap(maps))); } catch (EmptyResultDataAccessException e) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } } } if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_TPK)) { MetaData tpkMetaData = mapServerDataCenter.getTpkMetaData(tileset); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.ok(tpkMetaData)); } StringBuilder sb = new StringBuilder(appConfig.getDataPath()); sb.append(File.separator).append("tilesets").append(File.separator).append(tileset).append(File.separator).append("metadata.json"); if (new File(sb.toString()).exists()) { try { String s = Files.readString(Path.of(sb.toString())); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.ok(s)); } catch (IOException e) { throw new RuntimeException(e); } } return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } private Map<String, Object> wrapMap(List<Map<String, Object>> maps) { Map<String, Object> result = new HashMap<>(); for (Map<String, Object> map : maps) { result.put(String.valueOf(map.get("name")), map.get("value")); } return result; } /** * 将多个mbtiles文件合并成一个mbtiles文件。 * 部分文件不存在则跳过,所有不存在或者目标文件已存在则合并失败。 * * @return 任务任务ID和进度。 */ @PostMapping(value = "/merge") @ResponseBody @Operation(summary = "合并多个Mbtiles文件", description = "将多个mbtiles文件合并成一个mbtiles文件。") @Parameter(name = "mergeInfo", description = "合并对象模型,多个文件用英文分号分割") @ApiResponse(responseCode = "200", description = "成功响应", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))) public ResponseEntity<Map<String, Object>> merge(@RequestBody MbtilesOfMerge mergeInfo) { List<String> sourceNamePaths = new ArrayList<>(); String basePath = appConfig.getDataPath() + File.separator + "tilesets" + File.separator; String[] split = mergeInfo.getSourceNames().split(";"); for (String fileName : split) { if (new File(basePath + fileName).exists() || fileName.toLowerCase(Locale.getDefault()).endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { sourceNamePaths.add(basePath + fileName); } } if (sourceNamePaths.isEmpty()) { Map<String, Object> ok = ResponseMapUtil.nok(ResponseMapUtil.STATUS_NOT_FOUND, "至少得存在一个合法的mbtiles文件,且文件已存在!"); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ok); } if (new File(basePath + mergeInfo.getTargetName()).exists()) { Map<String, Object> ok = ResponseMapUtil.nok(ResponseMapUtil.STATUS_RESOURCE_ALREADY_EXISTS, "目标资源已存在!"); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ok); } String taskId = asyncService.computeTaskId(sourceNamePaths);
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return ResponseEntity.ok().body(ResponseMapUtil.ok(wrapMap(maps))); } catch (EmptyResultDataAccessException e) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } } } if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_TPK)) { MetaData tpkMetaData = mapServerDataCenter.getTpkMetaData(tileset); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.ok(tpkMetaData)); } StringBuilder sb = new StringBuilder(appConfig.getDataPath()); sb.append(File.separator).append("tilesets").append(File.separator).append(tileset).append(File.separator).append("metadata.json"); if (new File(sb.toString()).exists()) { try { String s = Files.readString(Path.of(sb.toString())); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.ok(s)); } catch (IOException e) { throw new RuntimeException(e); } } return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } private Map<String, Object> wrapMap(List<Map<String, Object>> maps) { Map<String, Object> result = new HashMap<>(); for (Map<String, Object> map : maps) { result.put(String.valueOf(map.get("name")), map.get("value")); } return result; } /** * 将多个mbtiles文件合并成一个mbtiles文件。 * 部分文件不存在则跳过,所有不存在或者目标文件已存在则合并失败。 * * @return 任务任务ID和进度。 */ @PostMapping(value = "/merge") @ResponseBody @Operation(summary = "合并多个Mbtiles文件", description = "将多个mbtiles文件合并成一个mbtiles文件。") @Parameter(name = "mergeInfo", description = "合并对象模型,多个文件用英文分号分割") @ApiResponse(responseCode = "200", description = "成功响应", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))) public ResponseEntity<Map<String, Object>> merge(@RequestBody MbtilesOfMerge mergeInfo) { List<String> sourceNamePaths = new ArrayList<>(); String basePath = appConfig.getDataPath() + File.separator + "tilesets" + File.separator; String[] split = mergeInfo.getSourceNames().split(";"); for (String fileName : split) { if (new File(basePath + fileName).exists() || fileName.toLowerCase(Locale.getDefault()).endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { sourceNamePaths.add(basePath + fileName); } } if (sourceNamePaths.isEmpty()) { Map<String, Object> ok = ResponseMapUtil.nok(ResponseMapUtil.STATUS_NOT_FOUND, "至少得存在一个合法的mbtiles文件,且文件已存在!"); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ok); } if (new File(basePath + mergeInfo.getTargetName()).exists()) { Map<String, Object> ok = ResponseMapUtil.nok(ResponseMapUtil.STATUS_RESOURCE_ALREADY_EXISTS, "目标资源已存在!"); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ok); } String taskId = asyncService.computeTaskId(sourceNamePaths);
Optional<MbtilesOfMergeProgress> taskOpt = asyncService.getTask(taskId);
3
2023-10-09 03:18:52+00:00
12k
codegrits/CodeGRITS
src/main/java/api/RealtimeDataImpl.java
[ { "identifier": "EyeTracker", "path": "src/main/java/trackers/EyeTracker.java", "snippet": "public class EyeTracker implements Disposable {\n String dataOutputPath = \"\";\n /**\n * This variable indicates the sample frequency of the eye tracker.\n */\n double sampleFrequency;\n PsiD...
import com.intellij.openapi.project.Project; import trackers.EyeTracker; import trackers.IDETracker; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.function.Consumer;
9,485
package api; /** * This class provides the API for getting real-time data from the IDE and eye tracker. */ public class RealtimeDataImpl { // make it singleton private static RealtimeDataImpl realtimeData = new RealtimeDataImpl(); Socket socket; InputStream dataInputStream; private Consumer<String> ideTrackerDataHandler; private Consumer<String> eyeTrackerDataHandler; private static IDETracker ideTracker;
package api; /** * This class provides the API for getting real-time data from the IDE and eye tracker. */ public class RealtimeDataImpl { // make it singleton private static RealtimeDataImpl realtimeData = new RealtimeDataImpl(); Socket socket; InputStream dataInputStream; private Consumer<String> ideTrackerDataHandler; private Consumer<String> eyeTrackerDataHandler; private static IDETracker ideTracker;
private static EyeTracker eyeTracker;
0
2023-10-12 15:40:39+00:00
12k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/handlers/RenderGameOverlayHandler.java
[ { "identifier": "ZombiesUtilsConfig", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/config/ZombiesUtilsConfig.java", "snippet": "public class ZombiesUtilsConfig {\n public static Configuration config;\n private static Property slaToggle;\n private static Property slaShortener;...
import com.github.stachelbeere1248.zombiesutils.config.ZombiesUtilsConfig; import com.github.stachelbeere1248.zombiesutils.game.sla.SLA; import com.github.stachelbeere1248.zombiesutils.game.waves.Waves; import com.github.stachelbeere1248.zombiesutils.game.windows.Room; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.Scoreboard; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; import java.util.Objects;
9,290
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return;
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return;
Timer.getInstance().ifPresent(timer -> {
4
2023-10-11 01:30:28+00:00
12k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/monitor/job/util/AbstractQuartzJob.java
[ { "identifier": "Constants", "path": "src/main/java/com/ruoyi/common/constant/Constants.java", "snippet": "public class Constants\n{\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK = \"GBK\";\n\...
import java.util.Date; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.ScheduleConstants; import com.ruoyi.common.utils.ExceptionUtil; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.bean.BeanUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.project.monitor.job.domain.Job; import com.ruoyi.project.monitor.job.domain.JobLog; import com.ruoyi.project.monitor.job.service.IJobLogService;
10,264
package com.ruoyi.project.monitor.job.util; /** * 抽象quartz调用 * * @author ruoyi */ public abstract class AbstractQuartzJob implements org.quartz.Job { private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); /** * 线程本地变量 */ private static ThreadLocal<Date> threadLocal = new ThreadLocal<>(); @Override public void execute(JobExecutionContext context) throws JobExecutionException { Job job = new Job(); BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); try { before(context, job); if (job != null) { doExecute(context, job); } after(context, job, null); } catch (Exception e) { log.error("任务执行异常 - :", e); after(context, job, e); } } /** * 执行前 * * @param context 工作执行上下文对象 * @param sysJob 系统计划任务 */ protected void before(JobExecutionContext context, Job job) { threadLocal.set(new Date()); } /** * 执行后 * * @param context 工作执行上下文对象 * @param sysScheduleJob 系统计划任务 */ protected void after(JobExecutionContext context, Job job, Exception e) { Date startTime = threadLocal.get(); threadLocal.remove(); final JobLog jobLog = new JobLog(); jobLog.setJobName(job.getJobName()); jobLog.setJobGroup(job.getJobGroup()); jobLog.setInvokeTarget(job.getInvokeTarget()); jobLog.setStartTime(startTime); jobLog.setEndTime(new Date()); long runMs = jobLog.getEndTime().getTime() - jobLog.getStartTime().getTime(); jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); if (e != null) {
package com.ruoyi.project.monitor.job.util; /** * 抽象quartz调用 * * @author ruoyi */ public abstract class AbstractQuartzJob implements org.quartz.Job { private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); /** * 线程本地变量 */ private static ThreadLocal<Date> threadLocal = new ThreadLocal<>(); @Override public void execute(JobExecutionContext context) throws JobExecutionException { Job job = new Job(); BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); try { before(context, job); if (job != null) { doExecute(context, job); } after(context, job, null); } catch (Exception e) { log.error("任务执行异常 - :", e); after(context, job, e); } } /** * 执行前 * * @param context 工作执行上下文对象 * @param sysJob 系统计划任务 */ protected void before(JobExecutionContext context, Job job) { threadLocal.set(new Date()); } /** * 执行后 * * @param context 工作执行上下文对象 * @param sysScheduleJob 系统计划任务 */ protected void after(JobExecutionContext context, Job job, Exception e) { Date startTime = threadLocal.get(); threadLocal.remove(); final JobLog jobLog = new JobLog(); jobLog.setJobName(job.getJobName()); jobLog.setJobGroup(job.getJobGroup()); jobLog.setInvokeTarget(job.getInvokeTarget()); jobLog.setStartTime(startTime); jobLog.setEndTime(new Date()); long runMs = jobLog.getEndTime().getTime() - jobLog.getStartTime().getTime(); jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); if (e != null) {
jobLog.setStatus(Constants.FAIL);
0
2023-10-14 02:27:47+00:00
12k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/ui/clickgui/ModuleButton.java
[ { "identifier": "SCMain", "path": "src/main/java/net/shadowclient/main/SCMain.java", "snippet": "public class SCMain {\n\n public static final String ClientModId = \"shadowclient\";\n public static final String ClientName = \"ShadowClient\";\n public static final String ClientVersion = \"0.2.0\...
import net.minecraft.client.gui.DrawContext; import net.shadowclient.main.SCMain; import net.shadowclient.main.annotations.Hidden; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleManager; import net.shadowclient.main.setting.Setting; import net.shadowclient.main.setting.settings.BooleanSetting; import net.shadowclient.main.setting.settings.EnumSetting; import net.shadowclient.main.setting.settings.NumberSetting; import net.shadowclient.main.setting.settings.StringSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.SettingComponent; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.BoolSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.ModeSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.SliderSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.TextSetting; import org.lwjgl.glfw.GLFW; import java.util.ArrayList; import java.util.List;
8,916
package net.shadowclient.main.ui.clickgui; public class ModuleButton extends FrameChild { public final Module module; public final Frame parent; public int offset; public boolean extended; public final List<SettingComponent> components; public ModuleButton(String modulename, Frame parent, int offset) { this.module = ModuleManager.getModule(modulename); this.parent = parent; this.offset = offset; this.components = new ArrayList<>(); this.extended = false; int settingOffset = parent.height; for (Setting setting : module.getSettings()) { if (setting.getClass().isAnnotationPresent(Hidden.class)) { continue; } if (setting instanceof BooleanSetting) { components.add(new BoolSetting(setting, this, settingOffset)); } else if (setting instanceof EnumSetting<?>) { components.add(new ModeSetting(setting, this, settingOffset));
package net.shadowclient.main.ui.clickgui; public class ModuleButton extends FrameChild { public final Module module; public final Frame parent; public int offset; public boolean extended; public final List<SettingComponent> components; public ModuleButton(String modulename, Frame parent, int offset) { this.module = ModuleManager.getModule(modulename); this.parent = parent; this.offset = offset; this.components = new ArrayList<>(); this.extended = false; int settingOffset = parent.height; for (Setting setting : module.getSettings()) { if (setting.getClass().isAnnotationPresent(Hidden.class)) { continue; } if (setting instanceof BooleanSetting) { components.add(new BoolSetting(setting, this, settingOffset)); } else if (setting instanceof EnumSetting<?>) { components.add(new ModeSetting(setting, this, settingOffset));
} else if (setting instanceof NumberSetting) {
6
2023-10-07 06:55:12+00:00
12k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/client/gui/GuiVoiceChange.java
[ { "identifier": "MappetVoice", "path": "src/main/java/mrkto/mvoice/MappetVoice.java", "snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String ...
import mchorse.mclib.client.gui.framework.GuiBase; import mchorse.mclib.client.gui.framework.elements.GuiElement; import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement; import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement; import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel; import mchorse.mclib.client.gui.utils.keys.IKey; import mrkto.mvoice.MappetVoice; import mrkto.mvoice.client.ClientData; import mrkto.mvoice.client.audio.DefaultRecorder; import mrkto.mvoice.client.audio.DefaultSpeaker; import mrkto.mvoice.client.AudioUtils; import mrkto.mvoice.utils.PlayerUtils; import net.minecraft.client.Minecraft; import java.util.ArrayList; import java.util.List;
7,905
package mrkto.mvoice.client.gui; public class GuiVoiceChange extends GuiBase { public GuiStringListElement Speakerlist; public GuiStringListElement Microlist; public GuiButtonElement SpeakerButton; public GuiButtonElement MicroButton; public GuiVoiceChange() { super(); Minecraft mc = Minecraft.getMinecraft(); GuiElement lelement = new GuiElement(mc); GuiElement relement = new GuiElement(mc); lelement.flex().relative(this.viewport).xy(0.25F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); relement.flex().relative(this.viewport).xy(0.75F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); ArrayList<String> mlist = MappetVoice.AudioManager.getInput().getAudioDevices(); ArrayList<String> slist = MappetVoice.AudioManager.getOutput().getAudioDevices(); this.Speakerlist = new GuiStringListElement(mc, this::GuiSpeakerList); this.Speakerlist.background().setList(slist); this.Speakerlist.sort(); this.Speakerlist.flex().relative(this.viewport).x(0.5F, -10).y(0.5F).w(50).h(100).anchor(1F, 0.5F); this.Speakerlist.setVisible(false); this.Microlist = new GuiStringListElement(mc, this::GuiMicroList); this.Microlist.background().setList(mlist); this.Microlist.sort(); this.Microlist.flex().relative(this.viewport).x(0.5F, -10).y(0.5F).w(50).h(100).anchor(1F, 0.5F); this.Microlist.setVisible(false); this.MicroButton = new GuiButtonElement(mc, IKey.str(MappetVoice.AudioManager.getInput().getMixer()), this::GuiMicroButton); this.SpeakerButton = new GuiButtonElement(mc, IKey.str(MappetVoice.AudioManager.getOutput().getMixer()), this::GuiSpeakerButton); GuiLabel rguiLabel = new GuiLabel(mc, IKey.lang("mvoice.settings.speaker")); GuiLabel lguiLabel = new GuiLabel(mc, IKey.lang("mvoice.settings.micro")); rguiLabel.flex().h(10); lguiLabel.flex().h(10); lelement.add(lguiLabel); lelement.add(MicroButton); lelement.add(Microlist); relement.add(rguiLabel); relement.add(SpeakerButton); relement.add(Speakerlist); this.root.add(lelement); this.root.add(relement); } private void GuiMicroButton(GuiButtonElement guiButtonElement) { this.Microlist.setVisible(true); } private void GuiSpeakerButton(GuiButtonElement guiButtonElement) { this.Speakerlist.setVisible(true); } private void GuiSpeakerList(List<String> strings) { this.SpeakerButton.label = IKey.str(this.Speakerlist.getList().get(this.Speakerlist.getIndex())); MappetVoice.AudioManager.getOutput().setMixer(this.SpeakerButton.label.get());
package mrkto.mvoice.client.gui; public class GuiVoiceChange extends GuiBase { public GuiStringListElement Speakerlist; public GuiStringListElement Microlist; public GuiButtonElement SpeakerButton; public GuiButtonElement MicroButton; public GuiVoiceChange() { super(); Minecraft mc = Minecraft.getMinecraft(); GuiElement lelement = new GuiElement(mc); GuiElement relement = new GuiElement(mc); lelement.flex().relative(this.viewport).xy(0.25F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); relement.flex().relative(this.viewport).xy(0.75F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); ArrayList<String> mlist = MappetVoice.AudioManager.getInput().getAudioDevices(); ArrayList<String> slist = MappetVoice.AudioManager.getOutput().getAudioDevices(); this.Speakerlist = new GuiStringListElement(mc, this::GuiSpeakerList); this.Speakerlist.background().setList(slist); this.Speakerlist.sort(); this.Speakerlist.flex().relative(this.viewport).x(0.5F, -10).y(0.5F).w(50).h(100).anchor(1F, 0.5F); this.Speakerlist.setVisible(false); this.Microlist = new GuiStringListElement(mc, this::GuiMicroList); this.Microlist.background().setList(mlist); this.Microlist.sort(); this.Microlist.flex().relative(this.viewport).x(0.5F, -10).y(0.5F).w(50).h(100).anchor(1F, 0.5F); this.Microlist.setVisible(false); this.MicroButton = new GuiButtonElement(mc, IKey.str(MappetVoice.AudioManager.getInput().getMixer()), this::GuiMicroButton); this.SpeakerButton = new GuiButtonElement(mc, IKey.str(MappetVoice.AudioManager.getOutput().getMixer()), this::GuiSpeakerButton); GuiLabel rguiLabel = new GuiLabel(mc, IKey.lang("mvoice.settings.speaker")); GuiLabel lguiLabel = new GuiLabel(mc, IKey.lang("mvoice.settings.micro")); rguiLabel.flex().h(10); lguiLabel.flex().h(10); lelement.add(lguiLabel); lelement.add(MicroButton); lelement.add(Microlist); relement.add(rguiLabel); relement.add(SpeakerButton); relement.add(Speakerlist); this.root.add(lelement); this.root.add(relement); } private void GuiMicroButton(GuiButtonElement guiButtonElement) { this.Microlist.setVisible(true); } private void GuiSpeakerButton(GuiButtonElement guiButtonElement) { this.Speakerlist.setVisible(true); } private void GuiSpeakerList(List<String> strings) { this.SpeakerButton.label = IKey.str(this.Speakerlist.getList().get(this.Speakerlist.getIndex())); MappetVoice.AudioManager.getOutput().setMixer(this.SpeakerButton.label.get());
ClientData.getInstance().setSpeakerName(this.SpeakerButton.label.get());
1
2023-10-14 19:20:12+00:00
12k
Spider-Admin/Frost
src/main/java/frost/messaging/frost/gui/AttachedBoardTableModel.java
[ { "identifier": "BoardAttachment", "path": "src/main/java/frost/messaging/frost/BoardAttachment.java", "snippet": "@SuppressWarnings(\"serial\")\r\npublic class BoardAttachment extends Attachment {\r\n\r\n\tprivate Board boardObj;\r\n\r\n\t@Override\r\n public int getType() {\r\n\t\treturn Attachment...
import java.util.Iterator; import java.util.List; import javax.swing.table.DefaultTableModel; import frost.messaging.frost.BoardAttachment; import frost.messaging.frost.boards.Board; import frost.util.gui.translation.Language; import frost.util.gui.translation.LanguageEvent; import frost.util.gui.translation.LanguageListener;
8,503
/* AttachedBoardTableModel.java / Frost Copyright (C) 2003 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; @SuppressWarnings("serial") public class AttachedBoardTableModel extends DefaultTableModel implements LanguageListener { private Language language = null; protected final static String columnNames[] = new String[3]; protected final static Class<?> columnClasses[] = { String.class, //"Board Name", String.class, //"Access rights" String.class, //"Description" }; public AttachedBoardTableModel() { super(); language = Language.getInstance(); language.addLanguageListener(this); refreshLanguage(); } /* (non-Javadoc) * @see javax.swing.table.TableModel#isCellEditable(int, int) */ @Override public boolean isCellEditable(int row, int col) { return false; } /* (non-Javadoc) * @see frost.gui.translation.LanguageListener#languageChanged(frost.gui.translation.LanguageEvent) */ public void languageChanged(LanguageEvent event) { refreshLanguage(); } private void refreshLanguage() { columnNames[0] = language.getString("MessagePane.boardAttachmentTable.boardName"); columnNames[1] = language.getString("MessagePane.boardAttachmentTable.accessRights"); columnNames[2] = language.getString("MessagePane.boardAttachmentTable.description"); fireTableStructureChanged(); } /** * This method fills the table model with the BoardAttachments * in the list passed as a parameter * @param boardAttachments list of BoardAttachments fo fill the model with */ public void setData(List<BoardAttachment> boardAttachments) { setRowCount(0); Iterator<BoardAttachment> boards = boardAttachments.iterator(); while (boards.hasNext()) {
/* AttachedBoardTableModel.java / Frost Copyright (C) 2003 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; @SuppressWarnings("serial") public class AttachedBoardTableModel extends DefaultTableModel implements LanguageListener { private Language language = null; protected final static String columnNames[] = new String[3]; protected final static Class<?> columnClasses[] = { String.class, //"Board Name", String.class, //"Access rights" String.class, //"Description" }; public AttachedBoardTableModel() { super(); language = Language.getInstance(); language.addLanguageListener(this); refreshLanguage(); } /* (non-Javadoc) * @see javax.swing.table.TableModel#isCellEditable(int, int) */ @Override public boolean isCellEditable(int row, int col) { return false; } /* (non-Javadoc) * @see frost.gui.translation.LanguageListener#languageChanged(frost.gui.translation.LanguageEvent) */ public void languageChanged(LanguageEvent event) { refreshLanguage(); } private void refreshLanguage() { columnNames[0] = language.getString("MessagePane.boardAttachmentTable.boardName"); columnNames[1] = language.getString("MessagePane.boardAttachmentTable.accessRights"); columnNames[2] = language.getString("MessagePane.boardAttachmentTable.description"); fireTableStructureChanged(); } /** * This method fills the table model with the BoardAttachments * in the list passed as a parameter * @param boardAttachments list of BoardAttachments fo fill the model with */ public void setData(List<BoardAttachment> boardAttachments) { setRowCount(0); Iterator<BoardAttachment> boards = boardAttachments.iterator(); while (boards.hasNext()) {
Board board = boards.next().getBoardObj();
1
2023-10-07 22:25:20+00:00
12k
Milosz08/screen-sharing-system
client/src/main/java/pl/polsl/screensharing/client/view/ClientWindow.java
[ { "identifier": "BottomInfobarController", "path": "client/src/main/java/pl/polsl/screensharing/client/controller/BottomInfobarController.java", "snippet": "public class BottomInfobarController extends AbstractBottomInfobarController {\n private final ClientWindow clientWindow;\n private final Tim...
import lombok.Getter; import lombok.Setter; import pl.polsl.screensharing.client.controller.BottomInfobarController; import pl.polsl.screensharing.client.net.ClientDatagramSocket; import pl.polsl.screensharing.client.net.ClientTcpSocket; import pl.polsl.screensharing.client.state.ClientState; import pl.polsl.screensharing.client.view.dialog.*; import pl.polsl.screensharing.client.view.fragment.BottomInfobar; import pl.polsl.screensharing.client.view.fragment.TopMenuBar; import pl.polsl.screensharing.client.view.fragment.TopToolbar; import pl.polsl.screensharing.client.view.fragment.VideoCanvas; import pl.polsl.screensharing.client.view.tabbed.TabbedPaneWindow; import pl.polsl.screensharing.lib.AppType; import pl.polsl.screensharing.lib.gui.AbstractRootFrame; import javax.swing.*; import java.awt.*;
7,988
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view; @Getter public class ClientWindow extends AbstractRootFrame { private final ClientState clientState; private final TopMenuBar topMenuBar; private final TopToolbar topToolbar; private final TabbedPaneWindow tabbedPaneWindow; private final BottomInfobar bottomInfobar; private final ConnectWindow connectWindow; private final LastConnectionsWindow lastConnectionsWindow; private final AboutDialogWindow aboutDialogWindow; private final LicenseDialogWindow licenseDialogWindow; private final SessionInfoDialogWindow sessionInfoDialogWindow; @Setter private ClientDatagramSocket clientDatagramSocket; @Setter
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view; @Getter public class ClientWindow extends AbstractRootFrame { private final ClientState clientState; private final TopMenuBar topMenuBar; private final TopToolbar topToolbar; private final TabbedPaneWindow tabbedPaneWindow; private final BottomInfobar bottomInfobar; private final ConnectWindow connectWindow; private final LastConnectionsWindow lastConnectionsWindow; private final AboutDialogWindow aboutDialogWindow; private final LicenseDialogWindow licenseDialogWindow; private final SessionInfoDialogWindow sessionInfoDialogWindow; @Setter private ClientDatagramSocket clientDatagramSocket; @Setter
private ClientTcpSocket clientTcpSocket;
2
2023-10-11 16:12:02+00:00
12k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/integrations/llms/llama/LlamaServiceProvider.java
[ { "identifier": "DevPilotChatToolWindowService", "path": "src/main/java/com/zhongan/devpilot/gui/toolwindows/chat/DevPilotChatToolWindowService.java", "snippet": "@Service\npublic final class DevPilotChatToolWindowService {\n private final Project project;\n\n private final DevPilotChatToolWindow ...
import com.fasterxml.jackson.databind.ObjectMapper; import com.intellij.openapi.components.Service; import com.intellij.openapi.project.Project; import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService; import com.zhongan.devpilot.integrations.llms.LlmProvider; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionResponse; import com.zhongan.devpilot.integrations.llms.entity.DevPilotFailedResponse; import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage; import com.zhongan.devpilot.integrations.llms.entity.DevPilotSuccessResponse; import com.zhongan.devpilot.settings.state.CodeLlamaSettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.OkhttpUtils; import com.zhongan.devpilot.util.UserAgentUtils; import com.zhongan.devpilot.webview.model.MessageModel; import java.io.IOException; import java.util.Objects; import java.util.function.Consumer; import org.apache.commons.lang3.StringUtils; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.sse.EventSource;
7,277
package com.zhongan.devpilot.integrations.llms.llama; @Service(Service.Level.PROJECT) public final class LlamaServiceProvider implements LlmProvider { private final ObjectMapper objectMapper = new ObjectMapper(); private EventSource es; private DevPilotChatToolWindowService toolWindowService; private MessageModel resultModel = new MessageModel(); @Override public String chatCompletion(Project project, DevPilotChatCompletionRequest chatCompletionRequest, Consumer<String> callback) { var host = CodeLlamaSettingsState.getInstance().getModelHost(); var service = project.getService(DevPilotChatToolWindowService.class); this.toolWindowService = service; if (StringUtils.isEmpty(host)) { service.callErrorInfo("Chat completion failed: host is empty"); return ""; } var modelName = CodeLlamaSettingsState.getInstance().getModelName(); if (StringUtils.isEmpty(modelName)) { service.callErrorInfo("Chat completion failed: code llama model name is empty"); return ""; } chatCompletionRequest.setModel(modelName); try { var request = new Request.Builder() .url(host + "/v1/chat/completions") .header("User-Agent", UserAgentUtils.getUserAgent()) .post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json"))) .build(); this.es = this.buildEventSource(request, service, callback); } catch (Exception e) { service.callErrorInfo("Chat completion failed: " + e.getMessage()); return ""; } return ""; } @Override public void interruptSend() { if (es != null) { es.cancel(); // remember the broken message if (resultModel != null && !StringUtils.isEmpty(resultModel.getContent())) { resultModel.setStreaming(false); toolWindowService.addMessage(resultModel); } toolWindowService.callWebView(); // after interrupt, reset result model resultModel = null; } } @Override public void restoreMessage(MessageModel messageModel) { this.resultModel = messageModel; } @Override public DevPilotChatCompletionResponse chatCompletionSync(DevPilotChatCompletionRequest chatCompletionRequest) { var host = CodeLlamaSettingsState.getInstance().getModelHost(); if (StringUtils.isEmpty(host)) { return DevPilotChatCompletionResponse.failed("Chat completion failed: host is empty"); } var modelName = CodeLlamaSettingsState.getInstance().getModelName(); if (StringUtils.isEmpty(modelName)) { return DevPilotChatCompletionResponse.failed("Chat completion failed: code llama model name is empty"); } chatCompletionRequest.setModel(modelName); okhttp3.Response response; try { var request = new Request.Builder() .url(host + "/v1/chat/completions") .header("User-Agent", UserAgentUtils.getUserAgent()) .post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json"))) .build();
package com.zhongan.devpilot.integrations.llms.llama; @Service(Service.Level.PROJECT) public final class LlamaServiceProvider implements LlmProvider { private final ObjectMapper objectMapper = new ObjectMapper(); private EventSource es; private DevPilotChatToolWindowService toolWindowService; private MessageModel resultModel = new MessageModel(); @Override public String chatCompletion(Project project, DevPilotChatCompletionRequest chatCompletionRequest, Consumer<String> callback) { var host = CodeLlamaSettingsState.getInstance().getModelHost(); var service = project.getService(DevPilotChatToolWindowService.class); this.toolWindowService = service; if (StringUtils.isEmpty(host)) { service.callErrorInfo("Chat completion failed: host is empty"); return ""; } var modelName = CodeLlamaSettingsState.getInstance().getModelName(); if (StringUtils.isEmpty(modelName)) { service.callErrorInfo("Chat completion failed: code llama model name is empty"); return ""; } chatCompletionRequest.setModel(modelName); try { var request = new Request.Builder() .url(host + "/v1/chat/completions") .header("User-Agent", UserAgentUtils.getUserAgent()) .post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json"))) .build(); this.es = this.buildEventSource(request, service, callback); } catch (Exception e) { service.callErrorInfo("Chat completion failed: " + e.getMessage()); return ""; } return ""; } @Override public void interruptSend() { if (es != null) { es.cancel(); // remember the broken message if (resultModel != null && !StringUtils.isEmpty(resultModel.getContent())) { resultModel.setStreaming(false); toolWindowService.addMessage(resultModel); } toolWindowService.callWebView(); // after interrupt, reset result model resultModel = null; } } @Override public void restoreMessage(MessageModel messageModel) { this.resultModel = messageModel; } @Override public DevPilotChatCompletionResponse chatCompletionSync(DevPilotChatCompletionRequest chatCompletionRequest) { var host = CodeLlamaSettingsState.getInstance().getModelHost(); if (StringUtils.isEmpty(host)) { return DevPilotChatCompletionResponse.failed("Chat completion failed: host is empty"); } var modelName = CodeLlamaSettingsState.getInstance().getModelName(); if (StringUtils.isEmpty(modelName)) { return DevPilotChatCompletionResponse.failed("Chat completion failed: code llama model name is empty"); } chatCompletionRequest.setModel(modelName); okhttp3.Response response; try { var request = new Request.Builder() .url(host + "/v1/chat/completions") .header("User-Agent", UserAgentUtils.getUserAgent()) .post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json"))) .build();
Call call = OkhttpUtils.getClient().newCall(request);
9
2023-11-29 06:37:51+00:00
12k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/postprocess/batch/GaiaBatcher.java
[ { "identifier": "GaiaBuffer", "path": "core/src/main/java/com/gaia3d/basic/exchangable/GaiaBuffer.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class GaiaBuffer {\n AttributeType attributeType;\n AccessorType accessorType;\n\n int elementsCount = -1;\n\n ...
import com.gaia3d.basic.exchangable.GaiaBuffer; import com.gaia3d.basic.exchangable.GaiaBufferDataSet; import com.gaia3d.basic.exchangable.GaiaSet; import com.gaia3d.basic.geometry.GaiaRectangle; import com.gaia3d.basic.structure.GaiaMaterial; import com.gaia3d.basic.structure.GaiaTexture; import com.gaia3d.basic.types.AttributeType; import com.gaia3d.basic.types.TextureType; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.LevelOfDetail; import com.gaia3d.process.tileprocess.tile.TileInfo; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.joml.Matrix4d; import org.joml.Vector2d; import org.joml.Vector4d; import org.lwjgl.opengl.GL20; import java.util.*; import java.util.stream.Collectors;
9,461
package com.gaia3d.process.postprocess.batch; @Slf4j public class GaiaBatcher implements Batcher { private final static int SHORT_LIMIT = 65535; private final CommandLine command; public GaiaBatcher(CommandLine command) { this.command = command; } private void reassignMaterialsToGaiaBufferDataSetWithSameMaterial(List<GaiaBufferDataSet> dataSets, LevelOfDetail lod) { int datasetsCount = dataSets.size(); for (int i = 0; i < datasetsCount; i++) { GaiaBufferDataSet dataSet = dataSets.get(i);
package com.gaia3d.process.postprocess.batch; @Slf4j public class GaiaBatcher implements Batcher { private final static int SHORT_LIMIT = 65535; private final CommandLine command; public GaiaBatcher(CommandLine command) { this.command = command; } private void reassignMaterialsToGaiaBufferDataSetWithSameMaterial(List<GaiaBufferDataSet> dataSets, LevelOfDetail lod) { int datasetsCount = dataSets.size(); for (int i = 0; i < datasetsCount; i++) { GaiaBufferDataSet dataSet = dataSets.get(i);
GaiaMaterial material = dataSet.material;
4
2023-11-30 01:59:44+00:00
12k
xuemingqi/x-cloud
x-auth/src/main/java/com/x/auth/service/impl/LoginServiceImpl.java
[ { "identifier": "JwtConfig", "path": "x-auth/src/main/java/com/x/auth/common/jwt/JwtConfig.java", "snippet": "@RefreshScope\n@Configuration\npublic class JwtConfig {\n\n /**\n * 加密字符串\n */\n public static String sign;\n\n /**\n * 签发机构\n */\n public static String iss;\n\n /...
import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.LineCaptcha; import cn.hutool.core.lang.Snowflake; import com.x.auth.common.jwt.JwtConfig; import com.x.auth.common.jwt.JwtUtil; import com.x.auth.common.jwt.UserInfoClaims; import com.x.auth.common.property.LoginProperty; import com.x.auth.domain.VerificationCodeDo; import com.x.auth.service.LoginService; import com.x.common.constants.CommonConstant; import com.x.common.enums.ResponseCodeEnum; import com.x.common.response.BaseResult; import com.x.common.response.ResultUtil; import com.x.common.utils.ServerUtil; import com.x.config.redis.util.RedisUtil; import com.x.contact.api.UserApi; import com.x.contact.dto.UserAuthDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit;
9,488
package com.x.auth.service.impl; /** * @author : xuemingqi * @since : 2023/1/10 14:04 */ @Slf4j @Service @RequiredArgsConstructor(onConstructor = @__({@Autowired})) public class LoginServiceImpl implements LoginService { private final Snowflake snowflake; private final RedisUtil redisUtil; private final UserApi userApi; private final JwtUtil jwtUtil; private final LoginProperty loginProperty; @Override public BaseResult<?> login(String mobile, String password) { //用户密码是否正确 BaseResult<Long> checkResult = userApi.userAuth(UserAuthDto.builder() .mobile(mobile) .password(password) .build()); if (!ResponseCodeEnum.SUCCESS.getCode().equals(checkResult.getCode())) { return fail(mobile); } //生成token String token = jwtUtil.createToken(UserInfoClaims.builder() .userId(checkResult.getData().toString()) .mobile(mobile) .build());
package com.x.auth.service.impl; /** * @author : xuemingqi * @since : 2023/1/10 14:04 */ @Slf4j @Service @RequiredArgsConstructor(onConstructor = @__({@Autowired})) public class LoginServiceImpl implements LoginService { private final Snowflake snowflake; private final RedisUtil redisUtil; private final UserApi userApi; private final JwtUtil jwtUtil; private final LoginProperty loginProperty; @Override public BaseResult<?> login(String mobile, String password) { //用户密码是否正确 BaseResult<Long> checkResult = userApi.userAuth(UserAuthDto.builder() .mobile(mobile) .password(password) .build()); if (!ResponseCodeEnum.SUCCESS.getCode().equals(checkResult.getCode())) { return fail(mobile); } //生成token String token = jwtUtil.createToken(UserInfoClaims.builder() .userId(checkResult.getData().toString()) .mobile(mobile) .build());
String redisKey = CommonConstant.TOKEN_KEY + token;
6
2023-11-27 08:23:38+00:00
12k
okx/OKBund
aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/gas/impl/GasEstimatorDefaultImpl.java
[ { "identifier": "IChain", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/IChain.java", "snippet": "public interface IChain {\n\n long getChainId();\n\n boolean isEip1559();\n\n Web3jDebug getWeb3j();\n\n}" }, { "identifier": "TransactionUtil", "path": "aa-infra/...
import com.google.common.collect.Lists; import com.okcoin.dapp.bundler.infra.chain.IChain; import com.okcoin.dapp.bundler.infra.chain.TransactionUtil; import com.okcoin.dapp.bundler.infra.chain.constant.ChainIdConstant; import com.okcoin.dapp.bundler.infra.chain.constant.Web3Constant; import com.okcoin.dapp.bundler.infra.chain.exception.ChainException; import com.okcoin.dapp.bundler.pool.domain.UserOperationDO; import com.okcoin.dapp.bundler.pool.domain.error.SimulateHandleOpResultOKX; import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint; import com.okcoin.dapp.bundler.pool.exception.AAException; import com.okcoin.dapp.bundler.pool.exception.AAExceptionEnum; import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo; import com.okcoin.dapp.bundler.pool.gasprice.GasService; import com.okcoin.dapp.bundler.pool.simulation.EntryPointSimulationsFactory; import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations; import com.okcoin.dapp.bundler.pool.util.MathUtil; import com.okcoin.dapp.bundler.rest.config.RestConfig; import com.okcoin.dapp.bundler.rest.constant.GasConstant; import com.okcoin.dapp.bundler.rest.gas.IGasEstimator; import com.okcoin.dapp.bundler.rest.gas.UserOperationGasDO; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.web3j.utils.Numeric; import java.math.BigInteger; import static com.okcoin.dapp.bundler.rest.constant.GasConstant.*;
9,096
package com.okcoin.dapp.bundler.rest.gas.impl; @Service @Setter public class GasEstimatorDefaultImpl implements IGasEstimator { @Autowired private EntryPointSimulationsFactory entryPointSimulationsFactory; @Autowired private RestConfig restConfig; @Autowired private GasService gasService; @Override
package com.okcoin.dapp.bundler.rest.gas.impl; @Service @Setter public class GasEstimatorDefaultImpl implements IGasEstimator { @Autowired private EntryPointSimulationsFactory entryPointSimulationsFactory; @Autowired private RestConfig restConfig; @Autowired private GasService gasService; @Override
public boolean fit(IChain chain) {
0
2023-11-27 10:54:49+00:00
12k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/PlayerConfig.java
[ { "identifier": "IRConnectionManager", "path": "core/src/bms/player/beatoraja/ir/IRConnectionManager.java", "snippet": "public class IRConnectionManager {\n\t\n\t/**\n\t * 検出されたIRConnection\n\t */\n\tprivate static Class<IRConnection>[] irconnections;\n\n\n\t/**\n\t * 利用可能な全てのIRConnectionの名称を返す\n\t * \n...
import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.logging.Logger; import bms.player.beatoraja.ir.IRConnectionManager; import bms.player.beatoraja.pattern.*; import bms.player.beatoraja.play.GrooveGauge; import bms.player.beatoraja.select.BarSorter; import bms.player.beatoraja.skin.SkinType; import bms.model.Mode; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonWriter; import com.badlogic.gdx.utils.SerializationException;
8,163
package bms.player.beatoraja; /** * プレイヤー毎の設定項目 * * @author exch */ public class PlayerConfig { static final Path configpath_old = Paths.get("config.json"); static final Path configpath = Paths.get("config_player.json"); private String id; /** * プレイヤーネーム */ private String name = "NO NAME"; /** * ゲージの種類 */ private int gauge = 0; /** * 譜面オプション */ private int random; /** * 譜面オプション(2P) */ private int random2; /** * DP用オプション */ private int doubleoption; /** * スコアターゲット */ private String targetid = "MAX"; private String[] targetlist = new String[] {"RATE_A-","RATE_A", "RATE_A+","RATE_AA-","RATE_AA", "RATE_AA+", "RATE_AAA-", "RATE_AAA", "RATE_AAA+", "MAX" ,"RANK_NEXT", "IR_NEXT_1", "IR_NEXT_2", "IR_NEXT_3", "IR_NEXT_4", "IR_NEXT_5", "IR_NEXT_10" , "IR_RANK_1", "IR_RANK_5", "IR_RANK_10", "IR_RANK_20", "IR_RANK_30", "IR_RANK_40", "IR_RANK_50" , "IR_RANKRATE_5", "IR_RANKRATE_10", "IR_RANKRATE_15", "IR_RANKRATE_20", "IR_RANKRATE_25", "IR_RANKRATE_30", "IR_RANKRATE_35", "IR_RANKRATE_40", "IR_RANKRATE_45","IR_RANKRATE_50" ,"RIVAL_RANK_1","RIVAL_RANK_2","RIVAL_RANK_3","RIVAL_NEXT_1","RIVAL_NEXT_2","RIVAL_NEXT_3"}; /** * 判定タイミング */ private int judgetiming = 0; public static final int JUDGETIMING_MAX = 500; public static final int JUDGETIMING_MIN = -500; /** * ディスプレイ表示タイミング自動調整 */ private boolean notesDisplayTimingAutoAdjust = false; /** * 選曲時のモードフィルター */ private Mode mode = null; /** * 指定がない場合のミスレイヤー表示時間(ms) */ private int misslayerDuration = 500; /** * LNモード */ private int lnmode = 0; /** * スクロール追加/削除モード */ private int scrollMode = 0; private int scrollSection = 4; private double scrollRate = 0.5; /** * ロングノート追加/削除モード */ private int longnoteMode = 0; private double longnoteRate = 1.0; /** * アシストオプション:カスタムジャッジ */ private boolean customJudge = false; private int keyJudgeWindowRatePerfectGreat = 400; private int keyJudgeWindowRateGreat = 400; private int keyJudgeWindowRateGood = 100; private int scratchJudgeWindowRatePerfectGreat = 400; private int scratchJudgeWindowRateGreat = 400; private int scratchJudgeWindowRateGood = 100; /** * 地雷モード */ private int mineMode = 0; /** * アシストオプション:BPMガイド */ private boolean bpmguide = false; private int extranoteType = 0; private int extranoteDepth = 0; private boolean extranoteScratch = false; private boolean showjudgearea = false; private boolean markprocessednote = false; /** * H-RANDOM連打しきい値BPM */ private int hranThresholdBPM = 120; /** * プレイ中のゲージ切替 */ private int gaugeAutoShift = GAUGEAUTOSHIFT_NONE; /** * GASで遷移可能なゲージの下限 ASSIST EASY, EASY, NORMALから選択 */ private int bottomShiftableGauge = GrooveGauge.ASSISTEASY; public static final int GAUGEAUTOSHIFT_NONE = 0; public static final int GAUGEAUTOSHIFT_CONTINUE = 1; public static final int GAUGEAUTOSHIFT_SURVIVAL_TO_GROOVE = 2; public static final int GAUGEAUTOSHIFT_BESTCLEAR = 3; public static final int GAUGEAUTOSHIFT_SELECT_TO_UNDER = 4; private int autosavereplay[]; /** * 7to9 スクラッチ鍵盤位置関係 0:OFF 1:SC1KEY2~8 2:SC1KEY3~9 3:SC2KEY3~9 4:SC8KEY1~7 5:SC9KEY1~7 6:SC9KEY2~8 */ private int sevenToNinePattern = 0; /** * 7to9 スクラッチ処理タイプ 0:そのまま 1:連打回避 2:交互 */ private int sevenToNineType = 0; /** * START+SELECTを押すと終了するまでの時間 */ private int exitPressDuration = 1000; /** * Guide SE */ private boolean isGuideSE = false; /** * Window Hold */ private boolean isWindowHold = false; /** * Enable folder random select bar */ private boolean isRandomSelect = false;
package bms.player.beatoraja; /** * プレイヤー毎の設定項目 * * @author exch */ public class PlayerConfig { static final Path configpath_old = Paths.get("config.json"); static final Path configpath = Paths.get("config_player.json"); private String id; /** * プレイヤーネーム */ private String name = "NO NAME"; /** * ゲージの種類 */ private int gauge = 0; /** * 譜面オプション */ private int random; /** * 譜面オプション(2P) */ private int random2; /** * DP用オプション */ private int doubleoption; /** * スコアターゲット */ private String targetid = "MAX"; private String[] targetlist = new String[] {"RATE_A-","RATE_A", "RATE_A+","RATE_AA-","RATE_AA", "RATE_AA+", "RATE_AAA-", "RATE_AAA", "RATE_AAA+", "MAX" ,"RANK_NEXT", "IR_NEXT_1", "IR_NEXT_2", "IR_NEXT_3", "IR_NEXT_4", "IR_NEXT_5", "IR_NEXT_10" , "IR_RANK_1", "IR_RANK_5", "IR_RANK_10", "IR_RANK_20", "IR_RANK_30", "IR_RANK_40", "IR_RANK_50" , "IR_RANKRATE_5", "IR_RANKRATE_10", "IR_RANKRATE_15", "IR_RANKRATE_20", "IR_RANKRATE_25", "IR_RANKRATE_30", "IR_RANKRATE_35", "IR_RANKRATE_40", "IR_RANKRATE_45","IR_RANKRATE_50" ,"RIVAL_RANK_1","RIVAL_RANK_2","RIVAL_RANK_3","RIVAL_NEXT_1","RIVAL_NEXT_2","RIVAL_NEXT_3"}; /** * 判定タイミング */ private int judgetiming = 0; public static final int JUDGETIMING_MAX = 500; public static final int JUDGETIMING_MIN = -500; /** * ディスプレイ表示タイミング自動調整 */ private boolean notesDisplayTimingAutoAdjust = false; /** * 選曲時のモードフィルター */ private Mode mode = null; /** * 指定がない場合のミスレイヤー表示時間(ms) */ private int misslayerDuration = 500; /** * LNモード */ private int lnmode = 0; /** * スクロール追加/削除モード */ private int scrollMode = 0; private int scrollSection = 4; private double scrollRate = 0.5; /** * ロングノート追加/削除モード */ private int longnoteMode = 0; private double longnoteRate = 1.0; /** * アシストオプション:カスタムジャッジ */ private boolean customJudge = false; private int keyJudgeWindowRatePerfectGreat = 400; private int keyJudgeWindowRateGreat = 400; private int keyJudgeWindowRateGood = 100; private int scratchJudgeWindowRatePerfectGreat = 400; private int scratchJudgeWindowRateGreat = 400; private int scratchJudgeWindowRateGood = 100; /** * 地雷モード */ private int mineMode = 0; /** * アシストオプション:BPMガイド */ private boolean bpmguide = false; private int extranoteType = 0; private int extranoteDepth = 0; private boolean extranoteScratch = false; private boolean showjudgearea = false; private boolean markprocessednote = false; /** * H-RANDOM連打しきい値BPM */ private int hranThresholdBPM = 120; /** * プレイ中のゲージ切替 */ private int gaugeAutoShift = GAUGEAUTOSHIFT_NONE; /** * GASで遷移可能なゲージの下限 ASSIST EASY, EASY, NORMALから選択 */ private int bottomShiftableGauge = GrooveGauge.ASSISTEASY; public static final int GAUGEAUTOSHIFT_NONE = 0; public static final int GAUGEAUTOSHIFT_CONTINUE = 1; public static final int GAUGEAUTOSHIFT_SURVIVAL_TO_GROOVE = 2; public static final int GAUGEAUTOSHIFT_BESTCLEAR = 3; public static final int GAUGEAUTOSHIFT_SELECT_TO_UNDER = 4; private int autosavereplay[]; /** * 7to9 スクラッチ鍵盤位置関係 0:OFF 1:SC1KEY2~8 2:SC1KEY3~9 3:SC2KEY3~9 4:SC8KEY1~7 5:SC9KEY1~7 6:SC9KEY2~8 */ private int sevenToNinePattern = 0; /** * 7to9 スクラッチ処理タイプ 0:そのまま 1:連打回避 2:交互 */ private int sevenToNineType = 0; /** * START+SELECTを押すと終了するまでの時間 */ private int exitPressDuration = 1000; /** * Guide SE */ private boolean isGuideSE = false; /** * Window Hold */ private boolean isWindowHold = false; /** * Enable folder random select bar */ private boolean isRandomSelect = false;
private SkinConfig[] skin = new SkinConfig[SkinType.getMaxSkinTypeID() + 1];
3
2023-12-02 23:41:17+00:00
12k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/ThunderBolt.java
[ { "identifier": "DungeonTilemap", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/tiles/DungeonTilemap.java", "snippet": "public abstract class DungeonTilemap extends Tilemap {\n\n\tpublic static final int SIZE = 16;\n\n\tprotected int[] map;\n\n\tpublic DungeonTilemap(String tex) {...
import java.util.Arrays; import java.util.List; import com.shatteredpixel.shatteredpixeldungeon.tiles.DungeonTilemap; import com.watabou.glwrap.Blending; import com.watabou.noosa.Game; import com.watabou.noosa.Group; import com.watabou.noosa.Image; import com.watabou.utils.Callback; import com.watabou.utils.PointF; import com.watabou.utils.Random;
9,737
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * 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 com.shatteredpixel.shatteredpixeldungeon.effects; public class ThunderBolt extends Group { private static final float DURATION = 0.3f; private float life; private List<Arc> arcs; private Callback callback; public ThunderBolt(int from, int to, Callback callback){ this(Arrays.asList(new Arc(from, to)), callback); }
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * 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 com.shatteredpixel.shatteredpixeldungeon.effects; public class ThunderBolt extends Group { private static final float DURATION = 0.3f; private float life; private List<Arc> arcs; private Callback callback; public ThunderBolt(int from, int to, Callback callback){ this(Arrays.asList(new Arc(from, to)), callback); }
public ThunderBolt(PointF from, int to, Callback callback){
6
2023-11-27 05:56:58+00:00
12k
Tofaa2/EntityLib
src/main/java/me/tofaa/entitylib/MetaConverterRegistry.java
[ { "identifier": "EntityMeta", "path": "src/main/java/me/tofaa/entitylib/meta/EntityMeta.java", "snippet": "public class EntityMeta implements EntityMetadataProvider {\n\n public static final byte OFFSET = 0;\n public static final byte MAX_OFFSET = OFFSET + 8;\n\n private final static byte ON_FI...
import com.github.retrooper.packetevents.protocol.entity.type.EntityType; import me.tofaa.entitylib.meta.EntityMeta; import me.tofaa.entitylib.meta.Metadata; import me.tofaa.entitylib.meta.display.BlockDisplayMeta; import me.tofaa.entitylib.meta.display.ItemDisplayMeta; import me.tofaa.entitylib.meta.display.TextDisplayMeta; import me.tofaa.entitylib.meta.mobs.*; import me.tofaa.entitylib.meta.mobs.DonkeyMeta; import me.tofaa.entitylib.meta.mobs.cuboid.MagmaCubeMeta; import me.tofaa.entitylib.meta.mobs.cuboid.SlimeMeta; import me.tofaa.entitylib.meta.mobs.golem.IronGolemMeta; import me.tofaa.entitylib.meta.mobs.golem.ShulkerMeta; import me.tofaa.entitylib.meta.mobs.golem.SnowGolemMeta; import me.tofaa.entitylib.meta.mobs.horse.*; import me.tofaa.entitylib.meta.mobs.monster.*; import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinBruteMeta; import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinMeta; import me.tofaa.entitylib.meta.mobs.monster.raider.*; import me.tofaa.entitylib.meta.mobs.monster.skeleton.SkeletonMeta; import me.tofaa.entitylib.meta.mobs.monster.skeleton.StrayMeta; import me.tofaa.entitylib.meta.mobs.monster.skeleton.WitherSkeletonMeta; import me.tofaa.entitylib.meta.mobs.monster.zombie.*; import me.tofaa.entitylib.meta.mobs.passive.*; import me.tofaa.entitylib.meta.mobs.water.*; import me.tofaa.entitylib.meta.mobs.minecart.*; import me.tofaa.entitylib.meta.mobs.tameable.CatMeta; import me.tofaa.entitylib.meta.mobs.tameable.ParrotMeta; import me.tofaa.entitylib.meta.mobs.tameable.WolfMeta; import me.tofaa.entitylib.meta.mobs.villager.VillagerMeta; import me.tofaa.entitylib.meta.mobs.villager.WanderingTraderMeta; import me.tofaa.entitylib.meta.other.*; import me.tofaa.entitylib.meta.projectile.*; import me.tofaa.entitylib.meta.types.PlayerMeta; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import static com.github.retrooper.packetevents.protocol.entity.type.EntityTypes.*;
10,145
package me.tofaa.entitylib; @SuppressWarnings("unchecked") final class MetaConverterRegistry { private final Map<EntityType, BiFunction<Integer, Metadata, EntityMeta>> converters = new HashMap<>(); private final Map<EntityType, Class<? extends EntityMeta>> metaClasses = new HashMap<>(); MetaConverterRegistry() { put(SNIFFER, SnifferMeta.class, SnifferMeta::new); put(INTERACTION, InteractionMeta.class, InteractionMeta::new); put(BLOCK_DISPLAY, BlockDisplayMeta.class, BlockDisplayMeta::new); put(ITEM_DISPLAY, ItemDisplayMeta.class, ItemDisplayMeta::new); put(TEXT_DISPLAY, TextDisplayMeta.class, TextDisplayMeta::new); put(AREA_EFFECT_CLOUD, AreaEffectCloudMeta.class, AreaEffectCloudMeta::new); put(ARMOR_STAND, ArmorStandMeta.class, ArmorStandMeta::new); put(BOAT, BoatMeta.class, BoatMeta::new); put(DRAGON_FIREBALL, DragonFireballMeta.class, DragonFireballMeta::new); put(END_CRYSTAL, EndCrystalMeta.class, EndCrystalMeta::new); put(ENDER_DRAGON, EnderDragonMeta.class, EnderDragonMeta::new); put(EVOKER_FANGS, EvokerFangsMeta.class, EvokerFangsMeta::new); put(FALLING_BLOCK, FallingBlockMeta.class, FallingBlockMeta::new); put(FIREWORK_ROCKET, FireworkRocketMeta.class, FireworkRocketMeta::new); put(FISHING_BOBBER, FishingHookMeta.class, FishingHookMeta::new); put(GLOW_ITEM_FRAME, GlowItemFrameMeta.class, GlowItemFrameMeta::new); put(ITEM_FRAME, ItemFrameMeta.class, ItemFrameMeta::new); put(LEASH_KNOT, LeashKnotMeta.class, LeashKnotMeta::new); put(LIGHTNING_BOLT, LightningBoltMeta.class, LightningBoltMeta::new); put(LLAMA_SPIT, LlamaSpitMeta.class, LlamaSpitMeta::new); put(MARKER, MarkerMeta.class, MarkerMeta::new); put(PAINTING, PaintingMeta.class, PaintingMeta::new); put(PRIMED_TNT, PrimedTntMeta.class, PrimedTntMeta::new); put(WITHER_SKULL, WitherSkullMeta.class, WitherSkullMeta::new); put(ZOGLIN, ZoglinMeta.class, ZoglinMeta::new); put(WITHER, WitherMeta.class, WitherMeta::new); put(VEX, VexMeta.class, VexMeta::new); put(SPIDER, SpiderMeta.class, SpiderMeta::new); put(SILVERFISH, SilverfishMeta.class, SilverfishMeta::new); put(GUARDIAN, GuardianMeta.class, GuardianMeta::new); put(GIANT, GiantMeta.class, GiantMeta::new); put(ENDERMITE, EndermiteMeta.class, EndermiteMeta::new); put(ENDERMITE, EndermiteMeta.class, EndermiteMeta::new); put(ELDER_GUARDIAN, ElderGuardianMeta.class, ElderGuardianMeta::new); put(CREEPER, CreeperMeta.class, CreeperMeta::new); put(CAVE_SPIDER, CaveSpiderMeta.class, CaveSpiderMeta::new); put(BLAZE, BlazeMeta.class, BlazeMeta::new); put(PIGLIN, PiglinMeta.class, PiglinMeta::new); put(PIGLIN_BRUTE, PiglinBruteMeta.class, PiglinBruteMeta::new); put(EVOKER, EvokerMeta.class, EvokerMeta::new); put(ILLUSIONER, IllusionerMeta.class, IllusionerMeta::new); put(PILLAGER, PillagerMeta.class, PillagerMeta::new); put(RAVAGER, RavagerMeta.class, RavagerMeta::new); put(VINDICATOR, VindicatorMeta.class, VindicatorMeta::new); put(WITCH, WitchMeta.class, WitchMeta::new); put(SKELETON, SkeletonMeta.class, SkeletonMeta::new); put(STRAY, StrayMeta.class, StrayMeta::new); put(WITHER_SKELETON, WitherSkeletonMeta.class, WitherSkeletonMeta::new); put(DROWNED, DrownedMeta.class, DrownedMeta::new); put(HUSK, HuskMeta.class, HuskMeta::new); put(ZOMBIE, ZombieMeta.class, ZombieMeta::new); put(ZOMBIE_VILLAGER, ZombieVillagerMeta.class, ZombieVillagerMeta::new); put(ZOMBIFIED_PIGLIN, ZombifiedPiglinMeta.class, ZombifiedPiglinMeta::new); put(AXOLOTL, AxolotlMeta.class, AxolotlMeta::new); put(COD, CodMeta.class, CodMeta::new); put(DOLPHIN, DolphinMeta.class, DolphinMeta::new); put(GLOW_SQUID, GlowSquidMeta.class, GlowSquidMeta::new); put(PUFFERFISH, PufferFishMeta.class, PufferFishMeta::new); put(SALMON, SalmonMeta.class, SalmonMeta::new); put(TROPICAL_FISH, TropicalFishMeta.class, TropicalFishMeta::new); put(ARROW, ArrowMeta.class, ArrowMeta::new); put(VILLAGER, VillagerMeta.class, VillagerMeta::new); put(WANDERING_TRADER, WanderingTraderMeta.class, WanderingTraderMeta::new); put(CHEST_MINECART, ChestMinecartMeta.class, ChestMinecartMeta::new); put(COMMAND_BLOCK_MINECART, CommandBlockMinecartMeta.class, CommandBlockMinecartMeta::new); put(COMMAND_BLOCK_MINECART, CommandBlockMinecartMeta.class, CommandBlockMinecartMeta::new); put(FURNACE_MINECART, FurnaceMinecartMeta.class, FurnaceMinecartMeta::new); put(HOPPER_MINECART, FurnaceMinecartMeta.class, FurnaceMinecartMeta::new); put(SPAWNER_MINECART, SpawnerMinecartMeta.class, SpawnerMinecartMeta::new); put(TNT_MINECART, TntMinecartMeta.class, TntMinecartMeta::new);
package me.tofaa.entitylib; @SuppressWarnings("unchecked") final class MetaConverterRegistry { private final Map<EntityType, BiFunction<Integer, Metadata, EntityMeta>> converters = new HashMap<>(); private final Map<EntityType, Class<? extends EntityMeta>> metaClasses = new HashMap<>(); MetaConverterRegistry() { put(SNIFFER, SnifferMeta.class, SnifferMeta::new); put(INTERACTION, InteractionMeta.class, InteractionMeta::new); put(BLOCK_DISPLAY, BlockDisplayMeta.class, BlockDisplayMeta::new); put(ITEM_DISPLAY, ItemDisplayMeta.class, ItemDisplayMeta::new); put(TEXT_DISPLAY, TextDisplayMeta.class, TextDisplayMeta::new); put(AREA_EFFECT_CLOUD, AreaEffectCloudMeta.class, AreaEffectCloudMeta::new); put(ARMOR_STAND, ArmorStandMeta.class, ArmorStandMeta::new); put(BOAT, BoatMeta.class, BoatMeta::new); put(DRAGON_FIREBALL, DragonFireballMeta.class, DragonFireballMeta::new); put(END_CRYSTAL, EndCrystalMeta.class, EndCrystalMeta::new); put(ENDER_DRAGON, EnderDragonMeta.class, EnderDragonMeta::new); put(EVOKER_FANGS, EvokerFangsMeta.class, EvokerFangsMeta::new); put(FALLING_BLOCK, FallingBlockMeta.class, FallingBlockMeta::new); put(FIREWORK_ROCKET, FireworkRocketMeta.class, FireworkRocketMeta::new); put(FISHING_BOBBER, FishingHookMeta.class, FishingHookMeta::new); put(GLOW_ITEM_FRAME, GlowItemFrameMeta.class, GlowItemFrameMeta::new); put(ITEM_FRAME, ItemFrameMeta.class, ItemFrameMeta::new); put(LEASH_KNOT, LeashKnotMeta.class, LeashKnotMeta::new); put(LIGHTNING_BOLT, LightningBoltMeta.class, LightningBoltMeta::new); put(LLAMA_SPIT, LlamaSpitMeta.class, LlamaSpitMeta::new); put(MARKER, MarkerMeta.class, MarkerMeta::new); put(PAINTING, PaintingMeta.class, PaintingMeta::new); put(PRIMED_TNT, PrimedTntMeta.class, PrimedTntMeta::new); put(WITHER_SKULL, WitherSkullMeta.class, WitherSkullMeta::new); put(ZOGLIN, ZoglinMeta.class, ZoglinMeta::new); put(WITHER, WitherMeta.class, WitherMeta::new); put(VEX, VexMeta.class, VexMeta::new); put(SPIDER, SpiderMeta.class, SpiderMeta::new); put(SILVERFISH, SilverfishMeta.class, SilverfishMeta::new); put(GUARDIAN, GuardianMeta.class, GuardianMeta::new); put(GIANT, GiantMeta.class, GiantMeta::new); put(ENDERMITE, EndermiteMeta.class, EndermiteMeta::new); put(ENDERMITE, EndermiteMeta.class, EndermiteMeta::new); put(ELDER_GUARDIAN, ElderGuardianMeta.class, ElderGuardianMeta::new); put(CREEPER, CreeperMeta.class, CreeperMeta::new); put(CAVE_SPIDER, CaveSpiderMeta.class, CaveSpiderMeta::new); put(BLAZE, BlazeMeta.class, BlazeMeta::new); put(PIGLIN, PiglinMeta.class, PiglinMeta::new); put(PIGLIN_BRUTE, PiglinBruteMeta.class, PiglinBruteMeta::new); put(EVOKER, EvokerMeta.class, EvokerMeta::new); put(ILLUSIONER, IllusionerMeta.class, IllusionerMeta::new); put(PILLAGER, PillagerMeta.class, PillagerMeta::new); put(RAVAGER, RavagerMeta.class, RavagerMeta::new); put(VINDICATOR, VindicatorMeta.class, VindicatorMeta::new); put(WITCH, WitchMeta.class, WitchMeta::new); put(SKELETON, SkeletonMeta.class, SkeletonMeta::new); put(STRAY, StrayMeta.class, StrayMeta::new); put(WITHER_SKELETON, WitherSkeletonMeta.class, WitherSkeletonMeta::new); put(DROWNED, DrownedMeta.class, DrownedMeta::new); put(HUSK, HuskMeta.class, HuskMeta::new); put(ZOMBIE, ZombieMeta.class, ZombieMeta::new); put(ZOMBIE_VILLAGER, ZombieVillagerMeta.class, ZombieVillagerMeta::new); put(ZOMBIFIED_PIGLIN, ZombifiedPiglinMeta.class, ZombifiedPiglinMeta::new); put(AXOLOTL, AxolotlMeta.class, AxolotlMeta::new); put(COD, CodMeta.class, CodMeta::new); put(DOLPHIN, DolphinMeta.class, DolphinMeta::new); put(GLOW_SQUID, GlowSquidMeta.class, GlowSquidMeta::new); put(PUFFERFISH, PufferFishMeta.class, PufferFishMeta::new); put(SALMON, SalmonMeta.class, SalmonMeta::new); put(TROPICAL_FISH, TropicalFishMeta.class, TropicalFishMeta::new); put(ARROW, ArrowMeta.class, ArrowMeta::new); put(VILLAGER, VillagerMeta.class, VillagerMeta::new); put(WANDERING_TRADER, WanderingTraderMeta.class, WanderingTraderMeta::new); put(CHEST_MINECART, ChestMinecartMeta.class, ChestMinecartMeta::new); put(COMMAND_BLOCK_MINECART, CommandBlockMinecartMeta.class, CommandBlockMinecartMeta::new); put(COMMAND_BLOCK_MINECART, CommandBlockMinecartMeta.class, CommandBlockMinecartMeta::new); put(FURNACE_MINECART, FurnaceMinecartMeta.class, FurnaceMinecartMeta::new); put(HOPPER_MINECART, FurnaceMinecartMeta.class, FurnaceMinecartMeta::new); put(SPAWNER_MINECART, SpawnerMinecartMeta.class, SpawnerMinecartMeta::new); put(TNT_MINECART, TntMinecartMeta.class, TntMinecartMeta::new);
put(PLAYER, PlayerMeta.class, PlayerMeta::new);
21
2023-11-27 02:17:41+00:00
12k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/HuskClaimsCommand.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import de.themoep.minedown.adventure.MineDown; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.JoinConfiguration; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextColor; import net.william278.desertwell.about.AboutMenu; import net.william278.desertwell.util.UpdateChecker; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.config.Locales; import net.william278.huskclaims.hook.HuskHomesHook; import net.william278.huskclaims.hook.Importer; import net.william278.huskclaims.position.Position; import net.william278.huskclaims.user.AuditLogger; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.OnlineUser; import net.william278.huskclaims.user.SavedUser; import net.william278.paginedown.PaginatedList; import org.apache.commons.text.WordUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.IntStream;
7,837
executor.sendMessage(Component.join( JoinConfiguration.newlines(), Arrays.stream(StatusLine.values()).map(s -> s.get(plugin)).toList() )); } case "import" -> handleImportCommand(executor, removeFirstArg(args)); case "reload" -> { try { plugin.unloadHooks(); plugin.loadSettings(); plugin.loadHooks(); plugin.getLocales().getLocale("reload_complete").ifPresent(executor::sendMessage); } catch (Throwable e) { executor.sendMessage(new MineDown( "[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)" )); plugin.log(Level.SEVERE, "Failed to reload the plugin", e); } } case "update" -> updateChecker.check().thenAccept(checked -> { if (checked.isUpToDate()) { plugin.getLocales().getLocale("up_to_date", plugin.getPluginVersion().toString()) .ifPresent(executor::sendMessage); return; } plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(), plugin.getPluginVersion().toString()).ifPresent(executor::sendMessage); }); default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); } } @Nullable @Override public List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) { return switch (args.length) { case 0, 1 -> SUB_COMMANDS.keySet().stream().filter(n -> user.hasPermission(getPermission(n))).toList(); default -> switch (args[0].toLowerCase(Locale.ENGLISH)) { case "import" -> switch (args.length - 2) { case 0 -> plugin.getImporters().stream().map(Importer::getName).toList(); case 1 -> List.of("start", "set", "reset"); default -> plugin.getImporters().stream().filter(i -> i.getName().equalsIgnoreCase(args[1])) .flatMap(i -> i.getRequiredParameters().keySet().stream() .filter(p -> parseKeyValues(args, 3).keySet().stream() .noneMatch(p::equalsIgnoreCase)) .map("%s:"::formatted)).toList(); }; case "help" -> IntStream.rangeClosed(1, getCommandList(user).getTotalPages()) .mapToObj(Integer::toString).toList(); default -> null; }; }; } private void handleImportCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<Importer> optionalImporter = parseStringArg(args, 0).flatMap(plugin::getImporterByName); if (optionalImporter.isEmpty()) { plugin.getLocales().getLocale("available_importers", plugin.getImporters().stream() .map(Importer::getName).collect(Collectors.joining(", "))) .ifPresent(executor::sendMessage); return; } final Importer importer = optionalImporter.get(); switch (parseStringArg(args, 1).map(a -> a.toLowerCase(Locale.ENGLISH)).orElse("start")) { case "start", "begin" -> importer.start(executor); case "set", "config", "configure" -> parseKeyValues(args, 2) .forEach((k, v) -> importer.setValue(executor, k, v, k.equalsIgnoreCase("password"))); case "reset" -> importer.reset(executor); default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); } } private void handleLogsCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<SavedUser> optionalUser = parseStringArg(args, 0).flatMap(plugin.getDatabase()::getUser); if (optionalUser.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); return; } final SavedUser user = optionalUser.get(); final List<AuditLogger.TimestampedEntry> auditLog = user.getPreferences().getTimestampedLogEntries(); if (auditLog.isEmpty()) { plugin.getLocales().getLocale("error_invalid_user", user.getUser().getName()) .ifPresent(executor::sendMessage); return; } final Locales locales = plugin.getLocales(); final String userName = user.getUser().getName(); final PaginatedList list = PaginatedList.of(auditLog .stream().map( entry -> locales.getRawLocale("audit_log_row", DateTimeFormatter.ofPattern("dd MMM, yyyy HH:mm").format(entry.timestamp()), Locales.escapeText(entry.entry().getAction().getFormattedName()), entry.entry().getUser() != null ? Locales.escapeText(entry.entry().getUser().getName()) : "", entry.entry().getMessage() != null ? Locales.escapeText(entry.entry().getMessage()) : "" ).orElse("") ).toList(), locales.getBaseList(ITEMS_PER_LIST_PAGE) .setItemSeparator("\n").setCommand("/%s logs %s".formatted(getName(), userName)) .setHeaderFormat(locales.getRawLocale("audit_log_header", Locales.escapeText(userName)).orElse("")) .build() ); executor.sendMessage(list.getNearestValidPage(parseIntArg(args, 1).orElse(1))); } private void handleTeleportCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<Position> position = parsePositionArgs(args, 0) .or(() -> parsePositionArgs(args, 1)); final String server = parseStringArg(args, 0).orElse(plugin.getServerName()); if (position.isEmpty() || !(executor instanceof OnlineUser online)) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); return; }
/* * 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.command; public class HuskClaimsCommand extends Command implements TabCompletable { private static final int ITEMS_PER_LIST_PAGE = 8; private static final Map<String, Boolean> SUB_COMMANDS = Map.of( "about", false, "help", false, "teleport", true, "logs", true, "status", true, "import", true, "reload", true, "update", true ); private final UpdateChecker updateChecker; private final AboutMenu aboutMenu; protected HuskClaimsCommand(@NotNull HuskClaims plugin) { super( List.of("huskclaims"), "[" + String.join("|", SUB_COMMANDS.keySet()) + "]", plugin ); addAdditionalPermissions(SUB_COMMANDS); this.updateChecker = plugin.getUpdateChecker(); this.aboutMenu = AboutMenu.builder() .title(Component.text("HuskClaims")) .description(Component.text("A clean, cross-server compatible grief prevention plugin")) .version(plugin.getPluginVersion()) .credits("Author", AboutMenu.Credit.of("William278").description("Click to visit website").url("https://william278.net")) .credits("Contributors", AboutMenu.Credit.of("AlexDev_").description("Code")) .credits("Translators", AboutMenu.Credit.of("jhqwqmc").description("Simplified Chinese (zh-cn)"), AboutMenu.Credit.of("Artem4ikBaik").description("Russian (ru-ru)")) .buttons( AboutMenu.Link.of("https://william278.net/docs/huskclaims").text("Documentation").icon("⛏"), AboutMenu.Link.of("https://github.com/WiIIiam278/HuskClaims/issues").text("Issues").icon("❌").color(TextColor.color(0xff9f0f)), AboutMenu.Link.of("https://discord.gg/tVYhJfyDWG").text("Discord").icon("⭐").color(TextColor.color(0x6773f5))) .build(); } @Override public void execute(@NotNull CommandUser executor, @NotNull String[] args) { final String subCommand = parseStringArg(args, 0).orElse("about").toLowerCase(Locale.ENGLISH); if (SUB_COMMANDS.containsKey(subCommand) && !executor.hasPermission(getPermission(subCommand))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); return; } switch (subCommand) { case "about" -> executor.sendMessage(aboutMenu.toComponent()); case "help" -> executor.sendMessage( getCommandList(executor).getNearestValidPage(parseIntArg(args, 1).orElse(1)) ); case "teleport" -> handleTeleportCommand(executor, removeFirstArg(args)); case "logs" -> handleLogsCommand(executor, removeFirstArg(args)); case "status" -> { getPlugin().getLocales().getLocale("system_status_header").ifPresent(executor::sendMessage); executor.sendMessage(Component.join( JoinConfiguration.newlines(), Arrays.stream(StatusLine.values()).map(s -> s.get(plugin)).toList() )); } case "import" -> handleImportCommand(executor, removeFirstArg(args)); case "reload" -> { try { plugin.unloadHooks(); plugin.loadSettings(); plugin.loadHooks(); plugin.getLocales().getLocale("reload_complete").ifPresent(executor::sendMessage); } catch (Throwable e) { executor.sendMessage(new MineDown( "[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)" )); plugin.log(Level.SEVERE, "Failed to reload the plugin", e); } } case "update" -> updateChecker.check().thenAccept(checked -> { if (checked.isUpToDate()) { plugin.getLocales().getLocale("up_to_date", plugin.getPluginVersion().toString()) .ifPresent(executor::sendMessage); return; } plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(), plugin.getPluginVersion().toString()).ifPresent(executor::sendMessage); }); default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); } } @Nullable @Override public List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) { return switch (args.length) { case 0, 1 -> SUB_COMMANDS.keySet().stream().filter(n -> user.hasPermission(getPermission(n))).toList(); default -> switch (args[0].toLowerCase(Locale.ENGLISH)) { case "import" -> switch (args.length - 2) { case 0 -> plugin.getImporters().stream().map(Importer::getName).toList(); case 1 -> List.of("start", "set", "reset"); default -> plugin.getImporters().stream().filter(i -> i.getName().equalsIgnoreCase(args[1])) .flatMap(i -> i.getRequiredParameters().keySet().stream() .filter(p -> parseKeyValues(args, 3).keySet().stream() .noneMatch(p::equalsIgnoreCase)) .map("%s:"::formatted)).toList(); }; case "help" -> IntStream.rangeClosed(1, getCommandList(user).getTotalPages()) .mapToObj(Integer::toString).toList(); default -> null; }; }; } private void handleImportCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<Importer> optionalImporter = parseStringArg(args, 0).flatMap(plugin::getImporterByName); if (optionalImporter.isEmpty()) { plugin.getLocales().getLocale("available_importers", plugin.getImporters().stream() .map(Importer::getName).collect(Collectors.joining(", "))) .ifPresent(executor::sendMessage); return; } final Importer importer = optionalImporter.get(); switch (parseStringArg(args, 1).map(a -> a.toLowerCase(Locale.ENGLISH)).orElse("start")) { case "start", "begin" -> importer.start(executor); case "set", "config", "configure" -> parseKeyValues(args, 2) .forEach((k, v) -> importer.setValue(executor, k, v, k.equalsIgnoreCase("password"))); case "reset" -> importer.reset(executor); default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); } } private void handleLogsCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<SavedUser> optionalUser = parseStringArg(args, 0).flatMap(plugin.getDatabase()::getUser); if (optionalUser.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); return; } final SavedUser user = optionalUser.get(); final List<AuditLogger.TimestampedEntry> auditLog = user.getPreferences().getTimestampedLogEntries(); if (auditLog.isEmpty()) { plugin.getLocales().getLocale("error_invalid_user", user.getUser().getName()) .ifPresent(executor::sendMessage); return; } final Locales locales = plugin.getLocales(); final String userName = user.getUser().getName(); final PaginatedList list = PaginatedList.of(auditLog .stream().map( entry -> locales.getRawLocale("audit_log_row", DateTimeFormatter.ofPattern("dd MMM, yyyy HH:mm").format(entry.timestamp()), Locales.escapeText(entry.entry().getAction().getFormattedName()), entry.entry().getUser() != null ? Locales.escapeText(entry.entry().getUser().getName()) : "", entry.entry().getMessage() != null ? Locales.escapeText(entry.entry().getMessage()) : "" ).orElse("") ).toList(), locales.getBaseList(ITEMS_PER_LIST_PAGE) .setItemSeparator("\n").setCommand("/%s logs %s".formatted(getName(), userName)) .setHeaderFormat(locales.getRawLocale("audit_log_header", Locales.escapeText(userName)).orElse("")) .build() ); executor.sendMessage(list.getNearestValidPage(parseIntArg(args, 1).orElse(1))); } private void handleTeleportCommand(@NotNull CommandUser executor, @NotNull String[] args) { final Optional<Position> position = parsePositionArgs(args, 0) .or(() -> parsePositionArgs(args, 1)); final String server = parseStringArg(args, 0).orElse(plugin.getServerName()); if (position.isEmpty() || !(executor instanceof OnlineUser online)) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); return; }
plugin.getHook(HuskHomesHook.class).ifPresentOrElse(
2
2023-11-28 01:09:43+00:00
12k
Manzzx/multi-channel-message-reach
metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/reflect/ReflectUtils.java
[ { "identifier": "Convert", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/text/Convert.java", "snippet": "public class Convert\n{\n /**\n * 转换为字符串<br>\n * 如果给定的值为null,或者转换失败,返回默认值<br>\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue...
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.poi.ss.usermodel.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.metax.common.core.text.Convert; import com.metax.common.core.utils.DateUtils;
10,092
package com.metax.common.core.utils.reflect; /** * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. * * @author ruoyi */ @SuppressWarnings("rawtypes") public class ReflectUtils { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class); /** * 调用Getter方法. * 支持多级,如:对象名.对象名.方法 */ @SuppressWarnings("unchecked") public static <E> E invokeGetter(Object obj, String propertyName) { Object object = obj; for (String name : StringUtils.split(propertyName, ".")) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } return (E) object; } /** * 调用Setter方法, 仅匹配方法名。 * 支持多级,如:对象名.对象名.方法 */ public static <E> void invokeSetter(Object obj, String propertyName, E value) { Object object = obj; String[] names = StringUtils.split(propertyName, "."); for (int i = 0; i < names.length; i++) { if (i < names.length - 1) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } else { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); invokeMethodByName(object, setterMethodName, new Object[] { value }); } } } /** * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */ @SuppressWarnings("unchecked") public static <E> E getFieldValue(final Object obj, final String fieldName) { Field field = getAccessibleField(obj, fieldName); if (field == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return null; } E result = null; try { result = (E) field.get(obj); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常{}", e.getMessage()); } return result; } /** * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return; } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常: {}", e.getMessage()); } } /** * 直接调用对象方法, 无视private/protected修饰符. * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. * 同时匹配方法名+参数类型, */ @SuppressWarnings("unchecked") public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) { if (obj == null || methodName == null) { return null; } Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } try { return (E) method.invoke(obj, args); } catch (Exception e) { String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; throw convertReflectionExceptionToUnchecked(msg, e); } } /** * 直接调用对象方法, 无视private/protected修饰符, * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用. * 只匹配函数名,如果有多个同名函数调用第一个。 */ @SuppressWarnings("unchecked") public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) { Method method = getAccessibleMethodByName(obj, methodName, args.length); if (method == null) { // 如果为空不报错,直接返回空。 logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } try { // 类型转换(将参数数据类型转换为目标方法参数类型) Class<?>[] cs = method.getParameterTypes(); for (int i = 0; i < cs.length; i++) { if (args[i] != null && !args[i].getClass().equals(cs[i])) { if (cs[i] == String.class) {
package com.metax.common.core.utils.reflect; /** * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. * * @author ruoyi */ @SuppressWarnings("rawtypes") public class ReflectUtils { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class); /** * 调用Getter方法. * 支持多级,如:对象名.对象名.方法 */ @SuppressWarnings("unchecked") public static <E> E invokeGetter(Object obj, String propertyName) { Object object = obj; for (String name : StringUtils.split(propertyName, ".")) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } return (E) object; } /** * 调用Setter方法, 仅匹配方法名。 * 支持多级,如:对象名.对象名.方法 */ public static <E> void invokeSetter(Object obj, String propertyName, E value) { Object object = obj; String[] names = StringUtils.split(propertyName, "."); for (int i = 0; i < names.length; i++) { if (i < names.length - 1) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } else { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); invokeMethodByName(object, setterMethodName, new Object[] { value }); } } } /** * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */ @SuppressWarnings("unchecked") public static <E> E getFieldValue(final Object obj, final String fieldName) { Field field = getAccessibleField(obj, fieldName); if (field == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return null; } E result = null; try { result = (E) field.get(obj); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常{}", e.getMessage()); } return result; } /** * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); return; } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("不可能抛出的异常: {}", e.getMessage()); } } /** * 直接调用对象方法, 无视private/protected修饰符. * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. * 同时匹配方法名+参数类型, */ @SuppressWarnings("unchecked") public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) { if (obj == null || methodName == null) { return null; } Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } try { return (E) method.invoke(obj, args); } catch (Exception e) { String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; throw convertReflectionExceptionToUnchecked(msg, e); } } /** * 直接调用对象方法, 无视private/protected修饰符, * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用. * 只匹配函数名,如果有多个同名函数调用第一个。 */ @SuppressWarnings("unchecked") public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) { Method method = getAccessibleMethodByName(obj, methodName, args.length); if (method == null) { // 如果为空不报错,直接返回空。 logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); return null; } try { // 类型转换(将参数数据类型转换为目标方法参数类型) Class<?>[] cs = method.getParameterTypes(); for (int i = 0; i < cs.length; i++) { if (args[i] != null && !args[i].getClass().equals(cs[i])) { if (cs[i] == String.class) {
args[i] = Convert.toStr(args[i]);
0
2023-12-04 05:10:13+00:00
12k
ydb-platform/yoj-project
repository-ydb-v2/src/main/java/tech/ydb/yoj/repository/ydb/yql/YqlPrimitiveType.java
[ { "identifier": "FieldValueType", "path": "databind/src/main/java/tech/ydb/yoj/databind/FieldValueType.java", "snippet": "public enum FieldValueType {\n /**\n * Integer value.\n * Java-side <strong>must</strong> either be a numeric primitive, or extend {@link Number java.lang.Number} and\n ...
import com.google.common.primitives.Primitives; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors; import com.google.protobuf.UnsafeByteOperations; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.Value; import lombok.With; import tech.ydb.proto.ValueProtos; import tech.ydb.proto.ValueProtos.Type.PrimitiveTypeId; import tech.ydb.proto.ValueProtos.Value.ValueCase; import tech.ydb.table.values.proto.ProtoValue; import tech.ydb.yoj.databind.FieldValueType; import tech.ydb.yoj.databind.schema.Column; import tech.ydb.yoj.databind.schema.Schema.JavaField; import tech.ydb.yoj.repository.DbTypeQualifier; import tech.ydb.yoj.repository.db.common.CommonConverters; import tech.ydb.yoj.repository.db.exception.ConversionException; import tech.ydb.yoj.util.lang.BetterCollectors; import java.lang.reflect.Type; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import static java.lang.String.format; import static lombok.AccessLevel.PRIVATE; import static tech.ydb.yoj.repository.db.common.CommonConverters.enumToStringValueGetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.enumToStringValueSetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.enumValueGetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.enumValueSetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.opaqueObjectValueGetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.opaqueObjectValueSetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.stringValueGetter; import static tech.ydb.yoj.repository.db.common.CommonConverters.stringValueSetter;
8,600
package tech.ydb.yoj.repository.ydb.yql; @Value @AllArgsConstructor(access = PRIVATE) public class YqlPrimitiveType implements YqlType { // Only table column data types. See https://ydb.tech/en/docs/yql/reference/types/ private static final Map<PrimitiveTypeId, String> YQL_TYPE_NAMES = Map.ofEntries( Map.entry(PrimitiveTypeId.BOOL, "Bool"), Map.entry(PrimitiveTypeId.UINT8, "Uint8"), Map.entry(PrimitiveTypeId.INT32, "Int32"), Map.entry(PrimitiveTypeId.UINT32, "Uint32"), Map.entry(PrimitiveTypeId.INT64, "Int64"), Map.entry(PrimitiveTypeId.UINT64, "Uint64"), Map.entry(PrimitiveTypeId.FLOAT, "Float"), Map.entry(PrimitiveTypeId.DOUBLE, "Double"), Map.entry(PrimitiveTypeId.DATE, "Date"), Map.entry(PrimitiveTypeId.DATETIME, "Datetime"), Map.entry(PrimitiveTypeId.TIMESTAMP, "Timestamp"), Map.entry(PrimitiveTypeId.INTERVAL, "Interval"), Map.entry(PrimitiveTypeId.STRING, "String"), Map.entry(PrimitiveTypeId.UTF8, "Utf8"), Map.entry(PrimitiveTypeId.JSON, "Json"), Map.entry(PrimitiveTypeId.JSON_DOCUMENT, "JsonDocument") ); private static final Setter BOOL_SETTER = (b, v) -> b.setBoolValue((Boolean) v); private static final Setter BYTE_SETTER = (b, v) -> b.setInt32Value(((Number) v).byteValue()); private static final Setter BYTE_UINT_SETTER = (b, v) -> b.setUint32Value(((Number) v).byteValue()); private static final Setter SHORT_SETTER = (b, v) -> b.setInt32Value(((Number) v).shortValue()); private static final Setter INT_SETTER = (b, v) -> b.setInt32Value(((Number) v).intValue()); private static final Setter UINT_SETTER = (b, v) -> b.setUint32Value(((Number) v).intValue()); private static final Setter LONG_SETTER = (b, v) -> b.setInt64Value(((Number) v).longValue()); private static final Setter ULONG_SETTER = (b, v) -> b.setUint64Value(((Number) v).longValue()); private static final Setter FLOAT_SETTER = (b, v) -> b.setFloatValue(((Number) v).floatValue()); private static final Setter DOUBLE_SETTER = (b, v) -> b.setDoubleValue(((Number) v).doubleValue()); private static final Setter STRING_SETTER = (b, v) -> b.setBytesValue(ByteString.copyFromUtf8((String) v)); private static final Setter TEXT_SETTER = (b, v) -> b.setTextValue((String) v); private static final Setter BYTES_SETTER = (b, v) -> b.setBytesValue(UnsafeByteOperations.unsafeWrap((byte[]) v)); private static final Setter INSTANT_SETTER = (b, v) -> b.setInt64Value(((Instant) v).toEpochMilli()); private static final Setter INSTANT_UINT_SETTER = (b, v) -> b.setUint64Value(((Instant) v).toEpochMilli()); private static final Setter INSTANT_SECOND_SETTER = (b, v) -> b.setInt64Value(((Instant) v).getEpochSecond()); private static final Setter INSTANT_UINT_SECOND_SETTER = (b, v) -> b.setUint64Value(((Instant) v).getEpochSecond()); private static final Setter TIMESTAMP_SETTER = (b, v) -> b.setUint64Value(ProtoValue.fromTimestamp((Instant) v).getUint64Value()); private static final Setter DURATION_SETTER = (b, v) -> b.setInt64Value(ProtoValue.fromInterval((Duration) v).getInt64Value()); private static final Setter DURATION_UINT_SETTER = (b, v) -> b.setUint64Value(ProtoValue.fromInterval((Duration) v).getInt64Value()); private static final Setter DURATION_MILLI_SETTER = (b, v) -> b.setInt64Value(((Duration) v).toMillis()); private static final Setter DURATION_MILLI_UINT_SETTER = (b, v) -> b.setUint64Value(((Duration) v).toMillis()); private static final Setter DURATION_SECOND_SETTER = (b, v) -> b.setInt32Value(Math.toIntExact(((Duration) v).toSeconds())); private static final Setter DURATION_SECOND_UINT_SETTER = (b, v) -> b.setUint32Value(Math.toIntExact(((Duration) v).toSeconds())); private static final Setter DURATION_UTF8_SETTER = (b, v) -> b.setTextValue(((Duration) v).truncatedTo(ChronoUnit.MICROS).toString());
package tech.ydb.yoj.repository.ydb.yql; @Value @AllArgsConstructor(access = PRIVATE) public class YqlPrimitiveType implements YqlType { // Only table column data types. See https://ydb.tech/en/docs/yql/reference/types/ private static final Map<PrimitiveTypeId, String> YQL_TYPE_NAMES = Map.ofEntries( Map.entry(PrimitiveTypeId.BOOL, "Bool"), Map.entry(PrimitiveTypeId.UINT8, "Uint8"), Map.entry(PrimitiveTypeId.INT32, "Int32"), Map.entry(PrimitiveTypeId.UINT32, "Uint32"), Map.entry(PrimitiveTypeId.INT64, "Int64"), Map.entry(PrimitiveTypeId.UINT64, "Uint64"), Map.entry(PrimitiveTypeId.FLOAT, "Float"), Map.entry(PrimitiveTypeId.DOUBLE, "Double"), Map.entry(PrimitiveTypeId.DATE, "Date"), Map.entry(PrimitiveTypeId.DATETIME, "Datetime"), Map.entry(PrimitiveTypeId.TIMESTAMP, "Timestamp"), Map.entry(PrimitiveTypeId.INTERVAL, "Interval"), Map.entry(PrimitiveTypeId.STRING, "String"), Map.entry(PrimitiveTypeId.UTF8, "Utf8"), Map.entry(PrimitiveTypeId.JSON, "Json"), Map.entry(PrimitiveTypeId.JSON_DOCUMENT, "JsonDocument") ); private static final Setter BOOL_SETTER = (b, v) -> b.setBoolValue((Boolean) v); private static final Setter BYTE_SETTER = (b, v) -> b.setInt32Value(((Number) v).byteValue()); private static final Setter BYTE_UINT_SETTER = (b, v) -> b.setUint32Value(((Number) v).byteValue()); private static final Setter SHORT_SETTER = (b, v) -> b.setInt32Value(((Number) v).shortValue()); private static final Setter INT_SETTER = (b, v) -> b.setInt32Value(((Number) v).intValue()); private static final Setter UINT_SETTER = (b, v) -> b.setUint32Value(((Number) v).intValue()); private static final Setter LONG_SETTER = (b, v) -> b.setInt64Value(((Number) v).longValue()); private static final Setter ULONG_SETTER = (b, v) -> b.setUint64Value(((Number) v).longValue()); private static final Setter FLOAT_SETTER = (b, v) -> b.setFloatValue(((Number) v).floatValue()); private static final Setter DOUBLE_SETTER = (b, v) -> b.setDoubleValue(((Number) v).doubleValue()); private static final Setter STRING_SETTER = (b, v) -> b.setBytesValue(ByteString.copyFromUtf8((String) v)); private static final Setter TEXT_SETTER = (b, v) -> b.setTextValue((String) v); private static final Setter BYTES_SETTER = (b, v) -> b.setBytesValue(UnsafeByteOperations.unsafeWrap((byte[]) v)); private static final Setter INSTANT_SETTER = (b, v) -> b.setInt64Value(((Instant) v).toEpochMilli()); private static final Setter INSTANT_UINT_SETTER = (b, v) -> b.setUint64Value(((Instant) v).toEpochMilli()); private static final Setter INSTANT_SECOND_SETTER = (b, v) -> b.setInt64Value(((Instant) v).getEpochSecond()); private static final Setter INSTANT_UINT_SECOND_SETTER = (b, v) -> b.setUint64Value(((Instant) v).getEpochSecond()); private static final Setter TIMESTAMP_SETTER = (b, v) -> b.setUint64Value(ProtoValue.fromTimestamp((Instant) v).getUint64Value()); private static final Setter DURATION_SETTER = (b, v) -> b.setInt64Value(ProtoValue.fromInterval((Duration) v).getInt64Value()); private static final Setter DURATION_UINT_SETTER = (b, v) -> b.setUint64Value(ProtoValue.fromInterval((Duration) v).getInt64Value()); private static final Setter DURATION_MILLI_SETTER = (b, v) -> b.setInt64Value(((Duration) v).toMillis()); private static final Setter DURATION_MILLI_UINT_SETTER = (b, v) -> b.setUint64Value(((Duration) v).toMillis()); private static final Setter DURATION_SECOND_SETTER = (b, v) -> b.setInt32Value(Math.toIntExact(((Duration) v).toSeconds())); private static final Setter DURATION_SECOND_UINT_SETTER = (b, v) -> b.setUint32Value(Math.toIntExact(((Duration) v).toSeconds())); private static final Setter DURATION_UTF8_SETTER = (b, v) -> b.setTextValue(((Duration) v).truncatedTo(ChronoUnit.MICROS).toString());
private static final Function<Type, Setter> ENUM_NAME_STRING_SETTERS = type -> enumValueSetter(type, STRING_SETTER)::accept;
9
2023-12-05 15:57:58+00:00
12k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/JREUtils.java
[ { "identifier": "ARCH_X86", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java", "snippet": "public static final int ARCH_X86 = 0x4;" }, { "identifier": "is64BitsDevice", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java", "snippet...
import static net.kdt.pojavlaunch.Architecture.ARCH_X86; import static net.kdt.pojavlaunch.Architecture.is64BitsDevice; import static net.kdt.pojavlaunch.Tools.LOCAL_RENDERER; import static net.kdt.pojavlaunch.Tools.NATIVE_LIB_DIR; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.Tools.shareLog; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.*; import android.app.*; import android.content.*; import android.os.Build; import android.system.*; import android.util.*; import android.widget.Toast; import com.oracle.dalvik.*; import java.io.*; import java.util.*; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.plugins.FFmpegPlugin; import net.kdt.pojavlaunch.prefs.*; import org.lwjgl.glfw.*; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay;
8,821
returnValue.addAll(locateLibs(f)); } } } return returnValue; } public static void initJavaRuntime(String jreHome) { dlopen(findInLdLibPath("libjli.so")); if(!dlopen("libjvm.so")){ Log.w("DynamicLoader","Failed to load with no path, trying with full path"); dlopen(jvmLibraryPath+"/libjvm.so"); } dlopen(findInLdLibPath("libverify.so")); dlopen(findInLdLibPath("libjava.so")); // dlopen(findInLdLibPath("libjsig.so")); dlopen(findInLdLibPath("libnet.so")); dlopen(findInLdLibPath("libnio.so")); dlopen(findInLdLibPath("libawt.so")); dlopen(findInLdLibPath("libawt_headless.so")); dlopen(findInLdLibPath("libfreetype.so")); dlopen(findInLdLibPath("libfontmanager.so")); for(File f : locateLibs(new File(jreHome, Tools.DIRNAME_HOME_JRE))) { dlopen(f.getAbsolutePath()); } dlopen(NATIVE_LIB_DIR + "/libopenal.so"); } public static void redirectAndPrintJRELog() { Log.v("jrelog","Log starts here"); new Thread(new Runnable(){ int failTime = 0; ProcessBuilder logcatPb; @Override public void run() { try { if (logcatPb == null) { logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true); } Log.i("jrelog-logcat","Clearing logcat"); new ProcessBuilder().command("logcat", "-c").redirectErrorStream(true).start(); Log.i("jrelog-logcat","Starting logcat"); java.lang.Process p = logcatPb.start(); byte[] buf = new byte[1024]; int len; while ((len = p.getInputStream().read(buf)) != -1) { String currStr = new String(buf, 0, len); Logger.appendToLog(currStr); } if (p.waitFor() != 0) { Log.e("jrelog-logcat", "Logcat exited with code " + p.exitValue()); failTime++; Log.i("jrelog-logcat", (failTime <= 10 ? "Restarting logcat" : "Too many restart fails") + " (attempt " + failTime + "/10"); if (failTime <= 10) { run(); } else { Logger.appendToLog("ERROR: Unable to get more log."); } } } catch (Throwable e) { Log.e("jrelog-logcat", "Exception on logging thread", e); Logger.appendToLog("Exception on logging thread:\n" + Log.getStackTraceString(e)); } } }).start(); Log.i("jrelog-logcat","Logcat thread started"); } public static void relocateLibPath(Runtime runtime, String jreHome) { String JRE_ARCHITECTURE = runtime.arch; if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){ JRE_ARCHITECTURE = "i386/i486/i586"; } for (String arch : JRE_ARCHITECTURE.split("/")) { File f = new File(jreHome, "lib/" + arch); if (f.exists() && f.isDirectory()) { Tools.DIRNAME_HOME_JRE = "lib/" + arch; } } String libName = is64BitsDevice() ? "lib64" : "lib"; StringBuilder ldLibraryPath = new StringBuilder(); if(FFmpegPlugin.isAvailable) { ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":"); } ldLibraryPath.append(jreHome) .append("/").append(Tools.DIRNAME_HOME_JRE) .append("/jli:").append(jreHome).append("/").append(Tools.DIRNAME_HOME_JRE) .append(":"); ldLibraryPath.append("/system/").append(libName).append(":") .append("/vendor/").append(libName).append(":") .append("/vendor/").append(libName).append("/hw:") .append(NATIVE_LIB_DIR); LD_LIBRARY_PATH = ldLibraryPath.toString(); } public static void setJavaEnvironment(Activity activity, String jreHome) throws Throwable { Map<String, String> envMap = new ArrayMap<>(); envMap.put("POJAV_NATIVEDIR", NATIVE_LIB_DIR); envMap.put("JAVA_HOME", jreHome); envMap.put("HOME", Tools.DIR_GAME_HOME); envMap.put("TMPDIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("LIBGL_MIPMAP", "3"); // Prevent OptiFine (and other error-reporting stuff in Minecraft) from balooning the log envMap.put("LIBGL_NOERROR", "1"); // On certain GLES drivers, overloading default functions shader hack fails, so disable it envMap.put("LIBGL_NOINTOVLHACK", "1"); // Fix white color on banner and sheep, since GL4ES 1.1.5 envMap.put("LIBGL_NORMALIZE", "1"); // The OPEN GL version is changed according
package net.kdt.pojavlaunch.utils; public class JREUtils { private JREUtils() {} public static String LD_LIBRARY_PATH; public static String jvmLibraryPath; public static String findInLdLibPath(String libName) { if(Os.getenv("LD_LIBRARY_PATH")==null) { try { if (LD_LIBRARY_PATH != null) { Os.setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, true); } }catch (ErrnoException e) { e.printStackTrace(); } return libName; } for (String libPath : Os.getenv("LD_LIBRARY_PATH").split(":")) { File f = new File(libPath, libName); if (f.exists() && f.isFile()) { return f.getAbsolutePath(); } } return libName; } public static ArrayList<File> locateLibs(File path) { ArrayList<File> returnValue = new ArrayList<>(); File[] list = path.listFiles(); if(list != null) { for(File f : list) { if(f.isFile() && f.getName().endsWith(".so")) { returnValue.add(f); }else if(f.isDirectory()) { returnValue.addAll(locateLibs(f)); } } } return returnValue; } public static void initJavaRuntime(String jreHome) { dlopen(findInLdLibPath("libjli.so")); if(!dlopen("libjvm.so")){ Log.w("DynamicLoader","Failed to load with no path, trying with full path"); dlopen(jvmLibraryPath+"/libjvm.so"); } dlopen(findInLdLibPath("libverify.so")); dlopen(findInLdLibPath("libjava.so")); // dlopen(findInLdLibPath("libjsig.so")); dlopen(findInLdLibPath("libnet.so")); dlopen(findInLdLibPath("libnio.so")); dlopen(findInLdLibPath("libawt.so")); dlopen(findInLdLibPath("libawt_headless.so")); dlopen(findInLdLibPath("libfreetype.so")); dlopen(findInLdLibPath("libfontmanager.so")); for(File f : locateLibs(new File(jreHome, Tools.DIRNAME_HOME_JRE))) { dlopen(f.getAbsolutePath()); } dlopen(NATIVE_LIB_DIR + "/libopenal.so"); } public static void redirectAndPrintJRELog() { Log.v("jrelog","Log starts here"); new Thread(new Runnable(){ int failTime = 0; ProcessBuilder logcatPb; @Override public void run() { try { if (logcatPb == null) { logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true); } Log.i("jrelog-logcat","Clearing logcat"); new ProcessBuilder().command("logcat", "-c").redirectErrorStream(true).start(); Log.i("jrelog-logcat","Starting logcat"); java.lang.Process p = logcatPb.start(); byte[] buf = new byte[1024]; int len; while ((len = p.getInputStream().read(buf)) != -1) { String currStr = new String(buf, 0, len); Logger.appendToLog(currStr); } if (p.waitFor() != 0) { Log.e("jrelog-logcat", "Logcat exited with code " + p.exitValue()); failTime++; Log.i("jrelog-logcat", (failTime <= 10 ? "Restarting logcat" : "Too many restart fails") + " (attempt " + failTime + "/10"); if (failTime <= 10) { run(); } else { Logger.appendToLog("ERROR: Unable to get more log."); } } } catch (Throwable e) { Log.e("jrelog-logcat", "Exception on logging thread", e); Logger.appendToLog("Exception on logging thread:\n" + Log.getStackTraceString(e)); } } }).start(); Log.i("jrelog-logcat","Logcat thread started"); } public static void relocateLibPath(Runtime runtime, String jreHome) { String JRE_ARCHITECTURE = runtime.arch; if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){ JRE_ARCHITECTURE = "i386/i486/i586"; } for (String arch : JRE_ARCHITECTURE.split("/")) { File f = new File(jreHome, "lib/" + arch); if (f.exists() && f.isDirectory()) { Tools.DIRNAME_HOME_JRE = "lib/" + arch; } } String libName = is64BitsDevice() ? "lib64" : "lib"; StringBuilder ldLibraryPath = new StringBuilder(); if(FFmpegPlugin.isAvailable) { ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":"); } ldLibraryPath.append(jreHome) .append("/").append(Tools.DIRNAME_HOME_JRE) .append("/jli:").append(jreHome).append("/").append(Tools.DIRNAME_HOME_JRE) .append(":"); ldLibraryPath.append("/system/").append(libName).append(":") .append("/vendor/").append(libName).append(":") .append("/vendor/").append(libName).append("/hw:") .append(NATIVE_LIB_DIR); LD_LIBRARY_PATH = ldLibraryPath.toString(); } public static void setJavaEnvironment(Activity activity, String jreHome) throws Throwable { Map<String, String> envMap = new ArrayMap<>(); envMap.put("POJAV_NATIVEDIR", NATIVE_LIB_DIR); envMap.put("JAVA_HOME", jreHome); envMap.put("HOME", Tools.DIR_GAME_HOME); envMap.put("TMPDIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("LIBGL_MIPMAP", "3"); // Prevent OptiFine (and other error-reporting stuff in Minecraft) from balooning the log envMap.put("LIBGL_NOERROR", "1"); // On certain GLES drivers, overloading default functions shader hack fails, so disable it envMap.put("LIBGL_NOINTOVLHACK", "1"); // Fix white color on banner and sheep, since GL4ES 1.1.5 envMap.put("LIBGL_NORMALIZE", "1"); // The OPEN GL version is changed according
envMap.put("LIBGL_ES", (String) ExtraCore.getValue(ExtraConstants.OPEN_GL_VERSION));
7
2023-12-01 16:16:12+00:00
12k
kawashirov/distant-horizons
forge/src/main/java/com/seibel/distanthorizons/forge/ForgeClientProxy.java
[ { "identifier": "ProxyUtil", "path": "common/src/main/java/com/seibel/distanthorizons/common/util/ProxyUtil.java", "snippet": "public class ProxyUtil\n{\n\t\n\tpublic static ILevelWrapper getLevelWrapper(LevelAccessor level)\n\t{\n\t\tILevelWrapper levelWrapper;\n\t\tif (level instanceof ServerLevel)\n\...
import com.seibel.distanthorizons.common.util.ProxyUtil; import com.seibel.distanthorizons.common.wrappers.minecraft.MinecraftRenderWrapper; import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper; import com.seibel.distanthorizons.core.api.internal.ClientApi; import com.seibel.distanthorizons.core.api.internal.SharedApi; import com.seibel.distanthorizons.core.dependencyInjection.SingletonInjector; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IMinecraftClientWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.ILevelWrapper; import com.seibel.distanthorizons.coreapi.ModInfo; import net.minecraft.world.level.LevelAccessor; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.event.level.ChunkEvent; import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.client.event.RenderLevelStageEvent; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.glfw.GLFW; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import org.lwjgl.opengl.GL32;
10,245
/* * 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.forge; //import io.netty.buffer.ByteBuf; #if PRE_MC_1_19_2 #else #endif #if POST_MC_1_18_2 #endif import net.minecraftforge.event.entity.player.PlayerInteractEvent; //import net.minecraftforge.network.NetworkRegistry; //import net.minecraftforge.network.simple.SimpleChannel; /** * This handles all events sent to the client, * and is the starting point for most of the mod. * * @author James_Seibel * @version 2023-7-27 */ public class ForgeClientProxy { private static final IMinecraftClientWrapper MC = SingletonInjector.INSTANCE.get(IMinecraftClientWrapper.class); private static final Logger LOGGER = DhLoggerBuilder.getLogger(); // private static SimpleChannel multiversePluginChannel; #if PRE_MC_1_19_2 private static LevelAccessor GetEventLevel(WorldEvent e) { return e.getWorld(); } #else private static LevelAccessor GetEventLevel(LevelEvent e) { return e.getLevel(); } #endif //=============// // tick events // //=============// @SubscribeEvent public void clientTickEvent(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START) { ClientApi.INSTANCE.clientTickEvent(); } } //==============// // world events // //==============// @SubscribeEvent #if PRE_MC_1_19_2 public void clientLevelLoadEvent(WorldEvent.Load event) #else public void clientLevelLoadEvent(LevelEvent.Load event) #endif { LOGGER.info("level load"); #if PRE_MC_1_19_2 LevelAccessor level = event.getWorld(); #else LevelAccessor level = event.getLevel(); #endif if (!(level instanceof ClientLevel)) { return; } ClientLevel clientLevel = (ClientLevel) level;
/* * 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.forge; //import io.netty.buffer.ByteBuf; #if PRE_MC_1_19_2 #else #endif #if POST_MC_1_18_2 #endif import net.minecraftforge.event.entity.player.PlayerInteractEvent; //import net.minecraftforge.network.NetworkRegistry; //import net.minecraftforge.network.simple.SimpleChannel; /** * This handles all events sent to the client, * and is the starting point for most of the mod. * * @author James_Seibel * @version 2023-7-27 */ public class ForgeClientProxy { private static final IMinecraftClientWrapper MC = SingletonInjector.INSTANCE.get(IMinecraftClientWrapper.class); private static final Logger LOGGER = DhLoggerBuilder.getLogger(); // private static SimpleChannel multiversePluginChannel; #if PRE_MC_1_19_2 private static LevelAccessor GetEventLevel(WorldEvent e) { return e.getWorld(); } #else private static LevelAccessor GetEventLevel(LevelEvent e) { return e.getLevel(); } #endif //=============// // tick events // //=============// @SubscribeEvent public void clientTickEvent(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START) { ClientApi.INSTANCE.clientTickEvent(); } } //==============// // world events // //==============// @SubscribeEvent #if PRE_MC_1_19_2 public void clientLevelLoadEvent(WorldEvent.Load event) #else public void clientLevelLoadEvent(LevelEvent.Load event) #endif { LOGGER.info("level load"); #if PRE_MC_1_19_2 LevelAccessor level = event.getWorld(); #else LevelAccessor level = event.getLevel(); #endif if (!(level instanceof ClientLevel)) { return; } ClientLevel clientLevel = (ClientLevel) level;
IClientLevelWrapper clientLevelWrapper = ClientLevelWrapper.getWrapper(clientLevel);
2
2023-12-04 11:41:46+00:00
12k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/generators/JurorPoolGeneratorUtil.java
[ { "identifier": "ExcusableCode", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ExcusableCode.java", "snippet": "@Getter\npublic enum ExcusableCode {\n\n CRIMINAL_RECORD(\"K\"),\n DECEASED(\"D\"),\n OVER_69(\"V\"),\n RECENTLY_SERVED(\"S\"),\n THE_FORCES(\"F\"),\n MEDICAL_...
import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.sql.entity.ExcusableCode; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.service.SqlSupportService; import java.time.LocalDate; import java.util.Arrays;
7,408
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList())); jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now())); //Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool return jurorPoolGenerator; } public static JurorPoolGenerator reassigned(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false)); return jurorPoolGenerator; } public static JurorPoolGenerator transferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setTransferDate( new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now()) ); return jurorPoolGenerator; } public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO); } public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND); generator.setNoAttendances(new FixedValueGeneratorImpl<>(0)); generator.setNoAttended(new FixedValueGeneratorImpl<>(0)); return generator; } public static JurorPoolGenerator completed(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED); generator.setNextDate(new NullValueGeneratorImpl<>()); return generator; } private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) { JurorPoolGenerator generator = new JurorPoolGenerator(); generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId())); if (isCourtOwned) {
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList())); jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now())); //Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool return jurorPoolGenerator; } public static JurorPoolGenerator reassigned(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false)); return jurorPoolGenerator; } public static JurorPoolGenerator transferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setTransferDate( new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now()) ); return jurorPoolGenerator; } public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO); } public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND); generator.setNoAttendances(new FixedValueGeneratorImpl<>(0)); generator.setNoAttended(new FixedValueGeneratorImpl<>(0)); return generator; } public static JurorPoolGenerator completed(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED); generator.setNextDate(new NullValueGeneratorImpl<>()); return generator; } private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) { JurorPoolGenerator generator = new JurorPoolGenerator(); generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId())); if (isCourtOwned) {
generator.setOwner(new RandomFromCollectionGeneratorImpl<>(SqlSupportService.getCourtOwners()));
4
2023-12-01 11:38:42+00:00
12k
vvbbnn00/JavaWeb-CanteenSystem
JavaBackend/src/main/java/cn/vvbbnn00/canteen/controller/rest/UserResource.java
[ { "identifier": "UserChangePasswordRequest", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dto/request/UserChangePasswordRequest.java", "snippet": "@Data\n@JavaBean\npublic class UserChangePasswordRequest {\n @NotBlank(message = \"旧密码不能为空\")\n private String oldPassword;\n\n @NotBlank(...
import cn.vvbbnn00.canteen.annotation.CheckRole; import cn.vvbbnn00.canteen.dto.request.UserChangePasswordRequest; import cn.vvbbnn00.canteen.dto.request.UserListRequest; import cn.vvbbnn00.canteen.dto.response.BasicDataResponse; import cn.vvbbnn00.canteen.dto.response.BasicListResponse; import cn.vvbbnn00.canteen.dto.response.BasicResponse; import cn.vvbbnn00.canteen.model.User; import cn.vvbbnn00.canteen.service.UserService; import cn.vvbbnn00.canteen.util.RequestValidatorUtils; import jakarta.enterprise.context.RequestScoped; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext;
7,884
package cn.vvbbnn00.canteen.controller.rest; @Path("/user") @RequestScoped public class UserResource { @Context SecurityContext securityContext; UserService userService = new UserService(); @POST @Path("/list") @Produces(MediaType.APPLICATION_JSON) @CheckRole("admin") public BasicListResponse restListUser( UserListRequest userListRequest ) { RequestValidatorUtils.doHibernateValidate(userListRequest); BasicListResponse response = new BasicListResponse(); response.setList(userService.getUserList( userListRequest.getCurrentPage(), userListRequest.getPageSize(), userListRequest.getKw(), userListRequest.getAvailable(), userListRequest.getRole(), userListRequest.getIsVerified(), userListRequest.getOrderBy(), userListRequest.getAsc() )); response.setTotal(userService.getUserListCount( userListRequest.getKw(), userListRequest.getAvailable(), userListRequest.getRole(), userListRequest.getIsVerified() )); response.setPageSize(userListRequest.getPageSize()); response.setCurrentPage(userListRequest.getCurrentPage()); return response; } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @CheckRole("admin") public BasicDataResponse restPostUser(User user) { // 校验请求参数 RequestValidatorUtils.doHibernateValidate(user); BasicDataResponse response = new BasicDataResponse(); try { response.setData(userService.createUser(user)); } catch (Exception e) { response.setCode(409); response.setMessage(e.getMessage()); } return response; } @GET @Path("/me") @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicDataResponse restGetMe() { Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); BasicDataResponse response = new BasicDataResponse(); User user = userService.getUserById(userId); response.setData(user); return response; } @POST @Path("/me/verify") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicResponse restVerifyMe( User verifyRequest ) { RequestValidatorUtils.doHibernateValidate(verifyRequest); Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); BasicResponse response = new BasicResponse(); try { userService.verifyUser(userId, verifyRequest.getEmployeeId(), verifyRequest.getName()); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @PUT @Path("/me/password") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicResponse restChangePassword(
package cn.vvbbnn00.canteen.controller.rest; @Path("/user") @RequestScoped public class UserResource { @Context SecurityContext securityContext; UserService userService = new UserService(); @POST @Path("/list") @Produces(MediaType.APPLICATION_JSON) @CheckRole("admin") public BasicListResponse restListUser( UserListRequest userListRequest ) { RequestValidatorUtils.doHibernateValidate(userListRequest); BasicListResponse response = new BasicListResponse(); response.setList(userService.getUserList( userListRequest.getCurrentPage(), userListRequest.getPageSize(), userListRequest.getKw(), userListRequest.getAvailable(), userListRequest.getRole(), userListRequest.getIsVerified(), userListRequest.getOrderBy(), userListRequest.getAsc() )); response.setTotal(userService.getUserListCount( userListRequest.getKw(), userListRequest.getAvailable(), userListRequest.getRole(), userListRequest.getIsVerified() )); response.setPageSize(userListRequest.getPageSize()); response.setCurrentPage(userListRequest.getCurrentPage()); return response; } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @CheckRole("admin") public BasicDataResponse restPostUser(User user) { // 校验请求参数 RequestValidatorUtils.doHibernateValidate(user); BasicDataResponse response = new BasicDataResponse(); try { response.setData(userService.createUser(user)); } catch (Exception e) { response.setCode(409); response.setMessage(e.getMessage()); } return response; } @GET @Path("/me") @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicDataResponse restGetMe() { Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); BasicDataResponse response = new BasicDataResponse(); User user = userService.getUserById(userId); response.setData(user); return response; } @POST @Path("/me/verify") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicResponse restVerifyMe( User verifyRequest ) { RequestValidatorUtils.doHibernateValidate(verifyRequest); Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); BasicResponse response = new BasicResponse(); try { userService.verifyUser(userId, verifyRequest.getEmployeeId(), verifyRequest.getName()); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @PUT @Path("/me/password") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicResponse restChangePassword(
UserChangePasswordRequest changePasswordRequest
0
2023-12-01 04:55:12+00:00
12k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/DeathManager.java
[ { "identifier": "LevelBoundVec3", "path": "src/main/java/net/superricky/tpaplusplus/util/LevelBoundVec3.java", "snippet": "public class LevelBoundVec3 extends Vec3 {\n private final ServerLevel serverLevel;\n\n public LevelBoundVec3(ServerLevel serverLevel, double pX, double pY, double pZ) {\n ...
import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.superricky.tpaplusplus.util.LevelBoundVec3; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Objects;
10,192
package net.superricky.tpaplusplus.util.manager; public class DeathManager { static final Map<ServerPlayer, LevelBoundVec3> playerDeathCoordinates = new HashMap<>(); private DeathManager() { } public static void teleportToLatestDeath(ServerPlayer executor) { if (Boolean.FALSE.equals(Config.BACK_COMMAND_ENABLED.get())) {
package net.superricky.tpaplusplus.util.manager; public class DeathManager { static final Map<ServerPlayer, LevelBoundVec3> playerDeathCoordinates = new HashMap<>(); private DeathManager() { } public static void teleportToLatestDeath(ServerPlayer executor) { if (Boolean.FALSE.equals(Config.BACK_COMMAND_ENABLED.get())) {
executor.sendSystemMessage(Component.literal(Messages.ERR_BACK_COMMAND_DISABLED.get()));
2
2023-12-02 05:41:24+00:00
12k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/helpers/LocationHelper.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.os.Looper; import androidx.core.content.ContextCompat; import androidx.preference.PreferenceManager; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.ui.settings.SettingsActivity; import android.Manifest; import android.content.AsyncQueryHandler; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle;
10,711
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.helpers; public class LocationHelper extends AsyncQueryHandler implements LocationListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LocationHelper.class.getName(); public static final LocationHelper helper = new LocationHelper(); private static final long MIN_TIME_DEF = 5; // for now every 5 minutes private static final long MIN_TIME_FACTOR = 1000 * 60; private static final float MIN_DISTANCE_DEF = 50.0f; private long minTime; private float minDist; private String setting; private Location currentLocation; LocationManager locationManager = (LocationManager) ActivityDiaryApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public LocationHelper() { super(ActivityDiaryApplication.getAppContext().getContentResolver()); currentLocation = new Location("DiaryLocation"); updatePreferences(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } public Location getCurrentLocation(){ return currentLocation; } void updateLocation() { if (setting.equals("off")) { // do nothing } else { int permissionCheckFine = PackageManager.PERMISSION_DENIED; int permissionCheckCoarse = PackageManager.PERMISSION_DENIED; if(setting.equals("gps") && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) { permissionCheckFine = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION); permissionCheckCoarse = permissionCheckFine; }else if(locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)){ permissionCheckCoarse = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION); } if(permissionCheckFine == PackageManager.PERMISSION_GRANTED){ String locationProvider = LocationManager.GPS_PROVIDER; locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper()); }else if(permissionCheckCoarse == PackageManager.PERMISSION_GRANTED){ String locationProvider = LocationManager.NETWORK_PROVIDER; locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper()); } } } /** * Called when the location has changed. * <p> * <p> There are no restrictions on the use of the supplied Location object. * * @param location The new location, as a Location object. */ @Override public void onLocationChanged(Location location) { ContentValues values = new ContentValues(); currentLocation = location; values.put(ActivityDiaryContract.DiaryLocation.TIMESTAMP, location.getTime()); values.put(ActivityDiaryContract.DiaryLocation.LATITUDE, location.getLatitude()); values.put(ActivityDiaryContract.DiaryLocation.LONGITUDE, location.getLongitude()); if (location.hasAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.HACC, new Integer(Math.round(location.getAccuracy() * 10))); } if (location.hasSpeed()) { values.put(ActivityDiaryContract.DiaryLocation.SPEED, location.getSpeed()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (location.hasSpeedAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.SACC, new Integer(Math.round(location.getSpeedAccuracyMetersPerSecond() * 10))); } } } if (location.hasAltitude()) { values.put(ActivityDiaryContract.DiaryLocation.ALTITUDE, location.getAltitude()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (location.hasVerticalAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.VACC, new Integer(Math.round(location.getVerticalAccuracyMeters() * 10))); } } } startInsert(0, null, ActivityDiaryContract.DiaryLocation.CONTENT_URI, values); } /** * Called when the provider status changes. This method is called when * a provider is unable to fetch a location or if the provider has recently * become available after a period of unavailability. * * @param provider the name of the location provider associated with this * update. * @param status {@link LocationProvider#OUT_OF_SERVICE} if the * provider is out of service, and this is not expected to change in the * near future; {@link LocationProvider#TEMPORARILY_UNAVAILABLE} if * the provider is temporarily unavailable but is expected to be available * shortly; and {@link LocationProvider#AVAILABLE} if the * provider is currently available. * @param extras an optional Bundle which will contain provider specific * status variables. * <p> * <p> A number of common key/value pairs for the extras Bundle are listed * below. Providers that use any of the keys on this list must * provide the corresponding value as described below. * <p> * <ul> * <li> satellites - the number of satellites used to derive the fix */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { } /** * Called when the provider is enabled by the user. * * @param provider the name of the location provider associated with this * update. */ @Override public void onProviderEnabled(String provider) { } /** * Called when the provider is disabled by the user. If requestLocationUpdates * is called on an already disabled provider, this method is called * immediately. * * @param provider the name of the location provider associated with this * update. */ @Override public void onProviderDisabled(String provider) { } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.helpers; public class LocationHelper extends AsyncQueryHandler implements LocationListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LocationHelper.class.getName(); public static final LocationHelper helper = new LocationHelper(); private static final long MIN_TIME_DEF = 5; // for now every 5 minutes private static final long MIN_TIME_FACTOR = 1000 * 60; private static final float MIN_DISTANCE_DEF = 50.0f; private long minTime; private float minDist; private String setting; private Location currentLocation; LocationManager locationManager = (LocationManager) ActivityDiaryApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public LocationHelper() { super(ActivityDiaryApplication.getAppContext().getContentResolver()); currentLocation = new Location("DiaryLocation"); updatePreferences(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } public Location getCurrentLocation(){ return currentLocation; } void updateLocation() { if (setting.equals("off")) { // do nothing } else { int permissionCheckFine = PackageManager.PERMISSION_DENIED; int permissionCheckCoarse = PackageManager.PERMISSION_DENIED; if(setting.equals("gps") && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) { permissionCheckFine = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION); permissionCheckCoarse = permissionCheckFine; }else if(locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)){ permissionCheckCoarse = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION); } if(permissionCheckFine == PackageManager.PERMISSION_GRANTED){ String locationProvider = LocationManager.GPS_PROVIDER; locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper()); }else if(permissionCheckCoarse == PackageManager.PERMISSION_GRANTED){ String locationProvider = LocationManager.NETWORK_PROVIDER; locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper()); } } } /** * Called when the location has changed. * <p> * <p> There are no restrictions on the use of the supplied Location object. * * @param location The new location, as a Location object. */ @Override public void onLocationChanged(Location location) { ContentValues values = new ContentValues(); currentLocation = location; values.put(ActivityDiaryContract.DiaryLocation.TIMESTAMP, location.getTime()); values.put(ActivityDiaryContract.DiaryLocation.LATITUDE, location.getLatitude()); values.put(ActivityDiaryContract.DiaryLocation.LONGITUDE, location.getLongitude()); if (location.hasAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.HACC, new Integer(Math.round(location.getAccuracy() * 10))); } if (location.hasSpeed()) { values.put(ActivityDiaryContract.DiaryLocation.SPEED, location.getSpeed()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (location.hasSpeedAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.SACC, new Integer(Math.round(location.getSpeedAccuracyMetersPerSecond() * 10))); } } } if (location.hasAltitude()) { values.put(ActivityDiaryContract.DiaryLocation.ALTITUDE, location.getAltitude()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (location.hasVerticalAccuracy()) { values.put(ActivityDiaryContract.DiaryLocation.VACC, new Integer(Math.round(location.getVerticalAccuracyMeters() * 10))); } } } startInsert(0, null, ActivityDiaryContract.DiaryLocation.CONTENT_URI, values); } /** * Called when the provider status changes. This method is called when * a provider is unable to fetch a location or if the provider has recently * become available after a period of unavailability. * * @param provider the name of the location provider associated with this * update. * @param status {@link LocationProvider#OUT_OF_SERVICE} if the * provider is out of service, and this is not expected to change in the * near future; {@link LocationProvider#TEMPORARILY_UNAVAILABLE} if * the provider is temporarily unavailable but is expected to be available * shortly; and {@link LocationProvider#AVAILABLE} if the * provider is currently available. * @param extras an optional Bundle which will contain provider specific * status variables. * <p> * <p> A number of common key/value pairs for the extras Bundle are listed * below. Providers that use any of the keys on this list must * provide the corresponding value as described below. * <p> * <ul> * <li> satellites - the number of satellites used to derive the fix */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { } /** * Called when the provider is enabled by the user. * * @param provider the name of the location provider associated with this * update. */ @Override public void onProviderEnabled(String provider) { } /** * Called when the provider is disabled by the user. If requestLocationUpdates * is called on an already disabled provider, this method is called * immediately. * * @param provider the name of the location provider associated with this * update. */ @Override public void onProviderDisabled(String provider) { } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(SettingsActivity.KEY_PREF_USE_LOCATION)
2
2023-12-02 12:36:40+00:00
12k
RabbitHareLu/K-Tools
frontend/src/main/java/com/ktools/frontend/frame/JDBCConnectionFrame.java
[ { "identifier": "KToolsContext", "path": "warehouse/src/main/java/com/ktools/warehouse/KToolsContext.java", "snippet": "@Getter\npublic class KToolsContext {\n\n private static volatile KToolsContext INSTANCE;\n\n private final MybatisContext mybatisContext;\n\n private final Properties propert...
import com.ktools.warehouse.KToolsContext; import com.ktools.frontend.action.CancelDisposeFrameAction; import com.ktools.frontend.action.TestConnectionAction; import com.ktools.frontend.action.TreeJDBCNodeAction; import com.ktools.warehouse.api.DataSourceApi; import com.ktools.frontend.common.utils.BoxUtil; import com.ktools.frontend.component.ImageLoad; import com.ktools.frontend.component.Tree; import com.ktools.warehouse.exception.KToolException; import com.ktools.warehouse.manager.datasource.model.KDataSourceMetadata; import com.ktools.warehouse.mybatis.entity.TreeEntity; import com.ktools.frontend.panel.AdvancedPanel; import com.ktools.frontend.panel.RegularPanel; import lombok.Data; import lombok.extern.slf4j.Slf4j; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.*; import java.util.Objects;
7,621
package com.ktools.frontend.frame; /** * @author lsl * @version 1.0 * @date 2023年12月18日 17:34 */ @Slf4j @Data public class JDBCConnectionFrame extends JFrame { public static boolean openFlag = true; private static final int WIDTH = 600; private static final int HEIGHT = 700; private KDataSourceMetadata kDataSourceMetadata; private TreeEntity treeEntity; private TreePath treePath; private RegularPanel regularPanel; private AdvancedPanel advancedPanel; private JTextField nameField; private JTextField commentField; public JDBCConnectionFrame() { Tree instance = Tree.getInstance(); this.treePath = instance.getCurrentTreePath(); this.treeEntity = instance.getCurrentTreeEntity(treePath); try { this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType()); } catch (KToolException e) { throw new RuntimeException(e); } setTitle("编辑" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initEdit(); frameEndInit(); } public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) { Tree instance = Tree.getInstance(); this.kDataSourceMetadata = kDataSourceMetadata; this.treePath = instance.getCurrentTreePath(); setTitle("新建" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initNew(); frameEndInit(); } private void frameStartInit() { openFlag = false; setIconImage(ImageLoad.getInstance().buildIcon(kDataSourceMetadata.getLogo()).getImage()); setSize(WIDTH, HEIGHT); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setResizable(false); closeAction(); } private void frameEndInit() { setVisible(true); } private void initEdit() { if (Objects.nonNull(treeEntity)) { Box publicBox = Box.createVerticalBox(); BoxUtil.addVerticalStrut(publicBox, 30); nameField = initSubBox(publicBox, "名称: "); nameField.setText(treeEntity.getNodeName()); BoxUtil.addVerticalStrut(publicBox, 30); commentField = initSubBox(publicBox, "注释: "); commentField.setText(treeEntity.getNodeComment()); BoxUtil.addVerticalStrut(publicBox, 30); add(publicBox, BorderLayout.NORTH); Box tabBox = Box.createHorizontalBox(); BoxUtil.addHorizontalStrut(tabBox, 30); JTabbedPane tabbedPane = new JTabbedPane(); regularPanel = new RegularPanel(treeEntity); advancedPanel = new AdvancedPanel(treeEntity, kDataSourceMetadata); tabbedPane.addTab("常规", null, regularPanel, "常规"); tabbedPane.addTab("高级", null, advancedPanel, "高级"); tabBox.add(tabbedPane); BoxUtil.addHorizontalStrut(tabBox, 30); add(tabBox, BorderLayout.CENTER); Box southBox = Box.createVerticalBox(); Box buttonBox = Box.createHorizontalBox(); BoxUtil.addHorizontalStrut(buttonBox, 30); JButton testButton = new JButton("测试连接"); testButton.addActionListener(new TestConnectionAction(this)); buttonBox.add(testButton); buttonBox.add(Box.createHorizontalGlue()); JButton okButton = new JButton("确认"); okButton.setBackground(new Color(53, 116, 240));
package com.ktools.frontend.frame; /** * @author lsl * @version 1.0 * @date 2023年12月18日 17:34 */ @Slf4j @Data public class JDBCConnectionFrame extends JFrame { public static boolean openFlag = true; private static final int WIDTH = 600; private static final int HEIGHT = 700; private KDataSourceMetadata kDataSourceMetadata; private TreeEntity treeEntity; private TreePath treePath; private RegularPanel regularPanel; private AdvancedPanel advancedPanel; private JTextField nameField; private JTextField commentField; public JDBCConnectionFrame() { Tree instance = Tree.getInstance(); this.treePath = instance.getCurrentTreePath(); this.treeEntity = instance.getCurrentTreeEntity(treePath); try { this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType()); } catch (KToolException e) { throw new RuntimeException(e); } setTitle("编辑" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initEdit(); frameEndInit(); } public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) { Tree instance = Tree.getInstance(); this.kDataSourceMetadata = kDataSourceMetadata; this.treePath = instance.getCurrentTreePath(); setTitle("新建" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initNew(); frameEndInit(); } private void frameStartInit() { openFlag = false; setIconImage(ImageLoad.getInstance().buildIcon(kDataSourceMetadata.getLogo()).getImage()); setSize(WIDTH, HEIGHT); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setResizable(false); closeAction(); } private void frameEndInit() { setVisible(true); } private void initEdit() { if (Objects.nonNull(treeEntity)) { Box publicBox = Box.createVerticalBox(); BoxUtil.addVerticalStrut(publicBox, 30); nameField = initSubBox(publicBox, "名称: "); nameField.setText(treeEntity.getNodeName()); BoxUtil.addVerticalStrut(publicBox, 30); commentField = initSubBox(publicBox, "注释: "); commentField.setText(treeEntity.getNodeComment()); BoxUtil.addVerticalStrut(publicBox, 30); add(publicBox, BorderLayout.NORTH); Box tabBox = Box.createHorizontalBox(); BoxUtil.addHorizontalStrut(tabBox, 30); JTabbedPane tabbedPane = new JTabbedPane(); regularPanel = new RegularPanel(treeEntity); advancedPanel = new AdvancedPanel(treeEntity, kDataSourceMetadata); tabbedPane.addTab("常规", null, regularPanel, "常规"); tabbedPane.addTab("高级", null, advancedPanel, "高级"); tabBox.add(tabbedPane); BoxUtil.addHorizontalStrut(tabBox, 30); add(tabBox, BorderLayout.CENTER); Box southBox = Box.createVerticalBox(); Box buttonBox = Box.createHorizontalBox(); BoxUtil.addHorizontalStrut(buttonBox, 30); JButton testButton = new JButton("测试连接"); testButton.addActionListener(new TestConnectionAction(this)); buttonBox.add(testButton); buttonBox.add(Box.createHorizontalGlue()); JButton okButton = new JButton("确认"); okButton.setBackground(new Color(53, 116, 240));
okButton.addActionListener(new TreeJDBCNodeAction(this));
3
2023-11-30 03:26:25+00:00
12k
ChrisGenti/VPL
velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java
[ { "identifier": "PluginCommand", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/PluginCommand.java", "snippet": "public interface PluginCommand extends SimpleCommand {\n String name();\n\n default String usage() { return \"/\" + this.name(); };\n}" }, { "identi...
import com.github.chrisgenti.vpl.velocity.commands.PluginCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.VPLCommand; import com.github.chrisgenti.vpl.velocity.commands.user.PremiumCommand; import com.github.chrisgenti.vpl.velocity.configurations.config.ConfigFile; import com.github.chrisgenti.vpl.velocity.configurations.language.LanguageFile; import com.github.chrisgenti.vpl.velocity.data.DataProvider; import com.github.chrisgenti.vpl.velocity.data.mysql.MySQLProvider; import com.github.chrisgenti.vpl.velocity.listeners.Listener; import com.github.chrisgenti.vpl.velocity.listeners.chat.ChatListener; import com.github.chrisgenti.vpl.velocity.listeners.command.CommandListener; import com.github.chrisgenti.vpl.velocity.listeners.disconnect.DisconnectListener; import com.github.chrisgenti.vpl.velocity.listeners.login.PreLoginListener; import com.github.chrisgenti.vpl.velocity.listeners.login.post.PostLoginListener; import com.github.chrisgenti.vpl.velocity.listeners.message.PluginMessageListener; import com.github.chrisgenti.vpl.velocity.listeners.profile.ProfileRequestListener; import com.github.chrisgenti.vpl.velocity.listeners.server.InitialServerListener; import com.github.chrisgenti.vpl.velocity.listeners.tab.TabCompleteListener; import com.github.chrisgenti.vpl.velocity.players.PlayerManager; import com.github.chrisgenti.vpl.velocity.servers.ServerManager; import com.github.chrisgenti.vpl.velocity.tasks.PluginTask; import com.github.chrisgenti.vpl.velocity.tasks.register.RegisterTask; import com.google.inject.Inject; import com.velocitypowered.api.command.CommandManager; import com.velocitypowered.api.command.CommandMeta; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.event.EventManager; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.api.proxy.messages.LegacyChannelIdentifier; import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier; import lombok.Getter; import net.kyori.adventure.text.minimessage.MiniMessage; import org.slf4j.Logger; import java.io.File; import java.nio.file.Path; import java.util.Arrays;
10,564
package com.github.chrisgenti.vpl.velocity; @Plugin( id = "vpl", name = "VPL", version = "1.0.0", description = "", authors = {"ChrisGenti"} ) @Getter public class VPLPlugin { public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main"); public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main"); @Inject private ProxyServer proxy; @Inject private Logger logger; @Inject private EventManager eventManager; @Inject @DataDirectory Path directory; private ConfigFile configFile; private LanguageFile languageFile; private PlayerManager playerManager; private ServerManager serverManager; private DataProvider provider; private PluginTask registerTask; @Subscribe public void onInitialization(ProxyInitializeEvent event) { /* * FILES */ this.configFile = new ConfigFile(directory.toFile(), "config.toml"); this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE); /* * SETUP MESSAGE */ this.sendMessage( "<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>" ); /* * MANAGERS */ this.playerManager = new PlayerManager(); this.serverManager = new ServerManager(this); /* * PROVIDERS */ this.provider = new MySQLProvider(this, configFile.CREDENTIALS); this.provider.init(); /* * COMMANDS */ this.registerCommands( new VPLCommand(this), new PremiumCommand(this) ); /* * LISTENERS */ this.registerListeners( new PluginMessageListener(this), new ChatListener(this), new CommandListener(this), new TabCompleteListener(this), new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this) ); /* * TASKS */ this.registerTask = new RegisterTask(this); this.registerTask.run(); /* * CHANNELS */ this.registerPluginChannels(); } @Subscribe public void onShutdown(ProxyShutdownEvent event) { /* * TASKS */ this.registerTask.stop(); /* * CHANNELS */ this.unregisterPluginChannels(); } public void debug(String message) { if (configFile.DEBUG) logger.info("[DEBUG] {}", message); } public void sendMessage(CommandSource source, String message) { if (!message.isEmpty()) source.sendMessage(MiniMessage.miniMessage().deserialize(message)); } public void sendMessage(String... messages) { CommandSource source = proxy.getConsoleCommandSource(); Arrays.stream(messages).forEach(message -> this.sendMessage(source, message)); } private void registerCommands(PluginCommand... commands) { CommandManager manager = proxy.getCommandManager(); Arrays.stream(commands).forEach(command -> { CommandMeta commandMeta = manager.metaBuilder(command.name()) .plugin(this) .build(); manager.register(commandMeta, command); }); }
package com.github.chrisgenti.vpl.velocity; @Plugin( id = "vpl", name = "VPL", version = "1.0.0", description = "", authors = {"ChrisGenti"} ) @Getter public class VPLPlugin { public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main"); public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main"); @Inject private ProxyServer proxy; @Inject private Logger logger; @Inject private EventManager eventManager; @Inject @DataDirectory Path directory; private ConfigFile configFile; private LanguageFile languageFile; private PlayerManager playerManager; private ServerManager serverManager; private DataProvider provider; private PluginTask registerTask; @Subscribe public void onInitialization(ProxyInitializeEvent event) { /* * FILES */ this.configFile = new ConfigFile(directory.toFile(), "config.toml"); this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE); /* * SETUP MESSAGE */ this.sendMessage( "<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>" ); /* * MANAGERS */ this.playerManager = new PlayerManager(); this.serverManager = new ServerManager(this); /* * PROVIDERS */ this.provider = new MySQLProvider(this, configFile.CREDENTIALS); this.provider.init(); /* * COMMANDS */ this.registerCommands( new VPLCommand(this), new PremiumCommand(this) ); /* * LISTENERS */ this.registerListeners( new PluginMessageListener(this), new ChatListener(this), new CommandListener(this), new TabCompleteListener(this), new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this) ); /* * TASKS */ this.registerTask = new RegisterTask(this); this.registerTask.run(); /* * CHANNELS */ this.registerPluginChannels(); } @Subscribe public void onShutdown(ProxyShutdownEvent event) { /* * TASKS */ this.registerTask.stop(); /* * CHANNELS */ this.unregisterPluginChannels(); } public void debug(String message) { if (configFile.DEBUG) logger.info("[DEBUG] {}", message); } public void sendMessage(CommandSource source, String message) { if (!message.isEmpty()) source.sendMessage(MiniMessage.miniMessage().deserialize(message)); } public void sendMessage(String... messages) { CommandSource source = proxy.getConsoleCommandSource(); Arrays.stream(messages).forEach(message -> this.sendMessage(source, message)); } private void registerCommands(PluginCommand... commands) { CommandManager manager = proxy.getCommandManager(); Arrays.stream(commands).forEach(command -> { CommandMeta commandMeta = manager.metaBuilder(command.name()) .plugin(this) .build(); manager.register(commandMeta, command); }); }
private void registerListeners(Listener<?>... listeners) {
7
2023-11-28 10:12:04+00:00
12k
Ethylene9160/Chess
src/chess/panels/GamePanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import chess.pieces.Chess; import chess.recorder.Loader; import chess.recorder.Record; import chess.recorder.Saver; import chess.util.Constants; import chess.util.ImagePath; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.ArrayList; import static java.awt.event.KeyEvent.VK_A; import static java.awt.event.KeyEvent.VK_E;
7,611
package chess.panels; public class GamePanel extends PanelBase implements ActionListener, MouseListener, KeyListener { @Override public void init() { super.init(); creatChess(Chess.FIRST_COLOR); } // private int[] xs, ys; public GamePanel(JLabel hint) { type = PanelType.Local; this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! addKeyListener(this); } @Override public void paint(Graphics g) { super.paint(g);//clear this.setBounds(0, 0, Constants.FRAME_LENGTH - 200, Constants.FRAME_HEIGHT);
package chess.panels; public class GamePanel extends PanelBase implements ActionListener, MouseListener, KeyListener { @Override public void init() { super.init(); creatChess(Chess.FIRST_COLOR); } // private int[] xs, ys; public GamePanel(JLabel hint) { type = PanelType.Local; this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! addKeyListener(this); } @Override public void paint(Graphics g) { super.paint(g);//clear this.setBounds(0, 0, Constants.FRAME_LENGTH - 200, Constants.FRAME_HEIGHT);
g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND),
5
2023-12-01 02:33:32+00:00
12k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/parser/Parser.java
[ { "identifier": "AssignStatement", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/AssignStatement.java", "snippet": "public class AssignStatement extends Statement {\n\n private final String leftHand;\n private final Expression rightHand;\n\n public AssignStatement(String leftHand,...
import java.util.ArrayList; import java.util.List; import org.vectorlang.compiler.ast.AssignStatement; import org.vectorlang.compiler.ast.BinaryExpression; import org.vectorlang.compiler.ast.BinaryOperator; import org.vectorlang.compiler.ast.BlockStatement; import org.vectorlang.compiler.ast.CallExpression; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.ast.DeclareStatement; import org.vectorlang.compiler.ast.Expression; import org.vectorlang.compiler.ast.ForStatement; import org.vectorlang.compiler.ast.FunctionStatement; import org.vectorlang.compiler.ast.GroupingExpression; import org.vectorlang.compiler.ast.IdentifierExpression; import org.vectorlang.compiler.ast.IfStatement; import org.vectorlang.compiler.ast.IndexExpression; import org.vectorlang.compiler.ast.LiteralExpression; import org.vectorlang.compiler.ast.PrintStatement; import org.vectorlang.compiler.ast.ReturnStatement; import org.vectorlang.compiler.ast.Statement; import org.vectorlang.compiler.ast.UnaryExpression; import org.vectorlang.compiler.ast.UnaryOperator; import org.vectorlang.compiler.ast.VectorExpression; import org.vectorlang.compiler.ast.WhileStatement; import org.vectorlang.compiler.compiler.BaseType; import org.vectorlang.compiler.compiler.Type;
7,256
} else { return null; } expr = new BinaryExpression( new IdentifierExpression(name), expression.apply(state), operator); } if (semicolon) { state.consume(TokenType.SEMICOLON); } return new AssignStatement(name, expr); } private Statement statement(ParserState state) { if (state.matches(TokenType.OPEN_BRACE)) { List<Statement> statements = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new BlockStatement(statements.toArray(new Statement[0])); } else if (state.matches(TokenType.PRINT)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new PrintStatement(expr); } else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) { boolean constant = state.previous().type() == TokenType.CONST; state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); } Type type = type(state); state.consume(TokenType.SEMICOLON); return new DeclareStatement(constant, name, expr, type); } else if (state.matches(TokenType.IF)) { state.consume(TokenType.OPEN_PAREN); Expression condition = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement ifStatement = statement.apply(state); Statement elseStatement = null; if (state.matches(TokenType.ELSE)) { elseStatement = statement.apply(state); } return new IfStatement(ifStatement, elseStatement, condition); } else if (state.peek().type() == TokenType.IDENTIFIER) { return assignStatement.apply(state); } else if (state.peek().type() == TokenType.WHILE) { return whileStatement.apply(state); } else if (state.peek().type() == TokenType.FOR) { return forStatement.apply(state); } else if (state.matches(TokenType.RETURN)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new ReturnStatement(expr); } else { return null; } } private FunctionStatement function(ParserState state) { List<String> names = new ArrayList<>(); List<Type> types = new ArrayList<>(); List<Statement> statements = new ArrayList<>(); state.consume(TokenType.FUNC); state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); state.consume(TokenType.OPEN_PAREN); boolean flag = false; while (!state.matches(TokenType.CLOSE_PAREN)) { if (flag) { state.consume(TokenType.COMMA); } state.consume(TokenType.IDENTIFIER); names.add(state.previous().value()); types.add(type(state)); flag = true; } Type type = null; if (state.peek().type() == TokenType.COLON) { type = type(state); } state.consume(TokenType.OPEN_BRACE); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new FunctionStatement( name, names.toArray(new String[0]), types.toArray(new Type[0]), statements.toArray(new Statement[0]), type ); } private Type type(ParserState state) { if (state.matches(TokenType.COLON)) { state.consume(TokenType.IDENTIFIER); BaseType baseType = switch(state.previous().value()) { case "int" -> BaseType.INT; case "float" -> BaseType.FLOAT; case "bool" -> BaseType.BOOL; case "char" -> BaseType.CHAR; default -> null; }; if (baseType == null) { return null; } List<Integer> list = new ArrayList<>(); while (state.matches(TokenType.OPEN_BRACKET)) { state.consume(TokenType.INT_LITERAL); list.add(Integer.parseInt(state.previous().value())); state.consume(TokenType.CLOSE_BRACKET); } int[] shape = new int[list.size()]; for (int i = 0; i < list.size(); i++) { shape[i] = list.get(i); } return new Type(baseType, shape, false); } else { return null; } }
package org.vectorlang.compiler.parser; public class Parser { private ParseRule<Expression> literalExpression, identifierExpression, value, unary, indexedValue, factor, term, comparison, equality, and, or, groupingExpression, vectorExpression, expression; private ParseRule<Statement> forStatement, whileStatement, assignStatement, assignStatement2, statement; private ParseRule<FunctionStatement> function; public Parser() { literalExpression = new ParseRule<>(this::literalExpression, TokenType.SEMICOLON); identifierExpression = new ParseRule<>(this::identifierExpression, TokenType.SEMICOLON); value = new ParseRule<>(this::value, TokenType.SEMICOLON); unary = new ParseRule<>(this::unary, TokenType.SEMICOLON); indexedValue = new ParseRule<>(this::indexedValue, TokenType.SEMICOLON); factor = new ParseRule<>(this::factor, TokenType.SEMICOLON); term = new ParseRule<>(this::term, TokenType.SEMICOLON); comparison = new ParseRule<>(this::comparison, TokenType.SEMICOLON); equality = new ParseRule<>(this::equality, TokenType.SEMICOLON); and = new ParseRule<>(this::and, TokenType.SEMICOLON); or = new ParseRule<>(this::or, TokenType.SEMICOLON); groupingExpression = new ParseRule<>(this::groupingExpression, TokenType.SEMICOLON); vectorExpression = new ParseRule<>(this::vectorExpression, TokenType.SEMICOLON); expression = or; forStatement = new ParseRule<>(this::forStatement, TokenType.CLOSE_BRACE); whileStatement = new ParseRule<>(this::whileStatement, TokenType.CLOSE_BRACE); assignStatement = new ParseRule<>((ParserState state) -> assignStatement(state, true), TokenType.SEMICOLON); assignStatement2 = new ParseRule<>((ParserState state) -> assignStatement(state, false), TokenType.SEMICOLON); statement = new ParseRule<>(this::statement, TokenType.CLOSE_BRACE); function = new ParseRule<>(this::function, TokenType.CLOSE_BRACE); } private LiteralExpression literalExpression(ParserState state) { if (state.matches(TokenType.TRUE)) { return new LiteralExpression(true); } else if (state.matches(TokenType.FALSE)) { return new LiteralExpression(false); } else if (state.matches(TokenType.INT_LITERAL)) { return new LiteralExpression(Integer.parseInt(state.previous().value())); } else if (state.matches(TokenType.FLOAT_LITERAL)) { return new LiteralExpression(Double.parseDouble(state.previous().value())); } else { return null; } } private Expression identifierExpression(ParserState state) { state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); if (state.matches(TokenType.OPEN_PAREN)) { boolean flag = false; List<Expression> expressions = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_PAREN)) { if (flag) { state.consume(TokenType.COMMA); } expressions.add(expression.apply(state)); flag = true; } return new CallExpression(name, expressions.toArray(new Expression[0]), null); } return new IdentifierExpression(name); } private Expression value(ParserState state) { if (state.peek().type() == TokenType.OPEN_PAREN) { return groupingExpression.apply(state); } else if (state.peek().type() == TokenType.IDENTIFIER) { return identifierExpression.apply(state); } else if (state.peek().type() == TokenType.OPEN_BRACKET) { return vectorExpression.apply(state); } else { return literalExpression.apply(state); } } private Expression indexedValue(ParserState state) { Expression expr = value.apply(state); while (state.matches(TokenType.OPEN_BRACKET)) { Expression index = expression.apply(state); expr = new IndexExpression(expr, index); state.consume(TokenType.CLOSE_BRACKET); } return expr; } private Expression unary(ParserState state) { if (state.matches(TokenType.BANG)) { return new UnaryExpression(unary.apply(state), UnaryOperator.NEGATE); } else if (state.matches(TokenType.DASH)) { return new UnaryExpression(unary.apply(state), UnaryOperator.INVERSE); } else { return indexedValue.apply(state); } } private Expression factor(ParserState state) { Expression expression = unary.apply(state); while (state.matches(new TokenType[]{TokenType.STAR, TokenType.SLASH, TokenType.DOT_STAR, TokenType.DOT_SLASH})) { BinaryOperator operator = switch (state.previous().type()) { case STAR -> BinaryOperator.MULTIPLY; case SLASH -> BinaryOperator.DIVIDE; case DOT_STAR -> BinaryOperator.DOT_MULTIPLY; case DOT_SLASH -> BinaryOperator.DOT_DIVIDE; case DOT_DOT -> BinaryOperator.CONCAT; default -> null; }; expression = new BinaryExpression(expression, unary.apply(state), operator); } return expression; } private Expression term(ParserState state) { Expression expression = factor.apply(state); while (state.matches(new TokenType[]{TokenType.PLUS, TokenType.DASH, TokenType.DOT_PLUS, TokenType.DOT_DASH})) { BinaryOperator operator = switch (state.previous().type()) { case PLUS -> BinaryOperator.ADD; case DASH -> BinaryOperator.SUBTRACT; case DOT_PLUS -> BinaryOperator.DOT_ADD; case DOT_DASH -> BinaryOperator.DOT_SUBTRACT; default -> null; }; expression = new BinaryExpression(expression, factor.apply(state), operator); } return expression; } private Expression comparison(ParserState state) { Expression expression = term.apply(state); while (state.matches(new TokenType[]{TokenType.LEFT_ARROW, TokenType.LEFT_ARROW_EQUALS, TokenType.RIGHT_ARROW, TokenType.RIGHT_ARROW_EQUALS})) { BinaryOperator operator = switch (state.previous().type()) { case LEFT_ARROW -> BinaryOperator.LESS_THAN; case RIGHT_ARROW -> BinaryOperator.GREATER_THAN; case LEFT_ARROW_EQUALS -> BinaryOperator.EQUAL_LESS_THAN; case RIGHT_ARROW_EQUALS -> BinaryOperator.EQUAL_GREATER_THAN; default -> null; }; expression = new BinaryExpression(expression, term.apply(state), operator); } return expression; } private Expression or(ParserState state) { Expression expression = and.apply(state); while (state.matches(TokenType.BAR)) { expression = new BinaryExpression(expression, and.apply(state), BinaryOperator.OR); } return expression; } private Expression and(ParserState state) { Expression expression = equality.apply(state); while (state.matches(TokenType.AMPERSAND)) { expression = new BinaryExpression(expression, equality.apply(state), BinaryOperator.AND); } return expression; } private Expression equality(ParserState state) { Expression expression = comparison.apply(state); while (state.matches(new TokenType[]{TokenType.EQUALS_EQUALS, TokenType.BANG_EQUALS})) { BinaryOperator operator = switch (state.previous().type()) { case EQUALS_EQUALS -> BinaryOperator.EQUAL; case BANG_EQUALS -> BinaryOperator.NOT_EQUAL; default -> null; }; expression = new BinaryExpression(expression, comparison.apply(state), operator); } return expression; } private GroupingExpression groupingExpression(ParserState state) { state.consume(TokenType.OPEN_PAREN); Expression expr = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); return new GroupingExpression(expr); } private VectorExpression vectorExpression(ParserState state) { List<Expression> expressions = new ArrayList<>(); state.consume(TokenType.OPEN_BRACKET); do { expressions.add(expression.apply(state)); } while (state.matches(TokenType.COMMA)); state.consume(TokenType.CLOSE_BRACKET); return new VectorExpression(expressions.toArray(new Expression[0])); } private ForStatement forStatement(ParserState state) { state.consume(TokenType.FOR); state.consume(TokenType.OPEN_PAREN); Statement initial = statement.apply(state); Expression condition = expression.apply(state); state.consume(TokenType.SEMICOLON); Statement each = assignStatement2.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new ForStatement(condition, initial, each, body); } private WhileStatement whileStatement(ParserState state) { state.consume(TokenType.WHILE); state.consume(TokenType.OPEN_PAREN); Expression condition = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new WhileStatement(condition, body); } private AssignStatement assignStatement(ParserState state, boolean semicolon) { state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); } else if (state.matches(TokenType.PLUS_PLUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.ADD ); } else if (state.matches(TokenType.MINUS_MINUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.SUBTRACT ); } else { BinaryOperator operator = null; if (state.matches(TokenType.PLUS_EQUALs)) { operator = BinaryOperator.ADD; } else if (state.matches(TokenType.MINUS_EQUALS)) { operator = BinaryOperator.SUBTRACT; } else if (state.matches(TokenType.STAR_EQUALS)) { operator = BinaryOperator.MULTIPLY; } else if (state.matches(TokenType.SLASH_EQUALS)) { operator = BinaryOperator.DIVIDE; } else if (state.matches(TokenType.BAR_EQUALS)) { operator = BinaryOperator.OR; } else if (state.matches(TokenType.AMPERSAND_EQUALS)) { operator = BinaryOperator.AND; } else { return null; } expr = new BinaryExpression( new IdentifierExpression(name), expression.apply(state), operator); } if (semicolon) { state.consume(TokenType.SEMICOLON); } return new AssignStatement(name, expr); } private Statement statement(ParserState state) { if (state.matches(TokenType.OPEN_BRACE)) { List<Statement> statements = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new BlockStatement(statements.toArray(new Statement[0])); } else if (state.matches(TokenType.PRINT)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new PrintStatement(expr); } else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) { boolean constant = state.previous().type() == TokenType.CONST; state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); } Type type = type(state); state.consume(TokenType.SEMICOLON); return new DeclareStatement(constant, name, expr, type); } else if (state.matches(TokenType.IF)) { state.consume(TokenType.OPEN_PAREN); Expression condition = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement ifStatement = statement.apply(state); Statement elseStatement = null; if (state.matches(TokenType.ELSE)) { elseStatement = statement.apply(state); } return new IfStatement(ifStatement, elseStatement, condition); } else if (state.peek().type() == TokenType.IDENTIFIER) { return assignStatement.apply(state); } else if (state.peek().type() == TokenType.WHILE) { return whileStatement.apply(state); } else if (state.peek().type() == TokenType.FOR) { return forStatement.apply(state); } else if (state.matches(TokenType.RETURN)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new ReturnStatement(expr); } else { return null; } } private FunctionStatement function(ParserState state) { List<String> names = new ArrayList<>(); List<Type> types = new ArrayList<>(); List<Statement> statements = new ArrayList<>(); state.consume(TokenType.FUNC); state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); state.consume(TokenType.OPEN_PAREN); boolean flag = false; while (!state.matches(TokenType.CLOSE_PAREN)) { if (flag) { state.consume(TokenType.COMMA); } state.consume(TokenType.IDENTIFIER); names.add(state.previous().value()); types.add(type(state)); flag = true; } Type type = null; if (state.peek().type() == TokenType.COLON) { type = type(state); } state.consume(TokenType.OPEN_BRACE); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new FunctionStatement( name, names.toArray(new String[0]), types.toArray(new Type[0]), statements.toArray(new Statement[0]), type ); } private Type type(ParserState state) { if (state.matches(TokenType.COLON)) { state.consume(TokenType.IDENTIFIER); BaseType baseType = switch(state.previous().value()) { case "int" -> BaseType.INT; case "float" -> BaseType.FLOAT; case "bool" -> BaseType.BOOL; case "char" -> BaseType.CHAR; default -> null; }; if (baseType == null) { return null; } List<Integer> list = new ArrayList<>(); while (state.matches(TokenType.OPEN_BRACKET)) { state.consume(TokenType.INT_LITERAL); list.add(Integer.parseInt(state.previous().value())); state.consume(TokenType.CLOSE_BRACKET); } int[] shape = new int[list.size()]; for (int i = 0; i < list.size(); i++) { shape[i] = list.get(i); } return new Type(baseType, shape, false); } else { return null; } }
public CodeBase parse(List<Token> tokens) {
5
2023-11-30 04:22:36+00:00
12k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
9,733
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>();
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>();
private AnswerItemProvider answerItemProvider;
10
2023-12-03 13:36:00+00:00
12k
godheaven/klib-data-jdbc
src/test/java/cl/kanopus/jdbc/example/ExampleDAO.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.jdbc.DAOInterface; import cl.kanopus.jdbc.example.entity.TestData; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.common.data.Paginator; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.common.data.Searcher; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.springframework.stereotype.Repository;
9,143
package cl.kanopus.jdbc.example; /** * * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @Repository public class ExampleDAO extends AbstractBaseDAO<TestData, Long> implements DAOInterface<TestData, Long> { /** * Get a list of records with a limit * * @param searcher * @return */ public Paginator<TestData> findWithPaginator(Searcher searcher) throws DataException {
package cl.kanopus.jdbc.example; /** * * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @Repository public class ExampleDAO extends AbstractBaseDAO<TestData, Long> implements DAOInterface<TestData, Long> { /** * Get a list of records with a limit * * @param searcher * @return */ public Paginator<TestData> findWithPaginator(Searcher searcher) throws DataException {
SQLQueryDynamic query = new SQLQueryDynamic(TestData.class);
4
2023-11-27 18:25:00+00:00
12k
victor-vilar/coleta
backend/src/main/java/com/victorvilar/projetoempresa/services/ContractService.java
[ { "identifier": "ContractCreateDto", "path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/contract/ContractCreateDto.java", "snippet": "public class ContractCreateDto {\n\n\n\n @NotBlank(message =\"The contract must have a number\")\n private String number;\n\n @NotNull(message = \...
import com.victorvilar.projetoempresa.dto.contract.ContractCreateDto; import com.victorvilar.projetoempresa.dto.contract.ContractResponseDto; import com.victorvilar.projetoempresa.dto.contract.ContractUpdateDto; import com.victorvilar.projetoempresa.dto.contract.ItemContractCreateDto; import com.victorvilar.projetoempresa.domain.Customer; import com.victorvilar.projetoempresa.enums.ContractStatus; import com.victorvilar.projetoempresa.exceptions.CustomerNotFoundException; import com.victorvilar.projetoempresa.exceptions.ContractNotFoundException; import com.victorvilar.projetoempresa.domain.Contract; import com.victorvilar.projetoempresa.domain.ItemContract; import com.victorvilar.projetoempresa.exceptions.ItemContractNotFoundException; import com.victorvilar.projetoempresa.mappers.ContractMapper; import com.victorvilar.projetoempresa.mappers.ItemContractMapper; import com.victorvilar.projetoempresa.repository.ContractRepository; import com.victorvilar.projetoempresa.repository.CustomerRepository; import com.victorvilar.projetoempresa.repository.ItemContractRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; import java.util.List;
8,801
package com.victorvilar.projetoempresa.services; @Service public class ContractService { private final ContractRepository contractRepository; private final ItemContractRepository itemContractRepository; private final CustomerRepository customerRepository; private final CustomerService customerService;
package com.victorvilar.projetoempresa.services; @Service public class ContractService { private final ContractRepository contractRepository; private final ItemContractRepository itemContractRepository; private final CustomerRepository customerRepository; private final CustomerService customerService;
private final ContractMapper contractMapper;
11
2023-12-02 21:29:33+00:00
12k
GiulianoVianna/Prototipo-Ferramenta-de-Backup-em-Java
src/main/java/com/mycompany/ferramentadebackup/view/FerramentaDeBackupView.java
[ { "identifier": "BancoDeDadosDAO", "path": "src/main/java/com/mycompany/ferramentadebackup/dao/BancoDeDadosDAO.java", "snippet": "public class BancoDeDadosDAO {\n\n // URL de conexão com o banco de dados SQLite\n String url = \"jdbc:sqlite:dados_backup.db\";\n\n // Lista para armazenar objetos ...
import com.mycompany.ferramentadebackup.dao.BancoDeDadosDAO; import com.mycompany.ferramentadebackup.dto.BancoDeDadosDTO; import com.mycompany.ferramentadebackup.compactadorzip.CompactadorZip; import javax.swing.*; import java.awt.*; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.Optional;
9,675
private javax.swing.JRadioButton rdbPC; private javax.swing.JTextField txtArquivoDiretorio; private javax.swing.JTextField txtDiretorio; private javax.swing.JTextField txtID; private javax.swing.JTextField txtNomeBackup; // End of variables declaration//GEN-END:variables /** * Permite ao usuário escolher entre selecionar um diretório ou um arquivo. * <p> * Este método exibe uma caixa de diálogo com duas opções: "Diretório" e * "Arquivo". A escolha do usuário determina se o {@link JFileChooser} será * configurado para selecionar apenas diretórios ou apenas arquivos. Após a * seleção, o caminho absoluto do diretório ou arquivo escolhido é retornado * dentro de um {@link java.util.Optional}. * </p> * * <p> * Se o usuário selecionar um item, o caminho absoluto é retornado * encapsulado em um {@code Optional<String>}. Se o usuário cancelar a * operação ou se ocorrer um erro, um {@code Optional<String>} vazio é * retornado. * </p> * * <p> * Exceções são tratadas internamente, e uma mensagem de erro é exibida em * caso de falha. * </p> * * @return Um {@link java.util.Optional<String>} contendo o caminho do * arquivo ou diretório selecionado, ou um {@code Optional} vazio em caso de * cancelamento ou erro. */ public Optional<String> selecionarDiretorioOuArquivo() { Object[] options = {"Diretório", "Arquivo"}; int choice = JOptionPane.showOptionDialog( null, "Você deseja selecionar um diretório ou um arquivo?", "Selecionar Diretório ou Arquivo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(choice == JOptionPane.YES_OPTION ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); try { int option = fileChooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (selectedFile != null) { String caminhoArquivoDiretorio = selectedFile.getAbsolutePath(); txtArquivoDiretorio.setText(caminhoArquivoDiretorio); // Ajuste conforme sua lógica de interface return Optional.of(caminhoArquivoDiretorio); } } } catch (HeadlessException error) { JOptionPane.showMessageDialog(null, "Ocorreu um erro ao selecionar o arquivo ou diretório " + error, "Erro", JOptionPane.ERROR_MESSAGE); } return Optional.empty(); } /** * Abre uma caixa de diálogo para o usuário selecionar um diretório. * <p> * Este método utiliza o {@link JFileChooser} configurado para permitir que * o usuário selecione apenas diretórios. Após a seleção, o caminho absoluto * do diretório escolhido é atribuído a uma variável de instância. * </p> * * <p> * Se o usuário selecionar um diretório, o caminho absoluto é armazenado na * variável {@code txtDiretorio}. Em caso de cancelamento da operação, * nenhuma ação é tomada. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, mas atualiza * diretamente a interface do usuário com o caminho do diretório * selecionado. * </p> */ public void selecionarDiretorio() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Configura para selecionar apenas diretórios int option = fileChooser.showOpenDialog(null); // Abre a caixa de diálogo centralizada if (option == JFileChooser.APPROVE_OPTION) { File selectedDirectory = fileChooser.getSelectedFile(); if (selectedDirectory != null) { // Atribui o caminho à variável de instância String caminhoDoDiretorio = selectedDirectory.getAbsolutePath(); txtDiretorio.setText(caminhoDoDiretorio); } } } /** * Verifica a existência do banco de dados e o cria, se necessário. * <p> * Este método utiliza a classe {@link BancoDeDadosDAO} para verificar se o * banco de dados já existe. Se o banco de dados não existir, ele é criado * por meio do método {@link BancoDeDadosDAO#verificarECriarBancoDeDados()}. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, pois sua função é * verificar e criar o banco de dados, se necessário, sem fornecer * resultados diretos. * </p> */ public final void verificarBancoDeDados() {
package com.mycompany.ferramentadebackup.view; /** * * @author Giuliano Vianna */ public class FerramentaDeBackupView extends javax.swing.JFrame { /** * Creates new form frmFerramentaDeBackupView */ public FerramentaDeBackupView() { initComponents(); verificarBancoDeDados(); iconeJanela(); popularTabelaAgendamentoBackup(); // Centraliza a janela this.setLocationRelativeTo(null); formatarJSpinner(); new Timer(delay, taskPerformer).start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); txtArquivoDiretorio = new javax.swing.JTextField(); btnSelecionarArquivoDiretorio = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); txtDiretorio = new javax.swing.JTextField(); btnSelecionarDiretorioDestino = new javax.swing.JButton(); jdData = new com.toedter.calendar.JDateChooser(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtTabela = new javax.swing.JTable(); rdbPC = new javax.swing.JRadioButton(); jPanel1 = new javax.swing.JPanel(); btnNovo = new javax.swing.JButton(); btnSalvar = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); btnEditar = new javax.swing.JButton(); btnExcluir = new javax.swing.JButton(); btnAtualizar = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); txtID = new javax.swing.JTextField(); txtNomeBackup = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jsHora = new javax.swing.JSpinner(); jLabel6 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Ferramenta de Backup"); setResizable(false); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel1.setText("Arquivo ou Diretório"); txtArquivoDiretorio.setEditable(false); txtArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtArquivoDiretorio.setEnabled(false); btnSelecionarArquivoDiretorio.setBackground(new java.awt.Color(153, 0, 255)); btnSelecionarArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnSelecionarArquivoDiretorio.setForeground(new java.awt.Color(255, 255, 255)); btnSelecionarArquivoDiretorio.setText("Selecionar"); btnSelecionarArquivoDiretorio.setEnabled(false); btnSelecionarArquivoDiretorio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelecionarArquivoDiretorioActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel2.setText("Diretório de Destino"); txtDiretorio.setEditable(false); txtDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtDiretorio.setEnabled(false); btnSelecionarDiretorioDestino.setBackground(new java.awt.Color(153, 0, 255)); btnSelecionarDiretorioDestino.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnSelecionarDiretorioDestino.setForeground(new java.awt.Color(255, 255, 255)); btnSelecionarDiretorioDestino.setText("Selecionar"); btnSelecionarDiretorioDestino.setEnabled(false); btnSelecionarDiretorioDestino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelecionarDiretorioDestinoActionPerformed(evt); } }); jdData.setDateFormatString("dd'/'MM'/'yy"); jdData.setEnabled(false); jdData.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel3.setText("Data"); jtTabela.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jtTabela.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "ID", "Nome Backup", "Arquivo/Diretório de Origem", "Diretório de Destino", "Data", "Hora", "Desligar PC" } )); jtTabela.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); jtTabela.setShowGrid(false); jtTabela.setShowVerticalLines(true); jScrollPane1.setViewportView(jtTabela); if (jtTabela.getColumnModel().getColumnCount() > 0) { jtTabela.getColumnModel().getColumn(0).setMinWidth(80); jtTabela.getColumnModel().getColumn(0).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(0).setMaxWidth(80); jtTabela.getColumnModel().getColumn(1).setMinWidth(200); jtTabela.getColumnModel().getColumn(2).setMinWidth(420); jtTabela.getColumnModel().getColumn(2).setPreferredWidth(420); jtTabela.getColumnModel().getColumn(2).setMaxWidth(420); jtTabela.getColumnModel().getColumn(3).setMinWidth(420); jtTabela.getColumnModel().getColumn(3).setPreferredWidth(420); jtTabela.getColumnModel().getColumn(3).setMaxWidth(420); jtTabela.getColumnModel().getColumn(4).setMinWidth(80); jtTabela.getColumnModel().getColumn(4).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(4).setMaxWidth(80); jtTabela.getColumnModel().getColumn(5).setMinWidth(80); jtTabela.getColumnModel().getColumn(5).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(5).setMaxWidth(80); jtTabela.getColumnModel().getColumn(6).setMinWidth(80); jtTabela.getColumnModel().getColumn(6).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(6).setMaxWidth(80); } rdbPC.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N rdbPC.setForeground(new java.awt.Color(153, 0, 255)); rdbPC.setText("Desligar o PC ao finalizar o backup"); rdbPC.setEnabled(false); btnNovo.setBackground(new java.awt.Color(153, 0, 255)); btnNovo.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnNovo.setForeground(new java.awt.Color(255, 255, 255)); btnNovo.setText("Novo"); btnNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNovoActionPerformed(evt); } }); btnSalvar.setBackground(new java.awt.Color(153, 0, 255)); btnSalvar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnSalvar.setForeground(new java.awt.Color(255, 255, 255)); btnSalvar.setText("Salvar"); btnSalvar.setEnabled(false); btnSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarActionPerformed(evt); } }); btnCancelar.setBackground(new java.awt.Color(153, 0, 255)); btnCancelar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnCancelar.setForeground(new java.awt.Color(255, 255, 255)); btnCancelar.setText("Cancelar"); btnCancelar.setEnabled(false); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } }); btnEditar.setBackground(new java.awt.Color(153, 0, 255)); btnEditar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnEditar.setForeground(new java.awt.Color(255, 255, 255)); btnEditar.setText("Editar"); btnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditarActionPerformed(evt); } }); btnExcluir.setBackground(new java.awt.Color(153, 0, 255)); btnExcluir.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnExcluir.setForeground(new java.awt.Color(255, 255, 255)); btnExcluir.setText("Excluir"); btnExcluir.setEnabled(false); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); btnAtualizar.setBackground(new java.awt.Color(153, 0, 255)); btnAtualizar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnAtualizar.setForeground(new java.awt.Color(255, 255, 255)); btnAtualizar.setText("Atualizar"); btnAtualizar.setEnabled(false); btnAtualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAtualizarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(15, Short.MAX_VALUE) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(25, Short.MAX_VALUE)) ); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel4.setText("ID"); txtID.setEditable(false); txtID.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtID.setForeground(new java.awt.Color(255, 255, 255)); txtID.setEnabled(false); txtNomeBackup.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtNomeBackup.setEnabled(false); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel5.setText("Horas"); jsHora.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jsHora.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.HOUR_OF_DAY) ); jsHora.setToolTipText(""); jsHora.setEnabled(false); jLabel6.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel6.setText("Nome do Backup"); jMenu1.setText("File"); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1374, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSelecionarArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSelecionarDiretorioDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jdData, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(67, 67, 67))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jsHora, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(rdbPC, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(24, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSelecionarArquivoDiretorio)) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSelecionarDiretorioDestino)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jsHora, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rdbPC)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jdData, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnSelecionarArquivoDiretorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarArquivoDiretorioActionPerformed selecionarDiretorioOuArquivo(); }//GEN-LAST:event_btnSelecionarArquivoDiretorioActionPerformed private void btnSelecionarDiretorioDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarDiretorioDestinoActionPerformed selecionarDiretorio(); }//GEN-LAST:event_btnSelecionarDiretorioDestinoActionPerformed private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed configurarBotoes(true, true, false, false, true, false, false, true); habilitarCampos(true, true, true, true, true, true); }//GEN-LAST:event_btnNovoActionPerformed private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed configurarBotoes(false, false, true, false, false, true, false, false); habilitarCampos(false, false, false, false, false, false); limparCampos(); }//GEN-LAST:event_btnCancelarActionPerformed private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed salvarAgendamentoBackup(); }//GEN-LAST:event_btnSalvarActionPerformed private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed editarAgendamentoBackup(); }//GEN-LAST:event_btnEditarActionPerformed private void btnAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtualizarActionPerformed atualizarAgendamentoBuckup(); }//GEN-LAST:event_btnAtualizarActionPerformed private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed excluirAgendamentoBackup(); }//GEN-LAST:event_btnExcluirActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FerramentaDeBackupView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new FerramentaDeBackupView().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAtualizar; private javax.swing.JButton btnCancelar; private javax.swing.JButton btnEditar; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnNovo; private javax.swing.JButton btnSalvar; private javax.swing.JButton btnSelecionarArquivoDiretorio; private javax.swing.JButton btnSelecionarDiretorioDestino; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private com.toedter.calendar.JDateChooser jdData; private javax.swing.JSpinner jsHora; private javax.swing.JTable jtTabela; private javax.swing.JRadioButton rdbPC; private javax.swing.JTextField txtArquivoDiretorio; private javax.swing.JTextField txtDiretorio; private javax.swing.JTextField txtID; private javax.swing.JTextField txtNomeBackup; // End of variables declaration//GEN-END:variables /** * Permite ao usuário escolher entre selecionar um diretório ou um arquivo. * <p> * Este método exibe uma caixa de diálogo com duas opções: "Diretório" e * "Arquivo". A escolha do usuário determina se o {@link JFileChooser} será * configurado para selecionar apenas diretórios ou apenas arquivos. Após a * seleção, o caminho absoluto do diretório ou arquivo escolhido é retornado * dentro de um {@link java.util.Optional}. * </p> * * <p> * Se o usuário selecionar um item, o caminho absoluto é retornado * encapsulado em um {@code Optional<String>}. Se o usuário cancelar a * operação ou se ocorrer um erro, um {@code Optional<String>} vazio é * retornado. * </p> * * <p> * Exceções são tratadas internamente, e uma mensagem de erro é exibida em * caso de falha. * </p> * * @return Um {@link java.util.Optional<String>} contendo o caminho do * arquivo ou diretório selecionado, ou um {@code Optional} vazio em caso de * cancelamento ou erro. */ public Optional<String> selecionarDiretorioOuArquivo() { Object[] options = {"Diretório", "Arquivo"}; int choice = JOptionPane.showOptionDialog( null, "Você deseja selecionar um diretório ou um arquivo?", "Selecionar Diretório ou Arquivo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(choice == JOptionPane.YES_OPTION ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); try { int option = fileChooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (selectedFile != null) { String caminhoArquivoDiretorio = selectedFile.getAbsolutePath(); txtArquivoDiretorio.setText(caminhoArquivoDiretorio); // Ajuste conforme sua lógica de interface return Optional.of(caminhoArquivoDiretorio); } } } catch (HeadlessException error) { JOptionPane.showMessageDialog(null, "Ocorreu um erro ao selecionar o arquivo ou diretório " + error, "Erro", JOptionPane.ERROR_MESSAGE); } return Optional.empty(); } /** * Abre uma caixa de diálogo para o usuário selecionar um diretório. * <p> * Este método utiliza o {@link JFileChooser} configurado para permitir que * o usuário selecione apenas diretórios. Após a seleção, o caminho absoluto * do diretório escolhido é atribuído a uma variável de instância. * </p> * * <p> * Se o usuário selecionar um diretório, o caminho absoluto é armazenado na * variável {@code txtDiretorio}. Em caso de cancelamento da operação, * nenhuma ação é tomada. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, mas atualiza * diretamente a interface do usuário com o caminho do diretório * selecionado. * </p> */ public void selecionarDiretorio() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Configura para selecionar apenas diretórios int option = fileChooser.showOpenDialog(null); // Abre a caixa de diálogo centralizada if (option == JFileChooser.APPROVE_OPTION) { File selectedDirectory = fileChooser.getSelectedFile(); if (selectedDirectory != null) { // Atribui o caminho à variável de instância String caminhoDoDiretorio = selectedDirectory.getAbsolutePath(); txtDiretorio.setText(caminhoDoDiretorio); } } } /** * Verifica a existência do banco de dados e o cria, se necessário. * <p> * Este método utiliza a classe {@link BancoDeDadosDAO} para verificar se o * banco de dados já existe. Se o banco de dados não existir, ele é criado * por meio do método {@link BancoDeDadosDAO#verificarECriarBancoDeDados()}. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, pois sua função é * verificar e criar o banco de dados, se necessário, sem fornecer * resultados diretos. * </p> */ public final void verificarBancoDeDados() {
BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO();
0
2023-12-02 02:23:51+00:00
12k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/judge/self/JudgeDispatcher.java
[ { "identifier": "StatusSystemErrorException", "path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusSystemErrorException.java", "snippet": "public class StatusSystemErrorException extends Exception {\n\n public StatusSystemErrorException() {\n }\n\n public StatusSystemErrorExce...
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; import top.hcode.hoj.common.exception.StatusSystemErrorException; import top.hcode.hoj.dao.judge.JudgeEntityService; import top.hcode.hoj.pojo.dto.TestJudgeReq; import top.hcode.hoj.pojo.entity.judge.Judge; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils;
9,133
package top.hcode.hoj.judge.self; /** * @Author: Himit_ZH * @Date: 2021/2/5 16:44 * @Description: */ @Component @Slf4j(topic = "hoj") @RefreshScope public class JudgeDispatcher { @Autowired private RedisUtils redisUtils; @Autowired private JudgeEntityService judgeEntityService; @Autowired private JudgeReceiver judgeReceiver; @Value("${hoj.judge.token}") private String judgeToken; public void sendTask(Long judgeId, Long pid, Boolean isContest) { JSONObject task = new JSONObject(); task.set("judgeId", judgeId); task.set("token", judgeToken); task.set("isContest", isContest); try { boolean isOk; if (isContest) {
package top.hcode.hoj.judge.self; /** * @Author: Himit_ZH * @Date: 2021/2/5 16:44 * @Description: */ @Component @Slf4j(topic = "hoj") @RefreshScope public class JudgeDispatcher { @Autowired private RedisUtils redisUtils; @Autowired private JudgeEntityService judgeEntityService; @Autowired private JudgeReceiver judgeReceiver; @Value("${hoj.judge.token}") private String judgeToken; public void sendTask(Long judgeId, Long pid, Boolean isContest) { JSONObject task = new JSONObject(); task.set("judgeId", judgeId); task.set("token", judgeToken); task.set("isContest", isContest); try { boolean isOk; if (isContest) {
isOk = redisUtils.llPush(Constants.Queue.CONTEST_JUDGE_WAITING.getName(), JSONUtil.toJsonStr(task));
4
2023-12-03 14:15:51+00:00
12k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
10,366
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) {
List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam);
1
2023-11-19 16:04:32+00:00
12k
NEWCIH2023/galois
src/main/java/io/liuguangsheng/galois/service/spring/listeners/SpringBeanListener.java
[ { "identifier": "FileType", "path": "src/main/java/io/liuguangsheng/galois/constants/FileType.java", "snippet": "public enum FileType {\n\n /**\n * Class file file type.\n */\n CLASS_FILE(\".class\"),\n /**\n * Xml file file type.\n */\n XML_FILE(\".xml\"),\n /**\n * J...
import io.liuguangsheng.galois.utils.FileUtil; import io.liuguangsheng.galois.utils.GaloisLog; import org.slf4j.Logger; import java.io.File; import java.lang.instrument.ClassDefinition; import io.liuguangsheng.galois.constants.FileType; import io.liuguangsheng.galois.service.annotation.LazyBean; import io.liuguangsheng.galois.service.monitor.FileChangedListener; import io.liuguangsheng.galois.service.spring.SpringAgentService; import io.liuguangsheng.galois.service.spring.SpringBeanReloader; import io.liuguangsheng.galois.utils.ClassUtil;
8,111
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * 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 io.liuguangsheng.galois.service.spring.listeners; /** * Spring的Bean变动监听器 * * @author liuguangsheng */ @LazyBean(value = "SpringBeanListener", manager = SpringAgentService.class) public class SpringBeanListener implements FileChangedListener { private static final Logger logger = new GaloisLog(SpringBeanListener.class); private static final ClassChangedCache classChangedCache = ClassChangedCache.getInstance(); private final SpringBeanReloader springBeanReloader = SpringBeanReloader.getInstance(); @Override public boolean isSuitable(File file) {
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * 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 io.liuguangsheng.galois.service.spring.listeners; /** * Spring的Bean变动监听器 * * @author liuguangsheng */ @LazyBean(value = "SpringBeanListener", manager = SpringAgentService.class) public class SpringBeanListener implements FileChangedListener { private static final Logger logger = new GaloisLog(SpringBeanListener.class); private static final ClassChangedCache classChangedCache = ClassChangedCache.getInstance(); private final SpringBeanReloader springBeanReloader = SpringBeanReloader.getInstance(); @Override public boolean isSuitable(File file) {
return FileUtil.matchFileType(file, FileType.CLASS_FILE);
5
2023-11-22 04:51:35+00:00
12k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/strategy/aggs/MathCategoryAggregation.java
[ { "identifier": "FieldSqlConverter", "path": "src/main/java/com/ly/ckibana/strategy/aggs/converter/FieldSqlConverter.java", "snippet": "@Data\npublic class FieldSqlConverter implements SqlConverter {\n\n private String condition;\n\n private String name;\n\n @Override\n public String toSql(d...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.strategy.aggs.converter.FieldSqlConverter; import com.ly.ckibana.strategy.aggs.converter.SqlConverter; import com.ly.ckibana.model.compute.aggregation.AggsParam; import com.ly.ckibana.model.compute.aggregation.bucket.MathBucket; import com.ly.ckibana.model.enums.AggCategory; import com.ly.ckibana.util.ProxyUtils; import com.ly.ckibana.util.SqlUtils; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
8,359
/* * 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.strategy.aggs; @EqualsAndHashCode(callSuper = true) @Component @NoArgsConstructor @Data public class MathCategoryAggregation extends Aggregation { public MathCategoryAggregation(AggsParam aggsParam) { super(aggsParam); this.setAggCategory(AggCategory.MATH); } /** * 这方法名实在没看懂是啥. * * @param mathKey mathKey * @return List */ public List<SqlConverter> buildMathCategorySelectSql(String mathKey) { List<SqlConverter> result = new ArrayList<>();
/* * 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.strategy.aggs; @EqualsAndHashCode(callSuper = true) @Component @NoArgsConstructor @Data public class MathCategoryAggregation extends Aggregation { public MathCategoryAggregation(AggsParam aggsParam) { super(aggsParam); this.setAggCategory(AggCategory.MATH); } /** * 这方法名实在没看懂是啥. * * @param mathKey mathKey * @return List */ public List<SqlConverter> buildMathCategorySelectSql(String mathKey) { List<SqlConverter> result = new ArrayList<>();
FieldSqlConverter fieldAggregation = new FieldSqlConverter();
0
2023-11-21 09:12:07+00:00
12k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/undo/undoables/ImagesRemoveUndoable.java
[ { "identifier": "Utils", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/Utils.java", "snippet": "public class Utils {\n\n public static final int[] EMPTY_KEYBIND = new int[] {};\n\n public static void openFileExplorer (FileHandle startDirectory) throws IOException {\n if (startDire...
import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g2d.ParticleEmitter; import com.badlogic.gdx.graphics.g2d.Sprite; import com.ray3k.gdxparticleeditor.Utils; import com.ray3k.gdxparticleeditor.undo.Undoable; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.widgets.panels.EffectEmittersPanel.effectEmittersPanel; import static com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.emitterPropertiesPanel;
9,002
package com.ray3k.gdxparticleeditor.undo.undoables; /** * Undoable to remove images from the emitter. */ public class ImagesRemoveUndoable implements Undoable { private ParticleEmitter emitter; private String path; private FileHandle fileHandle; private Sprite sprite; private String description; private int index; public ImagesRemoveUndoable(ParticleEmitter emitter, String path, FileHandle fileHandle, Sprite sprite, String description) { this.emitter = emitter; this.path = path; this.fileHandle = fileHandle; this.sprite = sprite; this.description = description; index = emitter.getSprites().indexOf(sprite, true); } @Override public void undo() { selectedEmitter = emitter; emitter.getImagePaths().insert(index, path); fileHandles.put(path, fileHandle); sprites.put(path, sprite); emitter.getSprites().insert(index, sprite); refreshDisplay(); } @Override public void redo() { selectedEmitter = emitter; emitter.getImagePaths().removeValue(path, false);
package com.ray3k.gdxparticleeditor.undo.undoables; /** * Undoable to remove images from the emitter. */ public class ImagesRemoveUndoable implements Undoable { private ParticleEmitter emitter; private String path; private FileHandle fileHandle; private Sprite sprite; private String description; private int index; public ImagesRemoveUndoable(ParticleEmitter emitter, String path, FileHandle fileHandle, Sprite sprite, String description) { this.emitter = emitter; this.path = path; this.fileHandle = fileHandle; this.sprite = sprite; this.description = description; index = emitter.getSprites().indexOf(sprite, true); } @Override public void undo() { selectedEmitter = emitter; emitter.getImagePaths().insert(index, path); fileHandles.put(path, fileHandle); sprites.put(path, sprite); emitter.getSprites().insert(index, sprite); refreshDisplay(); } @Override public void redo() { selectedEmitter = emitter; emitter.getImagePaths().removeValue(path, false);
Utils.removeUnusedImageFiles();
0
2023-11-24 15:58:20+00:00
12k
siam1026/siam-server
siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/service/GoodsSpecificationOptionService.java
[ { "identifier": "GoodsSpecificationOptionDto", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/model/dto/GoodsSpecificationOptionDto.java", "snippet": "public class GoodsSpecificationOptionDto extends GoodsSpecificationOption {\n @ApiModelProperty(notes = \"规格名称\")...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_goods.model.dto.GoodsSpecificationOptionDto; import com.siam.system.modular.package_goods.entity.GoodsAccessories; import com.siam.system.modular.package_goods.entity.GoodsSpecificationOption; import com.siam.system.modular.package_goods.model.example.GoodsSpecificationOptionExample; import java.math.BigDecimal; import java.util.List; import java.util.Map;
7,552
package com.siam.system.modular.package_goods.service; public interface GoodsSpecificationOptionService { int countByExample(GoodsSpecificationOptionExample example); void deleteByPrimaryKey(Integer id); void insertSelective(GoodsSpecificationOption record); List<GoodsSpecificationOption> selectByExample(GoodsSpecificationOptionExample example); GoodsSpecificationOption selectByPrimaryKey(Integer id); void updateByExampleSelective(GoodsSpecificationOption record, GoodsSpecificationOptionExample example); void updateByPrimaryKeySelective(GoodsSpecificationOption record); Page<GoodsSpecificationOption> getListByPage(int pageNo, int pageSize, GoodsSpecificationOption goodsSpecificationOption); Page<Map<String, Object>> getListByPageJoinGoods(int pageNo, int pageSize, GoodsSpecificationOptionDto goodsSpecificationOptionDto); int selectMaxSortNumberByGoodsSpecificationId(Integer specificationId); BigDecimal selectSumPriceByGoodsIdAndName(Integer goodsId, List<String> nameList); /** * 修改商品辅料时,级联修改商品规格选项的价格、库存 * @param goodsAccessories */
package com.siam.system.modular.package_goods.service; public interface GoodsSpecificationOptionService { int countByExample(GoodsSpecificationOptionExample example); void deleteByPrimaryKey(Integer id); void insertSelective(GoodsSpecificationOption record); List<GoodsSpecificationOption> selectByExample(GoodsSpecificationOptionExample example); GoodsSpecificationOption selectByPrimaryKey(Integer id); void updateByExampleSelective(GoodsSpecificationOption record, GoodsSpecificationOptionExample example); void updateByPrimaryKeySelective(GoodsSpecificationOption record); Page<GoodsSpecificationOption> getListByPage(int pageNo, int pageSize, GoodsSpecificationOption goodsSpecificationOption); Page<Map<String, Object>> getListByPageJoinGoods(int pageNo, int pageSize, GoodsSpecificationOptionDto goodsSpecificationOptionDto); int selectMaxSortNumberByGoodsSpecificationId(Integer specificationId); BigDecimal selectSumPriceByGoodsIdAndName(Integer goodsId, List<String> nameList); /** * 修改商品辅料时,级联修改商品规格选项的价格、库存 * @param goodsAccessories */
void updateByGoodsAccessories(GoodsAccessories goodsAccessories);
1
2023-11-26 12:41:06+00:00
12k
windsbell/shardingkey-autofill
src/main/java/com/windsbell/shardingkey/autofill/handler/BusinessKeyStrategyHelper.java
[ { "identifier": "StatementParser", "path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/StatementParser.java", "snippet": "public abstract class StatementParser implements SelectVisitor, FromItemVisitor, ExpressionVisitor, ItemsListVisitor, SelectItemVisitor, StatementVisitor {\n\n pr...
import com.windsbell.shardingkey.autofill.jsqlparser.StatementParser; import com.windsbell.shardingkey.autofill.strategy.BusinessKeyStrategy; import com.windsbell.shardingkey.autofill.strategy.BusinessStrategy; import com.windsbell.shardingkey.autofill.strategy.TableShardingKeyStrategy; import lombok.Getter; import net.sf.jsqlparser.expression.BinaryExpression; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.JdbcParameter; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.Join; import net.sf.jsqlparser.statement.select.PlainSelect; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
7,399
package com.windsbell.shardingkey.autofill.handler; /** * 业务字段策略执行器: * 匹配SQL中,找到必填业务字段和值,找到任意业务字段和值 */ public class BusinessKeyStrategyHelper extends StatementParser { private final Map<String, Map<String, BusinessStrategy<Object>>> matchNecessaryColumnMap = new LinkedHashMap<>(); // 匹配必填业务字段map private final Map<String, Map<String, BusinessStrategy<Object>>> matchAnyOneColumnMap = new LinkedHashMap<>(); // 匹配任意业务字段map private final List<?> parameterList; // 占位符内容值列表 @Getter private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 表分片键映射策略map @Getter
package com.windsbell.shardingkey.autofill.handler; /** * 业务字段策略执行器: * 匹配SQL中,找到必填业务字段和值,找到任意业务字段和值 */ public class BusinessKeyStrategyHelper extends StatementParser { private final Map<String, Map<String, BusinessStrategy<Object>>> matchNecessaryColumnMap = new LinkedHashMap<>(); // 匹配必填业务字段map private final Map<String, Map<String, BusinessStrategy<Object>>> matchAnyOneColumnMap = new LinkedHashMap<>(); // 匹配任意业务字段map private final List<?> parameterList; // 占位符内容值列表 @Getter private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 表分片键映射策略map @Getter
private List<BusinessKeyStrategy> businessKeyStrategyList;
1
2023-11-23 09:05:56+00:00
12k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/writer/CityJSONWriter.java
[ { "identifier": "PersistentMapStore", "path": "citydb-core/src/main/java/org/citydb/core/cache/PersistentMapStore.java", "snippet": "public class PersistentMapStore implements AutoCloseable {\n private MVStore store;\n private final Path backingFile;\n\n public enum CompressionLevel {\n ...
import org.apache.logging.log4j.Logger; import org.citydb.core.cache.PersistentMapStore; import org.citydb.core.concurrent.CountLatch; import org.citydb.core.concurrent.ExecutorHelper; import org.citydb.core.file.OutputFile; import org.citydb.io.citygml.CityGMLAdapterContext; import org.citydb.io.citygml.writer.util.GlobalFeatureWriter; import org.citydb.io.writer.FeatureWriter; import org.citydb.io.writer.WriteException; import org.citydb.io.writer.WriteOptions; import org.citydb.logging.LoggerManager; import org.citydb.model.feature.Feature; import org.citydb.model.geometry.ImplicitGeometry; import org.citygml4j.cityjson.CityJSONContext; import org.citygml4j.cityjson.writer.AbstractCityJSONWriter; import org.citygml4j.cityjson.writer.CityJSONWriteException; import org.citygml4j.core.model.core.AbstractFeature; import org.citygml4j.core.util.reference.DefaultReferenceResolver; import org.xmlobjects.gml.model.geometry.AbstractGeometry; import org.xmlobjects.gml.util.reference.ReferenceResolver; import java.io.IOException; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService;
9,206
/* * 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.writer; public class CityJSONWriter implements FeatureWriter, GlobalFeatureWriter { private final Logger logger = LoggerManager.getInstance().getLogger(CityJSONWriter.class); private final CityGMLAdapterContext adapterContext; private final CityJSONContext cityJSONContext; private AbstractCityJSONWriter<?> writer; private PersistentMapStore store; private ExecutorService service; private ThreadLocal<ModelSerializerHelper> helpers; private CountLatch countLatch; private Throwable exception; private volatile boolean isInitialized; private volatile boolean shouldRun; public CityJSONWriter(CityGMLAdapterContext adapterContext, CityJSONContext cityJSONContext) { this.adapterContext = Objects.requireNonNull(adapterContext, "CityGML adapter context must not be null."); this.cityJSONContext = Objects.requireNonNull(cityJSONContext, "CityJSON context must not be null."); } @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.writer; public class CityJSONWriter implements FeatureWriter, GlobalFeatureWriter { private final Logger logger = LoggerManager.getInstance().getLogger(CityJSONWriter.class); private final CityGMLAdapterContext adapterContext; private final CityJSONContext cityJSONContext; private AbstractCityJSONWriter<?> writer; private PersistentMapStore store; private ExecutorService service; private ThreadLocal<ModelSerializerHelper> helpers; private CountLatch countLatch; private Throwable exception; private volatile boolean isInitialized; private volatile boolean shouldRun; public CityJSONWriter(CityGMLAdapterContext adapterContext, CityJSONContext cityJSONContext) { this.adapterContext = Objects.requireNonNull(adapterContext, "CityGML adapter context must not be null."); this.cityJSONContext = Objects.requireNonNull(cityJSONContext, "CityJSON context must not be null."); } @Override
public void initialize(OutputFile file, WriteOptions options) throws WriteException {
8
2023-11-19 12:29:54+00:00
12k
magmamaintained/Magma-1.12.2
src/main/java/com/destroystokyo/paper/event/entity/EntityPathfindEvent.java
[ { "identifier": "Location", "path": "src/main/java/org/bukkit/Location.java", "snippet": "public class Location implements Cloneable, ConfigurationSerializable {\n private World world;\n private double x;\n private double y;\n private double z;\n private float pitch;\n private float ya...
import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent;
10,234
package com.destroystokyo.paper.event.entity; /** * Fired when an Entity decides to start moving towards a location. * * This event does not fire for the entities actual movement. Only when it * is choosing to start moving to a location. */ public class EntityPathfindEvent extends EntityEvent implements Cancellable { private final Entity targetEntity;
package com.destroystokyo.paper.event.entity; /** * Fired when an Entity decides to start moving towards a location. * * This event does not fire for the entities actual movement. Only when it * is choosing to start moving to a location. */ public class EntityPathfindEvent extends EntityEvent implements Cancellable { private final Entity targetEntity;
private final Location loc;
0
2023-11-22 11:25:51+00:00
12k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/chat/ChatCompletionFunctionToolDemo.java
[ { "identifier": "ChatCompletionApi", "path": "src/main/java/com/logaritex/ai/api/ChatCompletionApi.java", "snippet": "public class ChatCompletionApi {\n\n\tprivate static final String DEFAULT_BASE_URL = \"https://api.openai.com\";\n\tprivate static final String DEFAULT_EMBEDDING_MODEL = \"text-embedding...
import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.logaritex.ai.api.ChatCompletionApi; import com.logaritex.ai.api.ChatCompletionApi.ChatCompletion; import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage; import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage.Role; import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage.ToolCall; import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionRequest; import com.logaritex.ai.api.samples.function.WeatherFunction; import com.logaritex.ai.api.samples.function.WeatherFunction.Response;
7,818
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.chat; /** * Based on the OpenAI Function Calling tutorial: * https://platform.openai.com/docs/guides/function-calling/parallel-function-calling * * @author Christian Tzolov */ public class ChatCompletionFunctionToolDemo { public static void main(String[] args) {
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.chat; /** * Based on the OpenAI Function Calling tutorial: * https://platform.openai.com/docs/guides/function-calling/parallel-function-calling * * @author Christian Tzolov */ public class ChatCompletionFunctionToolDemo { public static void main(String[] args) {
var weatherService = new WeatherFunction(System.getenv("OPEN_WEATHER_MAP_API_KEY"));
1
2023-11-25 18:52:37+00:00
12k
Barsanti5BI/flight-simulator
src/Persona/Turista.java
[ { "identifier": "Gate", "path": "src/Aereo/Gate.java", "snippet": "public class Gate extends Thread{\n Timer timer;\n TimerTask timerTask;\n int nomeGate;\n String destinazione;\n Coda<Turista> codaPrioritaria;\n Coda<Turista> codaNormale;\n Boolean TerminatiIControlli;\n Coda<Tu...
import Aereo.Gate; import Aereoporto.ZonaArrivi.Dogana; import Aereoporto.ZonaArrivi.RitiroBagagli; import Aereoporto.ZonaArrivi.ZonaArrivi; import Aereoporto.ZonaCheckIn.CartaImbarco; import Aereoporto.ZonaCheckIn.ZonaCheckIn; import Aereoporto.ZonaControlli.MetalDetector; import Aereoporto.ZonaControlli.Scanner; import Aereoporto.ZonaControlli.Settore; import Aereoporto.ZonaControlli.ZonaControlli; import Aereoporto.ZonaEntrata.ZonaEntrata; import Aereoporto.ZonaNegozi.Negozio; import Aereoporto.ZonaNegozi.ZonaNegozi; import Aereoporto.ZonaPartenze.ZonaPartenze; import Utils.Coda; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Random;
8,465
this.oggetti = oggetti; this.doc = doc; setName(doc.getCognome() + " " + doc.getNome()); r = new Random(); vuoleFareAcquisto = r.nextBoolean(); this.codAereo = codAereo; this.inPartenza = inPartenza; deveFareCheckIn = true; deveFareControlli = false; devePoggiareBagagliAiControlli = true; deveFareControlliAlMetalDetector = true; deveRitirareBagagliAiControlli = true; controlliFattiConSuccesso = false; bagaglioSospetto = false; controlloMetalDetectorSospetto = false; perquisizioneTerminata = false; prontoPerImbarcarsi = false; passatoControlliGate = false; esitoControlloGate = false; gateGiusto = false; arrivatoAreaArrivi = false; haPassatoControlliArr = false; esitoControlli = false; haRitiratoBagagliArr = false; haFinitoArr = false; inPartenza = true; this.zonaCheckIn = zonaCheckIn; this.zonaControlli = zonaControlli; this.zonaNegozi = zonaNegozi; this.zonaPartenze = zonaPartenze; } public void run(){ System.out.println("Il turista " + getName() + " è stato generato"); while (true){ try{ // IL TURISTA DEVE PARTIRE if (inPartenza) { System.out.println("Il turista" + getName() + " si prepara ad affrontare il suo viaggio!"); // ZONA CHECK-IN if(deveFareCheckIn) { System.out.println("Il turista " + getName() + " si mette in attesa al banco del check-in per prendere la sua carta d'imbarco"); zonaCheckIn.getBanco().getCodaTuristi().push(this); synchronized (zonaCheckIn.getBanco().getImpiegatoCheckIn()) { while(deveFareCheckIn) { zonaCheckIn.getBanco().getImpiegatoCheckIn().wait(); } } System.out.println("Il turista " + getName() + " ha la sua carta d'imbarco e va ai controlli"); deveFareControlli = true; } // ZONA CONTROLLI if (deveFareControlli) { System.out.println("Il turista " + getName() + " è arrivato ai controlli"); Settore settore = zonaControlli.getSettore(0); MetalDetector metalDetector = settore.getMetalDetector(); Scanner scanner = settore.getScannerBagagali(); if (devePoggiareBagagliAiControlli) { if (bagaglio != null) { scanner.getCodaBagagli().push(bagaglio); System.out.println("Il turista " + getName() + " ha poggiato i bagagli sul rullo"); devePoggiareBagagliAiControlli = false; bagaglio = null; deveRitirareBagagliAiControlli = true; } else { devePoggiareBagagliAiControlli = false; deveRitirareBagagliAiControlli = false; } } if (deveFareControlliAlMetalDetector) { System.out.println("Il turista " + getName() + " si sta mettendo in coda per il metal detector"); metalDetector.getCodaTuristiAttesa().push(this); synchronized (metalDetector) { while (deveFareControlliAlMetalDetector) { metalDetector.wait(); } } if (!controlloMetalDetectorSospetto) { if (deveRitirareBagagliAiControlli) { if (bagaglioSospetto) { System.out.println("Turista arrestato!"); break; } else { // il turista continua a cercare il bagaglio finchè non lo System.out.println("Il turista " + getName() + " sta cercando il suo bagaglio..."); cercaBagaglio(scanner.getCodaBagagliControllati()); } } } else { System.out.println("Scansione di potenziali oggetti metallicie effettuata"); synchronized (metalDetector.getImpiegatoControlli()) { while (!perquisizioneTerminata) { metalDetector.getImpiegatoControlli().wait(); } } break; } deveFareControlli = false; controlliFattiConSuccesso = true; prontoPerImbarcarsi = true; } // ZONA NEGOZI if (vuoleFareAcquisto) { indiceNegozio = r.nextInt(0, zonaNegozi.getListaNegozi().size());
package Persona; public class Turista extends Thread{ // Determinazione turista public boolean inPartenza; public boolean inArrivo; //ZONA CHECKIN public ZonaCheckIn zonaCheckIn; public int indiceSettore; public boolean deveFareCheckIn; private CartaImbarco cartaImbarco; //ZONA CONTROLLI public ZonaControlli zonaControlli; public int IndiceSettore; public boolean deveFareControlli; public boolean devePoggiareBagagliAiControlli; public boolean deveFareControlliAlMetalDetector; public boolean deveRitirareBagagliAiControlli; public boolean controlliFattiConSuccesso; public boolean bagaglioSospetto; public boolean controlloMetalDetectorSospetto; public boolean perquisizioneTerminata; //ZONA NEGOZI public ZonaNegozi zonaNegozi; public int indiceNegozio; public boolean vuoleFareAcquisto; public List<Prodotto> oggettiDaComprare; private @Nullable Bagaglio bagaglio; private boolean pagato; // ZONA GATE public ZonaPartenze zonaPartenze; public boolean prontoPerImbarcarsi; public boolean passatoControlliGate; public boolean esitoControlloGate; public boolean gateGiusto; // ZONA ARRIVI public ZonaArrivi zonaArrivi; public boolean arrivatoAreaArrivi; public boolean haPassatoControlliArr; public boolean esitoControlli; public boolean haRitiratoBagagliArr; public boolean haFinitoArr; // elementi utili private List<Oggetto> oggetti; private Documento doc; private Random r; private int codAereo; public Turista(Documento doc, Bagaglio bag, CartaImbarco cartaImbarco, List<Oggetto> oggetti, int codAereo,ZonaCheckIn zonaCheckIn, ZonaControlli zonaControlli, ZonaNegozi zonaNegozi, ZonaPartenze zonaPartenze){ this.bagaglio = bag; this.cartaImbarco = cartaImbarco; this.oggetti = oggetti; this.doc = doc; setName(doc.getCognome() + " " + doc.getNome()); r = new Random(); vuoleFareAcquisto = r.nextBoolean(); this.codAereo = codAereo; this.inPartenza = inPartenza; deveFareCheckIn = true; deveFareControlli = false; devePoggiareBagagliAiControlli = true; deveFareControlliAlMetalDetector = true; deveRitirareBagagliAiControlli = true; controlliFattiConSuccesso = false; bagaglioSospetto = false; controlloMetalDetectorSospetto = false; perquisizioneTerminata = false; prontoPerImbarcarsi = false; passatoControlliGate = false; esitoControlloGate = false; gateGiusto = false; arrivatoAreaArrivi = false; haPassatoControlliArr = false; esitoControlli = false; haRitiratoBagagliArr = false; haFinitoArr = false; inPartenza = true; this.zonaCheckIn = zonaCheckIn; this.zonaControlli = zonaControlli; this.zonaNegozi = zonaNegozi; this.zonaPartenze = zonaPartenze; } public void run(){ System.out.println("Il turista " + getName() + " è stato generato"); while (true){ try{ // IL TURISTA DEVE PARTIRE if (inPartenza) { System.out.println("Il turista" + getName() + " si prepara ad affrontare il suo viaggio!"); // ZONA CHECK-IN if(deveFareCheckIn) { System.out.println("Il turista " + getName() + " si mette in attesa al banco del check-in per prendere la sua carta d'imbarco"); zonaCheckIn.getBanco().getCodaTuristi().push(this); synchronized (zonaCheckIn.getBanco().getImpiegatoCheckIn()) { while(deveFareCheckIn) { zonaCheckIn.getBanco().getImpiegatoCheckIn().wait(); } } System.out.println("Il turista " + getName() + " ha la sua carta d'imbarco e va ai controlli"); deveFareControlli = true; } // ZONA CONTROLLI if (deveFareControlli) { System.out.println("Il turista " + getName() + " è arrivato ai controlli"); Settore settore = zonaControlli.getSettore(0); MetalDetector metalDetector = settore.getMetalDetector(); Scanner scanner = settore.getScannerBagagali(); if (devePoggiareBagagliAiControlli) { if (bagaglio != null) { scanner.getCodaBagagli().push(bagaglio); System.out.println("Il turista " + getName() + " ha poggiato i bagagli sul rullo"); devePoggiareBagagliAiControlli = false; bagaglio = null; deveRitirareBagagliAiControlli = true; } else { devePoggiareBagagliAiControlli = false; deveRitirareBagagliAiControlli = false; } } if (deveFareControlliAlMetalDetector) { System.out.println("Il turista " + getName() + " si sta mettendo in coda per il metal detector"); metalDetector.getCodaTuristiAttesa().push(this); synchronized (metalDetector) { while (deveFareControlliAlMetalDetector) { metalDetector.wait(); } } if (!controlloMetalDetectorSospetto) { if (deveRitirareBagagliAiControlli) { if (bagaglioSospetto) { System.out.println("Turista arrestato!"); break; } else { // il turista continua a cercare il bagaglio finchè non lo System.out.println("Il turista " + getName() + " sta cercando il suo bagaglio..."); cercaBagaglio(scanner.getCodaBagagliControllati()); } } } else { System.out.println("Scansione di potenziali oggetti metallicie effettuata"); synchronized (metalDetector.getImpiegatoControlli()) { while (!perquisizioneTerminata) { metalDetector.getImpiegatoControlli().wait(); } } break; } deveFareControlli = false; controlliFattiConSuccesso = true; prontoPerImbarcarsi = true; } // ZONA NEGOZI if (vuoleFareAcquisto) { indiceNegozio = r.nextInt(0, zonaNegozi.getListaNegozi().size());
Negozio n = zonaNegozi.getListaNegozi().get(indiceNegozio);
11
2023-11-18 07:13:43+00:00
12k
Youkehai/openai_assistants_java
assistants-front/src/main/java/com/kh/assistants/front/controller/AssistantsApiController.java
[ { "identifier": "CommonPathReq", "path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/CommonPathReq.java", "snippet": "@Data\n@Accessors(chain = true)\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommonPathReq {\n private fin...
import io.github.youkehai.assistant.core.req.CommonPathReq; import io.github.youkehai.assistant.core.req.PageReq; import io.github.youkehai.assistant.core.req.assistants.CreateAssistantFileReq; import io.github.youkehai.assistant.core.req.message.CreateAndRunReq; import io.github.youkehai.assistant.core.req.message.CreateMessageReq; import io.github.youkehai.assistant.core.req.run.CreateRunReq; import io.github.youkehai.assistant.core.resp.BasePageResp; import io.github.youkehai.assistant.core.resp.assistants.AssistantFile; import io.github.youkehai.assistant.core.resp.assistants.Assistants; import io.github.youkehai.assistant.core.resp.file.File; import io.github.youkehai.assistant.core.resp.message.Message; import io.github.youkehai.assistant.core.resp.run.Run; import io.github.youkehai.assistant.core.resp.run.RunStep; import io.github.youkehai.assistant.core.resp.thread.Thread; import io.github.youkehai.assistant.core.service.AssistantsMessageApiService; import io.github.youkehai.assistant.core.service.AssistantsRunApiService; import io.github.youkehai.assistant.core.service.AssistantsService; import io.github.youkehai.assistant.core.service.AssistantsThreadApiService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile;
7,311
package com.kh.assistants.front.controller; /** * assistants api */ @AllArgsConstructor @Tag(name = "assistantsAPI") @RestController @RequestMapping("/assistant") @Slf4j public class AssistantsApiController { private final AssistantsMessageApiService assistantsMessageApiService; private final AssistantsRunApiService assistantsRunApiService; private final AssistantsService assistantsService; private final AssistantsThreadApiService assistantsThreadApiService; @Operation(summary = "获取消息列表") @GetMapping("/message/{threadId}") public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) { BasePageResp<Message> messageList = assistantsMessageApiService.getMessageList(threadId, pageReqVO); for (Message datum : messageList.getData()) { log.info("测试:{}", datum); } return messageList; } @Operation(summary = "发送并运行消息") @PostMapping("/message/{threadId}") public Run messageList(@PathVariable("threadId") String threadId, CreateAndRunReq req) { assistantsMessageApiService.createMessage(threadId, new CreateMessageReq().setContent(req.getContent())); return assistantsRunApiService.createRun(threadId, new CreateRunReq().setAssistant_id(req.getAssistant_id())); } @Operation(summary = "获取线程信息") @GetMapping("/thread/{threadId}") public Thread messageList(@PathVariable("threadId") String threadId) { return assistantsThreadApiService.retrieveThread(threadId); } @Operation(summary = "获取线程信息") @GetMapping("/assistants/{assistantsId}") public Assistants retrieveAssistants(@PathVariable("assistantsId") String assistantsId) { return assistantsService.retrieveAssistants(assistantsId); } @Operation(summary = "单纯的只上传文件,给某次问答使用") @GetMapping("/upload") public File retrieveAssistants(MultipartFile file) { return assistantsService.upload(file); } @Operation(summary = "上传文件并绑定具体的 assistant") @PostMapping("/createAssistantFile/{assistantsId}")
package com.kh.assistants.front.controller; /** * assistants api */ @AllArgsConstructor @Tag(name = "assistantsAPI") @RestController @RequestMapping("/assistant") @Slf4j public class AssistantsApiController { private final AssistantsMessageApiService assistantsMessageApiService; private final AssistantsRunApiService assistantsRunApiService; private final AssistantsService assistantsService; private final AssistantsThreadApiService assistantsThreadApiService; @Operation(summary = "获取消息列表") @GetMapping("/message/{threadId}") public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) { BasePageResp<Message> messageList = assistantsMessageApiService.getMessageList(threadId, pageReqVO); for (Message datum : messageList.getData()) { log.info("测试:{}", datum); } return messageList; } @Operation(summary = "发送并运行消息") @PostMapping("/message/{threadId}") public Run messageList(@PathVariable("threadId") String threadId, CreateAndRunReq req) { assistantsMessageApiService.createMessage(threadId, new CreateMessageReq().setContent(req.getContent())); return assistantsRunApiService.createRun(threadId, new CreateRunReq().setAssistant_id(req.getAssistant_id())); } @Operation(summary = "获取线程信息") @GetMapping("/thread/{threadId}") public Thread messageList(@PathVariable("threadId") String threadId) { return assistantsThreadApiService.retrieveThread(threadId); } @Operation(summary = "获取线程信息") @GetMapping("/assistants/{assistantsId}") public Assistants retrieveAssistants(@PathVariable("assistantsId") String assistantsId) { return assistantsService.retrieveAssistants(assistantsId); } @Operation(summary = "单纯的只上传文件,给某次问答使用") @GetMapping("/upload") public File retrieveAssistants(MultipartFile file) { return assistantsService.upload(file); } @Operation(summary = "上传文件并绑定具体的 assistant") @PostMapping("/createAssistantFile/{assistantsId}")
public AssistantFile CreateAssistantFileReq(@PathVariable("assistantsId") String assistantsId, MultipartFile file, String fileId) {
2
2023-11-25 13:19:47+00:00
12k
objectionary/opeo-maven-plugin
src/main/java/org/eolang/opeo/decompilation/DecompilerMachine.java
[ { "identifier": "Instruction", "path": "src/main/java/org/eolang/opeo/Instruction.java", "snippet": "public interface Instruction {\n\n /**\n * Opcode number.\n * @return Opcode number.\n */\n int opcode();\n\n /**\n * Retrieve operand by position index.\n * @param index Ope...
import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.cactoos.list.ListOf; import org.cactoos.map.MapEntry; import org.cactoos.map.MapOf; import org.eolang.opeo.Instruction; import org.eolang.opeo.ast.Add; import org.eolang.opeo.ast.AstNode; import org.eolang.opeo.ast.Attributes; import org.eolang.opeo.ast.Constructor; import org.eolang.opeo.ast.InstanceField; import org.eolang.opeo.ast.Invocation; import org.eolang.opeo.ast.Label; import org.eolang.opeo.ast.Literal; import org.eolang.opeo.ast.Mul; import org.eolang.opeo.ast.Opcode; import org.eolang.opeo.ast.Reference; import org.eolang.opeo.ast.Root; import org.eolang.opeo.ast.StoreLocal; import org.eolang.opeo.ast.Super; import org.eolang.opeo.ast.WriteField; import org.eolang.opeo.jeo.JeoLabel; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.xembly.Directive;
9,428
/* * The MIT License (MIT) * * Copyright (c) 2016-2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.eolang.opeo.decompilation; /** * Decompiler machine. * @since 0.1 */ public final class DecompilerMachine { /** * Output Stack. */ private final Deque<AstNode> stack; /** * Local variables. */ private final LocalVariables locals; /** * Instruction handlers. */ private final Map<Integer, InstructionHandler> handlers; /** * Arguments provided to decompiler. */ private final Map<String, String> arguments; /** * Constructor. */ public DecompilerMachine() { this(new HashMap<>()); } /** * Constructor. * @param args Arguments provided to decompiler. */ public DecompilerMachine(final Map<String, String> args) { this(new LocalVariables(), args); } /** * Constructor. * @param locals Local variables. * @param arguments Arguments provided to decompiler. */ public DecompilerMachine(final LocalVariables locals, final Map<String, String> arguments) { this.stack = new LinkedList<>(); this.locals = locals; this.arguments = arguments; this.handlers = new MapOf<>( new MapEntry<>(Opcodes.ICONST_1, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_2, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_3, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_4, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_5, new IconstHandler()), new MapEntry<>(Opcodes.IADD, new AddHandler()), new MapEntry<>(Opcodes.IMUL, new MulHandler()), new MapEntry<>(Opcodes.ILOAD, new LoadHandler(Type.INT_TYPE)), new MapEntry<>(Opcodes.LLOAD, new LoadHandler(Type.LONG_TYPE)), new MapEntry<>(Opcodes.FLOAD, new LoadHandler(Type.FLOAT_TYPE)), new MapEntry<>(Opcodes.DLOAD, new LoadHandler(Type.DOUBLE_TYPE)), new MapEntry<>(Opcodes.ALOAD, new LoadHandler(Type.getType(Object.class))), new MapEntry<>(Opcodes.ISTORE, new StoreHandler(Type.INT_TYPE)), new MapEntry<>(Opcodes.LSTORE, new StoreHandler(Type.LONG_TYPE)), new MapEntry<>(Opcodes.FSTORE, new StoreHandler(Type.FLOAT_TYPE)), new MapEntry<>(Opcodes.DSTORE, new StoreHandler(Type.DOUBLE_TYPE)), new MapEntry<>(Opcodes.ASTORE, new StoreHandler(Type.getType(Object.class))), new MapEntry<>(Opcodes.NEW, new NewHandler()), new MapEntry<>(Opcodes.DUP, new DupHandler()), new MapEntry<>(Opcodes.BIPUSH, new BipushHandler()), new MapEntry<>(Opcodes.INVOKESPECIAL, new InvokespecialHandler()), new MapEntry<>(Opcodes.INVOKEVIRTUAL, new InvokevirtualHandler()), new MapEntry<>(Opcodes.GETFIELD, new GetFieldHandler()), new MapEntry<>(Opcodes.PUTFIELD, new PutFieldHnadler()), new MapEntry<>(Opcodes.LDC, new LdcHandler()), new MapEntry<>(Opcodes.POP, new PopHandler()), new MapEntry<>(Opcodes.RETURN, new ReturnHandler()), new MapEntry<>(JeoLabel.LABEL_OPCODE, new LabelHandler()) ); } /** * Decompile instructions into directives. * @param instructions Instructions to decompile. * @return Decompiled instructions. */
/* * The MIT License (MIT) * * Copyright (c) 2016-2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.eolang.opeo.decompilation; /** * Decompiler machine. * @since 0.1 */ public final class DecompilerMachine { /** * Output Stack. */ private final Deque<AstNode> stack; /** * Local variables. */ private final LocalVariables locals; /** * Instruction handlers. */ private final Map<Integer, InstructionHandler> handlers; /** * Arguments provided to decompiler. */ private final Map<String, String> arguments; /** * Constructor. */ public DecompilerMachine() { this(new HashMap<>()); } /** * Constructor. * @param args Arguments provided to decompiler. */ public DecompilerMachine(final Map<String, String> args) { this(new LocalVariables(), args); } /** * Constructor. * @param locals Local variables. * @param arguments Arguments provided to decompiler. */ public DecompilerMachine(final LocalVariables locals, final Map<String, String> arguments) { this.stack = new LinkedList<>(); this.locals = locals; this.arguments = arguments; this.handlers = new MapOf<>( new MapEntry<>(Opcodes.ICONST_1, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_2, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_3, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_4, new IconstHandler()), new MapEntry<>(Opcodes.ICONST_5, new IconstHandler()), new MapEntry<>(Opcodes.IADD, new AddHandler()), new MapEntry<>(Opcodes.IMUL, new MulHandler()), new MapEntry<>(Opcodes.ILOAD, new LoadHandler(Type.INT_TYPE)), new MapEntry<>(Opcodes.LLOAD, new LoadHandler(Type.LONG_TYPE)), new MapEntry<>(Opcodes.FLOAD, new LoadHandler(Type.FLOAT_TYPE)), new MapEntry<>(Opcodes.DLOAD, new LoadHandler(Type.DOUBLE_TYPE)), new MapEntry<>(Opcodes.ALOAD, new LoadHandler(Type.getType(Object.class))), new MapEntry<>(Opcodes.ISTORE, new StoreHandler(Type.INT_TYPE)), new MapEntry<>(Opcodes.LSTORE, new StoreHandler(Type.LONG_TYPE)), new MapEntry<>(Opcodes.FSTORE, new StoreHandler(Type.FLOAT_TYPE)), new MapEntry<>(Opcodes.DSTORE, new StoreHandler(Type.DOUBLE_TYPE)), new MapEntry<>(Opcodes.ASTORE, new StoreHandler(Type.getType(Object.class))), new MapEntry<>(Opcodes.NEW, new NewHandler()), new MapEntry<>(Opcodes.DUP, new DupHandler()), new MapEntry<>(Opcodes.BIPUSH, new BipushHandler()), new MapEntry<>(Opcodes.INVOKESPECIAL, new InvokespecialHandler()), new MapEntry<>(Opcodes.INVOKEVIRTUAL, new InvokevirtualHandler()), new MapEntry<>(Opcodes.GETFIELD, new GetFieldHandler()), new MapEntry<>(Opcodes.PUTFIELD, new PutFieldHnadler()), new MapEntry<>(Opcodes.LDC, new LdcHandler()), new MapEntry<>(Opcodes.POP, new PopHandler()), new MapEntry<>(Opcodes.RETURN, new ReturnHandler()), new MapEntry<>(JeoLabel.LABEL_OPCODE, new LabelHandler()) ); } /** * Decompile instructions into directives. * @param instructions Instructions to decompile. * @return Decompiled instructions. */
public Iterable<Directive> decompileToXmir(final Instruction... instructions) {
0
2023-11-20 13:01:13+00:00
12k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityCatalyticReformer.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 gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.unification.material.Materials; import gregtech.client.renderer.ICubeRenderer; import gregtech.client.renderer.texture.Textures; import gregtech.common.blocks.BlockBoilerCasing; import gregtech.common.blocks.BlockMetalCasing; import gregtech.common.blocks.MetaBlocks; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull;
10,001
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCatalyticReformer extends RecipeMapMultiblockController { public EPMetaTileEntityCatalyticReformer(ResourceLocation metaTileEntityId) {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityCatalyticReformer extends RecipeMapMultiblockController { public EPMetaTileEntityCatalyticReformer(ResourceLocation metaTileEntityId) {
super(metaTileEntityId, EPRecipeMaps.CATALYTIC_REFORMER_RECIPES);
0
2023-11-26 01:56:35+00:00
12k
LaughingMuffin/laughing-logger
app/src/main/java/org/laughing/logger/ui/SettingsActivity.java
[ { "identifier": "LogLine", "path": "app/src/main/java/org/laughing/logger/data/LogLine.java", "snippet": "public class LogLine {\n\n private static final int TIMESTAMP_LENGTH = 19;\n\n private static Pattern logPattern = Pattern.compile(\n // log level\n \"(\\\\w)\" +\n ...
import android.app.Fragment; import android.app.FragmentManager; import android.content.Intent; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceFragment; import android.preference.SwitchPreference; import android.text.TextUtils; import android.view.KeyEvent; import android.view.MenuItem; import android.widget.Toast; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.laughing.logger.R; import org.laughing.logger.data.LogLine; import org.laughing.logger.helper.PackageHelper; import org.laughing.logger.helper.PreferenceHelper; import org.laughing.logger.util.ArrayUtil; import org.laughing.logger.util.StringUtil; import org.laughing.logger.widget.MultipleChoicePreference; import java.util.ArrayList; import java.util.List;
8,393
displayLimitPreference.setOnPreferenceChangeListener(this); filterPatternPreference = (EditTextPreference) findPreference(getString(R.string.pref_filter_pattern)); filterPatternPreference.setSummary(getString(R.string.pref_filter_pattern_summary)); filterPatternPreference.setOnPreferenceChangeListener(this); logLinePeriodPreference = (EditTextPreference) findPreference(getString(R.string.pref_log_line_period)); int logLinePrefValue = PreferenceHelper.getLogLinePeriodPreference(getActivity()); logLinePeriodPreference.setSummary(getString(R.string.pref_log_line_period_summary, logLinePrefValue, getString(R.string.pref_log_line_period_default))); logLinePeriodPreference.setOnPreferenceChangeListener(this); textSizePreference = (ListPreference) findPreference(getString(R.string.pref_text_size)); textSizePreference.setSummary(textSizePreference.getEntry()); textSizePreference.setOnPreferenceChangeListener(this); defaultLevelPreference = (ListPreference) findPreference(getString(R.string.pref_default_log_level)); defaultLevelPreference.setOnPreferenceChangeListener(this); setDefaultLevelPreferenceSummary(defaultLevelPreference.getEntry()); mThemePreference = findPreference("ui.theme"); mThemePreference.setOnPreferenceChangeListener(this); findPreference("ui.accent").setOnPreferenceChangeListener(this); bufferPreference = (MultipleChoicePreference) findPreference(getString(R.string.pref_buffer)); bufferPreference.setOnPreferenceChangeListener(this); setBufferPreferenceSummary(bufferPreference.getValue()); mThemePreference.setOnPreferenceChangeListener(this); mAboutPreference = findPreference(getString(R.string.pref_about)); mAboutPreference.setOnPreferenceClickListener(preference -> { // launch about activity Intent intent = new Intent(getActivity(), AboutDialogActivity.class); startActivity(intent); return true; }); mAboutPreference.setSummary(getString(R.string.version, PackageHelper.getVersionName(getActivity()))); scrubberPreference = (SwitchPreference) getPreferenceScreen().findPreference("scrubber"); scrubberPreference.setOnPreferenceChangeListener((preference, newValue) -> { LogLine.isScrubberEnabled = (boolean) newValue; return true; }); } private void setDefaultLevelPreferenceSummary(CharSequence entry) { defaultLevelPreference.setSummary( getString(R.string.pref_default_log_level_summary, entry)); } public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.getKey().equals(getString(R.string.pref_display_limit))) { // display buffer preference; update summary String input = ((String) newValue).trim(); try { int value = Integer.parseInt(input); if (value >= MIN_DISPLAY_LIMIT && value <= MAX_DISPLAY_LIMIT) { PreferenceHelper.setDisplayLimitPreference(getActivity(), value); displayLimitPreference.setSummary(getString(R.string.pref_display_limit_summary, value, getString(R.string.pref_display_limit_default))); // notify that a restart is required Toast.makeText(getActivity(), R.string.toast_pref_changed_restart_required, Toast.LENGTH_LONG).show(); return true; } } catch (NumberFormatException ignore) { } String invalidEntry = getString(R.string.toast_invalid_display_limit, MIN_DISPLAY_LIMIT, MAX_DISPLAY_LIMIT); Toast.makeText(getActivity(), invalidEntry, Toast.LENGTH_LONG).show(); return false; } else if (preference.getKey().equals(getString(R.string.pref_log_line_period))) { // log line period preference; update summary String input = ((String) newValue).trim(); try { int value = Integer.parseInt(input); if (value >= MIN_LOG_LINE_PERIOD && value <= MAX_LOG_LINE_PERIOD) { PreferenceHelper.setLogLinePeriodPreference(getActivity(), value); logLinePeriodPreference.setSummary(getString(R.string.pref_log_line_period_summary, value, getString(R.string.pref_log_line_period_default))); return true; } } catch (NumberFormatException ignore) { } Toast.makeText(getActivity(), R.string.pref_log_line_period_error, Toast.LENGTH_LONG).show(); return false; } else if (preference.getKey().equals(getString(R.string.pref_theme))) { setCurrentValue(preference.getKey()); return true; } else if (preference.getKey().equals("ui.accent")) { setCurrentValue(preference.getKey()); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent("org.openintents.action.REFRESH_THEME")); return true; } else if (preference.getKey().equals(getString(R.string.pref_buffer))) { // buffers pref // check to make sure nothing was left unchecked if (TextUtils.isEmpty(newValue.toString())) { Toast.makeText(getActivity(), R.string.pref_buffer_none_checked_error, Toast.LENGTH_SHORT).show(); return false; } // notify the LogcatActivity that the buffer has changed if (!newValue.toString().equals(bufferPreference.getValue())) { bufferChanged = true; } setBufferPreferenceSummary(newValue.toString()); return true; } else if (preference.getKey().equals(getString(R.string.pref_default_log_level))) { // default log level preference // update the summary to reflect changes ListPreference listPreference = (ListPreference) preference;
package org.laughing.logger.ui; public class SettingsActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar toolbar = findViewById(R.id.toolbar_actionbar); toolbar.setOverflowIcon(AppCompatResources.getDrawable(this, R.drawable.ic_more_vert)); setSupportActionBar(toolbar); FragmentManager fm = getFragmentManager(); Fragment f = fm.findFragmentById(R.id.content); if (f == null) { fm.beginTransaction() .replace(R.id.content, new SettingsFragment()) .commit(); } //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle(R.string.settings); } private void setResultAndFinish() { Intent data = new Intent(); FragmentManager fm = getFragmentManager(); SettingsFragment f = (SettingsFragment) fm.findFragmentById(R.id.content); data.putExtra("bufferChanged", f.getBufferChanged()); setResult(RESULT_OK, data); finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // set result and finish setResultAndFinish(); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: setResultAndFinish(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment implements OnPreferenceChangeListener { private static final int MAX_LOG_LINE_PERIOD = 1000; private static final int MIN_LOG_LINE_PERIOD = 1; private static final int MAX_DISPLAY_LIMIT = 100000; private static final int MIN_DISPLAY_LIMIT = 1000; private EditTextPreference logLinePeriodPreference, displayLimitPreference, filterPatternPreference; private ListPreference textSizePreference, defaultLevelPreference; private MultipleChoicePreference bufferPreference; private Preference mThemePreference; private Preference mAboutPreference; private SwitchPreference scrubberPreference; private boolean bufferChanged = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); setUpPreferences(); } public boolean getBufferChanged() { return bufferChanged; } private void setUpPreferences() { setCurrentValue("ui.accent"); setCurrentValue("ui.theme"); setCurrentValue("theme"); displayLimitPreference = (EditTextPreference) findPreference(getString(R.string.pref_display_limit)); int displayLimitValue = PreferenceHelper.getDisplayLimitPreference(getActivity()); displayLimitPreference.setSummary(getString(R.string.pref_display_limit_summary, displayLimitValue, getString(R.string.pref_display_limit_default))); displayLimitPreference.setOnPreferenceChangeListener(this); filterPatternPreference = (EditTextPreference) findPreference(getString(R.string.pref_filter_pattern)); filterPatternPreference.setSummary(getString(R.string.pref_filter_pattern_summary)); filterPatternPreference.setOnPreferenceChangeListener(this); logLinePeriodPreference = (EditTextPreference) findPreference(getString(R.string.pref_log_line_period)); int logLinePrefValue = PreferenceHelper.getLogLinePeriodPreference(getActivity()); logLinePeriodPreference.setSummary(getString(R.string.pref_log_line_period_summary, logLinePrefValue, getString(R.string.pref_log_line_period_default))); logLinePeriodPreference.setOnPreferenceChangeListener(this); textSizePreference = (ListPreference) findPreference(getString(R.string.pref_text_size)); textSizePreference.setSummary(textSizePreference.getEntry()); textSizePreference.setOnPreferenceChangeListener(this); defaultLevelPreference = (ListPreference) findPreference(getString(R.string.pref_default_log_level)); defaultLevelPreference.setOnPreferenceChangeListener(this); setDefaultLevelPreferenceSummary(defaultLevelPreference.getEntry()); mThemePreference = findPreference("ui.theme"); mThemePreference.setOnPreferenceChangeListener(this); findPreference("ui.accent").setOnPreferenceChangeListener(this); bufferPreference = (MultipleChoicePreference) findPreference(getString(R.string.pref_buffer)); bufferPreference.setOnPreferenceChangeListener(this); setBufferPreferenceSummary(bufferPreference.getValue()); mThemePreference.setOnPreferenceChangeListener(this); mAboutPreference = findPreference(getString(R.string.pref_about)); mAboutPreference.setOnPreferenceClickListener(preference -> { // launch about activity Intent intent = new Intent(getActivity(), AboutDialogActivity.class); startActivity(intent); return true; }); mAboutPreference.setSummary(getString(R.string.version, PackageHelper.getVersionName(getActivity()))); scrubberPreference = (SwitchPreference) getPreferenceScreen().findPreference("scrubber"); scrubberPreference.setOnPreferenceChangeListener((preference, newValue) -> { LogLine.isScrubberEnabled = (boolean) newValue; return true; }); } private void setDefaultLevelPreferenceSummary(CharSequence entry) { defaultLevelPreference.setSummary( getString(R.string.pref_default_log_level_summary, entry)); } public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.getKey().equals(getString(R.string.pref_display_limit))) { // display buffer preference; update summary String input = ((String) newValue).trim(); try { int value = Integer.parseInt(input); if (value >= MIN_DISPLAY_LIMIT && value <= MAX_DISPLAY_LIMIT) { PreferenceHelper.setDisplayLimitPreference(getActivity(), value); displayLimitPreference.setSummary(getString(R.string.pref_display_limit_summary, value, getString(R.string.pref_display_limit_default))); // notify that a restart is required Toast.makeText(getActivity(), R.string.toast_pref_changed_restart_required, Toast.LENGTH_LONG).show(); return true; } } catch (NumberFormatException ignore) { } String invalidEntry = getString(R.string.toast_invalid_display_limit, MIN_DISPLAY_LIMIT, MAX_DISPLAY_LIMIT); Toast.makeText(getActivity(), invalidEntry, Toast.LENGTH_LONG).show(); return false; } else if (preference.getKey().equals(getString(R.string.pref_log_line_period))) { // log line period preference; update summary String input = ((String) newValue).trim(); try { int value = Integer.parseInt(input); if (value >= MIN_LOG_LINE_PERIOD && value <= MAX_LOG_LINE_PERIOD) { PreferenceHelper.setLogLinePeriodPreference(getActivity(), value); logLinePeriodPreference.setSummary(getString(R.string.pref_log_line_period_summary, value, getString(R.string.pref_log_line_period_default))); return true; } } catch (NumberFormatException ignore) { } Toast.makeText(getActivity(), R.string.pref_log_line_period_error, Toast.LENGTH_LONG).show(); return false; } else if (preference.getKey().equals(getString(R.string.pref_theme))) { setCurrentValue(preference.getKey()); return true; } else if (preference.getKey().equals("ui.accent")) { setCurrentValue(preference.getKey()); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent("org.openintents.action.REFRESH_THEME")); return true; } else if (preference.getKey().equals(getString(R.string.pref_buffer))) { // buffers pref // check to make sure nothing was left unchecked if (TextUtils.isEmpty(newValue.toString())) { Toast.makeText(getActivity(), R.string.pref_buffer_none_checked_error, Toast.LENGTH_SHORT).show(); return false; } // notify the LogcatActivity that the buffer has changed if (!newValue.toString().equals(bufferPreference.getValue())) { bufferChanged = true; } setBufferPreferenceSummary(newValue.toString()); return true; } else if (preference.getKey().equals(getString(R.string.pref_default_log_level))) { // default log level preference // update the summary to reflect changes ListPreference listPreference = (ListPreference) preference;
int index = ArrayUtil.indexOf(listPreference.getEntryValues(), newValue);
3
2023-11-19 15:31:51+00:00
12k
GT-ARC/opaca-core
opaca-platform/src/main/java/de/gtarc/opaca/platform/PlatformImpl.java
[ { "identifier": "RuntimePlatformApi", "path": "opaca-model/src/main/java/de/gtarc/opaca/api/RuntimePlatformApi.java", "snippet": "public interface RuntimePlatformApi extends CommonApi {\n\n /**\n * Get full information on the Runtime Platform, including all running Agent Containers and\n * Ag...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import de.gtarc.opaca.api.RuntimePlatformApi; import de.gtarc.opaca.platform.auth.JwtUtil; import de.gtarc.opaca.platform.auth.TokenUserDetailsService; import de.gtarc.opaca.platform.containerclient.ContainerClient; import de.gtarc.opaca.platform.containerclient.DockerClient; import de.gtarc.opaca.platform.containerclient.KubernetesClient; import de.gtarc.opaca.platform.session.SessionData; import de.gtarc.opaca.model.*; import de.gtarc.opaca.util.ApiProxy; import lombok.extern.java.Log; import de.gtarc.opaca.util.EventHistory; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
8,807
package de.gtarc.opaca.platform; /** * This class provides the actual implementation of the API routes. Might also be split up * further, e.g. for agent-forwarding, container-management, and linking to other platforms. */ @Log @Component
package de.gtarc.opaca.platform; /** * This class provides the actual implementation of the API routes. Might also be split up * further, e.g. for agent-forwarding, container-management, and linking to other platforms. */ @Log @Component
public class PlatformImpl implements RuntimePlatformApi {
0
2023-11-23 11:06:10+00:00
12k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/controller/ArtworkController.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import javafx.animation.FadeTransition; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.web.WebView; import javafx.stage.DirectoryChooser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.api.artwork.Identifier; import xyz.zcraft.zpixiv.api.artwork.PixivArtwork; import xyz.zcraft.zpixiv.api.artwork.Quality; import xyz.zcraft.zpixiv.ui.Main; import xyz.zcraft.zpixiv.util.*; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Objects; import java.util.ResourceBundle; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingQueue;
9,203
package xyz.zcraft.zpixiv.ui.controller; public class ArtworkController implements Initializable, Refreshable, Closeable { private static final Logger LOG = LogManager.getLogger(ArtworkController.class); private final LinkedBlockingQueue<LoadTask> tasks = new LinkedBlockingQueue<>(); @FXML public ImageView imgView; @FXML public Button nextPageBtn; @FXML public Button prevPageBtn; @FXML public Label titleLbl; @FXML public ImageView authorImg; @FXML public Label authorNameLbl; @FXML public Label pubDateLbl; @FXML public Region followBtn; @FXML public Label likeLbl; @FXML public Label bookmarkLbl; @FXML public Label viewLbl; @FXML public Region likeBtn; @FXML public Region bookmarkBtn; @FXML public Label xResLbl; @FXML public HBox titleBox; @FXML public WebView descView; @FXML public ScrollPane root; @FXML public AnchorPane imgAnchor; @FXML public ProgressBar loadProgressBar; @FXML public Label processLabel; @FXML public VBox loadPane; @FXML public Label likeTextLbl; @FXML public Label pageLbl; public AnchorPane pageWrapperPane; public FlowPane tagsPane; public Button downloadBtn;
package xyz.zcraft.zpixiv.ui.controller; public class ArtworkController implements Initializable, Refreshable, Closeable { private static final Logger LOG = LogManager.getLogger(ArtworkController.class); private final LinkedBlockingQueue<LoadTask> tasks = new LinkedBlockingQueue<>(); @FXML public ImageView imgView; @FXML public Button nextPageBtn; @FXML public Button prevPageBtn; @FXML public Label titleLbl; @FXML public ImageView authorImg; @FXML public Label authorNameLbl; @FXML public Label pubDateLbl; @FXML public Region followBtn; @FXML public Label likeLbl; @FXML public Label bookmarkLbl; @FXML public Label viewLbl; @FXML public Region likeBtn; @FXML public Region bookmarkBtn; @FXML public Label xResLbl; @FXML public HBox titleBox; @FXML public WebView descView; @FXML public ScrollPane root; @FXML public AnchorPane imgAnchor; @FXML public ProgressBar loadProgressBar; @FXML public Label processLabel; @FXML public VBox loadPane; @FXML public Label likeTextLbl; @FXML public Label pageLbl; public AnchorPane pageWrapperPane; public FlowPane tagsPane; public Button downloadBtn;
private PixivClient client;
0
2023-11-23 15:08:16+00:00
12k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/QuickShopHandler/QSHikariAPIHandler.java
[ { "identifier": "FindItemCmdHikariImpl", "path": "src/main/java/io/myzticbean/finditemaddon/Commands/QSSubCommands/FindItemCmdHikariImpl.java", "snippet": "public class FindItemCmdHikariImpl implements CommandHandler<Player> {\n\n private final String hideSubCommand;\n private final String revealS...
import com.ghostchu.quickshop.QuickShop; import com.ghostchu.quickshop.api.QuickShopAPI; import com.ghostchu.quickshop.api.command.CommandContainer; import com.ghostchu.quickshop.api.obj.QUser; import com.ghostchu.quickshop.api.shop.Shop; import com.ghostchu.quickshop.api.shop.permission.BuiltInShopPermission; import io.myzticbean.finditemaddon.Commands.QSSubCommands.FindItemCmdHikariImpl; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Models.ShopSearchActivityModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import net.kyori.adventure.text.Component; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.nio.charset.StandardCharsets; import java.util.*;
7,648
package io.myzticbean.finditemaddon.QuickShopHandler; /** * Implementation of QSApi for Reremake * * @author ronsane */ public class QSHikariAPIHandler implements QSApi<QuickShop, Shop> { private QuickShopAPI api; public QSHikariAPIHandler() { api = QuickShopAPI.getInstance(); } public List<FoundShopItemModel> findItemBasedOnTypeFromAllShops(ItemStack item, boolean toBuy, Player searchingPlayer) { List<FoundShopItemModel> shopsFoundList = new ArrayList<>(); List<Shop> allShops; if (FindItemAddOn.getConfigProvider().SEARCH_LOADED_SHOPS_ONLY) { allShops = new ArrayList<>(api.getShopManager().getLoadedShops()); } else { allShops = api.getShopManager().getAllShops(); } LoggerUtils.logDebugInfo("Total shops on server: " + allShops.size()); allShops.forEach((shop_i) -> { // check for quickshop hikari internal per-shop based search permission if (shop_i.playerAuthorize(searchingPlayer.getUniqueId(), BuiltInShopPermission.SEARCH)) { // check for blacklisted worlds if (!FindItemAddOn.getConfigProvider().getBlacklistedWorlds().contains(shop_i.getLocation().getWorld()) && shop_i.getItem().getType().equals(item.getType()) && (toBuy ? shop_i.getRemainingStock() != 0 : shop_i.getRemainingSpace() != 0) && (toBuy ? shop_i.isSelling() : shop_i.isBuying())) { // check for shop if hidden
package io.myzticbean.finditemaddon.QuickShopHandler; /** * Implementation of QSApi for Reremake * * @author ronsane */ public class QSHikariAPIHandler implements QSApi<QuickShop, Shop> { private QuickShopAPI api; public QSHikariAPIHandler() { api = QuickShopAPI.getInstance(); } public List<FoundShopItemModel> findItemBasedOnTypeFromAllShops(ItemStack item, boolean toBuy, Player searchingPlayer) { List<FoundShopItemModel> shopsFoundList = new ArrayList<>(); List<Shop> allShops; if (FindItemAddOn.getConfigProvider().SEARCH_LOADED_SHOPS_ONLY) { allShops = new ArrayList<>(api.getShopManager().getLoadedShops()); } else { allShops = api.getShopManager().getAllShops(); } LoggerUtils.logDebugInfo("Total shops on server: " + allShops.size()); allShops.forEach((shop_i) -> { // check for quickshop hikari internal per-shop based search permission if (shop_i.playerAuthorize(searchingPlayer.getUniqueId(), BuiltInShopPermission.SEARCH)) { // check for blacklisted worlds if (!FindItemAddOn.getConfigProvider().getBlacklistedWorlds().contains(shop_i.getLocation().getWorld()) && shop_i.getItem().getType().equals(item.getType()) && (toBuy ? shop_i.getRemainingStock() != 0 : shop_i.getRemainingSpace() != 0) && (toBuy ? shop_i.isSelling() : shop_i.isBuying())) { // check for shop if hidden
if (!HiddenShopStorageUtil.isShopHidden(shop_i)) {
5
2023-11-22 11:36:01+00:00
12k
DIDA-lJ/qiyao-12306
services/user-service/src/main/java/org/opengoofy/index12306/biz/userservice/service/impl/UserLoginServiceImpl.java
[ { "identifier": "UserChainMarkEnum", "path": "services/user-service/src/main/java/org/opengoofy/index12306/biz/userservice/common/enums/UserChainMarkEnum.java", "snippet": "public enum UserChainMarkEnum {\n\n /**\n * 用户注册过滤器\n */\n USER_REGISTER_FILTER\n}" }, { "identifier": "UserD...
import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.opengoofy.index12306.biz.userservice.common.enums.UserChainMarkEnum; import org.opengoofy.index12306.biz.userservice.dao.entity.UserDO; import org.opengoofy.index12306.biz.userservice.dao.entity.UserDeletionDO; import org.opengoofy.index12306.biz.userservice.dao.entity.UserMailDO; import org.opengoofy.index12306.biz.userservice.dao.entity.UserPhoneDO; import org.opengoofy.index12306.biz.userservice.dao.entity.UserReuseDO; import org.opengoofy.index12306.biz.userservice.dao.mapper.UserDeletionMapper; import org.opengoofy.index12306.biz.userservice.dao.mapper.UserMailMapper; import org.opengoofy.index12306.biz.userservice.dao.mapper.UserMapper; import org.opengoofy.index12306.biz.userservice.dao.mapper.UserPhoneMapper; import org.opengoofy.index12306.biz.userservice.dao.mapper.UserReuseMapper; import org.opengoofy.index12306.biz.userservice.dto.req.UserDeletionReqDTO; import org.opengoofy.index12306.biz.userservice.dto.req.UserLoginReqDTO; import org.opengoofy.index12306.biz.userservice.dto.req.UserRegisterReqDTO; import org.opengoofy.index12306.biz.userservice.dto.resp.UserLoginRespDTO; import org.opengoofy.index12306.biz.userservice.dto.resp.UserQueryRespDTO; import org.opengoofy.index12306.biz.userservice.dto.resp.UserRegisterRespDTO; import org.opengoofy.index12306.biz.userservice.service.UserLoginService; import org.opengoofy.index12306.biz.userservice.service.UserService; import org.opengoofy.index12306.framework.starter.cache.DistributedCache; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ClientException; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.designpattern.chain.AbstractChainContext; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.opengoofy.index12306.frameworks.starter.user.core.UserInfoDTO; import org.opengoofy.index12306.frameworks.starter.user.toolkit.JWTUtil; import org.redisson.api.RBloomFilter; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; 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.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import static org.opengoofy.index12306.biz.userservice.common.constant.RedisKeyConstant.LOCK_USER_REGISTER; import static org.opengoofy.index12306.biz.userservice.common.constant.RedisKeyConstant.USER_DELETION; import static org.opengoofy.index12306.biz.userservice.common.constant.RedisKeyConstant.USER_REGISTER_REUSE_SHARDING; import static org.opengoofy.index12306.biz.userservice.common.enums.UserRegisterErrorCodeEnum.HAS_USERNAME_NOTNULL; import static org.opengoofy.index12306.biz.userservice.common.enums.UserRegisterErrorCodeEnum.MAIL_REGISTERED; import static org.opengoofy.index12306.biz.userservice.common.enums.UserRegisterErrorCodeEnum.PHONE_REGISTERED; import static org.opengoofy.index12306.biz.userservice.common.enums.UserRegisterErrorCodeEnum.USER_REGISTER_FAIL; import static org.opengoofy.index12306.biz.userservice.toolkit.UserReuseUtil.hashShardingIdx;
9,647
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.userservice.service.impl; /** * 用户登录接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class UserLoginServiceImpl implements UserLoginService { private final UserService userService; private final UserMapper userMapper; private final UserReuseMapper userReuseMapper; private final UserDeletionMapper userDeletionMapper; private final UserPhoneMapper userPhoneMapper; private final UserMailMapper userMailMapper; private final RedissonClient redissonClient; private final DistributedCache distributedCache; private final AbstractChainContext<UserRegisterReqDTO> abstractChainContext; private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter; @Override public UserLoginRespDTO login(UserLoginReqDTO requestParam) { String usernameOrMailOrPhone = requestParam.getUsernameOrMailOrPhone(); boolean mailFlag = false; // 时间复杂度最佳 O(1)。indexOf or contains 时间复杂度为 O(n) for (char c : usernameOrMailOrPhone.toCharArray()) { if (c == '@') { mailFlag = true; break; } } String username; if (mailFlag) { LambdaQueryWrapper<UserMailDO> queryWrapper = Wrappers.lambdaQuery(UserMailDO.class) .eq(UserMailDO::getMail, usernameOrMailOrPhone); username = Optional.ofNullable(userMailMapper.selectOne(queryWrapper)) .map(UserMailDO::getUsername)
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.userservice.service.impl; /** * 用户登录接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class UserLoginServiceImpl implements UserLoginService { private final UserService userService; private final UserMapper userMapper; private final UserReuseMapper userReuseMapper; private final UserDeletionMapper userDeletionMapper; private final UserPhoneMapper userPhoneMapper; private final UserMailMapper userMailMapper; private final RedissonClient redissonClient; private final DistributedCache distributedCache; private final AbstractChainContext<UserRegisterReqDTO> abstractChainContext; private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter; @Override public UserLoginRespDTO login(UserLoginReqDTO requestParam) { String usernameOrMailOrPhone = requestParam.getUsernameOrMailOrPhone(); boolean mailFlag = false; // 时间复杂度最佳 O(1)。indexOf or contains 时间复杂度为 O(n) for (char c : usernameOrMailOrPhone.toCharArray()) { if (c == '@') { mailFlag = true; break; } } String username; if (mailFlag) { LambdaQueryWrapper<UserMailDO> queryWrapper = Wrappers.lambdaQuery(UserMailDO.class) .eq(UserMailDO::getMail, usernameOrMailOrPhone); username = Optional.ofNullable(userMailMapper.selectOne(queryWrapper)) .map(UserMailDO::getUsername)
.orElseThrow(() -> new ClientException("用户名/手机号/邮箱不存在"));
21
2023-11-23 07:59:11+00:00
12k
estkme-group/infineon-lpa-mirror
core/src/main/java/com/infineon/esim/lpa/core/es10/base/TransportCommand.java
[ { "identifier": "Ber", "path": "messages/src/main/java/com/infineon/esim/messages/Ber.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Ber {\n private static final String TAG = Ber.class.getName();\n\n // Tags see: http://luca.ntop.org/Teaching/Appunti/asn1.html\n public static fi...
import com.beanit.jasn1.ber.types.BerType; import com.infineon.esim.messages.Ber; import com.infineon.esim.util.Bytes; import com.infineon.esim.util.Strings; import java.util.ArrayList; import java.util.List;
7,705
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es10.base; public class TransportCommand { private static final String TAG = TransportCommand.class.getName(); private static final String CLA = "81"; private static final String INS = "E2"; private static final String P1_11 = "11"; private static final String P1_91 = "91"; private static final int MAX_DATA_LENGTH_BYTE = 240; /* See GSMA SGP.21 chapter 5.7.2 Transport Command for more details */ public static List<String> getTransportCommands(BerType berData) {
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es10.base; public class TransportCommand { private static final String TAG = TransportCommand.class.getName(); private static final String CLA = "81"; private static final String INS = "E2"; private static final String P1_11 = "11"; private static final String P1_91 = "91"; private static final int MAX_DATA_LENGTH_BYTE = 240; /* See GSMA SGP.21 chapter 5.7.2 Transport Command for more details */ public static List<String> getTransportCommands(BerType berData) {
return getTransportCommands(Ber.getEncodedAsHexString(berData));
0
2023-11-22 07:46:30+00:00
12k
MattiDragon/JsonPatcherLang
src/main/java/io/github/mattidragon/jsonpatcher/lang/parse/Parser.java
[ { "identifier": "PositionedException", "path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/PositionedException.java", "snippet": "public abstract class PositionedException extends RuntimeException {\n protected PositionedException(String message) {\n super(message);\n }\n\n pro...
import io.github.mattidragon.jsonpatcher.lang.PositionedException; import io.github.mattidragon.jsonpatcher.lang.parse.parselet.PostfixParser; import io.github.mattidragon.jsonpatcher.lang.parse.parselet.Precedence; import io.github.mattidragon.jsonpatcher.lang.parse.parselet.PrefixParser; import io.github.mattidragon.jsonpatcher.lang.parse.parselet.StatementParser; import io.github.mattidragon.jsonpatcher.lang.runtime.Program; import io.github.mattidragon.jsonpatcher.lang.runtime.expression.ErrorExpression; import io.github.mattidragon.jsonpatcher.lang.runtime.expression.Expression; import io.github.mattidragon.jsonpatcher.lang.runtime.statement.Statement; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.List;
8,123
package io.github.mattidragon.jsonpatcher.lang.parse; public class Parser { private final List<PositionedToken<?>> tokens; private List<ParseException> errors = new ArrayList<>(); private final PatchMetadata metadata; private int current = 0; private Parser(List<PositionedToken<?>> tokens) { this.tokens = tokens; this.metadata = new PatchMetadata(); } public static Result parse(List<PositionedToken<?>> tokens) { return new Parser(tokens).program(); } @VisibleForTesting public static Expression parseExpression(List<PositionedToken<?>> tokens) throws ParseException { var parser = new Parser(tokens); var errors = parser.errors; Expression expression = null; try { expression = parser.expression(); } catch (EndParsingException ignored) { } catch (ParseException e) { errors.add(e); } if (!errors.isEmpty()) { var error = new RuntimeException("Expected successful parse"); errors.forEach(error::addSuppressed); throw error; } return expression; } public Result program() { while (hasNext(Token.SimpleToken.AT_SIGN)) { next(); var id = expectWord().value(); metadata.add(id, this); expect(Token.SimpleToken.SEMICOLON); } var statements = new ArrayList<Statement>(); try { while (hasNext()) statements.add(statement()); } catch (ParseException e) { errors.add(e); } catch (EndParsingException ignored) {} if (!errors.isEmpty()) { return new Result.Fail(errors); } return new Result.Success(new Program(statements), metadata); } private Statement statement() { return StatementParser.parse(this); } public Expression expression() {
package io.github.mattidragon.jsonpatcher.lang.parse; public class Parser { private final List<PositionedToken<?>> tokens; private List<ParseException> errors = new ArrayList<>(); private final PatchMetadata metadata; private int current = 0; private Parser(List<PositionedToken<?>> tokens) { this.tokens = tokens; this.metadata = new PatchMetadata(); } public static Result parse(List<PositionedToken<?>> tokens) { return new Parser(tokens).program(); } @VisibleForTesting public static Expression parseExpression(List<PositionedToken<?>> tokens) throws ParseException { var parser = new Parser(tokens); var errors = parser.errors; Expression expression = null; try { expression = parser.expression(); } catch (EndParsingException ignored) { } catch (ParseException e) { errors.add(e); } if (!errors.isEmpty()) { var error = new RuntimeException("Expected successful parse"); errors.forEach(error::addSuppressed); throw error; } return expression; } public Result program() { while (hasNext(Token.SimpleToken.AT_SIGN)) { next(); var id = expectWord().value(); metadata.add(id, this); expect(Token.SimpleToken.SEMICOLON); } var statements = new ArrayList<Statement>(); try { while (hasNext()) statements.add(statement()); } catch (ParseException e) { errors.add(e); } catch (EndParsingException ignored) {} if (!errors.isEmpty()) { return new Result.Fail(errors); } return new Result.Success(new Program(statements), metadata); } private Statement statement() { return StatementParser.parse(this); } public Expression expression() {
return expression(Precedence.ROOT);
2
2023-11-23 14:17:00+00:00
12k
wssun/AST4PLU
data-process/process/src/main/java/process/SplitAST_for_bcb.java
[ { "identifier": "GenerateAST", "path": "data-process/process/src/main/java/JDT/GenerateAST.java", "snippet": "public class GenerateAST {\n\tprivate static String ast;\n\tprivate static String masked_ast;\n\t\n\tpublic static class astVisitor extends ASTVisitor{\n\t\tpublic void preVisit(ASTNode node) {\...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import JDT.GenerateAST; import tree.Tree; import utils.TreeToJSON; import utils.TreeTools; import tree.Test;
9,395
package process; public class SplitAST_for_bcb { private static String AST_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data_ast.jsonl"; private static String JSON_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data.jsonl"; // use Tree-sitter public static void main(String[] args) throws IOException { FileReader fr = null; BufferedReader br = null; File jsonFile = null; FileWriter fileWriter = null; BufferedWriter bw = null; try { fr = new FileReader(AST_FILE_PATH); br = new BufferedReader(fr); jsonFile = new File(JSON_FILE_PATH); if (!jsonFile.exists()) { jsonFile.createNewFile(); } fileWriter = new FileWriter(jsonFile.getAbsoluteFile()); bw = new BufferedWriter(fileWriter); String line = ""; //读取每一行的数据 int cnt=1; while ( (line = br.readLine()) != null) { JSONObject lineJson = JSONObject.parseObject(line); String idx=lineJson.getString("idx"); JSONArray asts=lineJson.getJSONArray("asts"); List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class); int sz=ast_seqs.size(); JSONArray new_asts=new JSONArray(); for(int i=0;i<sz;++i) {
package process; public class SplitAST_for_bcb { private static String AST_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data_ast.jsonl"; private static String JSON_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data.jsonl"; // use Tree-sitter public static void main(String[] args) throws IOException { FileReader fr = null; BufferedReader br = null; File jsonFile = null; FileWriter fileWriter = null; BufferedWriter bw = null; try { fr = new FileReader(AST_FILE_PATH); br = new BufferedReader(fr); jsonFile = new File(JSON_FILE_PATH); if (!jsonFile.exists()) { jsonFile.createNewFile(); } fileWriter = new FileWriter(jsonFile.getAbsoluteFile()); bw = new BufferedWriter(fileWriter); String line = ""; //读取每一行的数据 int cnt=1; while ( (line = br.readLine()) != null) { JSONObject lineJson = JSONObject.parseObject(line); String idx=lineJson.getString("idx"); JSONArray asts=lineJson.getJSONArray("asts"); List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class); int sz=ast_seqs.size(); JSONArray new_asts=new JSONArray(); for(int i=0;i<sz;++i) {
Tree ast=TreeTools.stringToTree(ast_seqs.get(i));
3
2023-11-23 06:08:43+00:00
12k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/revokeDistribution/CRL.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 de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.revokeDistribution.objects.RevokedCertificate; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.tools.certificate.generator.CertificateRevokationListGenerator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.security.cert.CRLException; import java.security.cert.X509CRL; import java.time.LocalTime; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
8,763
package de.morihofi.acmeserver.certificate.revokeDistribution; /** * Manages the creation and updating of a Certificate Revocation List (CRL). * This class handles the generation of CRLs based on revoked certificates and maintains * a cache of the current CRL. It also schedules regular updates to the CRL. */ public class CRL { private volatile byte[] currentCrlBytes = null; private volatile X509CRL currentCrl = null; private volatile LocalTime lastUpdate = null; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** * Instance for accessing the current provisioner */
package de.morihofi.acmeserver.certificate.revokeDistribution; /** * Manages the creation and updating of a Certificate Revocation List (CRL). * This class handles the generation of CRLs based on revoked certificates and maintains * a cache of the current CRL. It also schedules regular updates to the CRL. */ public class CRL { private volatile byte[] currentCrlBytes = null; private volatile X509CRL currentCrl = null; private volatile LocalTime lastUpdate = null; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** * Instance for accessing the current provisioner */
private final Provisioner provisioner;
0
2023-11-22 15:54:36+00:00
12k
sakura-ryoko/afkplus
src/main/java/io/github/sakuraryoko/afkplus/commands/AfkPlusCommand.java
[ { "identifier": "ConfigManager", "path": "src/main/java/io/github/sakuraryoko/afkplus/config/ConfigManager.java", "snippet": "public class ConfigManager {\n public static ConfigData CONFIG = new ConfigData();\n\n public static void initConfig() {\n CONFIG.afkPlusOptions.afkPlusCommandPermis...
import static io.github.sakuraryoko.afkplus.config.ConfigManager.*; import static net.minecraft.server.command.CommandManager.*; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; import eu.pb4.placeholders.api.TextParserUtils; import io.github.sakuraryoko.afkplus.config.ConfigManager; import io.github.sakuraryoko.afkplus.data.IAfkPlayer; import io.github.sakuraryoko.afkplus.util.AfkPlayerInfo; import io.github.sakuraryoko.afkplus.util.AfkPlusInfo; import io.github.sakuraryoko.afkplus.util.AfkPlusLogger; import io.github.sakuraryoko.afkplus.util.FormattingExample; import me.lucko.fabric.api.permissions.v0.Permissions; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text;
9,154
package io.github.sakuraryoko.afkplus.commands; public class AfkPlusCommand { public static void register() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register( literal("afkplus") .executes(ctx -> afkAbout(ctx.getSource(), ctx)) .then(literal("ex") .requires(Permissions.require("afkplus.afkplus.ex", 4)) .executes(ctx -> afkExample(ctx.getSource(), ctx)) ) .then(literal("reload") .requires(Permissions.require("afkplus.afkplus.reload", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .executes(ctx -> afkReload(ctx.getSource(), ctx)) ) .then(literal("set") .requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"),"", ctx)) .then(argument("reason", StringArgumentType.greedyString()) .requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"), StringArgumentType.getString(ctx, "reason"), ctx)) ) ) ) .then(literal("clear") .requires(Permissions.require("afkplus.afkplus.clear", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> clearAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("info") .requires(Permissions.require("afkplus.afkplus.info", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> infoAfkPlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("damage") .then(literal("disable") .requires(Permissions.require("afkplus.afkplus.damage.disable", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> disableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("enable") .requires(Permissions.require("afkplus.afkplus.damage.enable", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> enableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) ) .then(literal("update") .requires(Permissions.require("afkplus.afkplus.update", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> updatePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx) ) ) ) )); } private static int afkAbout(ServerCommandSource src, CommandContext<ServerCommandSource> context) { Text ModInfo = AfkPlusInfo.getModInfoText(); String user = src.getName(); context.getSource().sendFeedback(() -> ModInfo, false); AfkPlusLogger.debug(user + " has executed /afkplus ."); return 1; } private static int afkExample(ServerCommandSource src, CommandContext<ServerCommandSource> context) { String user = src.getName(); context.getSource().sendFeedback(() -> FormattingExample.runBuiltInTest(), false); context.getSource().sendFeedback(() -> FormattingExample.runAliasTest(), false); context.getSource().sendFeedback(() -> FormattingExample.runColorsTest(), false); AfkPlusLogger.debug(user + " has executed /afkplus example ."); return 1; } private static int afkReload(ServerCommandSource src, CommandContext<ServerCommandSource> context) { String user = src.getName(); ConfigManager.reloadConfig(); context.getSource().sendFeedback(() -> Text.of("Reloaded config!"), false); AfkPlusLogger.info(user + " has reloaded the configuration."); return 1; } private static int setAfk(ServerCommandSource src, ServerPlayerEntity player, String reason, CommandContext<ServerCommandSource> context) {
package io.github.sakuraryoko.afkplus.commands; public class AfkPlusCommand { public static void register() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register( literal("afkplus") .executes(ctx -> afkAbout(ctx.getSource(), ctx)) .then(literal("ex") .requires(Permissions.require("afkplus.afkplus.ex", 4)) .executes(ctx -> afkExample(ctx.getSource(), ctx)) ) .then(literal("reload") .requires(Permissions.require("afkplus.afkplus.reload", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .executes(ctx -> afkReload(ctx.getSource(), ctx)) ) .then(literal("set") .requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"),"", ctx)) .then(argument("reason", StringArgumentType.greedyString()) .requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"), StringArgumentType.getString(ctx, "reason"), ctx)) ) ) ) .then(literal("clear") .requires(Permissions.require("afkplus.afkplus.clear", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> clearAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("info") .requires(Permissions.require("afkplus.afkplus.info", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> infoAfkPlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("damage") .then(literal("disable") .requires(Permissions.require("afkplus.afkplus.damage.disable", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> disableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) .then(literal("enable") .requires(Permissions.require("afkplus.afkplus.damage.enable", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> enableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)) ) ) ) .then(literal("update") .requires(Permissions.require("afkplus.afkplus.update", CONFIG.afkPlusOptions.afkPlusCommandPermissions)) .then(argument("player", EntityArgumentType.player()) .executes(ctx -> updatePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx) ) ) ) )); } private static int afkAbout(ServerCommandSource src, CommandContext<ServerCommandSource> context) { Text ModInfo = AfkPlusInfo.getModInfoText(); String user = src.getName(); context.getSource().sendFeedback(() -> ModInfo, false); AfkPlusLogger.debug(user + " has executed /afkplus ."); return 1; } private static int afkExample(ServerCommandSource src, CommandContext<ServerCommandSource> context) { String user = src.getName(); context.getSource().sendFeedback(() -> FormattingExample.runBuiltInTest(), false); context.getSource().sendFeedback(() -> FormattingExample.runAliasTest(), false); context.getSource().sendFeedback(() -> FormattingExample.runColorsTest(), false); AfkPlusLogger.debug(user + " has executed /afkplus example ."); return 1; } private static int afkReload(ServerCommandSource src, CommandContext<ServerCommandSource> context) { String user = src.getName(); ConfigManager.reloadConfig(); context.getSource().sendFeedback(() -> Text.of("Reloaded config!"), false); AfkPlusLogger.info(user + " has reloaded the configuration."); return 1; } private static int setAfk(ServerCommandSource src, ServerPlayerEntity player, String reason, CommandContext<ServerCommandSource> context) {
IAfkPlayer afkPlayer = (IAfkPlayer) player;
2
2023-11-22 00:21:36+00:00
12k
clover/clover-tr34-host
src/test/java/com/clover/tr34/Tr34AscX9Test.java
[ { "identifier": "AscSampleTr34KeyStoreData", "path": "src/test/java/com/clover/tr34/samples/AscSampleTr34KeyStoreData.java", "snippet": "public class AscSampleTr34KeyStoreData extends Tr34KeyStoreData {\n\n public static final String SAMPLE_ROOT_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n ...
import com.clover.tr34.samples.AscSampleTr34KeyStoreData; import com.clover.tr34.samples.AscSampleTr34Messages; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DLSet; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.util.Properties; import org.bouncycastle.util.Selector; import org.bouncycastle.util.encoders.Hex; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.security.MessageDigest; import java.security.PublicKey; import java.security.Signature; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertArrayEquals;
7,359
package com.clover.tr34; @Ignore("Enable after populating redacted ASC X9 TR-34 sample messages") public class Tr34AscX9Test { @Before public void setup() { // ASC X9 TR 34 sample certs sometimes include repeated extensions Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true); } @Test public void ascSampleRandomTokenParse() { byte[] rand = Tr34RandomToken.create(AscSampleTr34Messages.RKRD_PEM).getRandomNumber().getOctets(); assertArrayEquals(Hex.decode("167EB0E72781E4940112233445566778"), rand); } @Test public void ascSampleCheckKdhBindToken() throws Exception { // Despite the name this CMS is not actually signed Tr34KdhCredentialToken.create(Tr34CryptoUtils.pemToDer(AscSampleTr34Messages.SAMPLE_CT_KDH_PEM)); } @Test public void ascSampleCheckKdhUnbindToken() throws Exception { Tr34RandomToken randomToken = Tr34RandomToken.createFromNonce(Hex.decode("7DEA1C00894E246A")); Tr34KdhUnbindToken unbindToken = Tr34KdhUnbindToken.create(AscSampleTr34Messages.SAMPLE_UBT_KDH_PEM);
package com.clover.tr34; @Ignore("Enable after populating redacted ASC X9 TR-34 sample messages") public class Tr34AscX9Test { @Before public void setup() { // ASC X9 TR 34 sample certs sometimes include repeated extensions Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true); } @Test public void ascSampleRandomTokenParse() { byte[] rand = Tr34RandomToken.create(AscSampleTr34Messages.RKRD_PEM).getRandomNumber().getOctets(); assertArrayEquals(Hex.decode("167EB0E72781E4940112233445566778"), rand); } @Test public void ascSampleCheckKdhBindToken() throws Exception { // Despite the name this CMS is not actually signed Tr34KdhCredentialToken.create(Tr34CryptoUtils.pemToDer(AscSampleTr34Messages.SAMPLE_CT_KDH_PEM)); } @Test public void ascSampleCheckKdhUnbindToken() throws Exception { Tr34RandomToken randomToken = Tr34RandomToken.createFromNonce(Hex.decode("7DEA1C00894E246A")); Tr34KdhUnbindToken unbindToken = Tr34KdhUnbindToken.create(AscSampleTr34Messages.SAMPLE_UBT_KDH_PEM);
X509Certificate krdCert = Tr34CryptoUtils.parseCert(AscSampleTr34KeyStoreData.SAMPLE_KRD_1_CERT_PEM);
0
2023-11-22 06:30:40+00:00
12k
trgpnt/java-class-jacksonizer
src/main/java/com/aggregated/entry_point/InputEntry.java
[ { "identifier": "Driver", "path": "src/main/java/com/aggregated/Driver.java", "snippet": "public class Driver {\n private static final ClassDecorator decorator = ClassDecorator.emptyInstance();\n\n public static void JacksonModePackageExecution(String packageName) {\n\n decorator.reset();\n...
import com.aggregated.Driver; import com.aggregated.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Objects;
7,664
package com.aggregated.entry_point; public class InputEntry { private static final Logger LOG = LoggerFactory.getLogger(InputEntry.class); private final static String INPUT_FILE_NAME = "input.txt"; private final static String SKIP_INDICATOR = "#"; private static final String BASE_PATH = "src//main//java//"; private static boolean isSinglePackage = false; public static void main(String[] args) { scanPackageOrSingleJava(); } public static String resolveJavaFile(String inp) { int firstUpperCaseIdx = isPackage(inp); if (firstUpperCaseIdx == -1) { return inp; } String fullJavaName = inp.substring(0, firstUpperCaseIdx) + inp.substring(firstUpperCaseIdx) + ".java"; return fullJavaName; } private static int isPackage(String inp) { for (int i = 0, n = inp.length(); i < n; i++) { if (Character.isUpperCase(inp.charAt(i))) { return i; } } return -1; } private static void scanPackageOrSingleJava() { /** * Build defined values */ isSinglePackage = false; ClassLoader classLoader = InputEntry.class.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(INPUT_FILE_NAME); if (Objects.isNull(inputStream)) { return; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { if (line.isEmpty() || line.contains(SKIP_INDICATOR)) { continue; } if (evalSinglePackage(line)) { isSinglePackage = true; line = resolveReplaces(line, ".*", "", "**", "", "*", "", " ", ""); scanClassesInPackage(line); } else {
package com.aggregated.entry_point; public class InputEntry { private static final Logger LOG = LoggerFactory.getLogger(InputEntry.class); private final static String INPUT_FILE_NAME = "input.txt"; private final static String SKIP_INDICATOR = "#"; private static final String BASE_PATH = "src//main//java//"; private static boolean isSinglePackage = false; public static void main(String[] args) { scanPackageOrSingleJava(); } public static String resolveJavaFile(String inp) { int firstUpperCaseIdx = isPackage(inp); if (firstUpperCaseIdx == -1) { return inp; } String fullJavaName = inp.substring(0, firstUpperCaseIdx) + inp.substring(firstUpperCaseIdx) + ".java"; return fullJavaName; } private static int isPackage(String inp) { for (int i = 0, n = inp.length(); i < n; i++) { if (Character.isUpperCase(inp.charAt(i))) { return i; } } return -1; } private static void scanPackageOrSingleJava() { /** * Build defined values */ isSinglePackage = false; ClassLoader classLoader = InputEntry.class.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(INPUT_FILE_NAME); if (Objects.isNull(inputStream)) { return; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { if (line.isEmpty() || line.contains(SKIP_INDICATOR)) { continue; } if (evalSinglePackage(line)) { isSinglePackage = true; line = resolveReplaces(line, ".*", "", "**", "", "*", "", " ", ""); scanClassesInPackage(line); } else {
line = resolveJavaFile(StringUtils.stripDoubleEndedNonAlphaNumeric(line));
1
2023-11-23 10:59:01+00:00
12k
clasSeven7/sebo-cultural
src/Main.java
[ { "identifier": "IClienteRepository", "path": "src/Domain/Repositories/IClienteRepository.java", "snippet": "public interface IClienteRepository {\n ArrayList<Cliente> buscar();\n void criar(Cliente cliente);\n void atualizar(String clienteId, Cliente cliente);\n void deletar(String clienteI...
import Domain.Repositories.IClienteRepository; import Domain.Repositories.IEstoqueRepository; import Domain.Repositories.ILivroRepository; import Domain.Repositories.IRevistaRepository; import Domain.Services.ClienteService; import Domain.Services.Contracts.IClienteService; import Domain.Services.Contracts.IEstoqueService; import Domain.Services.Contracts.ILivroService; import Domain.Services.Contracts.IRevistaService; import Domain.Services.EstoqueService; import Domain.Services.LivroService; import Domain.Services.RevistaService; import Infrastructure.ClienteRepository; import Infrastructure.EstoqueRepository; import Infrastructure.LivroRepository; import Infrastructure.RevistaRepository; import Presentation.Cli.CliFacade;
7,481
public class Main { public static void main(String[] args) { ILivroRepository livroRepository = new LivroRepository();
public class Main { public static void main(String[] args) { ILivroRepository livroRepository = new LivroRepository();
ILivroService livroService = new LivroService(livroRepository);
10
2023-11-19 02:11:46+00:00
12k