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
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/ApplicationInit.java
[ { "identifier": "MobileAppRepository", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/MobileAppRepository.java", "snippet": "@AppComponent\npublic abstract class MobileAppRepository {\n\tprotected abstract List<MobileApp> getMobileApps();\n\n\tpublic MobileApp forAndroidPackage(String pk...
import nl.rrd.senseeact.client.MobileAppRepository; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.DatabaseConnection; import nl.rrd.senseeact.dao.DatabaseFactory; import nl.rrd.senseeact.dao.DatabaseTableDef; import nl.rrd.senseeact.dao.mysql.MySQLDatabaseFactory; import nl.rrd.senseeact.service.access.ProjectUserAccessControlRepository; import nl.rrd.senseeact.service.export.DataExporterFactory; import nl.rrd.senseeact.service.mail.EmailTemplateRepository; import nl.rrd.senseeact.service.sso.SSOTokenRepository; import nl.rrd.utils.AppComponents; import nl.rrd.utils.exception.ParseException; import nl.rrd.utils.schedule.DefaultTaskScheduler; import nl.rrd.utils.schedule.TaskScheduler; import org.slf4j.Logger; import org.springframework.context.event.ContextClosedEvent; import java.net.URL; import java.util.List;
8,287
package nl.rrd.senseeact.service; public abstract class ApplicationInit { private final Object LOCK = new Object(); private boolean dbInitStarted = false; /** * Constructs a new application. It reads service.properties and * initialises the {@link Configuration Configuration} and the {@link * AppComponents AppComponents} with the {@link DatabaseFactory * DatabaseFactory}. * * @throws Exception if the application can't be initialised */ public ApplicationInit() throws Exception { AppComponents components = AppComponents.getInstance(); ClassLoader classLoader = ApplicationInit.class.getClassLoader(); URL propsUrl = classLoader.getResource("service.properties"); if (propsUrl == null) { throw new Exception("Can't find resource service.properties. " + "Did you run gradlew updateConfig?"); } Configuration config = createConfiguration(); config.loadProperties(propsUrl); propsUrl = classLoader.getResource("deployment.properties"); config.loadProperties(propsUrl); if (components.findComponent(Configuration.class) == null) components.addComponent(config); if (components.findComponent(DatabaseFactory.class) == null) components.addComponent(createDatabaseFactory()); if (components.findComponent(OAuthTableRepository.class) == null) components.addComponent(createOAuthTableRepository()); if (components.findComponent(SSOTokenRepository.class) == null) components.addComponent(createSSOTokenRepository()); if (components.findComponent( EmailTemplateRepository.class) == null) { components.addComponent(createResetPasswordTemplateRepository()); }
package nl.rrd.senseeact.service; public abstract class ApplicationInit { private final Object LOCK = new Object(); private boolean dbInitStarted = false; /** * Constructs a new application. It reads service.properties and * initialises the {@link Configuration Configuration} and the {@link * AppComponents AppComponents} with the {@link DatabaseFactory * DatabaseFactory}. * * @throws Exception if the application can't be initialised */ public ApplicationInit() throws Exception { AppComponents components = AppComponents.getInstance(); ClassLoader classLoader = ApplicationInit.class.getClassLoader(); URL propsUrl = classLoader.getResource("service.properties"); if (propsUrl == null) { throw new Exception("Can't find resource service.properties. " + "Did you run gradlew updateConfig?"); } Configuration config = createConfiguration(); config.loadProperties(propsUrl); propsUrl = classLoader.getResource("deployment.properties"); config.loadProperties(propsUrl); if (components.findComponent(Configuration.class) == null) components.addComponent(config); if (components.findComponent(DatabaseFactory.class) == null) components.addComponent(createDatabaseFactory()); if (components.findComponent(OAuthTableRepository.class) == null) components.addComponent(createOAuthTableRepository()); if (components.findComponent(SSOTokenRepository.class) == null) components.addComponent(createSSOTokenRepository()); if (components.findComponent( EmailTemplateRepository.class) == null) { components.addComponent(createResetPasswordTemplateRepository()); }
if (components.findComponent(ProjectRepository.class) == null)
2
2023-10-24 09:36:50+00:00
12k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/pilot/Pilot.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train...
import frc.robot.Robot; import frc.robot.RobotCommands; import frc.robot.RobotTelemetry; import frc.robot.leds.LEDsCommands; import frc.robot.training.commands.TrainingCommands; import frc.spectrumLib.Gamepad; import frc.spectrumLib.util.ExpCurve;
8,141
package frc.robot.pilot; public class Pilot extends Gamepad { public class PilotConfig { public static final String name = "Pilot"; public static final int port = 0; public static final double slowModeScalor = 0.5; public final double leftStickDeadzone = 0.1; public final double leftStickExp = 2.0;
package frc.robot.pilot; public class Pilot extends Gamepad { public class PilotConfig { public static final String name = "Pilot"; public static final int port = 0; public static final double slowModeScalor = 0.5; public final double leftStickDeadzone = 0.1; public final double leftStickExp = 2.0;
public final double leftStickScalor = Robot.swerve.config.maxVelocity;
0
2023-10-23 17:01:53+00:00
12k
RaulGB88/MOD-034-Microservicios-con-Java
REM20231023/catalogo/src/main/java/com/example/application/resources/FilmResource.java
[ { "identifier": "DomainEventService", "path": "REM20231023/catalogo/src/main/java/com/example/DomainEventService.java", "snippet": "@Service\npublic class DomainEventService {\n\n\t@Data @AllArgsConstructor\n\tpublic class MessageDTO implements Serializable {\n\t\tprivate static final long serialVersion...
import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.transaction.Transactional; import jakarta.validation.Valid; import org.springdoc.core.converters.models.PageableAsQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; 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 org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.example.DomainEventService; import com.example.application.proxies.MeGustaProxy; import com.example.domains.contracts.services.FilmService; import com.example.domains.entities.Category; import com.example.domains.entities.Film; import com.example.domains.entities.dtos.ActorDTO; import com.example.domains.entities.dtos.FilmDetailsDTO; import com.example.domains.entities.dtos.FilmEditDTO; import com.example.domains.entities.dtos.FilmShortDTO; import com.example.exceptions.BadRequestException; import com.example.exceptions.NotFoundException; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; 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.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag;
7,805
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page") public Page<FilmShortDTO> getAll(Pageable pageable, @RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(pageable, FilmShortDTO.class); } @Operation( summary = "Listado de las peliculas", description = "Recupera la lista de peliculas en formato corto o detallado, se puede paginar.", parameters = { @Parameter(in = ParameterIn.QUERY, name = "mode", required = false, description = "Formato de las peliculas", schema = @Schema(type = "string", allowableValues = { "details", "short" }, defaultValue = "short")) }, responses = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(anyOf = {FilmShortDTO.class, FilmDetailsDTO.class}) )) }) @GetMapping(params = { "page", "mode=details" }) @PageableAsQueryParam @Transactional public Page<FilmDetailsDTO> getAllDetailsPage(@Parameter(hidden = true) Pageable pageable, @RequestParam(defaultValue = "short") String mode) { var content = srv.getAll(pageable); return new PageImpl<>(content.getContent().stream().map(item -> FilmDetailsDTO.from(item)).toList(), pageable, content.getTotalElements()); } @Hidden @GetMapping public List<FilmShortDTO> getAll(@RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(FilmShortDTO.class); } @Hidden @GetMapping(params = "mode=details") public List<FilmDetailsDTO> getAllDetails( // @Parameter(allowEmptyValue = true, required = false, schema = @Schema(type = "string", allowableValues = {"details","short"}, defaultValue = "short")) @RequestParam(defaultValue = "short") String mode) { return srv.getAll().stream().map(item -> FilmDetailsDTO.from(item)).toList(); } @GetMapping(path = "/{id}", params = "mode=short") public FilmShortDTO getOneCorto( @Parameter(description = "Identificador de la pelicula", required = true) @PathVariable int id, @Parameter(required = false, allowEmptyValue = true, schema = @Schema(type = "string", allowableValues = { "details", "short", "edit" }, defaultValue = "edit")) @RequestParam(required = false, defaultValue = "edit") String mode) throws Exception { Optional<Film> rslt = srv.getOne(id); if (rslt.isEmpty())
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page") public Page<FilmShortDTO> getAll(Pageable pageable, @RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(pageable, FilmShortDTO.class); } @Operation( summary = "Listado de las peliculas", description = "Recupera la lista de peliculas en formato corto o detallado, se puede paginar.", parameters = { @Parameter(in = ParameterIn.QUERY, name = "mode", required = false, description = "Formato de las peliculas", schema = @Schema(type = "string", allowableValues = { "details", "short" }, defaultValue = "short")) }, responses = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(anyOf = {FilmShortDTO.class, FilmDetailsDTO.class}) )) }) @GetMapping(params = { "page", "mode=details" }) @PageableAsQueryParam @Transactional public Page<FilmDetailsDTO> getAllDetailsPage(@Parameter(hidden = true) Pageable pageable, @RequestParam(defaultValue = "short") String mode) { var content = srv.getAll(pageable); return new PageImpl<>(content.getContent().stream().map(item -> FilmDetailsDTO.from(item)).toList(), pageable, content.getTotalElements()); } @Hidden @GetMapping public List<FilmShortDTO> getAll(@RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(FilmShortDTO.class); } @Hidden @GetMapping(params = "mode=details") public List<FilmDetailsDTO> getAllDetails( // @Parameter(allowEmptyValue = true, required = false, schema = @Schema(type = "string", allowableValues = {"details","short"}, defaultValue = "short")) @RequestParam(defaultValue = "short") String mode) { return srv.getAll().stream().map(item -> FilmDetailsDTO.from(item)).toList(); } @GetMapping(path = "/{id}", params = "mode=short") public FilmShortDTO getOneCorto( @Parameter(description = "Identificador de la pelicula", required = true) @PathVariable int id, @Parameter(required = false, allowEmptyValue = true, schema = @Schema(type = "string", allowableValues = { "details", "short", "edit" }, defaultValue = "edit")) @RequestParam(required = false, defaultValue = "edit") String mode) throws Exception { Optional<Film> rslt = srv.getOne(id); if (rslt.isEmpty())
throw new NotFoundException();
10
2023-10-24 14:35:15+00:00
12k
Amir-UL-Islam/eTBManager3-Backend
src/test/java/org/msh/etbm/test/DataTestSupport.java
[ { "identifier": "SynchronizableItem", "path": "src/main/java/org/msh/etbm/commons/SynchronizableItem.java", "snippet": "public class SynchronizableItem extends Item<UUID> {\n public SynchronizableItem() {\n super();\n }\n\n public SynchronizableItem(UUID id, String name) {\n super...
import org.msh.etbm.commons.SynchronizableItem; import org.msh.etbm.commons.entities.ServiceResult; import org.msh.etbm.commons.entities.query.QueryResult; import org.msh.etbm.db.entities.AdministrativeUnit; import org.msh.etbm.db.entities.CountryStructure; import org.msh.etbm.services.admin.AddressRequest; import org.msh.etbm.services.admin.admunits.AdminUnitService; import org.msh.etbm.services.admin.admunits.data.AdminUnitData; import org.msh.etbm.services.admin.admunits.data.AdminUnitFormData; import org.msh.etbm.services.admin.units.UnitService; import org.msh.etbm.services.admin.units.UnitType; import org.msh.etbm.services.admin.units.data.UnitData; import org.msh.etbm.services.admin.units.data.UnitFormData; import org.msh.etbm.services.admin.userprofiles.UserProfileQueryParams; import org.msh.etbm.services.admin.userprofiles.UserProfileService; import org.msh.etbm.services.admin.usersws.UserWsService; import org.msh.etbm.services.admin.usersws.data.UserWsData; import org.msh.etbm.services.admin.usersws.data.UserWsFormData; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.UUID;
9,181
package org.msh.etbm.test; /** * Simple component to generate data for testing support * Created by rmemoria on 24/6/16. */ @Component public class DataTestSupport { @Autowired UnitService unitService; @Autowired AdminUnitService adminUnitService; @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired UserProfileService userProfileService; @Autowired UserWsService userWsService; /** * Create an administrative unit * * @param name * @param parentId * @return */ @Transactional public AdminUnitData createAdminUnit(String name, UUID parentId) { AdminUnitFormData au = new AdminUnitFormData(); // select country structure List<CountryStructure> cslist = entityManager .createQuery("from CountryStructure where workspace.id = :id") .setParameter("id", userRequestService.getUserSession().getWorkspaceId()) .getResultList(); int level; if (parentId != null) { AdministrativeUnit parent = (AdministrativeUnit) entityManager .createQuery("from AdministrativeUnit where id = :id") .setParameter("id", parentId) .getSingleResult(); level = parent.getLevel() + 2; } else { level = 1; } CountryStructure cs = null; for (CountryStructure item : cslist) { if (item.getLevel() == level) { cs = item; break; } } if (cs == null) { throw new RuntimeException("No country structure found to insert admin unit"); } au.setName(Optional.of(name)); au.setCountryStructure(Optional.of(cs.getId())); au.setParentId(parentId != null ? Optional.of(parentId) : Optional.<UUID>empty()); ServiceResult res = adminUnitService.create(au); return adminUnitService.findOne(res.getId(), AdminUnitData.class); } @Transactional public UnitData createTBUnit(String name, UUID adminUnitId) { UnitFormData unit = new UnitFormData(); unit.setType(UnitType.TBUNIT); unit.setName(Optional.of(name)); unit.setNumDaysOrder(Optional.of(90)); unit.setNtmFacility(Optional.of(true)); unit.setTbFacility(Optional.of(true)); unit.setDrtbFacility(Optional.of(true)); unit.setActive(Optional.of(true)); AddressRequest addr = new AddressRequest(); addr.setAdminUnitId(adminUnitId); addr.setAddress("Test"); addr.setZipCode("20100-00"); unit.setAddress(addr); ServiceResult res = unitService.create(unit); return unitService.findOne(res.getId(), UnitData.class); } @Transactional
package org.msh.etbm.test; /** * Simple component to generate data for testing support * Created by rmemoria on 24/6/16. */ @Component public class DataTestSupport { @Autowired UnitService unitService; @Autowired AdminUnitService adminUnitService; @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired UserProfileService userProfileService; @Autowired UserWsService userWsService; /** * Create an administrative unit * * @param name * @param parentId * @return */ @Transactional public AdminUnitData createAdminUnit(String name, UUID parentId) { AdminUnitFormData au = new AdminUnitFormData(); // select country structure List<CountryStructure> cslist = entityManager .createQuery("from CountryStructure where workspace.id = :id") .setParameter("id", userRequestService.getUserSession().getWorkspaceId()) .getResultList(); int level; if (parentId != null) { AdministrativeUnit parent = (AdministrativeUnit) entityManager .createQuery("from AdministrativeUnit where id = :id") .setParameter("id", parentId) .getSingleResult(); level = parent.getLevel() + 2; } else { level = 1; } CountryStructure cs = null; for (CountryStructure item : cslist) { if (item.getLevel() == level) { cs = item; break; } } if (cs == null) { throw new RuntimeException("No country structure found to insert admin unit"); } au.setName(Optional.of(name)); au.setCountryStructure(Optional.of(cs.getId())); au.setParentId(parentId != null ? Optional.of(parentId) : Optional.<UUID>empty()); ServiceResult res = adminUnitService.create(au); return adminUnitService.findOne(res.getId(), AdminUnitData.class); } @Transactional public UnitData createTBUnit(String name, UUID adminUnitId) { UnitFormData unit = new UnitFormData(); unit.setType(UnitType.TBUNIT); unit.setName(Optional.of(name)); unit.setNumDaysOrder(Optional.of(90)); unit.setNtmFacility(Optional.of(true)); unit.setTbFacility(Optional.of(true)); unit.setDrtbFacility(Optional.of(true)); unit.setActive(Optional.of(true)); AddressRequest addr = new AddressRequest(); addr.setAdminUnitId(adminUnitId); addr.setAddress("Test"); addr.setZipCode("20100-00"); unit.setAddress(addr); ServiceResult res = unitService.create(unit); return unitService.findOne(res.getId(), UnitData.class); } @Transactional
public SynchronizableItem getAdminProfile() {
0
2023-10-23 13:47:54+00:00
12k
toel--/ocpp-backend-emulator
src/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java
[ { "identifier": "Opcode", "path": "src/org/java_websocket/enums/Opcode.java", "snippet": "public enum Opcode {\n CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING\n // more to come\n}" }, { "identifier": "InvalidDataException", "path": "src/org/java_websocket/exceptions/InvalidDataException.ja...
import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.extensions.CompressionExtension; import org.java_websocket.extensions.ExtensionRequestData; import org.java_websocket.extensions.IExtension; import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.DataFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.framing.TextFrame;
10,724
} byte[] outputBytes = output.toByteArray(); int outputLength = outputBytes.length; /* https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed payload ends with 0x00 0x00 0xff 0xff, they should be removed. To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. */ if (inputFrame.isFin()) { if (endsWithTail(outputBytes)) { outputLength -= TAIL_BYTES.length; } if (serverNoContextTakeover) { deflater.end(); deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); } } // Set frames payload to the new compressed data. ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); } /** * @param data the bytes of data * @return true if the data is OK */ private static boolean endsWithTail(byte[] data) { if (data.length < 4) { return false; } int length = data.length; for (int i = 0; i < TAIL_BYTES.length; i++) { if (TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) { return false; } } return true; } @Override public boolean acceptProvidedExtensionAsServer(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { continue; } // Holds parameters that peer client has sent. Map<String, String> headers = extensionData.getExtensionParameters(); requestedParameters.putAll(headers); if (requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) { clientNoContextTakeover = true; } return true; } return false; } @Override public boolean acceptProvidedExtensionAsClient(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { continue; } // Holds parameters that are sent by the server, as a response to our initial extension request. Map<String, String> headers = extensionData.getExtensionParameters(); // After this point, parameters that the server sent back can be configured, but we don't use them for now. return true; } return false; } @Override public String getProvidedExtensionAsClient() { requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; } @Override public String getProvidedExtensionAsServer() { return SERVER_NO_CONTEXT_TAKEOVER + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); /* return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); */ } @Override public IExtension copyInstance() { return new PerMessageDeflateExtension(); } /** * This extension requires the RSV1 bit to be set only for the first frame. If the frame is type * is CONTINUOUS, RSV1 bit must be unset. */ @Override public void isFrameValid(Framedata inputFrame) throws InvalidDataException { if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) {
package org.java_websocket.extensions.permessage_deflate; /** * PerMessage Deflate Extension (<a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The * "permessage-deflate" Extension</a> in * <a href="https://tools.ietf.org/html/rfc7692">RFC 7692</a>). * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The "permessage-deflate" * Extension in RFC 7692</a> */ public class PerMessageDeflateExtension extends CompressionExtension { // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; // Below values are defined for convenience. They are not used in the compression/decompression phase. // They may be needed during the extension-negotiation offer in the future. private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; private static final byte[] TAIL_BYTES = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF}; private static final int BUFFER_SIZE = 1 << 10; private int threshold = 1024; private boolean serverNoContextTakeover = true; private boolean clientNoContextTakeover = false; // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map<String, String> requestedParameters = new LinkedHashMap<>(); private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); public Inflater getInflater() { return inflater; } public void setInflater(Inflater inflater) { this.inflater = inflater; } public Deflater getDeflater() { return deflater; } public void setDeflater(Deflater deflater) { this.deflater = deflater; } /** * Get the size threshold for doing the compression * @return Size (in bytes) below which messages will not be compressed * @since 1.5.3 */ public int getThreshold() { return threshold; } /** * Set the size when payloads smaller than this will not be compressed. * @param threshold the size in bytes * @since 1.5.3 */ public void setThreshold(int threshold) { this.threshold = threshold; } /** * Access the "server_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @return serverNoContextTakeover is the server no context parameter active */ public boolean isServerNoContextTakeover() { return serverNoContextTakeover; } /** * Setter for the "server_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @param serverNoContextTakeover set the server no context parameter */ public void setServerNoContextTakeover(boolean serverNoContextTakeover) { this.serverNoContextTakeover = serverNoContextTakeover; } /** * Access the "client_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @return clientNoContextTakeover is the client no context parameter active */ public boolean isClientNoContextTakeover() { return clientNoContextTakeover; } /** * Setter for the "client_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @param clientNoContextTakeover set the client no context parameter */ public void setClientNoContextTakeover(boolean clientNoContextTakeover) { this.clientNoContextTakeover = clientNoContextTakeover; } /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the payload of the message. 2. Decompress the resulting data using DEFLATE. See, https://tools.ietf.org/html/rfc7692#section-7.2.2 */ @Override public void decodeFrame(Framedata inputFrame) throws InvalidDataException { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } if (!inputFrame.isRSV1() && inputFrame.getOpcode() != Opcode.CONTINUOUS) { return; } // RSV1 bit must be set only for the first frame. if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); } // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); try { decompress(inputFrame.getPayloadData().array(), output); /* If a message is "first fragmented and then compressed", as this project does, then the inflater can not inflate fragments except the first one. This behavior occurs most likely because those fragments end with "final deflate blocks". We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. And if not, we just reset the inflater and decompress again. Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ if (inflater.getRemaining() > 0) { inflater = new Inflater(true); decompress(inputFrame.getPayloadData().array(), output); } if (inputFrame.isFin()) { decompress(TAIL_BYTES, output); // If context takeover is disabled, inflater can be reset. if (clientNoContextTakeover) { inflater = new Inflater(true); } } } catch (DataFormatException e) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); } // Set frames payload to the new decompressed data. ((FramedataImpl1) inputFrame) .setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); } /** * @param data the bytes of data * @param outputBuffer the output stream * @throws DataFormatException */ private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException { inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; int bytesInflated; while ((bytesInflated = inflater.inflate(buffer)) > 0) { outputBuffer.write(buffer, 0, bytesInflated); } } @Override public void encodeFrame(Framedata inputFrame) { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } byte[] payloadData = inputFrame.getPayloadData().array(); if (payloadData.length < threshold) { return; } // Only the first frame's RSV1 must be set. if (!(inputFrame instanceof ContinuousFrame)) { ((DataFrame) inputFrame).setRSV1(true); } deflater.setInput(payloadData); // Compressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); // Temporary buffer to hold compressed output. byte[] buffer = new byte[1024]; int bytesCompressed; while ((bytesCompressed = deflater.deflate(buffer, 0, buffer.length, Deflater.SYNC_FLUSH)) > 0) { output.write(buffer, 0, bytesCompressed); } byte[] outputBytes = output.toByteArray(); int outputLength = outputBytes.length; /* https://tools.ietf.org/html/rfc7692#section-7.2.1 states that if the final fragment's compressed payload ends with 0x00 0x00 0xff 0xff, they should be removed. To simulate removal, we just pass 4 bytes less to the new payload if the frame is final and outputBytes ends with 0x00 0x00 0xff 0xff. */ if (inputFrame.isFin()) { if (endsWithTail(outputBytes)) { outputLength -= TAIL_BYTES.length; } if (serverNoContextTakeover) { deflater.end(); deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); } } // Set frames payload to the new compressed data. ((FramedataImpl1) inputFrame).setPayload(ByteBuffer.wrap(outputBytes, 0, outputLength)); } /** * @param data the bytes of data * @return true if the data is OK */ private static boolean endsWithTail(byte[] data) { if (data.length < 4) { return false; } int length = data.length; for (int i = 0; i < TAIL_BYTES.length; i++) { if (TAIL_BYTES[i] != data[length - TAIL_BYTES.length + i]) { return false; } } return true; } @Override public boolean acceptProvidedExtensionAsServer(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { continue; } // Holds parameters that peer client has sent. Map<String, String> headers = extensionData.getExtensionParameters(); requestedParameters.putAll(headers); if (requestedParameters.containsKey(CLIENT_NO_CONTEXT_TAKEOVER)) { clientNoContextTakeover = true; } return true; } return false; } @Override public boolean acceptProvidedExtensionAsClient(String inputExtension) { String[] requestedExtensions = inputExtension.split(","); for (String extension : requestedExtensions) { ExtensionRequestData extensionData = ExtensionRequestData.parseExtensionRequest(extension); if (!EXTENSION_REGISTERED_NAME.equalsIgnoreCase(extensionData.getExtensionName())) { continue; } // Holds parameters that are sent by the server, as a response to our initial extension request. Map<String, String> headers = extensionData.getExtensionParameters(); // After this point, parameters that the server sent back can be configured, but we don't use them for now. return true; } return false; } @Override public String getProvidedExtensionAsClient() { requestedParameters.put(CLIENT_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); requestedParameters.put(SERVER_NO_CONTEXT_TAKEOVER, ExtensionRequestData.EMPTY_VALUE); return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + "; " + CLIENT_NO_CONTEXT_TAKEOVER; } @Override public String getProvidedExtensionAsServer() { return SERVER_NO_CONTEXT_TAKEOVER + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); /* return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); */ } @Override public IExtension copyInstance() { return new PerMessageDeflateExtension(); } /** * This extension requires the RSV1 bit to be set only for the first frame. If the frame is type * is CONTINUOUS, RSV1 bit must be unset. */ @Override public void isFrameValid(Framedata inputFrame) throws InvalidDataException { if ((inputFrame instanceof ContinuousFrame) && (inputFrame.isRSV1() || inputFrame.isRSV2() || inputFrame.isRSV3())) {
throw new InvalidFrameException(
2
2023-10-16 23:10:55+00:00
12k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/runners/ForeachTaskRunner.java
[ { "identifier": "Mapping", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/mapping/Mapping.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n/**\n * 映射规则\n * 1. source 代表源集合以json path表示的值\n * 2. target 代表目标集合以json path表示的key\n *\n *...
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.weibo.rill.flow.interfaces.model.mapping.Mapping; import com.weibo.rill.flow.interfaces.model.task.BaseTask; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInvokeMsg; import com.weibo.rill.flow.interfaces.model.task.TaskStatus; import com.weibo.rill.flow.olympicene.core.helper.DAGWalkHelper; import com.weibo.rill.flow.olympicene.core.helper.TaskInfoMaker; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.mapping.IterationMapping; import com.weibo.rill.flow.olympicene.core.model.strategy.Synchronization; import com.weibo.rill.flow.olympicene.core.model.task.ExecutionResult; import com.weibo.rill.flow.olympicene.core.model.task.ForeachTask; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.traversal.helper.Stasher; import com.weibo.rill.flow.olympicene.traversal.mappings.InputOutputMapping; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPath; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors;
10,107
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class ForeachTaskRunner extends AbstractTaskRunner { private final JSONPath jsonPath; @Setter private Stasher stasher; public ForeachTaskRunner(InputOutputMapping inputOutputMapping, JSONPath jsonPath, DAGContextStorage dagContextStorage, DAGInfoStorage dagInfoStorage, DAGStorageProcedure dagStorageProcedure, SwitcherManager switcherManager) { super(inputOutputMapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); this.jsonPath = jsonPath; } @SuppressWarnings("unchecked") @Override protected ExecutionResult doRun(String executionId, TaskInfo taskInfo, Map<String, Object> input) { log.info("foreach task begin to run executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); ForeachTask foreachTask = (ForeachTask) taskInfo.getTask(); IterationMapping iterationMapping = foreachTask.getIterationMapping(); Collection<Object> collection = (Collection<Object>) jsonPath.getValue(ImmutableMap.of("input", input), iterationMapping.getCollection()); if (CollectionUtils.isEmpty(collection) || CollectionUtils.isEmpty(foreachTask.getTasks())) { TaskInvokeMsg taskInvokeMsg = TaskInvokeMsg.builder().msg("loop collection or subTasks empty").build(); taskInfo.updateInvokeMsg(taskInvokeMsg); updateTaskInvokeEndTime(taskInfo); taskInfo.setTaskStatus(TaskStatus.SUCCEED); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } log.info("foreach group size:{} executionId:{}, taskInfoName:{}", collection.size(), executionId, taskInfo.getName()); int maxConcurrentGroups = maxGroupsToRun(executionId, taskInfo, input); Map<String, TaskStatus> indexToStatus = Maps.newConcurrentMap(); taskInfo.setSubGroupIndexToStatus(indexToStatus); Map<String, Boolean> indexToKey = Maps.newConcurrentMap(); taskInfo.setSubGroupKeyJudgementMapping(indexToKey); taskInfo.setTaskStatus(TaskStatus.RUNNING); taskInfo.setChildren(Optional.ofNullable(taskInfo.getChildren()).orElse(Maps.newConcurrentMap())); jsonPath.delete(ImmutableMap.of("input", input), iterationMapping.getCollection()); AtomicInteger index = new AtomicInteger(0); Map<String, Object> contextToUpdate = Maps.newHashMap(); List<Pair<Set<TaskInfo>, Map<String, Object>>> readyToRun = Lists.newArrayList(); collection.forEach(item -> { int groupIndex = index.getAndIncrement(); Map<String, TaskInfo> taskInfoMap = TaskInfoMaker.getMaker().makeTaskInfos(foreachTask.getTasks(), taskInfo, groupIndex); Set<TaskInfo> subTaskInfos = new HashSet<>(taskInfoMap.values()); Map<String, Object> subContext = Maps.newConcurrentMap(); subContext.putAll(input); subContext.put(iterationMapping.getItem(), item); // record whether the subtask is key if (existKeyExp(taskInfo)) { for (TaskInfo subTaskInfo : subTaskInfos) { boolean isKey = isKeySubTask(executionId, subContext, subTaskInfo); if (existKeyExp(subTaskInfo) && isKey) { indexToKey.put(String.valueOf(groupIndex), true); break; } } } taskInfo.getChildren().putAll(subTaskInfos.stream().collect(Collectors.toMap(TaskInfo::getName, it -> it))); indexToStatus.put(String.valueOf(groupIndex), TaskStatus.READY); updateGroupIdentity(executionId, item, taskInfo, iterationMapping.getIdentity(), groupIndex); Map<String, Object> groupedContext = Maps.newHashMap();
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class ForeachTaskRunner extends AbstractTaskRunner { private final JSONPath jsonPath; @Setter private Stasher stasher; public ForeachTaskRunner(InputOutputMapping inputOutputMapping, JSONPath jsonPath, DAGContextStorage dagContextStorage, DAGInfoStorage dagInfoStorage, DAGStorageProcedure dagStorageProcedure, SwitcherManager switcherManager) { super(inputOutputMapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); this.jsonPath = jsonPath; } @SuppressWarnings("unchecked") @Override protected ExecutionResult doRun(String executionId, TaskInfo taskInfo, Map<String, Object> input) { log.info("foreach task begin to run executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); ForeachTask foreachTask = (ForeachTask) taskInfo.getTask(); IterationMapping iterationMapping = foreachTask.getIterationMapping(); Collection<Object> collection = (Collection<Object>) jsonPath.getValue(ImmutableMap.of("input", input), iterationMapping.getCollection()); if (CollectionUtils.isEmpty(collection) || CollectionUtils.isEmpty(foreachTask.getTasks())) { TaskInvokeMsg taskInvokeMsg = TaskInvokeMsg.builder().msg("loop collection or subTasks empty").build(); taskInfo.updateInvokeMsg(taskInvokeMsg); updateTaskInvokeEndTime(taskInfo); taskInfo.setTaskStatus(TaskStatus.SUCCEED); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); return ExecutionResult.builder().taskStatus(taskInfo.getTaskStatus()).build(); } log.info("foreach group size:{} executionId:{}, taskInfoName:{}", collection.size(), executionId, taskInfo.getName()); int maxConcurrentGroups = maxGroupsToRun(executionId, taskInfo, input); Map<String, TaskStatus> indexToStatus = Maps.newConcurrentMap(); taskInfo.setSubGroupIndexToStatus(indexToStatus); Map<String, Boolean> indexToKey = Maps.newConcurrentMap(); taskInfo.setSubGroupKeyJudgementMapping(indexToKey); taskInfo.setTaskStatus(TaskStatus.RUNNING); taskInfo.setChildren(Optional.ofNullable(taskInfo.getChildren()).orElse(Maps.newConcurrentMap())); jsonPath.delete(ImmutableMap.of("input", input), iterationMapping.getCollection()); AtomicInteger index = new AtomicInteger(0); Map<String, Object> contextToUpdate = Maps.newHashMap(); List<Pair<Set<TaskInfo>, Map<String, Object>>> readyToRun = Lists.newArrayList(); collection.forEach(item -> { int groupIndex = index.getAndIncrement(); Map<String, TaskInfo> taskInfoMap = TaskInfoMaker.getMaker().makeTaskInfos(foreachTask.getTasks(), taskInfo, groupIndex); Set<TaskInfo> subTaskInfos = new HashSet<>(taskInfoMap.values()); Map<String, Object> subContext = Maps.newConcurrentMap(); subContext.putAll(input); subContext.put(iterationMapping.getItem(), item); // record whether the subtask is key if (existKeyExp(taskInfo)) { for (TaskInfo subTaskInfo : subTaskInfos) { boolean isKey = isKeySubTask(executionId, subContext, subTaskInfo); if (existKeyExp(subTaskInfo) && isKey) { indexToKey.put(String.valueOf(groupIndex), true); break; } } } taskInfo.getChildren().putAll(subTaskInfos.stream().collect(Collectors.toMap(TaskInfo::getName, it -> it))); indexToStatus.put(String.valueOf(groupIndex), TaskStatus.READY); updateGroupIdentity(executionId, item, taskInfo, iterationMapping.getIdentity(), groupIndex); Map<String, Object> groupedContext = Maps.newHashMap();
groupedContext.put(DAGWalkHelper.getInstance().buildSubTaskContextFieldName(subTaskInfos.iterator().next().getRouteName()), subContext);
5
2023-11-03 03:46:01+00:00
12k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/test/java/org/example/service/impl/OrderServiceImplTest.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.PaymentType; import org.example.common.constant.ProductName; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.service.AlipayService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyDouble; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.when;
7,625
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; class OrderServiceImplTest { @Mock AlipayService alipayService; @Mock OrderOtsHelper orderOtsHelper; @Mock WalletHelper walletHelper; @Mock ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Mock Logger log; @Mock private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Mock private ServiceManager serviceManager; @InjectMocks OrderServiceImpl orderServiceImpl; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void testCreateOrder() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), anyList(), anyList(), anyString(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE);
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; class OrderServiceImplTest { @Mock AlipayService alipayService; @Mock OrderOtsHelper orderOtsHelper; @Mock WalletHelper walletHelper; @Mock ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Mock Logger log; @Mock private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Mock private ServiceManager serviceManager; @InjectMocks OrderServiceImpl orderServiceImpl; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void testCreateOrder() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), anyList(), anyList(), anyString(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE);
BaseResult<String> result = orderServiceImpl.createOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), createOrderParam);
10
2023-11-01 08:19:34+00:00
12k
mioclient/oyvey-ported
src/main/java/me/alpha432/oyvey/features/gui/items/buttons/BindButton.java
[ { "identifier": "OyVey", "path": "src/main/java/me/alpha432/oyvey/OyVey.java", "snippet": "public class OyVey implements ModInitializer, ClientModInitializer {\n public static final String NAME = \"OyVey\";\n public static final String VERSION = \"0.0.3 - 1.20.1\";\n\n public static float TIMER...
import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.gui.OyVeyGui; import me.alpha432.oyvey.features.modules.client.ClickGui; import me.alpha432.oyvey.features.settings.Bind; import me.alpha432.oyvey.features.settings.Setting; import me.alpha432.oyvey.util.ColorUtil; import me.alpha432.oyvey.util.RenderUtil; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.sound.PositionedSoundInstance; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Formatting; import org.lwjgl.glfw.GLFW;
8,047
package me.alpha432.oyvey.features.gui.items.buttons; public class BindButton extends Button { private final Setting<Bind> setting; public boolean isListening; public BindButton(Setting<Bind> setting) { super(setting.getName()); this.setting = setting; this.width = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {
package me.alpha432.oyvey.features.gui.items.buttons; public class BindButton extends Button { private final Setting<Bind> setting; public boolean isListening; public BindButton(Setting<Bind> setting) { super(setting.getName()); this.setting = setting; this.width = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {
int color = ColorUtil.toARGB(ClickGui.getInstance().red.getValue(), ClickGui.getInstance().green.getValue(), ClickGui.getInstance().blue.getValue(), 255);
5
2023-11-05 18:10:28+00:00
12k
EB-wilson/TooManyItems
src/main/java/tmi/recipe/types/BuildingRecipe.java
[ { "identifier": "Recipe", "path": "src/main/java/tmi/recipe/Recipe.java", "snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeT...
import arc.Core; import arc.graphics.Color; import arc.math.Angles; import arc.math.Mathf; import arc.math.Rand; import arc.math.geom.Vec2; import arc.scene.Group; import arc.scene.ui.ImageButton; import arc.scene.ui.Label; import arc.scene.ui.layout.Scl; import arc.struct.ObjectMap; import arc.struct.Seq; import arc.util.Align; import arc.util.Log; import arc.util.Strings; import mindustry.Vars; import mindustry.core.UI; import mindustry.gen.Icon; import mindustry.ui.Styles; import mindustry.world.Block; import mindustry.world.meta.Stat; import mindustry.world.meta.StatUnit; import tmi.recipe.Recipe; import tmi.recipe.RecipeItemStack; import tmi.recipe.RecipeType; import tmi.ui.NodeType; import tmi.ui.RecipeNode; import tmi.ui.RecipeView; import tmi.util.Consts; import static mindustry.Vars.state; import static tmi.ui.RecipeNode.SIZE;
7,313
package tmi.recipe.types; public class BuildingRecipe extends RecipeType { public static final float ITEM_PAD = Scl.scl(30); public static final float RAND = Scl.scl(65); public static final float MIN_RAD = Scl.scl(125); final Vec2 bound = new Vec2(); final Vec2 blockPos = new Vec2(); final ObjectMap<RecipeItem<?>, Vec2> materialPos = new ObjectMap<>(); float time; Block build; @Override public void buildView(Group view) { Label label = new Label(Core.bundle.get("misc.building"), Styles.outlineLabel); label.getStyle().background = Consts.grayUIAlpha; label.validate(); label.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + label.getPrefWidth()/2, blockPos.y, Align.center); view.addChild(label); if (time > 0){ Label time = new Label(Stat.buildTime.localized() + ": " + (this.time > 3600? UI.formatTime(this.time): Strings.autoFixed(this.time/60, 2) + StatUnit.seconds.localized()), Styles.outlineLabel); time.getStyle().background = Consts.grayUIAlpha; time.validate(); time.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + time.getPrefWidth()/2, blockPos.y - label.getHeight() - 4, Align.center); view.addChild(time); } if (Vars.state.isGame()){ ImageButton button = new ImageButton(Icon.hammer, Styles.clearNonei); button.setDisabled(() -> build == null || !build.unlockedNow() || !build.placeablePlayer || !build.environmentBuildable() || !build.supportsEnv(state.rules.env)); button.clicked(() -> { while (Core.scene.hasDialog()) { Core.scene.getDialog().hide(); } Vars.control.input.block = build; }); button.margin(5); button.setSize(40); button.setPosition(bound.x, 0, Align.topRight); view.addChild(button); } } @Override public Vec2 initial(Recipe recipe) { build = (Block) recipe.block.item; time = recipe.time; bound.setZero(); blockPos.setZero(); materialPos.clear(); Seq<RecipeItemStack> seq = recipe.materials.values().toSeq(); float radians = 2f*Mathf.pi/seq.size; float radius = Math.max(MIN_RAD, (SIZE + ITEM_PAD)/radians); bound.set(radius + SIZE, radius + SIZE).scl(2); blockPos.set(bound).scl(0.5f); Rand r = new Rand(build.id); float off = r.random(0, 360f); for (int i = 0; i < seq.size; i++) { float angle = radians*i*Mathf.radDeg + off; float rot = r.random(0, RAND) + radius; materialPos.put(seq.get(i).item(), new Vec2(blockPos.x + Angles.trnsx(angle, rot), blockPos.y + Angles.trnsy(angle, rot))); } return bound; } @Override public void layout(RecipeNode recipeNode) { if (recipeNode.type == NodeType.material){ Vec2 pos = materialPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.block){ recipeNode.setPosition(blockPos.x, blockPos.y, Align.center); } else Log.warn("unexpected production in building recipe"); } @Override
package tmi.recipe.types; public class BuildingRecipe extends RecipeType { public static final float ITEM_PAD = Scl.scl(30); public static final float RAND = Scl.scl(65); public static final float MIN_RAD = Scl.scl(125); final Vec2 bound = new Vec2(); final Vec2 blockPos = new Vec2(); final ObjectMap<RecipeItem<?>, Vec2> materialPos = new ObjectMap<>(); float time; Block build; @Override public void buildView(Group view) { Label label = new Label(Core.bundle.get("misc.building"), Styles.outlineLabel); label.getStyle().background = Consts.grayUIAlpha; label.validate(); label.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + label.getPrefWidth()/2, blockPos.y, Align.center); view.addChild(label); if (time > 0){ Label time = new Label(Stat.buildTime.localized() + ": " + (this.time > 3600? UI.formatTime(this.time): Strings.autoFixed(this.time/60, 2) + StatUnit.seconds.localized()), Styles.outlineLabel); time.getStyle().background = Consts.grayUIAlpha; time.validate(); time.setPosition(blockPos.x + SIZE/2 + ITEM_PAD + time.getPrefWidth()/2, blockPos.y - label.getHeight() - 4, Align.center); view.addChild(time); } if (Vars.state.isGame()){ ImageButton button = new ImageButton(Icon.hammer, Styles.clearNonei); button.setDisabled(() -> build == null || !build.unlockedNow() || !build.placeablePlayer || !build.environmentBuildable() || !build.supportsEnv(state.rules.env)); button.clicked(() -> { while (Core.scene.hasDialog()) { Core.scene.getDialog().hide(); } Vars.control.input.block = build; }); button.margin(5); button.setSize(40); button.setPosition(bound.x, 0, Align.topRight); view.addChild(button); } } @Override public Vec2 initial(Recipe recipe) { build = (Block) recipe.block.item; time = recipe.time; bound.setZero(); blockPos.setZero(); materialPos.clear(); Seq<RecipeItemStack> seq = recipe.materials.values().toSeq(); float radians = 2f*Mathf.pi/seq.size; float radius = Math.max(MIN_RAD, (SIZE + ITEM_PAD)/radians); bound.set(radius + SIZE, radius + SIZE).scl(2); blockPos.set(bound).scl(0.5f); Rand r = new Rand(build.id); float off = r.random(0, 360f); for (int i = 0; i < seq.size; i++) { float angle = radians*i*Mathf.radDeg + off; float rot = r.random(0, RAND) + radius; materialPos.put(seq.get(i).item(), new Vec2(blockPos.x + Angles.trnsx(angle, rot), blockPos.y + Angles.trnsy(angle, rot))); } return bound; } @Override public void layout(RecipeNode recipeNode) { if (recipeNode.type == NodeType.material){ Vec2 pos = materialPos.get(recipeNode.stack.item()); recipeNode.setPosition(pos.x, pos.y, Align.center); } else if (recipeNode.type == NodeType.block){ recipeNode.setPosition(blockPos.x, blockPos.y, Align.center); } else Log.warn("unexpected production in building recipe"); } @Override
public RecipeView.LineMeta line(RecipeNode from, RecipeNode to) {
5
2023-11-05 11:39:21+00:00
12k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/library/MyClassesFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.group.ClassCopyAdapter; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.data.model.User; import com.daominh.quickmem.databinding.FragmentMyClassesBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateClassActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
10,063
package com.daominh.quickmem.ui.fragments.library; public class MyClassesFragment extends Fragment { private FragmentMyClassesBinding binding; private UserSharePreferences userSharePreferences; private ArrayList<Group> classes;
package com.daominh.quickmem.ui.fragments.library; public class MyClassesFragment extends Fragment { private FragmentMyClassesBinding binding; private UserSharePreferences userSharePreferences; private ArrayList<Group> classes;
private GroupDAO groupDAO;
2
2023-11-07 16:56:39+00:00
12k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/commands/ArmToPoseCommand.java
[ { "identifier": "ArmSubsystem", "path": "src/main/java/org/frcteam2910/c2023/subsystems/arm/ArmSubsystem.java", "snippet": "public class ArmSubsystem extends SubsystemBase {\n // Distance from pivot point to arm base\n public static final double ARM_PIVOT_OFFSET = Units.inchesToMeters(6.75 - 0.125...
import java.util.function.BooleanSupplier; import java.util.function.Supplier; import edu.wpi.first.math.util.Units; import edu.wpi.first.wpilibj2.command.CommandBase; import org.frcteam2910.c2023.subsystems.arm.ArmSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.ArmPositions; import org.frcteam2910.c2023.util.GamePiece; import org.frcteam2910.c2023.util.GridLevel; import org.frcteam2910.c2023.util.OperatorDashboard;
10,381
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm;
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm;
private Supplier<ArmPositions> targetPoseSupplier;
2
2023-11-03 02:12:12+00:00
12k
YunaBraska/type-map
src/test/java/berlin/yuna/typemap/config/TypeConversionRegisterTest.java
[ { "identifier": "TestEnum", "path": "src/test/java/berlin/yuna/typemap/model/TestEnum.java", "snippet": "public enum TestEnum {\n\n AA,\n BB,\n CC\n}" }, { "identifier": "TypeConversionRegister", "path": "src/main/java/berlin/yuna/typemap/config/TypeConversionRegister.java", "sn...
import berlin.yuna.typemap.model.TestEnum; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.net.*; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Time; import java.sql.Timestamp; import java.time.*; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static berlin.yuna.typemap.config.TypeConversionRegister.*; import static berlin.yuna.typemap.logic.TypeConverter.convertObj; import static org.assertj.core.api.Assertions.assertThat;
8,088
package berlin.yuna.typemap.config; class TypeConversionRegisterTest { @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } @AfterEach void tearDown() { registerTypeConvert(String.class, Integer.class, Integer::valueOf); } @Test void registerCustomConversion() { assertThat(convertObj("123", Integer.class)).isEqualTo(123); registerTypeConvert(String.class, Integer.class, source -> 999); assertThat(convertObj("123", Integer.class)).isEqualTo(999); conversionFrom(String.class).to(Integer.class).register(source -> 567); assertThat(convertObj("123", Integer.class)).isEqualTo(567); } @Test void registerCustomConversionThrowingException() { assertThat(convertObj("123", Integer.class)).isEqualTo(123); registerTypeConvert(String.class, Integer.class, source -> { throw new IllegalStateException("This Exception should be ignored"); }); assertThat(convertObj("123", Integer.class)).isNull(); } @Test void convertNumbers() { assertThat(convertObj(123, Long.class)).isEqualTo(123L); assertThat(convertObj(123L, Integer.class)).isEqualTo(123); assertThat(convertObj(123, Float.class)).isEqualTo(123f); assertThat(convertObj(123, Double.class)).isEqualTo(123d); assertThat(convertObj(123, Short.class)).isEqualTo(Short.valueOf("123")); assertThat(convertObj(123, Byte.class)).isEqualTo(((Integer) 123).byteValue()); assertThat(convertObj(123, BigInteger.class)).isEqualTo(BigInteger.valueOf(123)); assertThat(convertObj(123, BigDecimal.class)).isEqualTo(BigDecimal.valueOf(((Number) 123).doubleValue())); assertThat(convertObj(123, Number.class)).isEqualTo(123); assertThat(convertObj(123, Boolean.class)).isFalse(); assertThat(convertObj(1, Boolean.class)).isTrue(); assertThat(convertObj(0, Boolean.class)).isFalse(); } @Test void convertAtomics() { assertThat(convertObj(new AtomicInteger(123), Integer.class)).isEqualTo(123); assertThat(convertObj(123, AtomicInteger.class).get()).isEqualTo(123); assertThat(convertObj(new AtomicLong(123), Long.class)).isEqualTo(123L); assertThat(convertObj(123, AtomicLong.class).get()).isEqualTo(123L); assertThat(convertObj(new AtomicBoolean(true), Boolean.class)).isTrue(); assertThat(convertObj(new AtomicBoolean(false), Boolean.class)).isFalse(); assertThat(convertObj(false, AtomicBoolean.class).get()).isFalse(); assertThat(convertObj(true, AtomicBoolean.class).get()).isTrue(); } @Test void convertStrings() { final UUID uuid = UUID.randomUUID(); assertThat(convertObj("123", Character.class)).isEqualTo('1'); assertThat(convertObj('1', String.class)).isEqualTo("1"); assertThat(convertObj(uuid, String.class)).isEqualTo(uuid.toString()); assertThat(convertObj(uuid.toString(), UUID.class)).isEqualTo(uuid); assertThat(convertObj("true", Boolean.class)).isTrue(); assertThat(convertObj("false", Boolean.class)).isFalse(); assertThat(convertObj("1", Boolean.class)).isTrue(); assertThat(convertObj("0", Boolean.class)).isFalse(); assertThat(convertObj("123", Boolean.class)).isFalse(); assertThat(convertObj(null, String.class)).isNull(); assertThat(convertObj(true, String.class)).isEqualTo("true"); assertThat(convertObj(false, String.class)).isEqualTo("false");
package berlin.yuna.typemap.config; class TypeConversionRegisterTest { @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } @AfterEach void tearDown() { registerTypeConvert(String.class, Integer.class, Integer::valueOf); } @Test void registerCustomConversion() { assertThat(convertObj("123", Integer.class)).isEqualTo(123); registerTypeConvert(String.class, Integer.class, source -> 999); assertThat(convertObj("123", Integer.class)).isEqualTo(999); conversionFrom(String.class).to(Integer.class).register(source -> 567); assertThat(convertObj("123", Integer.class)).isEqualTo(567); } @Test void registerCustomConversionThrowingException() { assertThat(convertObj("123", Integer.class)).isEqualTo(123); registerTypeConvert(String.class, Integer.class, source -> { throw new IllegalStateException("This Exception should be ignored"); }); assertThat(convertObj("123", Integer.class)).isNull(); } @Test void convertNumbers() { assertThat(convertObj(123, Long.class)).isEqualTo(123L); assertThat(convertObj(123L, Integer.class)).isEqualTo(123); assertThat(convertObj(123, Float.class)).isEqualTo(123f); assertThat(convertObj(123, Double.class)).isEqualTo(123d); assertThat(convertObj(123, Short.class)).isEqualTo(Short.valueOf("123")); assertThat(convertObj(123, Byte.class)).isEqualTo(((Integer) 123).byteValue()); assertThat(convertObj(123, BigInteger.class)).isEqualTo(BigInteger.valueOf(123)); assertThat(convertObj(123, BigDecimal.class)).isEqualTo(BigDecimal.valueOf(((Number) 123).doubleValue())); assertThat(convertObj(123, Number.class)).isEqualTo(123); assertThat(convertObj(123, Boolean.class)).isFalse(); assertThat(convertObj(1, Boolean.class)).isTrue(); assertThat(convertObj(0, Boolean.class)).isFalse(); } @Test void convertAtomics() { assertThat(convertObj(new AtomicInteger(123), Integer.class)).isEqualTo(123); assertThat(convertObj(123, AtomicInteger.class).get()).isEqualTo(123); assertThat(convertObj(new AtomicLong(123), Long.class)).isEqualTo(123L); assertThat(convertObj(123, AtomicLong.class).get()).isEqualTo(123L); assertThat(convertObj(new AtomicBoolean(true), Boolean.class)).isTrue(); assertThat(convertObj(new AtomicBoolean(false), Boolean.class)).isFalse(); assertThat(convertObj(false, AtomicBoolean.class).get()).isFalse(); assertThat(convertObj(true, AtomicBoolean.class).get()).isTrue(); } @Test void convertStrings() { final UUID uuid = UUID.randomUUID(); assertThat(convertObj("123", Character.class)).isEqualTo('1'); assertThat(convertObj('1', String.class)).isEqualTo("1"); assertThat(convertObj(uuid, String.class)).isEqualTo(uuid.toString()); assertThat(convertObj(uuid.toString(), UUID.class)).isEqualTo(uuid); assertThat(convertObj("true", Boolean.class)).isTrue(); assertThat(convertObj("false", Boolean.class)).isFalse(); assertThat(convertObj("1", Boolean.class)).isTrue(); assertThat(convertObj("0", Boolean.class)).isFalse(); assertThat(convertObj("123", Boolean.class)).isFalse(); assertThat(convertObj(null, String.class)).isNull(); assertThat(convertObj(true, String.class)).isEqualTo("true"); assertThat(convertObj(false, String.class)).isEqualTo("false");
assertThat(convertObj(TestEnum.BB, String.class)).isEqualTo("BB");
0
2023-11-09 14:40:13+00:00
12k
estkme-group/InfiLPA
messages/src/main/java/com/gsma/sgp/messages/pkix1implicit88/GeneralName.java
[ { "identifier": "Attribute", "path": "messages/src/main/java/com/gsma/sgp/messages/pkix1explicit88/Attribute.java", "snippet": "public class Attribute implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static class Values implements BerType, Serializable...
import java.io.IOException; import java.io.EOFException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.io.Serializable; import com.beanit.jasn1.ber.*; import com.beanit.jasn1.ber.types.*; import com.beanit.jasn1.ber.types.string.*; import com.gsma.sgp.messages.pkix1explicit88.Attribute; import com.gsma.sgp.messages.pkix1explicit88.CertificateSerialNumber; import com.gsma.sgp.messages.pkix1explicit88.DirectoryString; import com.gsma.sgp.messages.pkix1explicit88.Name; import com.gsma.sgp.messages.pkix1explicit88.ORAddress; import com.gsma.sgp.messages.pkix1explicit88.RelativeDistinguishedName;
7,201
/** * This class file was automatically generated by jASN1 v1.11.3 (http://www.beanit.com) */ package com.gsma.sgp.messages.pkix1implicit88; public class GeneralName implements BerType, Serializable { private static final long serialVersionUID = 1L; public byte[] code = null; private AnotherName otherName = null; private BerIA5String rfc822Name = null; private BerIA5String dNSName = null;
/** * This class file was automatically generated by jASN1 v1.11.3 (http://www.beanit.com) */ package com.gsma.sgp.messages.pkix1implicit88; public class GeneralName implements BerType, Serializable { private static final long serialVersionUID = 1L; public byte[] code = null; private AnotherName otherName = null; private BerIA5String rfc822Name = null; private BerIA5String dNSName = null;
private ORAddress x400Address = null;
4
2023-11-06 02:41:13+00:00
12k
viego1999/xuecheng-plus-project
xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CoursePublishServiceImpl.java
[ { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin...
import com.alibaba.fastjson.JSON; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.content.config.MultipartSupportConfig; import com.xuecheng.content.feignclient.MediaServiceClient; import com.xuecheng.content.feignclient.SearchServiceClient; import com.xuecheng.content.feignclient.po.CourseIndex; import com.xuecheng.content.mapper.CourseBaseMapper; import com.xuecheng.content.mapper.CourseMarketMapper; import com.xuecheng.content.mapper.CoursePublishMapper; import com.xuecheng.content.mapper.CoursePublishPreMapper; import com.xuecheng.content.model.dto.CourseBaseInfoDto; import com.xuecheng.content.model.dto.CoursePreviewDto; import com.xuecheng.content.model.dto.TeachplanDto; import com.xuecheng.content.model.po.CourseBase; import com.xuecheng.content.model.po.CourseMarket; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.content.model.po.CoursePublishPre; import com.xuecheng.content.service.CourseBaseInfoService; import com.xuecheng.content.service.CoursePublishService; import com.xuecheng.content.service.TeachplanService; import com.xuecheng.messagesdk.model.po.MqMessage; import com.xuecheng.messagesdk.service.MqMessageService; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
8,245
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CoursePublishServiceImpl * @since 2023/1/30 15:45 */ @Slf4j @Service public class CoursePublishServiceImpl implements CoursePublishService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CoursePublishServiceImpl * @since 2023/1/30 15:45 */ @Slf4j @Service public class CoursePublishServiceImpl implements CoursePublishService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource
private CoursePublishMapper coursePublishMapper;
7
2023-11-04 07:15:26+00:00
12k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \...
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,647
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao;
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao;
List<Attends> alist;
7
2023-11-03 02:29:57+00:00
12k
ballerina-platform/module-ballerina-data-xmldata
native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/XmlParser.java
[ { "identifier": "FromString", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java", "snippet": "public class FromString {\n\n public static Object fromStringWithType(BString string, BTypedesc typed) {\n Type expType = typed.getDescribingType();\n\n try {\n ...
import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.RecordType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import io.ballerina.stdlib.data.xmldata.FromString; import io.ballerina.stdlib.data.xmldata.utils.Constants; import io.ballerina.stdlib.data.xmldata.utils.DataUtils; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; import java.io.Reader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Stack; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.DTD; import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
10,267
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) { return DiagnosticLog.error(DiagnosticErrorCode.XML_PARSE_ERROR, e.getMessage()); } } private void handleXMLStreamException(Exception e) { String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); if (reason == null) { throw DiagnosticLog.getXmlError(PARSE_ERROR); } throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + reason); } public Object parse(Type type, XmlParserData xmlParserData) { if (type.getTag() != TypeTags.RECORD_TYPE_TAG) {
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) { return DiagnosticLog.error(DiagnosticErrorCode.XML_PARSE_ERROR, e.getMessage()); } } private void handleXMLStreamException(Exception e) { String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); if (reason == null) { throw DiagnosticLog.getXmlError(PARSE_ERROR); } throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + reason); } public Object parse(Type type, XmlParserData xmlParserData) { if (type.getTag() != TypeTags.RECORD_TYPE_TAG) {
throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, Constants.RECORD, type.getName());
1
2023-11-08 04:13:52+00:00
12k
Mau38/SparePartsFTC
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.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.external.navigation.Quaternion; 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,847
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 List<Long> nsTimes; 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;
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 List<Long> nsTimes; 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.kP;
1
2023-11-06 21:25:54+00:00
12k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/ui/frames/MainFrame.java
[ { "identifier": "Const", "path": "src/main/java/dev/cele/asa_sm/Const.java", "snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.res...
import com.fasterxml.jackson.databind.ObjectMapper; import com.formdev.flatlaf.FlatClientProperties; import dev.cele.asa_sm.Const; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.dto.AsaServerConfigDto; import dev.cele.asa_sm.services.UpdateService; import dev.cele.asa_sm.ui.components.ServerTab; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.IntConsumer; import java.util.stream.Collectors;
7,631
package dev.cele.asa_sm.ui.frames; @Slf4j public class MainFrame extends JFrame { private final JTabbedPane tabbedPane = new JTabbedPane(); private final ObjectMapper objectMapper = SpringApplicationContext.autoWire(ObjectMapper.class); private final UpdateService updateService = SpringApplicationContext.autoWire(UpdateService.class); private final Environment environment = SpringApplicationContext.autoWire(Environment.class); @SneakyThrows public MainFrame() { setTitle("ASA Server Manager"); setDefaultCloseOperation(EXIT_ON_CLOSE); setMinimumSize(new Dimension(825, 600)); setSize(new Dimension(1020, 890)); setLocationRelativeTo(null); setLayout(new BorderLayout()); var iconResource = new ClassPathResource("icon.png"); setIconImage( new ImageIcon(iconResource.getContentAsByteArray()).getImage() ); try {
package dev.cele.asa_sm.ui.frames; @Slf4j public class MainFrame extends JFrame { private final JTabbedPane tabbedPane = new JTabbedPane(); private final ObjectMapper objectMapper = SpringApplicationContext.autoWire(ObjectMapper.class); private final UpdateService updateService = SpringApplicationContext.autoWire(UpdateService.class); private final Environment environment = SpringApplicationContext.autoWire(Environment.class); @SneakyThrows public MainFrame() { setTitle("ASA Server Manager"); setDefaultCloseOperation(EXIT_ON_CLOSE); setMinimumSize(new Dimension(825, 600)); setSize(new Dimension(1020, 890)); setLocationRelativeTo(null); setLayout(new BorderLayout()); var iconResource = new ClassPathResource("icon.png"); setIconImage( new ImageIcon(iconResource.getContentAsByteArray()).getImage() ); try {
Files.createDirectories(Const.PROFILES_DIR);
0
2023-11-07 19:36:49+00:00
12k
SeanPesce/AWS-IoT-Recon
src/main/java/com/seanpesce/aws/iot/AwsIotRecon.java
[ { "identifier": "AwsIotConstants", "path": "src/main/java/com/seanpesce/aws/iot/AwsIotConstants.java", "snippet": "public class AwsIotConstants {\n\n public static final String PROJECT_TITLE = \"[AWS IoT Core Enumeration Tool by Sean Pesce]\";\n\n public static final String ACTION_MQTT_DUMP = \"mq...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.security.cert.CertificateException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import com.seanpesce.aws.iot.AwsIotConstants; import com.seanpesce.http.MtlsHttpClient; import com.seanpesce.mqtt.MqttScript; import com.seanpesce.regex.PatternWithNamedGroups; import com.seanpesce.Util; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder;
7,335
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX)); public static String jarName = AwsIotRecon.class.getSimpleName() + ".jar"; // Run-time resources public static CommandLine cmd = null; public static String clientId = null; public static MqttClientConnection clientConnection = null; public static Mqtt5Client mqtt5ClientConnection = null; public static ClientTlsContext tlsContext = null; // For assuming IAM roles public static final MqttClientConnectionEvents connectionCallbacks = new MqttClientConnectionEvents() { @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionInterrupted(int errorCode) { System.err.println("[WARNING] Connection interrupted: (" + errorCode + ") " + CRT.awsErrorName(errorCode) + ": " + CRT.awsErrorString(errorCode)); } @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionResumed(boolean sessionPresent) { System.err.println("[INFO] Connection resumed (" + (sessionPresent ? "existing" : "new") + " session)"); } }; public static final Consumer<MqttMessage> genericMqttMsgConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { String msg = "\n[MQTT Message] " + message.getTopic() + "\t" + new String(message.getPayload(), StandardCharsets.UTF_8); System.out.println(msg); } }; public static final Consumer<MqttMessage> topicFieldHarvester = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { Map<String, String> m = extractFieldsFromTopic(message.getTopic()); if (m != null) { String msg = "[MQTT Topic Field Harvester] " + message.getTopic() + "\t" + m; System.out.println(msg); } } }; public static void main(String[] args) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException, InterruptedException, ExecutionException { cmd = parseCommandLineArguments(args); buildConnection(cmd); String action = cmd.getOptionValue("a"); if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { mqttConnect(); beginMqttDump(); } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { mqttConnect(); beginMqttTopicFieldHarvesting(); } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) {
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX)); public static String jarName = AwsIotRecon.class.getSimpleName() + ".jar"; // Run-time resources public static CommandLine cmd = null; public static String clientId = null; public static MqttClientConnection clientConnection = null; public static Mqtt5Client mqtt5ClientConnection = null; public static ClientTlsContext tlsContext = null; // For assuming IAM roles public static final MqttClientConnectionEvents connectionCallbacks = new MqttClientConnectionEvents() { @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionInterrupted(int errorCode) { System.err.println("[WARNING] Connection interrupted: (" + errorCode + ") " + CRT.awsErrorName(errorCode) + ": " + CRT.awsErrorString(errorCode)); } @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionResumed(boolean sessionPresent) { System.err.println("[INFO] Connection resumed (" + (sessionPresent ? "existing" : "new") + " session)"); } }; public static final Consumer<MqttMessage> genericMqttMsgConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { String msg = "\n[MQTT Message] " + message.getTopic() + "\t" + new String(message.getPayload(), StandardCharsets.UTF_8); System.out.println(msg); } }; public static final Consumer<MqttMessage> topicFieldHarvester = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { Map<String, String> m = extractFieldsFromTopic(message.getTopic()); if (m != null) { String msg = "[MQTT Topic Field Harvester] " + message.getTopic() + "\t" + m; System.out.println(msg); } } }; public static void main(String[] args) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException, InterruptedException, ExecutionException { cmd = parseCommandLineArguments(args); buildConnection(cmd); String action = cmd.getOptionValue("a"); if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { mqttConnect(); beginMqttDump(); } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { mqttConnect(); beginMqttTopicFieldHarvesting(); } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) {
getIamCredentialsFromDeviceX509(cmd.hasOption("R") ? Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("R")).split("\n") : new String[] {"admin"}, cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId);
4
2023-11-06 23:10:21+00:00
12k
baguchan/BetterWithAquatic
src/main/java/baguchan/better_with_aquatic/mixin/BiomeMixin.java
[ { "identifier": "BetterWithAquatic", "path": "src/main/java/baguchan/better_with_aquatic/BetterWithAquatic.java", "snippet": "public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer {\n\n\tpublic static final String MOD_ID = \"better_with_aquatic\";\n\tprivate static final boolean ...
import baguchan.better_with_aquatic.BetterWithAquatic; import baguchan.better_with_aquatic.entity.EntityAnglerFish; import baguchan.better_with_aquatic.entity.EntityDrowned; import baguchan.better_with_aquatic.entity.EntityFish; import baguchan.better_with_aquatic.entity.EntityFrog; import net.minecraft.core.entity.SpawnListEntry; import net.minecraft.core.world.biome.Biome; import net.minecraft.core.world.biome.Biomes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List;
8,437
package baguchan.better_with_aquatic.mixin; @Mixin(value = Biome.class, remap = false) public class BiomeMixin { @Shadow protected List<SpawnListEntry> spawnableWaterCreatureList; @Shadow protected List<SpawnListEntry> spawnableCreatureList; @Shadow protected List<SpawnListEntry> spawnableMonsterList; @Inject(method = "<init>", remap = false, at = @At("TAIL")) private void addMobs(CallbackInfo ci) { Biome biome = (Biome) (Object) this; if (biome != Biomes.NETHER_NETHER) {
package baguchan.better_with_aquatic.mixin; @Mixin(value = Biome.class, remap = false) public class BiomeMixin { @Shadow protected List<SpawnListEntry> spawnableWaterCreatureList; @Shadow protected List<SpawnListEntry> spawnableCreatureList; @Shadow protected List<SpawnListEntry> spawnableMonsterList; @Inject(method = "<init>", remap = false, at = @At("TAIL")) private void addMobs(CallbackInfo ci) { Biome biome = (Biome) (Object) this; if (biome != Biomes.NETHER_NETHER) {
if (BetterWithAquatic.isEnableDrowned()) {
0
2023-11-08 23:02:14+00:00
12k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/datafix/db/DBUpdate107.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import org.by1337.bauction.Main; import org.by1337.bauction.serialize.FileUtil; import org.by1337.bauction.serialize.SerializableToByteArray; import org.by1337.bauction.serialize.SerializeUtils; import org.by1337.bauction.util.TimeCounter; import java.io.*; import java.lang.reflect.Type; import java.util.*;
8,974
package org.by1337.bauction.datafix.db; public class DBUpdate107 { // обновляет файлы сохранения с версий 1.0.4-b до 1.0.6.2-b (включительно) на новый формат принятый начиная с версии 1.0.7-b public void update() throws IOException { Main.getMessage().logger("Loading items v1.0.4..."); List<JsonObject> items = load("sellItems", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/sellItems").delete(); FileUtil.deleteFileInDataFolderIfExist("sellItems"); List<JsonObject> users = load("users", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/users").delete(); FileUtil.deleteFileInDataFolderIfExist("users"); List<JsonObject> unsoldItems = load("unsoldItems", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/unsoldItems").delete(); FileUtil.deleteFileInDataFolderIfExist("unsoldItems"); Main.getMessage().logger("loaded %s sell items, %s users and %s unsold items", items.size(), users.size(), unsoldItems.size()); File home = new File(Main.getInstance().getDataFolder() + "/data"); if (!home.exists()) { home.mkdir(); } File fItems = FileUtil.createNewInDataFolderIfNotExist("data/items.bauc"); File fUsers = FileUtil.createNewInDataFolderIfNotExist("data/users.bauc"); File fUnsoldItems = FileUtil.createNewInDataFolderIfNotExist("data/unsoldItems.bauc"); TimeCounter timeCounter = new TimeCounter(); if (!items.isEmpty()) { FileUtil.write(fItems, items.stream().map(jsonObject -> (SerializableToByteArray) () -> getSellItemBytes(jsonObject)).toList()); } if (!users.isEmpty()) { FileUtil.write(fUsers, users.stream().map(jsonObject -> (SerializableToByteArray) () -> getUserBytes(jsonObject)).toList()); } if (!unsoldItems.isEmpty()) { FileUtil.write(fUnsoldItems, unsoldItems.stream().map(jsonObject -> (SerializableToByteArray) () -> getUnsoldItemBytes(jsonObject)).toList()); } Main.getMessage().logger( "updated %s sell items, %s users and %s unsold items in %s ms.", items.size(), users.size(), items.size(), timeCounter.getTime() ); } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getUserBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("nickName").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("uuid").getAsString()); data.writeInt(jsonObject.getAsJsonPrimitive("dealCount").getAsInt()); data.writeDouble(jsonObject.getAsJsonPrimitive("dealSum").getAsDouble()); data.flush(); return out.toByteArray(); } } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getUnsoldItemBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("item").getAsString()); data.writeLong(jsonObject.getAsJsonPrimitive("expired").getAsLong()); data.writeUTF(jsonObject.getAsJsonPrimitive("owner").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("uuid").getAsString()); data.writeInt(-1); data.writeLong(-1); data.writeLong(jsonObject.getAsJsonPrimitive("deleteVia").getAsLong()); data.flush(); return out.toByteArray(); } } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getSellItemBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("item").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("sellerName").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("sellerUuid").getAsString()); data.writeDouble(jsonObject.getAsJsonPrimitive("price").getAsDouble()); data.writeBoolean(jsonObject.getAsJsonPrimitive("saleByThePiece").getAsBoolean());
package org.by1337.bauction.datafix.db; public class DBUpdate107 { // обновляет файлы сохранения с версий 1.0.4-b до 1.0.6.2-b (включительно) на новый формат принятый начиная с версии 1.0.7-b public void update() throws IOException { Main.getMessage().logger("Loading items v1.0.4..."); List<JsonObject> items = load("sellItems", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/sellItems").delete(); FileUtil.deleteFileInDataFolderIfExist("sellItems"); List<JsonObject> users = load("users", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/users").delete(); FileUtil.deleteFileInDataFolderIfExist("users"); List<JsonObject> unsoldItems = load("unsoldItems", new TypeToken<List<JsonObject>>() { }.getType()); new File(Main.getInstance().getDataFolder() + "/unsoldItems").delete(); FileUtil.deleteFileInDataFolderIfExist("unsoldItems"); Main.getMessage().logger("loaded %s sell items, %s users and %s unsold items", items.size(), users.size(), unsoldItems.size()); File home = new File(Main.getInstance().getDataFolder() + "/data"); if (!home.exists()) { home.mkdir(); } File fItems = FileUtil.createNewInDataFolderIfNotExist("data/items.bauc"); File fUsers = FileUtil.createNewInDataFolderIfNotExist("data/users.bauc"); File fUnsoldItems = FileUtil.createNewInDataFolderIfNotExist("data/unsoldItems.bauc"); TimeCounter timeCounter = new TimeCounter(); if (!items.isEmpty()) { FileUtil.write(fItems, items.stream().map(jsonObject -> (SerializableToByteArray) () -> getSellItemBytes(jsonObject)).toList()); } if (!users.isEmpty()) { FileUtil.write(fUsers, users.stream().map(jsonObject -> (SerializableToByteArray) () -> getUserBytes(jsonObject)).toList()); } if (!unsoldItems.isEmpty()) { FileUtil.write(fUnsoldItems, unsoldItems.stream().map(jsonObject -> (SerializableToByteArray) () -> getUnsoldItemBytes(jsonObject)).toList()); } Main.getMessage().logger( "updated %s sell items, %s users and %s unsold items in %s ms.", items.size(), users.size(), items.size(), timeCounter.getTime() ); } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getUserBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("nickName").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("uuid").getAsString()); data.writeInt(jsonObject.getAsJsonPrimitive("dealCount").getAsInt()); data.writeDouble(jsonObject.getAsJsonPrimitive("dealSum").getAsDouble()); data.flush(); return out.toByteArray(); } } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getUnsoldItemBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("item").getAsString()); data.writeLong(jsonObject.getAsJsonPrimitive("expired").getAsLong()); data.writeUTF(jsonObject.getAsJsonPrimitive("owner").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("uuid").getAsString()); data.writeInt(-1); data.writeLong(-1); data.writeLong(jsonObject.getAsJsonPrimitive("deleteVia").getAsLong()); data.flush(); return out.toByteArray(); } } // извлекает данные из json объекта и перегоняет их в байты для сохранения по формату сохранения версии 1.0.7-b private byte[] getSellItemBytes(JsonObject jsonObject) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(jsonObject.getAsJsonPrimitive("item").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("sellerName").getAsString()); data.writeUTF(jsonObject.getAsJsonPrimitive("sellerUuid").getAsString()); data.writeDouble(jsonObject.getAsJsonPrimitive("price").getAsDouble()); data.writeBoolean(jsonObject.getAsJsonPrimitive("saleByThePiece").getAsBoolean());
SerializeUtils.writeCollectionToStream(data,
3
2023-11-08 18:25:18+00:00
12k
Svydovets-Bobocode-Java-Ultimate-3-0/Bring
src/test/java/com/bobocode/svydovets/ioc/core/beanDefinitionFactory/BeanDefinitionFactoryTest.java
[ { "identifier": "ValidConstructorInjectionService", "path": "src/test/java/com/bobocode/svydovets/source/autowire/constructor/ValidConstructorInjectionService.java", "snippet": "@Component\npublic class ValidConstructorInjectionService {\n\n private final FirstInjectionCandidate firstInjectionCandida...
import com.bobocode.svydovets.source.autowire.constructor.ValidConstructorInjectionService; import com.bobocode.svydovets.source.autowire.constructor.InvalidConstructorInjectionService; import com.bobocode.svydovets.source.autowire.constructor.FirstInjectionCandidate; import com.bobocode.svydovets.source.autowire.method.CopyService; import com.bobocode.svydovets.source.autowire.method.PrintLnService; import com.bobocode.svydovets.source.autowire.method.TrimService; import com.bobocode.svydovets.source.base.CommonService; import com.bobocode.svydovets.source.base.MessageService; import com.bobocode.svydovets.source.config.BasePackageBeansConfig; import com.bobocode.svydovets.source.config.BasePackageWithAdditionalBeansConfig; import com.bobocode.svydovets.source.config.ConfigWithThrowScope; import org.junit.jupiter.api.*; import svydovets.core.context.ApplicationContext; import svydovets.core.context.beanDefinition.BeanAnnotationBeanDefinition; import svydovets.core.context.beanDefinition.BeanDefinition; import svydovets.core.context.beanDefinition.BeanDefinitionFactory; import svydovets.core.context.beanDefinition.ComponentAnnotationBeanDefinition; import svydovets.core.exception.BeanDefinitionCreateException; import svydovets.core.exception.UnsupportedScopeException; import svydovets.util.ErrorMessageConstants; import java.util.Set; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertThrows; import static svydovets.util.NameResolver.resolveBeanName;
7,459
package com.bobocode.svydovets.ioc.core.beanDefinitionFactory; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class BeanDefinitionFactoryTest { private BeanDefinitionFactory beanDefinitionFactory; @BeforeEach void setUp() { beanDefinitionFactory = new BeanDefinitionFactory(); } @Test @Order(1) void shouldRegisterComponentAnnotationBeanDefinitions() { beanDefinitionFactory.registerBeanDefinitions(Set.of(CommonService.class, MessageService.class)); BeanDefinition commonServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("commonService"); BeanDefinition messageServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("messageService"); assertThat(commonServiceBeanDefinition).isNotNull(); assertThat(messageServiceBeanDefinition).isNotNull(); assertThat(commonServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); assertThat(messageServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(2) void shouldRegisterConfigClassesAsComponentAnnotationBeanDefinitions() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageBeansConfig.class, BasePackageWithAdditionalBeansConfig.class)); BeanDefinition basePackageBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("basePackageBeansConfig"); BeanDefinition baseAdditionalPackageBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("basePackageWithAdditionalBeansConfig"); assertThat(basePackageBeanDefinition).isNotNull(); assertThat(baseAdditionalPackageBeanDefinition).isNotNull(); assertThat(basePackageBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); assertThat(baseAdditionalPackageBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(3) void shouldRegisterFilledBeanAnnotationSingletonBeanDefinition() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageWithAdditionalBeansConfig.class)); BeanDefinition beanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("copyService"); assertThat(beanDefinition).isNotNull(); assertThat(beanDefinition.getScope()).isEqualTo(ApplicationContext.SCOPE_SINGLETON); assertThat(beanDefinition.getBeanClass()).isEqualTo(CopyService.class); } @Test @Order(4) void shouldRegisterFilledBeanAnnotationPrototypeBeanDefinition() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageWithAdditionalBeansConfig.class)); BeanDefinition beanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("printLnService"); assertThat(beanDefinition).isNotNull(); assertThat(beanDefinition.getScope()).isEqualTo(ApplicationContext.SCOPE_PROTOTYPE); assertThat(beanDefinition.getBeanClass()).isEqualTo(PrintLnService.class); } @Test @Order(5) void shouldThrowUnsupportedScopeExceptionWithNotValidScope() { String errorMessage = String.format(ErrorMessageConstants.UNSUPPORTED_SCOPE_TYPE, "hernya"); assertThatExceptionOfType(UnsupportedScopeException.class) .isThrownBy(() -> beanDefinitionFactory.registerBeanDefinitions(Set.of(ConfigWithThrowScope.class))) .withMessage(errorMessage); } @Test @Order(6) void shouldRegisterComponentAnnotationBeanDefinition() { beanDefinitionFactory.registerBeanDefinition(CommonService.class); BeanDefinition commonServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("commonService"); assertThat(commonServiceBeanDefinition).isNotNull(); assertThat(commonServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(7) void shouldReturnCorrectFilledComponentAnnotationBeanDefinition() { beanDefinitionFactory.registerBeanDefinition(ValidConstructorInjectionService.class); ComponentAnnotationBeanDefinition serviceDefinition = (ComponentAnnotationBeanDefinition) beanDefinitionFactory.getBeanDefinitionByBeanName("validConstructorInjectionService"); assertThat(serviceDefinition).isNotNull(); assertThat(serviceDefinition.getInitializationConstructor()).isNotNull();
package com.bobocode.svydovets.ioc.core.beanDefinitionFactory; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class BeanDefinitionFactoryTest { private BeanDefinitionFactory beanDefinitionFactory; @BeforeEach void setUp() { beanDefinitionFactory = new BeanDefinitionFactory(); } @Test @Order(1) void shouldRegisterComponentAnnotationBeanDefinitions() { beanDefinitionFactory.registerBeanDefinitions(Set.of(CommonService.class, MessageService.class)); BeanDefinition commonServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("commonService"); BeanDefinition messageServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("messageService"); assertThat(commonServiceBeanDefinition).isNotNull(); assertThat(messageServiceBeanDefinition).isNotNull(); assertThat(commonServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); assertThat(messageServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(2) void shouldRegisterConfigClassesAsComponentAnnotationBeanDefinitions() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageBeansConfig.class, BasePackageWithAdditionalBeansConfig.class)); BeanDefinition basePackageBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("basePackageBeansConfig"); BeanDefinition baseAdditionalPackageBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("basePackageWithAdditionalBeansConfig"); assertThat(basePackageBeanDefinition).isNotNull(); assertThat(baseAdditionalPackageBeanDefinition).isNotNull(); assertThat(basePackageBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); assertThat(baseAdditionalPackageBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(3) void shouldRegisterFilledBeanAnnotationSingletonBeanDefinition() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageWithAdditionalBeansConfig.class)); BeanDefinition beanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("copyService"); assertThat(beanDefinition).isNotNull(); assertThat(beanDefinition.getScope()).isEqualTo(ApplicationContext.SCOPE_SINGLETON); assertThat(beanDefinition.getBeanClass()).isEqualTo(CopyService.class); } @Test @Order(4) void shouldRegisterFilledBeanAnnotationPrototypeBeanDefinition() { beanDefinitionFactory.registerBeanDefinitions(Set.of(BasePackageWithAdditionalBeansConfig.class)); BeanDefinition beanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("printLnService"); assertThat(beanDefinition).isNotNull(); assertThat(beanDefinition.getScope()).isEqualTo(ApplicationContext.SCOPE_PROTOTYPE); assertThat(beanDefinition.getBeanClass()).isEqualTo(PrintLnService.class); } @Test @Order(5) void shouldThrowUnsupportedScopeExceptionWithNotValidScope() { String errorMessage = String.format(ErrorMessageConstants.UNSUPPORTED_SCOPE_TYPE, "hernya"); assertThatExceptionOfType(UnsupportedScopeException.class) .isThrownBy(() -> beanDefinitionFactory.registerBeanDefinitions(Set.of(ConfigWithThrowScope.class))) .withMessage(errorMessage); } @Test @Order(6) void shouldRegisterComponentAnnotationBeanDefinition() { beanDefinitionFactory.registerBeanDefinition(CommonService.class); BeanDefinition commonServiceBeanDefinition = beanDefinitionFactory.getBeanDefinitionByBeanName("commonService"); assertThat(commonServiceBeanDefinition).isNotNull(); assertThat(commonServiceBeanDefinition.getClass()).isEqualTo(ComponentAnnotationBeanDefinition.class); } @Test @Order(7) void shouldReturnCorrectFilledComponentAnnotationBeanDefinition() { beanDefinitionFactory.registerBeanDefinition(ValidConstructorInjectionService.class); ComponentAnnotationBeanDefinition serviceDefinition = (ComponentAnnotationBeanDefinition) beanDefinitionFactory.getBeanDefinitionByBeanName("validConstructorInjectionService"); assertThat(serviceDefinition).isNotNull(); assertThat(serviceDefinition.getInitializationConstructor()).isNotNull();
assertThat(serviceDefinition.getInitializationConstructor().getParameterTypes()[0]).isEqualTo(FirstInjectionCandidate.class);
2
2023-11-07 06:36:50+00:00
12k
oneqxz/RiseLoader
src/main/java/me/oneqxz/riseloader/RiseUI.java
[ { "identifier": "Elua", "path": "src/main/java/me/oneqxz/riseloader/elua/Elua.java", "snippet": "public class Elua {\n\n private static Elua elua;\n private File eluaFile;\n\n private Elua()\n {\n eluaFile = new File(OSUtils.getRiseFolder().toFile(), \"elua\");\n }\n\n\n public ...
import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.text.Font; import javafx.stage.Stage; import me.oneqxz.riseloader.elua.Elua; import me.oneqxz.riseloader.fxml.components.impl.EluaAccept; import me.oneqxz.riseloader.fxml.components.impl.ErrorBox; import me.oneqxz.riseloader.fxml.components.impl.Loading; import me.oneqxz.riseloader.fxml.components.impl.Updater; import me.oneqxz.riseloader.fxml.rpc.DiscordRichPresence; import me.oneqxz.riseloader.fxml.scenes.MainScene; import me.oneqxz.riseloader.rise.ClientInfo; import me.oneqxz.riseloader.rise.RiseInfo; import me.oneqxz.riseloader.rise.pub.PublicInstance; import me.oneqxz.riseloader.rise.startup.IStartCommand; import me.oneqxz.riseloader.rise.versions.PublicBeta; import me.oneqxz.riseloader.rise.versions.Release; import me.oneqxz.riseloader.settings.Settings; import me.oneqxz.riseloader.utils.OSUtils; import me.oneqxz.riseloader.utils.Version; import me.oneqxz.riseloader.utils.requests.Requests; import me.oneqxz.riseloader.utils.requests.Response; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.io.File; import java.io.IOException;
7,400
package me.oneqxz.riseloader; public class RiseUI extends Application { private static final Logger log = LogManager.getLogger("RiseLoader"); public static final Version version = new Version("1.0.8"); public static final String serverIp = "http://riseloader.0x22.xyz"; public static final SimpleObjectProperty<Image> backgroundImage = new SimpleObjectProperty<Image>(); @Override public void start(Stage stage) throws IOException { loadBackgroundImage();
package me.oneqxz.riseloader; public class RiseUI extends Application { private static final Logger log = LogManager.getLogger("RiseLoader"); public static final Version version = new Version("1.0.8"); public static final String serverIp = "http://riseloader.0x22.xyz"; public static final SimpleObjectProperty<Image> backgroundImage = new SimpleObjectProperty<Image>(); @Override public void start(Stage stage) throws IOException { loadBackgroundImage();
if(!Elua.getElua().isEluaAccepted())
0
2023-11-01 01:40:52+00:00
12k
YufiriaMazenta/CrypticLib
common/src/main/java/crypticlib/BukkitPlugin.java
[ { "identifier": "AnnotationProcessor", "path": "common/src/main/java/crypticlib/annotation/AnnotationProcessor.java", "snippet": "public enum AnnotationProcessor {\n\n INSTANCE;\n\n private final Map<Class<?>, Object> singletonObjectMap;\n private final Map<Class<? extends Annotation>, BiConsum...
import crypticlib.annotation.AnnotationProcessor; import crypticlib.chat.LangConfigContainer; import crypticlib.chat.LangConfigHandler; import crypticlib.chat.MessageSender; import crypticlib.command.BukkitCommand; import crypticlib.command.CommandInfo; import crypticlib.command.CommandManager; import crypticlib.config.ConfigContainer; import crypticlib.config.ConfigHandler; import crypticlib.config.ConfigWrapper; import crypticlib.listener.BukkitListener; import crypticlib.perm.PermissionManager; import org.bukkit.Bukkit; import org.bukkit.command.TabExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
7,421
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>(); protected final Map<String, LangConfigContainer> langConfigContainerMap = new ConcurrentHashMap<>(); private final String defaultConfigFileName = "config.yml"; private Integer lowestSupportVersion = 11200; private Integer highestSupportVersion = 12004; protected BukkitPlugin() { super(); } @Override public final void onLoad() {
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>(); protected final Map<String, LangConfigContainer> langConfigContainerMap = new ConcurrentHashMap<>(); private final String defaultConfigFileName = "config.yml"; private Integer lowestSupportVersion = 11200; private Integer highestSupportVersion = 12004; protected BukkitPlugin() { super(); } @Override public final void onLoad() {
AnnotationProcessor annotationProcessor = AnnotationProcessor.INSTANCE;
0
2023-11-07 12:39:20+00:00
12k
Traben-0/resource_explorer
common/src/main/java/traben/resource_explorer/REConfig.java
[ { "identifier": "REExplorer", "path": "common/src/main/java/traben/resource_explorer/explorer/REExplorer.java", "snippet": "public class REExplorer {\n public static final Identifier ICON_FILE_BUILT = new Identifier(\"resource_explorer:textures/file_built.png\");\n public static final Identifier I...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ButtonTextures; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.TexturedButtonWidget; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import traben.resource_explorer.explorer.REExplorer; import traben.resource_explorer.explorer.REExplorerScreen; import traben.resource_explorer.explorer.REResourceFile; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Objects; import java.util.function.Predicate; import static traben.resource_explorer.ResourceExplorerClient.MOD_ID;
8,164
package traben.resource_explorer; public class REConfig { private static REConfig instance; public boolean showResourcePackButton = true; public boolean logFullFileTree = false; public boolean addCauseToReloadFailureToast = true; public REFileFilter filterMode = REFileFilter.ALL_RESOURCES; private REConfig() { } public static REConfig getInstance() { if (instance == null) { loadConfig(); } return instance; } public static void setInstance(REConfig newInstance) { instance = newInstance; saveConfig(); } public static void loadConfig() { try { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (config.exists()) { try { FileReader fileReader = new FileReader(config); instance = gson.fromJson(fileReader, REConfig.class); fileReader.close(); saveConfig(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be loaded, using defaults"); } } else { instance = new REConfig(); saveConfig(); } if (instance == null) { instance = new REConfig(); saveConfig(); } } catch (Exception e) { instance = new REConfig(); } } public static void saveConfig() { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (!config.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored config.getParentFile().mkdirs(); } try { FileWriter fileWriter = new FileWriter(config); fileWriter.write(gson.toJson(instance)); fileWriter.close(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be saved"); } } public REConfig copy() { REConfig newConfig = new REConfig(); newConfig.showResourcePackButton = showResourcePackButton; newConfig.filterMode = filterMode; newConfig.logFullFileTree = logFullFileTree; newConfig.addCauseToReloadFailureToast = addCauseToReloadFailureToast; return newConfig; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; REConfig reConfig = (REConfig) o; return showResourcePackButton == reConfig.showResourcePackButton && logFullFileTree == reConfig.logFullFileTree && filterMode == reConfig.filterMode && addCauseToReloadFailureToast == reConfig.addCauseToReloadFailureToast; } @Override public int hashCode() { return Objects.hash(showResourcePackButton, logFullFileTree, filterMode, addCauseToReloadFailureToast); } public enum REFileFilter {
package traben.resource_explorer; public class REConfig { private static REConfig instance; public boolean showResourcePackButton = true; public boolean logFullFileTree = false; public boolean addCauseToReloadFailureToast = true; public REFileFilter filterMode = REFileFilter.ALL_RESOURCES; private REConfig() { } public static REConfig getInstance() { if (instance == null) { loadConfig(); } return instance; } public static void setInstance(REConfig newInstance) { instance = newInstance; saveConfig(); } public static void loadConfig() { try { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (config.exists()) { try { FileReader fileReader = new FileReader(config); instance = gson.fromJson(fileReader, REConfig.class); fileReader.close(); saveConfig(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be loaded, using defaults"); } } else { instance = new REConfig(); saveConfig(); } if (instance == null) { instance = new REConfig(); saveConfig(); } } catch (Exception e) { instance = new REConfig(); } } public static void saveConfig() { File config = new File(REVersionDifferenceManager.getConfigDirectory().toFile(), "resource_explorer.json"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (!config.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored config.getParentFile().mkdirs(); } try { FileWriter fileWriter = new FileWriter(config); fileWriter.write(gson.toJson(instance)); fileWriter.close(); } catch (IOException e) { ResourceExplorerClient.logError("Config could not be saved"); } } public REConfig copy() { REConfig newConfig = new REConfig(); newConfig.showResourcePackButton = showResourcePackButton; newConfig.filterMode = filterMode; newConfig.logFullFileTree = logFullFileTree; newConfig.addCauseToReloadFailureToast = addCauseToReloadFailureToast; return newConfig; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; REConfig reConfig = (REConfig) o; return showResourcePackButton == reConfig.showResourcePackButton && logFullFileTree == reConfig.logFullFileTree && filterMode == reConfig.filterMode && addCauseToReloadFailureToast == reConfig.addCauseToReloadFailureToast; } @Override public int hashCode() { return Objects.hash(showResourcePackButton, logFullFileTree, filterMode, addCauseToReloadFailureToast); } public enum REFileFilter {
ALL_RESOURCES(MOD_ID + ".filter.0",
3
2023-11-05 17:35:39+00:00
12k
txline0420/nacos-dm
config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceProperties.java
[ { "identifier": "Preconditions", "path": "common/src/main/java/com/alibaba/nacos/common/utils/Preconditions.java", "snippet": "public class Preconditions {\n\n private Preconditions() {\n }\n\n /**\n * check precondition.\n * @param expression a boolean expression\n * @param errorMe...
import com.alibaba.nacos.common.utils.Preconditions; import com.alibaba.nacos.common.utils.StringUtils; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.collections.CollectionUtils; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.Environment; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.alibaba.nacos.common.utils.CollectionUtils.getOrDefault;
8,884
/* * Copyright 1999-2018 Alibaba Group Holding 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.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this));
/* * Copyright 1999-2018 Alibaba Group Holding 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.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this));
Preconditions.checkArgument(Objects.nonNull(num), "db.num is null");
0
2023-11-02 01:34:09+00:00
12k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \...
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,596
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired
AttendceDao attenceDao;
1
2023-11-03 02:08:22+00:00
12k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/actions/JarMergeAction.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.jarmanager.JarManager; import com.hypherionmc.jarrelocator.Relocation; import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.utils.FileTools; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.Deflater; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.logger; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.utils.FileTools.*;
10,663
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory"); FileTools.createOrReCreate(tempDir); // Check if the required input files exists if (forgeInput == null && fabricInput == null && quiltInput == null && customInputs.isEmpty()) { throw new IllegalArgumentException("No input jars were provided."); } if (modFusionerExtension.getForgeConfiguration() != null && !FileTools.exists(forgeInput)) { logger.warn("Forge jar does not exist! You can ignore this warning if you are not using forge"); } if (modFusionerExtension.getFabricConfiguration() != null && !FileTools.exists(fabricInput)) { logger.warn("Fabric jar does not exist! You can ignore this warning if you are not using fabric"); } if (modFusionerExtension.getQuiltConfiguration() != null && !FileTools.exists(quiltInput)) { logger.warn("Quilt jar does not exist! You can ignore this warning if you are not using quilt"); } customInputs.forEach((key, value) -> { if (!FileTools.exists(value)) { logger.warn(key.getProjectName() + " jar does not exist! You can ignore this if you are not using custom configurations"); } }); // Remap the jar files to match their platform name remapJars(); // Create the temporary processing directories File fabricTemp = FileTools.getOrCreate(new File(tempDir, "fabric-temp")); File forgeTemp = FileTools.getOrCreate(new File(tempDir, "forge-temp")); File quiltTemp = FileTools.getOrCreate(new File(tempDir, "quilt-temp")); customTemps = new HashMap<>(); customInputs.forEach((key, value) -> { Map<File, File> temp = new HashMap<>(); temp.put(value, new File(tempDir, key.getProjectName() + "-temp")); FileTools.getOrCreate(new File(tempDir, key.getProjectName() + "-temp")); customTemps.put(key, temp); }); // Extract the input jars to their processing directories logger.lifecycle("Unpacking input jars"); if (FileTools.exists(forgeInput)) { jarManager.unpackJar(forgeInput, forgeTemp); } if (FileTools.exists(fabricInput)) { jarManager.unpackJar(fabricInput, fabricTemp); } if (FileTools.exists(quiltInput)) { jarManager.unpackJar(quiltInput, quiltTemp); } customTemps.forEach((key, value) -> value.forEach((k, v) -> { if (FileTools.exists(k)) { try { jarManager.unpackJar(k, v); } catch (IOException e) { throw new RuntimeException(e); } } })); File mergedTemp = FileTools.getOrCreate(new File(tempDir, "merged-temp")); processManifests(mergedTemp, forgeTemp, fabricTemp, quiltTemp); FileTools.moveDirectory(forgeTemp, mergedTemp); FileTools.moveDirectory(fabricTemp, mergedTemp); FileTools.moveDirectory(quiltTemp, mergedTemp); for (Map.Entry<FusionerExtension.CustomConfiguration, Map<File, File>> entry : customTemps.entrySet()) { for (Map.Entry<File, File> entry2 : entry.getValue().entrySet()) { FileTools.moveDirectory(entry2.getValue(), mergedTemp); } } // Process duplicate packages and resources logger.lifecycle("Processing duplicate packages and resources"); processDuplicatePackages(); removeDuplicatePackages(mergedTemp); removeDuplicateResources(mergedTemp); // Clean the output jar if it exists FileUtils.deleteQuietly(outJar); // Repack the fully processed jars into a single jar logger.lifecycle("Fusing jars into single jar"); jarManager.remapAndPack(mergedTemp, outJar, relocations); try {
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory"); FileTools.createOrReCreate(tempDir); // Check if the required input files exists if (forgeInput == null && fabricInput == null && quiltInput == null && customInputs.isEmpty()) { throw new IllegalArgumentException("No input jars were provided."); } if (modFusionerExtension.getForgeConfiguration() != null && !FileTools.exists(forgeInput)) { logger.warn("Forge jar does not exist! You can ignore this warning if you are not using forge"); } if (modFusionerExtension.getFabricConfiguration() != null && !FileTools.exists(fabricInput)) { logger.warn("Fabric jar does not exist! You can ignore this warning if you are not using fabric"); } if (modFusionerExtension.getQuiltConfiguration() != null && !FileTools.exists(quiltInput)) { logger.warn("Quilt jar does not exist! You can ignore this warning if you are not using quilt"); } customInputs.forEach((key, value) -> { if (!FileTools.exists(value)) { logger.warn(key.getProjectName() + " jar does not exist! You can ignore this if you are not using custom configurations"); } }); // Remap the jar files to match their platform name remapJars(); // Create the temporary processing directories File fabricTemp = FileTools.getOrCreate(new File(tempDir, "fabric-temp")); File forgeTemp = FileTools.getOrCreate(new File(tempDir, "forge-temp")); File quiltTemp = FileTools.getOrCreate(new File(tempDir, "quilt-temp")); customTemps = new HashMap<>(); customInputs.forEach((key, value) -> { Map<File, File> temp = new HashMap<>(); temp.put(value, new File(tempDir, key.getProjectName() + "-temp")); FileTools.getOrCreate(new File(tempDir, key.getProjectName() + "-temp")); customTemps.put(key, temp); }); // Extract the input jars to their processing directories logger.lifecycle("Unpacking input jars"); if (FileTools.exists(forgeInput)) { jarManager.unpackJar(forgeInput, forgeTemp); } if (FileTools.exists(fabricInput)) { jarManager.unpackJar(fabricInput, fabricTemp); } if (FileTools.exists(quiltInput)) { jarManager.unpackJar(quiltInput, quiltTemp); } customTemps.forEach((key, value) -> value.forEach((k, v) -> { if (FileTools.exists(k)) { try { jarManager.unpackJar(k, v); } catch (IOException e) { throw new RuntimeException(e); } } })); File mergedTemp = FileTools.getOrCreate(new File(tempDir, "merged-temp")); processManifests(mergedTemp, forgeTemp, fabricTemp, quiltTemp); FileTools.moveDirectory(forgeTemp, mergedTemp); FileTools.moveDirectory(fabricTemp, mergedTemp); FileTools.moveDirectory(quiltTemp, mergedTemp); for (Map.Entry<FusionerExtension.CustomConfiguration, Map<File, File>> entry : customTemps.entrySet()) { for (Map.Entry<File, File> entry2 : entry.getValue().entrySet()) { FileTools.moveDirectory(entry2.getValue(), mergedTemp); } } // Process duplicate packages and resources logger.lifecycle("Processing duplicate packages and resources"); processDuplicatePackages(); removeDuplicatePackages(mergedTemp); removeDuplicateResources(mergedTemp); // Clean the output jar if it exists FileUtils.deleteQuietly(outJar); // Repack the fully processed jars into a single jar logger.lifecycle("Fusing jars into single jar"); jarManager.remapAndPack(mergedTemp, outJar, relocations); try {
Files.setPosixFilePermissions(outJar.toPath(), Constants.filePerms);
0
2023-11-03 23:19:08+00:00
12k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/app/model/DevAiChatDialogue.java
[ { "identifier": "SysDept", "path": "application-webadmin/src/main/java/supie/webadmin/upms/model/SysDept.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(value = \"sdt_sys_dept\")\npublic class SysDept extends BaseModel {\n\n /**\n * 测试字段。\n */\n private Long mark...
import com.baomidou.mybatisplus.annotation.*; import supie.webadmin.upms.model.SysDept; import supie.webadmin.upms.model.SysUser; import supie.common.core.util.MyCommonUtil; import supie.common.core.annotation.*; import supie.common.core.base.model.BaseModel; import supie.common.core.base.mapper.BaseModelMapper; import supie.webadmin.app.vo.DevAiChatDialogueVo; import lombok.Data; import lombok.EqualsAndHashCode; import org.mapstruct.*; import org.mapstruct.factory.Mappers; import java.util.Map;
8,199
package supie.webadmin.app.model; /** * DevAiChatDialogue实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_dev_ai_chat_dialogue") public class DevAiChatDialogue extends BaseModel { /** * 主表控制台id。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 对话名称。 */ private String dialogueName; /** * 对话问题。 */ private String dialogueQuestion; /** * 相应答案。 */ private String dialogueAnswer; /** * 问答类型:对话、工具调用、代码执行。 */ private String dialogueType; /** * 数据应用类型:数据探源、生成图表、归因总结等等。 */ private String dialogueDataType; /** * 问答角色。 */ private String dialogueRole; /** * 问答预设提示语。 */ private String dialoguePrompt; /** * 对话标识ID。 */ private String dialogueStrId; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * dialogue_name / dialogue_question / dialogue_answer LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } @RelationDict( masterIdField = "createUserId",
package supie.webadmin.app.model; /** * DevAiChatDialogue实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_dev_ai_chat_dialogue") public class DevAiChatDialogue extends BaseModel { /** * 主表控制台id。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 对话名称。 */ private String dialogueName; /** * 对话问题。 */ private String dialogueQuestion; /** * 相应答案。 */ private String dialogueAnswer; /** * 问答类型:对话、工具调用、代码执行。 */ private String dialogueType; /** * 数据应用类型:数据探源、生成图表、归因总结等等。 */ private String dialogueDataType; /** * 问答角色。 */ private String dialogueRole; /** * 问答预设提示语。 */ private String dialoguePrompt; /** * 对话标识ID。 */ private String dialogueStrId; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * dialogue_name / dialogue_question / dialogue_answer LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } @RelationDict( masterIdField = "createUserId",
slaveModelClass = SysUser.class,
1
2023-11-04 12:36:44+00:00
12k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
10,725
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1;
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1;
private TrajectorySequenceRunner trajectorySequenceRunner;
2
2023-11-03 13:32:48+00:00
12k
beminder/BeautyMinder
java/src/main/java/app/beautyminder/controller/chat/StompController.java
[ { "identifier": "ChatLog", "path": "java/src/main/java/app/beautyminder/domain/ChatLog.java", "snippet": "@Document(collection = \"chats\")\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PUBLIC)\n@Getter\n@Setter\npublic class ChatLog {\n\n @Id\n private String id;\n\n private St...
import app.beautyminder.domain.ChatLog; import app.beautyminder.domain.Cosmetic; import app.beautyminder.domain.Review; import app.beautyminder.dto.chat.ChatMessage; import app.beautyminder.dto.chat.ChatRoom; import app.beautyminder.repository.ChatLogRepository; import app.beautyminder.service.chat.ChatService; import app.beautyminder.service.chat.WebSocketSessionManager; import app.beautyminder.service.cosmetic.GPTService; import app.beautyminder.service.review.ReviewService; import com.fasterxml.jackson.databind.ObjectMapper; import com.vane.badwordfiltering.BadWordFiltering; import jakarta.annotation.PreDestroy; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Controller; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors;
9,894
public ChatMessage enterRoom(@DestinationVariable String roomId, @Payload String messageJson) throws Exception { ChatMessage chatMessage = objectMapper.readValue(messageJson, ChatMessage.class); chatMessage.setMessage(chatMessage.getSender() + " 님이 입장 하셨습니다."); chatService.userEnteredRoom(roomId); addToDatabase(roomId, chatMessage); messagingTemplate.convertAndSend("/topic/room/name/" + roomId, Map.of("title", chatService.getRoomUserCount(roomId))); messagingTemplate.convertAndSend("/topic/room/currentUsers", getCurrentUsers()); return chatMessage; } @MessageMapping("/chat.quit/{roomId}") @SendTo("/topic/room/{roomId}") public ChatMessage quitRoom(@DestinationVariable String roomId, @Payload String messageJson, SimpMessageHeaderAccessor accessor) throws Exception { ChatMessage chatMessage = objectMapper.readValue(messageJson, ChatMessage.class); // chatService.sendMessageToRoom(roomId, chatMessage); chatMessage.setMessage(chatMessage.getSender() + " 님이 퇴장 하셨습니다."); chatService.userLeftRoom(roomId); addToDatabase(roomId, chatMessage); // double check sessionManager.removeSession(accessor.getSessionId()); messagingTemplate.convertAndSend("/topic/room/name/" + roomId, Map.of("title", chatService.getRoomUserCount(roomId))); messagingTemplate.convertAndSend("/topic/room/currentUsers", getCurrentUsers()); return chatMessage; } @Scheduled(cron = "*/30 * * * * *") // sends recommended product every 30 seconds public void sendProductToWhole() { chatService.findAllRoom().stream() .filter(this::isEligibleForProductRecommendation) .forEach(this::processRoomAndStoreFuture); } @Scheduled(cron = "*/30 * * * * *") public void processGPTnotice() { chatService.findAllRoom().stream() .filter(this::isEligibleForGPTNotice) .forEach(this::processGPTAndStoreFuture); } @Async public CompletableFuture<Void> processGPT(ChatRoom room) { try { var chatMessage = new ChatMessage(); chatMessage.setType(ChatMessage.MessageType.NOTICE); // Extract the first four characters or the entire string if it's shorter than four characters var roomName = room.getName(); var shortName = roomName.length() > 4 ? roomName.substring(0, 4) : roomName; chatMessage.setMessage("[GPT 팁] " + gptService.generateNotice(shortName)); messagingTemplate.convertAndSend("/topic/room/" + room.getRoomId(), chatMessage); return CompletableFuture.completedFuture(null); } catch (Exception e) { // Handle or log the exception return CompletableFuture.failedFuture(e); } } @Async public CompletableFuture<Void> processRoom(ChatRoom room) { try { var chatMessage = new ChatMessage(); chatMessage.setType(ChatMessage.MessageType.NOTICE); // Extract the first four characters or the entire string if it's shorter than four characters var roomName = room.getName(); var shortName = roomName.length() > 4 ? roomName.substring(0, 4) : roomName; var cosmetics = getCosmeticIdsByProbability(shortName); if (!cosmetics.isEmpty()) { int randomIndex = random.nextInt(cosmetics.size()); Cosmetic randomCosmetic = cosmetics.get(randomIndex); chatMessage.setMessage("[공지] " + room.getName() + "! 이러한 제품은 어때요? " + randomCosmetic.getName()); messagingTemplate.convertAndSend("/topic/room/" + room.getRoomId(), chatMessage); } return CompletableFuture.completedFuture(null); } catch (Exception e) { // Handle or log the exception return CompletableFuture.failedFuture(e); } } private void cancelFuture(CompletableFuture<Void> future) { if (future != null && !future.isDone()) { future.cancel(true); } } private boolean isEligibleForProductRecommendation(ChatRoom room) { return !room.getName().equals("BeautyMinder") && room.getUserCounts() >= 1; } private boolean isEligibleForGPTNotice(ChatRoom room) { return !room.getName().equals("BeautyMinder") && room.getUserCounts() >= 1; } private void processRoomAndStoreFuture(ChatRoom room) { CompletableFuture<Void> future = processRoom(room); roomFutures.put(room.getRoomId(), future); } private void processGPTAndStoreFuture(ChatRoom room) { CompletableFuture<Void> future = processGPT(room); gptFutures.put(room.getRoomId(), future); } private List<Cosmetic> getCosmeticIdsByProbability(String baumannSkinType) { // Get reviews filtered by the probability scores from the NLP analysis
package app.beautyminder.controller.chat; @Slf4j @Controller @RequiredArgsConstructor public class StompController { private final ChatService chatService; private final ObjectMapper objectMapper; private final SimpMessageSendingOperations messagingTemplate; private final ReviewService reviewService; private final GPTService gptService; private final ChatLogRepository chatLogRepository; private final WebSocketSessionManager sessionManager; private final Random random = new Random(); private final BadWordFiltering badWordFiltering; private final Map<String, CompletableFuture<Void>> roomFutures = new ConcurrentHashMap<>(); private final Map<String, CompletableFuture<Void>> gptFutures = new ConcurrentHashMap<>(); @PreDestroy public void onDestroy() { roomFutures.values().forEach(this::cancelFuture); gptFutures.values().forEach(this::cancelFuture); } public List<String> getCurrentUsers() { ConcurrentHashMap<String, String> userSessionMap = sessionManager.getConnectedUsers(); return new ArrayList<>(userSessionMap.values()); } // SimpMessageHeaderAccessor accessor // enter -> if BM, send to /chat.save -> send back to /topic/room @MessageMapping("/chat.save/{roomId}") public void sendSavedMsg(@DestinationVariable String roomId) { var room = chatService.findRoomById(roomId); var optRoom = chatLogRepository.findByRoomName(room.getName()); optRoom.ifPresent(chatLog -> { if (chatLog.getMessages().size() == 1) { // on first user entered a room for the first time return; } List<ChatMessage> savedChats = chatLog.getMessages().stream().map(message -> ChatMessage.builder() .sender(message.getSender()) .message(message.getContent()) .roomId(roomId) .type(message.getType()) .build() ).collect(Collectors.toList()); messagingTemplate.convertAndSend("/topic/room/batch/" + roomId, savedChats); }); } @MessageMapping("/chat.send/{roomId}") @SendTo("/topic/room/{roomId}") public ChatMessage send(@DestinationVariable String roomId, @Payload String messageJson) throws Exception { ChatMessage chatMessage = objectMapper.readValue(messageJson, ChatMessage.class); // Format the current time in Korean timezone LocalDateTime now = LocalDateTime.now(TimeZone.getTimeZone("Asia/Seoul").toZoneId()); DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("HH:mm"); String fullFormattedDateTime = now.format(fullFormatter); String shortFormattedDateTime = now.format(shortFormatter); // Append the full timestamp for the desktop and the short one for mobile clients chatMessage.setMessage( "<span class=\"timestamp-full\">" + "[" + fullFormattedDateTime + "]" + "</span>" + "<span class=\"timestamp-short\">" + "[" + shortFormattedDateTime + "]" + "</span>" + chatMessage.getSender() + ": " + badWordFiltering.change(chatMessage.getMessage()) ); addToDatabase(roomId, chatMessage); chatService.sendMessageToRoom(roomId, chatMessage); return chatMessage; } @MessageMapping("/chat.enter/{roomId}") @SendTo("/topic/room/{roomId}") public ChatMessage enterRoom(@DestinationVariable String roomId, @Payload String messageJson) throws Exception { ChatMessage chatMessage = objectMapper.readValue(messageJson, ChatMessage.class); chatMessage.setMessage(chatMessage.getSender() + " 님이 입장 하셨습니다."); chatService.userEnteredRoom(roomId); addToDatabase(roomId, chatMessage); messagingTemplate.convertAndSend("/topic/room/name/" + roomId, Map.of("title", chatService.getRoomUserCount(roomId))); messagingTemplate.convertAndSend("/topic/room/currentUsers", getCurrentUsers()); return chatMessage; } @MessageMapping("/chat.quit/{roomId}") @SendTo("/topic/room/{roomId}") public ChatMessage quitRoom(@DestinationVariable String roomId, @Payload String messageJson, SimpMessageHeaderAccessor accessor) throws Exception { ChatMessage chatMessage = objectMapper.readValue(messageJson, ChatMessage.class); // chatService.sendMessageToRoom(roomId, chatMessage); chatMessage.setMessage(chatMessage.getSender() + " 님이 퇴장 하셨습니다."); chatService.userLeftRoom(roomId); addToDatabase(roomId, chatMessage); // double check sessionManager.removeSession(accessor.getSessionId()); messagingTemplate.convertAndSend("/topic/room/name/" + roomId, Map.of("title", chatService.getRoomUserCount(roomId))); messagingTemplate.convertAndSend("/topic/room/currentUsers", getCurrentUsers()); return chatMessage; } @Scheduled(cron = "*/30 * * * * *") // sends recommended product every 30 seconds public void sendProductToWhole() { chatService.findAllRoom().stream() .filter(this::isEligibleForProductRecommendation) .forEach(this::processRoomAndStoreFuture); } @Scheduled(cron = "*/30 * * * * *") public void processGPTnotice() { chatService.findAllRoom().stream() .filter(this::isEligibleForGPTNotice) .forEach(this::processGPTAndStoreFuture); } @Async public CompletableFuture<Void> processGPT(ChatRoom room) { try { var chatMessage = new ChatMessage(); chatMessage.setType(ChatMessage.MessageType.NOTICE); // Extract the first four characters or the entire string if it's shorter than four characters var roomName = room.getName(); var shortName = roomName.length() > 4 ? roomName.substring(0, 4) : roomName; chatMessage.setMessage("[GPT 팁] " + gptService.generateNotice(shortName)); messagingTemplate.convertAndSend("/topic/room/" + room.getRoomId(), chatMessage); return CompletableFuture.completedFuture(null); } catch (Exception e) { // Handle or log the exception return CompletableFuture.failedFuture(e); } } @Async public CompletableFuture<Void> processRoom(ChatRoom room) { try { var chatMessage = new ChatMessage(); chatMessage.setType(ChatMessage.MessageType.NOTICE); // Extract the first four characters or the entire string if it's shorter than four characters var roomName = room.getName(); var shortName = roomName.length() > 4 ? roomName.substring(0, 4) : roomName; var cosmetics = getCosmeticIdsByProbability(shortName); if (!cosmetics.isEmpty()) { int randomIndex = random.nextInt(cosmetics.size()); Cosmetic randomCosmetic = cosmetics.get(randomIndex); chatMessage.setMessage("[공지] " + room.getName() + "! 이러한 제품은 어때요? " + randomCosmetic.getName()); messagingTemplate.convertAndSend("/topic/room/" + room.getRoomId(), chatMessage); } return CompletableFuture.completedFuture(null); } catch (Exception e) { // Handle or log the exception return CompletableFuture.failedFuture(e); } } private void cancelFuture(CompletableFuture<Void> future) { if (future != null && !future.isDone()) { future.cancel(true); } } private boolean isEligibleForProductRecommendation(ChatRoom room) { return !room.getName().equals("BeautyMinder") && room.getUserCounts() >= 1; } private boolean isEligibleForGPTNotice(ChatRoom room) { return !room.getName().equals("BeautyMinder") && room.getUserCounts() >= 1; } private void processRoomAndStoreFuture(ChatRoom room) { CompletableFuture<Void> future = processRoom(room); roomFutures.put(room.getRoomId(), future); } private void processGPTAndStoreFuture(ChatRoom room) { CompletableFuture<Void> future = processGPT(room); gptFutures.put(room.getRoomId(), future); } private List<Cosmetic> getCosmeticIdsByProbability(String baumannSkinType) { // Get reviews filtered by the probability scores from the NLP analysis
List<Review> probablyBaumannReviews = reviewService.getReviewsForRecommendation(3, baumannSkinType);
2
2023-11-01 12:37:16+00:00
12k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/Gizmo.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.sprites.Sprite; import engine.editor.PropertiesWindow; import engine.ruby.KeyListener; import engine.ruby.MouseListener; import engine.scenes.Scene; import engine.util.Prefabs; import org.joml.Vector2f; import org.joml.Vector4f; import static org.lwjgl.glfw.GLFW.GLFW_KEY_N; import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT;
10,551
package engine.components; public class Gizmo extends Component { private final float scale = 120.0f; private final float gizmoWidth = 16.0f / scale, gizmoHeight = 48.0f / scale; private final Vector4f xArrowColor = new Vector4f(1, 0, 0, 1), yArrowColor = new Vector4f(0, 1, 0, 1); private final Vector4f xAxisHoverColor = new Vector4f(0, 0, 1, 1), yAxisHoverColor = new Vector4f(0, 0, 1, 1); private final Vector2f xOffset = new Vector2f(24.0f / scale, -6.0f / scale), yOffset = new Vector2f(-7.0f / scale, 21.0f / scale); private final GameObject xArrow, yArrow; private final PropertiesWindow window; private final SpriteRenderer xArrowRenderer, yArrowRenderer; protected GameObject activeGameObject = null; protected boolean xActive = false, yActive = false, use = false, isSnapping = false; public Gizmo(Scene scene, Sprite sprite, PropertiesWindow window) { this.window = window; xArrow = Prefabs.generateSpriteObject(sprite, gizmoWidth, gizmoHeight); yArrow = Prefabs.generateSpriteObject(sprite, gizmoWidth, gizmoHeight); xArrowRenderer = xArrow.getComponent(SpriteRenderer.class); yArrowRenderer = yArrow.getComponent(SpriteRenderer.class); xArrow.transform.setZIndex(100); yArrow.transform.setZIndex(100); xArrow.addComponent(new NonPickable()); yArrow.addComponent(new NonPickable()); scene.addGameObjectToScene(xArrow); scene.addGameObjectToScene(yArrow); } private void setActiveGameObject(GameObject obj) { activeGameObject = obj; xArrowRenderer.setColor(xArrowColor); yArrowRenderer.setColor(yArrowColor); } private void clearActiveGameObject() { activeGameObject = null; xArrowRenderer.setColor(new Vector4f(0, 0, 0, 0)); yArrowRenderer.setColor(new Vector4f(0, 0, 0, 0)); } @Override public void update(float dt) { if (use) clearActiveGameObject(); xArrow.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); yArrow.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); } @Override public void editorUpdate(float dt) { if (!use) return; activeGameObject = window.getActiveGameObject(); if (activeGameObject != null) { setActiveGameObject(activeGameObject); } else { clearActiveGameObject(); return; } boolean xHover = checkXHoverState(), yHover = checkYHoverState();
package engine.components; public class Gizmo extends Component { private final float scale = 120.0f; private final float gizmoWidth = 16.0f / scale, gizmoHeight = 48.0f / scale; private final Vector4f xArrowColor = new Vector4f(1, 0, 0, 1), yArrowColor = new Vector4f(0, 1, 0, 1); private final Vector4f xAxisHoverColor = new Vector4f(0, 0, 1, 1), yAxisHoverColor = new Vector4f(0, 0, 1, 1); private final Vector2f xOffset = new Vector2f(24.0f / scale, -6.0f / scale), yOffset = new Vector2f(-7.0f / scale, 21.0f / scale); private final GameObject xArrow, yArrow; private final PropertiesWindow window; private final SpriteRenderer xArrowRenderer, yArrowRenderer; protected GameObject activeGameObject = null; protected boolean xActive = false, yActive = false, use = false, isSnapping = false; public Gizmo(Scene scene, Sprite sprite, PropertiesWindow window) { this.window = window; xArrow = Prefabs.generateSpriteObject(sprite, gizmoWidth, gizmoHeight); yArrow = Prefabs.generateSpriteObject(sprite, gizmoWidth, gizmoHeight); xArrowRenderer = xArrow.getComponent(SpriteRenderer.class); yArrowRenderer = yArrow.getComponent(SpriteRenderer.class); xArrow.transform.setZIndex(100); yArrow.transform.setZIndex(100); xArrow.addComponent(new NonPickable()); yArrow.addComponent(new NonPickable()); scene.addGameObjectToScene(xArrow); scene.addGameObjectToScene(yArrow); } private void setActiveGameObject(GameObject obj) { activeGameObject = obj; xArrowRenderer.setColor(xArrowColor); yArrowRenderer.setColor(yArrowColor); } private void clearActiveGameObject() { activeGameObject = null; xArrowRenderer.setColor(new Vector4f(0, 0, 0, 0)); yArrowRenderer.setColor(new Vector4f(0, 0, 0, 0)); } @Override public void update(float dt) { if (use) clearActiveGameObject(); xArrow.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); yArrow.getComponent(SpriteRenderer.class).setColor(new Vector4f(0, 0, 0, 0)); } @Override public void editorUpdate(float dt) { if (!use) return; activeGameObject = window.getActiveGameObject(); if (activeGameObject != null) { setActiveGameObject(activeGameObject); } else { clearActiveGameObject(); return; } boolean xHover = checkXHoverState(), yHover = checkYHoverState();
if ((xHover || xActive) && MouseListener.isDragging() && MouseListener.mouseButtonDown(GLFW_MOUSE_BUTTON_LEFT)) {
3
2023-11-04 13:19:21+00:00
12k
RezaGooner/University-food-ordering
Frames/Profile/NewUserFrame.java
[ { "identifier": "Gender", "path": "Classes/Roles/Gender.java", "snippet": "public enum Gender {\r\n MALE(\"مرد\"),\r\n FEMALE(\"زن\");\r\n\r\n Gender(String label) {\r\n }\r\n}\r" }, { "identifier": "Organization", "path": "Classes/Roles/Organization.java", "snippet": "public...
import java.awt.event.*; import java.io.*; import java.util.Scanner; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Classes.Theme.SoundEffect.successSound; import static Frames.LoginFrame.isNumeric; import static Classes.Pathes.FilesPath.UserPassPath; import Classes.Roles.Gender; import Classes.Roles.Organization; import Classes.Theme.StyledButtonUI; import Frames.LoginFrame; import Frames.Order.BalanceHandler; import javax.swing.*; import java.awt.*;
7,703
new LoginFrame(); } } }); organizationComboBox = new JComboBox<>(Organization.values()); organizationComboBox.setBackground(colorBackground); organizationComboBox.setEnabled(false); JButton registerButton = new JButton("ثبت نام"); registerButton.setUI(new StyledButtonUI()); registerButton.setForeground(Color.white); registerButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(10, 1)); panel.setBackground(colorBackground); panel.add(firstNameLabel); panel.add(firstNameField); panel.add(lastNameLabel); panel.add(lastNameField); panel.add(idLabel); panel.add(idField); panel.add(numberLabel); panel.add(numberField); panel.add(passwordLabel); panel.add(passwordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(genderLabel); panel.add(genderComboBox); panel.add(employeeCheckBox); panel.add(studentCheckBox); panel.add(vipStudentCheckBox); panel.add(organizationComboBox); panel.add(registerButton); panel.add(statusLabel); add(panel); setVisible(true); employeeCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (employeeCheckBox.isSelected()) { studentCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); studentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (studentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); vipStudentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vipStudentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); studentCheckBox.setSelected(false); organizationComboBox.setEnabled(true); } else { organizationComboBox.setEnabled(false); } } }); registerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String firstName = firstNameField.getText(); String lastName = lastNameField.getText(); String id = idField.getText(); Gender gender = (Gender) genderComboBox.getSelectedItem(); String password = new String(passwordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); String number = numberField.getText(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(UserPassPath, true))) { String organizationInput = String.valueOf(organizationComboBox.getSelectedItem()); switch (organizationInput) { case "سایر": organization = "NOT"; break; case "کمیته امام": organization = "KOMITE"; break; case "سازمان بهزیستی": organization = "BEHZISTI"; break; case "دانشجوی ممتاز": organization = "MOMTAZ"; break; } if (isValidRegistration(firstName, lastName, id, password, confirmPassword)) { if (studentCheckBox.isSelected()){ if ( id.startsWith("4") ) { writer.write(id + ',' + password + ',' + firstName + ',' + lastName + ',' + gender + ',' + number + ',' + organization); writer.newLine(); try { successSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "کاربر با موفقیت ثبت شد.");
package Frames.Profile; /* این کلاس برای ایجاد حساب کاربری جدید ساخته شده است در اغاز پنجره ای باز می شود با ورودی های firstNameField , lastNameField , idField , numberField و همچنین genderComboBox , organizationComboBox و گزینه های Student , VIPStudent و Employee . در ورودی های تعریف شده کاربر بایستی نام و نام خانوادگی ، شناسه و همچنین شماره همراه خود را وارد کند شناسه باید ده عددی ده رقمی باشد . همچنین بسته به نوع کاربر با انتخاب هر کدام از checkBox های دانشجو و کارمند و دانشجوی ویژه باید با عددی خاص شروع شود. شماره همراه نیز باید عددی یازده رقمی باشد. در ضمن همه فیلد های ورودی باید پر شوند. کاربر باید جنسیت خود را از genderComboBox انتخاب کرده و اگر تیک بخش VIPStudent را فعال کند بایستی وضعیت خود را در organizationComboBox مشخص کند تا تخفیف های خرید غذا شامل وی شود سپس بعد از وارد کردن و تایید شدن اطلاعات ، داده ها در مسیر فایل مشخص شده ، به صورت جداشده با کاما نوشته میشوند. */ public class NewUserFrame extends JFrame { private final JTextField firstNameField; private final JTextField lastNameField; private final JTextField idField; private final JTextField numberField; private final JComboBox<Gender> genderComboBox; private final JComboBox<Organization> organizationComboBox; private final JCheckBox employeeCheckBox; private final JCheckBox studentCheckBox; private final JCheckBox vipStudentCheckBox; private final JPasswordField passwordField; private final JPasswordField confirmPasswordField; private final JLabel statusLabel; private String organization ; public static Color colorButton = new Color(19,56,190); public static Color colorBackground = new Color(136,226,242); public NewUserFrame() { setTitle("ثبت نام"); setIconImage(icon.getImage()); setSize(400, 350); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); JLabel firstNameLabel = new JLabel(": نام"); firstNameLabel.setHorizontalAlignment(SwingConstants.CENTER); firstNameField = new JTextField(10); JLabel lastNameLabel = new JLabel(": نام خانوادگی"); lastNameLabel.setHorizontalAlignment(SwingConstants.CENTER); lastNameField = new JTextField(10); JLabel idLabel = new JLabel(": شناسه"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel numberLabel = new JLabel(": شماره همراه"); numberLabel.setHorizontalAlignment(SwingConstants.CENTER); numberField = new JTextField(11); JLabel passwordLabel = new JLabel(": رمز عبور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); JLabel confirmPasswordLabel = new JLabel(": تکرار رمز عبور"); confirmPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER); confirmPasswordField = new JPasswordField(10); JLabel genderLabel = new JLabel(": جنسیت"); genderLabel.setHorizontalAlignment(SwingConstants.CENTER); genderComboBox = new JComboBox<>(Gender.values()); genderComboBox.setBackground(colorBackground); employeeCheckBox = new JCheckBox("کارمند"); employeeCheckBox.setBackground(colorBackground); studentCheckBox = new JCheckBox("دانشجو"); studentCheckBox.setBackground(colorBackground); vipStudentCheckBox = new JCheckBox("دانشجوی ویژه"); vipStudentCheckBox.setBackground(colorBackground); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenuItem exitItem = new JMenuItem("بازگشت"); exitItem.setForeground(Color.white); exitItem.setBackground(colorButton); menuBar.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); new LoginFrame(); } } }); organizationComboBox = new JComboBox<>(Organization.values()); organizationComboBox.setBackground(colorBackground); organizationComboBox.setEnabled(false); JButton registerButton = new JButton("ثبت نام"); registerButton.setUI(new StyledButtonUI()); registerButton.setForeground(Color.white); registerButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(10, 1)); panel.setBackground(colorBackground); panel.add(firstNameLabel); panel.add(firstNameField); panel.add(lastNameLabel); panel.add(lastNameField); panel.add(idLabel); panel.add(idField); panel.add(numberLabel); panel.add(numberField); panel.add(passwordLabel); panel.add(passwordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(genderLabel); panel.add(genderComboBox); panel.add(employeeCheckBox); panel.add(studentCheckBox); panel.add(vipStudentCheckBox); panel.add(organizationComboBox); panel.add(registerButton); panel.add(statusLabel); add(panel); setVisible(true); employeeCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (employeeCheckBox.isSelected()) { studentCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); studentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (studentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); vipStudentCheckBox.setSelected(false); organizationComboBox.setSelectedItem(Organization.NOT); organizationComboBox.setEnabled(false); } } }); vipStudentCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (vipStudentCheckBox.isSelected()) { employeeCheckBox.setSelected(false); studentCheckBox.setSelected(false); organizationComboBox.setEnabled(true); } else { organizationComboBox.setEnabled(false); } } }); registerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String firstName = firstNameField.getText(); String lastName = lastNameField.getText(); String id = idField.getText(); Gender gender = (Gender) genderComboBox.getSelectedItem(); String password = new String(passwordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); String number = numberField.getText(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(UserPassPath, true))) { String organizationInput = String.valueOf(organizationComboBox.getSelectedItem()); switch (organizationInput) { case "سایر": organization = "NOT"; break; case "کمیته امام": organization = "KOMITE"; break; case "سازمان بهزیستی": organization = "BEHZISTI"; break; case "دانشجوی ممتاز": organization = "MOMTAZ"; break; } if (isValidRegistration(firstName, lastName, id, password, confirmPassword)) { if (studentCheckBox.isSelected()){ if ( id.startsWith("4") ) { writer.write(id + ',' + password + ',' + firstName + ',' + lastName + ',' + gender + ',' + number + ',' + organization); writer.newLine(); try { successSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "کاربر با موفقیت ثبت شد.");
BalanceHandler.addNewUser(id);
4
2023-11-03 08:35:22+00:00
12k
af19git5/EasyImage
src/main/java/io/github/af19git5/builder/ImageBuilder.java
[ { "identifier": "Image", "path": "src/main/java/io/github/af19git5/entity/Image.java", "snippet": "@Getter\npublic class Image extends Item {\n\n private final BufferedImage bufferedImage;\n\n private int overrideWidth = -1;\n\n private int overrideHeight = -1;\n\n /**\n * @param x 放置x軸位...
import io.github.af19git5.entity.Image; import io.github.af19git5.entity.Item; import io.github.af19git5.entity.Text; import io.github.af19git5.exception.ImageException; import io.github.af19git5.type.OutputType; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.imageio.ImageIO;
7,783
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor;
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor;
private final List<Item> itemList = new ArrayList<>();
1
2023-11-01 03:55:06+00:00
12k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/RenderBoard.java
[ { "identifier": "ImageCache", "path": "src/main/java/com/chadfield/shogiexplorer/objects/ImageCache.java", "snippet": "public class ImageCache {\n\n private Map<String, BaseMultiResolutionImage> imageMap = new HashMap<>();\n\n public void putImage(String identifier, BaseMultiResolutionImage image)...
import java.util.EnumMap; import java.awt.Image; import com.chadfield.shogiexplorer.objects.ImageCache; import com.chadfield.shogiexplorer.objects.Koma; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.utils.MathUtils; import com.chadfield.shogiexplorer.utils.ImageUtils; import javax.swing.JPanel; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Dimension; import static com.chadfield.shogiexplorer.utils.StringUtils.substituteKomaName; import static com.chadfield.shogiexplorer.utils.StringUtils.substituteKomaNameRotated; import java.awt.Color; import java.awt.image.BaseMultiResolutionImage;
7,879
xCoordMap.put(Koma.Type.GFU, 0); yCoordMap.put(Koma.Type.GFU, 0); xOffsetMap.put(Koma.Type.GKY, 0); yOffsetMap.put(Koma.Type.GKY, 0); xCoordMap.put(Koma.Type.GKY, 0); yCoordMap.put(Koma.Type.GKY, 1); xOffsetMap.put(Koma.Type.GKE, 0); yOffsetMap.put(Koma.Type.GKE, 0); xCoordMap.put(Koma.Type.GKE, 0); yCoordMap.put(Koma.Type.GKE, 2); xOffsetMap.put(Koma.Type.GGI, 0); yOffsetMap.put(Koma.Type.GGI, 0); xCoordMap.put(Koma.Type.GGI, 0); yCoordMap.put(Koma.Type.GGI, 3); xOffsetMap.put(Koma.Type.GKI, 0); yOffsetMap.put(Koma.Type.GKI, 0); xCoordMap.put(Koma.Type.GKI, 0); yCoordMap.put(Koma.Type.GKI, 4); xOffsetMap.put(Koma.Type.GKA, 0); yOffsetMap.put(Koma.Type.GKA, 0); xCoordMap.put(Koma.Type.GKA, 0); yCoordMap.put(Koma.Type.GKA, 5); xOffsetMap.put(Koma.Type.GHI, 0); yOffsetMap.put(Koma.Type.GHI, 0); xCoordMap.put(Koma.Type.GHI, 0); yCoordMap.put(Koma.Type.GHI, 6); xOffsetMap.put(Koma.Type.SFU, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SFU, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SFU, 0); yCoordMap.put(Koma.Type.SFU, 6); xOffsetMap.put(Koma.Type.SKY, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKY, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKY, 0); yCoordMap.put(Koma.Type.SKY, 5); xOffsetMap.put(Koma.Type.SKE, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKE, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKE, 0); yCoordMap.put(Koma.Type.SKE, 4); xOffsetMap.put(Koma.Type.SGI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SGI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SGI, 0); yCoordMap.put(Koma.Type.SGI, 3); xOffsetMap.put(Koma.Type.SKI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKI, 0); yCoordMap.put(Koma.Type.SKI, 2); xOffsetMap.put(Koma.Type.SKA, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKA, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKA, 0); yCoordMap.put(Koma.Type.SKA, 1); xOffsetMap.put(Koma.Type.SHI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SHI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SHI, 0); yCoordMap.put(Koma.Type.SHI, 0); xOffsetMapRotated.put(Koma.Type.SFU, 0); yOffsetMapRotated.put(Koma.Type.SFU, 0); xCoordMapRotated.put(Koma.Type.SFU, 0); yCoordMapRotated.put(Koma.Type.SFU, 0); xOffsetMapRotated.put(Koma.Type.SKY, 0); yOffsetMapRotated.put(Koma.Type.SKY, 0); xCoordMapRotated.put(Koma.Type.SKY, 0); yCoordMapRotated.put(Koma.Type.SKY, 1); xOffsetMapRotated.put(Koma.Type.SKE, 0); yOffsetMapRotated.put(Koma.Type.SKE, 0); xCoordMapRotated.put(Koma.Type.SKE, 0); yCoordMapRotated.put(Koma.Type.SKE, 2); xOffsetMapRotated.put(Koma.Type.SGI, 0); yOffsetMapRotated.put(Koma.Type.SGI, 0); xCoordMapRotated.put(Koma.Type.SGI, 0); yCoordMapRotated.put(Koma.Type.SGI, 3); xOffsetMapRotated.put(Koma.Type.SKI, 0); yOffsetMapRotated.put(Koma.Type.SKI, 0); xCoordMapRotated.put(Koma.Type.SKI, 0); yCoordMapRotated.put(Koma.Type.SKI, 4); xOffsetMapRotated.put(Koma.Type.SKA, 0); yOffsetMapRotated.put(Koma.Type.SKA, 0); xCoordMapRotated.put(Koma.Type.SKA, 0); yCoordMapRotated.put(Koma.Type.SKA, 5); xOffsetMapRotated.put(Koma.Type.SHI, 0); yOffsetMapRotated.put(Koma.Type.SHI, 0); xCoordMapRotated.put(Koma.Type.SHI, 0); yCoordMapRotated.put(Koma.Type.SHI, 6); xOffsetMapRotated.put(Koma.Type.GFU, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GFU, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GFU, 0); yCoordMapRotated.put(Koma.Type.GFU, 6); xOffsetMapRotated.put(Koma.Type.GKY, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKY, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKY, 0); yCoordMapRotated.put(Koma.Type.GKY, 5); xOffsetMapRotated.put(Koma.Type.GKE, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKE, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKE, 0); yCoordMapRotated.put(Koma.Type.GKE, 4); xOffsetMapRotated.put(Koma.Type.GGI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GGI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GGI, 0); yCoordMapRotated.put(Koma.Type.GGI, 3); xOffsetMapRotated.put(Koma.Type.GKI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKI, 0); yCoordMapRotated.put(Koma.Type.GKI, 2); xOffsetMapRotated.put(Koma.Type.GKA, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKA, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKA, 0); yCoordMapRotated.put(Koma.Type.GKA, 1); xOffsetMapRotated.put(Koma.Type.GHI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GHI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GHI, 0); yCoordMapRotated.put(Koma.Type.GHI, 0); //</editor-fold> for (Koma.Type komaType : Koma.Type.values()) { Integer numberHeld = board.getInHandKomaMap().get(komaType); if (numberHeld != null && numberHeld > 0) { BaseMultiResolutionImage pieceImage; if (rotatedView) {
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class RenderBoard { static final int SBAN_XOFFSET = (MathUtils.BOARD_XY + 1) * MathUtils.KOMA_X + MathUtils.COORD_XY * 5; static final int SBAN_YOFFSET = MathUtils.KOMA_Y * 2 + MathUtils.COORD_XY * 2; static final int CENTRE_X = 5; static final int CENTRE_Y = 5; static final String IMAGE_STR_SENTE = "sente"; static final String IMAGE_STR_GOTE = "gote"; static final String IMAGE_STR_BOARD = "board"; static final String IMAGE_STR_KOMADAI = "komadai"; static final String PIECE_SET_CLASSIC = "classic"; static double scale; private RenderBoard() { throw new IllegalStateException("Utility class"); } public static void loadBoard(Board board, ImageCache imageCache, javax.swing.JPanel boardPanel, boolean rotatedView) { int boardPanelWidth = boardPanel.getWidth(); if (boardPanelWidth == 0) { return; } java.awt.Dimension minimumDimension = boardPanel.getMinimumSize(); double vertScale = boardPanel.getHeight() / minimumDimension.getHeight(); double horizScale = boardPanelWidth / minimumDimension.getWidth(); if (vertScale < horizScale) { scale = vertScale; } else { scale = horizScale; } var highlightColor = new Color(200, 100, 100, 160); // Start with a clean slate. boardPanel.removeAll(); drawPieces(board, imageCache, boardPanel, rotatedView); drawPiecesInHand(board, imageCache, boardPanel, rotatedView); drawCoordinates(boardPanel, rotatedView); drawGrid(imageCache, boardPanel); drawHighlights(board, boardPanel, rotatedView, highlightColor); drawKomadai(imageCache, boardPanel); drawBackground(imageCache, boardPanel); drawTurnNotification(board, imageCache, boardPanel, rotatedView); boardPanel.setVisible(true); boardPanel.repaint(); } private static void drawCoordinates(JPanel boardPanel, boolean rotatedView) { String[] rank = {"一", "二", "三", "四", "五", "六", "七", "八", "九"}; if (rotatedView) { for (int i = 0; i < 9; i++) { boardPanel.add(ImageUtils.getTextLabelForBan( new Coordinate(i, 0), new Dimension( MathUtils.KOMA_X + MathUtils.COORD_XY * 4 - 2, MathUtils.BOARD_XY * MathUtils.KOMA_Y + MathUtils.COORD_XY / 2 - 3), new Coordinate(CENTRE_X, CENTRE_Y), Integer.toString(i + 1), scale )); } for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(0, i), new Dimension( MathUtils.COORD_XY * 4 + 7, MathUtils.COORD_XY / 2 + 7), new Coordinate(CENTRE_X, CENTRE_Y), rank[8 - i], scale )); } } else { for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(i, 0), new Dimension( MathUtils.KOMA_X + MathUtils.COORD_XY * 4 - 2, -(MathUtils.COORD_XY / 2) - 3), new Coordinate(CENTRE_X, CENTRE_Y), Integer.toString(9 - i), scale )); } for (int i = 0; i < 9; i++) { boardPanel.add( ImageUtils.getTextLabelForBan( new Coordinate(0, i), new Dimension( MathUtils.KOMA_X * 10 + MathUtils.COORD_XY * 3 + 3, MathUtils.COORD_XY / 2 + 7), new Coordinate(CENTRE_X, CENTRE_Y), rank[i], scale )); } } } private static void drawTurnNotification(Board board, ImageCache imageCache, JPanel boardPanel, boolean rotatedView) { if (board.getNextTurn() == Turn.SENTE) { BaseMultiResolutionImage image = imageCache.getImage(IMAGE_STR_SENTE); if (image == null) { image = ImageUtils.loadSVGImageFromResources(IMAGE_STR_SENTE, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(IMAGE_STR_SENTE, image); } if (rotatedView) { boardPanel.add( ImageUtils.getPieceLabelForKoma(image, new Coordinate(0, 8), new Dimension(MathUtils.COORD_XY, MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } else { boardPanel.add( ImageUtils.getPieceLabelForKoma( image, new Coordinate(0, -2), new Dimension(SBAN_XOFFSET, SBAN_YOFFSET - MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } } else { BaseMultiResolutionImage image = imageCache.getImage(IMAGE_STR_GOTE); if (image == null) { image = ImageUtils.loadSVGImageFromResources(IMAGE_STR_GOTE, new Dimension(MathUtils.KOMA_X, MathUtils.KOMA_Y), scale); imageCache.putImage(IMAGE_STR_GOTE, image); } if (rotatedView) { boardPanel.add( ImageUtils.getPieceLabelForKoma(image, new Coordinate(0, -2), new Dimension(SBAN_XOFFSET, SBAN_YOFFSET - MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } else { boardPanel.add( ImageUtils.getPieceLabelForKoma( image, new Coordinate(0, 8), new Dimension(MathUtils.COORD_XY, MathUtils.COORD_XY), new Coordinate(CENTRE_X, CENTRE_Y), scale ) ); } } } private static void drawPiecesInHand(Board board, ImageCache imageCache, JPanel boardPanel, boolean rotatedView) { EnumMap<Koma.Type, Integer> xOffsetMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yOffsetMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xOffsetMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yOffsetMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xCoordMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yCoordMap = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> xCoordMapRotated = new EnumMap<>(Koma.Type.class); EnumMap<Koma.Type, Integer> yCoordMapRotated = new EnumMap<>(Koma.Type.class); //<editor-fold defaultstate="collapsed" desc="Map initialization"> xOffsetMap.put(Koma.Type.GFU, 0); yOffsetMap.put(Koma.Type.GFU, 0); xCoordMap.put(Koma.Type.GFU, 0); yCoordMap.put(Koma.Type.GFU, 0); xOffsetMap.put(Koma.Type.GKY, 0); yOffsetMap.put(Koma.Type.GKY, 0); xCoordMap.put(Koma.Type.GKY, 0); yCoordMap.put(Koma.Type.GKY, 1); xOffsetMap.put(Koma.Type.GKE, 0); yOffsetMap.put(Koma.Type.GKE, 0); xCoordMap.put(Koma.Type.GKE, 0); yCoordMap.put(Koma.Type.GKE, 2); xOffsetMap.put(Koma.Type.GGI, 0); yOffsetMap.put(Koma.Type.GGI, 0); xCoordMap.put(Koma.Type.GGI, 0); yCoordMap.put(Koma.Type.GGI, 3); xOffsetMap.put(Koma.Type.GKI, 0); yOffsetMap.put(Koma.Type.GKI, 0); xCoordMap.put(Koma.Type.GKI, 0); yCoordMap.put(Koma.Type.GKI, 4); xOffsetMap.put(Koma.Type.GKA, 0); yOffsetMap.put(Koma.Type.GKA, 0); xCoordMap.put(Koma.Type.GKA, 0); yCoordMap.put(Koma.Type.GKA, 5); xOffsetMap.put(Koma.Type.GHI, 0); yOffsetMap.put(Koma.Type.GHI, 0); xCoordMap.put(Koma.Type.GHI, 0); yCoordMap.put(Koma.Type.GHI, 6); xOffsetMap.put(Koma.Type.SFU, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SFU, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SFU, 0); yCoordMap.put(Koma.Type.SFU, 6); xOffsetMap.put(Koma.Type.SKY, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKY, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKY, 0); yCoordMap.put(Koma.Type.SKY, 5); xOffsetMap.put(Koma.Type.SKE, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKE, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKE, 0); yCoordMap.put(Koma.Type.SKE, 4); xOffsetMap.put(Koma.Type.SGI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SGI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SGI, 0); yCoordMap.put(Koma.Type.SGI, 3); xOffsetMap.put(Koma.Type.SKI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKI, 0); yCoordMap.put(Koma.Type.SKI, 2); xOffsetMap.put(Koma.Type.SKA, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SKA, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SKA, 0); yCoordMap.put(Koma.Type.SKA, 1); xOffsetMap.put(Koma.Type.SHI, SBAN_XOFFSET); yOffsetMap.put(Koma.Type.SHI, SBAN_YOFFSET); xCoordMap.put(Koma.Type.SHI, 0); yCoordMap.put(Koma.Type.SHI, 0); xOffsetMapRotated.put(Koma.Type.SFU, 0); yOffsetMapRotated.put(Koma.Type.SFU, 0); xCoordMapRotated.put(Koma.Type.SFU, 0); yCoordMapRotated.put(Koma.Type.SFU, 0); xOffsetMapRotated.put(Koma.Type.SKY, 0); yOffsetMapRotated.put(Koma.Type.SKY, 0); xCoordMapRotated.put(Koma.Type.SKY, 0); yCoordMapRotated.put(Koma.Type.SKY, 1); xOffsetMapRotated.put(Koma.Type.SKE, 0); yOffsetMapRotated.put(Koma.Type.SKE, 0); xCoordMapRotated.put(Koma.Type.SKE, 0); yCoordMapRotated.put(Koma.Type.SKE, 2); xOffsetMapRotated.put(Koma.Type.SGI, 0); yOffsetMapRotated.put(Koma.Type.SGI, 0); xCoordMapRotated.put(Koma.Type.SGI, 0); yCoordMapRotated.put(Koma.Type.SGI, 3); xOffsetMapRotated.put(Koma.Type.SKI, 0); yOffsetMapRotated.put(Koma.Type.SKI, 0); xCoordMapRotated.put(Koma.Type.SKI, 0); yCoordMapRotated.put(Koma.Type.SKI, 4); xOffsetMapRotated.put(Koma.Type.SKA, 0); yOffsetMapRotated.put(Koma.Type.SKA, 0); xCoordMapRotated.put(Koma.Type.SKA, 0); yCoordMapRotated.put(Koma.Type.SKA, 5); xOffsetMapRotated.put(Koma.Type.SHI, 0); yOffsetMapRotated.put(Koma.Type.SHI, 0); xCoordMapRotated.put(Koma.Type.SHI, 0); yCoordMapRotated.put(Koma.Type.SHI, 6); xOffsetMapRotated.put(Koma.Type.GFU, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GFU, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GFU, 0); yCoordMapRotated.put(Koma.Type.GFU, 6); xOffsetMapRotated.put(Koma.Type.GKY, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKY, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKY, 0); yCoordMapRotated.put(Koma.Type.GKY, 5); xOffsetMapRotated.put(Koma.Type.GKE, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKE, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKE, 0); yCoordMapRotated.put(Koma.Type.GKE, 4); xOffsetMapRotated.put(Koma.Type.GGI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GGI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GGI, 0); yCoordMapRotated.put(Koma.Type.GGI, 3); xOffsetMapRotated.put(Koma.Type.GKI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKI, 0); yCoordMapRotated.put(Koma.Type.GKI, 2); xOffsetMapRotated.put(Koma.Type.GKA, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GKA, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GKA, 0); yCoordMapRotated.put(Koma.Type.GKA, 1); xOffsetMapRotated.put(Koma.Type.GHI, SBAN_XOFFSET); yOffsetMapRotated.put(Koma.Type.GHI, SBAN_YOFFSET); xCoordMapRotated.put(Koma.Type.GHI, 0); yCoordMapRotated.put(Koma.Type.GHI, 0); //</editor-fold> for (Koma.Type komaType : Koma.Type.values()) { Integer numberHeld = board.getInHandKomaMap().get(komaType); if (numberHeld != null && numberHeld > 0) { BaseMultiResolutionImage pieceImage; if (rotatedView) {
String name = PIECE_SET_CLASSIC + "/" + substituteKomaNameRotated(komaType.toString());
9
2023-11-08 09:24:57+00:00
12k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/GroupServiceImpl.java
[ { "identifier": "ChatAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/ChatAdapt.java", "snippet": "public class ChatAdapt {\n\n /**\n * 建立聊天群房间\n *\n * @param roomId 房间 ID\n * @return {@link ChatGroupRoom }\n * @author qingmeng\n * @...
import com.qingmeng.config.adapt.ChatAdapt; import com.qingmeng.config.adapt.RoomAdapt; import com.qingmeng.config.annotation.RedissonLock; import com.qingmeng.config.cache.*; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.*; import com.qingmeng.dto.chatGroup.*; import com.qingmeng.entity.*; import com.qingmeng.enums.chat.RoomStatusEnum; import com.qingmeng.enums.chat.RoomTypeEnum; import com.qingmeng.service.FileService; import com.qingmeng.service.GroupService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.chat.GroupDetailInfo; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors;
10,473
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月06日 22:03:00 */ @Service public class GroupServiceImpl implements GroupService { @Resource private ChatRoomDao chatRoomDao; @Resource private ChatGroupMemberDao chatGroupMemberDao; @Resource private ChatGroupManagerDao chatGroupManagerDao; @Resource private ChatGroupRoomDao chatGroupRoomDao; @Resource private ChatGroupPersonalSettingDao chatGroupPersonalSettingDao; @Resource private ChatGroupSettingDao chatGroupSettingDao; @Resource private UserCache userCache; @Resource private FileService fileService; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private ChatGroupMemberCache chatGroupMemberCache; @Resource private ChatRoomCache chatRoomCache; @Resource private ChatGroupRoomCache chatGroupRoomCache; @Resource private ChatGroupSettingCache chatGroupSettingCache; @Resource private ChatGroupPersonalSettingCache chatGroupPersonalSettingCache; @Resource private ChatGroupManagerCache chatGroupManagerCache; /** * 创建群聊 * * @param userId 用户 ID * @param creatGroupDTO 创建群聊 DTO * @author qingmeng * @createTime: 2023/12/06 22:07:59 */ @Override @Transactional(rollbackFor = Exception.class) public void creatGroup(Long userId, CreatGroupDTO creatGroupDTO) { List<Long> ids = preCheckUserList(creatGroupDTO.getMemberIds(), SystemConstant.CREATE_GROUP_MIN_COUNT); // 创建抽象群聊房间记录 ChatRoom chatRoom = RoomAdapt.buildDefaultGroupRoom(); chatRoomDao.save(chatRoom); Long roomId = chatRoom.getId(); // 创建群聊房间记录 ChatGroupRoom chatGroupRoom = ChatAdapt.buildChatGroupRoom(roomId); chatGroupRoomDao.save(chatGroupRoom); Long groupRoomId = chatGroupRoom.getId(); // 添加群成员记录 addGroupMemberRecord(groupRoomId, ids); // 添加群管理员(即群主)记录 ChatGroupManager chatGroupManager = ChatAdapt.buildChatGroupOwner(userId, groupRoomId); chatGroupManagerDao.save(chatGroupManager); // 添加对应成员对群聊设置记录 List<ChatGroupPersonalSetting> builtChatGroupPersonalSettingSaveList = ChatAdapt.buildChatGroupPersonalSettingSaveList(groupRoomId, ids); chatGroupPersonalSettingDao.saveBatch(builtChatGroupPersonalSettingSaveList); // 添加管理员管理群聊设置记录 SysUser sysUser = userCache.get(userId); String qrcodeUrl = fileService.getQrcodeUrl(groupRoomId); ChatGroupSetting chatGroupPersonalSetting = ChatAdapt.buildDefaultChatGroupSetting(groupRoomId, sysUser, qrcodeUrl); chatGroupSettingDao.save(chatGroupPersonalSetting); } /** * 邀请 * * @param userId 用户 ID * @param inviteDTO 邀请 DTO * @author qingmeng * @createTime: 2023/12/07 08:42:51 */ @Override @RedissonLock(key = "#invite", waitTime = 3000) public void invite(Long userId, InviteDTO inviteDTO) { Long roomId = inviteDTO.getRoomId(); checkChatRoom(roomId); ChatGroupRoom chatGroupRoom = chatGroupRoomCache.get(roomId); Long groupRoomId = chatGroupRoom.getId(); checkGroupRoom(groupRoomId); List<Long> inviteIds = preCheckUserList(inviteDTO.getUserIds(), SystemConstant.INVITE_MEMBER_MIN_COUNT); int memberCount = chatGroupMemberCache.getMemberUserIdList(roomId).size();
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月06日 22:03:00 */ @Service public class GroupServiceImpl implements GroupService { @Resource private ChatRoomDao chatRoomDao; @Resource private ChatGroupMemberDao chatGroupMemberDao; @Resource private ChatGroupManagerDao chatGroupManagerDao; @Resource private ChatGroupRoomDao chatGroupRoomDao; @Resource private ChatGroupPersonalSettingDao chatGroupPersonalSettingDao; @Resource private ChatGroupSettingDao chatGroupSettingDao; @Resource private UserCache userCache; @Resource private FileService fileService; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private ChatGroupMemberCache chatGroupMemberCache; @Resource private ChatRoomCache chatRoomCache; @Resource private ChatGroupRoomCache chatGroupRoomCache; @Resource private ChatGroupSettingCache chatGroupSettingCache; @Resource private ChatGroupPersonalSettingCache chatGroupPersonalSettingCache; @Resource private ChatGroupManagerCache chatGroupManagerCache; /** * 创建群聊 * * @param userId 用户 ID * @param creatGroupDTO 创建群聊 DTO * @author qingmeng * @createTime: 2023/12/06 22:07:59 */ @Override @Transactional(rollbackFor = Exception.class) public void creatGroup(Long userId, CreatGroupDTO creatGroupDTO) { List<Long> ids = preCheckUserList(creatGroupDTO.getMemberIds(), SystemConstant.CREATE_GROUP_MIN_COUNT); // 创建抽象群聊房间记录 ChatRoom chatRoom = RoomAdapt.buildDefaultGroupRoom(); chatRoomDao.save(chatRoom); Long roomId = chatRoom.getId(); // 创建群聊房间记录 ChatGroupRoom chatGroupRoom = ChatAdapt.buildChatGroupRoom(roomId); chatGroupRoomDao.save(chatGroupRoom); Long groupRoomId = chatGroupRoom.getId(); // 添加群成员记录 addGroupMemberRecord(groupRoomId, ids); // 添加群管理员(即群主)记录 ChatGroupManager chatGroupManager = ChatAdapt.buildChatGroupOwner(userId, groupRoomId); chatGroupManagerDao.save(chatGroupManager); // 添加对应成员对群聊设置记录 List<ChatGroupPersonalSetting> builtChatGroupPersonalSettingSaveList = ChatAdapt.buildChatGroupPersonalSettingSaveList(groupRoomId, ids); chatGroupPersonalSettingDao.saveBatch(builtChatGroupPersonalSettingSaveList); // 添加管理员管理群聊设置记录 SysUser sysUser = userCache.get(userId); String qrcodeUrl = fileService.getQrcodeUrl(groupRoomId); ChatGroupSetting chatGroupPersonalSetting = ChatAdapt.buildDefaultChatGroupSetting(groupRoomId, sysUser, qrcodeUrl); chatGroupSettingDao.save(chatGroupPersonalSetting); } /** * 邀请 * * @param userId 用户 ID * @param inviteDTO 邀请 DTO * @author qingmeng * @createTime: 2023/12/07 08:42:51 */ @Override @RedissonLock(key = "#invite", waitTime = 3000) public void invite(Long userId, InviteDTO inviteDTO) { Long roomId = inviteDTO.getRoomId(); checkChatRoom(roomId); ChatGroupRoom chatGroupRoom = chatGroupRoomCache.get(roomId); Long groupRoomId = chatGroupRoom.getId(); checkGroupRoom(groupRoomId); List<Long> inviteIds = preCheckUserList(inviteDTO.getUserIds(), SystemConstant.INVITE_MEMBER_MIN_COUNT); int memberCount = chatGroupMemberCache.getMemberUserIdList(roomId).size();
AssertUtils.equal(memberCount + inviteIds.size(), SystemConstant.MEMBER_MAX_COUNT, "邀请人数已超过限制");
7
2023-11-07 16:04:55+00:00
12k
Einzieg/EinziegCloud
src/main/java/com/cloud/service/impl/AuthenticationService.java
[ { "identifier": "AuthenticationDTO", "path": "src/main/java/com/cloud/entity/AuthenticationDTO.java", "snippet": "@Data\npublic class AuthenticationDTO implements Serializable, UserDetails {\n\n\t@Serial\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate String id;\n\n\tprivate String emai...
import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cloud.entity.AuthenticationDTO; import com.cloud.entity.User; import com.cloud.entity.UserRole; import com.cloud.entity.request.AuthenticationRequest; import com.cloud.entity.request.RegisterRequest; import com.cloud.entity.response.AuthenticationResponse; import com.cloud.mapper.AuthenticationMapper; import com.cloud.service.IAuthenticationService; import com.cloud.service.IUserRoleService; import com.cloud.service.IUserService; import com.cloud.util.HttpUtil; import com.cloud.util.IPUtil; import com.cloud.util.JwtUtil; import com.cloud.util.RedisUtil; import com.cloud.util.msg.Msg; import com.cloud.util.msg.ResultCode; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Optional;
9,159
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService;
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService;
private final IUserRoleService userRoleService;
8
2023-11-07 07:27:53+00:00
12k
hlysine/create_power_loader
src/main/java/com/hlysine/create_power_loader/command/ListLoadersCommand.java
[ { "identifier": "ChunkLoadManager", "path": "src/main/java/com/hlysine/create_power_loader/content/ChunkLoadManager.java", "snippet": "public class ChunkLoadManager {\n private static final Logger LOGGER = LogUtils.getLogger();\n private static final int SAVED_CHUNKS_DISCARD_TICKS = 100;\n\n pr...
import com.hlysine.create_power_loader.content.ChunkLoadManager; import com.hlysine.create_power_loader.content.ChunkLoader; import com.hlysine.create_power_loader.content.LoaderMode; import com.hlysine.create_power_loader.content.WeakCollection; import com.hlysine.create_power_loader.content.trains.CarriageChunkLoader; import com.hlysine.create_power_loader.content.trains.StationChunkLoader; import com.hlysine.create_power_loader.content.trains.TrainChunkLoader; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.ArgumentBuilder; import com.simibubi.create.foundation.utility.Components; import com.simibubi.create.foundation.utility.Pair; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.server.command.EnumArgument; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function;
7,608
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) { for (WeakCollection<ChunkLoader> list : ChunkLoadManager.allLoaders.values()) { loaders.addAll(list); } } else { loaders.addAll(ChunkLoadManager.allLoaders.get(mode)); } loaders.removeIf(loader -> { if (loader instanceof TrainChunkLoader trainLoader) { for (CarriageChunkLoader carriageLoader : trainLoader.carriageLoaders) { if (carriageLoader.known && (carriageLoader.brass || carriageLoader.andesite)) return false; } return true;
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) { for (WeakCollection<ChunkLoader> list : ChunkLoadManager.allLoaders.values()) { loaders.addAll(list); } } else { loaders.addAll(ChunkLoadManager.allLoaders.get(mode)); } loaders.removeIf(loader -> { if (loader instanceof TrainChunkLoader trainLoader) { for (CarriageChunkLoader carriageLoader : trainLoader.carriageLoaders) { if (carriageLoader.known && (carriageLoader.brass || carriageLoader.andesite)) return false; } return true;
} else if (loader instanceof StationChunkLoader stationLoader) {
5
2023-11-09 04:29:33+00:00
12k
dingodb/dingo-expr
rel/src/main/java/io/dingodb/expr/rel/op/CsvValuesOp.java
[ { "identifier": "Parser", "path": "json/src/main/java/io/dingodb/expr/json/runtime/Parser.java", "snippet": "public class Parser implements Serializable {\n public static final Parser JSON = new Parser(DataFormat.APPLICATION_JSON);\n public static final Parser YAML = new Parser(DataFormat.APPLICAT...
import com.fasterxml.jackson.databind.MappingIterator; import io.dingodb.expr.json.runtime.Parser; import io.dingodb.expr.rel.RelConfig; import io.dingodb.expr.rel.SourceOp; import io.dingodb.expr.runtime.ExprConfig; import io.dingodb.expr.runtime.op.collection.ArrayBuilder; import io.dingodb.expr.runtime.type.AnyType; import io.dingodb.expr.runtime.type.ArrayType; import io.dingodb.expr.runtime.type.BoolType; import io.dingodb.expr.runtime.type.BytesType; import io.dingodb.expr.runtime.type.DateType; import io.dingodb.expr.runtime.type.DecimalType; import io.dingodb.expr.runtime.type.DoubleType; import io.dingodb.expr.runtime.type.FloatType; import io.dingodb.expr.runtime.type.IntType; import io.dingodb.expr.runtime.type.ListType; import io.dingodb.expr.runtime.type.LongType; import io.dingodb.expr.runtime.type.StringType; import io.dingodb.expr.runtime.type.TimeType; import io.dingodb.expr.runtime.type.TimestampType; import io.dingodb.expr.runtime.type.TupleType; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.TypeVisitorBase; import io.dingodb.expr.runtime.utils.CodecUtils; import io.dingodb.expr.runtime.utils.DateTimeUtils; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.commons.io.IOUtils; import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport;
10,516
/* * Copyright 2021 DataCanvas * * 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 io.dingodb.expr.rel.op; final class CsvValuesOp implements SourceOp { public static final String NAME = "CSV"; private final InputStream csvFile; @Getter private TupleType type; private transient ExprConfig exprConfig; CsvValuesOp(InputStream csvFile) { this.csvFile = csvFile; } CsvValuesOp(String... csvLines) { this.csvFile = IOUtils.toInputStream(String.join("\n", csvLines), StandardCharsets.UTF_8); } @Override public @NonNull Stream<Object[]> get() { try { FromStringConverter converter = new FromStringConverter(); MappingIterator<String[]> it = Parser.CSV.readValues(csvFile, String[].class); return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false) .map(i -> (Object[]) converter.visit(type, i)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void init(TupleType type, @NonNull RelConfig config) { this.type = type; exprConfig = config.getExprCompiler().getConfig(); } @Override public String toString() { return NAME; } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private class FromStringConverter extends TypeVisitorBase<Object, @NonNull Object> { @Override public @NonNull Object visitIntType(@NonNull IntType type, @NonNull Object obj) { return Integer.parseInt((String) obj); } @Override public @NonNull Object visitLongType(@NonNull LongType type, @NonNull Object obj) { return Long.parseLong((String) obj); } @Override public @NonNull Object visitFloatType(@NonNull FloatType type, @NonNull Object obj) { return Float.parseFloat((String) obj); } @Override public @NonNull Object visitDoubleType(@NonNull DoubleType type, @NonNull Object obj) { return Double.parseDouble((String) obj); } @Override public @NonNull Object visitBoolType(@NonNull BoolType type, @NonNull Object obj) { return Boolean.getBoolean((String) obj); } @Override public @NonNull Object visitDecimalType(@NonNull DecimalType type, @NonNull Object obj) { return new BigDecimal((String) obj); } @Override public @NonNull Object visitStringType(@NonNull StringType type, @NonNull Object obj) { return obj; } @Override public @NonNull Object visitBytesType(@NonNull BytesType type, @NonNull Object obj) { return CodecUtils.hexStringToBytes((String) obj); } @Override public Object visitDateType(@NonNull DateType type, @NonNull Object obj) {
/* * Copyright 2021 DataCanvas * * 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 io.dingodb.expr.rel.op; final class CsvValuesOp implements SourceOp { public static final String NAME = "CSV"; private final InputStream csvFile; @Getter private TupleType type; private transient ExprConfig exprConfig; CsvValuesOp(InputStream csvFile) { this.csvFile = csvFile; } CsvValuesOp(String... csvLines) { this.csvFile = IOUtils.toInputStream(String.join("\n", csvLines), StandardCharsets.UTF_8); } @Override public @NonNull Stream<Object[]> get() { try { FromStringConverter converter = new FromStringConverter(); MappingIterator<String[]> it = Parser.CSV.readValues(csvFile, String[].class); return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false) .map(i -> (Object[]) converter.visit(type, i)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void init(TupleType type, @NonNull RelConfig config) { this.type = type; exprConfig = config.getExprCompiler().getConfig(); } @Override public String toString() { return NAME; } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private class FromStringConverter extends TypeVisitorBase<Object, @NonNull Object> { @Override public @NonNull Object visitIntType(@NonNull IntType type, @NonNull Object obj) { return Integer.parseInt((String) obj); } @Override public @NonNull Object visitLongType(@NonNull LongType type, @NonNull Object obj) { return Long.parseLong((String) obj); } @Override public @NonNull Object visitFloatType(@NonNull FloatType type, @NonNull Object obj) { return Float.parseFloat((String) obj); } @Override public @NonNull Object visitDoubleType(@NonNull DoubleType type, @NonNull Object obj) { return Double.parseDouble((String) obj); } @Override public @NonNull Object visitBoolType(@NonNull BoolType type, @NonNull Object obj) { return Boolean.getBoolean((String) obj); } @Override public @NonNull Object visitDecimalType(@NonNull DecimalType type, @NonNull Object obj) { return new BigDecimal((String) obj); } @Override public @NonNull Object visitStringType(@NonNull StringType type, @NonNull Object obj) { return obj; } @Override public @NonNull Object visitBytesType(@NonNull BytesType type, @NonNull Object obj) { return CodecUtils.hexStringToBytes((String) obj); } @Override public Object visitDateType(@NonNull DateType type, @NonNull Object obj) {
return DateTimeUtils.parseDate((String) obj, exprConfig.getParseDateFormatters());
23
2023-11-04 08:43:49+00:00
12k
Arborsm/ArborCore
src/main/java/org/arbor/gtnn/data/GTNNMachines.java
[ { "identifier": "GTNN", "path": "src/main/java/org/arbor/gtnn/GTNN.java", "snippet": "@Mod(GTNN.MODID)\npublic class GTNN {\n\n public static final String MODID = \"gtnn\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n public GTNN() {\n MinecraftForge.EVENT_BUS.register...
import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.ICoilType; import com.gregtechceu.gtceu.api.data.RotationState; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MachineDefinition; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.MultiblockMachineDefinition; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.pattern.FactoryBlockPattern; import com.gregtechceu.gtceu.api.pattern.MultiblockShapeInfo; import com.gregtechceu.gtceu.api.pattern.Predicates; import com.gregtechceu.gtceu.api.registry.registrate.MachineBuilder; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.GTMaterials; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.arbor.gtnn.GTNN; import org.arbor.gtnn.api.machine.multiblock.APartAbility; import org.arbor.gtnn.api.machine.multiblock.ChemicalPlant; import org.arbor.gtnn.api.machine.multiblock.NeutronActivator; import org.arbor.gtnn.api.machine.multiblock.part.HighSpeedPipeBlock; import org.arbor.gtnn.api.machine.multiblock.part.NeutronAccelerator; import org.arbor.gtnn.api.pattern.APredicates; import org.arbor.gtnn.block.BlockTier; import org.arbor.gtnn.block.MachineCasingBlock; import org.arbor.gtnn.block.PipeBlock; import org.arbor.gtnn.block.PlantCasingBlock; import org.arbor.gtnn.client.renderer.machine.BlockMachineRenderer; import org.arbor.gtnn.client.renderer.machine.GTPPMachineRenderer; import java.util.*; import java.util.function.BiFunction; import static com.gregtechceu.gtceu.api.GTValues.V; import static com.gregtechceu.gtceu.api.GTValues.VNF; import static com.gregtechceu.gtceu.api.pattern.Predicates.abilities; import static com.gregtechceu.gtceu.api.pattern.Predicates.autoAbilities; import static com.gregtechceu.gtceu.api.pattern.util.RelativeDirection.*; import static org.arbor.gtnn.api.registry.GTNNRegistries.REGISTRATE;
10,336
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new) .renderer(() -> new BlockMachineRenderer(GTNN.id("block/machine/part/high_speed_pipe_block"))) .rotationState(RotationState.Y_AXIS) .register(); // public static final MachineDefinition CATALYTIC_HATCH = GTRegistries.REGISTRATE.machine("catalytic_hatch", // (holder) -> new SteamItemBusPartMachine(holder, IO.IN)) // .rotationState(RotationState.ALL) // .abilities(PartAbility.IMPORT_ITEMS) // .overlaySteamHullRenderer("item_bus.import") // .langValue("Catalytic Hatch") // .compassSections(GTCompassSections.PARTS) // .compassNode("item_bus") // .register(); ////////////////////////////////////// //********** Machine **********// ////////////////////////////////////// public static final MultiblockMachineDefinition CHEMICAL_PLANT = REGISTRATE.multiblock("chemical_plant", ChemicalPlant::new) .rotationState(RotationState.NON_Y_AXIS) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip1")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip2")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip3")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip4")) .recipeTypes(GTNNRecipesTypes.CHEMICAL_PLANT_RECIPES) .recipeModifier(ChemicalPlant::chemicalPlantRecipe) .appearanceBlock(GTBlocks.CASING_BRONZE_BRICKS) .pattern(definition -> FactoryBlockPattern.start() .aisle("VVVVVVV", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AVVSVVA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where("S", Predicates.controller(Predicates.blocks(definition.get()))) .where("V", APredicates.plantCasings() .or(autoAbilities(definition.getRecipeTypes())) .or(autoAbilities(true, false, false)) .or(abilities(PartAbility.INPUT_ENERGY)) .or(abilities(PartAbility.IMPORT_ITEMS)) .or(abilities(PartAbility.EXPORT_ITEMS)) .or(abilities(PartAbility.IMPORT_FLUIDS)) .or(abilities(PartAbility.EXPORT_FLUIDS)) ) .where("A", APredicates.plantCasings()) .where("D", APredicates.pipeBlock()) .where("C", Predicates.heatingCoils()) .where("B", APredicates.machineCasing()) .where("#", Predicates.air()) .build()) .shapeInfos(definition -> { List<MultiblockShapeInfo> shapeInfo = new ArrayList<>(); var builder = MultiblockShapeInfo.builder() .aisle("AAOSJAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("MBBBBBN", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("KBBBBBL", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AAAAAAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where('S', definition, Direction.NORTH) .where('#', Blocks.AIR.defaultBlockState()) .where('J', GTMachines.MAINTENANCE_HATCH, Direction.NORTH); Map<Integer, BlockState> shapeBlock = new HashMap<>(); for (PlantCasingBlock.PlantCasing casing : PlantCasingBlock.PlantCasing.values()) { shapeBlock.put(casing.getTier() + 10, casing.getPlantCasing(casing.getTier()).getDefaultState()); }
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new) .renderer(() -> new BlockMachineRenderer(GTNN.id("block/machine/part/high_speed_pipe_block"))) .rotationState(RotationState.Y_AXIS) .register(); // public static final MachineDefinition CATALYTIC_HATCH = GTRegistries.REGISTRATE.machine("catalytic_hatch", // (holder) -> new SteamItemBusPartMachine(holder, IO.IN)) // .rotationState(RotationState.ALL) // .abilities(PartAbility.IMPORT_ITEMS) // .overlaySteamHullRenderer("item_bus.import") // .langValue("Catalytic Hatch") // .compassSections(GTCompassSections.PARTS) // .compassNode("item_bus") // .register(); ////////////////////////////////////// //********** Machine **********// ////////////////////////////////////// public static final MultiblockMachineDefinition CHEMICAL_PLANT = REGISTRATE.multiblock("chemical_plant", ChemicalPlant::new) .rotationState(RotationState.NON_Y_AXIS) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip1")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip2")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip3")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip4")) .recipeTypes(GTNNRecipesTypes.CHEMICAL_PLANT_RECIPES) .recipeModifier(ChemicalPlant::chemicalPlantRecipe) .appearanceBlock(GTBlocks.CASING_BRONZE_BRICKS) .pattern(definition -> FactoryBlockPattern.start() .aisle("VVVVVVV", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AVVSVVA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where("S", Predicates.controller(Predicates.blocks(definition.get()))) .where("V", APredicates.plantCasings() .or(autoAbilities(definition.getRecipeTypes())) .or(autoAbilities(true, false, false)) .or(abilities(PartAbility.INPUT_ENERGY)) .or(abilities(PartAbility.IMPORT_ITEMS)) .or(abilities(PartAbility.EXPORT_ITEMS)) .or(abilities(PartAbility.IMPORT_FLUIDS)) .or(abilities(PartAbility.EXPORT_FLUIDS)) ) .where("A", APredicates.plantCasings()) .where("D", APredicates.pipeBlock()) .where("C", Predicates.heatingCoils()) .where("B", APredicates.machineCasing()) .where("#", Predicates.air()) .build()) .shapeInfos(definition -> { List<MultiblockShapeInfo> shapeInfo = new ArrayList<>(); var builder = MultiblockShapeInfo.builder() .aisle("AAOSJAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("MBBBBBN", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("KBBBBBL", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AAAAAAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where('S', definition, Direction.NORTH) .where('#', Blocks.AIR.defaultBlockState()) .where('J', GTMachines.MAINTENANCE_HATCH, Direction.NORTH); Map<Integer, BlockState> shapeBlock = new HashMap<>(); for (PlantCasingBlock.PlantCasing casing : PlantCasingBlock.PlantCasing.values()) { shapeBlock.put(casing.getTier() + 10, casing.getPlantCasing(casing.getTier()).getDefaultState()); }
for (MachineCasingBlock.MachineCasing machineCasing : MachineCasingBlock.MachineCasing.values()) {
8
2023-11-04 07:59:02+00:00
12k
satisfyu/HerbalBrews
common/src/main/java/satisfyu/herbalbrews/compat/jei/HerbalBrewsJEIPlugin.java
[ { "identifier": "CauldronGuiHandler", "path": "common/src/main/java/satisfyu/herbalbrews/client/gui/handler/CauldronGuiHandler.java", "snippet": "public class CauldronGuiHandler extends AbstractRecipeBookGUIScreenHandler {\n\n public CauldronGuiHandler(int syncId, Inventory playerInventory) {\n ...
import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.registration.IRecipeCatalystRegistration; import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; import mezz.jei.api.registration.IRecipeTransferRegistration; import net.minecraft.client.Minecraft; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeManager; import satisfyu.herbalbrews.client.gui.handler.CauldronGuiHandler; import satisfyu.herbalbrews.client.gui.handler.TeaKettleGuiHandler; import satisfyu.herbalbrews.compat.jei.category.CauldronCategory; import satisfyu.herbalbrews.compat.jei.category.TeaKettleCategory; import satisfyu.herbalbrews.recipe.CauldronRecipe; import satisfyu.herbalbrews.recipe.TeaKettleRecipe; import satisfyu.herbalbrews.registry.ObjectRegistry; import satisfyu.herbalbrews.registry.RecipeTypeRegistry; import satisfyu.herbalbrews.registry.ScreenHandlerTypeRegistry; import satisfyu.herbalbrews.util.HerbalBrewsIdentifier; import java.util.List; import java.util.Objects;
10,168
package satisfyu.herbalbrews.compat.jei; @JeiPlugin public class HerbalBrewsJEIPlugin implements IModPlugin { @Override public void registerCategories(IRecipeCategoryRegistration registration) {
package satisfyu.herbalbrews.compat.jei; @JeiPlugin public class HerbalBrewsJEIPlugin implements IModPlugin { @Override public void registerCategories(IRecipeCategoryRegistration registration) {
registration.addRecipeCategories(new TeaKettleCategory(registration.getJeiHelpers().getGuiHelper()));
3
2023-11-05 16:46:52+00:00
12k
AnhyDev/AnhyLingo
src/main/java/ink/anh/lingo/command/LingoCommand.java
[ { "identifier": "AnhyLingo", "path": "src/main/java/ink/anh/lingo/AnhyLingo.java", "snippet": "public class AnhyLingo extends JavaPlugin {\n\n private static AnhyLingo instance;\n \n private boolean isSpigot;\n private boolean isPaper;\n private boolean isFolia;\n private boolean hasPa...
import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Map; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import ink.anh.api.lingo.Translator; import ink.anh.api.messages.MessageType; import ink.anh.api.messages.Messenger; import ink.anh.api.utils.LangUtils; import ink.anh.lingo.AnhyLingo; import ink.anh.lingo.GlobalManager; import ink.anh.lingo.Permissions; import ink.anh.lingo.file.DirectoryContents; import ink.anh.lingo.file.FileProcessType; import ink.anh.lingo.item.ItemLang; import net.md_5.bungee.api.ChatColor; import ink.anh.lingo.file.FileCommandProcessor;
8,005
package ink.anh.lingo.command; /** * Command executor for the 'lingo' command in the AnhyLingo plugin. * This class processes and executes various subcommands related to language settings and file management. */ public class LingoCommand implements CommandExecutor { private AnhyLingo lingoPlugin; private GlobalManager globalManager; /** * Constructor for the LingoCommand class. * * @param lingoPlugin The instance of AnhyLingo plugin. */ public LingoCommand(AnhyLingo lingoPlugin) { this.lingoPlugin = lingoPlugin; this.globalManager = lingoPlugin.getGlobalManager(); } /** * Executes the given command, returning its success. * * @param sender Source of the command. * @param cmd The command which was executed. * @param label Alias of the command which was used. * @param args Passed command arguments. * @return true if a valid command, otherwise false. */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { switch (args[0].toLowerCase()) { case "nbt": return new NBTSubCommand(lingoPlugin).execNBT(sender, args); case "items": return itemLang(sender, args); case "reload": return reload(sender); case "set": return setLang(sender, args); case "get": return getLang(sender); case "reset": return resetLang(sender); case "dir": return directory(sender, args); case "flingo": case "fl": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.YAML_LOADER); case "fother": case "fo": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.SIMPLE_LOADER); case "fdel": case "fd": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.FILE_DELETER); default: return false; } } return false; } private boolean directory(CommandSender sender, String[] args) { if (!lingoPlugin.getGlobalManager().isAllowBrowsing()) { sendMessage(sender, "lingo_err_not_alloved_config ", MessageType.WARNING); return true; } int perm = checkPlayerPermissions(sender, Permissions.DIR_VIEW); if (perm != 0 && perm != 1) { return true; } // Перевірка, чи достатньо аргументів if (args.length != 2) { sendMessage(sender, "lingo_err_command_format /lingo dir <path>", MessageType.WARNING); return true; } String path = args[1];
package ink.anh.lingo.command; /** * Command executor for the 'lingo' command in the AnhyLingo plugin. * This class processes and executes various subcommands related to language settings and file management. */ public class LingoCommand implements CommandExecutor { private AnhyLingo lingoPlugin; private GlobalManager globalManager; /** * Constructor for the LingoCommand class. * * @param lingoPlugin The instance of AnhyLingo plugin. */ public LingoCommand(AnhyLingo lingoPlugin) { this.lingoPlugin = lingoPlugin; this.globalManager = lingoPlugin.getGlobalManager(); } /** * Executes the given command, returning its success. * * @param sender Source of the command. * @param cmd The command which was executed. * @param label Alias of the command which was used. * @param args Passed command arguments. * @return true if a valid command, otherwise false. */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length > 0) { switch (args[0].toLowerCase()) { case "nbt": return new NBTSubCommand(lingoPlugin).execNBT(sender, args); case "items": return itemLang(sender, args); case "reload": return reload(sender); case "set": return setLang(sender, args); case "get": return getLang(sender); case "reset": return resetLang(sender); case "dir": return directory(sender, args); case "flingo": case "fl": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.YAML_LOADER); case "fother": case "fo": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.SIMPLE_LOADER); case "fdel": case "fd": return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.FILE_DELETER); default: return false; } } return false; } private boolean directory(CommandSender sender, String[] args) { if (!lingoPlugin.getGlobalManager().isAllowBrowsing()) { sendMessage(sender, "lingo_err_not_alloved_config ", MessageType.WARNING); return true; } int perm = checkPlayerPermissions(sender, Permissions.DIR_VIEW); if (perm != 0 && perm != 1) { return true; } // Перевірка, чи достатньо аргументів if (args.length != 2) { sendMessage(sender, "lingo_err_command_format /lingo dir <path>", MessageType.WARNING); return true; } String path = args[1];
DirectoryContents.listDirectoryContents(sender, path);
3
2023-11-10 00:35:39+00:00
12k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/objects/lidar/LiDARController.java
[ { "identifier": "SubLiDARPipeline", "path": "src/main/java/io/github/mmm/measurement/device/objects/lidar/multithread/SubLiDARPipeline.java", "snippet": "public class SubLiDARPipeline implements Runnable {\n\n private final LiDAR[] subLidars;\n private volatile LidarScan[] scans;\n\n public Sub...
import io.github.mmm.measurement.device.objects.lidar.multithread.SubLiDARPipeline; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.measurement.device.scans.LidarScan3D; import io.github.mmm.modconfig.Config; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER;
7,832
LiDAR[] subLidarsForThread = new LiDAR[subLidarsPerThread]; for(int j = 0; j < subLidarsPerThread; j++) { int index = i * subLidarsPerThread + j; if(index >= subLidars.size()) break; subLidarsForThread[j] = subLidars.get(index); } // create and start thread pipelines[i] = new SubLiDARPipeline(subLidarsForThread); threads[i] = new Thread(pipelines[i]); threads[i].start(); } // join threads try { for(int i = 0; i < threadCount; i++) { threads[i].join(); } } catch (InterruptedException e) { e.printStackTrace(); } // get scans from threads int parsedSubLidars = 0; int currentLidar = 0; LidarScan[] scans = new LidarScan[this.lidars.length]; ArrayList<LidarScan> scansForLidar = new ArrayList<>(); for(int i = 0; i < pipelines.length; i++) { // loop through threads LidarScan[] subScans = pipelines[i].getScans(); for(int s=0; s < subScans.length; s++) { // loop through every scan of current thread if(subScans[s] == null) break; if(parsedSubLidars == subLidarsPerLidar[currentLidar]) { parsedSubLidars = 0; if(!this.isLidarAllowedToScan(this.lidars[currentLidar])) { currentLidar++; break; } LidarScan[] scansForLidarTemp = new LidarScan[scansForLidar.size()]; scansForLidarTemp = scansForLidar.toArray(scansForLidarTemp); scans[currentLidar] = this.buildScanFromSubScans( scansForLidarTemp, this.lidars[currentLidar] ); currentLidar++; scansForLidar.clear(); } scansForLidar.add(subScans[s]); parsedSubLidars++; } } // get last scan if(parsedSubLidars == subLidarsPerLidar[currentLidar]) { if(this.isLidarAllowedToScan(this.lidars[currentLidar])) { LidarScan[] scansForLidarTemp = new LidarScan[scansForLidar.size()]; scansForLidarTemp = scansForLidar.toArray(scansForLidarTemp); scans[currentLidar] = this.buildScanFromSubScans( scansForLidarTemp, this.lidars[currentLidar] ); } } return scans; } private ArrayList<LiDAR> getSubLidarsFrom2DLidar(LiDAR lidar2d) { // TODO: implement for (very large) 2D lidars ArrayList<LiDAR> subLidars = new ArrayList<>(); subLidars.add(lidar2d); return subLidars; } private ArrayList<LiDAR> getSubLidarsFrom3DLidar(LiDAR lidar3d) { ArrayList<LiDAR> subLidars = new ArrayList<>(); float verticalScanAngleDifferenceInDeg = lidar3d.getVerticalScanRadiusInDeg() / lidar3d.getVerticalScansPerRadius(); float pitchFromPOVInDegOffset = lidar3d.getPitchFromPOVInDeg() + (lidar3d.getVerticalScanRadiusInDeg() / 2); // start at the top of the scan for(int i = 0; i < lidar3d.getVerticalScansPerRadius(); i++) { float pitchFromPOVFor3DScanInDeg2D = pitchFromPOVInDegOffset - i * verticalScanAngleDifferenceInDeg; subLidars.add(new LiDAR( // just spam 2d lidars lol lidar3d.getHorizontalScanRadiusInDeg(), lidar3d.getHorizontalScansPerRadius(), lidar3d.getYawFromPOVInDeg(), pitchFromPOVFor3DScanInDeg2D, lidar3d.getRollFromPOVInDeg(), lidar3d.getMaximumMeasurementDistanceInMeters(), lidar3d.getPlayer(), lidar3d.getLevel(), null )); } return subLidars; } private LidarScan buildScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { if(lidar.getVerticalScanRadiusInDeg() == 0) { // 2D return this.build2DScanFromSubScans(subScans, lidar); } else { // 3D return this.build3DScanFromSubScans(subScans, lidar); } } private LidarScan build2DScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { if (subScans.length == 1) { return subScans[0]; } LidarScan2D scan2D = new LidarScan2D( lidar.getHorizontalScansPerRadius(), lidar.getPlayer().position().x, lidar.getPlayer().position().y, lidar.getPlayer().position().z, lidar.getPlayer().getViewVector(1.0F).x, lidar.getPlayer().getViewVector(1.0F).y, lidar.getPlayer().getViewVector(1.0F).z); int currentScan = 0; for(LidarScan scan : subScans) { if(scan == null) break; LidarScan2D scan2DToAdd = scan.getScan2D(); for(int i = 0; i < scan2DToAdd.getScansPerRadius(); i++) { scan2D.setDistance(currentScan, scan2DToAdd.getDistance(i)); currentScan++; } } return new LidarScan(scan2D); } private LidarScan build3DScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { // subScans are 2D scans
package io.github.mmm.measurement.device.objects.lidar; public class LiDARController { private final LiDAR[] lidars; private ArrayList<LidarScan>[] scans; private int maxThreadCount; private int passedTicks; public LiDARController(LiDAR[] lidars) { if (Config.MULTITHREAD_SWITCH.get()) { this.maxThreadCount = Config.THREAD_COUNT_MULTIPLIER.get() * Runtime.getRuntime().availableProcessors(); } else { this.maxThreadCount = 1; } this.lidars = lidars; this.scans = new ArrayList[this.lidars.length]; for(int i = 0; i < this.lidars.length; i++) { this.scans[i] = new ArrayList<>(); } } public ArrayList<LidarScan>[] getScans() { return this.scans; } public void clearScans() { this.scans = new ArrayList[this.lidars.length]; for(int i = 0; i < this.lidars.length; i++) { this.scans[i] = new ArrayList<>(); } } public void scan() { this.passedTicks = 0; this.executeScan(); } public void scan(int passedTicks) { this.passedTicks = passedTicks; this.executeScan(); } private void executeScan() { LidarScan[] currentScans; if(this.maxThreadCount == 1) { currentScans = this.getScansSingleThreaded(); } else { currentScans = this.getScansMultiThreaded(); } for(int i = 0; i < currentScans.length; i++) { this.scans[i].add(currentScans[i]); } } private LidarScan[] getScansSingleThreaded() { LidarScan[] scans = new LidarScan[this.lidars.length]; for (int i = 0; i < this.lidars.length; i++) { if(this.isLidarAllowedToScan(this.lidars[i])) { scans[i] = this.lidars[i].performScan(); } else { scans[i] = null; } } return scans; } private LidarScan[] getScansMultiThreaded() { int[] subLidarsPerLidar = new int[this.lidars.length]; ArrayList<LiDAR> subLidars = new ArrayList<>(); // slice main lidars into sublidars for(int l = 0; l < this.lidars.length; l++) { LiDAR lidar = this.lidars[l]; if(!this.isLidarAllowedToScan(lidar)) continue; ArrayList<LiDAR> newSubLidars; if(lidar.getVerticalScanRadiusInDeg() == 0) { // 2D newSubLidars = this.getSubLidarsFrom2DLidar(lidar); } else { // 3D newSubLidars = this.getSubLidarsFrom3DLidar(lidar); } subLidarsPerLidar[l] = newSubLidars.size(); subLidars.addAll(newSubLidars); } int threadCount = Math.min(this.maxThreadCount, subLidars.size()); int subLidarsPerThread = (int)Math.ceil((double)subLidars.size() / threadCount); // create threads SubLiDARPipeline[] pipelines = new SubLiDARPipeline[threadCount]; Thread[] threads = new Thread[threadCount]; for(int i = 0; i < threadCount; i++) { // get sublidars for thread LiDAR[] subLidarsForThread = new LiDAR[subLidarsPerThread]; for(int j = 0; j < subLidarsPerThread; j++) { int index = i * subLidarsPerThread + j; if(index >= subLidars.size()) break; subLidarsForThread[j] = subLidars.get(index); } // create and start thread pipelines[i] = new SubLiDARPipeline(subLidarsForThread); threads[i] = new Thread(pipelines[i]); threads[i].start(); } // join threads try { for(int i = 0; i < threadCount; i++) { threads[i].join(); } } catch (InterruptedException e) { e.printStackTrace(); } // get scans from threads int parsedSubLidars = 0; int currentLidar = 0; LidarScan[] scans = new LidarScan[this.lidars.length]; ArrayList<LidarScan> scansForLidar = new ArrayList<>(); for(int i = 0; i < pipelines.length; i++) { // loop through threads LidarScan[] subScans = pipelines[i].getScans(); for(int s=0; s < subScans.length; s++) { // loop through every scan of current thread if(subScans[s] == null) break; if(parsedSubLidars == subLidarsPerLidar[currentLidar]) { parsedSubLidars = 0; if(!this.isLidarAllowedToScan(this.lidars[currentLidar])) { currentLidar++; break; } LidarScan[] scansForLidarTemp = new LidarScan[scansForLidar.size()]; scansForLidarTemp = scansForLidar.toArray(scansForLidarTemp); scans[currentLidar] = this.buildScanFromSubScans( scansForLidarTemp, this.lidars[currentLidar] ); currentLidar++; scansForLidar.clear(); } scansForLidar.add(subScans[s]); parsedSubLidars++; } } // get last scan if(parsedSubLidars == subLidarsPerLidar[currentLidar]) { if(this.isLidarAllowedToScan(this.lidars[currentLidar])) { LidarScan[] scansForLidarTemp = new LidarScan[scansForLidar.size()]; scansForLidarTemp = scansForLidar.toArray(scansForLidarTemp); scans[currentLidar] = this.buildScanFromSubScans( scansForLidarTemp, this.lidars[currentLidar] ); } } return scans; } private ArrayList<LiDAR> getSubLidarsFrom2DLidar(LiDAR lidar2d) { // TODO: implement for (very large) 2D lidars ArrayList<LiDAR> subLidars = new ArrayList<>(); subLidars.add(lidar2d); return subLidars; } private ArrayList<LiDAR> getSubLidarsFrom3DLidar(LiDAR lidar3d) { ArrayList<LiDAR> subLidars = new ArrayList<>(); float verticalScanAngleDifferenceInDeg = lidar3d.getVerticalScanRadiusInDeg() / lidar3d.getVerticalScansPerRadius(); float pitchFromPOVInDegOffset = lidar3d.getPitchFromPOVInDeg() + (lidar3d.getVerticalScanRadiusInDeg() / 2); // start at the top of the scan for(int i = 0; i < lidar3d.getVerticalScansPerRadius(); i++) { float pitchFromPOVFor3DScanInDeg2D = pitchFromPOVInDegOffset - i * verticalScanAngleDifferenceInDeg; subLidars.add(new LiDAR( // just spam 2d lidars lol lidar3d.getHorizontalScanRadiusInDeg(), lidar3d.getHorizontalScansPerRadius(), lidar3d.getYawFromPOVInDeg(), pitchFromPOVFor3DScanInDeg2D, lidar3d.getRollFromPOVInDeg(), lidar3d.getMaximumMeasurementDistanceInMeters(), lidar3d.getPlayer(), lidar3d.getLevel(), null )); } return subLidars; } private LidarScan buildScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { if(lidar.getVerticalScanRadiusInDeg() == 0) { // 2D return this.build2DScanFromSubScans(subScans, lidar); } else { // 3D return this.build3DScanFromSubScans(subScans, lidar); } } private LidarScan build2DScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { if (subScans.length == 1) { return subScans[0]; } LidarScan2D scan2D = new LidarScan2D( lidar.getHorizontalScansPerRadius(), lidar.getPlayer().position().x, lidar.getPlayer().position().y, lidar.getPlayer().position().z, lidar.getPlayer().getViewVector(1.0F).x, lidar.getPlayer().getViewVector(1.0F).y, lidar.getPlayer().getViewVector(1.0F).z); int currentScan = 0; for(LidarScan scan : subScans) { if(scan == null) break; LidarScan2D scan2DToAdd = scan.getScan2D(); for(int i = 0; i < scan2DToAdd.getScansPerRadius(); i++) { scan2D.setDistance(currentScan, scan2DToAdd.getDistance(i)); currentScan++; } } return new LidarScan(scan2D); } private LidarScan build3DScanFromSubScans(LidarScan[] subScans, LiDAR lidar) { // subScans are 2D scans
LidarScan3D scan3D = new LidarScan3D(
3
2023-11-06 16:56:46+00:00
12k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/Dr...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,777
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config //@TeleOp(name="sample mechna drive ", group="Linear OpMode") public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = .4; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config //@TeleOp(name="sample mechna drive ", group="Linear OpMode") public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = .4; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner;
private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
2
2023-11-04 04:11:26+00:00
12k
InfantinoAndrea00/polimi-software-engineering-project-2022
src/main/java/it/polimi/ingsw/server/controller/ViewObserver.java
[ { "identifier": "ActionPhase1Move", "path": "src/main/java/it/polimi/ingsw/resources/ActionPhase1Move.java", "snippet": "public class ActionPhase1Move implements Serializable {\n private Color student;\n private Destination destination;\n private int islandId;\n\n private ActionPhase1Move(Co...
import it.polimi.ingsw.resources.ActionPhase1Move; import it.polimi.ingsw.resources.GameState; import it.polimi.ingsw.resources.Message; import it.polimi.ingsw.resources.enumerators.TowerColor; import it.polimi.ingsw.server.ClientHandler; import it.polimi.ingsw.server.Server; import it.polimi.ingsw.server.controller.states.ChooseCloudTile; import it.polimi.ingsw.server.controller.states.MoveMotherNature; import it.polimi.ingsw.server.controller.states.NextRoundOrEndGame; import it.polimi.ingsw.server.model.Cloud; import it.polimi.ingsw.server.model.Player; import it.polimi.ingsw.server.model.PlayerTurn; import it.polimi.ingsw.server.model.Team; import it.polimi.ingsw.server.model.expert.ExpertGame; import it.polimi.ingsw.server.model.expert.ExpertPlayer; import java.io.IOException; import java.net.Socket; import java.util.*; import static it.polimi.ingsw.resources.enumerators.MessageCode.*;
10,007
} return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param moves * @return */ public Message moveStudents(int playerId, List<ActionPhase1Move> moves) { System.out.println("Students movement\n" + Server.game.currentRound.getAssistantCardsPlayed()); if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, moves); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); c.sendResponseMessage(new Message(START_ACTION_PHASE_2, null, null)); } } catch (IOException e) { e.printStackTrace(); } gameController.nextState(); return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param islandId * @return */ public Message moveMotherNature(int playerId, int islandId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { int maxPossibleMoves = Server.game.currentRound.getAssistantCardsPlayed().get(playerId).getMoveValue(); if(Server.game.currentRound.currentTurn.card4Played) maxPossibleMoves += 2; int islandCounter = Server.game.getBoard().getMotherNatureIsland().getId(); for (int i = 0; i < maxPossibleMoves; i++) { if (islandCounter < Server.game.getBoard().getIslandGroups().size() - 1) islandCounter++; else islandCounter = 0; if(islandCounter == islandId) { System.out.println("Teams:" + Server.game.getTeamById(0).towerColor + " " + Server.game.getTeamById(1).towerColor); gameController.changeModel(islandId, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } if(!((MoveMotherNature) gameController.getState()).checkEndConditions()) { gameController.nextState(); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_3, null, null)); } } catch (IOException e) { e.printStackTrace(); } } else { gameController.nextState(); gameController.changeModel(null, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(END_GAME, Server.game.getTeamById(Server.game.winnerTeamId).towerColor, null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } } return new Message(INVALID_MOVE, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param cloudId * @return */ public Message chooseCloudTile(int playerId, int cloudId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, cloudId); try { for (ClientHandler c : clients) { if(counter == Server.game.getPlayerNumber()-1) Server.game.currentRound.resetCardsPlayed(); c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) { gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } else { ((ChooseCloudTile) gameController.getState()).mustEndRound = true; gameController.nextState();
package it.polimi.ingsw.server.controller; /** * class that observe the view */ public class ViewObserver { private GameController gameController; private int counter; private boolean canAddPlayer; private CharacterCardHandler characterCardHandler; private Map<Integer, Socket> playersSockets; private List<ClientHandler> clients; public ViewObserver () { clients = new ArrayList<>(); playersSockets = new HashMap<>(); gameController = new GameController(); counter = 0; canAddPlayer = false; } /** * * @param expertMode true if the game is in expert mode, false otherwise * @param playerNumber number of players in the game * @return an acknowledgement message */ public Message expertModeAndPlayerNumber(boolean expertMode, int playerNumber) { gameController.changeModel(expertMode, playerNumber); gameController.nextState(); canAddPlayer = true; return new Message(GAME_CREATED, null, null); } /** * * @param playerName * @param client * @return */ public Message addNewPlayer(String playerName, ClientHandler client) { if(canAddPlayer) { if (Server.game.getPlayerNumber() > Server.game.getPlayers().size()) { gameController.changeModel(playerName, counter); playersSockets.put(counter, client.getClient()); clients.add(client); try { client.sendResponseMessage(new Message(PLAYER_ADDED, counter, Server.game.getPlayerNumber())); } catch (IOException e) { e.printStackTrace(); } counter++; if (Server.game.getPlayerNumber() == counter) { gameController.nextState(); counter = 0; Map<Integer, String> playerNames = new HashMap<>(); for(Player p : Server.game.getPlayers()) playerNames.put(p.getId(), p.getName()); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(PLAYERS_AND_MODE, playerNames, Server.game.isExpertMode())); } } catch (IOException e) { e.printStackTrace(); } if (Server.game.getPlayerNumber() != 4) { gameController.changeModel(null, null); System.out.println("Initialized game"); gameController.nextState(); gameController.changeModel(null, null); System.out.println("Refilled cloud tiles"); gameController.nextState(); Map<Integer, TowerColor> playersAssociation = new HashMap<>(); for (Player p : Server.game.getPlayers()) playersAssociation.put(p.getId(), Server.game.getTeamById(p.getId()).towerColor); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_GAME_SESSION, playersAssociation, new GameState(Server.game))); c.sendResponseMessage(new Message(START_PLANNING_PHASE, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(0), null)); } } catch (IOException e) { e.printStackTrace(); } } } return new Message(ACK, null, null); } return new Message(MAX_PLAYER_NUMBER_REACHED, null, null); } return new Message(CREATING_GAME, null, null); } /** * * @param playerId * @param teamId * @return */ public Message addPlayerInTeam(int playerId, int teamId) { if(Server.game.getTeamById(teamId).getPlayers().size() < 2) { gameController.changeModel(playerId, teamId); counter++; if(counter == 4) { gameController.nextState(); counter = 0; gameController.changeModel(null, null); gameController.nextState(); gameController.changeModel(null, null); gameController.nextState(); Map<Integer, TowerColor> teamsAssociation = new HashMap<>(); for (Team t : Server.game.getTeams()) for (int id : t.getPlayers()) teamsAssociation.put(id, t.towerColor); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_GAME_SESSION, teamsAssociation, new GameState(Server.game))); c.sendResponseMessage(new Message(START_PLANNING_PHASE, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(0), null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } return new Message(FULL_TEAM, null, null); } /** * * @param playerId * @param assistantCardSpeedValue * @return */ public Message playAssistantCard(int playerId, int assistantCardSpeedValue) { if(Server.game.currentRound.getOrder().get(counter) == playerId) { if(Server.game.currentRound.playableCards(Server.game.getPlayerById(playerId)).contains(assistantCardSpeedValue)) { gameController.changeModel(playerId, assistantCardSpeedValue); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.getOrder().get(counter), null)); } } catch (IOException e) { e.printStackTrace(); } } else return new Message(UNPLAYABLE_ASSISTANT_CARD, null, null); if(counter == Server.game.getPlayerNumber()) { counter = 0; gameController.nextState(); gameController.changeModel(null, null); System.out.println("Establish round order\n" + Server.game.currentRound.getAssistantCardsPlayed()); gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param moves * @return */ public Message moveStudents(int playerId, List<ActionPhase1Move> moves) { System.out.println("Students movement\n" + Server.game.currentRound.getAssistantCardsPlayed()); if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, moves); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); c.sendResponseMessage(new Message(START_ACTION_PHASE_2, null, null)); } } catch (IOException e) { e.printStackTrace(); } gameController.nextState(); return new Message(ACK, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param islandId * @return */ public Message moveMotherNature(int playerId, int islandId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { int maxPossibleMoves = Server.game.currentRound.getAssistantCardsPlayed().get(playerId).getMoveValue(); if(Server.game.currentRound.currentTurn.card4Played) maxPossibleMoves += 2; int islandCounter = Server.game.getBoard().getMotherNatureIsland().getId(); for (int i = 0; i < maxPossibleMoves; i++) { if (islandCounter < Server.game.getBoard().getIslandGroups().size() - 1) islandCounter++; else islandCounter = 0; if(islandCounter == islandId) { System.out.println("Teams:" + Server.game.getTeamById(0).towerColor + " " + Server.game.getTeamById(1).towerColor); gameController.changeModel(islandId, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } if(!((MoveMotherNature) gameController.getState()).checkEndConditions()) { gameController.nextState(); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_3, null, null)); } } catch (IOException e) { e.printStackTrace(); } } else { gameController.nextState(); gameController.changeModel(null, null); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(END_GAME, Server.game.getTeamById(Server.game.winnerTeamId).towerColor, null)); } } catch (IOException e) { e.printStackTrace(); } } return new Message(ACK, null, null); } } return new Message(INVALID_MOVE, null, null); } return new Message(NOT_YOUR_TURN, null, null); } /** * * @param playerId * @param cloudId * @return */ public Message chooseCloudTile(int playerId, int cloudId) { if(Server.game.currentRound.currentTurn.getPlayerId() == playerId) { gameController.changeModel(playerId, cloudId); try { for (ClientHandler c : clients) { if(counter == Server.game.getPlayerNumber()-1) Server.game.currentRound.resetCardsPlayed(); c.sendResponseMessage(new Message(MODEL_CHANGED, new GameState(Server.game), null)); } } catch (IOException e) { e.printStackTrace(); } counter++; if(counter < Server.game.getPlayerNumber()) { gameController.nextState(); Server.game.currentRound.currentTurn = new PlayerTurn(Server.game.currentRound.getOrder().get(counter)); try { for (ClientHandler c : clients) { c.sendResponseMessage(new Message(START_ACTION_PHASE_1, null, null)); c.sendResponseMessage(new Message(NEW_TURN, Server.game.currentRound.currentTurn.getPlayerId(), null)); } } catch (IOException e) { e.printStackTrace(); } } else { ((ChooseCloudTile) gameController.getState()).mustEndRound = true; gameController.nextState();
if(!((NextRoundOrEndGame) gameController.getState()).checkEndConditions()) {
8
2023-11-06 00:50:18+00:00
12k
conductor-oss/conductor
rest/src/test/java/com/netflix/conductor/rest/controllers/WorkflowResourceTest.java
[ { "identifier": "RerunWorkflowRequest", "path": "common/src/main/java/com/netflix/conductor/common/metadata/workflow/RerunWorkflowRequest.java", "snippet": "@ProtoMessage\npublic class RerunWorkflowRequest {\n\n @ProtoField(id = 1)\n private String reRunFromWorkflowId;\n\n @ProtoField(id = 2)\n...
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import com.netflix.conductor.common.metadata.workflow.RerunWorkflowRequest; import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.service.WorkflowService; import com.netflix.conductor.service.WorkflowTestService; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
10,636
/* * Copyright 2020 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.rest.controllers; public class WorkflowResourceTest { @Mock private WorkflowService mockWorkflowService; @Mock private WorkflowTestService mockWorkflowTestService; private WorkflowResource workflowResource; @Before public void before() { this.mockWorkflowService = mock(WorkflowService.class); this.mockWorkflowTestService = mock(WorkflowTestService.class); this.workflowResource = new WorkflowResource(this.mockWorkflowService, this.mockWorkflowTestService); } @Test public void testStartWorkflow() { StartWorkflowRequest startWorkflowRequest = new StartWorkflowRequest(); startWorkflowRequest.setName("w123"); Map<String, Object> input = new HashMap<>(); input.put("1", "abc"); startWorkflowRequest.setInput(input); String workflowID = "w112"; when(mockWorkflowService.startWorkflow(any(StartWorkflowRequest.class))) .thenReturn(workflowID); assertEquals("w112", workflowResource.startWorkflow(startWorkflowRequest)); } @Test public void testStartWorkflowParam() { Map<String, Object> input = new HashMap<>(); input.put("1", "abc"); String workflowID = "w112"; when(mockWorkflowService.startWorkflow( anyString(), anyInt(), anyString(), anyInt(), anyMap())) .thenReturn(workflowID); assertEquals("w112", workflowResource.startWorkflow("test1", 1, "c123", 0, input)); } @Test public void getWorkflows() {
/* * Copyright 2020 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.rest.controllers; public class WorkflowResourceTest { @Mock private WorkflowService mockWorkflowService; @Mock private WorkflowTestService mockWorkflowTestService; private WorkflowResource workflowResource; @Before public void before() { this.mockWorkflowService = mock(WorkflowService.class); this.mockWorkflowTestService = mock(WorkflowTestService.class); this.workflowResource = new WorkflowResource(this.mockWorkflowService, this.mockWorkflowTestService); } @Test public void testStartWorkflow() { StartWorkflowRequest startWorkflowRequest = new StartWorkflowRequest(); startWorkflowRequest.setName("w123"); Map<String, Object> input = new HashMap<>(); input.put("1", "abc"); startWorkflowRequest.setInput(input); String workflowID = "w112"; when(mockWorkflowService.startWorkflow(any(StartWorkflowRequest.class))) .thenReturn(workflowID); assertEquals("w112", workflowResource.startWorkflow(startWorkflowRequest)); } @Test public void testStartWorkflowParam() { Map<String, Object> input = new HashMap<>(); input.put("1", "abc"); String workflowID = "w112"; when(mockWorkflowService.startWorkflow( anyString(), anyInt(), anyString(), anyInt(), anyMap())) .thenReturn(workflowID); assertEquals("w112", workflowResource.startWorkflow("test1", 1, "c123", 0, input)); } @Test public void getWorkflows() {
Workflow workflow = new Workflow();
2
2023-12-08 06:06:09+00:00
12k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/views/WallColorPreview.java
[ { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_ACCENT_SATURATION = \"monetAccentSaturationValue\";" }, { "identifier": "MONET_ACCURATE_SHADES", "path": "app/src/main/java/com/dr...
import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.SystemUtil; import java.util.ArrayList;
8,857
squarePaint.setStyle(Paint.Style.FILL); halfCirclePaint = new Paint(); halfCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_primary90)); halfCirclePaint.setStyle(Paint.Style.FILL); halfCirclePaint.setStrokeCap(Paint.Cap.BUTT); firstQuarterCirclePaint = new Paint(); firstQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_secondary90)); firstQuarterCirclePaint.setStyle(Paint.Style.FILL); firstQuarterCirclePaint.setStrokeCap(Paint.Cap.BUTT); secondQuarterCirclePaint = new Paint(); secondQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_tertiary90)); secondQuarterCirclePaint.setStyle(Paint.Style.FILL); secondQuarterCirclePaint.setStrokeCap(Paint.Cap.BUTT); centerCirclePaint = new Paint(); centerCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_primary70)); centerCirclePaint.setStyle(Paint.Style.FILL); centerClearCirclePaint = new Paint(); centerClearCirclePaint.setColor(ContextCompat.getColor(context, !isDarkMode ? com.google.android.material.R.color.material_dynamic_neutral99 : com.google.android.material.R.color.material_dynamic_neutral10 )); centerClearCirclePaint.setStyle(Paint.Style.FILL); tickPaint = new Paint(); tickPaint.setColor(ContextCompat.getColor(context, !isDarkMode ? com.google.android.material.R.color.material_dynamic_neutral99 : com.google.android.material.R.color.material_dynamic_neutral10 )); tickPaint.setStyle(Paint.Style.STROKE); tickPaint.setStrokeWidth(4); tickPaint.setStrokeCap(Paint.Cap.ROUND); } @Override protected void onDraw(@NonNull Canvas canvas) { super.onDraw(canvas); int width = getWidth(); int height = getHeight(); float cornerRadius = 12 * getResources().getDisplayMetrics().density; squareRect.set(0, 0, width, height); canvas.drawRoundRect(squareRect, cornerRadius, cornerRadius, squarePaint); float padding = 6 * getResources().getDisplayMetrics().density; float margin = 0 * getResources().getDisplayMetrics().density; circleRect.set(padding, padding, width - padding, height - padding - margin); canvas.drawArc(circleRect, 180, 180, true, halfCirclePaint); circleRect.set(padding, padding + margin, width - padding - margin, height - padding); canvas.drawArc(circleRect, 90, 90, true, firstQuarterCirclePaint); circleRect.set(padding + margin, padding + margin, width - padding, height - padding); canvas.drawArc(circleRect, 0, 90, true, secondQuarterCirclePaint); circleRect.set(width / 2f - clearCircleRadius, height / 2f - clearCircleRadius, width / 2f + clearCircleRadius, height / 2f + clearCircleRadius); canvas.drawArc(circleRect, 0, 360, true, centerClearCirclePaint); circleRect.set(width / 2f - circleRadius, height / 2f - circleRadius, width / 2f + circleRadius, height / 2f + circleRadius); canvas.drawCircle(width / 2f, height / 2f, circleRadius, centerCirclePaint); if (isSelected) { tickPath.moveTo(width / 2f - circleRadius / 2, height / 2f); tickPath.lineTo(width / 2f - circleRadius / 6, height / 2f + circleRadius / 3); tickPath.lineTo(width / 2f + circleRadius / 2, height / 2f - circleRadius / 3); canvas.drawPath(tickPath, tickPaint); } } private void setSquareColor(@ColorInt int color) { squarePaint.setColor(color); centerClearCirclePaint.setColor(color); } private void setFirstQuarterCircleColor(@ColorInt int color) { firstQuarterCirclePaint.setColor(color); } private void setSecondQuarterCircleColor(@ColorInt int color) { secondQuarterCirclePaint.setColor(color); } private void setHalfCircleColor(@ColorInt int color) { halfCirclePaint.setColor(color); } private void setCenterCircleColor(@ColorInt int color) { centerCirclePaint.setColor(color); @ColorInt int textColor = ColorUtil.calculateTextColor(color); tickPaint.setColor( colorPalette != null ? colorPalette.get(4).get(textColor == Color.WHITE ? 2 : 11) : textColor ); } private void invalidateColors() { invalidate(); } public void setMainColor(@ColorInt int color) { new Thread(() -> { try { colorPalette = ColorUtil.generateModifiedColors( ColorSchemeUtil.stringToEnumMonetStyle( context, RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot)) ), color, RPrefs.getInt(MONET_ACCENT_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100),
package com.drdisagree.colorblendr.ui.views; public class WallColorPreview extends View { private Context context; private boolean isDarkMode; private Paint tickPaint, squarePaint, centerCirclePaint, centerClearCirclePaint, secondQuarterCirclePaint, firstQuarterCirclePaint, halfCirclePaint; private RectF squareRect, circleRect; private Path tickPath; private float clearCircleRadius, circleRadius; private boolean isSelected = false; private ArrayList<ArrayList<Integer>> colorPalette; public WallColorPreview(Context context) { super(context); init(context); } public WallColorPreview(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public WallColorPreview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { this.context = context; isDarkMode = (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) == Configuration.UI_MODE_NIGHT_YES; circleRadius = 10 * getResources().getDisplayMetrics().density; clearCircleRadius = circleRadius + 0 * getResources().getDisplayMetrics().density; squareRect = new RectF(); circleRect = new RectF(); tickPath = new Path(); squarePaint = new Paint(); squarePaint.setColor(ContextCompat.getColor(context, !isDarkMode ? com.google.android.material.R.color.material_dynamic_neutral99 : com.google.android.material.R.color.material_dynamic_neutral10 )); squarePaint.setStyle(Paint.Style.FILL); halfCirclePaint = new Paint(); halfCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_primary90)); halfCirclePaint.setStyle(Paint.Style.FILL); halfCirclePaint.setStrokeCap(Paint.Cap.BUTT); firstQuarterCirclePaint = new Paint(); firstQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_secondary90)); firstQuarterCirclePaint.setStyle(Paint.Style.FILL); firstQuarterCirclePaint.setStrokeCap(Paint.Cap.BUTT); secondQuarterCirclePaint = new Paint(); secondQuarterCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_tertiary90)); secondQuarterCirclePaint.setStyle(Paint.Style.FILL); secondQuarterCirclePaint.setStrokeCap(Paint.Cap.BUTT); centerCirclePaint = new Paint(); centerCirclePaint.setColor(ContextCompat.getColor(context, com.google.android.material.R.color.material_dynamic_primary70)); centerCirclePaint.setStyle(Paint.Style.FILL); centerClearCirclePaint = new Paint(); centerClearCirclePaint.setColor(ContextCompat.getColor(context, !isDarkMode ? com.google.android.material.R.color.material_dynamic_neutral99 : com.google.android.material.R.color.material_dynamic_neutral10 )); centerClearCirclePaint.setStyle(Paint.Style.FILL); tickPaint = new Paint(); tickPaint.setColor(ContextCompat.getColor(context, !isDarkMode ? com.google.android.material.R.color.material_dynamic_neutral99 : com.google.android.material.R.color.material_dynamic_neutral10 )); tickPaint.setStyle(Paint.Style.STROKE); tickPaint.setStrokeWidth(4); tickPaint.setStrokeCap(Paint.Cap.ROUND); } @Override protected void onDraw(@NonNull Canvas canvas) { super.onDraw(canvas); int width = getWidth(); int height = getHeight(); float cornerRadius = 12 * getResources().getDisplayMetrics().density; squareRect.set(0, 0, width, height); canvas.drawRoundRect(squareRect, cornerRadius, cornerRadius, squarePaint); float padding = 6 * getResources().getDisplayMetrics().density; float margin = 0 * getResources().getDisplayMetrics().density; circleRect.set(padding, padding, width - padding, height - padding - margin); canvas.drawArc(circleRect, 180, 180, true, halfCirclePaint); circleRect.set(padding, padding + margin, width - padding - margin, height - padding); canvas.drawArc(circleRect, 90, 90, true, firstQuarterCirclePaint); circleRect.set(padding + margin, padding + margin, width - padding, height - padding); canvas.drawArc(circleRect, 0, 90, true, secondQuarterCirclePaint); circleRect.set(width / 2f - clearCircleRadius, height / 2f - clearCircleRadius, width / 2f + clearCircleRadius, height / 2f + clearCircleRadius); canvas.drawArc(circleRect, 0, 360, true, centerClearCirclePaint); circleRect.set(width / 2f - circleRadius, height / 2f - circleRadius, width / 2f + circleRadius, height / 2f + circleRadius); canvas.drawCircle(width / 2f, height / 2f, circleRadius, centerCirclePaint); if (isSelected) { tickPath.moveTo(width / 2f - circleRadius / 2, height / 2f); tickPath.lineTo(width / 2f - circleRadius / 6, height / 2f + circleRadius / 3); tickPath.lineTo(width / 2f + circleRadius / 2, height / 2f - circleRadius / 3); canvas.drawPath(tickPath, tickPaint); } } private void setSquareColor(@ColorInt int color) { squarePaint.setColor(color); centerClearCirclePaint.setColor(color); } private void setFirstQuarterCircleColor(@ColorInt int color) { firstQuarterCirclePaint.setColor(color); } private void setSecondQuarterCircleColor(@ColorInt int color) { secondQuarterCirclePaint.setColor(color); } private void setHalfCircleColor(@ColorInt int color) { halfCirclePaint.setColor(color); } private void setCenterCircleColor(@ColorInt int color) { centerCirclePaint.setColor(color); @ColorInt int textColor = ColorUtil.calculateTextColor(color); tickPaint.setColor( colorPalette != null ? colorPalette.get(4).get(textColor == Color.WHITE ? 2 : 11) : textColor ); } private void invalidateColors() { invalidate(); } public void setMainColor(@ColorInt int color) { new Thread(() -> { try { colorPalette = ColorUtil.generateModifiedColors( ColorSchemeUtil.stringToEnumMonetStyle( context, RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot)) ), color, RPrefs.getInt(MONET_ACCENT_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100), RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100),
RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false),
4
2023-12-06 13:20:16+00:00
12k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/dupe/MenuItemMarker.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.dupe.marker.ItemMarker; import com.extendedclip.deluxemenus.dupe.marker.impl.NMSMenuItemMarker; import com.extendedclip.deluxemenus.dupe.marker.impl.PDCMenuItemMarker; import com.extendedclip.deluxemenus.dupe.marker.impl.UnavailableMenuItemMarker; import com.extendedclip.deluxemenus.nbt.NbtProvider; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.VersionHelper; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.logging.Level; import java.util.regex.Pattern;
8,491
package com.extendedclip.deluxemenus.dupe; public class MenuItemMarker implements ItemMarker { private final static String DEFAULT_MARK = "DM"; private final static Pattern MARK_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$");
package com.extendedclip.deluxemenus.dupe; public class MenuItemMarker implements ItemMarker { private final static String DEFAULT_MARK = "DM"; private final static Pattern MARK_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$");
private final static boolean SUPPORTS_PDC = VersionHelper.IS_PDC_VERSION;
7
2023-12-14 23:41:07+00:00
12k
lxs2601055687/contextAdminRuoYi
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java
[ { "identifier": "BaseController", "path": "ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java", "snippet": "public class BaseController {\n\n /**\n * 响应返回结果\n *\n * @param rows 影响行数\n * @return 操作结果\n */\n protected R<Void> toAjax(int rows) {\n ...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.entity.SysDictData; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.system.service.ISysDictDataService; import com.ruoyi.system.service.ISysDictTypeService; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List;
7,519
package com.ruoyi.web.controller.system; /** * 数据字典信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/dict/data") public class SysDictDataController extends BaseController { private final ISysDictDataService dictDataService; private final ISysDictTypeService dictTypeService; /** * 查询字典数据列表 */ @SaCheckPermission("system:dict:list") @GetMapping("/list")
package com.ruoyi.web.controller.system; /** * 数据字典信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/dict/data") public class SysDictDataController extends BaseController { private final ISysDictDataService dictDataService; private final ISysDictTypeService dictTypeService; /** * 查询字典数据列表 */ @SaCheckPermission("system:dict:list") @GetMapping("/list")
public TableDataInfo<SysDictData> list(SysDictData dictData, PageQuery pageQuery) {
3
2023-12-07 12:06:21+00:00
12k
Earthcomputer/ModCompatChecker
root/src/main/java/net/earthcomputer/modcompatchecker/checker/indy/LambdaMetafactoryChecker.java
[ { "identifier": "Errors", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/checker/Errors.java", "snippet": "public enum Errors {\n CLASS_EXTENDS_REMOVED(\"Superclass %s is removed\"),\n CLASS_EXTENDS_FINAL(\"Superclass %s is final\"),\n CLASS_EXTENDS_INTERFACE(\"Superclass %s is ...
import net.earthcomputer.modcompatchecker.checker.Errors; import net.earthcomputer.modcompatchecker.indexer.IResolvedClass; import net.earthcomputer.modcompatchecker.util.AccessFlags; import net.earthcomputer.modcompatchecker.util.AccessLevel; import net.earthcomputer.modcompatchecker.util.AsmUtil; import net.earthcomputer.modcompatchecker.util.ClassMember; import net.earthcomputer.modcompatchecker.util.InheritanceUtil; import net.earthcomputer.modcompatchecker.util.OwnedClassMember; import net.earthcomputer.modcompatchecker.util.UnimplementedMethodChecker; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.lang.invoke.LambdaMetafactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
7,654
package net.earthcomputer.modcompatchecker.checker.indy; public enum LambdaMetafactoryChecker implements IndyChecker { INSTANCE; @Override public void check(IndyContext context) { List<String> interfaces = new ArrayList<>(); List<String> interfaceMethodDescs = new ArrayList<>(); Type interfaceType = Type.getReturnType(context.descriptor()); if (interfaceType.getSort() != Type.OBJECT) { return; } interfaces.add(interfaceType.getInternalName()); String interfaceMethodName = context.name(); if (!(context.args()[0] instanceof Type interfaceMethodType)) { return; } interfaceMethodDescs.add(interfaceMethodType.getDescriptor()); if ("altMetafactory".equals(context.bsm().getName())) { if (!(context.args()[3] instanceof Integer flags)) { return; } int argIndex = 4; if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) { if (!(context.args()[argIndex++] instanceof Integer markerCount)) { return; } for (int i = 0; i < markerCount; i++) { if (!(context.args()[argIndex++] instanceof Type itfType)) { return; } if (itfType.getSort() != Type.OBJECT) { return; } interfaces.add(itfType.getInternalName()); } } if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) { if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) { return; } for (int i = 0; i < bridgeCount; i++) { if (!(context.args()[argIndex++] instanceof Type bridgeType)) { return; } if (bridgeType.getSort() != Type.METHOD) { return; } interfaceMethodDescs.add(bridgeType.getDescriptor()); } } } for (String interfaceName : interfaces) { IResolvedClass resolvedInterface = context.index().findClass(interfaceName); if (resolvedInterface == null) { context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName); continue; } if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) { context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName()); } if (!resolvedInterface.getAccess().isInterface()) { context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName); } } UnimplementedMethodChecker checker = new UnimplementedMethodChecker(context.index(), AsmUtil.OBJECT, interfaces.toArray(String[]::new)) { @Override
package net.earthcomputer.modcompatchecker.checker.indy; public enum LambdaMetafactoryChecker implements IndyChecker { INSTANCE; @Override public void check(IndyContext context) { List<String> interfaces = new ArrayList<>(); List<String> interfaceMethodDescs = new ArrayList<>(); Type interfaceType = Type.getReturnType(context.descriptor()); if (interfaceType.getSort() != Type.OBJECT) { return; } interfaces.add(interfaceType.getInternalName()); String interfaceMethodName = context.name(); if (!(context.args()[0] instanceof Type interfaceMethodType)) { return; } interfaceMethodDescs.add(interfaceMethodType.getDescriptor()); if ("altMetafactory".equals(context.bsm().getName())) { if (!(context.args()[3] instanceof Integer flags)) { return; } int argIndex = 4; if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) { if (!(context.args()[argIndex++] instanceof Integer markerCount)) { return; } for (int i = 0; i < markerCount; i++) { if (!(context.args()[argIndex++] instanceof Type itfType)) { return; } if (itfType.getSort() != Type.OBJECT) { return; } interfaces.add(itfType.getInternalName()); } } if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) { if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) { return; } for (int i = 0; i < bridgeCount; i++) { if (!(context.args()[argIndex++] instanceof Type bridgeType)) { return; } if (bridgeType.getSort() != Type.METHOD) { return; } interfaceMethodDescs.add(bridgeType.getDescriptor()); } } } for (String interfaceName : interfaces) { IResolvedClass resolvedInterface = context.index().findClass(interfaceName); if (resolvedInterface == null) { context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName); continue; } if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) { context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName()); } if (!resolvedInterface.getAccess().isInterface()) { context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName); } } UnimplementedMethodChecker checker = new UnimplementedMethodChecker(context.index(), AsmUtil.OBJECT, interfaces.toArray(String[]::new)) { @Override
protected boolean isMethodAccessible(String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) {
3
2023-12-11 00:48:12+00:00
12k
HzlGauss/bulls
src/main/java/com/bulls/qa/service/PioneerService.java
[ { "identifier": "RequestConfigs", "path": "src/main/java/com/bulls/qa/configuration/RequestConfigs.java", "snippet": "@Data\n@Configuration\n@Component\n@PropertySource(factory = YamlPropertySourceFactory.class, value = {\"testerhome.yml\"})\n//@PropertySource(factory = YamlPropertySourceFactory.class, ...
import com.bulls.qa.configuration.RequestConfigs; import com.bulls.qa.request.Request; import com.bulls.qa.configuration.PioneerConfig; import io.restassured.RestAssured; import io.restassured.filter.FilterContext; import io.restassured.response.Response; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; import io.restassured.spi.AuthFilter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.*;
9,381
package com.bulls.qa.service; @Service public class PioneerService { @Autowired private RequestConfigs requestConfigs; @Value("${miria.cookie:abc}") String buildinCookie; @Autowired private Environment env; private static Environment staticEnv; public static String getProperty(String key) { return staticEnv.getProperty(key); } public static void handle(PioneerConfig pioneerConfig, RequestConfigs requestConfigs) {
package com.bulls.qa.service; @Service public class PioneerService { @Autowired private RequestConfigs requestConfigs; @Value("${miria.cookie:abc}") String buildinCookie; @Autowired private Environment env; private static Environment staticEnv; public static String getProperty(String key) { return staticEnv.getProperty(key); } public static void handle(PioneerConfig pioneerConfig, RequestConfigs requestConfigs) {
Request request = Request.getInstance(pioneerConfig);
1
2023-12-14 06:54:24+00:00
12k
DantSu/studio
driver/src/main/java/studio/driver/fs/FsStoryTellerAsyncDriver.java
[ { "identifier": "transformUuid", "path": "core/src/main/java/studio/core/v1/writer/fs/FsStoryPackWriter.java", "snippet": "public static String transformUuid(String uuid) {\n String uuidStr = uuid.replace(\"-\", \"\");\n return uuidStr.substring(uuidStr.length()-8).toUpperCase();\n}" }, { ...
import static studio.core.v1.writer.fs.FsStoryPackWriter.transformUuid; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import studio.core.v1.utils.AESCBCCipher; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.XXTEACipher; import studio.core.v1.utils.exception.StoryTellerException; import studio.core.v1.utils.stream.ThrowingConsumer; import studio.core.v1.writer.fs.FsStoryPackWriter; import studio.core.v1.writer.fs.FsStoryPackWriterV3; import studio.driver.DeviceVersion; import studio.driver.LibUsbDetectionHelper; import studio.driver.StoryTellerAsyncDriver; import studio.driver.event.DevicePluggedListener; import studio.driver.event.DeviceUnpluggedListener; import studio.driver.event.TransferProgressListener; import studio.driver.model.TransferStatus; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos;
10,442
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.fs; public class FsStoryTellerAsyncDriver implements StoryTellerAsyncDriver<FsDeviceInfos, FsStoryPackInfos> { private static final Logger LOGGER = LogManager.getLogger(FsStoryTellerAsyncDriver.class); private static final String DEVICE_METADATA_FILENAME = ".md"; private static final String PACK_INDEX_FILENAME = ".pi"; private static final String CONTENT_FOLDER = ".content"; private static final String NODE_INDEX_FILENAME = "ni"; private static final String NIGHT_MODE_FILENAME = "nm"; private static final long FS_MOUNTPOINT_POLL_DELAY = 1000L; private static final long FS_MOUNTPOINT_RETRY = 10; private Device device = null; private Path partitionMountPoint = null; private List<DevicePluggedListener> pluggedlisteners = new ArrayList<>(); private List<DeviceUnpluggedListener> unpluggedlisteners = new ArrayList<>(); public FsStoryTellerAsyncDriver() { // Initialize libusb, handle and propagate hotplug events LOGGER.debug("Registering hotplug listener"); LibUsbDetectionHelper.initializeLibUsb(DeviceVersion.DEVICE_VERSION_2, // device2 -> { // Wait for a partition to be mounted which contains the .md file LOGGER.debug("Waiting for device partition..."); for (int i = 0; i < FS_MOUNTPOINT_RETRY && partitionMountPoint == null; i++) { try { Thread.sleep(FS_MOUNTPOINT_POLL_DELAY); DeviceUtils.listMountPoints().forEach(path -> { LOGGER.trace("Looking for .md in {}", path); if (Files.exists(path.resolve(DEVICE_METADATA_FILENAME))) { partitionMountPoint = path; LOGGER.info("FS device partition located: {}", partitionMountPoint); } }); } catch (InterruptedException e) { LOGGER.error("Failed to locate device partition", e); Thread.currentThread().interrupt(); } } if (partitionMountPoint == null) {
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.fs; public class FsStoryTellerAsyncDriver implements StoryTellerAsyncDriver<FsDeviceInfos, FsStoryPackInfos> { private static final Logger LOGGER = LogManager.getLogger(FsStoryTellerAsyncDriver.class); private static final String DEVICE_METADATA_FILENAME = ".md"; private static final String PACK_INDEX_FILENAME = ".pi"; private static final String CONTENT_FOLDER = ".content"; private static final String NODE_INDEX_FILENAME = "ni"; private static final String NIGHT_MODE_FILENAME = "nm"; private static final long FS_MOUNTPOINT_POLL_DELAY = 1000L; private static final long FS_MOUNTPOINT_RETRY = 10; private Device device = null; private Path partitionMountPoint = null; private List<DevicePluggedListener> pluggedlisteners = new ArrayList<>(); private List<DeviceUnpluggedListener> unpluggedlisteners = new ArrayList<>(); public FsStoryTellerAsyncDriver() { // Initialize libusb, handle and propagate hotplug events LOGGER.debug("Registering hotplug listener"); LibUsbDetectionHelper.initializeLibUsb(DeviceVersion.DEVICE_VERSION_2, // device2 -> { // Wait for a partition to be mounted which contains the .md file LOGGER.debug("Waiting for device partition..."); for (int i = 0; i < FS_MOUNTPOINT_RETRY && partitionMountPoint == null; i++) { try { Thread.sleep(FS_MOUNTPOINT_POLL_DELAY); DeviceUtils.listMountPoints().forEach(path -> { LOGGER.trace("Looking for .md in {}", path); if (Files.exists(path.resolve(DEVICE_METADATA_FILENAME))) { partitionMountPoint = path; LOGGER.info("FS device partition located: {}", partitionMountPoint); } }); } catch (InterruptedException e) { LOGGER.error("Failed to locate device partition", e); Thread.currentThread().interrupt(); } } if (partitionMountPoint == null) {
throw new StoryTellerException("Could not locate device partition");
4
2023-12-14 15:08:35+00:00
12k
conductor-oss/conductor-community
event-queue/amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueueTest.java
[ { "identifier": "AMQPEventQueueProperties", "path": "event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPEventQueueProperties.java", "snippet": "@ConfigurationProperties(\"conductor.event-queues.amqp\")\npublic class AMQPEventQueueProperties {\n\n private int batchSize...
import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.DoesNothing; import org.mockito.stubbing.OngoingStubbing; import com.netflix.conductor.contribs.queue.amqp.config.AMQPEventQueueProperties; import com.netflix.conductor.contribs.queue.amqp.config.AMQPRetryPattern; import com.netflix.conductor.contribs.queue.amqp.util.AMQPConstants; import com.netflix.conductor.contribs.queue.amqp.util.AMQPSettings; import com.netflix.conductor.contribs.queue.amqp.util.RetryType; import com.netflix.conductor.core.events.queue.Message; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AMQP.PROTOCOL; import com.rabbitmq.client.AMQP.Queue.DeclareOk; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.impl.AMQImpl; import rx.Observable; import rx.observers.Subscribers; import rx.observers.TestSubscriber; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
8,070
getResponseOngoingStubbing.thenThrow( new IOException("Not working"), new RuntimeException("Not working")); } // basicPublish if (isWorking) { doNothing() .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } else { doThrow(new IOException("Not working")) .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } return channel; } Connection mockGoodConnection(Channel channel) throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); when(connection.isOpen()).thenReturn(Boolean.TRUE); /* * doAnswer(invocation -> { when(connection.isOpen()).thenReturn(Boolean.FALSE); * return DoesNothing.doesNothing(); }).when(connection).close(); */ return connection; } Connection mockBadConnection() throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenThrow(new IOException("Can't create channel")); when(connection.isOpen()).thenReturn(Boolean.TRUE); doThrow(new IOException("Can't close connection")).when(connection).close(); return connection; } ConnectionFactory mockConnectionFactory(Connection connection) throws IOException, TimeoutException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection(eq(addresses), Mockito.anyString())) .thenReturn(connection); return connectionFactory; } void runObserve( Channel channel, AMQPObservableQueue observableQueue, String queueName, boolean useWorkingChannel, int batchSize) throws IOException { final List<Message> found = new ArrayList<>(batchSize); TestSubscriber<Message> subscriber = TestSubscriber.create(Subscribers.create(found::add)); rx.Observable<Message> observable = observableQueue.observe().take(pollTimeMs * 2, TimeUnit.MILLISECONDS); assertNotNull(observable); observable.subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); subscriber.assertCompleted(); if (useWorkingChannel) { verify(channel, atLeast(1)) .basicConsume(eq(queueName), anyBoolean(), any(Consumer.class)); doNothing().when(channel).basicAck(anyLong(), eq(false)); doAnswer(DoesNothing.doesNothing()).when(channel).basicAck(anyLong(), eq(false)); observableQueue.ack(Collections.synchronizedList(found)); } else { assertNotNull(found); assertTrue(found.isEmpty()); } observableQueue.close(); } @Test public void testGetMessagesFromExistingExchangeWithDurableExclusiveAutoDeleteQueueConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndCustomConfigurationFromURI( channel, connection, true, true, true, true, true); } @Test public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndDefaultConfiguration(channel, connection, true, true); } @Test public void testPublishMessagesToNotExistingExchangeAndDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testPublishMessagesToExchangeAndDefaultConfiguration(channel, connection, false, true); } @Test public void testAck() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); AMQPRetryPattern retrySettings = null;
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.queue.amqp; @SuppressWarnings({"rawtypes", "unchecked"}) public class AMQPObservableQueueTest { final int batchSize = 10; final int pollTimeMs = 500; Address[] addresses; AMQPEventQueueProperties properties; @Before public void setUp() { properties = mock(AMQPEventQueueProperties.class); when(properties.getBatchSize()).thenReturn(1); when(properties.getPollTimeDuration()).thenReturn(Duration.ofMillis(100)); when(properties.getHosts()).thenReturn(ConnectionFactory.DEFAULT_HOST); when(properties.getUsername()).thenReturn(ConnectionFactory.DEFAULT_USER); when(properties.getPassword()).thenReturn(ConnectionFactory.DEFAULT_PASS); when(properties.getVirtualHost()).thenReturn(ConnectionFactory.DEFAULT_VHOST); when(properties.getPort()).thenReturn(PROTOCOL.PORT); when(properties.getConnectionTimeoutInMilliSecs()).thenReturn(60000); when(properties.isUseNio()).thenReturn(false); when(properties.isDurable()).thenReturn(true); when(properties.isExclusive()).thenReturn(false); when(properties.isAutoDelete()).thenReturn(false); when(properties.getContentType()).thenReturn("application/json"); when(properties.getContentEncoding()).thenReturn("UTF-8"); when(properties.getExchangeType()).thenReturn("topic"); when(properties.getDeliveryMode()).thenReturn(2); when(properties.isUseExchange()).thenReturn(true); addresses = new Address[] {new Address("localhost", PROTOCOL.PORT)}; AMQPConnection.setAMQPConnection(null); } List<GetResponse> buildQueue(final Random random, final int bound) { final LinkedList<GetResponse> queue = new LinkedList(); for (int i = 0; i < bound; i++) { AMQP.BasicProperties props = mock(AMQP.BasicProperties.class); when(props.getMessageId()).thenReturn(UUID.randomUUID().toString()); Envelope envelope = mock(Envelope.class); when(envelope.getDeliveryTag()).thenReturn(random.nextLong()); GetResponse response = mock(GetResponse.class); when(response.getProps()).thenReturn(props); when(response.getEnvelope()).thenReturn(envelope); when(response.getBody()).thenReturn("{}".getBytes()); when(response.getMessageCount()).thenReturn(bound - i); queue.add(response); } return queue; } Channel mockBaseChannel() throws IOException, TimeoutException { Channel channel = mock(Channel.class); when(channel.isOpen()).thenReturn(Boolean.TRUE); /* * doAnswer(invocation -> { when(channel.isOpen()).thenReturn(Boolean.FALSE); * return DoesNothing.doesNothing(); }).when(channel).close(); */ return channel; } Channel mockChannelForQueue( Channel channel, boolean isWorking, boolean exists, String name, List<GetResponse> queue) throws IOException { // queueDeclarePassive final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(name, queue.size(), 1); if (exists) { when(channel.queueDeclarePassive(eq(name))).thenReturn(queueDeclareOK); } else { when(channel.queueDeclarePassive(eq(name))) .thenThrow(new IOException("Queue " + name + " exists")); } // queueDeclare OngoingStubbing<DeclareOk> declareOkOngoingStubbing = when(channel.queueDeclare( eq(name), anyBoolean(), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(queueDeclareOK); if (!isWorking) { declareOkOngoingStubbing.thenThrow( new IOException("Cannot declare queue " + name), new RuntimeException("Not working")); } // messageCount when(channel.messageCount(eq(name))).thenReturn((long) queue.size()); // basicGet OngoingStubbing<String> getResponseOngoingStubbing = Mockito.when(channel.basicConsume(eq(name), anyBoolean(), any(Consumer.class))) .thenReturn(name); if (!isWorking) { getResponseOngoingStubbing.thenThrow( new IOException("Not working"), new RuntimeException("Not working")); } // basicPublish if (isWorking) { doNothing() .when(channel) .basicPublish( eq(StringUtils.EMPTY), eq(name), any(AMQP.BasicProperties.class), any(byte[].class)); } else { doThrow(new IOException("Not working")) .when(channel) .basicPublish( eq(StringUtils.EMPTY), eq(name), any(AMQP.BasicProperties.class), any(byte[].class)); } return channel; } Channel mockChannelForExchange( Channel channel, boolean isWorking, boolean exists, String queueName, String name, String type, String routingKey, List<GetResponse> queue) throws IOException { // exchangeDeclarePassive final AMQImpl.Exchange.DeclareOk exchangeDeclareOK = new AMQImpl.Exchange.DeclareOk(); if (exists) { when(channel.exchangeDeclarePassive(eq(name))).thenReturn(exchangeDeclareOK); } else { when(channel.exchangeDeclarePassive(eq(name))) .thenThrow(new IOException("Exchange " + name + " exists")); } // exchangeDeclare OngoingStubbing<AMQP.Exchange.DeclareOk> declareOkOngoingStubbing = when(channel.exchangeDeclare( eq(name), eq(type), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(exchangeDeclareOK); if (!isWorking) { declareOkOngoingStubbing.thenThrow( new IOException("Cannot declare exchange " + name + " of type " + type), new RuntimeException("Not working")); } // queueDeclarePassive final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(queueName, queue.size(), 1); if (exists) { when(channel.queueDeclarePassive(eq(queueName))).thenReturn(queueDeclareOK); } else { when(channel.queueDeclarePassive(eq(queueName))) .thenThrow(new IOException("Queue " + queueName + " exists")); } // queueDeclare when(channel.queueDeclare( eq(queueName), anyBoolean(), anyBoolean(), anyBoolean(), anyMap())) .thenReturn(queueDeclareOK); // queueBind when(channel.queueBind(eq(queueName), eq(name), eq(routingKey))) .thenReturn(new AMQImpl.Queue.BindOk()); // messageCount when(channel.messageCount(eq(name))).thenReturn((long) queue.size()); // basicGet OngoingStubbing<String> getResponseOngoingStubbing = Mockito.when(channel.basicConsume(eq(queueName), anyBoolean(), any(Consumer.class))) .thenReturn(queueName); if (!isWorking) { getResponseOngoingStubbing.thenThrow( new IOException("Not working"), new RuntimeException("Not working")); } // basicPublish if (isWorking) { doNothing() .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } else { doThrow(new IOException("Not working")) .when(channel) .basicPublish( eq(name), eq(routingKey), any(AMQP.BasicProperties.class), any(byte[].class)); } return channel; } Connection mockGoodConnection(Channel channel) throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); when(connection.isOpen()).thenReturn(Boolean.TRUE); /* * doAnswer(invocation -> { when(connection.isOpen()).thenReturn(Boolean.FALSE); * return DoesNothing.doesNothing(); }).when(connection).close(); */ return connection; } Connection mockBadConnection() throws IOException { Connection connection = mock(Connection.class); when(connection.createChannel()).thenThrow(new IOException("Can't create channel")); when(connection.isOpen()).thenReturn(Boolean.TRUE); doThrow(new IOException("Can't close connection")).when(connection).close(); return connection; } ConnectionFactory mockConnectionFactory(Connection connection) throws IOException, TimeoutException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection(eq(addresses), Mockito.anyString())) .thenReturn(connection); return connectionFactory; } void runObserve( Channel channel, AMQPObservableQueue observableQueue, String queueName, boolean useWorkingChannel, int batchSize) throws IOException { final List<Message> found = new ArrayList<>(batchSize); TestSubscriber<Message> subscriber = TestSubscriber.create(Subscribers.create(found::add)); rx.Observable<Message> observable = observableQueue.observe().take(pollTimeMs * 2, TimeUnit.MILLISECONDS); assertNotNull(observable); observable.subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); subscriber.assertCompleted(); if (useWorkingChannel) { verify(channel, atLeast(1)) .basicConsume(eq(queueName), anyBoolean(), any(Consumer.class)); doNothing().when(channel).basicAck(anyLong(), eq(false)); doAnswer(DoesNothing.doesNothing()).when(channel).basicAck(anyLong(), eq(false)); observableQueue.ack(Collections.synchronizedList(found)); } else { assertNotNull(found); assertTrue(found.isEmpty()); } observableQueue.close(); } @Test public void testGetMessagesFromExistingExchangeWithDurableExclusiveAutoDeleteQueueConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndCustomConfigurationFromURI( channel, connection, true, true, true, true, true); } @Test public void testGetMessagesFromExistingExchangeWithDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testGetMessagesFromExchangeAndDefaultConfiguration(channel, connection, true, true); } @Test public void testPublishMessagesToNotExistingExchangeAndDefaultConfiguration() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); testPublishMessagesToExchangeAndDefaultConfiguration(channel, connection, false, true); } @Test public void testAck() throws IOException, TimeoutException { // Mock channel and connection Channel channel = mockBaseChannel(); Connection connection = mockGoodConnection(channel); final Random random = new Random(); final String name = RandomStringUtils.randomAlphabetic(30), type = "topic", routingKey = RandomStringUtils.randomAlphabetic(30); AMQPRetryPattern retrySettings = null;
final AMQPSettings settings =
3
2023-12-08 06:06:20+00:00
12k
i-moonlight/Movie_Manager
backend/src/test/java/ch/xxx/moviemanager/adapter/controller/MovieControllerTest.java
[ { "identifier": "SecurityConfig", "path": "backend/src/main/java/ch/xxx/moviemanager/adapter/config/SecurityConfig.java", "snippet": "@Configuration\n@EnableWebSecurity\n@Order(SecurityProperties.DEFAULT_FILTER_ORDER)\npublic class SecurityConfig {\n\tprivate final JwtTokenService jwtTokenService;\n\n\t...
import static org.mockito.ArgumentMatchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; import java.util.Optional; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import ch.xxx.moviemanager.adapter.config.SecurityConfig; import ch.xxx.moviemanager.domain.common.Role; import ch.xxx.moviemanager.domain.model.entity.Movie; import ch.xxx.moviemanager.domain.utils.JwtUtils; import ch.xxx.moviemanager.usecase.mapper.DefaultMapper; import ch.xxx.moviemanager.usecase.service.JwtTokenService; import ch.xxx.moviemanager.usecase.service.MovieService; import jakarta.servlet.http.HttpServletRequest;
8,159
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.moviemanager.adapter.controller; @WebMvcTest(controllers = MovieController.class, includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { SecurityConfig.class, JwtTokenService.class })) @WithMockUser public class MovieControllerTest { private static final String TEST_SECRECT_KEY = "w1a7WlSUrqEfDvlVd47SGlwSb9CJk1BymiIhXXZP82MyNNxsY1krgpb0bQt-Z9uohLRR6afgBsRHP_qiaHQhb" + "wFNWJeTTWr1x28hABtuvbRGMdW9ihvM_8JpVDhwuFbr2YCUW_nBeqJwcT9h6024RB7gJRYdxy1R6-onq9VG-TAJ00lrsfpnWWWn7LSLoxkj4gxeLTaF_0hozjoZ" +"90sTm3loeS0CfX2MgXi-UAdjsGG4ki40iw4wWrKverKUtZQPotcvObtTGdAEx4DfTGdU0ZK7O9IY9xxddoGxPgG9l2_ahhPjfqMJYPY-TuI_UXiKfbFhnRTrdg8GtXyU0G3GJQ=="; @Autowired private MockMvc mockMvc; @MockBean private MovieService service; @MockBean private JwtTokenService jwtTokenService; @MockBean private DefaultMapper defaultMapper; @SuppressWarnings("unchecked") @BeforeEach public void init() { Mockito.when(this.defaultMapper.convertOnlyMovie(any(Movie.class))).thenCallRealMethod(); Mockito.when(this.defaultMapper.convert(any(Movie.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.createToken(any(String.class), any(List.class), any(Optional.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.validateToken(any(String.class))).thenReturn(true); Mockito.when(this.jwtTokenService.resolveToken(any(HttpServletRequest.class))).thenReturn(Optional.of("")); Mockito.when(this.jwtTokenService.getAuthentication(any(String.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.getUsername(any(String.class))).thenReturn("XXX");
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.moviemanager.adapter.controller; @WebMvcTest(controllers = MovieController.class, includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { SecurityConfig.class, JwtTokenService.class })) @WithMockUser public class MovieControllerTest { private static final String TEST_SECRECT_KEY = "w1a7WlSUrqEfDvlVd47SGlwSb9CJk1BymiIhXXZP82MyNNxsY1krgpb0bQt-Z9uohLRR6afgBsRHP_qiaHQhb" + "wFNWJeTTWr1x28hABtuvbRGMdW9ihvM_8JpVDhwuFbr2YCUW_nBeqJwcT9h6024RB7gJRYdxy1R6-onq9VG-TAJ00lrsfpnWWWn7LSLoxkj4gxeLTaF_0hozjoZ" +"90sTm3loeS0CfX2MgXi-UAdjsGG4ki40iw4wWrKverKUtZQPotcvObtTGdAEx4DfTGdU0ZK7O9IY9xxddoGxPgG9l2_ahhPjfqMJYPY-TuI_UXiKfbFhnRTrdg8GtXyU0G3GJQ=="; @Autowired private MockMvc mockMvc; @MockBean private MovieService service; @MockBean private JwtTokenService jwtTokenService; @MockBean private DefaultMapper defaultMapper; @SuppressWarnings("unchecked") @BeforeEach public void init() { Mockito.when(this.defaultMapper.convertOnlyMovie(any(Movie.class))).thenCallRealMethod(); Mockito.when(this.defaultMapper.convert(any(Movie.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.createToken(any(String.class), any(List.class), any(Optional.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.validateToken(any(String.class))).thenReturn(true); Mockito.when(this.jwtTokenService.resolveToken(any(HttpServletRequest.class))).thenReturn(Optional.of("")); Mockito.when(this.jwtTokenService.getAuthentication(any(String.class))).thenCallRealMethod(); Mockito.when(this.jwtTokenService.getUsername(any(String.class))).thenReturn("XXX");
Mockito.when(this.jwtTokenService.getAuthorities(any(String.class))).thenReturn(List.of(Role.USERS));
1
2023-12-11 13:53:51+00:00
12k
i-moonlight/Suricate
src/test/java/com/michelin/suricate/services/websocket/DashboardWebSocketServiceTest.java
[ { "identifier": "ProjectResponseDto", "path": "src/main/java/com/michelin/suricate/model/dto/api/project/ProjectResponseDto.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@Schema(description = \"Describe a project/dashboard\")\npublic class ProjectResponseDto extend...
import static com.michelin.suricate.model.enums.UpdateType.CONNECT_DASHBOARD; import static com.michelin.suricate.model.enums.UpdateType.DISCONNECT; import static com.michelin.suricate.model.enums.UpdateType.RELOAD; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.michelin.suricate.model.dto.api.project.ProjectResponseDto; import com.michelin.suricate.model.dto.js.JsExecutionDto; import com.michelin.suricate.model.dto.websocket.UpdateEvent; import com.michelin.suricate.model.dto.websocket.WebsocketClient; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.js.scheduler.JsExecutionScheduler; import com.michelin.suricate.services.js.services.JsExecutionService; import com.michelin.suricate.services.mapper.ProjectMapper; import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.messaging.simp.SimpMessagingTemplate;
7,934
package com.michelin.suricate.services.websocket; @ExtendWith(MockitoExtension.class) class DashboardWebSocketServiceTest { @Mock private JsExecutionScheduler jsExecutionScheduler; @Mock private SimpMessagingTemplate simpMessagingTemplate; @Mock private ProjectService projectService; @Mock private ProjectMapper projectMapper; @Mock
package com.michelin.suricate.services.websocket; @ExtendWith(MockitoExtension.class) class DashboardWebSocketServiceTest { @Mock private JsExecutionScheduler jsExecutionScheduler; @Mock private SimpMessagingTemplate simpMessagingTemplate; @Mock private ProjectService projectService; @Mock private ProjectMapper projectMapper; @Mock
private JsExecutionService jsExecutionService;
7
2023-12-11 11:28:37+00:00
12k
NaerQAQ/js4bukkit
src/main/java/org/js4bukkit/script/ScriptHandler.java
[ { "identifier": "Js4Bukkit", "path": "src/main/java/org/js4bukkit/Js4Bukkit.java", "snippet": "public class Js4Bukkit extends JavaPlugin {\n /**\n * 实例。\n */\n @Getter\n @Setter\n private static Js4Bukkit instance;\n\n /**\n * 服务器版本。\n */\n @Getter\n @Setter\n pri...
import de.leonhard.storage.Yaml; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.SneakyThrows; import org.js4bukkit.Js4Bukkit; import org.js4bukkit.io.config.ConfigManager; import org.js4bukkit.script.interop.command.CommandInterop; import org.js4bukkit.script.interop.listener.EasyEventListenerInterop; import org.js4bukkit.script.interop.listener.EventListenerInterop; import org.js4bukkit.script.interop.placeholder.PlaceholderInterop; import org.js4bukkit.script.objects.handler.CustomContextHandler; import org.js4bukkit.script.objects.handler.ScriptExecutorHandler; import org.js4bukkit.script.objects.objects.ScriptExecutor; import org.js4bukkit.script.objects.objects.ScriptPlugin; import org.js4bukkit.thread.Scheduler; import org.js4bukkit.thread.enums.SchedulerExecutionMode; import org.js4bukkit.thread.enums.SchedulerTypeEnum; import org.js4bukkit.utils.common.text.QuickUtils; import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum; import java.io.File; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors;
8,417
package org.js4bukkit.script; /** * 脚本处理程序。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/12 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ScriptHandler { /** * 脚本所在文件夹。 */ public static final String SCRIPT_PATH = Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/"; /** * 获取上下文的函数名称。 */ public static final String GET_CONTEXT_FUNCTION = "getContext"; /** * 所有脚本插件对象。 */ public static final Queue<ScriptPlugin> SCRIPT_PLUGINS = new ConcurrentLinkedQueue<>(); /** * 注册脚本插件对象。 */ public static void registerScriptPlugins() { Yaml plugins = ConfigManager.getPlugins(); SCRIPT_PLUGINS.addAll( plugins.singleLayerKeySet() .stream() .map(folder -> new ScriptPlugin().init(plugins, folder)) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } /** * 获取所有脚本文件。 * * @return 所有脚本文件 */ public static Queue<File> getScriptFiles() { return SCRIPT_PLUGINS.stream() .flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream()) .collect(Collectors.toCollection(ConcurrentLinkedQueue::new)); } /** * 注册所有脚本。 */ @SneakyThrows public static void registerScripts() { registerScriptPlugins(); Queue<File> scriptFiles = getScriptFiles(); scriptFiles.forEach(scriptFile -> { String scriptName = scriptFile.getName(); try { ScriptExecutorHandler.addScriptExecutor( new ScriptExecutor(scriptFile) .setName(scriptName) .to(ScriptExecutor.class) ); QuickUtils.sendMessage(
package org.js4bukkit.script; /** * 脚本处理程序。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/12 */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ScriptHandler { /** * 脚本所在文件夹。 */ public static final String SCRIPT_PATH = Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/"; /** * 获取上下文的函数名称。 */ public static final String GET_CONTEXT_FUNCTION = "getContext"; /** * 所有脚本插件对象。 */ public static final Queue<ScriptPlugin> SCRIPT_PLUGINS = new ConcurrentLinkedQueue<>(); /** * 注册脚本插件对象。 */ public static void registerScriptPlugins() { Yaml plugins = ConfigManager.getPlugins(); SCRIPT_PLUGINS.addAll( plugins.singleLayerKeySet() .stream() .map(folder -> new ScriptPlugin().init(plugins, folder)) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } /** * 获取所有脚本文件。 * * @return 所有脚本文件 */ public static Queue<File> getScriptFiles() { return SCRIPT_PLUGINS.stream() .flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream()) .collect(Collectors.toCollection(ConcurrentLinkedQueue::new)); } /** * 注册所有脚本。 */ @SneakyThrows public static void registerScripts() { registerScriptPlugins(); Queue<File> scriptFiles = getScriptFiles(); scriptFiles.forEach(scriptFile -> { String scriptName = scriptFile.getName(); try { ScriptExecutorHandler.addScriptExecutor( new ScriptExecutor(scriptFile) .setName(scriptName) .to(ScriptExecutor.class) ); QuickUtils.sendMessage(
ConsoleMessageTypeEnum.NORMAL,
14
2023-12-14 13:50:24+00:00
12k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/OpenskyService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.config.FeederMapping; import com.amnesica.belugaproject.config.StaticValues; import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft; import com.amnesica.belugaproject.entities.data.AirportData; import com.amnesica.belugaproject.repositories.aircraft.OpenskyAircraftRepository; import com.amnesica.belugaproject.services.data.AircraftDataService; import com.amnesica.belugaproject.services.data.AirportDataService; import com.amnesica.belugaproject.services.helper.HelperService; import com.amnesica.belugaproject.services.helper.NetworkHandlerService; import com.amnesica.belugaproject.services.helper.Request; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
8,713
package com.amnesica.belugaproject.services.aircraft; @Slf4j @EnableScheduling @Service public class OpenskyService { @Autowired private AircraftService aircraftService; @Autowired private NetworkHandlerService networkHandler; @Autowired private AircraftDataService aircraftDataService; @Autowired private AirportDataService airportDataService; @Autowired private OpenskyAircraftRepository openskyAircraftRepository; @Autowired
package com.amnesica.belugaproject.services.aircraft; @Slf4j @EnableScheduling @Service public class OpenskyService { @Autowired private AircraftService aircraftService; @Autowired private NetworkHandlerService networkHandler; @Autowired private AircraftDataService aircraftDataService; @Autowired private AirportDataService airportDataService; @Autowired private OpenskyAircraftRepository openskyAircraftRepository; @Autowired
private Configuration configuration;
0
2023-12-11 11:37:46+00:00
12k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-script/src/main/java/io/fiber/net/script/parse/CompiledScript.java
[ { "identifier": "FiberException", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/FiberException.java", "snippet": "public class FiberException extends Exception {\n private int code;\n private final String errorName;\n\n public FiberException(String message, int code, String er...
import com.fasterxml.jackson.databind.JsonNode; import io.fiber.net.common.FiberException; import io.fiber.net.common.async.Maybe; import io.fiber.net.common.utils.SystemPropertyUtil; import io.fiber.net.script.Script; import io.fiber.net.script.ScriptExecException; import io.fiber.net.script.Vm;
7,651
package io.fiber.net.script.parse; public class CompiledScript implements Script { private static final boolean errInfoIncludeSource = SystemPropertyUtil.getBoolean( "fiberNet.errorSource", false ); public static CompiledScript create(String script, Node ast) throws ParseException { return createNonOptimise(script, OptimiserNodeVisitor.optimiseAst(ast)); } public static CompiledScript createNonOptimise(String script, Node ast) throws ParseException { CompilerNodeVisitor.Compiled cpd = CompilerNodeVisitor.compile(ast); return new CompiledScript(script, cpd); } private final String expressionString; private final CompilerNodeVisitor.Compiled compiled; private CompiledScript(String expressionString, CompilerNodeVisitor.Compiled compiled) { this.expressionString = expressionString; this.compiled = compiled; } private static int startPos(long pos) { return ((int) (pos >> 16)) & 0xFFFF; } @Override public Maybe<JsonNode> exec(JsonNode root, Object attach) {
package io.fiber.net.script.parse; public class CompiledScript implements Script { private static final boolean errInfoIncludeSource = SystemPropertyUtil.getBoolean( "fiberNet.errorSource", false ); public static CompiledScript create(String script, Node ast) throws ParseException { return createNonOptimise(script, OptimiserNodeVisitor.optimiseAst(ast)); } public static CompiledScript createNonOptimise(String script, Node ast) throws ParseException { CompilerNodeVisitor.Compiled cpd = CompilerNodeVisitor.compile(ast); return new CompiledScript(script, cpd); } private final String expressionString; private final CompilerNodeVisitor.Compiled compiled; private CompiledScript(String expressionString, CompilerNodeVisitor.Compiled compiled) { this.expressionString = expressionString; this.compiled = compiled; } private static int startPos(long pos) { return ((int) (pos >> 16)) & 0xFFFF; } @Override public Maybe<JsonNode> exec(JsonNode root, Object attach) {
Vm vm = compiled.createVM(root, attach);
5
2023-12-08 15:18:05+00:00
12k
sigbla/sigbla-pds
src/main/java/sigbla/app/pds/collection/TreeSet.java
[ { "identifier": "AbstractSortedSet", "path": "src/main/java/sigbla/app/pds/collection/internal/base/AbstractSortedSet.java", "snippet": "public abstract class AbstractSortedSet<E> extends AbstractSet<E> implements SortedSet<E> {\n @SuppressWarnings(\"ConstantConditions\")\n @NotNull\n @Override...
import java.util.Comparator; import java.util.Iterator; import sigbla.app.pds.collection.internal.base.AbstractSortedSet; import sigbla.app.pds.collection.internal.builder.AbstractSelfBuilder; import sigbla.app.pds.collection.internal.redblack.DerivedKeyFactory; import sigbla.app.pds.collection.internal.redblack.RedBlackTree; import sigbla.app.pds.collection.internal.redblack.Tree; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
7,396
/* * Copyright (c) 2014 Andrew O'Malley * * 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 sigbla.app.pds.collection; /** * {@code TreeSet} is an implementation of {@code SortedSet} backed by a {@code TreeMap}. */ public class TreeSet<E> extends AbstractSortedSet<E> { private final Tree<E, E> tree;
/* * Copyright (c) 2014 Andrew O'Malley * * 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 sigbla.app.pds.collection; /** * {@code TreeSet} is an implementation of {@code SortedSet} backed by a {@code TreeMap}. */ public class TreeSet<E> extends AbstractSortedSet<E> { private final Tree<E, E> tree;
private final RedBlackTree<E, E> redBlackTree;
3
2023-12-10 15:10:13+00:00
12k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCryptoTest.java
[ { "identifier": "AsymmetricCipherKeyPair", "path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricCipherKeyPair.java", "snippet": "public interface AsymmetricCipherKeyPair {\n\n /**\n * Returns the public key parameters.\n *\n * @return the public key parameters.\...
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.incubator.codec.hpke.CryptoException; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DecoderException; import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; import org.bouncycastle.crypto.params.X25519PublicKeyParameters; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
8,940
/* * Copyright 2023 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCryptoTest { private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } static AsymmetricCipherKeyPair createX25519KeyPair(OHttpCryptoProvider cryptoProvider, String privateKeyHexBytes) { X25519PrivateKeyParameters privateKey = new X25519PrivateKeyParameters( ByteBufUtil.decodeHexDump(privateKeyHexBytes)); X25519PublicKeyParameters publicKey = privateKey.generatePublicKey(); return cryptoProvider.deserializePrivateKey( KEM.X25519_SHA256, privateKey.getEncoded(), publicKey.getEncoded()); } /* * Use values from * https://ietf-wg-ohai.github.io/oblivious-http/draft-ietf-ohai-ohttp.html#name-complete-example-of-a-reque */ @ParameterizedTest @ArgumentsSource(value = OHttpCryptoProviderArgumentsProvider.class) public void testCryptoVectors(OHttpCryptoProvider senderProvider, OHttpCryptoProvider receiverProvider) throws DecoderException, CryptoException { byte keyId = 1; AsymmetricCipherKeyPair kpR = createX25519KeyPair( receiverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); AsymmetricCipherKeyPair kpE = createX25519KeyPair( senderProvider, "bc51d5e930bda26589890ac7032f70ad12e4ecb37abb1b65b1256c9c48999c73"); byte[] request = ByteBufUtil.decodeHexDump("00034745540568747470730b6578616d706c652e636f6d012f"); byte[] response = ByteBufUtil.decodeHexDump("0140c8"); OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList(
/* * Copyright 2023 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCryptoTest { private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } static AsymmetricCipherKeyPair createX25519KeyPair(OHttpCryptoProvider cryptoProvider, String privateKeyHexBytes) { X25519PrivateKeyParameters privateKey = new X25519PrivateKeyParameters( ByteBufUtil.decodeHexDump(privateKeyHexBytes)); X25519PublicKeyParameters publicKey = privateKey.generatePublicKey(); return cryptoProvider.deserializePrivateKey( KEM.X25519_SHA256, privateKey.getEncoded(), publicKey.getEncoded()); } /* * Use values from * https://ietf-wg-ohai.github.io/oblivious-http/draft-ietf-ohai-ohttp.html#name-complete-example-of-a-reque */ @ParameterizedTest @ArgumentsSource(value = OHttpCryptoProviderArgumentsProvider.class) public void testCryptoVectors(OHttpCryptoProvider senderProvider, OHttpCryptoProvider receiverProvider) throws DecoderException, CryptoException { byte keyId = 1; AsymmetricCipherKeyPair kpR = createX25519KeyPair( receiverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); AsymmetricCipherKeyPair kpE = createX25519KeyPair( senderProvider, "bc51d5e930bda26589890ac7032f70ad12e4ecb37abb1b65b1256c9c48999c73"); byte[] request = ByteBufUtil.decodeHexDump("00034745540568747470730b6578616d706c652e636f6d012f"); byte[] response = ByteBufUtil.decodeHexDump("0140c8"); OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList(
OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.AES_GCM128),
7
2023-12-06 09:14:09+00:00
12k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/audio/generic/Utils.java
[ { "identifier": "AudioFile", "path": "android/src/main/java/org/jaudiotagger/audio/AudioFile.java", "snippet": "public class AudioFile\n{\n //Logger\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio\");\n\n /**\n *\n * The physical file that this instance represe...
import static org.jaudiotagger.StandardCharsets.ISO_8859_1; import static org.jaudiotagger.StandardCharsets.US_ASCII; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.utils.FileTypeUtil; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger;
10,788
return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Reads 4 bytes and concatenates them into a String. * This pattern is used for ID's of various kinds. * * @param bytes * @return * @throws IOException */ public static String readFourBytesAsChars(final ByteBuffer bytes) { byte[] b = new byte[4]; bytes.get(b); return new String(b, ISO_8859_1); } /** * Reads 3 bytes and concatenates them into a String. * This pattern is used for ID's of various kinds. * * @param bytes * @return */ public static String readThreeBytesAsChars(final ByteBuffer bytes) { byte[] b = new byte[3]; bytes.get(b); return new String(b, ISO_8859_1); } /** * Used to convert (signed integer) to an long as if signed integer was unsigned hence allowing * it to represent full range of integral values. * * @param n * @return */ public static long u(final int n) { return n & 0xffffffffl; } /** * Used to convert (signed short) to an integer as if signed short was unsigned hence allowing * it to represent values 0 -> 65536 rather than -32786 -> 32786 * * @param n * @return */ public static int u(final short n) { return n & 0xffff; } /** * Used to convert (signed byte) to an integer as if signed byte was unsigned hence allowing * it to represent values 0 -> 255 rather than -128 -> 127. * * @param n * @return */ public static int u(final byte n) { return n & 0xff; } /** * @param fc * @param size * @return * @throws IOException */ public static ByteBuffer readFileDataIntoBufferLE(FileChannel fc, final int size) throws IOException { final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size); fc.read(tagBuffer); tagBuffer.position(0); tagBuffer.order(ByteOrder.LITTLE_ENDIAN); return tagBuffer; } /** * @param fc * @param size * @return * @throws IOException */ public static ByteBuffer readFileDataIntoBufferBE(FileChannel fc, final int size) throws IOException { final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size); fc.read(tagBuffer); tagBuffer.position(0); tagBuffer.order(ByteOrder.BIG_ENDIAN); return tagBuffer; } /** * Copy src file to dst file. FileChannels are used to maximize performance. * * @param source source File * @param destination destination File which will be created or truncated, before copying, if it already exists * @throws IOException if any error occurS */ public static void copyThrowsOnException(final File source, final File destination) throws IOException { // Must be done in a loop as there's no guarantee that a request smaller than request count will complete in one invocation. // Setting the transfer size more than about 1MB is pretty pointless because there is no asymptotic benefit. What you're trying // to achieve with larger transfer sizes is fewer context switches, and every time you double the transfer size you halve the // context switch cost. Pretty soon it vanishes into the noise. FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(source); outStream = new FileOutputStream(destination); final FileChannel inChannel = inStream.getChannel(); final FileChannel outChannel = outStream.getChannel(); final long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, 1024L * 1024L, outChannel); } } finally { //Closeables closed exiting try block in all circumstances
/* * Entagged Audio Tag library * Copyright (c) 2003-2005 Raphaël Slinckx <raphael@slinckx.net> * * This library 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; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.audio.generic; /** * Contains various frequently used static functions in the different tag formats. * * @author Raphael Slinckx */ public class Utils { public static int BITS_IN_BYTE_MULTIPLIER = 8; public static int KILOBYTE_MULTIPLIER = 1000; private static final Logger logger = Logger.getLogger("org.jaudiotagger.audio.generic.utils"); private static final int MAX_BASE_TEMP_FILENAME_LENGTH = 20; /** * Returns the extension of the given file. * The extension is empty if there is no extension * The extension is the string after the last "." * * @param f The file whose extension is requested * @return The extension of the given file */ public static String getExtension(final File f) { final String name = f.getName().toLowerCase(); final int i = name.lastIndexOf("."); if (i == -1) { return ""; } return name.substring(i + 1); } /** * Returns the extension of the given file based on the file signature. * The extension is empty if the file signature is not recognized. * * @param f The file whose extension is requested * @return The extension of the given file */ public static String getMagicExtension(final File f) throws IOException { final String fileType = FileTypeUtil.getMagicFileType(f); return FileTypeUtil.getMagicExt(fileType); } /** * Computes a number whereby the 1st byte is the least signifcant and the last * byte is the most significant. * So if storing a number which only requires one byte it will be stored in the first * byte. * * @param b The byte array @param start The starting offset in b * (b[offset]). The less significant byte @param end The end index * (included) in b (b[end]). The most significant byte * @return a long number represented by the byte sequence. */ public static long getLongLE(final ByteBuffer b, final int start, final int end) { long number = 0; for (int i = 0; i < (end - start + 1); i++) { number += ((b.get(start + i) & 0xFF) << i * 8); } return number; } /** * Computes a number whereby the 1st byte is the most significant and the last * byte is the least significant. * <p> * So if storing a number which only requires one byte it will be stored in the last * byte. * <p> * Will fail if end - start >= 8, due to the limitations of the long type. */ public static long getLongBE(final ByteBuffer b, final int start, final int end) { long number = 0; for (int i = 0; i < (end - start + 1); i++) { number += ((long) ((b.get(end - i) & 0xFF)) << i * 8); } return number; } /** * Computes a number whereby the 1st byte is the least significant and the last * byte is the most significant. This version doesn't take a length, * and it returns an int rather than a long. * * @param b The byte array. Maximum length for valid results is 4 bytes. */ public static int getIntLE(final byte[] b) { return (int) getLongLE(ByteBuffer.wrap(b), 0, b.length - 1); } /** * Computes a number whereby the 1st byte is the least significant and the last * byte is the most significant. end - start must be no greater than 4. * * @param b The byte array * @param start The starting offset in b (b[offset]). The less * significant byte * @param end The end index (included) in b (b[end]) * @return a int number represented by the byte sequence. */ public static int getIntLE(final byte[] b, final int start, final int end) { return (int) getLongLE(ByteBuffer.wrap(b), start, end); } /** * Computes a number whereby the 1st byte is the most significant and the last * byte is the least significant. * * @param b The ByteBuffer * @param start The starting offset in b. The less * significant byte * @param end The end index (included) in b * @return an int number represented by the byte sequence. */ public static int getIntBE(final ByteBuffer b, final int start, final int end) { return (int) getLongBE(b, start, end); } /** * Computes a number whereby the 1st byte is the most significant and the last * byte is the least significant. * * @param b The ByteBuffer * @param start The starting offset in b. The less * significant byte * @param end The end index (included) in b * @return a short number represented by the byte sequence. */ public static short getShortBE(final ByteBuffer b, final int start, final int end) { return (short) getIntBE(b, start, end); } /** * Convert int to byte representation - Big Endian (as used by mp4). * * @param size * @return byte representation */ public static byte[] getSizeBEInt32(final int size) { final byte[] b = new byte[4]; b[0] = (byte) ((size >> 24) & 0xFF); b[1] = (byte) ((size >> 16) & 0xFF); b[2] = (byte) ((size >> 8) & 0xFF); b[3] = (byte) (size & 0xFF); return b; } /** * Convert short to byte representation - Big Endian (as used by mp4). * * @param size number to convert * @return byte representation */ public static byte[] getSizeBEInt16(final short size) { final byte[] b = new byte[2]; b[0] = (byte) ((size >> 8) & 0xFF); b[1] = (byte) (size & 0xFF); return b; } /** * Convert int to byte representation - Little Endian (as used by ogg vorbis). * * @param size number to convert * @return byte representation */ public static byte[] getSizeLEInt32(final int size) { final byte[] b = new byte[4]; b[0] = (byte) (size & 0xff); b[1] = (byte) ((size >>> 8) & 0xffL); b[2] = (byte) ((size >>> 16) & 0xffL); b[3] = (byte) ((size >>> 24) & 0xffL); return b; } /** * Convert a byte array to a Pascal string. The first byte is the byte count, * followed by that many active characters. * * @param bb * @return * @throws IOException */ public static String readPascalString(final ByteBuffer bb) throws IOException { final int len = Utils.u(bb.get()); //Read as unsigned value final byte[] buf = new byte[len]; bb.get(buf); return new String(buf, 0, len, ISO_8859_1); } /** * Reads bytes from a ByteBuffer as if they were encoded in the specified CharSet. * * @param buffer * @param offset offset from current position * @param length size of data to process * @param encoding * @return */ public static String getString(final ByteBuffer buffer, final int offset, final int length, final Charset encoding) { final byte[] b = new byte[length]; buffer.position(buffer.position() + offset); buffer.get(b); return new String(b, 0, length, encoding); } /** * Reads bytes from a ByteBuffer as if they were encoded in the specified CharSet. * * @param buffer * @param encoding * @return */ public static String getString(final ByteBuffer buffer, final Charset encoding) { final byte[] b = new byte[buffer.remaining()]; buffer.get(b); return new String(b, 0, b.length, encoding); } /** * Read a 32-bit big-endian unsigned integer using a DataInput. * <p> * Reads 4 bytes but returns as long */ public static long readUint32(final DataInput di) throws IOException { final byte[] buf8 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; di.readFully(buf8, 4, 4); return ByteBuffer.wrap(buf8).getLong(); } /** * Read a 16-bit big-endian unsigned integer. * <p> * Reads 2 bytes but returns as an integer */ public static int readUint16(final DataInput di) throws IOException { final byte[] buf = {0x00, 0x00, 0x00, 0x00}; di.readFully(buf, 2, 2); return ByteBuffer.wrap(buf).getInt(); } /** * Read a string of a specified number of ASCII bytes. */ public static String readString(final DataInput di, final int charsToRead) throws IOException { final byte[] buf = new byte[charsToRead]; di.readFully(buf); return new String(buf, US_ASCII); } /** * Get a base for temp file, this should be long enough so that it easy to work out later what file the temp file * was created for if it is left lying round, but not ridiculously long as this can cause problems with max filename * limits and is not very useful. * * @param file * @return */ public static String getBaseFilenameForTempFile(final File file) { final String filename = getMinBaseFilenameAllowedForTempFile(file); if (filename.length() <= MAX_BASE_TEMP_FILENAME_LENGTH) { return filename; } return filename.substring(0, MAX_BASE_TEMP_FILENAME_LENGTH); } /** * @param file * @return filename with audioformat separator stripped of, lengthened to ensure not too small for valid tempfile * creation. */ public static String getMinBaseFilenameAllowedForTempFile(final File file) { final String s = AudioFile.getBaseFilename(file); if (s.length() >= 3) { return s; } if (s.length() == 1) { return s + "000"; } else if (s.length() == 1) { return s + "00"; } else if (s.length() == 2) { return s + "0"; } return s; } /** * Rename file, and if normal rename fails, try copy and delete instead. * * @param fromFile * @param toFile * @return */ public static boolean rename(final File fromFile, final File toFile) { logger.log(Level.CONFIG, "Renaming From:" + fromFile.getAbsolutePath() + " to " + toFile.getAbsolutePath()); if (toFile.exists()) { logger.log(Level.SEVERE, "Destination File:" + toFile + " already exists"); return false; } //Rename File, could fail because being used or because trying to rename over filesystems final boolean result = fromFile.renameTo(toFile); if (!result) { // Might be trying to rename over filesystem, so try copy and delete instead if (copy(fromFile, toFile)) { //If copy works but deletion of original file fails then it is because the file is being used //so we need to delete the file we have just created boolean deleteResult = fromFile.delete(); if (!deleteResult) { logger.log(Level.SEVERE, "Unable to delete File:" + fromFile); toFile.delete(); return false; } return true; } else { return false; } } return true; } /** * Copy a File. * <p> * ToDo refactor AbstractTestCase to use this method as it contains an exact duplicate. * * @param fromFile The existing File * @param toFile The new File * @return <code>true</code> if and only if the renaming succeeded; * <code>false</code> otherwise */ public static boolean copy(final File fromFile, final File toFile) { try { copyThrowsOnException(fromFile, toFile); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Reads 4 bytes and concatenates them into a String. * This pattern is used for ID's of various kinds. * * @param bytes * @return * @throws IOException */ public static String readFourBytesAsChars(final ByteBuffer bytes) { byte[] b = new byte[4]; bytes.get(b); return new String(b, ISO_8859_1); } /** * Reads 3 bytes and concatenates them into a String. * This pattern is used for ID's of various kinds. * * @param bytes * @return */ public static String readThreeBytesAsChars(final ByteBuffer bytes) { byte[] b = new byte[3]; bytes.get(b); return new String(b, ISO_8859_1); } /** * Used to convert (signed integer) to an long as if signed integer was unsigned hence allowing * it to represent full range of integral values. * * @param n * @return */ public static long u(final int n) { return n & 0xffffffffl; } /** * Used to convert (signed short) to an integer as if signed short was unsigned hence allowing * it to represent values 0 -> 65536 rather than -32786 -> 32786 * * @param n * @return */ public static int u(final short n) { return n & 0xffff; } /** * Used to convert (signed byte) to an integer as if signed byte was unsigned hence allowing * it to represent values 0 -> 255 rather than -128 -> 127. * * @param n * @return */ public static int u(final byte n) { return n & 0xff; } /** * @param fc * @param size * @return * @throws IOException */ public static ByteBuffer readFileDataIntoBufferLE(FileChannel fc, final int size) throws IOException { final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size); fc.read(tagBuffer); tagBuffer.position(0); tagBuffer.order(ByteOrder.LITTLE_ENDIAN); return tagBuffer; } /** * @param fc * @param size * @return * @throws IOException */ public static ByteBuffer readFileDataIntoBufferBE(FileChannel fc, final int size) throws IOException { final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size); fc.read(tagBuffer); tagBuffer.position(0); tagBuffer.order(ByteOrder.BIG_ENDIAN); return tagBuffer; } /** * Copy src file to dst file. FileChannels are used to maximize performance. * * @param source source File * @param destination destination File which will be created or truncated, before copying, if it already exists * @throws IOException if any error occurS */ public static void copyThrowsOnException(final File source, final File destination) throws IOException { // Must be done in a loop as there's no guarantee that a request smaller than request count will complete in one invocation. // Setting the transfer size more than about 1MB is pretty pointless because there is no asymptotic benefit. What you're trying // to achieve with larger transfer sizes is fewer context switches, and every time you double the transfer size you halve the // context switch cost. Pretty soon it vanishes into the noise. FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(source); outStream = new FileOutputStream(destination); final FileChannel inChannel = inStream.getChannel(); final FileChannel outChannel = outStream.getChannel(); final long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, 1024L * 1024L, outChannel); } } finally { //Closeables closed exiting try block in all circumstances
AudioFileIO.closeQuietly(inStream, outStream);
1
2023-12-11 05:58:19+00:00
12k
Ender-Cube/Endercube
src/main/java/net/endercube/Endercube/Main.java
[ { "identifier": "EndercubeServer", "path": "Common/src/main/java/net/endercube/Common/EndercubeServer.java", "snippet": "public class EndercubeServer {\n\n private final ArrayList<EndercubeMinigame> minigames = new ArrayList<>();\n private final CommentedConfigurationNode globalConfig;\n privat...
import net.endercube.Common.EndercubeServer; import net.endercube.Common.commands.GenericRootCommand; import net.endercube.Endercube.blocks.Sign; import net.endercube.Endercube.blocks.Skull; import net.endercube.Endercube.commands.BanCommand; import net.endercube.Endercube.commands.DiscordCommand; import net.endercube.Endercube.commands.KickCommand; import net.endercube.Endercube.commands.ResetTimeCommand; import net.endercube.Endercube.commands.UnbanCommand; import net.endercube.Endercube.listeners.AsyncPlayerConfiguration; import net.endercube.Endercube.listeners.PlayerDisconnect; import net.endercube.Hub.HubMinigame; import net.endercube.Parkour.ParkourMinigame; import net.minestom.server.MinecraftServer; import net.minestom.server.permission.Permission; import net.minestom.server.utils.NamespaceID; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPooled;
7,401
package net.endercube.Endercube; /** * This is the entrypoint for the server */ public class Main { public static final Logger logger = LoggerFactory.getLogger(Main.class); @Nullable public static EndercubeServer endercubeServer; public static JedisPooled jedis; public static void main(String[] args) { logger.info("Starting Server"); endercubeServer = new EndercubeServer.EndercubeServerBuilder() .addGlobalEvent(new AsyncPlayerConfiguration()) .addGlobalEvent(new PlayerDisconnect()) .addBlockHandler(NamespaceID.from("minecraft:sign"), Sign::new) .addBlockHandler(NamespaceID.from("minecraft:skull"), Skull::new) .startServer(); endercubeServer .addMinigame(new ParkourMinigame(endercubeServer)) .addMinigame(new HubMinigame(endercubeServer)); jedis = endercubeServer.getJedisPooled(); initCommands(); } private static void initCommands() { GenericRootCommand adminCommand = new GenericRootCommand("admin"); adminCommand.setCondition(((sender, commandString) -> sender.hasPermission(new Permission("operator")))); adminCommand.addSubcommand(new ResetTimeCommand()); adminCommand.addSubcommand(new BanCommand()); adminCommand.addSubcommand(new UnbanCommand()); adminCommand.addSubcommand(new KickCommand()); MinecraftServer.getCommandManager().register(adminCommand);
package net.endercube.Endercube; /** * This is the entrypoint for the server */ public class Main { public static final Logger logger = LoggerFactory.getLogger(Main.class); @Nullable public static EndercubeServer endercubeServer; public static JedisPooled jedis; public static void main(String[] args) { logger.info("Starting Server"); endercubeServer = new EndercubeServer.EndercubeServerBuilder() .addGlobalEvent(new AsyncPlayerConfiguration()) .addGlobalEvent(new PlayerDisconnect()) .addBlockHandler(NamespaceID.from("minecraft:sign"), Sign::new) .addBlockHandler(NamespaceID.from("minecraft:skull"), Skull::new) .startServer(); endercubeServer .addMinigame(new ParkourMinigame(endercubeServer)) .addMinigame(new HubMinigame(endercubeServer)); jedis = endercubeServer.getJedisPooled(); initCommands(); } private static void initCommands() { GenericRootCommand adminCommand = new GenericRootCommand("admin"); adminCommand.setCondition(((sender, commandString) -> sender.hasPermission(new Permission("operator")))); adminCommand.addSubcommand(new ResetTimeCommand()); adminCommand.addSubcommand(new BanCommand()); adminCommand.addSubcommand(new UnbanCommand()); adminCommand.addSubcommand(new KickCommand()); MinecraftServer.getCommandManager().register(adminCommand);
MinecraftServer.getCommandManager().register(new DiscordCommand());
5
2023-12-10 12:08:18+00:00
12k
lukebemishprojects/Tempest
fabriquilt/src/main/java/dev/lukebemish/tempest/impl/fabriquilt/ModPlatform.java
[ { "identifier": "FastChunkLookup", "path": "common/src/main/java/dev/lukebemish/tempest/impl/FastChunkLookup.java", "snippet": "public interface FastChunkLookup {\n WeatherChunkData tempest$getChunkData();\n void tempest$setChunkData(WeatherChunkData data);\n}" }, { "identifier": "Services...
import com.google.auto.service.AutoService; import dev.lukebemish.tempest.impl.FastChunkLookup; import dev.lukebemish.tempest.impl.Services; import dev.lukebemish.tempest.impl.data.WeatherMapData; import dev.lukebemish.tempest.impl.data.world.WeatherChunkData; import dev.lukebemish.tempest.impl.data.world.WeatherData; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.core.SectionPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.EmptyLevelChunk; import net.minecraft.world.level.chunk.LevelChunk; import java.util.List; import java.util.function.Supplier;
9,294
package dev.lukebemish.tempest.impl.fabriquilt; @AutoService(Services.Platform.class) public final class ModPlatform implements Services.Platform { @Override
package dev.lukebemish.tempest.impl.fabriquilt; @AutoService(Services.Platform.class) public final class ModPlatform implements Services.Platform { @Override
public WeatherChunkData getChunkData(LevelChunk chunk) {
2
2023-12-06 23:23:31+00:00
12k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/service/impl/SysDictServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.framework.mybatis.tool.SqlHelper; import com.xht.cloud.system.exceptions.DictException; import com.xht.cloud.system.module.dict.controller.request.SysDictAddRequest; import com.xht.cloud.system.module.dict.controller.request.SysDictQueryRequest; import com.xht.cloud.system.module.dict.controller.request.SysDictUpdateRequest; import com.xht.cloud.system.module.dict.controller.response.SysDictResponse; import com.xht.cloud.system.module.dict.controller.response.SysDictVo; import com.xht.cloud.system.module.dict.convert.SysDictConvert; import com.xht.cloud.system.module.dict.convert.SysDictItemConvert; import com.xht.cloud.system.module.dict.dao.dataobject.SysDictDO; import com.xht.cloud.system.module.dict.dao.dataobject.SysDictItemDO; import com.xht.cloud.system.module.dict.dao.mapper.SysDictItemMapper; import com.xht.cloud.system.module.dict.dao.mapper.SysDictMapper; import com.xht.cloud.system.module.dict.dao.wrapper.SysDictItemWrapper; import com.xht.cloud.system.module.dict.dao.wrapper.SysDictWrapper; import com.xht.cloud.system.module.dict.service.ISysDictService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Objects;
7,687
package com.xht.cloud.system.module.dict.service.impl; /** * 描述 :字典 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysDictServiceImpl implements ISysDictService { private final SysDictMapper sysDictMapper; private final SysDictConvert sysDictConvert;
package com.xht.cloud.system.module.dict.service.impl; /** * 描述 :字典 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysDictServiceImpl implements ISysDictService { private final SysDictMapper sysDictMapper; private final SysDictConvert sysDictConvert;
private final SysDictItemMapper sysDictItemMapper;
15
2023-12-12 08:16:30+00:00
12k
serendipitk/LunarCore
src/main/java/emu/lunarcore/game/rogue/RogueTalentData.java
[ { "identifier": "LunarCore", "path": "src/main/java/emu/lunarcore/LunarCore.java", "snippet": "public class LunarCore {\n private static final Logger log = LoggerFactory.getLogger(LunarCore.class);\n private static File configFile = new File(\"./config.json\");\n @Getter private static Config c...
import org.bson.types.ObjectId; import dev.morphia.annotations.Entity; import dev.morphia.annotations.Id; import dev.morphia.annotations.Indexed; import emu.lunarcore.LunarCore; import emu.lunarcore.game.player.Player; import lombok.Getter;
9,863
package emu.lunarcore.game.rogue; @Getter @Entity(value = "rogueTalents", useDiscriminator = false) public class RogueTalentData { @Id private ObjectId id; @Indexed private int ownerUid; private int talentId; @Deprecated // Morphia only public RogueTalentData() {}
package emu.lunarcore.game.rogue; @Getter @Entity(value = "rogueTalents", useDiscriminator = false) public class RogueTalentData { @Id private ObjectId id; @Indexed private int ownerUid; private int talentId; @Deprecated // Morphia only public RogueTalentData() {}
public RogueTalentData(Player player, int talentId) {
1
2023-12-08 14:13:04+00:00
12k
zhaw-iwi/promise
src/test/java/ch/zhaw/statefulconversation/paper/MultiStateInteraction.java
[ { "identifier": "Agent", "path": "src/main/java/ch/zhaw/statefulconversation/model/Agent.java", "snippet": "@Entity\npublic class Agent {\n\n // @TODO: maybe have an attribute or getter method is active?\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getId() {\n retur...
import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.google.gson.Gson; import ch.zhaw.statefulconversation.model.Agent; import ch.zhaw.statefulconversation.model.Final; import ch.zhaw.statefulconversation.model.OuterState; import ch.zhaw.statefulconversation.model.State; import ch.zhaw.statefulconversation.model.Storage; import ch.zhaw.statefulconversation.model.Transition; import ch.zhaw.statefulconversation.model.commons.actions.StaticExtractionAction; import ch.zhaw.statefulconversation.model.commons.decisions.StaticDecision; import ch.zhaw.statefulconversation.model.commons.states.DynamicSingleChoiceState; import ch.zhaw.statefulconversation.model.commons.states.EN_DynamicCauseAssessmentState; import ch.zhaw.statefulconversation.repositories.AgentRepository;
7,615
package ch.zhaw.statefulconversation.paper; @SpringBootTest class MultiStateInteraction { private static final String PROMPT_THERAPYCOACH = """ As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans. Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences. """; private static final String PROMPT_THERAPYCOACH_TRIGGER = """ Review the patient's latest messages in the following conversation. Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat. """; private static final String PROMPT_THERAPYCOACH_GUARD = """ Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing. """; private static final String PROMPT_THERAPYCOACH_ACTION = """ Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review. """; @Autowired private AgentRepository repository; @Test void setUp() { String storageKeyFromActivityMissed = "ActivityMissed"; String storageKeyToReasonProvided = "ReasonProvided"; String storageKeyFromSuggestionsOffered = "SuggestionsOffered"; String storageKeyToSuggestionChosen = "SuggestionChosen"; Gson gson = new Gson(); Storage storage = new Storage(); storage.put(storageKeyFromActivityMissed, gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening."))); storage.put(storageKeyFromSuggestionsOffered, gson.toJsonTree(List.of( "Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.", "Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere."))); State patientChoosesSuggestion = new DynamicSingleChoiceState("PatientChoosesSuggestion", new Final(), storage, storageKeyFromSuggestionsOffered, storageKeyToSuggestionChosen); State patientProvidesReason = new EN_DynamicCauseAssessmentState("PatientProvidesReason", patientChoosesSuggestion, storage, storageKeyFromActivityMissed, storageKeyToReasonProvided); Transition therapyCoachTransition = new Transition(
package ch.zhaw.statefulconversation.paper; @SpringBootTest class MultiStateInteraction { private static final String PROMPT_THERAPYCOACH = """ As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans. Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences. """; private static final String PROMPT_THERAPYCOACH_TRIGGER = """ Review the patient's latest messages in the following conversation. Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat. """; private static final String PROMPT_THERAPYCOACH_GUARD = """ Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing. """; private static final String PROMPT_THERAPYCOACH_ACTION = """ Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review. """; @Autowired private AgentRepository repository; @Test void setUp() { String storageKeyFromActivityMissed = "ActivityMissed"; String storageKeyToReasonProvided = "ReasonProvided"; String storageKeyFromSuggestionsOffered = "SuggestionsOffered"; String storageKeyToSuggestionChosen = "SuggestionChosen"; Gson gson = new Gson(); Storage storage = new Storage(); storage.put(storageKeyFromActivityMissed, gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening."))); storage.put(storageKeyFromSuggestionsOffered, gson.toJsonTree(List.of( "Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.", "Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere."))); State patientChoosesSuggestion = new DynamicSingleChoiceState("PatientChoosesSuggestion", new Final(), storage, storageKeyFromSuggestionsOffered, storageKeyToSuggestionChosen); State patientProvidesReason = new EN_DynamicCauseAssessmentState("PatientProvidesReason", patientChoosesSuggestion, storage, storageKeyFromActivityMissed, storageKeyToReasonProvided); Transition therapyCoachTransition = new Transition(
List.of(new StaticDecision(MultiStateInteraction.PROMPT_THERAPYCOACH_TRIGGER),
7
2023-12-06 09:36:58+00:00
12k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencore/block/BlockGarden.java
[ { "identifier": "IPlantProxy", "path": "src/main/java/com/jaquadro/minecraft/gardencore/api/IPlantProxy.java", "snippet": "public interface IPlantProxy {\n\n TileEntityGarden getGardenEntity(IBlockAccess var1, int var2, int var3, int var4);\n\n boolean applyBonemeal(World var1, int var2, int var3,...
import com.jaquadro.minecraft.gardencore.api.IPlantProxy; import com.jaquadro.minecraft.gardencore.api.block.IGardenBlock; import com.jaquadro.minecraft.gardencore.api.block.garden.IConnectionProfile; import com.jaquadro.minecraft.gardencore.api.block.garden.ISlotProfile; import com.jaquadro.minecraft.gardencore.api.block.garden.ISlotShareProfile; import com.jaquadro.minecraft.gardencore.api.plant.PlantItem; import com.jaquadro.minecraft.gardencore.block.tile.TileEntityGarden; import com.jaquadro.minecraft.gardencore.core.ModBlocks; import com.jaquadro.minecraft.gardencore.core.ModItems; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; import java.util.Iterator;
8,142
public void onBlockHarvested(World world, int x, int y, int z, int p_149681_5_, EntityPlayer player) { super.onBlockHarvested(world, x, y, z, p_149681_5_, player); if (player.capabilities.isCreativeMode) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.clearPlantedContents(); } } } public void breakBlock(World world, int x, int y, int z, Block block, int data) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { Iterator var8 = te.getReachableContents().iterator(); while(var8.hasNext()) { ItemStack item = (ItemStack)var8.next(); this.dropBlockAsItem(world, x, y, z, item); } te.clearReachableContents(); } super.breakBlock(world, x, y, z, block, data); } public int getDefaultSlot() { return -1; } public IConnectionProfile getConnectionProfile() { return this.connectionProfile; } public ISlotProfile getSlotProfile() { return this.slotProfile; } public ISlotShareProfile getSlotShareProfile() { return this.slotShareProfile; } public void clearPlantedContents(IBlockAccess world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.clearReachableContents(); } validateBlockState(te); } public NBTTagCompound saveAndClearPlantedContents(IBlockAccess world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te == null) { return null; } else { NBTTagCompound tag = new NBTTagCompound(); te.writeToNBT(tag); this.clearPlantedContents(world, x, y, z); return tag; } } public void restorePlantedContents(IBlockAccess world, int x, int y, int z, NBTTagCompound tag) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.readFromNBT(tag); validateBlockState(te); } } public Block getPlantBlockFromSlot(IBlockAccess blockAccess, int x, int y, int z, int slot) { TileEntityGarden te = this.getTileEntity(blockAccess, x, y, z); ItemStack stack = te.getPlantInSlot(slot); return stack != null && stack.getItem() != null ? Block.getBlockFromItem(stack.getItem()) : null; } public int getPlantMetaFromSlot(IBlockAccess blockAccess, int x, int y, int z, int slot) { TileEntityGarden te = this.getTileEntity(blockAccess, x, y, z); ItemStack stack = te.getPlantInSlot(slot); return stack != null && stack.getItem() != null ? stack.getItemDamage() : 0; } public static void validateBlockState(TileEntityGarden tileEntity) { Block baseBlock = tileEntity.getWorldObj().getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); if (baseBlock instanceof BlockGarden) { BlockGarden garden = (BlockGarden)baseBlock; int plantHeight = garden.getAggregatePlantHeight(tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); World world = tileEntity.getWorldObj(); int x = tileEntity.xCoord; int y = tileEntity.yCoord + 1; int z = tileEntity.zCoord; for(int yLimit = y + plantHeight; y < yLimit; ++y) { Block block = world.getBlock(x, y, z); if (block.isAir(world, x, y, z)) { world.setBlock(x, y, z, ModBlocks.gardenProxy, 0, 3); } world.func_147479_m(x, y, z); } while(world.getBlock(x, y, z) instanceof BlockGardenProxy) { world.setBlockToAir(x, y++, z); } } } public int getAggregatePlantHeight(IBlockAccess blockAccess, int x, int y, int z) { TileEntityGarden garden = this.getTileEntity(blockAccess, x, y, z); int height = 0; int[] var7 = this.slotProfile.getPlantSlots(); int var8 = var7.length; for(int var9 = 0; var9 < var8; ++var9) { int slot = var7[var9]; ItemStack item = garden.getStackInSlot(slot);
package com.jaquadro.minecraft.gardencore.block; public abstract class BlockGarden extends BlockContainer implements IGardenBlock { public static final int SLOT_INVALID = -1; protected IConnectionProfile connectionProfile; protected ISlotProfile slotProfile; protected ISlotShareProfile slotShareProfile; protected BlockGarden(String blockName, Material material) { super(material); this.setBlockName(blockName); } public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plantable) { return false; } public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (side != ForgeDirection.UP.ordinal()) { return false; } else { TileEntityGarden tileEntity = this.getTileEntity(world, x, y, z); if (tileEntity == null) { tileEntity = this.createNewTileEntity(world, 0); world.setTileEntity(x, y, z, tileEntity); } return this.applyItemToGarden(world, x, y, z, player, (ItemStack)null, hitX, hitY, hitZ); } } public abstract TileEntityGarden createNewTileEntity(World var1, int var2); public void onBlockHarvested(World world, int x, int y, int z, int p_149681_5_, EntityPlayer player) { super.onBlockHarvested(world, x, y, z, p_149681_5_, player); if (player.capabilities.isCreativeMode) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.clearPlantedContents(); } } } public void breakBlock(World world, int x, int y, int z, Block block, int data) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { Iterator var8 = te.getReachableContents().iterator(); while(var8.hasNext()) { ItemStack item = (ItemStack)var8.next(); this.dropBlockAsItem(world, x, y, z, item); } te.clearReachableContents(); } super.breakBlock(world, x, y, z, block, data); } public int getDefaultSlot() { return -1; } public IConnectionProfile getConnectionProfile() { return this.connectionProfile; } public ISlotProfile getSlotProfile() { return this.slotProfile; } public ISlotShareProfile getSlotShareProfile() { return this.slotShareProfile; } public void clearPlantedContents(IBlockAccess world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.clearReachableContents(); } validateBlockState(te); } public NBTTagCompound saveAndClearPlantedContents(IBlockAccess world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te == null) { return null; } else { NBTTagCompound tag = new NBTTagCompound(); te.writeToNBT(tag); this.clearPlantedContents(world, x, y, z); return tag; } } public void restorePlantedContents(IBlockAccess world, int x, int y, int z, NBTTagCompound tag) { TileEntityGarden te = this.getTileEntity(world, x, y, z); if (te != null) { te.readFromNBT(tag); validateBlockState(te); } } public Block getPlantBlockFromSlot(IBlockAccess blockAccess, int x, int y, int z, int slot) { TileEntityGarden te = this.getTileEntity(blockAccess, x, y, z); ItemStack stack = te.getPlantInSlot(slot); return stack != null && stack.getItem() != null ? Block.getBlockFromItem(stack.getItem()) : null; } public int getPlantMetaFromSlot(IBlockAccess blockAccess, int x, int y, int z, int slot) { TileEntityGarden te = this.getTileEntity(blockAccess, x, y, z); ItemStack stack = te.getPlantInSlot(slot); return stack != null && stack.getItem() != null ? stack.getItemDamage() : 0; } public static void validateBlockState(TileEntityGarden tileEntity) { Block baseBlock = tileEntity.getWorldObj().getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); if (baseBlock instanceof BlockGarden) { BlockGarden garden = (BlockGarden)baseBlock; int plantHeight = garden.getAggregatePlantHeight(tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); World world = tileEntity.getWorldObj(); int x = tileEntity.xCoord; int y = tileEntity.yCoord + 1; int z = tileEntity.zCoord; for(int yLimit = y + plantHeight; y < yLimit; ++y) { Block block = world.getBlock(x, y, z); if (block.isAir(world, x, y, z)) { world.setBlock(x, y, z, ModBlocks.gardenProxy, 0, 3); } world.func_147479_m(x, y, z); } while(world.getBlock(x, y, z) instanceof BlockGardenProxy) { world.setBlockToAir(x, y++, z); } } } public int getAggregatePlantHeight(IBlockAccess blockAccess, int x, int y, int z) { TileEntityGarden garden = this.getTileEntity(blockAccess, x, y, z); int height = 0; int[] var7 = this.slotProfile.getPlantSlots(); int var8 = var7.length; for(int var9 = 0; var9 < var8; ++var9) { int slot = var7[var9]; ItemStack item = garden.getStackInSlot(slot);
PlantItem plant = PlantItem.getForItem(blockAccess, item);
5
2023-12-12 08:13:16+00:00
12k
Zergatul/java-scripting-language
src/main/java/com/zergatul/scripting/compiler/ScriptingLanguageCompiler.java
[ { "identifier": "BinaryOperation", "path": "src/main/java/com/zergatul/scripting/compiler/operations/BinaryOperation.java", "snippet": "public abstract class BinaryOperation {\r\n\r\n public abstract SType getType();\r\n public abstract void apply(CompilerMethodVisitor left, BufferVisitor right) t...
import com.zergatul.scripting.compiler.operations.BinaryOperation; import com.zergatul.scripting.compiler.operations.ImplicitCast; import com.zergatul.scripting.compiler.operations.UnaryOperation; import com.zergatul.scripting.compiler.types.*; import com.zergatul.scripting.compiler.variables.FunctionEntry; import com.zergatul.scripting.compiler.variables.StaticVariableEntry; import com.zergatul.scripting.compiler.variables.VariableContextStack; import com.zergatul.scripting.compiler.variables.VariableEntry; import com.zergatul.scripting.generated.*; import org.objectweb.asm.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Parameter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static org.objectweb.asm.Opcodes.*;
8,272
null, null); fieldVisitor.visitEnd(); } } writer.visitEnd(); byte[] code = writer.toByteArray(); return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code); } private void compile( ASTInput input, ClassWriter classWriter, CompilerMethodVisitor constructorVisitor, CompilerMethodVisitor runVisitor ) throws ScriptCompileException { if (input.jjtGetNumChildren() < 2) { throw new ScriptCompileException("ASTInput: num children < 2."); } if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) { throw new ScriptCompileException("ASTInput: static vars list expected."); } if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) { throw new ScriptCompileException("ASTInput: functions list expected."); } compile(variablesList, constructorVisitor); compile(functionsList, classWriter, constructorVisitor); for (int i = 2; i < input.jjtGetNumChildren(); i++) { if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) { throw new ScriptCompileException("ASTInput statement expected."); } compile(statement, runVisitor); } } private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) { throw new ScriptCompileException("ASTStaticVariablesList declaration expected."); } compile(variableDeclaration, visitor); } } private void compile( ASTFunctionsList list, ClassWriter classWriter, CompilerMethodVisitor visitor ) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) { throw new ScriptCompileException("ASTFunctionsList: declaration expected."); } SType type = getFunctionReturnType(functionDeclaration); ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration); List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration); String name = (String) identifier.jjtGetValue(); visitor.getContextStack().addFunction( name, type, parameters.stream().map(p -> p.type).toArray(SType[]::new), visitor.getClassName()); } for (int i = 0; i < list.jjtGetNumChildren(); i++) { compile( (ASTFunctionDeclaration) list.jjtGetChild(i), classWriter, visitor.getContextStack().newWithStaticVariables(0)); } } private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException { if (declaration.jjtGetNumChildren() != 1) { throw new ScriptCompileException("Invalid static var decl structure."); } Node node = declaration.jjtGetChild(0); if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) { throw new ScriptCompileException("ASTLocalVariableDeclaration expected."); } ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0); ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1); ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0); ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0); ASTVariableInitializer initializer = null; if (variableDeclarator.jjtGetNumChildren() > 1) { initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1); } SType type = parseType(astType); if (initializer != null) { SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor); if (!returnType.equals(type)) { UnaryOperation operation = ImplicitCast.get(returnType, type); if (operation != null) { operation.apply(visitor); } else { throw new ScriptCompileException(String.format("Static variable type %s assigned to expression of type %s.", type, returnType)); } } } else { type.storeDefaultValue(visitor); } String variableName = (String) identifier.jjtGetValue(); if (Arrays.stream(root.getDeclaredFields()).anyMatch(f -> f.getName().equals(variableName))) { throw new ScriptCompileException(String.format("Cannot declare static variable %s because API class with the same name exists.", variableName)); }
package com.zergatul.scripting.compiler; public class ScriptingLanguageCompiler { private static AtomicInteger counter = new AtomicInteger(0); private static ScriptingClassLoader classLoader = new ScriptingClassLoader(); private final Class<?> root; private final MethodVisibilityChecker visibilityChecker; public ScriptingLanguageCompiler(Class<?> root) { this(root, new MethodVisibilityChecker()); } public ScriptingLanguageCompiler(Class<?> root, MethodVisibilityChecker visibilityChecker) { this.root = root; this.visibilityChecker = visibilityChecker; } public Runnable compile(String program) throws ParseException, ScriptCompileException { program += "\r\n"; // temp fix for error if last token is comment InputStream stream = new ByteArrayInputStream(program.getBytes(StandardCharsets.UTF_8)); ScriptingLanguage parser = new ScriptingLanguage(stream); ASTInput input = parser.Input(); Class<Runnable> dynamic = compileRunnable((cw, v1, v2) -> { compile(input, cw, v1, v2); }); Constructor<Runnable> constructor; try { constructor = dynamic.getConstructor(); } catch (NoSuchMethodException e) { throw new ScriptCompileException("Cannot find constructor for dynamic class."); } Runnable instance; try { instance = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new ScriptCompileException("Cannot instantiate dynamic class."); } return instance; } private Class<Runnable> compileRunnable(CompileConsumer consumer) throws ScriptCompileException { // since this is instance method, local vars start from 1 // 0 = this return compileRunnable(consumer, new VariableContextStack(1)); } @SuppressWarnings("unchecked") private Class<Runnable> compileRunnable(CompileConsumer consumer, VariableContextStack context) throws ScriptCompileException { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); String name = "com/zergatul/scripting/dynamic/DynamicClass_" + counter.incrementAndGet(); writer.visit(V1_5, ACC_PUBLIC, name, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(Runnable.class) }); MethodVisitor constructorVisitor = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); constructorVisitor.visitCode(); constructorVisitor.visitVarInsn(ALOAD, 0); constructorVisitor.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); MethodVisitor runVisitor = writer.visitMethod(ACC_PUBLIC, "run", "()V", null, null); runVisitor.visitCode(); MethodVisitorWrapper constructorVisitorWrapper = new MethodVisitorWrapper(constructorVisitor, name, context); MethodVisitorWrapper runVisitorWrapper = new MethodVisitorWrapper(runVisitor, name, context); runVisitorWrapper.getLoops().push( v -> { throw new ScriptCompileException("Continue statement without loop."); }, v -> { throw new ScriptCompileException("Break statement without loop."); }); consumer.apply(writer, constructorVisitorWrapper, runVisitorWrapper); constructorVisitor.visitInsn(RETURN); constructorVisitor.visitMaxs(0, 0); constructorVisitor.visitEnd(); runVisitor.visitInsn(RETURN); runVisitor.visitMaxs(0, 0); runVisitor.visitEnd(); for (StaticVariableEntry entry : runVisitorWrapper.getContextStack().getStaticVariables()) { if (entry.getClassName().equals(name)) { FieldVisitor fieldVisitor = writer.visitField( ACC_PUBLIC | ACC_STATIC, entry.getIdentifier(), Type.getDescriptor(entry.getType().getJavaClass()), null, null); fieldVisitor.visitEnd(); } } writer.visitEnd(); byte[] code = writer.toByteArray(); return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code); } private void compile( ASTInput input, ClassWriter classWriter, CompilerMethodVisitor constructorVisitor, CompilerMethodVisitor runVisitor ) throws ScriptCompileException { if (input.jjtGetNumChildren() < 2) { throw new ScriptCompileException("ASTInput: num children < 2."); } if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) { throw new ScriptCompileException("ASTInput: static vars list expected."); } if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) { throw new ScriptCompileException("ASTInput: functions list expected."); } compile(variablesList, constructorVisitor); compile(functionsList, classWriter, constructorVisitor); for (int i = 2; i < input.jjtGetNumChildren(); i++) { if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) { throw new ScriptCompileException("ASTInput statement expected."); } compile(statement, runVisitor); } } private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) { throw new ScriptCompileException("ASTStaticVariablesList declaration expected."); } compile(variableDeclaration, visitor); } } private void compile( ASTFunctionsList list, ClassWriter classWriter, CompilerMethodVisitor visitor ) throws ScriptCompileException { for (int i = 0; i < list.jjtGetNumChildren(); i++) { if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) { throw new ScriptCompileException("ASTFunctionsList: declaration expected."); } SType type = getFunctionReturnType(functionDeclaration); ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration); List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration); String name = (String) identifier.jjtGetValue(); visitor.getContextStack().addFunction( name, type, parameters.stream().map(p -> p.type).toArray(SType[]::new), visitor.getClassName()); } for (int i = 0; i < list.jjtGetNumChildren(); i++) { compile( (ASTFunctionDeclaration) list.jjtGetChild(i), classWriter, visitor.getContextStack().newWithStaticVariables(0)); } } private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException { if (declaration.jjtGetNumChildren() != 1) { throw new ScriptCompileException("Invalid static var decl structure."); } Node node = declaration.jjtGetChild(0); if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) { throw new ScriptCompileException("ASTLocalVariableDeclaration expected."); } ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0); ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1); ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0); ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0); ASTVariableInitializer initializer = null; if (variableDeclarator.jjtGetNumChildren() > 1) { initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1); } SType type = parseType(astType); if (initializer != null) { SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor); if (!returnType.equals(type)) { UnaryOperation operation = ImplicitCast.get(returnType, type); if (operation != null) { operation.apply(visitor); } else { throw new ScriptCompileException(String.format("Static variable type %s assigned to expression of type %s.", type, returnType)); } } } else { type.storeDefaultValue(visitor); } String variableName = (String) identifier.jjtGetValue(); if (Arrays.stream(root.getDeclaredFields()).anyMatch(f -> f.getName().equals(variableName))) { throw new ScriptCompileException(String.format("Cannot declare static variable %s because API class with the same name exists.", variableName)); }
VariableEntry variable = visitor.getContextStack().addStatic(variableName, type, visitor.getClassName());
6
2023-12-10 00:37:27+00:00
12k
Lampadina17/MorpheusLauncher
src/team/morpheus/launcher/instance/Morpheus.java
[ { "identifier": "Launcher", "path": "src/team/morpheus/launcher/Launcher.java", "snippet": "public class Launcher {\r\n\r\n private static final MyLogger log = new MyLogger(Launcher.class);\r\n public JSONParser jsonParser = new JSONParser();\r\n private File gameFolder, assetsFolder;\r\n\r\n ...
import com.google.gson.Gson; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import team.morpheus.launcher.Launcher; import team.morpheus.launcher.Main; import team.morpheus.launcher.logging.MyLogger; import team.morpheus.launcher.model.MorpheusSession; import team.morpheus.launcher.model.MorpheusUser; import team.morpheus.launcher.model.products.MorpheusProduct; import team.morpheus.launcher.utils.Utils; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap;
9,909
package team.morpheus.launcher.instance; public class Morpheus { private static final MyLogger log = new MyLogger(Morpheus.class); public MorpheusSession session; public JSONParser jsonParser = new JSONParser(); public MorpheusUser user; public Morpheus(MorpheusSession session) { this.session = session; } public void prepareLaunch() throws Exception { /* Ask server user json */ HashMap<String, String> map = new HashMap<>(); map.put("accessToken", session.getSessionToken());
package team.morpheus.launcher.instance; public class Morpheus { private static final MyLogger log = new MyLogger(Morpheus.class); public MorpheusSession session; public JSONParser jsonParser = new JSONParser(); public MorpheusUser user; public Morpheus(MorpheusSession session) { this.session = session; } public void prepareLaunch() throws Exception { /* Ask server user json */ HashMap<String, String> map = new HashMap<>(); map.put("accessToken", session.getSessionToken());
HttpURLConnection userInfo = Utils.makePostRequest(new URL(String.format("%s/api/userinfo", Main.getMorpheusAPI())), map);
1
2023-12-07 14:34:54+00:00
12k
Serilum/Collective
Common/src/main/java/com/natamus/collective/events/CollectiveEvents.java
[ { "identifier": "RegisterMod", "path": "Common/src/main/java/com/natamus/collective/check/RegisterMod.java", "snippet": "public class RegisterMod {\n\tprivate static final CopyOnWriteArrayList<String> jarlist = new CopyOnWriteArrayList<String>();\n\tprivate static final HashMap<String, String> jartoname...
import com.mojang.datafixers.util.Pair; import com.natamus.collective.check.RegisterMod; import com.natamus.collective.config.CollectiveConfigHandler; import com.natamus.collective.data.GlobalVariables; import com.natamus.collective.functions.BlockPosFunctions; import com.natamus.collective.functions.EntityFunctions; import com.natamus.collective.functions.SpawnEntityFunctions; import com.natamus.collective.objects.SAMObject; import com.natamus.collective.util.CollectiveReference; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity.RemovalReason; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.horse.AbstractHorse; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CopyOnWriteArrayList;
9,832
package com.natamus.collective.events; public class CollectiveEvents { public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>(); public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>(); public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>(); public static void onWorldTick(ServerLevel serverLevel) { if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) { Entity tospawn = entitiesToSpawn.get(serverLevel).get(0); serverLevel.addFreshEntityWithPassengers(tospawn); if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) { Entity rider = entitiesToRide.get(serverLevel).get(tospawn); rider.startRiding(tospawn); entitiesToRide.get(serverLevel).remove(tospawn); } entitiesToSpawn.get(serverLevel).remove(0); } } public static void onServerTick(MinecraftServer minecraftServer) { int serverTickCount = minecraftServer.getTickCount(); for (Pair<Integer, Runnable> pair : scheduledRunnables) { if (pair.getFirst() <= serverTickCount) { minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond())); scheduledRunnables.remove(pair); } } } public static boolean onEntityJoinLevel(Level level, Entity entity) { if (!(entity instanceof LivingEntity)) { return true; } if (RegisterMod.shouldDoCheck) { if (entity instanceof Player) { RegisterMod.joinWorldProcess(level, (Player)entity); } } if (entity.isRemoved()) { return true; } if (GlobalVariables.globalSAMs.isEmpty()) { return true; } Set<String> tags = entity.getTags(); if (tags.contains(CollectiveReference.MOD_ID + ".checked")) { return true; } entity.addTag(CollectiveReference.MOD_ID + ".checked"); EntityType<?> entityType = entity.getType(); if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) { return true; } boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner"); List<SAMObject> possibles = new ArrayList<SAMObject>(); for (SAMObject sam : GlobalVariables.globalSAMs) { if (sam == null) { continue; } if (sam.fromEntityType == null) { continue; } if (sam.fromEntityType.equals(entityType)) { if ((sam.onlyFromSpawner && !isFromSpawner) || (!sam.onlyFromSpawner && isFromSpawner)) { continue; } possibles.add(sam); } } int size = possibles.size(); if (size == 0) { return true; } Vec3 eVec = entity.position(); boolean ageable = entity instanceof AgeableMob;
package com.natamus.collective.events; public class CollectiveEvents { public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>(); public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>(); public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>(); public static void onWorldTick(ServerLevel serverLevel) { if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) { Entity tospawn = entitiesToSpawn.get(serverLevel).get(0); serverLevel.addFreshEntityWithPassengers(tospawn); if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) { Entity rider = entitiesToRide.get(serverLevel).get(tospawn); rider.startRiding(tospawn); entitiesToRide.get(serverLevel).remove(tospawn); } entitiesToSpawn.get(serverLevel).remove(0); } } public static void onServerTick(MinecraftServer minecraftServer) { int serverTickCount = minecraftServer.getTickCount(); for (Pair<Integer, Runnable> pair : scheduledRunnables) { if (pair.getFirst() <= serverTickCount) { minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond())); scheduledRunnables.remove(pair); } } } public static boolean onEntityJoinLevel(Level level, Entity entity) { if (!(entity instanceof LivingEntity)) { return true; } if (RegisterMod.shouldDoCheck) { if (entity instanceof Player) { RegisterMod.joinWorldProcess(level, (Player)entity); } } if (entity.isRemoved()) { return true; } if (GlobalVariables.globalSAMs.isEmpty()) { return true; } Set<String> tags = entity.getTags(); if (tags.contains(CollectiveReference.MOD_ID + ".checked")) { return true; } entity.addTag(CollectiveReference.MOD_ID + ".checked"); EntityType<?> entityType = entity.getType(); if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) { return true; } boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner"); List<SAMObject> possibles = new ArrayList<SAMObject>(); for (SAMObject sam : GlobalVariables.globalSAMs) { if (sam == null) { continue; } if (sam.fromEntityType == null) { continue; } if (sam.fromEntityType.equals(entityType)) { if ((sam.onlyFromSpawner && !isFromSpawner) || (!sam.onlyFromSpawner && isFromSpawner)) { continue; } possibles.add(sam); } } int size = possibles.size(); if (size == 0) { return true; } Vec3 eVec = entity.position(); boolean ageable = entity instanceof AgeableMob;
boolean isOnSurface = BlockPosFunctions.isOnSurface(level, eVec);
3
2023-12-11 22:37:15+00:00
12k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java
[ { "identifier": "MenuCreateReqVO", "path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/vo/menu/MenuCreateReqVO.java", "snippet": "@Schema(description = \"管理后台 - 菜单创建 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npubl...
import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO; import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuUpdateReqVO; import cn.iocoder.yudao.module.system.convert.permission.MenuConvert; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.mysql.permission.MenuMapper; import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants; import cn.iocoder.yudao.module.system.enums.permission.MenuTypeEnum; import cn.iocoder.yudao.module.system.service.tenant.TenantService; import com.google.common.annotations.VisibleForTesting; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Collection; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList; import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
7,946
package cn.iocoder.yudao.module.system.service.permission; /** * 菜单 Service 实现 * * @author 芋道源码 */ @Service @Slf4j public class MenuServiceImpl implements MenuService { @Resource private MenuMapper menuMapper; @Resource private PermissionService permissionService; @Resource @Lazy // 延迟,避免循环依赖报错 private TenantService tenantService; @Override @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, key = "#reqVO.permission", condition = "#reqVO.permission != null")
package cn.iocoder.yudao.module.system.service.permission; /** * 菜单 Service 实现 * * @author 芋道源码 */ @Service @Slf4j public class MenuServiceImpl implements MenuService { @Resource private MenuMapper menuMapper; @Resource private PermissionService permissionService; @Resource @Lazy // 延迟,避免循环依赖报错 private TenantService tenantService; @Override @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, key = "#reqVO.permission", condition = "#reqVO.permission != null")
public Long createMenu(MenuCreateReqVO reqVO) {
0
2023-12-08 02:48:42+00:00
12k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/text/Typewriter.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Actor; import com.senetboom.game.SenetBoom; import com.senetboom.game.frontend.text.RandomText;
8,656
package com.senetboom.game.frontend.text; public class Typewriter { /* Typewrite is used to print text on the screen. It prints one character every 0.1 seconds. It is used to display speech. It has enums for emotion and character (colour white or black) */ public enum Emotion { NORMAL, HAPPY, SAD, ANGRY, CONFUSED } public enum Character { WHITE, BLACK } private final RandomText normalText; private final RandomText happyText; private final RandomText sadText; private final RandomText angryText; private final RandomText confusedText; public Typewriter() { normalText = new RandomText(); normalText.addText("Let us see where the pieces fall."); normalText.addText("A fair move, I suppose."); normalText.addText("The game progresses as expected."); normalText.addText("May the best player win."); normalText.addText("It's your turn, proceed."); normalText.addText("This is a decent challenge."); normalText.addText("We play as the gods watch."); normalText.addText("A typical turn of events."); normalText.addText("Let's maintain our focus."); normalText.addText("Steady as the journey of Ra across the sky."); happyText = new RandomText(); happyText.addText("Blessings of Isis upon my pieces!\n"); happyText.addText("I move as gracefully as the Nile!\n"); happyText.addText("Fortune smiles upon me today!\n"); happyText.addText("I am favored by the gods!\n"); happyText.addText("This is a joyous turn of events!\n"); happyText.addText("My heart is as light as Ma'at's feather!\n"); happyText.addText("Victory shall be mine!\n"); happyText.addText("What a splendid move!\n"); happyText.addText("I dance with the joy of Hathor!\n"); happyText.addText("The gods grant me their favor!\n"); sadText = new RandomText(); sadText.addText("My heart sinks\n" + "like the setting sun!\n"); sadText.addText("I am lost in the desert of defeat!\n"); sadText.addText("The gods have turned their backs on me!\n"); sadText.addText("My spirit is as heavy as lead!\n"); sadText.addText("I mourn my impending loss!\n"); sadText.addText("Such sorrow fills my heart!\n"); sadText.addText("I am adrift on the river of despair!\n"); sadText.addText("This game mirrors my misfortunes!\n"); sadText.addText("Sadness cloaks me like the night!\n"); sadText.addText("I am a servant to ill fate!\n"); angryText = new RandomText(); angryText.addText("By the gods, this is unfair!\n"); angryText.addText("I shall not play this treacherous game!\n"); angryText.addText("The gods have abandoned me!\n"); angryText.addText("Such misfortune is unheard of!\n"); angryText.addText("I am the scorn of Thoth!\n"); angryText.addText("This is an outrage!\n"); angryText.addText("I cannot believe my bad luck!\n"); angryText.addText("This game is cursed!\n"); angryText.addText("How can the pieces move like this?\n"); angryText.addText("You must be cheating, there's no way!\n"); confusedText = new RandomText(); confusedText.addText("What strange magic is this?\n"); confusedText.addText("The pieces move in mysterious ways.\n"); confusedText.addText("I do not understand this outcome.\n"); confusedText.addText("Is this a trick of Anubis?\n"); confusedText.addText("How perplexing!\n"); confusedText.addText("I am puzzled by this turn.\n"); confusedText.addText("The gods play games with my mind.\n"); confusedText.addText("What does this mean?\n"); confusedText.addText("I am lost in the labyrinth of this game.\n"); confusedText.addText("This is beyond my understanding.\n"); } public void makeSpeech(Emotion emotion, Character character){ // create a new speech Speech speech = new Speech(getText(emotion), character); // add it to the stage
package com.senetboom.game.frontend.text; public class Typewriter { /* Typewrite is used to print text on the screen. It prints one character every 0.1 seconds. It is used to display speech. It has enums for emotion and character (colour white or black) */ public enum Emotion { NORMAL, HAPPY, SAD, ANGRY, CONFUSED } public enum Character { WHITE, BLACK } private final RandomText normalText; private final RandomText happyText; private final RandomText sadText; private final RandomText angryText; private final RandomText confusedText; public Typewriter() { normalText = new RandomText(); normalText.addText("Let us see where the pieces fall."); normalText.addText("A fair move, I suppose."); normalText.addText("The game progresses as expected."); normalText.addText("May the best player win."); normalText.addText("It's your turn, proceed."); normalText.addText("This is a decent challenge."); normalText.addText("We play as the gods watch."); normalText.addText("A typical turn of events."); normalText.addText("Let's maintain our focus."); normalText.addText("Steady as the journey of Ra across the sky."); happyText = new RandomText(); happyText.addText("Blessings of Isis upon my pieces!\n"); happyText.addText("I move as gracefully as the Nile!\n"); happyText.addText("Fortune smiles upon me today!\n"); happyText.addText("I am favored by the gods!\n"); happyText.addText("This is a joyous turn of events!\n"); happyText.addText("My heart is as light as Ma'at's feather!\n"); happyText.addText("Victory shall be mine!\n"); happyText.addText("What a splendid move!\n"); happyText.addText("I dance with the joy of Hathor!\n"); happyText.addText("The gods grant me their favor!\n"); sadText = new RandomText(); sadText.addText("My heart sinks\n" + "like the setting sun!\n"); sadText.addText("I am lost in the desert of defeat!\n"); sadText.addText("The gods have turned their backs on me!\n"); sadText.addText("My spirit is as heavy as lead!\n"); sadText.addText("I mourn my impending loss!\n"); sadText.addText("Such sorrow fills my heart!\n"); sadText.addText("I am adrift on the river of despair!\n"); sadText.addText("This game mirrors my misfortunes!\n"); sadText.addText("Sadness cloaks me like the night!\n"); sadText.addText("I am a servant to ill fate!\n"); angryText = new RandomText(); angryText.addText("By the gods, this is unfair!\n"); angryText.addText("I shall not play this treacherous game!\n"); angryText.addText("The gods have abandoned me!\n"); angryText.addText("Such misfortune is unheard of!\n"); angryText.addText("I am the scorn of Thoth!\n"); angryText.addText("This is an outrage!\n"); angryText.addText("I cannot believe my bad luck!\n"); angryText.addText("This game is cursed!\n"); angryText.addText("How can the pieces move like this?\n"); angryText.addText("You must be cheating, there's no way!\n"); confusedText = new RandomText(); confusedText.addText("What strange magic is this?\n"); confusedText.addText("The pieces move in mysterious ways.\n"); confusedText.addText("I do not understand this outcome.\n"); confusedText.addText("Is this a trick of Anubis?\n"); confusedText.addText("How perplexing!\n"); confusedText.addText("I am puzzled by this turn.\n"); confusedText.addText("The gods play games with my mind.\n"); confusedText.addText("What does this mean?\n"); confusedText.addText("I am lost in the labyrinth of this game.\n"); confusedText.addText("This is beyond my understanding.\n"); } public void makeSpeech(Emotion emotion, Character character){ // create a new speech Speech speech = new Speech(getText(emotion), character); // add it to the stage
SenetBoom.typeWriterStage.addActor(speech);
0
2023-12-05 22:19:00+00:00
12k
ItzOverS/CoReScreen
src/main/java/me/overlight/corescreen/Commands.java
[ { "identifier": "AnalyzeModule", "path": "src/main/java/me/overlight/corescreen/Analyzer/AnalyzeModule.java", "snippet": "public class AnalyzeModule {\n public String getName() {\n return name;\n }\n\n private final String name;\n\n public AnalyzeModule(String name) {\n this.na...
import me.overlight.corescreen.Analyzer.AnalyzeModule; import me.overlight.corescreen.Analyzer.AnalyzerManager; import me.overlight.corescreen.ClientSettings.CSManager; import me.overlight.corescreen.ClientSettings.CSModule; import me.overlight.corescreen.Freeze.Cache.CacheManager; import me.overlight.corescreen.Freeze.FreezeManager; import me.overlight.corescreen.Freeze.Warps.WarpManager; import me.overlight.corescreen.Profiler.ProfilerManager; import me.overlight.corescreen.Profiler.Profiles.NmsHandler; import me.overlight.corescreen.Profiler.ProfilingSystem; import me.overlight.corescreen.Test.TestCheck; import me.overlight.corescreen.Test.TestManager; import me.overlight.corescreen.Vanish.VanishManager; import me.overlight.corescreen.api.Freeze.PlayerFreezeEvent; import me.overlight.corescreen.api.Freeze.PlayerUnfreezeEvent; import me.overlight.powerlib.Chat.Text.impl.PlayerChatMessage; import me.overlight.powerlib.Chat.Text.impl.ext.ClickableCommand; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors;
9,278
Player who = CoReScreen.getPlayer(args[0]); if (who == null) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Optional<CSModule> module = CSManager.modules.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst(); if(!module.isPresent()){ commandSender.sendMessage(CoReScreen.translate("messages.client-settings.invalid-client-setting")); return false; } if(!commandSender.hasPermission("corescreen.clientsettings." + module.get().getPermission().toLowerCase())){ commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.get().getName())); return false; } commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.get().getName()).replace("%value%", module.get().getValue(who))); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) { if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); if (args.length == 2) return CSManager.modules.stream().filter(r -> commandSender.hasPermission("corescreen.clientsettings." + r.getPermission())).map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Freeze implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1) { if (!commandSender.hasPermission("corescreen.freeze")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } Player who = CoReScreen.getPlayer(args[0]); if (who == null) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } if (who.getName().equals(commandSender.getName()) && (commandSender instanceof Player && !FreezeManager.isFrozen((Player) commandSender))) { who.sendMessage(CoReScreen.translate("messages.freeze.command.freeze-self")); return false; } FreezeManager.toggleFreeze(who); if (FreezeManager.isFrozen(who)) { PlayerFreezeEvent event = new PlayerFreezeEvent(false, who, !(commandSender instanceof Player)? null: (Player) commandSender); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isCancelled()) return false; commandSender.sendMessage(CoReScreen.translate("messages.freeze.command.you-freeze-other").replace("%who%", args[0])); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).filter(p -> !p.getName().equals(commandSender.getName())).forEach(p -> p.sendMessage(CoReScreen.translate("messages.freeze.command.freeze-other").replace("%other%", args[0]).replace("%who%", commandSender.getName()))); final List<Integer> ignored$alerts = CoReScreen.getInstance().getConfig().getIntegerList("settings.freeze.time-remaining-alert.ignore-alert"), manual$alerts = CoReScreen.getInstance().getConfig().getIntegerList("settings.freeze.time-remaining-alert.alert-come-to"); final int auto$alerts = CoReScreen.getInstance().getConfig().getInt("settings.freeze.time-remaining-alert.alert-every"); if(WarpManager.isEnabled && !WarpManager.warpPlayerToEmpty(who)) commandSender.sendMessage(CoReScreen.translate("messages.freeze.command.warping-failed").replace("%other%", who.getName())); new BukkitRunnable() { private int counter = CoReScreen.getInstance().getConfig().getInt("settings.freeze.time-remaining-alert.full"); @Override public void run() { if (!who.isOnline()) { cancel(); return; } if (!FreezeManager.isFrozen(who)) { cancel(); return; } if (counter < 0) { who.sendMessage(CoReScreen.translate("settings.freeze.time-remaining-alert.times-up")); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> { p.sendMessage(CoReScreen.translate("settings.freeze.time-remaining-alert.times-up-staff").replace("%who%", who.getName())); List<BaseComponent> components = new ArrayList<>(); for (String k : CoReScreen.getInstance().getConfig().getStringList("settings.freeze.time-remaining-alert.action-message")) { if (k.startsWith("%")) { ConfigurationSection section = CoReScreen.getInstance().getConfig().getConfigurationSection("settings.freeze.time-remaining-alert.actions." + k.replace("%", "").trim()); if (section != null) { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', section.getString("content") .replace("%who%", who.getName()) .replace("%prefix%", Commands.prefix == null ? "&e&lCoRe&cVanish &6»" : Commands.prefix))) .click(new ClickableCommand(section.getString("command").replace("%who%", who.getName()))) .hover(ChatColor.translateAlternateColorCodes('&', section.getString("hover").replace("%who%", who.getName()))).getComponent()); } } else { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', k)).getComponent()); } } p.spigot().sendMessage(components.toArray(new BaseComponent[0])); }); cancel(); return; } if (ignored$alerts.contains(counter)) { counter--; return; } if (counter % auto$alerts == 0 || manual$alerts.contains(counter)) { String text = CoReScreen.translate("settings.freeze.time-remaining-alert.message"); if (counter % 60 == 0) text = text.replace("%time%", (counter / 60) + " minute" + (counter > 60 ? "s" : "")); else if (counter > 60) text = text.replace("%time%", (counter / 60) + " minutes " + (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); else text = text.replace("%time%", (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); String text2 = CoReScreen.translate("settings.freeze.time-remaining-alert.message-staff").replace("%who%", who.getName()); if (!manual$alerts.contains(counter)) { if (counter % 60 == 0) text2 = text2.replace("%time%", (counter / 60) + " minute" + (counter > 60 ? "s" : "")); else if (counter > 60) text2 = text2.replace("%time%", (counter / 60) + " minutes " + (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); else text2 = text2.replace("%time%", (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); } who.sendMessage(text); final String finalText = text2; if (!manual$alerts.contains(counter)) Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> p.sendMessage(finalText)); CacheManager.cache(who, "[TIMER]" + text2); } counter--; } }.runTaskTimer(CoReScreen.getInstance(), 0, 20); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-freeze")).setContent("**" + who.getName() + "** has frozen by **" + commandSender.getName() + "**!").execute(); } else {
package me.overlight.corescreen; public class Commands { public static String prefix; public static class Vanish implements CommandExecutor { private final HashMap<String, Long> cooldown_vanish = new HashMap<>(); private final HashMap<String, Long> cooldown_unvanish = new HashMap<>(); private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"), unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish"); @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 0) { if (!commandSender.hasPermission("corescreen.vanish.self")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) || (VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) { if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis()); else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis()); VanishManager.toggleVanish((Player) commandSender); if (VanishManager.isVanish((Player) commandSender)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish")); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute(); } } else { commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message")); } } else if (args.length == 1) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); VanishManager.toggleVanish(who); if (VanishManager.isVanish(who)) { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute(); } else { commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute(); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.vanish.other")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } boolean forceEnabled = args[1].equalsIgnoreCase("on"); List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); if (forceEnabled) VanishManager.vanishPlayer(who); else VanishManager.unVanishPlayer(who); if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName())); else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName())); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Profiler implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("remove")) { if (!commandSender.hasPermission("corescreen.profiler.remove")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } ProfilerManager.removeProfiler((Player) commandSender); } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.profiler.append")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); try { ProfilingSystem profiler = ProfilerManager.profilingSystems.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).collect(Collectors.toList()).get(0); ProfilerManager.addProfiler((Player) commandSender, who, profiler.getMode()); commandSender.sendMessage(CoReScreen.translate("messages.profiler.profiler-success-add").replace("%who%", who.getName()).replace("%profiler%", args[1])); } catch (Exception ex) { if(NmsHandler.handlers.stream().anyMatch(r -> r.getName().equalsIgnoreCase(args[1]))){ ProfilerManager.addProfiler((Player) commandSender, who, NmsHandler.handlers.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst().get()); } else { commandSender.sendMessage(CoReScreen.translate("messages.profiler.invalid-profiler-name").replace("%name%", args[1])); } } } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) { if (args.length == 1) { List<String> out = new ArrayList<>(); if(commandSender.hasPermission("corescreen.profiler.append")) out.addAll(Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList())); if(commandSender.hasPermission("corescreen.profiler.remove")) out.add("remove"); return out; }; if (args.length == 2 && commandSender.hasPermission("corescreen.profiler.append")) { List<String> out = new ArrayList<>(ProfilerManager.profilingSystems.stream().map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList())); out.addAll(NmsHandler.handlers.stream().map(NmsHandler.NmsWrapper::getName).collect(Collectors.toList())); return out; }; return null; } } } public static class Test implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 2) { if (!commandSender.hasPermission("corescreen.test")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); TestCheck test = null; try { test = TestManager.tests.stream().filter(r -> Arrays.asList(r.getAlias()).contains(args[1])).collect(Collectors.toList()).get(0); } catch (Exception ex) { } if (test == null) { commandSender.sendMessage(CoReScreen.translate("messages.test.test-not-found").replace("%test%", args[1])); return false; } if (!commandSender.hasPermission("corescreen.test." + test.getName().toLowerCase())) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } test.handle(who, (Player) commandSender); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) { if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); if (args.length == 2) return TestManager.tests.stream().map(r -> r.getAlias()[0].toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Analyzer implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 2 || args.length == 3) { if (!commandSender.hasPermission("corescreen.analyzer")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList()); if (LWho.isEmpty()) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Player who = LWho.get(0); AnalyzeModule module = AnalyzerManager.analyzers.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst().orElse(null); if (module == null) { commandSender.sendMessage(CoReScreen.translate("messages.test.test-not-found").replace("%test%", args[1])); return false; } if (!commandSender.hasPermission("corescreen.analyzer." + module.getName().toLowerCase())) { commandSender.sendMessage(CoReScreen.translate("messages.analyzer.no-permission")); return false; } module.activate(who); commandSender.sendMessage(CoReScreen.translate("messages.analyzer.analyzing-started").replace("%player%", who.getName())); int delay; try { delay = args.length == 2 ? 5 : Integer.parseInt(args[2]); } catch(Exception ex) { commandSender.sendMessage(CoReScreen.translate("messages.analyzer.illegal-number")); return false; } if(!(delay >= 3 && delay <= 25)) { commandSender.sendMessage(CoReScreen.translate("messages.analyzer.illegal-number")); return false; } new BukkitRunnable(){ @Override public void run() { if(CoReScreen.getPlayer(commandSender.getName()) == null) { cancel(); return; } if(CoReScreen.getPlayer(who.getName()) == null) { cancel(); commandSender.sendMessage(CoReScreen.translate("messages.analyzer.analyzer-cancelled")); return; } if(t >= delay * 10){ commandSender.sendMessage(prefix); commandSender.sendMessage("§9Analyzer Result §9§l-------------"); module.result((Player) commandSender, who); commandSender.sendMessage("§9§l--------------------------"); cancel(); return; } t++; } private int t = 0; }.runTaskTimerAsynchronously(CoReScreen.getInstance(), 0, 2); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) { if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); if (args.length == 2) return AnalyzerManager.analyzers.stream().map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class ClientSettings implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1) { if (!commandSender.hasPermission("corescreen.clientsettings")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } Player who = CoReScreen.getPlayer(args[0]); if (who == null) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } AtomicInteger i = new AtomicInteger(0); CSManager.modules.forEach(module -> { if (!commandSender.hasPermission("corescreen.clientsettings." + module.getPermission().toLowerCase())) { commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.getName())); return; } commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.getName()).replace("%value%", module.getValue(who))); i.set(i.get() + 1); }); if(i.get() == 0){ commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-view-all")); } } else if (args.length == 2) { if (!commandSender.hasPermission("corescreen.clientsettings")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } if (!(commandSender instanceof Player)) { commandSender.sendMessage(CoReScreen.translate("messages.only-players")); return false; } Player who = CoReScreen.getPlayer(args[0]); if (who == null) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } Optional<CSModule> module = CSManager.modules.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst(); if(!module.isPresent()){ commandSender.sendMessage(CoReScreen.translate("messages.client-settings.invalid-client-setting")); return false; } if(!commandSender.hasPermission("corescreen.clientsettings." + module.get().getPermission().toLowerCase())){ commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.get().getName())); return false; } commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.get().getName()).replace("%value%", module.get().getValue(who))); } return false; } public static class TabComplete implements TabCompleter { @Override public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) { if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); if (args.length == 2) return CSManager.modules.stream().filter(r -> commandSender.hasPermission("corescreen.clientsettings." + r.getPermission())).map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()); return null; } } } public static class Freeze implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) { if (args.length == 1) { if (!commandSender.hasPermission("corescreen.freeze")) { commandSender.sendMessage(CoReScreen.translate("messages.no-permission")); return false; } Player who = CoReScreen.getPlayer(args[0]); if (who == null) { commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0])); return false; } if (who.getName().equals(commandSender.getName()) && (commandSender instanceof Player && !FreezeManager.isFrozen((Player) commandSender))) { who.sendMessage(CoReScreen.translate("messages.freeze.command.freeze-self")); return false; } FreezeManager.toggleFreeze(who); if (FreezeManager.isFrozen(who)) { PlayerFreezeEvent event = new PlayerFreezeEvent(false, who, !(commandSender instanceof Player)? null: (Player) commandSender); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isCancelled()) return false; commandSender.sendMessage(CoReScreen.translate("messages.freeze.command.you-freeze-other").replace("%who%", args[0])); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).filter(p -> !p.getName().equals(commandSender.getName())).forEach(p -> p.sendMessage(CoReScreen.translate("messages.freeze.command.freeze-other").replace("%other%", args[0]).replace("%who%", commandSender.getName()))); final List<Integer> ignored$alerts = CoReScreen.getInstance().getConfig().getIntegerList("settings.freeze.time-remaining-alert.ignore-alert"), manual$alerts = CoReScreen.getInstance().getConfig().getIntegerList("settings.freeze.time-remaining-alert.alert-come-to"); final int auto$alerts = CoReScreen.getInstance().getConfig().getInt("settings.freeze.time-remaining-alert.alert-every"); if(WarpManager.isEnabled && !WarpManager.warpPlayerToEmpty(who)) commandSender.sendMessage(CoReScreen.translate("messages.freeze.command.warping-failed").replace("%other%", who.getName())); new BukkitRunnable() { private int counter = CoReScreen.getInstance().getConfig().getInt("settings.freeze.time-remaining-alert.full"); @Override public void run() { if (!who.isOnline()) { cancel(); return; } if (!FreezeManager.isFrozen(who)) { cancel(); return; } if (counter < 0) { who.sendMessage(CoReScreen.translate("settings.freeze.time-remaining-alert.times-up")); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> { p.sendMessage(CoReScreen.translate("settings.freeze.time-remaining-alert.times-up-staff").replace("%who%", who.getName())); List<BaseComponent> components = new ArrayList<>(); for (String k : CoReScreen.getInstance().getConfig().getStringList("settings.freeze.time-remaining-alert.action-message")) { if (k.startsWith("%")) { ConfigurationSection section = CoReScreen.getInstance().getConfig().getConfigurationSection("settings.freeze.time-remaining-alert.actions." + k.replace("%", "").trim()); if (section != null) { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', section.getString("content") .replace("%who%", who.getName()) .replace("%prefix%", Commands.prefix == null ? "&e&lCoRe&cVanish &6»" : Commands.prefix))) .click(new ClickableCommand(section.getString("command").replace("%who%", who.getName()))) .hover(ChatColor.translateAlternateColorCodes('&', section.getString("hover").replace("%who%", who.getName()))).getComponent()); } } else { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', k)).getComponent()); } } p.spigot().sendMessage(components.toArray(new BaseComponent[0])); }); cancel(); return; } if (ignored$alerts.contains(counter)) { counter--; return; } if (counter % auto$alerts == 0 || manual$alerts.contains(counter)) { String text = CoReScreen.translate("settings.freeze.time-remaining-alert.message"); if (counter % 60 == 0) text = text.replace("%time%", (counter / 60) + " minute" + (counter > 60 ? "s" : "")); else if (counter > 60) text = text.replace("%time%", (counter / 60) + " minutes " + (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); else text = text.replace("%time%", (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); String text2 = CoReScreen.translate("settings.freeze.time-remaining-alert.message-staff").replace("%who%", who.getName()); if (!manual$alerts.contains(counter)) { if (counter % 60 == 0) text2 = text2.replace("%time%", (counter / 60) + " minute" + (counter > 60 ? "s" : "")); else if (counter > 60) text2 = text2.replace("%time%", (counter / 60) + " minutes " + (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); else text2 = text2.replace("%time%", (counter % 60) + " second" + (counter % 60 == 1 ? "" : "s")); } who.sendMessage(text); final String finalText = text2; if (!manual$alerts.contains(counter)) Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> p.sendMessage(finalText)); CacheManager.cache(who, "[TIMER]" + text2); } counter--; } }.runTaskTimer(CoReScreen.getInstance(), 0, 20); DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-freeze")).setContent("**" + who.getName() + "** has frozen by **" + commandSender.getName() + "**!").execute(); } else {
PlayerUnfreezeEvent event = new PlayerUnfreezeEvent(false, who, !(commandSender instanceof Player)? null: (Player) commandSender);
14
2023-12-07 16:34:39+00:00
12k
fabriciofx/cactoos-pdf
src/test/java/com/github/fabriciofx/cactoos/pdf/object/InformationTest.java
[ { "identifier": "Document", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Document.java", "snippet": "public final class Document implements Bytes {\n /**\n * PDF Version.\n */\n private static final String VERSION = \"1.3\";\n\n /**\n * PDF binary file signature.\n *...
import com.github.fabriciofx.cactoos.pdf.Document; import com.github.fabriciofx.cactoos.pdf.Font; import com.github.fabriciofx.cactoos.pdf.Id; import com.github.fabriciofx.cactoos.pdf.content.Contents; import com.github.fabriciofx.cactoos.pdf.content.Text; import com.github.fabriciofx.cactoos.pdf.id.Serial; import com.github.fabriciofx.cactoos.pdf.page.DefaultPage; import com.github.fabriciofx.cactoos.pdf.page.Format; import com.github.fabriciofx.cactoos.pdf.pages.DefaultPages; import com.github.fabriciofx.cactoos.pdf.resource.Resources; import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman; import com.github.fabriciofx.cactoos.pdf.text.Date; import org.cactoos.text.Concatenated; import org.cactoos.text.FormattedText; import org.cactoos.text.Joined; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsText; import org.llorllale.cactoos.matchers.StartsWith;
7,586
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf.object; /** * Test case for {@link Information}. * * @since 0.0.1 */ final class InformationTest { @Test void info() throws Exception { final Date date = new Date(2023, 12, 11, 20, 11, 32, "Etc/GMT-3"); new Assertion<>( "Must contain metadata contents", new TextOf( new Information( new Serial(), "Title", "Hello World", "Subject", "PDF document", "Author", "Fabricio Cabral", "Creator", "cactoos-pdf", "Producer", "cactoos-pdf", "CreationDate", date.asString(), "ModDate", date.asString(), "Keywords", "cactoos pdf elegant objects" ).indirect() ), new IsText( new FormattedText( new Joined( " ", "1 0 obj\n<<", "/Title (Hello World)", "/Subject (PDF document)", "/Author (Fabricio Cabral)", "/Creator (cactoos-pdf)", "/Producer (cactoos-pdf)", "/CreationDate (%s)", "/ModDate (%s)", "/Keywords (cactoos pdf elegant objects)", ">>\nendobj\n" ), date.asString(), date.asString() ) ) ).affirm(); } @Test void empty() throws Exception { new Assertion<>( "Must contain correct metadata from empty information", new TextOf( new Information( new Serial() ).indirect() ), new IsText( new FormattedText( new Joined( " ", "1 0 obj\n<<", "/Producer (cactoos-pdf)", ">>\nendobj\n" ) ) ) ).affirm(); } @Test void document() throws Exception { final Date date = new Date(2023, 12, 11, 20, 11, 32, "Etc/GMT-3"); final Id id = new Serial(); final Font font = new TimesRoman(id, 18); new Assertion<>( "Must match with information from a hello world PDF document", new TextOf( new Document( id, new Information( id, "Title", "Hello World", "Subject", "PDF document", "Author", "Fabricio Cabral", "Creator", "cactoos-pdf", "Producer", "cactoos-pdf", "CreationDate", date.asString(), "ModDate", date.asString(), "Keywords", "cactoos pdf elegant objects" ), new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id,
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf.object; /** * Test case for {@link Information}. * * @since 0.0.1 */ final class InformationTest { @Test void info() throws Exception { final Date date = new Date(2023, 12, 11, 20, 11, 32, "Etc/GMT-3"); new Assertion<>( "Must contain metadata contents", new TextOf( new Information( new Serial(), "Title", "Hello World", "Subject", "PDF document", "Author", "Fabricio Cabral", "Creator", "cactoos-pdf", "Producer", "cactoos-pdf", "CreationDate", date.asString(), "ModDate", date.asString(), "Keywords", "cactoos pdf elegant objects" ).indirect() ), new IsText( new FormattedText( new Joined( " ", "1 0 obj\n<<", "/Title (Hello World)", "/Subject (PDF document)", "/Author (Fabricio Cabral)", "/Creator (cactoos-pdf)", "/Producer (cactoos-pdf)", "/CreationDate (%s)", "/ModDate (%s)", "/Keywords (cactoos pdf elegant objects)", ">>\nendobj\n" ), date.asString(), date.asString() ) ) ).affirm(); } @Test void empty() throws Exception { new Assertion<>( "Must contain correct metadata from empty information", new TextOf( new Information( new Serial() ).indirect() ), new IsText( new FormattedText( new Joined( " ", "1 0 obj\n<<", "/Producer (cactoos-pdf)", ">>\nendobj\n" ) ) ) ).affirm(); } @Test void document() throws Exception { final Date date = new Date(2023, 12, 11, 20, 11, 32, "Etc/GMT-3"); final Id id = new Serial(); final Font font = new TimesRoman(id, 18); new Assertion<>( "Must match with information from a hello world PDF document", new TextOf( new Document( id, new Information( id, "Title", "Hello World", "Subject", "PDF document", "Author", "Fabricio Cabral", "Creator", "cactoos-pdf", "Producer", "cactoos-pdf", "CreationDate", date.asString(), "ModDate", date.asString(), "Keywords", "cactoos pdf elegant objects" ), new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id,
new Resources(id, font),
9
2023-12-05 00:07:24+00:00
12k
BeansGalaxy/Beans-Backpacks-2
fabric/src/main/java/com/beansgalaxy/backpacks/FabricMain.java
[ { "identifier": "BackpackEntity", "path": "common/src/main/java/com/beansgalaxy/backpacks/entity/BackpackEntity.java", "snippet": "public class BackpackEntity extends Backpack {\n public Direction direction;\n protected BlockPos pos;\n public double actualY;\n private static final in...
import com.beansgalaxy.backpacks.entity.BackpackEntity; import com.beansgalaxy.backpacks.events.*; import com.beansgalaxy.backpacks.events.advancements.EquipAnyCriterion; import com.beansgalaxy.backpacks.events.advancements.PlaceCriterion; import com.beansgalaxy.backpacks.events.advancements.SpecialCriterion; import com.beansgalaxy.backpacks.items.BackpackItem; import com.beansgalaxy.backpacks.items.DyableBackpack; import com.beansgalaxy.backpacks.items.RecipeCrafting; import com.beansgalaxy.backpacks.items.RecipeSmithing; import com.beansgalaxy.backpacks.network.NetworkPackages; import com.beansgalaxy.backpacks.screen.BackpackMenu; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.entity.event.v1.EntityElytraEvents; import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerType; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer;
10,141
package com.beansgalaxy.backpacks; public class FabricMain implements ModInitializer { public static EquipAnyCriterion EQUIP_ANY = CriteriaTriggers.register(Constants.MOD_ID + "/equip_any", new EquipAnyCriterion()); public static PlaceCriterion PLACE = CriteriaTriggers.register(Constants.MOD_ID + "/place", new PlaceCriterion()); public static SpecialCriterion SPECIAL = CriteriaTriggers.register(Constants.MOD_ID + "/special", new SpecialCriterion()); @Override public void onInitialize() { NetworkPackages.registerC2SPackets(); ServerLifecycleEvents.SYNC_DATA_PACK_CONTENTS.register(new SyncDataEvent()); ServerPlayerEvents.COPY_FROM.register(new CopyPlayerEvent()); ServerLivingEntityEvents.AFTER_DEATH.register(new LivingEntityDeath()); EntityElytraEvents.CUSTOM.register(new ElytraFlightEvent()); UseBlockCallback.EVENT.register(new PlayerInteractEvent()); Sounds.register(); Constants.LOG.info("Initializing Beans' Backpacks Fabric"); CommonClass.init(); } public static final Item LEATHER_BACKPACK = registerItem("backpack", new DyableBackpack());
package com.beansgalaxy.backpacks; public class FabricMain implements ModInitializer { public static EquipAnyCriterion EQUIP_ANY = CriteriaTriggers.register(Constants.MOD_ID + "/equip_any", new EquipAnyCriterion()); public static PlaceCriterion PLACE = CriteriaTriggers.register(Constants.MOD_ID + "/place", new PlaceCriterion()); public static SpecialCriterion SPECIAL = CriteriaTriggers.register(Constants.MOD_ID + "/special", new SpecialCriterion()); @Override public void onInitialize() { NetworkPackages.registerC2SPackets(); ServerLifecycleEvents.SYNC_DATA_PACK_CONTENTS.register(new SyncDataEvent()); ServerPlayerEvents.COPY_FROM.register(new CopyPlayerEvent()); ServerLivingEntityEvents.AFTER_DEATH.register(new LivingEntityDeath()); EntityElytraEvents.CUSTOM.register(new ElytraFlightEvent()); UseBlockCallback.EVENT.register(new PlayerInteractEvent()); Sounds.register(); Constants.LOG.info("Initializing Beans' Backpacks Fabric"); CommonClass.init(); } public static final Item LEATHER_BACKPACK = registerItem("backpack", new DyableBackpack());
public static final Item METAL_BACKPACK = registerItem("metal_backpack", new BackpackItem());
4
2023-12-14 21:55:00+00:00
12k
sinbad-navigator/erp-crm
common/src/main/java/com/ec/common/core/controller/BaseController.java
[ { "identifier": "HttpStatus", "path": "common/src/main/java/com/ec/common/constant/HttpStatus.java", "snippet": "public class HttpStatus {\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static final int CREATED = 201;\n\n /**\...
import java.beans.PropertyEditorSupport; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ec.common.constant.HttpStatus; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.domain.model.LoginUser; import com.ec.common.core.page.PageDomain; import com.ec.common.core.page.TableDataInfo; import com.ec.common.core.page.TableSupport; import com.ec.common.utils.DateUtils; import com.ec.common.utils.PageUtils; import com.ec.common.utils.SecurityUtils; import com.ec.common.utils.StringUtils; import com.ec.common.utils.sql.SqlUtil;
10,627
package com.ec.common.core.controller; /** * web层通用数据处理 * * @author ec */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBinder 对象进行初始化,用于将字符串类型的日期转换成 java.util.Date 类型。 public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({"rawtypes", "unchecked"}) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(HttpStatus.SUCCESS); rspData.setMsg("查询成功"); rspData.setRows(list); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? AjaxResult.success() : AjaxResult.error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } /** * 页面跳转 */ public String redirect(String url) { return StringUtils.format("redirect:{}", url); } /** * 获取用户缓存信息 */ public LoginUser getLoginUser() {
package com.ec.common.core.controller; /** * web层通用数据处理 * * @author ec */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBinder 对象进行初始化,用于将字符串类型的日期转换成 java.util.Date 类型。 public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({"rawtypes", "unchecked"}) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(HttpStatus.SUCCESS); rspData.setMsg("查询成功"); rspData.setRows(list); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? AjaxResult.success() : AjaxResult.error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } /** * 页面跳转 */ public String redirect(String url) { return StringUtils.format("redirect:{}", url); } /** * 获取用户缓存信息 */ public LoginUser getLoginUser() {
return SecurityUtils.getLoginUser();
8
2023-12-07 14:23:12+00:00
12k
ganeshbabugb/NASC-CMS
src/main/java/com/nasc/application/views/marks/table/MarksView.java
[ { "identifier": "AcademicYearEntity", "path": "src/main/java/com/nasc/application/data/core/AcademicYearEntity.java", "snippet": "@Data\n@Entity\n@Table(name = \"t_academic_year\")\npublic class AcademicYearEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY...
import com.flowingcode.vaadin.addons.fontawesome.FontAwesome; import com.nasc.application.data.core.AcademicYearEntity; import com.nasc.application.data.core.DepartmentEntity; import com.nasc.application.data.core.SubjectEntity; import com.nasc.application.data.core.User; import com.nasc.application.data.core.dto.StudentMarksDTO; import com.nasc.application.data.core.dto.StudentSubjectInfo; import com.nasc.application.data.core.enums.ExamType; import com.nasc.application.data.core.enums.Role; import com.nasc.application.data.core.enums.Semester; import com.nasc.application.data.core.enums.StudentSection; import com.nasc.application.services.*; import com.nasc.application.utils.NotificationUtils; import com.nasc.application.utils.UIUtils; import com.nasc.application.views.MainLayout; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Html; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.charts.Chart; import com.vaadin.flow.component.charts.export.SVGGenerator; import com.vaadin.flow.component.charts.model.*; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.combobox.ComboBoxVariant; import com.vaadin.flow.component.contextmenu.ContextMenu; import com.vaadin.flow.component.contextmenu.MenuItem; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.grid.ColumnTextAlign; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.GridVariant; import com.vaadin.flow.component.grid.HeaderRow; import com.vaadin.flow.component.grid.dataview.GridListDataView; import com.vaadin.flow.component.gridpro.GridPro; import com.vaadin.flow.component.gridpro.GridProVariant; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.NumberField; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.textfield.TextFieldVariant; import com.vaadin.flow.data.provider.Query; import com.vaadin.flow.data.renderer.TextRenderer; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.StreamResource; import jakarta.annotation.security.RolesAllowed; import lombok.extern.slf4j.Slf4j; import org.vaadin.olli.FileDownloadWrapper; import software.xdev.vaadin.grid_exporter.GridExporter; import software.xdev.vaadin.grid_exporter.column.ColumnConfigurationBuilder; import software.xdev.vaadin.grid_exporter.jasper.format.HtmlFormat; import software.xdev.vaadin.grid_exporter.jasper.format.PdfFormat; import software.xdev.vaadin.grid_exporter.jasper.format.XlsxFormat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.*; import java.util.function.Consumer;
8,234
Button exportButton = new Button("Export", FontAwesome.Solid.FILE_EXPORT.create(), e -> { ExamType selectedExamType = examTypeComboBox.getValue(); Semester selectedSemester = semesterComboBox.getValue(); DepartmentEntity selectedDepartment = departmentComboBox.getValue(); AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue(); StudentSection studentSection = studentSectionComboBox.getValue(); // Check Grid and Filter Before Export int size = marksGrid.getDataProvider().size(new Query<>()); if (!isFilterInValid() && size > 0) { String fileName = selectedDepartment.getShortName() + "_" + selectedAcademicYear.getStartYear() + "-" + selectedAcademicYear.getEndYear() + "_" + studentSection.getDisplayName() + "_" + selectedSemester.getDisplayName() + "_" + selectedExamType.getDisplayName() + "_Marks"; XlsxFormat xlsxFormat = new XlsxFormat(); PdfFormat pdfFormat = new PdfFormat(); HtmlFormat htmlFormat = new HtmlFormat(); gridExporter = GridExporter .newWithDefaults(marksGrid) .withFileName(fileName) // Ignoring chart column .withColumnFilter(studentMarksDTOColumn -> studentMarksDTOColumn.isVisible() && !studentMarksDTOColumn.getKey().equals("Chart")) .withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat) .withPreSelectedFormat(xlsxFormat) .withColumnConfigurationBuilder(new ColumnConfigurationBuilder()); gridExporter.open(); } } ); exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL); HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton); horizontalLayout.setWidthFull(); horizontalLayout.setJustifyContentMode(JustifyContentMode.END); horizontalLayout.setAlignItems(Alignment.CENTER); add(new H3("Marks View"), filterLayout, horizontalLayout, marksGrid); setSizeFull(); } private boolean isFilterInValid() { return examTypeComboBox.getValue() == null || semesterComboBox.getValue() == null || departmentComboBox.getValue() == null || academicYearComboBox.getValue() == null || studentSectionComboBox.getValue() == null; } private static Component createFilterHeader(Consumer<String> filterChangeConsumer) { TextField textField = new TextField(); textField.setValueChangeMode(ValueChangeMode.EAGER); textField.setClearButtonVisible(true); textField.addThemeVariants(TextFieldVariant.LUMO_SMALL); textField.setWidthFull(); // CASE IN SENSITIVE textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase())); return textField; } private void configureComboBoxes() { List<AcademicYearEntity> academicYears = academicYearService.findAll(); List<DepartmentEntity> departments = departmentService.findAll(); Semester[] semesters = Semester.values(); ExamType[] examTypes = ExamType.values(); StudentSection[] studentSections = StudentSection.values(); semesterComboBox.setItems(semesters); semesterComboBox.setItemLabelGenerator(Semester::getDisplayName); semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); semesterComboBox.setRequiredIndicatorVisible(true); examTypeComboBox.setItems(examTypes); examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName); examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); examTypeComboBox.setRequiredIndicatorVisible(true); academicYearComboBox.setItems(academicYears); academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear()); academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); academicYearComboBox.setRequiredIndicatorVisible(true); departmentComboBox.setItems(departments); departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName()); departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); departmentComboBox.setRequiredIndicatorVisible(true); studentSectionComboBox.setItems(studentSections); studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName); studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); studentSectionComboBox.setRequiredIndicatorVisible(true); } private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) { counts.totalPass = 0; counts.totalFail = 0; counts.totalPresent = 0; counts.totalAbsent = 0; counts.subjectPassCounts.clear(); counts.subjectFailCounts.clear(); counts.subjectPresentCounts.clear(); counts.subjectAbsentCounts.clear(); for (StudentMarksDTO studentMarksDTO : allStudentMarks) { updateTotalPassFailCounts(studentMarksDTO, counts); } } private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
package com.nasc.application.views.marks.table; @Route(value = "marks", layout = MainLayout.class) @RolesAllowed({"HOD", "ADMIN", "PROFESSOR"}) @PageTitle("Marks") @CssImport( themeFor = "vaadin-grid", value = "./recipe/gridcell/grid-cell.css" ) @Slf4j public class MarksView extends VerticalLayout { // Service private final MarksService marksService; private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final Button menuButton = new Button("Show/Hide Columns"); private final SubjectService subjectService; private final UserService userService; // Grid private final GridPro<StudentMarksDTO> marksGrid = new GridPro<>(StudentMarksDTO.class); private GridListDataView<StudentMarksDTO> dataProvider; // Combobox private final ComboBox<ExamType> examTypeComboBox = new ComboBox<>("Select Exam Type"); private final ComboBox<Semester> semesterComboBox = new ComboBox<>("Select Semester"); private final ComboBox<DepartmentEntity> departmentComboBox = new ComboBox<>("Select Department"); private final ComboBox<AcademicYearEntity> academicYearComboBox = new ComboBox<>("Select Academic Year"); private final ComboBox<StudentSection> studentSectionComboBox = new ComboBox<>("Select Student Section"); // UTILS private final ColumnToggleContextMenu contextMenu = new ColumnToggleContextMenu(menuButton); private final HeaderRow headerRow; private GridExporter<StudentMarksDTO> gridExporter; public MarksView(MarksService marksService, DepartmentService departmentService, AcademicYearService academicYearService, SubjectService subjectService, UserService userService ) { this.marksService = marksService; this.departmentService = departmentService; this.academicYearService = academicYearService; this.subjectService = subjectService; this.userService = userService; configureComboBoxes(); marksGrid.removeAllColumns(); marksGrid.setSizeFull(); marksGrid.setEditOnClick(true); marksGrid.setSingleCellEdit(true); marksGrid.setMultiSort(true); marksGrid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT, GridVariant.LUMO_COLUMN_BORDERS); marksGrid.addThemeVariants(GridProVariant.LUMO_ROW_STRIPES); // marksGrid.setAllRowsVisible(true); // TO AVOID SCROLLER DISPLAY ALL THE ROWS headerRow = marksGrid.appendHeaderRow(); // Button Button searchButton = new Button("Search/Refresh"); searchButton.addClickListener(e -> updateGridData()); searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL); menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL); HorizontalLayout filterLayout = new HorizontalLayout(); filterLayout.setAlignItems(Alignment.BASELINE); filterLayout.add( departmentComboBox, academicYearComboBox, semesterComboBox, examTypeComboBox, studentSectionComboBox, searchButton ); Button exportButton = new Button("Export", FontAwesome.Solid.FILE_EXPORT.create(), e -> { ExamType selectedExamType = examTypeComboBox.getValue(); Semester selectedSemester = semesterComboBox.getValue(); DepartmentEntity selectedDepartment = departmentComboBox.getValue(); AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue(); StudentSection studentSection = studentSectionComboBox.getValue(); // Check Grid and Filter Before Export int size = marksGrid.getDataProvider().size(new Query<>()); if (!isFilterInValid() && size > 0) { String fileName = selectedDepartment.getShortName() + "_" + selectedAcademicYear.getStartYear() + "-" + selectedAcademicYear.getEndYear() + "_" + studentSection.getDisplayName() + "_" + selectedSemester.getDisplayName() + "_" + selectedExamType.getDisplayName() + "_Marks"; XlsxFormat xlsxFormat = new XlsxFormat(); PdfFormat pdfFormat = new PdfFormat(); HtmlFormat htmlFormat = new HtmlFormat(); gridExporter = GridExporter .newWithDefaults(marksGrid) .withFileName(fileName) // Ignoring chart column .withColumnFilter(studentMarksDTOColumn -> studentMarksDTOColumn.isVisible() && !studentMarksDTOColumn.getKey().equals("Chart")) .withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat) .withPreSelectedFormat(xlsxFormat) .withColumnConfigurationBuilder(new ColumnConfigurationBuilder()); gridExporter.open(); } } ); exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL); HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton); horizontalLayout.setWidthFull(); horizontalLayout.setJustifyContentMode(JustifyContentMode.END); horizontalLayout.setAlignItems(Alignment.CENTER); add(new H3("Marks View"), filterLayout, horizontalLayout, marksGrid); setSizeFull(); } private boolean isFilterInValid() { return examTypeComboBox.getValue() == null || semesterComboBox.getValue() == null || departmentComboBox.getValue() == null || academicYearComboBox.getValue() == null || studentSectionComboBox.getValue() == null; } private static Component createFilterHeader(Consumer<String> filterChangeConsumer) { TextField textField = new TextField(); textField.setValueChangeMode(ValueChangeMode.EAGER); textField.setClearButtonVisible(true); textField.addThemeVariants(TextFieldVariant.LUMO_SMALL); textField.setWidthFull(); // CASE IN SENSITIVE textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase())); return textField; } private void configureComboBoxes() { List<AcademicYearEntity> academicYears = academicYearService.findAll(); List<DepartmentEntity> departments = departmentService.findAll(); Semester[] semesters = Semester.values(); ExamType[] examTypes = ExamType.values(); StudentSection[] studentSections = StudentSection.values(); semesterComboBox.setItems(semesters); semesterComboBox.setItemLabelGenerator(Semester::getDisplayName); semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); semesterComboBox.setRequiredIndicatorVisible(true); examTypeComboBox.setItems(examTypes); examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName); examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); examTypeComboBox.setRequiredIndicatorVisible(true); academicYearComboBox.setItems(academicYears); academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear()); academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); academicYearComboBox.setRequiredIndicatorVisible(true); departmentComboBox.setItems(departments); departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName()); departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); departmentComboBox.setRequiredIndicatorVisible(true); studentSectionComboBox.setItems(studentSections); studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName); studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL); studentSectionComboBox.setRequiredIndicatorVisible(true); } private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) { counts.totalPass = 0; counts.totalFail = 0; counts.totalPresent = 0; counts.totalAbsent = 0; counts.subjectPassCounts.clear(); counts.subjectFailCounts.clear(); counts.subjectPresentCounts.clear(); counts.subjectAbsentCounts.clear(); for (StudentMarksDTO studentMarksDTO : allStudentMarks) { updateTotalPassFailCounts(studentMarksDTO, counts); } } private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
for (Map.Entry<SubjectEntity, StudentSubjectInfo> entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {
5
2023-12-10 18:07:28+00:00
12k
Viola-Siemens/StellarForge
src/main/java/com/hexagram2021/stellarforge/StellarForge.java
[ { "identifier": "ClientProxy", "path": "src/main/java/com/hexagram2021/stellarforge/client/ClientProxy.java", "snippet": "@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)\npublic class ClientProxy {\n\tpublic static void modConstruction() {\n\t}\n\n\t@Sub...
import com.hexagram2021.stellarforge.client.ClientProxy; import com.hexagram2021.stellarforge.common.SFContent; import com.hexagram2021.stellarforge.common.config.SFCommonConfig; import com.hexagram2021.stellarforge.common.util.RegistryChecker; import com.hexagram2021.stellarforge.common.util.SFLogger; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.server.ServerAboutToStartEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLLoader; import org.apache.logging.log4j.LogManager; import java.util.function.Supplier;
7,248
package com.hexagram2021.stellarforge; @Mod(StellarForge.MODID) public class StellarForge { public static final String MODID = "stellarforge"; public static final String MODNAME = "StellarForge"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public static <T> Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) { if(FMLLoader.isProduction()) { return in; } return () -> { try { return in.get(); } catch(BootstrapMethodError e) { throw new RuntimeException(e); } }; } public StellarForge() {
package com.hexagram2021.stellarforge; @Mod(StellarForge.MODID) public class StellarForge { public static final String MODID = "stellarforge"; public static final String MODNAME = "StellarForge"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public static <T> Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) { if(FMLLoader.isProduction()) { return in; } return () -> { try { return in.get(); } catch(BootstrapMethodError e) { throw new RuntimeException(e); } }; } public StellarForge() {
SFLogger.logger = LogManager.getLogger(MODID);
4
2023-12-10 07:20:43+00:00
12k
zerodevstuff/ExploitFixerv2
src/main/java/dev/_2lstudios/exploitfixer/listener/PacketReceiveListener.java
[ { "identifier": "CheckItemResult", "path": "src/main/java/dev/_2lstudios/exploitfixer/enums/CheckItemResult.java", "snippet": "public enum CheckItemResult {\n // General Items\n INVALID_ITEM,\n INVALID_ITEM_NAME,\n INVALID_ITEM_LORE,\n // Fireworks\n INVALID_FIREWORK_POWER, \n INVAL...
import java.util.Map; import java.util.Map.Entry; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import dev._2lstudios.exploitfixer.enums.CheckItemResult; import dev._2lstudios.exploitfixer.exploit.BukkitExploitPlayer; import dev._2lstudios.exploitfixer.managers.ExploitPlayerManager; import dev._2lstudios.exploitfixer.managers.ModuleManager; import dev._2lstudios.exploitfixer.modules.CreativeItemsFixModule; import dev._2lstudios.exploitfixer.modules.ItemAnalysisModule; import dev._2lstudios.exploitfixer.modules.NotificationsModule; import dev._2lstudios.exploitfixer.modules.PacketsModule; import dev._2lstudios.exploitfixer.utils.ExploitUtil; import dev._2lstudios.hamsterapi.enums.PacketType; import dev._2lstudios.hamsterapi.events.PacketReceiveEvent; import dev._2lstudios.hamsterapi.hamsterplayer.HamsterPlayer; import dev._2lstudios.hamsterapi.wrappers.PacketWrapper;
8,702
package dev._2lstudios.exploitfixer.listener; public class PacketReceiveListener implements Listener { private ExploitUtil exploitUtil; private ExploitPlayerManager exploitPlayerManager; private CreativeItemsFixModule itemsFixModule; private NotificationsModule notificationsModule; private PacketsModule packetsModule;
package dev._2lstudios.exploitfixer.listener; public class PacketReceiveListener implements Listener { private ExploitUtil exploitUtil; private ExploitPlayerManager exploitPlayerManager; private CreativeItemsFixModule itemsFixModule; private NotificationsModule notificationsModule; private PacketsModule packetsModule;
private ItemAnalysisModule itemAnalysisModule;
5
2023-12-13 21:49:27+00:00
12k
xuexu2/Crasher
src/main/java/cn/sn0wo/crasher/utils/Utils.java
[ { "identifier": "Crasher", "path": "src/main/java/cn/sn0wo/crasher/Crasher.java", "snippet": "public final class Crasher extends JavaPlugin {\n\n public Crasher() {\n Utils.utils = new Utils(this);\n }\n\n @Override\n public void onLoad() {\n getLogger().info(\"Loaded \" + getD...
import cn.sn0wo.crasher.Crasher; import cn.sn0wo.crasher.bstats.Metrics; import cn.sn0wo.crasher.commands.Crash; import cn.sn0wo.crasher.datas.DataManager; import cn.sn0wo.crasher.listener.PlayerListener; import cn.sn0wo.crasher.tasks.CheckUpdate; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream;
8,288
package cn.sn0wo.crasher.utils; public final class Utils { public static Utils utils; public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final Set<UUID> crashSet = new HashSet<>(); public final Set<UUID> frozenSet = new HashSet<>(); public Crasher instance; public Metrics metrics;
package cn.sn0wo.crasher.utils; public final class Utils { public static Utils utils; public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final Set<UUID> crashSet = new HashSet<>(); public final Set<UUID> frozenSet = new HashSet<>(); public Crasher instance; public Metrics metrics;
public DataManager dataManager;
3
2023-12-05 15:08:54+00:00
12k
Crydsch/the-one
src/gui/DTNSimGUI.java
[ { "identifier": "PlayField", "path": "src/gui/playfield/PlayField.java", "snippet": "public class PlayField extends JPanel {\n\tpublic static final int PLAYFIELD_OFFSET = 10;\n\n\tprivate World w;\n\tprivate DTNSimGUI gui;\n\n\tprivate Color bgColor = Color.WHITE;\n\n\tprivate List<PlayFieldGraphic> ove...
import gui.playfield.PlayField; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import movement.Path; import ui.DTNSimUI; import core.Coord; import core.DTNHost; import core.SimClock;
10,507
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui; /** * Graphical User Interface for simulator */ public class DTNSimGUI extends DTNSimUI { private MainWindow main;
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui; /** * Graphical User Interface for simulator */ public class DTNSimGUI extends DTNSimUI { private MainWindow main;
private PlayField field;
0
2023-12-10 15:51:41+00:00
12k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/SAFHelper.java
[ { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java", "snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public ...
import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.storage.StorageManager; import android.os.storage.StorageVolume; import android.provider.DocumentsContract; import android.util.Log; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.progress.ProgressWidget; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Hashtable; import java.util.List;
9,474
/* * This file is part of MAME4droid. * * Copyright (C) 2023 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; class DirEnt{ private static int lastId = 1; DirEnt(){this.id = lastId++;} int id = 0; int fileNameIdx = 0; ArrayList fileNames = null; } public class SAFHelper {
/* * This file is part of MAME4droid. * * Copyright (C) 2023 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; class DirEnt{ private static int lastId = 1; DirEnt(){this.id = lastId++;} int id = 0; int fileNameIdx = 0; ArrayList fileNames = null; } public class SAFHelper {
static protected MAME4droid mm = null;
1
2023-12-18 11:16:18+00:00
12k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/item/items/weapon/Hyperion.java
[ { "identifier": "SkyBlockPlayer", "path": "generic/src/main/java/net/swofty/types/generic/user/SkyBlockPlayer.java", "snippet": "public class SkyBlockPlayer extends Player {\n\n @Getter\n private float mana = 100;\n public float health = 100;\n public long joined;\n @Setter\n @Getter\n...
import net.swofty.types.generic.item.impl.*; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.user.statistics.ItemStatistic; import net.swofty.types.generic.user.statistics.ItemStatistics; import net.swofty.types.generic.utility.ItemGroups; import net.swofty.types.generic.item.ItemType; import net.swofty.types.generic.item.ReforgeType; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.impl.*; import net.swofty.types.generic.item.impl.recipes.ShapelessRecipe; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,336
package net.swofty.types.generic.item.items.weapon; public class Hyperion implements CustomSkyBlockItem, CustomSkyBlockAbility, Reforgable, Enchantable, Craftable { @Override public ItemStatistics getStatistics() { return ItemStatistics.builder() .with(ItemStatistic.DAMAGE, 100) .with(ItemStatistic.HEALTH, 20) .with(ItemStatistic.DEFENSE, 30) .build(); } @Override
package net.swofty.types.generic.item.items.weapon; public class Hyperion implements CustomSkyBlockItem, CustomSkyBlockAbility, Reforgable, Enchantable, Craftable { @Override public ItemStatistics getStatistics() { return ItemStatistics.builder() .with(ItemStatistic.DAMAGE, 100) .with(ItemStatistic.HEALTH, 20) .with(ItemStatistic.DEFENSE, 30) .build(); } @Override
public ArrayList<String> getLore(SkyBlockPlayer player, SkyBlockItem item) {
6
2023-12-14 09:51:15+00:00
12k
Tianscar/uxgl
desktop/src/main/java/unrefined/desktop/CursorSupport.java
[ { "identifier": "OperatingSystem", "path": "desktop/src/main/java/unrefined/internal/OperatingSystem.java", "snippet": "public final class OperatingSystem {\n\n private OperatingSystem() {\n throw new NotInstantiableError(OperatingSystem.class);\n }\n\n private static final String OS_NAM...
import unrefined.internal.OperatingSystem; import unrefined.internal.X11.X11CursorSupport; import unrefined.media.graphics.CursorNotFoundException; import unrefined.util.NotInstantiableError; import java.awt.AWTException; import java.awt.Cursor; import java.awt.HeadlessException; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import static unrefined.media.graphics.Cursor.Type.*;
8,619
package unrefined.desktop; public final class CursorSupport { public static final Cursor NONE_CURSOR; static { Cursor cursor; try { cursor = Toolkit.getDefaultToolkit().createCustomCursor( Toolkit.getDefaultToolkit().getImage(CursorSupport.class.getResource("")), new Point(0, 0), "UXGL None Cursor"); } catch (HeadlessException e) { cursor = null; } NONE_CURSOR = cursor; } private CursorSupport() { throw new NotInstantiableError(CursorSupport.class); } public static Cursor getSystemCursor(int type) throws CursorNotFoundException { switch (type) { case ARROW: return Cursor.getDefaultCursor(); case CROSSHAIR: return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); case IBEAM: return Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); case WAIT: if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); // FIXME Cocoa else return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); case POINTING_HAND: return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); case MOVE: return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); case RESIZE_N: return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); case RESIZE_S: return Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); case RESIZE_W: return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); case RESIZE_E: return Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); case RESIZE_SW: return Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR); case RESIZE_SE: return Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR); case RESIZE_NW: return Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); case RESIZE_NE: return Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); case RESIZE_NS: if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // Windows unsupported else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // FIXME Cocoa
package unrefined.desktop; public final class CursorSupport { public static final Cursor NONE_CURSOR; static { Cursor cursor; try { cursor = Toolkit.getDefaultToolkit().createCustomCursor( Toolkit.getDefaultToolkit().getImage(CursorSupport.class.getResource("")), new Point(0, 0), "UXGL None Cursor"); } catch (HeadlessException e) { cursor = null; } NONE_CURSOR = cursor; } private CursorSupport() { throw new NotInstantiableError(CursorSupport.class); } public static Cursor getSystemCursor(int type) throws CursorNotFoundException { switch (type) { case ARROW: return Cursor.getDefaultCursor(); case CROSSHAIR: return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); case IBEAM: return Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); case WAIT: if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); // FIXME Cocoa else return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); case POINTING_HAND: return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); case MOVE: return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); case RESIZE_N: return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); case RESIZE_S: return Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); case RESIZE_W: return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); case RESIZE_E: return Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); case RESIZE_SW: return Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR); case RESIZE_SE: return Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR); case RESIZE_NW: return Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); case RESIZE_NE: return Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); case RESIZE_NS: if (OperatingSystem.IS_WINDOWS) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // Windows unsupported else if (OperatingSystem.IS_MAC) return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); // FIXME Cocoa
else return X11CursorSupport.getSystemCursor(X11CursorSupport.XC_sb_v_double_arrow);
1
2023-12-15 19:03:31+00:00
12k
Valerde/vadb
vadb-test/src/test/java/com/sovava/vadb/test/collection/map/Test1Part.java
[ { "identifier": "VaMap", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaMap.java", "snippet": "public interface VaMap<K, V> {\n int size();\n\n boolean isEmpty();\n\n boolean containsKey(Object key);\n\n boolean containValue(Object value);\n\n V get(Object key);\n\n ...
import com.sovava.vacollection.api.VaMap; import com.sovava.vacollection.api.VaSet; import com.sovava.vacollection.vamap.VaHashMap; import com.sovava.vadb.test.collection.utils.RandomObject; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import java.util.*;
10,421
package com.sovava.vadb.test.collection.map; /** * Description: * VaHashMap已支持array+链表的方式存储,这个类测试已有功能 * * @author: ykn * @date: 2023年12月24日 6:29 PM **/ @Slf4j public class Test1Part { /** * description: * <p>测试结果: * <p>1. 编译错误,VaArrays中copyOf方法错误,需要强转为Object * <p>2. 代码优化,getNode方法中起始处定义变量优化语法 * * @Author sovava * @Date 12/24/23 7:14 PM */ @Test public void testBasicFunc() {
package com.sovava.vadb.test.collection.map; /** * Description: * VaHashMap已支持array+链表的方式存储,这个类测试已有功能 * * @author: ykn * @date: 2023年12月24日 6:29 PM **/ @Slf4j public class Test1Part { /** * description: * <p>测试结果: * <p>1. 编译错误,VaArrays中copyOf方法错误,需要强转为Object * <p>2. 代码优化,getNode方法中起始处定义变量优化语法 * * @Author sovava * @Date 12/24/23 7:14 PM */ @Test public void testBasicFunc() {
VaMap<String, String> map = new VaHashMap<>();
0
2023-12-17 13:29:10+00:00
12k
litongjava/next-jfinal
src/main/java/com/jfinal/core/JFinal.java
[ { "identifier": "Constants", "path": "src/main/java/com/jfinal/config/Constants.java", "snippet": "final public class Constants {\n\t\n\tprivate boolean devMode = Const.DEFAULT_DEV_MODE;\n\t\n\tprivate String baseUploadPath = Const.DEFAULT_BASE_UPLOAD_PATH;\n\tprivate String baseDownloadPath = Const.DEF...
import java.util.List; import com.jfinal.config.Constants; import com.jfinal.config.JFinalConfig; import com.jfinal.handler.Handler; import com.jfinal.handler.HandlerFactory; import com.jfinal.kit.LogKit; import com.jfinal.kit.PathKit; import com.jfinal.plugin.IPlugin; import com.jfinal.render.RenderManager; import com.jfinal.server.IServer; import com.jfinal.servlet.ServletContext; import com.jfinal.token.ITokenCache; import com.jfinal.token.TokenManager; import com.jfinal.upload.UploadConfig;
10,783
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jfinal.core; /** * JFinal */ public final class JFinal { private Constants constants; private ActionMapping actionMapping; private Handler handler; private ServletContext servletContext; private String contextPath = "";
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jfinal.core; /** * JFinal */ public final class JFinal { private Constants constants; private ActionMapping actionMapping; private Handler handler; private ServletContext servletContext; private String contextPath = "";
private static IServer server;
8
2023-12-19 10:58:33+00:00
12k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/render/HUD.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.Cheeto; import xyz.apfelmus.cheeto.client.events.Render2DEvent; import xyz.apfelmus.cheeto.client.modules.render.ClickGUI; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.ModeSetting; import xyz.apfelmus.cheeto.client.utils.client.ColorUtils; import xyz.apfelmus.cheeto.client.utils.client.FontUtils; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.render.Render2DUtils;
8,094
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.ScaledResolution * net.minecraft.client.renderer.GlStateManager * net.minecraft.util.ResourceLocation */ package xyz.apfelmus.cheeto.client.modules.render; @Module(name="HUD", category=Category.RENDER) public class HUD { @Setting(name="Watermark") private BooleanSetting watermark = new BooleanSetting(true); @Setting(name="ModuleList") private BooleanSetting moduleList = new BooleanSetting(true); @Setting(name="Logo") private ModeSetting logo = new ModeSetting("bing_chilling", Arrays.asList("smirk_cat", "bing_chilling")); @Event public void onRender(Render2DEvent event) { if (this.watermark.isEnabled()) { this.renderTopString(); } if (!this.moduleList.isEnabled()) { return; } List<Object> modules = CF4M.INSTANCE.moduleManager.getModules().stream().filter(v -> CF4M.INSTANCE.moduleManager.isEnabled(v)).sorted((o1, o2) -> FontUtils.getStringWidth(this.getModuleName(o2)) - FontUtils.getStringWidth(this.getModuleName(o1))).collect(Collectors.toList()); this.renderModuleList(modules); } private void renderTopString() { GlStateManager.func_179139_a((double)2.0, (double)2.0, (double)2.0); ClickGUI click = (ClickGUI)CF4M.INSTANCE.moduleManager.getModule("ClickGUI"); if (click.theme.getCurrent().equals("Femboy")) { FontUtils.drawString(Cheeto.name, 2 + FontUtils.getFontHeight(), 2, ColorUtils.SELECTED.getRGB()); } else { FontUtils.drawChromaString(Cheeto.name, 2 + FontUtils.getFontHeight(), 2, 0); } GlStateManager.func_179139_a((double)0.5, (double)0.5, (double)0.5); int nameLength = FontUtils.getStringWidth(Cheeto.name); if (click.theme.getCurrent().equals("Femboy")) { FontUtils.drawString(" v" + Cheeto.version, 2 + nameLength * 2 + FontUtils.getFontHeight() * 2, 2 + FontUtils.getFontHeight(), ColorUtils.SELECTED.getRGB()); } else { FontUtils.drawChromaString(" v" + Cheeto.version, 2 + nameLength * 2 + FontUtils.getFontHeight() * 2, 2 + FontUtils.getFontHeight(), nameLength); } Render2DUtils.drawTexture(new ResourceLocation("chromahud:" + this.logo.getCurrent() + ".png"), 2, 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, 0, 0); } private void renderModuleList(List<Object> modules) { int yStart = 0; ScaledResolution sr = new ScaledResolution(Minecraft.func_71410_x()); for (Object module : modules) { int sw = FontUtils.getStringWidth(this.getModuleName(module)); int startX = sr.func_78326_a() - sw - 6; int animStartX = sr.func_78326_a(); long start = CF4M.INSTANCE.moduleManager.getActivatedTime(module); float spentMillis = System.currentTimeMillis() - start; float relativeProgress = spentMillis / 500.0f;
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.ScaledResolution * net.minecraft.client.renderer.GlStateManager * net.minecraft.util.ResourceLocation */ package xyz.apfelmus.cheeto.client.modules.render; @Module(name="HUD", category=Category.RENDER) public class HUD { @Setting(name="Watermark") private BooleanSetting watermark = new BooleanSetting(true); @Setting(name="ModuleList") private BooleanSetting moduleList = new BooleanSetting(true); @Setting(name="Logo") private ModeSetting logo = new ModeSetting("bing_chilling", Arrays.asList("smirk_cat", "bing_chilling")); @Event public void onRender(Render2DEvent event) { if (this.watermark.isEnabled()) { this.renderTopString(); } if (!this.moduleList.isEnabled()) { return; } List<Object> modules = CF4M.INSTANCE.moduleManager.getModules().stream().filter(v -> CF4M.INSTANCE.moduleManager.isEnabled(v)).sorted((o1, o2) -> FontUtils.getStringWidth(this.getModuleName(o2)) - FontUtils.getStringWidth(this.getModuleName(o1))).collect(Collectors.toList()); this.renderModuleList(modules); } private void renderTopString() { GlStateManager.func_179139_a((double)2.0, (double)2.0, (double)2.0); ClickGUI click = (ClickGUI)CF4M.INSTANCE.moduleManager.getModule("ClickGUI"); if (click.theme.getCurrent().equals("Femboy")) { FontUtils.drawString(Cheeto.name, 2 + FontUtils.getFontHeight(), 2, ColorUtils.SELECTED.getRGB()); } else { FontUtils.drawChromaString(Cheeto.name, 2 + FontUtils.getFontHeight(), 2, 0); } GlStateManager.func_179139_a((double)0.5, (double)0.5, (double)0.5); int nameLength = FontUtils.getStringWidth(Cheeto.name); if (click.theme.getCurrent().equals("Femboy")) { FontUtils.drawString(" v" + Cheeto.version, 2 + nameLength * 2 + FontUtils.getFontHeight() * 2, 2 + FontUtils.getFontHeight(), ColorUtils.SELECTED.getRGB()); } else { FontUtils.drawChromaString(" v" + Cheeto.version, 2 + nameLength * 2 + FontUtils.getFontHeight() * 2, 2 + FontUtils.getFontHeight(), nameLength); } Render2DUtils.drawTexture(new ResourceLocation("chromahud:" + this.logo.getCurrent() + ".png"), 2, 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, FontUtils.getFontHeight() * 2, 0, 0); } private void renderModuleList(List<Object> modules) { int yStart = 0; ScaledResolution sr = new ScaledResolution(Minecraft.func_71410_x()); for (Object module : modules) { int sw = FontUtils.getStringWidth(this.getModuleName(module)); int startX = sr.func_78326_a() - sw - 6; int animStartX = sr.func_78326_a(); long start = CF4M.INSTANCE.moduleManager.getActivatedTime(module); float spentMillis = System.currentTimeMillis() - start; float relativeProgress = spentMillis / 500.0f;
int relativeX = (int)((float)(startX - animStartX) * RotationUtils.easeOutCubic(relativeProgress) + (float)animStartX);
9
2023-12-21 16:22:25+00:00
12k
ciallo-dev/JWSystemLib
src/main/java/moe/snowflake/jwSystem/JWSystem.java
[ { "identifier": "CourseSelectManager", "path": "src/main/java/moe/snowflake/jwSystem/manager/CourseSelectManager.java", "snippet": "public class CourseSelectManager {\n private final JWSystem system;\n\n\n public CourseSelectManager(JWSystem system) {\n this.system = system;\n }\n\n /...
import moe.snowflake.jwSystem.manager.CourseSelectManager; import moe.snowflake.jwSystem.manager.CourseReviewManager; import moe.snowflake.jwSystem.manager.URLManager; import moe.snowflake.jwSystem.utils.HttpUtil; import moe.snowflake.jwSystem.utils.PasswordUtil; import org.jsoup.Connection; import org.jsoup.nodes.Element; import java.io.IOException; import java.util.*;
7,963
package moe.snowflake.jwSystem; public class JWSystem { public Connection.Response jwLoggedResponse; public Connection.Response courseSelectSystemResponse; public Map<String, String> headers = new HashMap<>(); private final boolean loginCourseSelectWeb; private final CourseSelectManager courseSelectManager; private final CourseReviewManager courseReviewManager; public JWSystem() { this(true); } public JWSystem(boolean loginCourseSelectWeb) { this.loginCourseSelectWeb = loginCourseSelectWeb; this.courseSelectManager = new CourseSelectManager(this); this.courseReviewManager = new CourseReviewManager(this); } /** * 判断教务是否登录成功 * * @return 是否登录成功 */ public boolean isJWLogged() { try { if (this.jwLoggedResponse != null) { // 只要有这个元素即登录失败 Element element = this.jwLoggedResponse.parse().getElementById("showMsg"); if (element != null) return false; } } catch (Exception e) { return false; } return true; } /** * 判断选课系统是否登录成功 * * @return 选课系统是否登录 */ public boolean isCourseLogged() { try { return this.isJWLogged() && this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录"); } catch (IOException e) { return false; } } /** * 设置全局的 headers,包含cookie * jsoup设置的cookie无法识别 * * @param cookie cookie */ private void setHeaders(String cookie) { headers.put("Cookie", "JSESSIONID=" + cookie); } /** * 直接导向目标API的登录 * * @param username 用户名 * @param password 密码 */ public JWSystem login(String username, String password) { Map<String, String> formData = new HashMap<>(); formData.put("userAccount", username); formData.put("userPassword", ""); // 很明显的两个base64加密 formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes()))); // 登录成功的 响应 Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN, formData); if (response == null) { System.err.println("network error..."); return this; } this.jwLoggedResponse = response; this.setHeaders(response.cookie("JSESSIONID")); this.loginCourseWeb(); return this; } /** * 用于直接登录选课系统 * 先登录学生选课系统,让后台存JSESSIONID * 并且设置登录成功的 */ public void loginCourseWeb() { // 是否登录选课系统 if (isLoginCourseSelectWeb()) { this.courseSelectSystemResponse = HttpUtil.sendGet(URLManager.COURSE_LOGIN_WEB, this.headers); if (this.courseSelectSystemResponse == null) { System.out.println("network error !"); return; } // 检测是否在选课时间内 if (this.courseSelectSystemResponse.body().contains("时间范围")) this.courseSelectSystemResponse = null; } } /** * 更慢的登录 * * @param username 账号 * @param password 密码 */ @Deprecated public void login1(String username, String password) { Connection.Response keyGet = HttpUtil.sendGet(URLManager.LOGIN_DATA); if (keyGet == null || keyGet.statusCode() != 200) { System.err.println("network error"); return; } // 拿数据的 String dataStr = keyGet.body(); // 先检测他能否拿到加密数据的密钥 if (dataStr.split("#").length < 2) { throw new RuntimeException("server or network error !"); } // 获取加密后的密码数据
package moe.snowflake.jwSystem; public class JWSystem { public Connection.Response jwLoggedResponse; public Connection.Response courseSelectSystemResponse; public Map<String, String> headers = new HashMap<>(); private final boolean loginCourseSelectWeb; private final CourseSelectManager courseSelectManager; private final CourseReviewManager courseReviewManager; public JWSystem() { this(true); } public JWSystem(boolean loginCourseSelectWeb) { this.loginCourseSelectWeb = loginCourseSelectWeb; this.courseSelectManager = new CourseSelectManager(this); this.courseReviewManager = new CourseReviewManager(this); } /** * 判断教务是否登录成功 * * @return 是否登录成功 */ public boolean isJWLogged() { try { if (this.jwLoggedResponse != null) { // 只要有这个元素即登录失败 Element element = this.jwLoggedResponse.parse().getElementById("showMsg"); if (element != null) return false; } } catch (Exception e) { return false; } return true; } /** * 判断选课系统是否登录成功 * * @return 选课系统是否登录 */ public boolean isCourseLogged() { try { return this.isJWLogged() && this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录"); } catch (IOException e) { return false; } } /** * 设置全局的 headers,包含cookie * jsoup设置的cookie无法识别 * * @param cookie cookie */ private void setHeaders(String cookie) { headers.put("Cookie", "JSESSIONID=" + cookie); } /** * 直接导向目标API的登录 * * @param username 用户名 * @param password 密码 */ public JWSystem login(String username, String password) { Map<String, String> formData = new HashMap<>(); formData.put("userAccount", username); formData.put("userPassword", ""); // 很明显的两个base64加密 formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes()))); // 登录成功的 响应 Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN, formData); if (response == null) { System.err.println("network error..."); return this; } this.jwLoggedResponse = response; this.setHeaders(response.cookie("JSESSIONID")); this.loginCourseWeb(); return this; } /** * 用于直接登录选课系统 * 先登录学生选课系统,让后台存JSESSIONID * 并且设置登录成功的 */ public void loginCourseWeb() { // 是否登录选课系统 if (isLoginCourseSelectWeb()) { this.courseSelectSystemResponse = HttpUtil.sendGet(URLManager.COURSE_LOGIN_WEB, this.headers); if (this.courseSelectSystemResponse == null) { System.out.println("network error !"); return; } // 检测是否在选课时间内 if (this.courseSelectSystemResponse.body().contains("时间范围")) this.courseSelectSystemResponse = null; } } /** * 更慢的登录 * * @param username 账号 * @param password 密码 */ @Deprecated public void login1(String username, String password) { Connection.Response keyGet = HttpUtil.sendGet(URLManager.LOGIN_DATA); if (keyGet == null || keyGet.statusCode() != 200) { System.err.println("network error"); return; } // 拿数据的 String dataStr = keyGet.body(); // 先检测他能否拿到加密数据的密钥 if (dataStr.split("#").length < 2) { throw new RuntimeException("server or network error !"); } // 获取加密后的密码数据
String encoded = PasswordUtil.encodeUserData(dataStr, username + "%%%" + password);
4
2023-12-21 10:58:12+00:00
12k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/dexbacked/DexBackedMethod.java
[ { "identifier": "BaseMethodReference", "path": "app/src/main/java/org/jf/dexlib2/base/reference/BaseMethodReference.java", "snippet": "public abstract class BaseMethodReference implements MethodReference {\n @Override\n public int hashCode() {\n int hashCode = getDefiningClass().hashCode();...
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jf.dexlib2.base.reference.BaseMethodReference; import org.jf.dexlib2.dexbacked.raw.MethodIdItem; import org.jf.dexlib2.dexbacked.raw.ProtoIdItem; import org.jf.dexlib2.dexbacked.raw.TypeListItem; import org.jf.dexlib2.dexbacked.reference.DexBackedMethodReference; import org.jf.dexlib2.dexbacked.util.AnnotationsDirectory; import org.jf.dexlib2.dexbacked.util.FixedSizeList; import org.jf.dexlib2.dexbacked.util.ParameterIterator; import org.jf.dexlib2.iface.Annotation; import org.jf.dexlib2.iface.Method; import org.jf.dexlib2.iface.MethodParameter; import org.jf.util.AbstractForwardSequentialList; import java.util.Iterator; import java.util.List; import java.util.Set;
9,109
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked; public class DexBackedMethod extends BaseMethodReference implements Method { @NonNull public final DexBackedDexFile dexFile; @NonNull public final DexBackedClassDef classDef; public final int accessFlags; public final int methodIndex; private final int codeOffset; private final int parameterAnnotationSetListOffset; private final int methodAnnotationSetOffset; private final int startOffset; private int methodIdItemOffset; private int protoIdItemOffset; private int parametersOffset = -1; public DexBackedMethod(@NonNull DexReader reader, @NonNull DexBackedClassDef classDef, int previousMethodIndex) { this.dexFile = reader.dexBuf; this.classDef = classDef; startOffset = reader.getOffset(); // large values may be used for the index delta, which cause the cumulative index to overflow upon // addition, effectively allowing out of order entries. int methodIndexDiff = reader.readLargeUleb128(); this.methodIndex = methodIndexDiff + previousMethodIndex; this.accessFlags = reader.readSmallUleb128(); this.codeOffset = reader.readSmallUleb128(); this.methodAnnotationSetOffset = 0; this.parameterAnnotationSetListOffset = 0; } public DexBackedMethod(@NonNull DexReader reader, @NonNull DexBackedClassDef classDef, int previousMethodIndex, @NonNull AnnotationsDirectory.AnnotationIterator methodAnnotationIterator, @NonNull AnnotationsDirectory.AnnotationIterator paramaterAnnotationIterator) { this.dexFile = reader.dexBuf; this.classDef = classDef; startOffset = reader.getOffset(); // large values may be used for the index delta, which cause the cumulative index to overflow upon // addition, effectively allowing out of order entries. int methodIndexDiff = reader.readLargeUleb128(); this.methodIndex = methodIndexDiff + previousMethodIndex; this.accessFlags = reader.readSmallUleb128(); this.codeOffset = reader.readSmallUleb128(); this.methodAnnotationSetOffset = methodAnnotationIterator.seekTo(methodIndex); this.parameterAnnotationSetListOffset = paramaterAnnotationIterator.seekTo(methodIndex); } /** * Skips the reader over the specified number of encoded_method structures * * @param reader The reader to skip * @param count The number of encoded_method structures to skip over */ public static void skipMethods(@NonNull DexReader reader, int count) { for (int i = 0; i < count; i++) { reader.skipUleb128(); reader.skipUleb128(); reader.skipUleb128(); } } public int getMethodIndex() { return methodIndex; } @NonNull @Override public String getDefiningClass() { return classDef.getType(); } @Override public int getAccessFlags() { return accessFlags; } @NonNull @Override public String getName() { return dexFile.getString(dexFile.readSmallUint(getMethodIdItemOffset() + MethodIdItem.NAME_OFFSET)); } @NonNull @Override public String getReturnType() { return dexFile.getType(dexFile.readSmallUint(getProtoIdItemOffset() + ProtoIdItem.RETURN_TYPE_OFFSET)); } @NonNull @Override public List<? extends MethodParameter> getParameters() { int parametersOffset = getParametersOffset(); if (parametersOffset > 0) { final List<String> parameterTypes = getParameterTypes();
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked; public class DexBackedMethod extends BaseMethodReference implements Method { @NonNull public final DexBackedDexFile dexFile; @NonNull public final DexBackedClassDef classDef; public final int accessFlags; public final int methodIndex; private final int codeOffset; private final int parameterAnnotationSetListOffset; private final int methodAnnotationSetOffset; private final int startOffset; private int methodIdItemOffset; private int protoIdItemOffset; private int parametersOffset = -1; public DexBackedMethod(@NonNull DexReader reader, @NonNull DexBackedClassDef classDef, int previousMethodIndex) { this.dexFile = reader.dexBuf; this.classDef = classDef; startOffset = reader.getOffset(); // large values may be used for the index delta, which cause the cumulative index to overflow upon // addition, effectively allowing out of order entries. int methodIndexDiff = reader.readLargeUleb128(); this.methodIndex = methodIndexDiff + previousMethodIndex; this.accessFlags = reader.readSmallUleb128(); this.codeOffset = reader.readSmallUleb128(); this.methodAnnotationSetOffset = 0; this.parameterAnnotationSetListOffset = 0; } public DexBackedMethod(@NonNull DexReader reader, @NonNull DexBackedClassDef classDef, int previousMethodIndex, @NonNull AnnotationsDirectory.AnnotationIterator methodAnnotationIterator, @NonNull AnnotationsDirectory.AnnotationIterator paramaterAnnotationIterator) { this.dexFile = reader.dexBuf; this.classDef = classDef; startOffset = reader.getOffset(); // large values may be used for the index delta, which cause the cumulative index to overflow upon // addition, effectively allowing out of order entries. int methodIndexDiff = reader.readLargeUleb128(); this.methodIndex = methodIndexDiff + previousMethodIndex; this.accessFlags = reader.readSmallUleb128(); this.codeOffset = reader.readSmallUleb128(); this.methodAnnotationSetOffset = methodAnnotationIterator.seekTo(methodIndex); this.parameterAnnotationSetListOffset = paramaterAnnotationIterator.seekTo(methodIndex); } /** * Skips the reader over the specified number of encoded_method structures * * @param reader The reader to skip * @param count The number of encoded_method structures to skip over */ public static void skipMethods(@NonNull DexReader reader, int count) { for (int i = 0; i < count; i++) { reader.skipUleb128(); reader.skipUleb128(); reader.skipUleb128(); } } public int getMethodIndex() { return methodIndex; } @NonNull @Override public String getDefiningClass() { return classDef.getType(); } @Override public int getAccessFlags() { return accessFlags; } @NonNull @Override public String getName() { return dexFile.getString(dexFile.readSmallUint(getMethodIdItemOffset() + MethodIdItem.NAME_OFFSET)); } @NonNull @Override public String getReturnType() { return dexFile.getType(dexFile.readSmallUint(getProtoIdItemOffset() + ProtoIdItem.RETURN_TYPE_OFFSET)); } @NonNull @Override public List<? extends MethodParameter> getParameters() { int parametersOffset = getParametersOffset(); if (parametersOffset > 0) { final List<String> parameterTypes = getParameterTypes();
return new AbstractForwardSequentialList<MethodParameter>() {
11
2023-12-16 11:11:16+00:00
12k
123yyh123/xiaofanshu
xfs-job-server/src/main/java/com/yyh/xfs/job/jobhandler/SampleXxlJob.java
[ { "identifier": "RedisConstant", "path": "xfs-common/common-redis/src/main/java/com/yyh/xfs/common/redis/constant/RedisConstant.java", "snippet": "public class RedisConstant {\n /**\n * redis key 用户登录过期前缀\n */\n public static final String REDIS_KEY_USER_LOGIN_EXPIRE = \"user:login:expire:\...
import com.xxl.job.core.context.XxlJobHelper; import com.xxl.job.core.handler.annotation.XxlJob; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.job.service.UserService; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.vo.UserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundZSetOperations; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.stream.Collectors;
8,481
package com.yyh.xfs.job.jobhandler; /** * @author yyh * @date 2023-12-23 * @desc xfs-job */ @Component @Slf4j public class SampleXxlJob { private final UserService userService; private final Executor jobThreadPool; private final RedisCache redisCache; public SampleXxlJob(RedisCache redisCache, Executor jobThreadPool, UserService userService) { this.redisCache = redisCache; this.jobThreadPool=jobThreadPool; this.userService = userService; } /** * 1、简单任务示例(Bean模式) */ @XxlJob("userInfoJobHandler") public void demoJobHandler() throws Exception { XxlJobHelper.log("start update userInfo"); // 从redis中获取要更新用户的id
package com.yyh.xfs.job.jobhandler; /** * @author yyh * @date 2023-12-23 * @desc xfs-job */ @Component @Slf4j public class SampleXxlJob { private final UserService userService; private final Executor jobThreadPool; private final RedisCache redisCache; public SampleXxlJob(RedisCache redisCache, Executor jobThreadPool, UserService userService) { this.redisCache = redisCache; this.jobThreadPool=jobThreadPool; this.userService = userService; } /** * 1、简单任务示例(Bean模式) */ @XxlJob("userInfoJobHandler") public void demoJobHandler() throws Exception { XxlJobHelper.log("start update userInfo"); // 从redis中获取要更新用户的id
long l = redisCache.zSetSize(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST);
0
2023-12-15 08:13:42+00:00
12k
egisac/ethicalvoting
src/main/java/net/egis/ethicalvoting/EthicalVoting.java
[ { "identifier": "EthicalVotingCommand", "path": "src/main/java/net/egis/ethicalvoting/commands/EthicalVotingCommand.java", "snippet": "public class EthicalVotingCommand implements CommandExecutor, TabCompleter {\n @Override\n public boolean onCommand(CommandSender sender, Command command, String l...
import lombok.Getter; import mc.obliviate.inventory.InventoryAPI; import net.egis.ethicalvoting.commands.EthicalVotingCommand; import net.egis.ethicalvoting.commands.VoteCommand; import net.egis.ethicalvoting.data.ProfileManager; import net.egis.ethicalvoting.data.StorageInterface; import net.egis.ethicalvoting.data.interfaces.MySQLInterface; import net.egis.ethicalvoting.data.interfaces.YamlInterface; import net.egis.ethicalvoting.https.UpdateChecker; import net.egis.ethicalvoting.integrations.EthicalPAPI; import net.egis.ethicalvoting.listeners.FireworkDamageListener; import net.egis.ethicalvoting.listeners.PlayerConnectionListener; import net.egis.ethicalvoting.listeners.VotifierVoteListener; import net.egis.ethicalvoting.rewards.VoteRewardHandler; import net.egis.ethicalvoting.utils.Translate; import net.egis.ethicalvoting.voteparty.VotePartyHandler; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin;
7,467
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage; private ProfileManager profiles; private PlayerConnectionListener connectionListener; private VotifierVoteListener voteListener; private FireworkDamageListener fireworkDamageListener; private VotePartyHandler votePartyHandler; private VoteRewardHandler voteRewardHandler; @Override public void onEnable() { self = this; new InventoryAPI(this).init(); saveDefaultConfig(); pickStorageType(); loadPluginData(); loadFeatures(); registerEventListeners(); registerCommands(); registerIntegrations(); getLogger().info("Storage Type: " + storage.getAdapterType()); checkUpdates(); getLogger().info("EthicalVoting has been successfully enabled."); } @Override public void onDisable() { profiles.shutdown(); voteRewardHandler.getVoteQueue().shutdown(); getLogger().info("EthicalVoting has been successfully disabled."); } public void registerIntegrations() { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new EthicalPAPI().register(); getLogger().info("PlaceholderAPI integration has been successfully enabled."); } else { getLogger().warning("PlaceholderAPI integration has failed to load."); } } /* Defines which database type will be used to store user data. Current options: - MySQL - YAML (Bukkit internal) */ public void pickStorageType() { String storageInterface = getConfig().getString("database.type"); if (storageInterface == null) { getLogger().severe("Storage Interface is null. Report this to plugin developer."); getServer().shutdown(); return; } if (storageInterface.equalsIgnoreCase("mysql")) { storage = new MySQLInterface(); String host = getConfig().getString("database.host"); int port = getConfig().getInt("database.port"); String database = getConfig().getString("database.database"); String username = getConfig().getString("database.username"); String password = getConfig().getString("database.password"); if (host == null || database == null || username == null || password == null) { getLogger().severe("MySQL credentials are null. Report this to plugin developer."); getServer().shutdown(); return; } if (!storage.jdbcInit("jdbc:mysql://" + host + ":" + port + "/" + database, username, password)) { getLogger().severe("Failed to connect to MySQL database. Report this to plugin developer."); getServer().shutdown(); return; } } else { storage = new YamlInterface(this); } } public void registerCommands() { EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand(); getCommand("ethicalvoting").setExecutor(ethicalVotingCommand); getCommand("ethicalvoting").setTabCompleter(ethicalVotingCommand);
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage; private ProfileManager profiles; private PlayerConnectionListener connectionListener; private VotifierVoteListener voteListener; private FireworkDamageListener fireworkDamageListener; private VotePartyHandler votePartyHandler; private VoteRewardHandler voteRewardHandler; @Override public void onEnable() { self = this; new InventoryAPI(this).init(); saveDefaultConfig(); pickStorageType(); loadPluginData(); loadFeatures(); registerEventListeners(); registerCommands(); registerIntegrations(); getLogger().info("Storage Type: " + storage.getAdapterType()); checkUpdates(); getLogger().info("EthicalVoting has been successfully enabled."); } @Override public void onDisable() { profiles.shutdown(); voteRewardHandler.getVoteQueue().shutdown(); getLogger().info("EthicalVoting has been successfully disabled."); } public void registerIntegrations() { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new EthicalPAPI().register(); getLogger().info("PlaceholderAPI integration has been successfully enabled."); } else { getLogger().warning("PlaceholderAPI integration has failed to load."); } } /* Defines which database type will be used to store user data. Current options: - MySQL - YAML (Bukkit internal) */ public void pickStorageType() { String storageInterface = getConfig().getString("database.type"); if (storageInterface == null) { getLogger().severe("Storage Interface is null. Report this to plugin developer."); getServer().shutdown(); return; } if (storageInterface.equalsIgnoreCase("mysql")) { storage = new MySQLInterface(); String host = getConfig().getString("database.host"); int port = getConfig().getInt("database.port"); String database = getConfig().getString("database.database"); String username = getConfig().getString("database.username"); String password = getConfig().getString("database.password"); if (host == null || database == null || username == null || password == null) { getLogger().severe("MySQL credentials are null. Report this to plugin developer."); getServer().shutdown(); return; } if (!storage.jdbcInit("jdbc:mysql://" + host + ":" + port + "/" + database, username, password)) { getLogger().severe("Failed to connect to MySQL database. Report this to plugin developer."); getServer().shutdown(); return; } } else { storage = new YamlInterface(this); } } public void registerCommands() { EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand(); getCommand("ethicalvoting").setExecutor(ethicalVotingCommand); getCommand("ethicalvoting").setTabCompleter(ethicalVotingCommand);
VoteCommand voteCommand = new VoteCommand();
1
2023-12-15 16:48:38+00:00
12k
Blawuken/MicroG-Extended
play-services-base/src/main/java/com/google/android/gms/common/api/GoogleApiClient.java
[ { "identifier": "ConnectionResult", "path": "play-services-basement/src/main/java/com/google/android/gms/common/ConnectionResult.java", "snippet": "@SafeParcelable.Class\npublic class ConnectionResult extends AbstractSafeParcelable {\n /**\n * The connection was successful.\n */\n public s...
import org.microg.gms.common.api.GoogleApiClientImpl; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.View; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.common.ConnectionResult; import org.microg.gms.auth.AuthConstants; import org.microg.gms.common.PublicApi; import org.microg.gms.common.api.ApiClientSettings;
7,513
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.common.api; /** * The main entry point for Google Play services integration. * <p/> * GoogleApiClient is used with a variety of static methods. Some of these methods require that * GoogleApiClient be connected, some will queue up calls before GoogleApiClient is connected; * check the specific API documentation to determine whether you need to be connected. * <p/> * Before any operation is executed, the GoogleApiClient must be connected using the * {@link #connect()} method. The client is not considered connected until the * {@link ConnectionCallbacks#onConnected(Bundle)} callback has been called. * <p/> * When your app is done using this client, call {@link #disconnect()}, even if the async result * from {@link #connect()} has not yet been delivered. * <p/> * You should instantiate a client object in your Activity's {@link Activity#onCreate(Bundle)} * method and then call {@link #connect()} in {@link Activity#onStart()} and {@link #disconnect()} * in {@link Activity#onStop()}, regardless of the state. */ @PublicApi @Deprecated public interface GoogleApiClient { /** * Connects the client to Google Play services. Blocks until the connection either succeeds or * fails. This is not allowed on the UI thread. * * @return the result of the connection */ ConnectionResult blockingConnect(); /** * Connects the client to Google Play services. Blocks until the connection is set or failed or * has timed out. This is not allowed on the UI thread. * * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return the result of the connection */ ConnectionResult blockingConnect(long timeout, TimeUnit unit); /** * Clears the account selected by the user and reconnects the client asking the user to pick an * account again if {@link Builder#useDefaultAccount()} was set. * * @return the pending result is fired once the default account has been cleared, but before * the client is reconnected - for that {@link ConnectionCallbacks} can be used. */ PendingResult<Status> clearDefaultAccountAndReconnect(); /** * Connects the client to Google Play services. This method returns immediately, and connects * to the service in the background. If the connection is successful, * {@link ConnectionCallbacks#onConnected(Bundle)} is called and enqueued items are executed. * On a failure, {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} is * called. */ void connect(); /** * Closes the connection to Google Play services. No calls can be made using this client after * calling this method. Any method calls that haven't executed yet will be canceled. That is * {@link ResultCallback#onResult(Result)} won't be called, if connection to the service hasn't * been established yet all calls already made will be canceled. * * @see #connect() */ void disconnect(); /** * Checks if the client is currently connected to the service, so that requests to other * methods will succeed. Applications should guard client actions caused by the user with a * call to this method. * * @return {@code true} if the client is connected to the service. */ boolean isConnected(); /** * Checks if the client is attempting to connect to the service. * * @return {@code true} if the client is attempting to connect to the service. */ boolean isConnecting(); /** * Returns {@code true} if the specified listener is currently registered to receive connection * events. * * @param listener The listener to check for. * @return {@code true} if the specified listener is currently registered to receive connection * events. * @see #registerConnectionCallbacks(ConnectionCallbacks) * @see #unregisterConnectionCallbacks(ConnectionCallbacks) */ boolean isConnectionCallbacksRegistered(ConnectionCallbacks listener); /** * Returns {@code true} if the specified listener is currently registered to receive connection * failed events. * * @param listener The listener to check for. * @return {@code true} if the specified listener is currently registered to receive connection * failed events. * @see #registerConnectionFailedListener(OnConnectionFailedListener) * @see #unregisterConnectionFailedListener(OnConnectionFailedListener) */ public boolean isConnectionFailedListenerRegistered(OnConnectionFailedListener listener); /** * Closes the current connection to Google Play services and creates a new connection. * <p/> * This method closes the current connection then returns immediately and reconnects to the * service in the background. * <p/> * After calling this method, your application will receive * {@link ConnectionCallbacks#onConnected(Bundle)} if the connection is successful, or * {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} if the connection * failed. * * @see #connect() * @see #disconnect() */ void reconnect(); /** * Registers a listener to receive connection events from this {@link GoogleApiClient}. If the * service is already connected, the listener's {@link ConnectionCallbacks#onConnected(Bundle)} * method will be called immediately. Applications should balance calls to this method with * calls to {@link #unregisterConnectionCallbacks(ConnectionCallbacks)} to avoid leaking * resources. * <p/> * If the specified listener is already registered to receive connection events, this method * will not add a duplicate entry for the same listener, but will still call the listener's * {@link ConnectionCallbacks#onConnected(Bundle)} method if currently connected. * <p/> * Note that the order of messages received here may not be stable, so clients should not rely * on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} call * are delivered. */ void registerConnectionCallbacks(ConnectionCallbacks listener); /** * Registers a listener to receive connection failed events from this {@link GoogleApiClient}. * Unlike {@link #registerConnectionCallbacks(ConnectionCallbacks)}, if the service is not * already connected, the listener's * {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} method will not be * called immediately. Applications should balance calls to this method with calls to * {@link #unregisterConnectionFailedListener(OnConnectionFailedListener)} to avoid leaking * resources. * <p/> * If the specified listener is already registered to receive connection failed events, this * method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not rely * on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} call * are delivered. */ public void registerConnectionFailedListener(OnConnectionFailedListener listener); /** * Disconnects the client and stops automatic lifecycle management. Use this before creating a * new client (which might be necessary when switching accounts, changing the set of used APIs * etc.). * <p/> * This method must be called from the main thread. * * @param lifecycleActivity the activity managing the client's lifecycle. * @throws IllegalStateException if called from outside of the main thread. * @see Builder#enableAutoManage(FragmentActivity, int, OnConnectionFailedListener) */ void stopAutoManager(FragmentActivity lifecycleActivity) throws IllegalStateException; /** * Removes a connection listener from this {@link GoogleApiClient}. Note that removing a * listener does not generate any callbacks. * <p/> * If the specified listener is not currently registered to receive connection events, this * method will have no effect. * * @param listener the listener to unregister. */ void unregisterConnectionCallbacks(ConnectionCallbacks listener); /** * Removes a connection failed listener from the {@link GoogleApiClient}. Note that removing a * listener does not generate any callbacks. * <p/> * If the specified listener is not currently registered to receive connection failed events, * this method will have no effect. * * @param listener the listener to unregister. */ void unregisterConnectionFailedListener(OnConnectionFailedListener listener); /** * Builder to configure a {@link GoogleApiClient}. */ @PublicApi class Builder { private final Context context; private final Map<Api, Api.ApiOptions> apis = new HashMap<Api, Api.ApiOptions>(); private final Set<ConnectionCallbacks> connectionCallbacks = new HashSet<ConnectionCallbacks>(); private final Set<OnConnectionFailedListener> connectionFailedListeners = new HashSet<OnConnectionFailedListener>(); private final Set<String> scopes = new HashSet<String>(); private String accountName; private int clientId = -1; private FragmentActivity fragmentActivity; private Looper looper; private int gravityForPopups; private OnConnectionFailedListener unresolvedConnectionFailedListener; private View viewForPopups; /** * Builder to help construct the {@link GoogleApiClient} object. * * @param context The context to use for the connection. */ public Builder(Context context) { this.context = context; this.looper = context.getMainLooper(); } /** * Builder to help construct the {@link GoogleApiClient} object. * * @param context The context to use for the connection. * @param connectedListener The listener where the results of the asynchronous * {@link #connect()} call are delivered. * @param connectionFailedListener The listener which will be notified if the connection * attempt fails. */ public Builder(Context context, ConnectionCallbacks connectedListener, OnConnectionFailedListener connectionFailedListener) { this(context); addConnectionCallbacks(connectedListener); addOnConnectionFailedListener(connectionFailedListener); } /** * Specify which Apis are requested by your app. See {@link Api} for more information. * * @param api The Api requested by your app. * @param options Any additional parameters required for the specific AP * @see Api */ public <O extends Api.ApiOptions.HasOptions> Builder addApi(Api<O> api, O options) { apis.put(api, options); return this; } /** * Specify which Apis are requested by your app. See {@link Api} for more information. * * @param api The Api requested by your app. * @see Api */ public Builder addApi(Api<? extends Api.ApiOptions.NotRequiredOptions> api) { apis.put(api, null); return this; } /** * Registers a listener to receive connection events from this {@link GoogleApiClient}. * Applications should balance calls to this method with calls to * {@link #unregisterConnectionCallbacks(ConnectionCallbacks)} to avoid * leaking resources. * <p/> * If the specified listener is already registered to receive connection events, this * method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not * rely on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} * call are delivered. */ public Builder addConnectionCallbacks(ConnectionCallbacks listener) { connectionCallbacks.add(listener); return this; } /** * Adds a listener to register to receive connection failed events from this * {@link GoogleApiClient}. Applications should balance calls to this method with calls to * {@link #unregisterConnectionFailedListener(OnConnectionFailedListener)} to avoid * leaking resources. * <p/> * If the specified listener is already registered to receive connection failed events, * this method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not * rely on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} * call are delivered. */ public Builder addOnConnectionFailedListener(OnConnectionFailedListener listener) { connectionFailedListeners.add(listener); return this; } /** * Specify the OAuth 2.0 scopes requested by your app. See * {@link com.google.android.gms.common.Scopes} for more information. * * @param scope The OAuth 2.0 scopes requested by your app. * @see com.google.android.gms.common.Scopes */ public Builder addScope(Scope scope) { scopes.add(scope.getScopeUri()); return this; } /** * Builds a new {@link GoogleApiClient} object for communicating with the Google APIs. * * @return The {@link GoogleApiClient} object. */ public GoogleApiClient build() { return new GoogleApiClientImpl(context, looper, getClientSettings(), apis, connectionCallbacks, connectionFailedListeners, clientId); }
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.common.api; /** * The main entry point for Google Play services integration. * <p/> * GoogleApiClient is used with a variety of static methods. Some of these methods require that * GoogleApiClient be connected, some will queue up calls before GoogleApiClient is connected; * check the specific API documentation to determine whether you need to be connected. * <p/> * Before any operation is executed, the GoogleApiClient must be connected using the * {@link #connect()} method. The client is not considered connected until the * {@link ConnectionCallbacks#onConnected(Bundle)} callback has been called. * <p/> * When your app is done using this client, call {@link #disconnect()}, even if the async result * from {@link #connect()} has not yet been delivered. * <p/> * You should instantiate a client object in your Activity's {@link Activity#onCreate(Bundle)} * method and then call {@link #connect()} in {@link Activity#onStart()} and {@link #disconnect()} * in {@link Activity#onStop()}, regardless of the state. */ @PublicApi @Deprecated public interface GoogleApiClient { /** * Connects the client to Google Play services. Blocks until the connection either succeeds or * fails. This is not allowed on the UI thread. * * @return the result of the connection */ ConnectionResult blockingConnect(); /** * Connects the client to Google Play services. Blocks until the connection is set or failed or * has timed out. This is not allowed on the UI thread. * * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return the result of the connection */ ConnectionResult blockingConnect(long timeout, TimeUnit unit); /** * Clears the account selected by the user and reconnects the client asking the user to pick an * account again if {@link Builder#useDefaultAccount()} was set. * * @return the pending result is fired once the default account has been cleared, but before * the client is reconnected - for that {@link ConnectionCallbacks} can be used. */ PendingResult<Status> clearDefaultAccountAndReconnect(); /** * Connects the client to Google Play services. This method returns immediately, and connects * to the service in the background. If the connection is successful, * {@link ConnectionCallbacks#onConnected(Bundle)} is called and enqueued items are executed. * On a failure, {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} is * called. */ void connect(); /** * Closes the connection to Google Play services. No calls can be made using this client after * calling this method. Any method calls that haven't executed yet will be canceled. That is * {@link ResultCallback#onResult(Result)} won't be called, if connection to the service hasn't * been established yet all calls already made will be canceled. * * @see #connect() */ void disconnect(); /** * Checks if the client is currently connected to the service, so that requests to other * methods will succeed. Applications should guard client actions caused by the user with a * call to this method. * * @return {@code true} if the client is connected to the service. */ boolean isConnected(); /** * Checks if the client is attempting to connect to the service. * * @return {@code true} if the client is attempting to connect to the service. */ boolean isConnecting(); /** * Returns {@code true} if the specified listener is currently registered to receive connection * events. * * @param listener The listener to check for. * @return {@code true} if the specified listener is currently registered to receive connection * events. * @see #registerConnectionCallbacks(ConnectionCallbacks) * @see #unregisterConnectionCallbacks(ConnectionCallbacks) */ boolean isConnectionCallbacksRegistered(ConnectionCallbacks listener); /** * Returns {@code true} if the specified listener is currently registered to receive connection * failed events. * * @param listener The listener to check for. * @return {@code true} if the specified listener is currently registered to receive connection * failed events. * @see #registerConnectionFailedListener(OnConnectionFailedListener) * @see #unregisterConnectionFailedListener(OnConnectionFailedListener) */ public boolean isConnectionFailedListenerRegistered(OnConnectionFailedListener listener); /** * Closes the current connection to Google Play services and creates a new connection. * <p/> * This method closes the current connection then returns immediately and reconnects to the * service in the background. * <p/> * After calling this method, your application will receive * {@link ConnectionCallbacks#onConnected(Bundle)} if the connection is successful, or * {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} if the connection * failed. * * @see #connect() * @see #disconnect() */ void reconnect(); /** * Registers a listener to receive connection events from this {@link GoogleApiClient}. If the * service is already connected, the listener's {@link ConnectionCallbacks#onConnected(Bundle)} * method will be called immediately. Applications should balance calls to this method with * calls to {@link #unregisterConnectionCallbacks(ConnectionCallbacks)} to avoid leaking * resources. * <p/> * If the specified listener is already registered to receive connection events, this method * will not add a duplicate entry for the same listener, but will still call the listener's * {@link ConnectionCallbacks#onConnected(Bundle)} method if currently connected. * <p/> * Note that the order of messages received here may not be stable, so clients should not rely * on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} call * are delivered. */ void registerConnectionCallbacks(ConnectionCallbacks listener); /** * Registers a listener to receive connection failed events from this {@link GoogleApiClient}. * Unlike {@link #registerConnectionCallbacks(ConnectionCallbacks)}, if the service is not * already connected, the listener's * {@link OnConnectionFailedListener#onConnectionFailed(ConnectionResult)} method will not be * called immediately. Applications should balance calls to this method with calls to * {@link #unregisterConnectionFailedListener(OnConnectionFailedListener)} to avoid leaking * resources. * <p/> * If the specified listener is already registered to receive connection failed events, this * method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not rely * on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} call * are delivered. */ public void registerConnectionFailedListener(OnConnectionFailedListener listener); /** * Disconnects the client and stops automatic lifecycle management. Use this before creating a * new client (which might be necessary when switching accounts, changing the set of used APIs * etc.). * <p/> * This method must be called from the main thread. * * @param lifecycleActivity the activity managing the client's lifecycle. * @throws IllegalStateException if called from outside of the main thread. * @see Builder#enableAutoManage(FragmentActivity, int, OnConnectionFailedListener) */ void stopAutoManager(FragmentActivity lifecycleActivity) throws IllegalStateException; /** * Removes a connection listener from this {@link GoogleApiClient}. Note that removing a * listener does not generate any callbacks. * <p/> * If the specified listener is not currently registered to receive connection events, this * method will have no effect. * * @param listener the listener to unregister. */ void unregisterConnectionCallbacks(ConnectionCallbacks listener); /** * Removes a connection failed listener from the {@link GoogleApiClient}. Note that removing a * listener does not generate any callbacks. * <p/> * If the specified listener is not currently registered to receive connection failed events, * this method will have no effect. * * @param listener the listener to unregister. */ void unregisterConnectionFailedListener(OnConnectionFailedListener listener); /** * Builder to configure a {@link GoogleApiClient}. */ @PublicApi class Builder { private final Context context; private final Map<Api, Api.ApiOptions> apis = new HashMap<Api, Api.ApiOptions>(); private final Set<ConnectionCallbacks> connectionCallbacks = new HashSet<ConnectionCallbacks>(); private final Set<OnConnectionFailedListener> connectionFailedListeners = new HashSet<OnConnectionFailedListener>(); private final Set<String> scopes = new HashSet<String>(); private String accountName; private int clientId = -1; private FragmentActivity fragmentActivity; private Looper looper; private int gravityForPopups; private OnConnectionFailedListener unresolvedConnectionFailedListener; private View viewForPopups; /** * Builder to help construct the {@link GoogleApiClient} object. * * @param context The context to use for the connection. */ public Builder(Context context) { this.context = context; this.looper = context.getMainLooper(); } /** * Builder to help construct the {@link GoogleApiClient} object. * * @param context The context to use for the connection. * @param connectedListener The listener where the results of the asynchronous * {@link #connect()} call are delivered. * @param connectionFailedListener The listener which will be notified if the connection * attempt fails. */ public Builder(Context context, ConnectionCallbacks connectedListener, OnConnectionFailedListener connectionFailedListener) { this(context); addConnectionCallbacks(connectedListener); addOnConnectionFailedListener(connectionFailedListener); } /** * Specify which Apis are requested by your app. See {@link Api} for more information. * * @param api The Api requested by your app. * @param options Any additional parameters required for the specific AP * @see Api */ public <O extends Api.ApiOptions.HasOptions> Builder addApi(Api<O> api, O options) { apis.put(api, options); return this; } /** * Specify which Apis are requested by your app. See {@link Api} for more information. * * @param api The Api requested by your app. * @see Api */ public Builder addApi(Api<? extends Api.ApiOptions.NotRequiredOptions> api) { apis.put(api, null); return this; } /** * Registers a listener to receive connection events from this {@link GoogleApiClient}. * Applications should balance calls to this method with calls to * {@link #unregisterConnectionCallbacks(ConnectionCallbacks)} to avoid * leaking resources. * <p/> * If the specified listener is already registered to receive connection events, this * method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not * rely on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} * call are delivered. */ public Builder addConnectionCallbacks(ConnectionCallbacks listener) { connectionCallbacks.add(listener); return this; } /** * Adds a listener to register to receive connection failed events from this * {@link GoogleApiClient}. Applications should balance calls to this method with calls to * {@link #unregisterConnectionFailedListener(OnConnectionFailedListener)} to avoid * leaking resources. * <p/> * If the specified listener is already registered to receive connection failed events, * this method will not add a duplicate entry for the same listener. * <p/> * Note that the order of messages received here may not be stable, so clients should not * rely on the order that multiple listeners receive events in. * * @param listener the listener where the results of the asynchronous {@link #connect()} * call are delivered. */ public Builder addOnConnectionFailedListener(OnConnectionFailedListener listener) { connectionFailedListeners.add(listener); return this; } /** * Specify the OAuth 2.0 scopes requested by your app. See * {@link com.google.android.gms.common.Scopes} for more information. * * @param scope The OAuth 2.0 scopes requested by your app. * @see com.google.android.gms.common.Scopes */ public Builder addScope(Scope scope) { scopes.add(scope.getScopeUri()); return this; } /** * Builds a new {@link GoogleApiClient} object for communicating with the Google APIs. * * @return The {@link GoogleApiClient} object. */ public GoogleApiClient build() { return new GoogleApiClientImpl(context, looper, getClientSettings(), apis, connectionCallbacks, connectionFailedListeners, clientId); }
private ApiClientSettings getClientSettings() {
2
2023-12-17 16:14:53+00:00
12k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/Raish.java
[ { "identifier": "SampleMecanumDrive", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java", "snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n publi...
import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.geometry.Vector2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DistanceSensor; import com.qualcomm.robotcore.hardware.OpticalDistanceSensor; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.openftc.apriltag.AprilTagDetection; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; import java.util.ArrayList;
10,085
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class Raish extends LinearOpMode { public static double SPEED = 0.15; OpticalDistanceSensor lightSensor; ColorSensor colorSensor; DistanceSensor distanceSensor; Boolean RedFirstTime = false; public double correction; public static double FirstDistance = 46; public static int ticksdc = 50; DcMotor armmotor; boolean Starting = false; boolean SawRed = false; boolean SawCancer = false; boolean SawCancer1 = false; int ConusIndex = 0; double value; private Servo Armservo; private Servo AngleServo; private Servo Claw; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); Armservo = hardwareMap.get(Servo .class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); double armservoTarget = 0.5; double Angle = 0.4; double ClawPos = 0.65; armmotor = hardwareMap.dcMotor.get("armmotor"); armmotor.setTargetPosition(0); armmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); camera.setPipeline(aprilTagDetectionPipeline); camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); } SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); colorSensor = hardwareMap.get(ColorSensor.class, "sensor_color"); distanceSensor = hardwareMap.get(DistanceSensor.class, "DistanceSensor"); waitForStart(); if (isStopRequested()) return; //--------------------------------------------------------------------------------------
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class Raish extends LinearOpMode { public static double SPEED = 0.15; OpticalDistanceSensor lightSensor; ColorSensor colorSensor; DistanceSensor distanceSensor; Boolean RedFirstTime = false; public double correction; public static double FirstDistance = 46; public static int ticksdc = 50; DcMotor armmotor; boolean Starting = false; boolean SawRed = false; boolean SawCancer = false; boolean SawCancer1 = false; int ConusIndex = 0; double value; private Servo Armservo; private Servo AngleServo; private Servo Claw; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); Armservo = hardwareMap.get(Servo .class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); double armservoTarget = 0.5; double Angle = 0.4; double ClawPos = 0.65; armmotor = hardwareMap.dcMotor.get("armmotor"); armmotor.setTargetPosition(0); armmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); camera.setPipeline(aprilTagDetectionPipeline); camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); } SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); colorSensor = hardwareMap.get(ColorSensor.class, "sensor_color"); distanceSensor = hardwareMap.get(DistanceSensor.class, "DistanceSensor"); waitForStart(); if (isStopRequested()) return; //--------------------------------------------------------------------------------------
TrajectorySequence raish = drive.trajectorySequenceBuilder(new Pose2d())
1
2023-12-15 16:57:19+00:00
12k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/server/MinecraftServer.java
[ { "identifier": "LevelIO", "path": "src/com/mojang/minecraft/level/LevelIO.java", "snippet": "public final class LevelIO {\r\n\r\n private MinecraftServer server;\r\n\r\n\r\n public LevelIO(MinecraftServer var1) {\r\n this.server = var1;\r\n }\r\n\r\n public final Level load(InputStream var...
import com.mojang.minecraft.level.LevelIO; import com.mojang.minecraft.level.generator.LevelGenerator; import com.mojang.minecraft.net.PacketType; import com.mojang.net.BindTo; import com.mojang.net.NetworkHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger;
9,157
package com.mojang.minecraft.server; public class MinecraftServer implements Runnable { static Logger logger = Logger.getLogger("MinecraftServer"); static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
package com.mojang.minecraft.server; public class MinecraftServer implements Runnable { static Logger logger = Logger.getLogger("MinecraftServer"); static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private BindTo bindTo;
3
2023-12-18 15:38:59+00:00
12k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AcquistoVoucherController.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.VoucherEntity; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.ValoreVoucher; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.view.HomePage; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.ResourceBundle;
10,131
lblVoucherId.setText(voucher.getId()); lblPrice.setText(importo.toString()); lblTotale.setText("€ " + voucher.getPrezzo()); } /** * Abilita le modifiche al text-field messaggio */ @FXML protected void onModificaTesto() { txtMessaggio.setDisable(false); } /** * @throws Exception * @see #onAlert(String) * @see #onScaricaBigliettoPDF() * @see #onGoToHomepage() * @see Acquisto * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> carrello = new ArrayList<>(); carrello.add(this.voucher); carrello.get(0).pagare(); if (Account.getLoggedIn()) { this.voucher.puntiFedelta(carrello); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } onScaricaBigliettoPDF(); onGoToHomepage(); } /** * Apre il file chooser e permette di scaricare il voucher in formato PDF * * @throws Exception * @see #fillPDF() * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF() throws Exception { fillPDF(); File voucher = new File(TicketBuilder.DEST); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il voucher"); fileChooser.setInitialFileName(lblVoucherId.getText()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(voucher, destin); Task<Void> task = new Task<>() { /** * Aspetta 4.0 secondi * @return sempre null * @throws InterruptedException necessaria per Thread.sleep() */ @Override public @Nullable Void call() throws InterruptedException { Thread.sleep(4000); return null; } }; task.setOnSucceeded(e -> { voucher.delete(); }); new Thread(task).start(); } /** * Compila i campi del voucher PDF * * @throws Exception * @see TicketBuilder */ private void fillPDF() throws Exception { titoloViaggio = new TicketBuilder(lblVoucherId.getText(), lblPrice.getText(), txtMessaggio.getText()); titoloViaggio.createVORegalo(); } /** * Conferma i dati personali */ @FXML protected void onConfermaDati() { lblDatiOK.setVisible(true); txtNome.setDisable(true); txtCognome.setDisable(true); dtpDataNascita.setDisable(true); txtVia.setDisable(true); txtCivico.setDisable(true); txtCitta.setDisable(true); txtCAP.setDisable(true); txtEmail.setDisable(true); } /** * Gestisce il controllo e la scelta della carta di credito * * @see Utils */ @FXML protected void onAggiungiCarta() {
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per acquistoVoucher.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.acquistoVoucher * @see javafx.fxml.Initializable */ public class AcquistoVoucherController implements Initializable { @FXML private BorderPane root; @FXML private Label lblVoucherId; @FXML private TextArea txtMessaggio; @FXML private Label lblPrice; @FXML private Button btnAcquisto; @FXML private TextField txtNumCarta; @FXML private TextField txtDataScadenza; @FXML private TextField txtCVV; @FXML private Label lblTotale; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Button btnAggiungiPagamento; @FXML private Label lblErroreNumCarta; @FXML private Label lblErroreData; @FXML private Label lblErroreCVV; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; @FXML private Label lblErroreMaxCaratteri; @FXML private VBox vboxDragMouse; private TicketBuilder titoloViaggio; private VoucherEntity voucher; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account */ @Override public void initialize(URL location, ResourceBundle resources) { checkPagamentoRealTime(); checkDatiRealTime(); vboxDragMouse.setOnMouseMoved(c -> { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); }); txtMessaggio.textProperty().addListener(c -> { if (txtMessaggio.getText().length() >= 100) { txtMessaggio.setStyle("-fx-border-color: #d70000; -fx-border-radius: 8 8 8 8"); lblErroreMaxCaratteri.setVisible(true); txtMessaggio.setDisable(true); } else { txtMessaggio.setStyle("-fx-border-color: #cccccc; -fx-border-radius: 8 8 8 8"); lblErroreMaxCaratteri.setVisible(false); } }); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Genera un voucher dato un importo * * @param importo valore in euro (enum) * @see VoucherEntity */ public void setVoucher(@NotNull ValoreVoucher importo) { String[] valore = importo.toString().split("(?=€)"); voucher = new VoucherEntity(); voucher.setPrezzo(Double.parseDouble(valore[0])); lblVoucherId.setText(voucher.getId()); lblPrice.setText(importo.toString()); lblTotale.setText("€ " + voucher.getPrezzo()); } /** * Abilita le modifiche al text-field messaggio */ @FXML protected void onModificaTesto() { txtMessaggio.setDisable(false); } /** * @throws Exception * @see #onAlert(String) * @see #onScaricaBigliettoPDF() * @see #onGoToHomepage() * @see Acquisto * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> carrello = new ArrayList<>(); carrello.add(this.voucher); carrello.get(0).pagare(); if (Account.getLoggedIn()) { this.voucher.puntiFedelta(carrello); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } onScaricaBigliettoPDF(); onGoToHomepage(); } /** * Apre il file chooser e permette di scaricare il voucher in formato PDF * * @throws Exception * @see #fillPDF() * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF() throws Exception { fillPDF(); File voucher = new File(TicketBuilder.DEST); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il voucher"); fileChooser.setInitialFileName(lblVoucherId.getText()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(voucher, destin); Task<Void> task = new Task<>() { /** * Aspetta 4.0 secondi * @return sempre null * @throws InterruptedException necessaria per Thread.sleep() */ @Override public @Nullable Void call() throws InterruptedException { Thread.sleep(4000); return null; } }; task.setOnSucceeded(e -> { voucher.delete(); }); new Thread(task).start(); } /** * Compila i campi del voucher PDF * * @throws Exception * @see TicketBuilder */ private void fillPDF() throws Exception { titoloViaggio = new TicketBuilder(lblVoucherId.getText(), lblPrice.getText(), txtMessaggio.getText()); titoloViaggio.createVORegalo(); } /** * Conferma i dati personali */ @FXML protected void onConfermaDati() { lblDatiOK.setVisible(true); txtNome.setDisable(true); txtCognome.setDisable(true); dtpDataNascita.setDisable(true); txtVia.setDisable(true); txtCivico.setDisable(true); txtCitta.setDisable(true); txtCAP.setDisable(true); txtEmail.setDisable(true); } /** * Gestisce il controllo e la scelta della carta di credito * * @see Utils */ @FXML protected void onAggiungiCarta() {
if (Utils.checkNumCarta(txtNumCarta.getText()) && Utils.checkDataScadenza(txtDataScadenza.getText()) && Utils.checkCVV(txtCVV.getText())) {
0
2023-12-21 10:41:11+00:00
12k
chulakasam/layered
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory boFactory;\n private BOFactory(){\n\n }\n public static BOFactory getBOFactory(){\n return (boFactory==null) ? boFact...
import com.example.layeredarchitecture.bo.BOFactory; import com.example.layeredarchitecture.bo.PlaceOrderBO; import com.example.layeredarchitecture.bo.PlaceOrderBOImpl; import com.example.layeredarchitecture.dao.custom.CustomerDAO; import com.example.layeredarchitecture.dao.custom.Impl.CustomerDAOImpl; import com.example.layeredarchitecture.dao.custom.Impl.ItemDAO; import com.example.layeredarchitecture.dao.custom.Impl.OrderDAO; import com.example.layeredarchitecture.dao.custom.Impl.OrderDetailDAOImpl; import com.example.layeredarchitecture.dao.custom.ItemDao; import com.example.layeredarchitecture.dao.custom.OrderDao; import com.example.layeredarchitecture.dao.custom.OrderDetailDAO; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.model.CustomerDTO; import com.example.layeredarchitecture.model.ItemDTO; import com.example.layeredarchitecture.model.OrderDetailDTO; import com.example.layeredarchitecture.view.tdm.OrderDetailTM; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
9,091
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { //CustomerDAOImpl customerDAO = new CustomerDAOImpl(); if (!placeOrderBO.existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { //ItemDAO itemDAO = new ItemDAO(); if (!placeOrderBO.existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } public String generateNewOrderId() { try { return placeOrderBO.generateNextId(); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomerIds = placeOrderBO.loadAllCustomerIds(); for(CustomerDTO c:allCustomerIds){ cmbCustomerId.getItems().add(c.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItemIds = placeOrderBO.loadAllItemIds(); for(ItemDTO itemDTO:allItemIds){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { //CustomerDAOImpl customerDAO = new CustomerDAOImpl(); if (!placeOrderBO.existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { //ItemDAO itemDAO = new ItemDAO(); if (!placeOrderBO.existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } public String generateNewOrderId() { try { return placeOrderBO.generateNextId(); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomerIds = placeOrderBO.loadAllCustomerIds(); for(CustomerDTO c:allCustomerIds){ cmbCustomerId.getItems().add(c.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItemIds = placeOrderBO.loadAllItemIds(); for(ItemDTO itemDTO:allItemIds){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
14
2023-12-15 04:45:10+00:00
12k
pan2013e/ppt4j
misc/src/main/java/ppt4j/Demo.java
[ { "identifier": "PatchAnalyzer", "path": "framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java", "snippet": "@Log4j\npublic class PatchAnalyzer {\n\n @Property(\"ppt4j.analysis.patch.presence_threshold\")\n private static double PATCH_PRESENCE_THRESHOLD;\n\n @Property(\"ppt4j.feature...
import ppt4j.analysis.patch.PatchAnalyzer; import ppt4j.database.Vulnerability; import ppt4j.database.VulnerabilityInfo; import ppt4j.factory.DatabaseFactory; import ppt4j.factory.ExtractorFactory; import ppt4j.util.PropertyUtils; import ppt4j.util.ResourceUtils; import ppt4j.util.VMUtils; import com.sun.tools.attach.VirtualMachine; import java.io.IOException;
10,181
package ppt4j; // Command line example (invoke in the project root folder) // java -Djdk.attach.allowAttachSelf=true --add-opens java.base/java.lang=ALL-UNNAMED \ // --add-opens java.base/java.lang.reflect=ALL-UNNAMED \ // -cp misc/target/classes:framework/target/classes:lib/*:${HOME}/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar \ // ppt4j.Demo // p.s. In some shells, e.g. zsh, you may need to escape the asterisk // In this prototype version, this class should be placed under `ppt4j` package, // otherwise the aspectjweaver agent will not work as expected, and some properties // will not be automatically loaded. /** * This class is a demo of how to use the patch * presence test framework in real cases * DEMO ONLY, NOT COMPILABLE */ @SuppressWarnings("unused") public class Demo { static { String prop = System.getProperty("jdk.attach.allowAttachSelf", "false"); if (!prop.equals("true")) { System.err.println("Error: set -Djdk.attach.allowAttachSelf=true when starting the VM"); System.exit(1); } try { VirtualMachine vm = VirtualMachine.attach("" + ProcessHandle.current().pid()); vm.loadAgent("lib/aspectjweaver-1.9.19.jar"); vm.detach(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } PropertyUtils.load(ResourceUtils.readProperties()); PropertyUtils.init(); } public static void main(String[] args) throws IOException { String home = System.getProperty("user.home"); // 1. Provide the directory of the project (pre-patch and post-patch versions) // Specify the string to something like "...src/main/java", so that // the framework can find the source code of the project String PREPATCH_DIR = home + "/database/prepatch/8/src/main/java"; String POSTPATCH_DIR = home + "/database/postpatch/8/src/main/java"; // 2. Provide the top level directory of the compiled classes // e.g., the classfile of aaa.bbb.XXX is in `CLASSPATH/aaa/bbb/XXX.class`, // so you should provide the path to `CLASSPATH` // or you can provide the path to a .jar file String CLASSPATH = home + "/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar"; // 3. Provide paths to third-party source code (optional) // For vulnerabilities in the dataset, this step is not required String[] THIRD_PARTY = new String[]{"<path to third-party dependencies>"}; // Note 1: You should manually set the classpath when invoking JVM using "-cp", // otherwise the framework will not be able to load classes when analyzing. // Note 2: PPT4J loads the bytecode to be analyzed, so be careful if you // want to test its own 3rd-party dependencies (e.g., asm). It should be fine // if you pass in a directory of classfiles, e.g., target/classes. But if you pass // in a jar file, please place your jar file before `lib/*` in the classpath, // so that the VM loads your jar file first. However, as the loaded dependency // changes, the framework may not work as expected. VMUtils.checkVMClassPathPresent(CLASSPATH); // 3. Create an ExtractorFactory instance with previous resources // The factory instance will be responsible for feature extractions // and feature matching ExtractorFactory factory = ExtractorFactory.get( PREPATCH_DIR, POSTPATCH_DIR, CLASSPATH //, THIRD_PARTY ); // 4. Create a Vulnerability instance // i. You can create a VulnerabilityInfo instance explicitly, // then assign values to all non-null fields
package ppt4j; // Command line example (invoke in the project root folder) // java -Djdk.attach.allowAttachSelf=true --add-opens java.base/java.lang=ALL-UNNAMED \ // --add-opens java.base/java.lang.reflect=ALL-UNNAMED \ // -cp misc/target/classes:framework/target/classes:lib/*:${HOME}/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar \ // ppt4j.Demo // p.s. In some shells, e.g. zsh, you may need to escape the asterisk // In this prototype version, this class should be placed under `ppt4j` package, // otherwise the aspectjweaver agent will not work as expected, and some properties // will not be automatically loaded. /** * This class is a demo of how to use the patch * presence test framework in real cases * DEMO ONLY, NOT COMPILABLE */ @SuppressWarnings("unused") public class Demo { static { String prop = System.getProperty("jdk.attach.allowAttachSelf", "false"); if (!prop.equals("true")) { System.err.println("Error: set -Djdk.attach.allowAttachSelf=true when starting the VM"); System.exit(1); } try { VirtualMachine vm = VirtualMachine.attach("" + ProcessHandle.current().pid()); vm.loadAgent("lib/aspectjweaver-1.9.19.jar"); vm.detach(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } PropertyUtils.load(ResourceUtils.readProperties()); PropertyUtils.init(); } public static void main(String[] args) throws IOException { String home = System.getProperty("user.home"); // 1. Provide the directory of the project (pre-patch and post-patch versions) // Specify the string to something like "...src/main/java", so that // the framework can find the source code of the project String PREPATCH_DIR = home + "/database/prepatch/8/src/main/java"; String POSTPATCH_DIR = home + "/database/postpatch/8/src/main/java"; // 2. Provide the top level directory of the compiled classes // e.g., the classfile of aaa.bbb.XXX is in `CLASSPATH/aaa/bbb/XXX.class`, // so you should provide the path to `CLASSPATH` // or you can provide the path to a .jar file String CLASSPATH = home + "/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar"; // 3. Provide paths to third-party source code (optional) // For vulnerabilities in the dataset, this step is not required String[] THIRD_PARTY = new String[]{"<path to third-party dependencies>"}; // Note 1: You should manually set the classpath when invoking JVM using "-cp", // otherwise the framework will not be able to load classes when analyzing. // Note 2: PPT4J loads the bytecode to be analyzed, so be careful if you // want to test its own 3rd-party dependencies (e.g., asm). It should be fine // if you pass in a directory of classfiles, e.g., target/classes. But if you pass // in a jar file, please place your jar file before `lib/*` in the classpath, // so that the VM loads your jar file first. However, as the loaded dependency // changes, the framework may not work as expected. VMUtils.checkVMClassPathPresent(CLASSPATH); // 3. Create an ExtractorFactory instance with previous resources // The factory instance will be responsible for feature extractions // and feature matching ExtractorFactory factory = ExtractorFactory.get( PREPATCH_DIR, POSTPATCH_DIR, CLASSPATH //, THIRD_PARTY ); // 4. Create a Vulnerability instance // i. You can create a VulnerabilityInfo instance explicitly, // then assign values to all non-null fields
VulnerabilityInfo vulInfo = new VulnerabilityInfo();
2
2023-12-14 15:33:50+00:00
12k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/common/Gun.java
[ { "identifier": "GunMod", "path": "src/main/java/com/mrcrayfish/guns/GunMod.java", "snippet": "@Mod(Reference.MOD_ID)\npublic class GunMod\n{\n public static boolean debugging = false;\n public static boolean controllableLoaded = false;\n public static boolean backpackedLoaded = false;\n pub...
import com.google.common.base.Preconditions; import com.google.gson.JsonObject; import com.mrcrayfish.guns.GunMod; import com.mrcrayfish.guns.Reference; import com.mrcrayfish.guns.annotation.Ignored; import com.mrcrayfish.guns.annotation.Optional; import com.mrcrayfish.guns.client.ClientHandler; import com.mrcrayfish.guns.compat.BackpackHelper; import com.mrcrayfish.guns.debug.Debug; import com.mrcrayfish.guns.debug.IDebugWidget; import com.mrcrayfish.guns.debug.IEditorMenu; import com.mrcrayfish.guns.debug.client.screen.widget.DebugButton; import com.mrcrayfish.guns.debug.client.screen.widget.DebugSlider; import com.mrcrayfish.guns.debug.client.screen.widget.DebugToggle; import com.mrcrayfish.guns.item.ScopeItem; import com.mrcrayfish.guns.item.attachment.IAttachment; import com.mrcrayfish.guns.item.attachment.impl.Scope; import com.mrcrayfish.guns.util.GunJsonUtil; import com.mrcrayfish.guns.util.SuperBuilder; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.util.Mth; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.registries.ForgeRegistries; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Supplier;
10,199
{ return this.rate; } /** * @return The type of grip this weapon uses */ public GripType getGripType() { return this.gripType; } /** * @return The maximum amount of ammo this weapon can hold */ public int getMaxAmmo() { return this.maxAmmo; } /** * @return The amount of ammo to add to the weapon each reload cycle */ public int getReloadAmount() { return this.reloadAmount; } /** * @return The amount of recoil this gun produces upon firing in degrees */ public float getRecoilAngle() { return this.recoilAngle; } /** * @return A radian that recoil may offset from vertical */ public float getRecoilRadian() { return this.recoilRadian; } /** * @return The amount of recoil ticks */ public float getRecoilDuration() { return this.recoilDuration; } /** * @return The amount of kick this gun produces upon firing */ public float getRecoilKick() { return this.recoilKick; } /** * @return The duration offset for recoil. This reduces the duration of recoil animation */ public float getRecoilDurationOffset() { return this.recoilDurationOffset; } /** * @return The amount of recoil reduction applied when aiming down this weapon's sight */ public float getRecoilAdsReduction() { return this.recoilAdsReduction; } /** * @return The amount of projectiles this weapon fires */ public int getProjectileAmount() { return this.projectileAmount; } /** * @return The count of projectiles this weapon fires at a strike */ public int getProjectileBurst() { return this.projectileBurst; } /** * @return If this weapon should always spread it's projectiles according to {@link #getSpread()} */ public boolean isAlwaysSpread() { return this.alwaysSpread; } /** * @return The maximum amount of degrees applied to the initial pitch and yaw direction of * the fired projectile. */ public float getSpread() { return this.spread; } /** * @return The amount of spread reduction allpied when aiming down this weapon's sight */ public float getSpreadAdsReduction() { return this.spreadAdsReduction; } } public static class Projectile implements INBTSerializable<CompoundTag> {
package com.mrcrayfish.guns.common; public class Gun implements INBTSerializable<CompoundTag>, IEditorMenu { protected General general = new General(); protected Projectile projectile = new Projectile(); protected Sounds sounds = new Sounds(); protected Display display = new Display(); protected Modules modules = new Modules(); public General getGeneral() { return this.general; } public Projectile getProjectile() { return this.projectile; } public Sounds getSounds() { return this.sounds; } public Display getDisplay() { return this.display; } public Modules getModules() { return this.modules; } @Override public Component getEditorLabel() { return Component.literal("Gun"); } @Override public void getEditorWidgets(List<Pair<Component, Supplier<IDebugWidget>>> widgets) { DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { ItemStack heldItem = Objects.requireNonNull(Minecraft.getInstance().player).getMainHandItem(); ItemStack scope = Gun.getScopeStack(heldItem); if(scope.getItem() instanceof ScopeItem scopeItem) { widgets.add(Pair.of(scope.getItem().getName(scope), () -> new DebugButton(Component.literal("Edit"), btn -> { Minecraft.getInstance().setScreen(ClientHandler.createEditorScreen(Debug.getScope(scopeItem))); }))); } widgets.add(Pair.of(this.modules.getEditorLabel(), () -> new DebugButton(Component.literal(">"), btn -> { Minecraft.getInstance().setScreen(ClientHandler.createEditorScreen(this.modules)); }))); }); } public static class General implements INBTSerializable<CompoundTag> { @Optional private boolean auto = false; private int rate; @Ignored private GripType gripType = GripType.ONE_HANDED; private int maxAmmo; @Optional private int reloadAmount = 1; @Optional private float recoilAngle; @Optional private float recoilRadian = 0.0F; @Optional private float recoilDuration = 6.67F; @Optional private float recoilKick; @Optional private float recoilDurationOffset; @Optional private float recoilAdsReduction = 0.2F; @Optional private int projectileAmount = 1; @Optional private int projectileBurst = 1; @Optional private boolean alwaysSpread; @Optional private float spread; @Optional private float spreadAdsReduction = 0.5F; @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); tag.putBoolean("Auto", this.auto); tag.putInt("Rate", this.rate); tag.putString("GripType", this.gripType.getId().toString()); tag.putInt("MaxAmmo", this.maxAmmo); tag.putInt("ReloadSpeed", this.reloadAmount); tag.putFloat("RecoilAngle", this.recoilAngle); tag.putFloat("RecoilRadian", this.recoilRadian); tag.putFloat("RecoilDuration", this.recoilDuration); tag.putFloat("RecoilKick", this.recoilKick); tag.putFloat("RecoilDurationOffset", this.recoilDurationOffset); tag.putFloat("RecoilAdsReduction", this.recoilAdsReduction); tag.putInt("ProjectileAmount", this.projectileAmount); tag.putInt("ProjectileBurst", this.projectileBurst); tag.putBoolean("AlwaysSpread", this.alwaysSpread); tag.putFloat("Spread", this.spread); tag.putFloat("SpreadAdsReduction", this.spreadAdsReduction); return tag; } @Override public void deserializeNBT(CompoundTag tag) { if(tag.contains("Auto", Tag.TAG_ANY_NUMERIC)) { this.auto = tag.getBoolean("Auto"); } if(tag.contains("Rate", Tag.TAG_ANY_NUMERIC)) { this.rate = tag.getInt("Rate"); } if(tag.contains("GripType", Tag.TAG_STRING)) { this.gripType = GripType.getType(ResourceLocation.tryParse(tag.getString("GripType"))); } if(tag.contains("MaxAmmo", Tag.TAG_ANY_NUMERIC)) { this.maxAmmo = tag.getInt("MaxAmmo"); } if(tag.contains("ReloadSpeed", Tag.TAG_ANY_NUMERIC)) { this.reloadAmount = tag.getInt("ReloadSpeed"); } if(tag.contains("RecoilAngle", Tag.TAG_ANY_NUMERIC)) { this.recoilAngle = tag.getFloat("RecoilAngle"); } if(tag.contains("RecoilRadian", Tag.TAG_ANY_NUMERIC)) { this.recoilRadian = tag.getFloat("RecoilRadian"); } if(tag.contains("RecoilDuration", Tag.TAG_ANY_NUMERIC)) { this.recoilDuration = tag.getFloat("RecoilDuration"); } if(tag.contains("RecoilKick", Tag.TAG_ANY_NUMERIC)) { this.recoilKick = tag.getFloat("RecoilKick"); } if(tag.contains("RecoilDurationOffset", Tag.TAG_ANY_NUMERIC)) { this.recoilDurationOffset = tag.getFloat("RecoilDurationOffset"); } if(tag.contains("RecoilAdsReduction", Tag.TAG_ANY_NUMERIC)) { this.recoilAdsReduction = tag.getFloat("RecoilAdsReduction"); } if(tag.contains("ProjectileAmount", Tag.TAG_ANY_NUMERIC)) { this.projectileAmount = tag.getInt("ProjectileAmount"); } if(tag.contains("ProjectileBurst", Tag.TAG_ANY_NUMERIC)) { this.projectileBurst = tag.getInt("ProjectileBurst"); } if(tag.contains("AlwaysSpread", Tag.TAG_ANY_NUMERIC)) { this.alwaysSpread = tag.getBoolean("AlwaysSpread"); } if(tag.contains("Spread", Tag.TAG_ANY_NUMERIC)) { this.spread = tag.getFloat("Spread"); } if(tag.contains("SpreadAdsReduction", Tag.TAG_ANY_NUMERIC)) { this.spreadAdsReduction = tag.getFloat("SpreadAdsReduction"); } } public JsonObject toJsonObject() { Preconditions.checkArgument(this.rate > 0, "Rate must be more than zero"); Preconditions.checkArgument(this.maxAmmo > 0, "Max ammo must be more than zero"); Preconditions.checkArgument(this.reloadAmount >= 1, "Reload angle must be more than or equal to zero"); Preconditions.checkArgument(this.recoilAngle >= 0.0F, "Recoil angle must be more than or equal to zero"); Preconditions.checkArgument(this.recoilRadian >= 0.0F, "Recoil radian must be more than or equal to zero"); Preconditions.checkArgument(this.recoilDuration > 0.0F, "Recoil duration must be more than zero"); Preconditions.checkArgument(this.recoilKick >= 0.0F, "Recoil kick must be more than or equal to zero"); Preconditions.checkArgument(this.recoilDurationOffset >= 0.0F && this.recoilDurationOffset <= 1.0F, "Recoil duration offset must be between 0.0 and 1.0"); Preconditions.checkArgument(this.recoilAdsReduction >= 0.0F && this.recoilAdsReduction <= 1.0F, "Recoil ads reduction must be between 0.0 and 1.0"); Preconditions.checkArgument(this.projectileAmount >= 1, "Projectile amount must be more than or equal to one"); Preconditions.checkArgument(this.projectileBurst >= 1, "Projectile burst must be more than or equal to one"); Preconditions.checkArgument(this.spread >= 0.0F, "Spread must be more than or equal to zero"); Preconditions.checkArgument(this.spreadAdsReduction >= 0.0F && this.spreadAdsReduction <= 1.0F, "Spread ads reduction must be between 0.0 and 1.0"); JsonObject object = new JsonObject(); if(this.auto) object.addProperty("auto", true); object.addProperty("rate", this.rate); object.addProperty("gripType", this.gripType.getId().toString()); object.addProperty("maxAmmo", this.maxAmmo); if(this.reloadAmount != 1) object.addProperty("reloadAmount", this.reloadAmount); if(this.recoilAngle != 0.0F) object.addProperty("recoilAngle", this.recoilAngle); if(this.recoilRadian != 0.0F) object.addProperty("recoilRadian", this.recoilRadian); if(this.recoilDuration != 6.67F) object.addProperty("recoilDuration", this.recoilDuration); if(this.recoilKick != 0.0F) object.addProperty("recoilKick", this.recoilKick); if(this.recoilDurationOffset != 0.0F) object.addProperty("recoilDurationOffset", this.recoilDurationOffset); if(this.recoilAdsReduction != 0.2F) object.addProperty("recoilAdsReduction", this.recoilAdsReduction); if(this.projectileAmount != 1) object.addProperty("projectileAmount", this.projectileAmount); if(this.projectileBurst != 1) object.addProperty("projectileBurst", this.projectileBurst); if(this.alwaysSpread) object.addProperty("alwaysSpread", true); if(this.spread != 0.0F) object.addProperty("spread", this.spread); if(this.spreadAdsReduction != 0.5F) object.addProperty("spreadAdsReduction", this.spreadAdsReduction); return object; } /** * @return A copy of the general get */ public General copy() { General general = new General(); general.auto = this.auto; general.rate = this.rate; general.gripType = this.gripType; general.maxAmmo = this.maxAmmo; general.reloadAmount = this.reloadAmount; general.recoilAngle = this.recoilAngle; general.recoilRadian = this.recoilRadian; general.recoilDuration = this.recoilDuration; general.recoilKick = this.recoilKick; general.recoilDurationOffset = this.recoilDurationOffset; general.recoilAdsReduction = this.recoilAdsReduction; general.projectileAmount = this.projectileAmount; general.projectileBurst = this.projectileBurst; general.alwaysSpread = this.alwaysSpread; general.spread = this.spread; general.spreadAdsReduction = this.spreadAdsReduction; return general; } /** * @return If this gun is automatic or not */ public boolean isAuto() { return this.auto; } /** * @return The fire rate of this weapon in ticks */ public int getRate() { return this.rate; } /** * @return The type of grip this weapon uses */ public GripType getGripType() { return this.gripType; } /** * @return The maximum amount of ammo this weapon can hold */ public int getMaxAmmo() { return this.maxAmmo; } /** * @return The amount of ammo to add to the weapon each reload cycle */ public int getReloadAmount() { return this.reloadAmount; } /** * @return The amount of recoil this gun produces upon firing in degrees */ public float getRecoilAngle() { return this.recoilAngle; } /** * @return A radian that recoil may offset from vertical */ public float getRecoilRadian() { return this.recoilRadian; } /** * @return The amount of recoil ticks */ public float getRecoilDuration() { return this.recoilDuration; } /** * @return The amount of kick this gun produces upon firing */ public float getRecoilKick() { return this.recoilKick; } /** * @return The duration offset for recoil. This reduces the duration of recoil animation */ public float getRecoilDurationOffset() { return this.recoilDurationOffset; } /** * @return The amount of recoil reduction applied when aiming down this weapon's sight */ public float getRecoilAdsReduction() { return this.recoilAdsReduction; } /** * @return The amount of projectiles this weapon fires */ public int getProjectileAmount() { return this.projectileAmount; } /** * @return The count of projectiles this weapon fires at a strike */ public int getProjectileBurst() { return this.projectileBurst; } /** * @return If this weapon should always spread it's projectiles according to {@link #getSpread()} */ public boolean isAlwaysSpread() { return this.alwaysSpread; } /** * @return The maximum amount of degrees applied to the initial pitch and yaw direction of * the fired projectile. */ public float getSpread() { return this.spread; } /** * @return The amount of spread reduction allpied when aiming down this weapon's sight */ public float getSpreadAdsReduction() { return this.spreadAdsReduction; } } public static class Projectile implements INBTSerializable<CompoundTag> {
private ResourceLocation item = new ResourceLocation(Reference.MOD_ID, "basic_ammo");
1
2023-12-18 15:04:35+00:00
12k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/sub/AppPicker.java
[ { "identifier": "IAppSelectCallback", "path": "app/src/main/java/com/sevtinge/hyperceiler/callback/IAppSelectCallback.java", "snippet": "public interface IAppSelectCallback {\n\n void sendMsgToActivity(byte[] appIcon, String appName, String appPackageName, String appVersion, String appActivityName);\...
import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import androidx.fragment.app.Fragment; import com.sevtinge.hyperceiler.R; import com.sevtinge.hyperceiler.callback.IAppSelectCallback; import com.sevtinge.hyperceiler.callback.IEditCallback; import com.sevtinge.hyperceiler.data.AppData; import com.sevtinge.hyperceiler.data.adapter.AppDataAdapter; import com.sevtinge.hyperceiler.utils.BitmapUtils; import com.sevtinge.hyperceiler.utils.PackageManagerUtils; import com.sevtinge.hyperceiler.utils.PrefsUtils; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import moralnorm.appcompat.app.AlertDialog;
7,445
package com.sevtinge.hyperceiler.ui.fragment.sub; public class AppPicker extends Fragment { private Bundle args; private String TAG = "AppPicker"; private String key = null; private boolean appSelector; private int modeSelection; private View mRootView; private ProgressBar mAmProgress; private ListView mAppListRv; private AppDataAdapter mAppListAdapter; private List<AppData> appDataList; public Handler mHandler; private Set<String> selectedApps; private IAppSelectCallback mAppSelectCallback; public static IEditCallback iEditCallback; public void setAppSelectCallback(IAppSelectCallback callback) { mAppSelectCallback = callback; } public interface EditDialogCallback { void onInputReceived(String userInput); } public static void setEditCallback(IEditCallback editCallback) { iEditCallback = editCallback; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_app_picker, container, false); initView(); return mRootView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requireActivity().setTitle(R.string.array_global_actions_launch_choose); args = requireActivity().getIntent().getExtras(); assert args != null; appSelector = args.getBoolean("is_app_selector"); modeSelection = args.getInt("need_mode"); if (appSelector) { if (modeSelection == 3) { key = args.getString("key"); } else key = args.getString("app_selector_key"); } else { key = args.getString("key"); } mHandler = new Handler(); initData(); } private void initView() { mAmProgress = mRootView.findViewById(R.id.am_progressBar); mAppListRv = mRootView.findViewById(R.id.app_list_rv); mAppListRv.setVisibility(View.GONE); mAppListRv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AppData appData = getAppInfo().get((int) id); // Log.e(TAG, "onItemClick: " + appData.packageName, null); switch (modeSelection) { case 1 -> {
package com.sevtinge.hyperceiler.ui.fragment.sub; public class AppPicker extends Fragment { private Bundle args; private String TAG = "AppPicker"; private String key = null; private boolean appSelector; private int modeSelection; private View mRootView; private ProgressBar mAmProgress; private ListView mAppListRv; private AppDataAdapter mAppListAdapter; private List<AppData> appDataList; public Handler mHandler; private Set<String> selectedApps; private IAppSelectCallback mAppSelectCallback; public static IEditCallback iEditCallback; public void setAppSelectCallback(IAppSelectCallback callback) { mAppSelectCallback = callback; } public interface EditDialogCallback { void onInputReceived(String userInput); } public static void setEditCallback(IEditCallback editCallback) { iEditCallback = editCallback; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_app_picker, container, false); initView(); return mRootView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requireActivity().setTitle(R.string.array_global_actions_launch_choose); args = requireActivity().getIntent().getExtras(); assert args != null; appSelector = args.getBoolean("is_app_selector"); modeSelection = args.getInt("need_mode"); if (appSelector) { if (modeSelection == 3) { key = args.getString("key"); } else key = args.getString("app_selector_key"); } else { key = args.getString("key"); } mHandler = new Handler(); initData(); } private void initView() { mAmProgress = mRootView.findViewById(R.id.am_progressBar); mAppListRv = mRootView.findViewById(R.id.app_list_rv); mAppListRv.setVisibility(View.GONE); mAppListRv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AppData appData = getAppInfo().get((int) id); // Log.e(TAG, "onItemClick: " + appData.packageName, null); switch (modeSelection) { case 1 -> {
mAppSelectCallback.sendMsgToActivity(BitmapUtils.Bitmap2Bytes(appData.icon),
4
2023-10-27 17:17:42+00:00
12k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controls/MyTableView.java
[ { "identifier": "TableBean", "path": "src/main/java/org/fofaviewer/bean/TableBean.java", "snippet": "public class TableBean extends BaseBean{\n public SimpleIntegerProperty num = new SimpleIntegerProperty();\n public SimpleStringProperty host = new SimpleStringProperty();\n public SimpleStringP...
import javafx.beans.binding.Bindings; import javafx.collections.ObservableList; import javafx.scene.control.*; import javafx.scene.control.MenuItem; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import org.fofaviewer.bean.TableBean; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.fofaviewer.utils.ResourceBundleUtil; import org.tinylog.Logger; import java.awt.*; import java.io.IOException; import java.net.URI; import java.util.*;
8,134
package org.fofaviewer.controls; /** * TableView装饰类 */ public class MyTableView { private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
package org.fofaviewer.controls; /** * TableView装饰类 */ public class MyTableView { private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private final RequestUtil helper = RequestUtil.getInstance();
3
2023-10-25 11:13:47+00:00
12k