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 |
|---|---|---|---|---|---|---|---|---|---|---|
jpdev01/asaasSdk | src/main/java/io/github/jpdev/asaassdk/rest/payment/identificationfield/PaymentIdentificationFieldFetcher.java | [
{
"identifier": "Domain",
"path": "src/main/java/io/github/jpdev/asaassdk/http/Domain.java",
"snippet": "public enum Domain {\n\n TRANSFER(\"transfers\"),\n PAYMENT(\"payments\"),\n REFUND_PAYMENT(\"payments/$id/refund\"),\n PIX_TRANSACTION(\"pix/transactions\"),\n PIX_TRANSACTION_CANCELL... | import io.github.jpdev.asaassdk.http.Domain;
import io.github.jpdev.asaassdk.rest.action.Fetcher; | 663 | package io.github.jpdev.asaassdk.rest.payment.identificationfield;
public class PaymentIdentificationFieldFetcher extends Fetcher<PaymentIdentificationField> {
final String id;
public PaymentIdentificationFieldFetcher(String id) {
this.id = id;
}
@Override
public String getResourceUrl() { | package io.github.jpdev.asaassdk.rest.payment.identificationfield;
public class PaymentIdentificationFieldFetcher extends Fetcher<PaymentIdentificationField> {
final String id;
public PaymentIdentificationFieldFetcher(String id) {
this.id = id;
}
@Override
public String getResourceUrl() { | return Domain.PAYMENT.addVariableList(this.id, "identificationField"); | 0 | 2023-11-12 01:19:17+00:00 | 2k |
GoldenStack/minestom-ca | src/main/java/dev/goldenstack/minestom_ca/parser/Parser.java | [
{
"identifier": "Token",
"path": "src/main/java/dev/goldenstack/minestom_ca/parser/Scanner.java",
"snippet": "public sealed interface Token {\r\n record Identifier(String value) implements Token {\r\n }\r\n\r\n record Constant(String value) implements Token {\r\n }\r\n\r\n record Number(l... | import dev.goldenstack.minestom_ca.Program;
import dev.goldenstack.minestom_ca.Rule;
import dev.goldenstack.minestom_ca.parser.Scanner.Token;
import net.minestom.server.coordinate.Point;
import net.minestom.server.instance.block.Block;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static dev.goldenstack.minestom_ca.Neighbors.NAMED;
| 1,272 | package dev.goldenstack.minestom_ca.parser;
public final class Parser {
private int line;
private List<Token> tokens;
private int index;
private final AtomicInteger stateCounter = new AtomicInteger(0);
private final Map<String, Integer> properties = new HashMap<>();
private final List<Rule> rules = new ArrayList<>();
public Parser() {
}
public void feedTokens(List<Token> tokens) {
this.line++;
this.tokens = tokens;
this.index = 0;
while (!isAtEnd()) {
List<Rule.Condition> conditions = new ArrayList<>();
List<Rule.Result> results = new ArrayList<>();
while (!(peek() instanceof Token.Arrow)) {
conditions.add(nextCondition());
if (peek() instanceof Token.And) advance();
}
consume(Token.Arrow.class, "Expected '->'");
while (!(peek() instanceof Token.EOF)) results.add(nextResult());
this.rules.add(new Rule(conditions.size() == 1 ? conditions.get(0) :
new Rule.Condition.And(conditions), results));
}
}
private Rule.Condition nextCondition() {
CountPredicate countPredicate = new CountPredicate(1, false, false, 0);
if (peek() instanceof Token.LeftBracket) {
countPredicate = nextCountPredicate();
}
if (peek() instanceof Token.Constant) {
// Self block check
final Block block = nextBlock();
return new Rule.Condition.Equal(block);
} else if (peek() instanceof Token.Exclamation) {
// Self block check not
advance();
final Token.Constant constant = consume(Token.Constant.class, "Expected constant");
final Block block = Block.fromNamespaceId(constant.value());
if (block == null) throw error("Unknown block " + constant.value());
return new Rule.Condition.Not(new Rule.Condition.Equal(block));
} else if (peek() instanceof Token.Identifier identifier) {
advance();
if (!(peek() instanceof Token.At)) {
// Self identifier
final int index = getIndex(identifier.value());
return switch (advance()) {
case Token.Equals ignored -> new Rule.Condition.Equal(
new Rule.Expression.Index(index),
nextExpression()
);
case Token.Exclamation ignored -> new Rule.Condition.Not(
new Rule.Condition.Equal(
new Rule.Expression.Index(index),
nextExpression()
));
default -> throw error("Expected operator");
};
} else {
// Neighbor block check
consume(Token.At.class, "Expected '@'");
| package dev.goldenstack.minestom_ca.parser;
public final class Parser {
private int line;
private List<Token> tokens;
private int index;
private final AtomicInteger stateCounter = new AtomicInteger(0);
private final Map<String, Integer> properties = new HashMap<>();
private final List<Rule> rules = new ArrayList<>();
public Parser() {
}
public void feedTokens(List<Token> tokens) {
this.line++;
this.tokens = tokens;
this.index = 0;
while (!isAtEnd()) {
List<Rule.Condition> conditions = new ArrayList<>();
List<Rule.Result> results = new ArrayList<>();
while (!(peek() instanceof Token.Arrow)) {
conditions.add(nextCondition());
if (peek() instanceof Token.And) advance();
}
consume(Token.Arrow.class, "Expected '->'");
while (!(peek() instanceof Token.EOF)) results.add(nextResult());
this.rules.add(new Rule(conditions.size() == 1 ? conditions.get(0) :
new Rule.Condition.And(conditions), results));
}
}
private Rule.Condition nextCondition() {
CountPredicate countPredicate = new CountPredicate(1, false, false, 0);
if (peek() instanceof Token.LeftBracket) {
countPredicate = nextCountPredicate();
}
if (peek() instanceof Token.Constant) {
// Self block check
final Block block = nextBlock();
return new Rule.Condition.Equal(block);
} else if (peek() instanceof Token.Exclamation) {
// Self block check not
advance();
final Token.Constant constant = consume(Token.Constant.class, "Expected constant");
final Block block = Block.fromNamespaceId(constant.value());
if (block == null) throw error("Unknown block " + constant.value());
return new Rule.Condition.Not(new Rule.Condition.Equal(block));
} else if (peek() instanceof Token.Identifier identifier) {
advance();
if (!(peek() instanceof Token.At)) {
// Self identifier
final int index = getIndex(identifier.value());
return switch (advance()) {
case Token.Equals ignored -> new Rule.Condition.Equal(
new Rule.Expression.Index(index),
nextExpression()
);
case Token.Exclamation ignored -> new Rule.Condition.Not(
new Rule.Condition.Equal(
new Rule.Expression.Index(index),
nextExpression()
));
default -> throw error("Expected operator");
};
} else {
// Neighbor block check
consume(Token.At.class, "Expected '@'");
| final List<Point> targets = NAMED.get(identifier.value());
| 1 | 2023-11-18 21:49:11+00:00 | 2k |
spring-projects/spring-rewrite-commons | spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/RewriteParserConfiguration.java | [
{
"identifier": "ScopeConfiguration",
"path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/ScopeConfiguration.java",
"snippet": "@AutoConfiguration\npublic class ScopeConfiguration {\n\n\t@Bean\n\tExecutionScope executionScope() {\n\t\treturn new Executio... | import org.openrewrite.ExecutionContext;
import org.openrewrite.maven.cache.CompositeMavenPomCache;
import org.openrewrite.maven.cache.InMemoryMavenPomCache;
import org.openrewrite.maven.cache.MavenPomCache;
import org.openrewrite.maven.cache.RocksdbMavenPomCache;
import org.openrewrite.maven.utilities.MavenArtifactDownloader;
import org.openrewrite.tree.ParsingEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ResourceLoader;
import org.springframework.rewrite.boot.autoconfigure.ScopeConfiguration;
import org.springframework.rewrite.parsers.events.RewriteParsingEventListenerAdapter;
import org.springframework.rewrite.parsers.maven.*;
import org.springframework.rewrite.scopes.annotations.ScanScope;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.function.Consumer; | 1,364 | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.rewrite.parsers;
/**
* Module configuration.
*
* @author Fabian Krüger
*/
@AutoConfiguration(after = { ScopeConfiguration.class })
@EnableConfigurationProperties({ SpringRewriteProperties.class })
@Import({ org.springframework.rewrite.scopes.ScanScope.class, ScopeConfiguration.class,
RewriteParserMavenConfiguration.class })
public class RewriteParserConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(RewriteParserConfiguration.class);
@Bean
ProjectScanner projectScanner(ResourceLoader resourceLoader, SpringRewriteProperties springRewriteProperties) {
return new ProjectScanner(resourceLoader, springRewriteProperties);
}
@Bean
ProvenanceMarkerFactory provenanceMarkerFactory(MavenProvenanceMarkerFactory mavenPovenanceMarkerFactory) {
return new ProvenanceMarkerFactory(mavenPovenanceMarkerFactory);
}
@Bean
@ScanScope
JavaParserBuilder javaParserBuilder() {
return new JavaParserBuilder();
}
@Bean
Consumer<Throwable> artifactDownloaderErrorConsumer() {
return (t) -> {
throw new RuntimeException(t);
};
}
@Bean
MavenModuleParser mavenModuleParser(SpringRewriteProperties springRewriteProperties) {
return new MavenModuleParser(springRewriteProperties);
}
@Bean
SourceFileParser sourceFileParser(MavenModuleParser mavenModuleParser) {
return new SourceFileParser(mavenModuleParser);
}
@Bean
StyleDetector styleDetector() {
return new StyleDetector();
}
@Bean
@ConditionalOnMissingBean(ParsingEventListener.class)
ParsingEventListener parsingEventListener(ApplicationEventPublisher eventPublisher) { | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.rewrite.parsers;
/**
* Module configuration.
*
* @author Fabian Krüger
*/
@AutoConfiguration(after = { ScopeConfiguration.class })
@EnableConfigurationProperties({ SpringRewriteProperties.class })
@Import({ org.springframework.rewrite.scopes.ScanScope.class, ScopeConfiguration.class,
RewriteParserMavenConfiguration.class })
public class RewriteParserConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(RewriteParserConfiguration.class);
@Bean
ProjectScanner projectScanner(ResourceLoader resourceLoader, SpringRewriteProperties springRewriteProperties) {
return new ProjectScanner(resourceLoader, springRewriteProperties);
}
@Bean
ProvenanceMarkerFactory provenanceMarkerFactory(MavenProvenanceMarkerFactory mavenPovenanceMarkerFactory) {
return new ProvenanceMarkerFactory(mavenPovenanceMarkerFactory);
}
@Bean
@ScanScope
JavaParserBuilder javaParserBuilder() {
return new JavaParserBuilder();
}
@Bean
Consumer<Throwable> artifactDownloaderErrorConsumer() {
return (t) -> {
throw new RuntimeException(t);
};
}
@Bean
MavenModuleParser mavenModuleParser(SpringRewriteProperties springRewriteProperties) {
return new MavenModuleParser(springRewriteProperties);
}
@Bean
SourceFileParser sourceFileParser(MavenModuleParser mavenModuleParser) {
return new SourceFileParser(mavenModuleParser);
}
@Bean
StyleDetector styleDetector() {
return new StyleDetector();
}
@Bean
@ConditionalOnMissingBean(ParsingEventListener.class)
ParsingEventListener parsingEventListener(ApplicationEventPublisher eventPublisher) { | return new RewriteParsingEventListenerAdapter(eventPublisher); | 1 | 2023-11-14 23:02:37+00:00 | 2k |
giftorg/gift | gift-backed/src/main/java/org/giftorg/backed/controller/ProjectController.java | [
{
"identifier": "Response",
"path": "gift-backed/src/main/java/org/giftorg/backed/entity/Response.java",
"snippet": "@Data\npublic class Response {\n private Integer code;\n private String msg;\n private Object data;\n\n public Response() {\n }\n\n public Response(Object data) {\n ... | import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.giftorg.backed.entity.Response;
import org.giftorg.backed.entity.repository.Project;
import org.giftorg.backed.entity.repository.Repository;
import org.giftorg.backed.entity.vo.FunctionVo;
import org.giftorg.backed.service.ChatService;
import org.giftorg.backed.service.CodeService;
import org.giftorg.backed.service.RepositoryService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; | 1,343 | /**
* Copyright 2023 GiftOrg Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.giftorg.backed.controller;
@RestController
@RequestMapping("/api")
@Slf4j
public class ProjectController {
@Resource
private CodeService codeService;
@Resource
private ChatService chatService;
@Resource
private RepositoryService repositoryService;
@GetMapping("/recommend")
public Response recommend() {
// TODO 根据关键字(语言?)来推荐项目列表 返回一个项目列表对象 Project
return new Response();
}
@GetMapping("/search/project")
public Response searchProject(@RequestParam String query) {
log.info("search project query: {}", query);
List<Repository> repositories = null;
try {
repositories = repositoryService.searchRepository(query);
} catch (Exception e) {
log.error("search project failed: {}", e.getMessage(), e);
return new Response(1, "search project failed");
}
return new Response(repositories);
}
@GetMapping("/search/code")
public Response searchCode(@RequestParam String query) { | /**
* Copyright 2023 GiftOrg Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.giftorg.backed.controller;
@RestController
@RequestMapping("/api")
@Slf4j
public class ProjectController {
@Resource
private CodeService codeService;
@Resource
private ChatService chatService;
@Resource
private RepositoryService repositoryService;
@GetMapping("/recommend")
public Response recommend() {
// TODO 根据关键字(语言?)来推荐项目列表 返回一个项目列表对象 Project
return new Response();
}
@GetMapping("/search/project")
public Response searchProject(@RequestParam String query) {
log.info("search project query: {}", query);
List<Repository> repositories = null;
try {
repositories = repositoryService.searchRepository(query);
} catch (Exception e) {
log.error("search project failed: {}", e.getMessage(), e);
return new Response(1, "search project failed");
}
return new Response(repositories);
}
@GetMapping("/search/code")
public Response searchCode(@RequestParam String query) { | List<FunctionVo> functionVos = codeService.searchCode(query); | 3 | 2023-11-15 08:58:35+00:00 | 2k |
exadel-inc/etoolbox-anydiff | core/src/test/java/com/exadel/etoolbox/anydiff/comparison/MarkedStringTest.java | [
{
"identifier": "OutputType",
"path": "core/src/main/java/com/exadel/etoolbox/anydiff/OutputType.java",
"snippet": "public enum OutputType {\n CONSOLE, LOG, HTML\n}"
},
{
"identifier": "Fragment",
"path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Fragment.java",
"snippet": ... | import com.exadel.etoolbox.anydiff.OutputType;
import com.exadel.etoolbox.anydiff.diff.Fragment;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | 752 | /*
* 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.exadel.etoolbox.anydiff.comparison;
public class MarkedStringTest {
private static final String DEFAULT_TEXT = "Lorem ipsum";
private static final String MARKED_TEXT_1 = "{{eq}} Lorem ipsum{{/}}";
private static final String MARKED_TEXT_2 = "{{del}}Lorem{{/}} {{ins}}ipsum{{/}}";
private static final int DEFAULT_COLUMN = 60;
private static final String DELETE_STRING = Marker.DELETE.toConsole();
private static final String INSERT_STRING = Marker.INSERT.toConsole();
private static final String RESET_STRING = Marker.RESET.toConsole();
@Test
public void shouldParseSimpleText() {
MarkedString side = new MarkedString(DEFAULT_TEXT, false);
Assert.assertEquals(DEFAULT_TEXT, side.toString()); | /*
* 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.exadel.etoolbox.anydiff.comparison;
public class MarkedStringTest {
private static final String DEFAULT_TEXT = "Lorem ipsum";
private static final String MARKED_TEXT_1 = "{{eq}} Lorem ipsum{{/}}";
private static final String MARKED_TEXT_2 = "{{del}}Lorem{{/}} {{ins}}ipsum{{/}}";
private static final int DEFAULT_COLUMN = 60;
private static final String DELETE_STRING = Marker.DELETE.toConsole();
private static final String INSERT_STRING = Marker.INSERT.toConsole();
private static final String RESET_STRING = Marker.RESET.toConsole();
@Test
public void shouldParseSimpleText() {
MarkedString side = new MarkedString(DEFAULT_TEXT, false);
Assert.assertEquals(DEFAULT_TEXT, side.toString()); | Assert.assertEquals(DEFAULT_TEXT, stripEnd(side.toText(OutputType.CONSOLE, DEFAULT_COLUMN).get(0))); | 0 | 2023-11-16 14:29:45+00:00 | 2k |
jimbro1000/DriveWire4Rebuild | src/test/java/org/thelair/dw4/drivewire/ports/DWPortManagerTest.java | [
{
"identifier": "DWSerialPort",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/DWSerialPort.java",
"snippet": "public final class DWSerialPort implements DWIPort {\n /**\n * Log appender.\n */\n private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class);\n /**\n ... | import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.thelair.dw4.drivewire.ports.serial.DWSerialPort;
import org.thelair.dw4.drivewire.ports.tcp.DWTcpPort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail; | 1,426 | package org.thelair.dw4.drivewire.ports;
/**
* Describes drivewire port manager.
*/
public class DWPortManagerTest {
private DWIPortManager portManager;
/**
* Prepare port manager for tests.
*/
@BeforeEach
public void setup() {
portManager = new DWPortManager();
}
/**
* It should generate null ports when required.
*/
@Test
public void itShouldReturnANullPortOnRequest() {
DWIPort actual =
portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.NULL_PORT);
assertEquals(DWNullPort.class, actual.getClass(), "it should provide a " +
"null port");
}
/**
* It should generate serial ports when required.
*/
@Test
public void itShouldReturnASerialPortOnRequest() {
DWIPort actual =
portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.SERIAL_PORT); | package org.thelair.dw4.drivewire.ports;
/**
* Describes drivewire port manager.
*/
public class DWPortManagerTest {
private DWIPortManager portManager;
/**
* Prepare port manager for tests.
*/
@BeforeEach
public void setup() {
portManager = new DWPortManager();
}
/**
* It should generate null ports when required.
*/
@Test
public void itShouldReturnANullPortOnRequest() {
DWIPort actual =
portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.NULL_PORT);
assertEquals(DWNullPort.class, actual.getClass(), "it should provide a " +
"null port");
}
/**
* It should generate serial ports when required.
*/
@Test
public void itShouldReturnASerialPortOnRequest() {
DWIPort actual =
portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.SERIAL_PORT); | assertEquals(DWSerialPort.class, actual.getClass(), "it should provide a " + | 0 | 2023-11-18 11:35:16+00:00 | 2k |
JustARandomGuyNo512/Gunscraft | src/main/java/sheridan/gunscraft/items/attachments/GenericMag.java | [
{
"identifier": "GunRenderContext",
"path": "src/main/java/sheridan/gunscraft/items/attachments/util/GunRenderContext.java",
"snippet": "public class GunRenderContext {\n public boolean occupiedStock = false;\n public boolean occupiedIS = false;\n public boolean occupiedMag = false;\n public... | import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import sheridan.gunscraft.items.attachments.util.GunRenderContext;
import sheridan.gunscraft.items.guns.IGenericGun; | 702 | package sheridan.gunscraft.items.attachments;
public class GenericMag extends GenericAttachment{
public int ammoIncrement;
public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) {
super(properties, id, type, name);
this.ammoIncrement = ammoIncrement;
}
@Override
public void onAttach(ItemStack stack, IGenericGun gun) {
gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement);
}
@Override
public void onOff(ItemStack stack, IGenericGun gun) {
gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement);
int ammoDec = gun.getAmmoLeft(stack);
ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0;
gun.setAmmoLeft(stack, ammoDec);
}
@Override | package sheridan.gunscraft.items.attachments;
public class GenericMag extends GenericAttachment{
public int ammoIncrement;
public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) {
super(properties, id, type, name);
this.ammoIncrement = ammoIncrement;
}
@Override
public void onAttach(ItemStack stack, IGenericGun gun) {
gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement);
}
@Override
public void onOff(ItemStack stack, IGenericGun gun) {
gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement);
int ammoDec = gun.getAmmoLeft(stack);
ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0;
gun.setAmmoLeft(stack, ammoDec);
}
@Override | public void handleParams(GunRenderContext params) { | 0 | 2023-11-14 14:00:55+00:00 | 2k |
zpascual/5419-Arm-Example | src/main/java/com/team5419/frc2023/subsystems/Intake.java | [
{
"identifier": "Ports",
"path": "src/main/java/com/team5419/frc2023/Ports.java",
"snippet": "public class Ports {\n\n public static int kArm = 1;\n public static int kWrist = 2;\n public static int kIntake = 3;\n\n public static int kDriver = 0;\n public static int kOperator = 1;\n\n}"
... | import com.ctre.phoenix6.hardware.TalonFX;
import com.team5419.frc2023.Ports;
import com.team5419.frc2023.loops.ILooper;
import com.team5419.frc2023.loops.Loop;
import com.team5419.lib.requests.Request;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; | 748 | package com.team5419.frc2023.subsystems;
public class Intake extends Subsystem {
public static Intake mInstance = null;
public static Intake getInstance() {
if (mInstance == null) {
return mInstance = new Intake();
}
return mInstance;
}
protected final TalonFX motor = new TalonFX(Ports.kIntake);
public Intake() {
}
public enum State {
IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0);
public final double voltage;
State (double voltage) {
this.voltage = voltage;
}
}
private State currentState = State.IDLE;
public State getState() {
return currentState;
}
public void setState(State wantedState) {
if (currentState != wantedState) {
currentState = wantedState;
}
}
@Override
public void registerEnabledLoops(ILooper mEnabledLooper) { | package com.team5419.frc2023.subsystems;
public class Intake extends Subsystem {
public static Intake mInstance = null;
public static Intake getInstance() {
if (mInstance == null) {
return mInstance = new Intake();
}
return mInstance;
}
protected final TalonFX motor = new TalonFX(Ports.kIntake);
public Intake() {
}
public enum State {
IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0);
public final double voltage;
State (double voltage) {
this.voltage = voltage;
}
}
private State currentState = State.IDLE;
public State getState() {
return currentState;
}
public void setState(State wantedState) {
if (currentState != wantedState) {
currentState = wantedState;
}
}
@Override
public void registerEnabledLoops(ILooper mEnabledLooper) { | mEnabledLooper.register(new Loop() { | 2 | 2023-11-14 06:44:40+00:00 | 2k |
Ouest-France/querydsl-postgrest | src/main/java/fr/ouestfrance/querydsl/postgrest/mappers/NotInMapper.java | [
{
"identifier": "Filter",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Filter.java",
"snippet": "public interface Filter extends FilterVisitor {\n\n /**\n * Get the filter key\n * @return filter key\n */\n String getKey();\n\n}"
},
{
"identifier": "PostgrestRe... | import java.util.Collection;
import java.util.stream.Collectors;
import fr.ouestfrance.querydsl.FilterOperation;
import fr.ouestfrance.querydsl.postgrest.model.Filter;
import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException;
import fr.ouestfrance.querydsl.postgrest.model.impl.QueryFilter; | 783 | package fr.ouestfrance.querydsl.postgrest.mappers;
/**
* Concrete mapping for notIn
*/
public class NotInMapper extends AbstractMapper {
@Override | package fr.ouestfrance.querydsl.postgrest.mappers;
/**
* Concrete mapping for notIn
*/
public class NotInMapper extends AbstractMapper {
@Override | public Filter getFilter(String field, Object value) { | 0 | 2023-11-14 10:45:54+00:00 | 2k |
threethan/QuestAudioPatcher | app/src/main/java/com/threethan/questpatcher/fragments/AboutFragment.java | [
{
"identifier": "AboutAdapter",
"path": "app/src/main/java/com/threethan/questpatcher/adapters/AboutAdapter.java",
"snippet": "public class AboutAdapter extends RecyclerView.Adapter<AboutAdapter.ViewHolder> {\n\n private static List<sSerializableItems> data;\n\n public AboutAdapter(List<sSerializa... | import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.threethan.questpatcher.BuildConfig;
import com.threethan.questpatcher.R;
import com.threethan.questpatcher.adapters.AboutAdapter;
import com.threethan.questpatcher.utils.APKEditorUtils;
import java.util.ArrayList;
import java.util.List;
import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils;
import in.sunilpaulmathew.sCommon.CommonUtils.sSerializableItems; | 1,527 | package com.threethan.questpatcher.fragments;
/*
* Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021
*/
public class AboutFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View mRootView = inflater.inflate(R.layout.fragment_about, container, false);
RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), sCommonUtils.getOrientation(requireActivity()) == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2)); | package com.threethan.questpatcher.fragments;
/*
* Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021
*/
public class AboutFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View mRootView = inflater.inflate(R.layout.fragment_about, container, false);
RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), sCommonUtils.getOrientation(requireActivity()) == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2)); | AboutAdapter mRecycleViewAdapter = new AboutAdapter(getData()); | 0 | 2023-11-18 15:13:30+00:00 | 2k |
jenkinsci/harbor-plugin | src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookStep.java | [
{
"identifier": "Severity",
"path": "src/main/java/io/jenkins/plugins/harbor/client/models/Severity.java",
"snippet": "public enum Severity {\n None(\"None\"),\n Unknown(\"Unknown\"),\n Negligible(\"Negligible\"),\n Low(\"Low\"),\n Medium(\"Medium\"),\n High(\"High\"),\n Critical(\"... | import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials;
import com.google.common.collect.ImmutableSet;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Item;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.security.ACL;
import hudson.util.ListBoxModel;
import io.jenkins.plugins.harbor.client.models.Severity;
import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration;
import io.jenkins.plugins.harbor.configuration.HarborServer;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import org.jenkinsci.plugins.workflow.steps.Step;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepDescriptor;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter; | 1,596 | package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookStep extends Step implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName());
private String server;
private String credentialsId;
private String fullImageName; | package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookStep extends Step implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName());
private String server;
private String credentialsId;
private String fullImageName; | private Severity severity; | 0 | 2023-11-11 14:54:53+00:00 | 2k |
wangxianhui111/xuechengzaixian | xuecheng-plus-generator/src/main/java/com/xuecheng/content/service/impl/TeachplanServiceImpl.java | [
{
"identifier": "Teachplan",
"path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/Teachplan.java",
"snippet": "@Data\n@TableName(\"teachplan\")\npublic class Teachplan implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n ... | import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired; | 1,141 | package com.xuecheng.content.service.impl;
/**
* <p>
* 课程计划 服务实现类
* </p>
*
* @author itcast
*/
@Slf4j
@Service | package com.xuecheng.content.service.impl;
/**
* <p>
* 课程计划 服务实现类
* </p>
*
* @author itcast
*/
@Slf4j
@Service | public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService { | 1 | 2023-11-13 11:39:35+00:00 | 2k |
dynatrace-research/ShuffleBench | shuffle-flink/src/main/java/com/dynatrace/research/shufflebench/AggregateFunction.java | [
{
"identifier": "ConsumerEvent",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/ConsumerEvent.java",
"snippet": "public class ConsumerEvent {\n private byte[] data;\n\n public ConsumerEvent() {\n }\n\n public ConsumerEvent(byte[] data) {\n this.data = data;\n }\n\n ... | import com.dynatrace.research.shufflebench.consumer.ConsumerEvent;
import com.dynatrace.research.shufflebench.consumer.ConsumerResult;
import com.dynatrace.research.shufflebench.consumer.State;
import com.dynatrace.research.shufflebench.consumer.StatefulConsumer;
import com.dynatrace.research.shufflebench.record.TimestampedRecord;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector; | 830 | package com.dynatrace.research.shufflebench;
public class AggregateFunction
extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> {
| package com.dynatrace.research.shufflebench;
public class AggregateFunction
extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> {
| private final StatefulConsumer consumer; | 3 | 2023-11-17 08:53:15+00:00 | 2k |
KafeinDev/InteractiveNpcs | src/main/java/dev/kafein/interactivenpcs/command/CommandAdapter.java | [
{
"identifier": "RegisteredTabCompletion",
"path": "src/main/java/dev/kafein/interactivenpcs/command/completion/RegisteredTabCompletion.java",
"snippet": "public final class RegisteredTabCompletion {\n private final int index;\n private final TabCompletion tabCompletion;\n\n public RegisteredTa... | import java.util.Arrays;
import java.util.List;
import com.google.common.collect.ImmutableList;
import dev.kafein.interactivenpcs.command.completion.RegisteredTabCompletion;
import dev.kafein.interactivenpcs.command.completion.TabCompletion;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import org.jetbrains.annotations.NotNull; | 1,201 | /*
* MIT License
*
* Copyright (c) 2023 Kafein
*
* 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 dev.kafein.interactivenpcs.command;
final class CommandAdapter extends BukkitCommand {
private final Command command;
CommandAdapter(Command command) {
super(command.getName(), command.getDescription(), command.getUsage(), command.getAliases());
this.command = command;
}
@Override
public boolean execute(@NotNull org.bukkit.command.CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
if (!getAliases().contains(commandLabel)) {
return false;
}
if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) {
//TODO: Send message
return true;
}
if (args.length == 0) {
this.command.execute(sender, args);
} else {
Command subCommand = this.command.findSubCommand(args);
if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) {
//TODO: Send message
return true;
}
String[] subCommandArgs = Arrays.copyOfRange(args, this.command.findSubCommandIndex(args), args.length);
subCommand.execute(sender, subCommandArgs);
}
return true;
}
@Override
public @NotNull List<String> tabComplete(@NotNull org.bukkit.command.CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) {
return ImmutableList.of();
}
if (args.length == 0) {
return complete(this.command, sender, 0);
} else {
Command subCommand = this.command.findSubCommand(args);
if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) {
return ImmutableList.of();
}
int subCommandIndex = this.command.findSubCommandIndex(args);
return complete(subCommand, sender, (args.length - subCommandIndex) - 1);
}
}
private List<String> complete(@NotNull Command command, @NotNull CommandSender commandSender, int index) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (Command subCommand : command.getSubCommands()) {
builder.addAll(subCommand.getAliases());
}
for (RegisteredTabCompletion registeredTabCompletion : command.getTabCompletions(index)) { | /*
* MIT License
*
* Copyright (c) 2023 Kafein
*
* 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 dev.kafein.interactivenpcs.command;
final class CommandAdapter extends BukkitCommand {
private final Command command;
CommandAdapter(Command command) {
super(command.getName(), command.getDescription(), command.getUsage(), command.getAliases());
this.command = command;
}
@Override
public boolean execute(@NotNull org.bukkit.command.CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
if (!getAliases().contains(commandLabel)) {
return false;
}
if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) {
//TODO: Send message
return true;
}
if (args.length == 0) {
this.command.execute(sender, args);
} else {
Command subCommand = this.command.findSubCommand(args);
if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) {
//TODO: Send message
return true;
}
String[] subCommandArgs = Arrays.copyOfRange(args, this.command.findSubCommandIndex(args), args.length);
subCommand.execute(sender, subCommandArgs);
}
return true;
}
@Override
public @NotNull List<String> tabComplete(@NotNull org.bukkit.command.CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) {
return ImmutableList.of();
}
if (args.length == 0) {
return complete(this.command, sender, 0);
} else {
Command subCommand = this.command.findSubCommand(args);
if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) {
return ImmutableList.of();
}
int subCommandIndex = this.command.findSubCommandIndex(args);
return complete(subCommand, sender, (args.length - subCommandIndex) - 1);
}
}
private List<String> complete(@NotNull Command command, @NotNull CommandSender commandSender, int index) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (Command subCommand : command.getSubCommands()) {
builder.addAll(subCommand.getAliases());
}
for (RegisteredTabCompletion registeredTabCompletion : command.getTabCompletions(index)) { | TabCompletion tabCompletion = registeredTabCompletion.getTabCompletion(); | 1 | 2023-11-18 10:12:16+00:00 | 2k |
jensjeflensje/minecraft_typewriter | src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BarTypeWriterButtonComponent.java | [
{
"identifier": "TypewriterPlugin",
"path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java",
"snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin... | import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin;
import dev.jensderuiter.minecrafttypewriter.Util;
import lombok.Getter;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.SoundCategory;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List; | 986 | package dev.jensderuiter.minecrafttypewriter.typewriter.component.button;
public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {
private final double Y_VALUE = -0.15;
private ItemStack skull;
private List<ItemDisplay> skullDisplays;
private int amount;
@Getter
private Location location;
public BarTypeWriterButtonComponent(ItemStack skull, int amount) {
this.skull = skull;
this.amount = amount;
this.skullDisplays = new ArrayList<>();
}
@Override
public void setUp(Location location) {
this.location = location;
for (int i = 0; i < this.amount; i++) {
Location displayLocation = Util.getRotatedLocation(
location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0);
ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(
displayLocation, EntityType.ITEM_DISPLAY);
skullDisplay.setItemStack(this.skull);
Transformation skullTransformation = skullDisplay.getTransformation();
skullTransformation.getScale().set(0.2);
skullDisplay.setTransformation(skullTransformation);
this.skullDisplays.add(skullDisplay);
}
}
@Override
public void destroy() {
this.skullDisplays.forEach(Entity::remove);
}
/**
* Plays pressing animation.
*/
public void press() { | package dev.jensderuiter.minecrafttypewriter.typewriter.component.button;
public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {
private final double Y_VALUE = -0.15;
private ItemStack skull;
private List<ItemDisplay> skullDisplays;
private int amount;
@Getter
private Location location;
public BarTypeWriterButtonComponent(ItemStack skull, int amount) {
this.skull = skull;
this.amount = amount;
this.skullDisplays = new ArrayList<>();
}
@Override
public void setUp(Location location) {
this.location = location;
for (int i = 0; i < this.amount; i++) {
Location displayLocation = Util.getRotatedLocation(
location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0);
ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(
displayLocation, EntityType.ITEM_DISPLAY);
skullDisplay.setItemStack(this.skull);
Transformation skullTransformation = skullDisplay.getTransformation();
skullTransformation.getScale().set(0.2);
skullDisplay.setTransformation(skullTransformation);
this.skullDisplays.add(skullDisplay);
}
}
@Override
public void destroy() {
this.skullDisplays.forEach(Entity::remove);
}
/**
* Plays pressing animation.
*/
public void press() { | new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1); | 0 | 2023-11-18 20:44:30+00:00 | 2k |
Nurislom373/SpringMicroservice | Observability/Grafana/src/main/java/og/khasanof/grafana/factories/handler/DefaultObservationHandlerFactory.java | [
{
"identifier": "AbstractObservationHandler",
"path": "Observability/Grafana/src/main/java/og/khasanof/grafana/AbstractObservationHandler.java",
"snippet": "public abstract class AbstractObservationHandler implements IObservationHandler {\n\n private AbstractObservationHandler nextObservationHandler;... | import og.khasanof.grafana.AbstractObservationHandler;
import og.khasanof.grafana.IObservationHandler;
import og.khasanof.grafana.context.ResourceContext;
import og.khasanof.grafana.enumeration.ObserveType;
import og.khasanof.grafana.models.resource.Resource;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.Set; | 946 | package og.khasanof.grafana.factories.handler;
/**
* @author Nurislom
* @see og.khasanof.grafana.factories.handler
* @since 12/16/2023 11:50 AM
*/
@Component
public class DefaultObservationHandlerFactory implements ObservationHandlerFactory {
private final ResourceContext context;
public DefaultObservationHandlerFactory(ResourceContext context) {
this.context = context;
}
@Override | package og.khasanof.grafana.factories.handler;
/**
* @author Nurislom
* @see og.khasanof.grafana.factories.handler
* @since 12/16/2023 11:50 AM
*/
@Component
public class DefaultObservationHandlerFactory implements ObservationHandlerFactory {
private final ResourceContext context;
public DefaultObservationHandlerFactory(ResourceContext context) {
this.context = context;
}
@Override | public IObservationHandler create(Resource resource) { | 1 | 2023-11-18 07:57:34+00:00 | 2k |
ZhiQinIsZhen/dubbo-springboot3 | dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/service/impl/StaffLoginLogServiceImpl.java | [
{
"identifier": "Device",
"path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/enums/Device.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum Device {\n MOBILE(1, \"移动端\"),\n WEB(2, \"网页端\"),\n ;\n\n private final int type;\n private f... | import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyz.boot3.service.auth.enums.Device;
import com.liyz.boot3.service.staff.dao.StaffLoginLogMapper;
import com.liyz.boot3.service.staff.model.StaffLoginLogDO;
import com.liyz.boot3.service.staff.service.StaffLoginLogService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Date;
import java.util.Objects; | 788 | package com.liyz.boot3.service.staff.service.impl;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/6/15 14:02
*/
@Service
public class StaffLoginLogServiceImpl extends ServiceImpl<StaffLoginLogMapper, StaffLoginLogDO> implements StaffLoginLogService {
/**
* 获取上次登录时间
*
* @param staffId 员工ID
* @param device 设备类型
* @return 上次登录时间
*/
@Override | package com.liyz.boot3.service.staff.service.impl;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/6/15 14:02
*/
@Service
public class StaffLoginLogServiceImpl extends ServiceImpl<StaffLoginLogMapper, StaffLoginLogDO> implements StaffLoginLogService {
/**
* 获取上次登录时间
*
* @param staffId 员工ID
* @param device 设备类型
* @return 上次登录时间
*/
@Override | public Date lastLoginTime(Long staffId, Device device) { | 0 | 2023-11-13 01:28:21+00:00 | 2k |
glowingstone124/QAPI3 | src/main/java/org/qo/Main.java | [
{
"identifier": "BackupDatabase",
"path": "src/main/java/org/qo/server/BackupDatabase.java",
"snippet": "public class BackupDatabase extends TimerTask {\n public static String dbName = \"qouser\";\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyyMMdd_HHmmss\");\n String formattedDate... | import org.qo.server.BackupDatabase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import static org.qo.Logger.LogLevel.*; | 688 | package org.qo;
@SpringBootApplication
public class Main {
public static void main(String[] args) throws Exception {
Funcs.Start();
Logger.log("API Started.", INFO);
SpringApplication.run(ApiApplication.class, args);
Logger.startLogWriter("log.log", 3000);
Timer timer = new Timer(); | package org.qo;
@SpringBootApplication
public class Main {
public static void main(String[] args) throws Exception {
Funcs.Start();
Logger.log("API Started.", INFO);
SpringApplication.run(ApiApplication.class, args);
Logger.startLogWriter("log.log", 3000);
Timer timer = new Timer(); | TimerTask task = new BackupDatabase(); | 0 | 2023-11-15 13:38:53+00:00 | 2k |
RaniAgus/java-docker-tutorial | src/main/java/io/github/raniagus/example/Application.java | [
{
"identifier": "Bootstrap",
"path": "src/main/java/io/github/raniagus/example/bootstrap/Bootstrap.java",
"snippet": "public class Bootstrap implements Runnable, WithSimplePersistenceUnit {\n private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);\n\n public static void main(String... | import gg.jte.ContentType;
import gg.jte.TemplateEngine;
import gg.jte.output.StringOutput;
import gg.jte.resolve.DirectoryCodeResolver;
import io.github.flbulgarelli.jpa.extras.simple.WithSimplePersistenceUnit;
import io.github.raniagus.example.bootstrap.Bootstrap;
import io.github.raniagus.example.constants.Routes;
import io.github.raniagus.example.controller.ErrorController;
import io.github.raniagus.example.controller.HomeController;
import io.github.raniagus.example.controller.LoginController;
import io.github.raniagus.example.exception.ShouldLoginException;
import io.github.raniagus.example.exception.UserNotAuthorizedException;
import io.github.raniagus.example.model.Rol;
import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import java.nio.file.Path;
import java.time.LocalDate; | 1,444 | package io.github.raniagus.example;
public class Application {
public static final Config config = Config.create();
public static void main(String[] args) {
startDatabaseConnection();
if (config.databaseHbm2ddlAuto().equals("create-drop")) { | package io.github.raniagus.example;
public class Application {
public static final Config config = Config.create();
public static void main(String[] args) {
startDatabaseConnection();
if (config.databaseHbm2ddlAuto().equals("create-drop")) { | new Bootstrap().run(); | 0 | 2023-11-12 15:14:24+00:00 | 2k |
heldermartins4/RPG_Pokemon | src/main/java/interfaces/combat/Combat.java | [
{
"identifier": "Trainer",
"path": "src/main/java/controllers/combat/Trainer.java",
"snippet": "public class Trainer {\n \n private String nome;\n private int dinheiro;\n private Pokemon pokemon;\n private String character;\n\n public Trainer(String nome, String character) {\n t... | import java.awt.image.BufferedImage;
import controllers.combat.Trainer;
import interfaces.GamePanel; | 1,038 | package interfaces.combat;
public class Combat {
BufferedImage gui, playerPokemon, rivalPokemon, move1, move2, move3, move4;
Trainer player, rival; | package interfaces.combat;
public class Combat {
BufferedImage gui, playerPokemon, rivalPokemon, move1, move2, move3, move4;
Trainer player, rival; | GamePanel screen; | 1 | 2023-11-12 16:44:00+00:00 | 2k |
kigangka/iotdb-server | src/main/java/com/kit/iotdb/common/task/WeatherTask.java | [
{
"identifier": "WeatherClient",
"path": "src/main/java/com/kit/iotdb/common/client/WeatherClient.java",
"snippet": "public interface WeatherClient {\n\n /**\n * 根据城市代码获取城市天气情况\n */\n @Get(\"http://t.weather.itboy.net/api/weather/city/{0}\")\n JSONObject getCityWeatherInfo(Integer cityK... | import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.kit.iotdb.common.client.WeatherClient;
import com.kit.iotdb.entity.WeatherEntity;
import com.kit.iotdb.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource; | 657 | package com.kit.iotdb.common.task;
/**
* 添加说明
*
* @author kit
* @version 1.0
* @date 2023/11/10 10:25
*/
@Component
@Slf4j
public class WeatherTask {
@Resource
private WeatherClient weatherClient;
@Resource | package com.kit.iotdb.common.task;
/**
* 添加说明
*
* @author kit
* @version 1.0
* @date 2023/11/10 10:25
*/
@Component
@Slf4j
public class WeatherTask {
@Resource
private WeatherClient weatherClient;
@Resource | private WeatherService weatherService; | 2 | 2023-11-15 06:04:04+00:00 | 2k |
penyoofficial/HerbMS | src/main/java/com/penyo/herbms/controller/ExperienceController.java | [
{
"identifier": "Experience",
"path": "src/main/java/com/penyo/herbms/pojo/Experience.java",
"snippet": "public class Experience extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 中草药 ID(外键)\n */\n private int herbId;\n /**\n * 出处\n */\n private String derivation;\n... | import com.penyo.herbms.pojo.Experience;
import com.penyo.herbms.pojo.ReturnDataPack;
import com.penyo.herbms.service.ExperienceService;
import com.penyo.herbms.service.HerbService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | 1,525 | package com.penyo.herbms.controller;
/**
* 中草药使用心得的控制器代理
*
* @author Penyo
* @see Experience
* @see GenericController
*/
@Controller
public class ExperienceController extends GenericController<Experience> {
@Override
@RequestMapping("/use-experiences")
@ResponseBody
public String requestMain(HttpServletRequest request) {
return requestMain(toMap(request), getService(ExperienceService.class)).toString();
}
@Override
@RequestMapping("/use-experiences-specific")
@ResponseBody
public String requestSub(HttpServletRequest request) {
List<String> hs = new ArrayList<>();
ReturnDataPack<Experience> exps = requestMain(toMap(request), getService(ExperienceService.class));
for (Experience o : exps.getObjs()) {
StringBuilder hTemp = new StringBuilder("\""); | package com.penyo.herbms.controller;
/**
* 中草药使用心得的控制器代理
*
* @author Penyo
* @see Experience
* @see GenericController
*/
@Controller
public class ExperienceController extends GenericController<Experience> {
@Override
@RequestMapping("/use-experiences")
@ResponseBody
public String requestMain(HttpServletRequest request) {
return requestMain(toMap(request), getService(ExperienceService.class)).toString();
}
@Override
@RequestMapping("/use-experiences-specific")
@ResponseBody
public String requestSub(HttpServletRequest request) {
List<String> hs = new ArrayList<>();
ReturnDataPack<Experience> exps = requestMain(toMap(request), getService(ExperienceService.class));
for (Experience o : exps.getObjs()) {
StringBuilder hTemp = new StringBuilder("\""); | hTemp.append(getService(HerbService.class).selectNameByExperienceId(o.getId())); | 3 | 2023-11-13 16:40:05+00:00 | 2k |
martin-bian/DimpleBlog | dimple-system/src/main/java/com/dimple/modules/system/rest/DictController.java | [
{
"identifier": "BadRequestException",
"path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java",
"snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ... | import com.dimple.annotation.OLog;
import com.dimple.exception.BadRequestException;
import com.dimple.modules.system.domain.Dict;
import com.dimple.modules.system.service.DictService;
import com.dimple.modules.system.service.dto.DictQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set; | 1,159 | package com.dimple.modules.system.rest;
/**
* @className: DictController
* @description:
* @author: Dimple
* @date: 06/17/20
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统:字典管理")
@RequestMapping("/api/dict")
public class DictController {
private static final String ENTITY_NAME = "dict";
private final DictService dictService;
@OLog("导出字典数据")
@ApiOperation("导出字典数据")
@GetMapping(value = "/download")
@PreAuthorize("@ps.check('dict:list')")
public void download(HttpServletResponse response, DictQueryCriteria criteria) throws IOException {
dictService.download(dictService.queryAll(criteria), response);
}
@OLog("查询字典")
@ApiOperation("查询字典")
@GetMapping(value = "/all")
@PreAuthorize("@ps.check('dict:list')")
public ResponseEntity<Object> queryAll() {
return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()), HttpStatus.OK);
}
@OLog("查询字典")
@ApiOperation("查询字典")
@GetMapping
@PreAuthorize("@ps.check('dict:list')")
public ResponseEntity<Object> query(DictQueryCriteria resources, Pageable pageable) {
return new ResponseEntity<>(dictService.queryAll(resources, pageable), HttpStatus.OK);
}
@OLog("新增字典")
@ApiOperation("新增字典")
@PostMapping
@PreAuthorize("@ps.check('dict:add')") | package com.dimple.modules.system.rest;
/**
* @className: DictController
* @description:
* @author: Dimple
* @date: 06/17/20
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统:字典管理")
@RequestMapping("/api/dict")
public class DictController {
private static final String ENTITY_NAME = "dict";
private final DictService dictService;
@OLog("导出字典数据")
@ApiOperation("导出字典数据")
@GetMapping(value = "/download")
@PreAuthorize("@ps.check('dict:list')")
public void download(HttpServletResponse response, DictQueryCriteria criteria) throws IOException {
dictService.download(dictService.queryAll(criteria), response);
}
@OLog("查询字典")
@ApiOperation("查询字典")
@GetMapping(value = "/all")
@PreAuthorize("@ps.check('dict:list')")
public ResponseEntity<Object> queryAll() {
return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()), HttpStatus.OK);
}
@OLog("查询字典")
@ApiOperation("查询字典")
@GetMapping
@PreAuthorize("@ps.check('dict:list')")
public ResponseEntity<Object> query(DictQueryCriteria resources, Pageable pageable) {
return new ResponseEntity<>(dictService.queryAll(resources, pageable), HttpStatus.OK);
}
@OLog("新增字典")
@ApiOperation("新增字典")
@PostMapping
@PreAuthorize("@ps.check('dict:add')") | public ResponseEntity<Object> create(@Validated @RequestBody Dict resources) { | 1 | 2023-11-10 03:30:36+00:00 | 2k |
LazyCoder0101/LazyCoder | ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/commandinput/moduleinit/variable/ModuleVariableFolderHiddenButton.java | [
{
"identifier": "FoldButton",
"path": "ui-utils/src/main/java/com/lazycoder/uiutils/folder/FoldButton.java",
"snippet": "public class FoldButton extends MyToggleButton implements ItemSelectable {\n\n /**\n *\n */\n private static final long serialVersionUID = 332081120052094106L;\n\n //... | import com.lazycoder.uiutils.folder.FoldButton;
import com.lazycoder.uiutils.folder.FoldButtonUI; | 1,571 | package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.variable;
public class ModuleVariableFolderHiddenButton extends FoldButton {
/**
*
*/
private static final long serialVersionUID = -7822164353880179167L;
/**
* 是否隐藏面板
*
* @param expanded
*/
public ModuleVariableFolderHiddenButton(boolean expanded) {
super(expanded);
// TODO Auto-generated constructor stub
setText("模块变量"); | package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.variable;
public class ModuleVariableFolderHiddenButton extends FoldButton {
/**
*
*/
private static final long serialVersionUID = -7822164353880179167L;
/**
* 是否隐藏面板
*
* @param expanded
*/
public ModuleVariableFolderHiddenButton(boolean expanded) {
super(expanded);
// TODO Auto-generated constructor stub
setText("模块变量"); | setUI(new FoldButtonUI()); | 1 | 2023-11-16 11:55:06+00:00 | 2k |
hardingadonis/miu-shop | src/main/java/io/hardingadonis/miu/controller/admin/OrderAdmin.java | [
{
"identifier": "OrderStatus",
"path": "src/main/java/io/hardingadonis/miu/model/detail/OrderStatus.java",
"snippet": "public enum OrderStatus {\n PROCESSING(\"processing\"),\n SHIPPING(\"shipping\"),\n DONE(\"done\"),\n CANCELED(\"canceled\");\n\n private final String label;\n\n priva... | import io.hardingadonis.miu.model.*;
import io.hardingadonis.miu.model.detail.OrderStatus;
import io.hardingadonis.miu.services.Singleton;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import org.json.simple.JSONObject; | 702 | package io.hardingadonis.miu.controller.admin;
@WebServlet(name = "OrderAdmin", urlPatterns = {"/admin/order"})
public class OrderAdmin extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
HttpSession session = request.getSession();
Admin admin = (Admin) session.getAttribute("admin");
if (admin == null) {
response.sendRedirect(request.getContextPath() + "/admin/login");
return;
}
request.getRequestDispatcher("/view/admin/order-admin.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
OrderStatus orderStatus = OrderStatus.create(request.getParameter("status"));
try {
int id = Integer.parseInt(request.getParameter("id"));
| package io.hardingadonis.miu.controller.admin;
@WebServlet(name = "OrderAdmin", urlPatterns = {"/admin/order"})
public class OrderAdmin extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
HttpSession session = request.getSession();
Admin admin = (Admin) session.getAttribute("admin");
if (admin == null) {
response.sendRedirect(request.getContextPath() + "/admin/login");
return;
}
request.getRequestDispatcher("/view/admin/order-admin.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
OrderStatus orderStatus = OrderStatus.create(request.getParameter("status"));
try {
int id = Integer.parseInt(request.getParameter("id"));
| Order order = Singleton.orderDAO.get(id); | 1 | 2023-11-16 07:15:44+00:00 | 2k |
kash-developer/HomeDeviceEmulator | app/src/main/java/kr/or/kashi/hde/device/DoorLockTest.java | [
{
"identifier": "PROP_CURRENT_STATES",
"path": "app/src/main/java/kr/or/kashi/hde/device/DoorLock.java",
"snippet": "@PropertyDef(valueClass=State.class, formatHint=\"bits\")\npublic static final String PROP_CURRENT_STATES = PROP_PREFIX + \"current_states\";"
},
{
"identifier": "DeviceTestC... | import static kr.or.kashi.hde.device.DoorLock.PROP_CURRENT_STATES;
import kr.or.kashi.hde.test.DeviceTestCase; | 1,025 | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kr.or.kashi.hde.device;
public class DoorLockTest extends DeviceTestCase {
public void test_DoorOpen() throws Exception { | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kr.or.kashi.hde.device;
public class DoorLockTest extends DeviceTestCase {
public void test_DoorOpen() throws Exception { | final long state = device().getProperty(PROP_CURRENT_STATES, Long.class); | 0 | 2023-11-10 01:19:44+00:00 | 2k |
zizai-Shen/young-im | young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/parse/ConfigParseFactory.java | [
{
"identifier": "ConfigType",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/ConfigType.java",
"snippet": "@Getter\npublic enum ConfigType {\n\n /**\n * Json\n *... | import cn.young.im.springboot.starter.adapter.config.ConfigType;
import cn.young.im.springboot.starter.adapter.config.parse.handler.JsonConfigParseHandler;
import cn.young.im.springboot.starter.adapter.config.parse.handler.PropertiesConfigParseHandler;
import cn.young.im.springboot.starter.adapter.config.parse.handler.YamlConfigParseHandler;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.Collections.synchronizedMap; | 1,007 | package cn.young.im.springboot.starter.adapter.config.parse;
/**
* 作者:沈自在 <a href="https://www.szz.tax">Blog</a>
*
* @description 配置解析处理器工厂
* @date 2023/12/16
*/
public class ConfigParseFactory {
private static final Map<String, IConfigParseHandler> handlers = synchronizedMap(new LinkedHashMap<>());
static { | package cn.young.im.springboot.starter.adapter.config.parse;
/**
* 作者:沈自在 <a href="https://www.szz.tax">Blog</a>
*
* @description 配置解析处理器工厂
* @date 2023/12/16
*/
public class ConfigParseFactory {
private static final Map<String, IConfigParseHandler> handlers = synchronizedMap(new LinkedHashMap<>());
static { | handlers.put(ConfigType.JSON.getType(), new JsonConfigParseHandler()); | 0 | 2023-11-10 06:21:17+00:00 | 2k |
Ouest-France/querydsl | src/test/java/fr/ouestfrance/querydsl/FilterFieldServiceTest.java | [
{
"identifier": "DummyRequest",
"path": "src/test/java/fr/ouestfrance/querydsl/dummy/DummyRequest.java",
"snippet": "@Getter\n@Setter\npublic class DummyRequest {\n\n @FilterField\n private String uuid;\n\n @FilterField(key = \"productCode\")\n private String code;\n\n @FilterField(operat... | import fr.ouestfrance.querydsl.dummy.DummyRequest;
import fr.ouestfrance.querydsl.dummy.DummyRequestOrGroupMultipleField;
import fr.ouestfrance.querydsl.dummy.DummyRequestOrSingleField;
import fr.ouestfrance.querydsl.dummy.DummyViolatedRulesRequest;
import fr.ouestfrance.querydsl.model.SimpleFilter;
import fr.ouestfrance.querydsl.model.Filter;
import fr.ouestfrance.querydsl.service.FilterFieldAnnotationProcessorService;
import fr.ouestfrance.querydsl.service.validators.FilterFieldConstraintException;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*; | 1,286 | package fr.ouestfrance.querydsl;
class FilterFieldServiceTest {
private final FilterFieldAnnotationProcessorService service = new FilterFieldAnnotationProcessorService();
@Test
void shouldLoad() {
List<Filter> model = service.process(DummyRequest.class);
System.out.println(model.stream().map(Filter::toString).collect(Collectors.joining("\n")));
assertNotNull(model);
assertEquals(6, model.size());
AtomicBoolean shouldFindOrNull = new AtomicBoolean(false);
model.forEach(x -> {
assertNotNull(x);
assertTrue(x instanceof SimpleFilter);
SimpleFilter filter = (SimpleFilter)x;
assertNotNull(filter.field());
shouldFindOrNull.set(shouldFindOrNull.get() | filter.orNull());
});
assertTrue(shouldFindOrNull.get());
}
@Test
void shouldLoadComplexe() { | package fr.ouestfrance.querydsl;
class FilterFieldServiceTest {
private final FilterFieldAnnotationProcessorService service = new FilterFieldAnnotationProcessorService();
@Test
void shouldLoad() {
List<Filter> model = service.process(DummyRequest.class);
System.out.println(model.stream().map(Filter::toString).collect(Collectors.joining("\n")));
assertNotNull(model);
assertEquals(6, model.size());
AtomicBoolean shouldFindOrNull = new AtomicBoolean(false);
model.forEach(x -> {
assertNotNull(x);
assertTrue(x instanceof SimpleFilter);
SimpleFilter filter = (SimpleFilter)x;
assertNotNull(filter.field());
shouldFindOrNull.set(shouldFindOrNull.get() | filter.orNull());
});
assertTrue(shouldFindOrNull.get());
}
@Test
void shouldLoadComplexe() { | List<Filter> model = service.process(DummyRequestOrSingleField.class); | 2 | 2023-11-14 10:50:02+00:00 | 2k |
backend-source/ecommerce-microservice-architecture | product-service/src/main/java/com/hoangtien2k3/productservice/service/impl/CategoryServiceImpl.java | [
{
"identifier": "CategoryDto",
"path": "product-service/src/main/java/com/hoangtien2k3/productservice/dto/CategoryDto.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class CategoryDto implements Serializable {\n @Serial\n private static final long serialVersionU... | import com.hoangtien2k3.productservice.dto.CategoryDto;
import com.hoangtien2k3.productservice.exception.wrapper.CategoryNotFoundException;
import com.hoangtien2k3.productservice.helper.CategoryMappingHelper;
import com.hoangtien2k3.productservice.repository.CategoryRepository;
import com.hoangtien2k3.productservice.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors; | 1,016 | package com.hoangtien2k3.productservice.service.impl;
@Transactional
@Slf4j
@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired | package com.hoangtien2k3.productservice.service.impl;
@Transactional
@Slf4j
@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired | private final CategoryRepository categoryRepository; | 3 | 2023-11-13 04:24:52+00:00 | 2k |
NewXdOnTop/skyblock-remake | src/main/java/com/sweattypalms/skyblock/core/events/def/SkyblockInteractEvent.java | [
{
"identifier": "TriggerType",
"path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/abilities/TriggerType.java",
"snippet": "public enum TriggerType {\n NONE,\n RIGHT_CLICK,\n LEFT_CLICK;\n\n public static TriggerType getTriggerType(Action action) {\n return switch (act... | import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType;
import com.sweattypalms.skyblock.core.player.SkyblockPlayer;
import org.bukkit.block.Block;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; | 1,221 | package com.sweattypalms.skyblock.core.events.def;
public class SkyblockInteractEvent extends SkyblockPlayerEvent implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList();
private boolean isCancelled;
private final SkyblockPlayer skyblockPlayer; | package com.sweattypalms.skyblock.core.events.def;
public class SkyblockInteractEvent extends SkyblockPlayerEvent implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList();
private boolean isCancelled;
private final SkyblockPlayer skyblockPlayer; | private final TriggerType interactType; | 0 | 2023-11-15 15:05:58+00:00 | 2k |
microsphere-projects/microsphere-i18n | microsphere-i18n-core/src/test/java/io/microsphere/i18n/spring/context/I18nConfigurationTest.java | [
{
"identifier": "ServiceMessageSource",
"path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/ServiceMessageSource.java",
"snippet": "public interface ServiceMessageSource {\n\n /**\n * Common internationalizing message sources\n */\n String COMMON_SOURCE = \"common\";\n\n /*... | import io.microsphere.i18n.ServiceMessageSource;
import io.microsphere.i18n.spring.beans.TestServiceMessageSourceConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Locale;
import static io.microsphere.i18n.util.I18nUtils.serviceMessageSource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; | 910 | package io.microsphere.i18n.spring.context;
/**
* {@link I18nConfiguration} Test
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {I18nConfiguration.class, TestServiceMessageSourceConfiguration.class})
public class I18nConfigurationTest {
@Before
public void before() {
LocaleContextHolder.resetLocaleContext();
}
@Autowired | package io.microsphere.i18n.spring.context;
/**
* {@link I18nConfiguration} Test
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {I18nConfiguration.class, TestServiceMessageSourceConfiguration.class})
public class I18nConfigurationTest {
@Before
public void before() {
LocaleContextHolder.resetLocaleContext();
}
@Autowired | private ServiceMessageSource serviceMessageSource; | 2 | 2023-11-17 11:35:59+00:00 | 2k |
issavior/savior | savior-event/src/main/java/cn/sunjinxin/savior/event/listener/sub/SyncListener.java | [
{
"identifier": "SpringHelper",
"path": "savior-core/src/main/java/cn/sunjinxin/savior/core/helper/SpringHelper.java",
"snippet": "@FieldDefaults(level = AccessLevel.PRIVATE)\npublic class SpringHelper implements BeanFactoryPostProcessor, ApplicationContextAware, PriorityOrdered {\n\n static Applicat... | import cn.sunjinxin.savior.core.helper.SpringHelper;
import cn.sunjinxin.savior.event.container.EventContainer;
import cn.sunjinxin.savior.event.context.EventContext;
import cn.sunjinxin.savior.event.context.InnerEventContext;
import cn.sunjinxin.savior.event.control.Eventer;
import cn.sunjinxin.savior.event.listener.Listener;
import com.google.common.eventbus.Subscribe;
import org.springframework.context.event.EventListener;
import java.util.Optional; | 1,085 | package cn.sunjinxin.savior.event.listener.sub;
/**
* Sync Api
*
* @author issavior
*/
@SuppressWarnings("all")
public interface SyncListener<EventType, RequestParam> extends Listener<EventType, EventContext<EventType, RequestParam>> {
/**
* t
*
* @param t /
* @return /
*/
@Override
default boolean enable(EventType t) {
return supportEventType().contains(t);
}
@Override | package cn.sunjinxin.savior.event.listener.sub;
/**
* Sync Api
*
* @author issavior
*/
@SuppressWarnings("all")
public interface SyncListener<EventType, RequestParam> extends Listener<EventType, EventContext<EventType, RequestParam>> {
/**
* t
*
* @param t /
* @return /
*/
@Override
default boolean enable(EventType t) {
return supportEventType().contains(t);
}
@Override | default void onEvent(InnerEventContext event, long l, boolean b) { | 3 | 2023-11-16 15:34:22+00:00 | 2k |
Viola-Siemens/Advanced-Enchantments | src/main/java/com/hexagram2021/advanced_enchantments/AdvancedEnchantments.java | [
{
"identifier": "AEContent",
"path": "src/main/java/com/hexagram2021/advanced_enchantments/common/AEContent.java",
"snippet": "public class AEContent {\n\tpublic static void modConstruction(IEventBus bus) {\n\t\tAEEnchantments.init(bus);\n\t}\n}"
},
{
"identifier": "AECommonConfig",
"path": ... | import com.hexagram2021.advanced_enchantments.common.AEContent;
import com.hexagram2021.advanced_enchantments.common.config.AECommonConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
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; | 717 | package com.hexagram2021.advanced_enchantments;
@SuppressWarnings("unused")
@Mod(AdvancedEnchantments.MODID)
public class AdvancedEnchantments {
public static final String MODID = "advanced_enchantments";
public static final String MODNAME = "Advanced Enchantments";
public static final String VERSION = ModList.get().getModFileById(MODID).versionString();
public AdvancedEnchantments() {
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
AEContent.modConstruction(bus);
| package com.hexagram2021.advanced_enchantments;
@SuppressWarnings("unused")
@Mod(AdvancedEnchantments.MODID)
public class AdvancedEnchantments {
public static final String MODID = "advanced_enchantments";
public static final String MODNAME = "Advanced Enchantments";
public static final String VERSION = ModList.get().getModFileById(MODID).versionString();
public AdvancedEnchantments() {
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
AEContent.modConstruction(bus);
| ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, AECommonConfig.getConfig()); | 1 | 2023-11-12 12:23:21+00:00 | 2k |
pyzpre/Create-Bicycles-Bitterballen | src/main/java/createbicyclesbitterballen/CreateBicBitMod.java | [
{
"identifier": "BlockEntityRegistry",
"path": "src/main/java/createbicyclesbitterballen/index/BlockEntityRegistry.java",
"snippet": "public class BlockEntityRegistry {\n\n public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE\n .blockEntity(\"mechanical... | import java.util.Random;
import com.simibubi.create.foundation.item.ItemDescription;
import com.simibubi.create.foundation.item.KineticStats;
import com.simibubi.create.foundation.item.TooltipModifier;
import createbicyclesbitterballen.index.BlockEntityRegistry;
import createbicyclesbitterballen.config.ConfigRegistry;
import createbicyclesbitterballen.index.CreateBicBitModFluids;
import createbicyclesbitterballen.index.FluidTypesRegistry;
import createbicyclesbitterballen.index.*;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.config.ModConfig;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.simibubi.create.foundation.item.TooltipHelper.Palette;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.common.MinecraftForge;
import createbicyclesbitterballen.index.BlockRegistry;
import com.simibubi.create.foundation.data.CreateRegistrate; | 1,479 |
package createbicyclesbitterballen;
@Mod("create_bic_bit")
public class CreateBicBitMod {
public static final Logger LOGGER = LogManager.getLogger(CreateBicBitMod.class);
public static final String MODID = "create_bic_bit";
public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID);
@Deprecated
public static final Random RANDOM = new Random();
static {
REGISTRATE.setTooltipModifierFactory(item -> {
return new ItemDescription.Modifier(item, Palette.STANDARD_CREATE)
.andThen(TooltipModifier.mapNull(KineticStats.create(item)));
});
}
public CreateBicBitMod() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus forgeEventBus = MinecraftForge.EVENT_BUS;
MinecraftForge.EVENT_BUS.register(this);
// Register components using Registrate
SoundsRegistry.prepare();
BlockRegistry.register();
CreateBicBitModItems.register();
CreateBicBitModTabs.register(modEventBus);
RecipeRegistry.register(modEventBus);
BlockEntityRegistry.register();
PonderIndex.register(); |
package createbicyclesbitterballen;
@Mod("create_bic_bit")
public class CreateBicBitMod {
public static final Logger LOGGER = LogManager.getLogger(CreateBicBitMod.class);
public static final String MODID = "create_bic_bit";
public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID);
@Deprecated
public static final Random RANDOM = new Random();
static {
REGISTRATE.setTooltipModifierFactory(item -> {
return new ItemDescription.Modifier(item, Palette.STANDARD_CREATE)
.andThen(TooltipModifier.mapNull(KineticStats.create(item)));
});
}
public CreateBicBitMod() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
IEventBus forgeEventBus = MinecraftForge.EVENT_BUS;
MinecraftForge.EVENT_BUS.register(this);
// Register components using Registrate
SoundsRegistry.prepare();
BlockRegistry.register();
CreateBicBitModItems.register();
CreateBicBitModTabs.register(modEventBus);
RecipeRegistry.register(modEventBus);
BlockEntityRegistry.register();
PonderIndex.register(); | CreateBicBitModFluids.REGISTRY.register(bus); | 2 | 2023-11-12 13:05:18+00:00 | 2k |
cometcake575/Origins-Reborn | src/main/java/com/starshootercity/Origin.java | [
{
"identifier": "Ability",
"path": "src/main/java/com/starshootercity/abilities/Ability.java",
"snippet": "public interface Ability {\n @NotNull Key getKey();\n}"
},
{
"identifier": "VisibleAbility",
"path": "src/main/java/com/starshootercity/abilities/VisibleAbility.java",
"snippet":... | import com.starshootercity.abilities.Ability;
import com.starshootercity.abilities.VisibleAbility;
import com.starshootercity.abilities.AbilityRegister;
import net.kyori.adventure.key.Key;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Range;
import java.util.ArrayList;
import java.util.List; | 1,560 | package com.starshootercity;
public class Origin {
private final ItemStack icon;
private final int position;
private final char impact;
private final String name;
private final List<Key> abilities;
private final List<OriginSwapper.LineData.LineComponent> lineComponent;
public List<OriginSwapper.LineData.LineComponent> getLineData() {
return lineComponent;
}
public Origin(String name, ItemStack icon, int position, @Range(from = 0, to = 3) int impact, List<Key> abilities, String description) {
this.lineComponent = OriginSwapper.LineData.makeLineFor(description, OriginSwapper.LineData.LineComponent.LineType.DESCRIPTION);
this.name = name;
this.abilities = abilities;
this.icon = icon;
this.position = position;
this.impact = switch (impact) {
case 0 -> '\uE002';
case 1 -> '\uE003';
case 2 -> '\uE004';
default -> '\uE005';
};
}
public List<VisibleAbility> getVisibleAbilities() {
List<VisibleAbility> result = new ArrayList<>();
for (Key key : abilities) { | package com.starshootercity;
public class Origin {
private final ItemStack icon;
private final int position;
private final char impact;
private final String name;
private final List<Key> abilities;
private final List<OriginSwapper.LineData.LineComponent> lineComponent;
public List<OriginSwapper.LineData.LineComponent> getLineData() {
return lineComponent;
}
public Origin(String name, ItemStack icon, int position, @Range(from = 0, to = 3) int impact, List<Key> abilities, String description) {
this.lineComponent = OriginSwapper.LineData.makeLineFor(description, OriginSwapper.LineData.LineComponent.LineType.DESCRIPTION);
this.name = name;
this.abilities = abilities;
this.icon = icon;
this.position = position;
this.impact = switch (impact) {
case 0 -> '\uE002';
case 1 -> '\uE003';
case 2 -> '\uE004';
default -> '\uE005';
};
}
public List<VisibleAbility> getVisibleAbilities() {
List<VisibleAbility> result = new ArrayList<>();
for (Key key : abilities) { | if (AbilityRegister.abilityMap.get(key) instanceof VisibleAbility visibleAbility) { | 2 | 2023-11-10 21:39:16+00:00 | 2k |
vadremix/journee | services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/controller/UserController.java | [
{
"identifier": "User",
"path": "services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/model/User.java",
"snippet": "@Entity\n@Table(name = \"users\")\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n privat... | import com.worldjournee.usermanagementservice.model.User;
import com.worldjournee.usermanagementservice.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | 732 | package com.worldjournee.usermanagementservice.controller;
@RestController
@RequestMapping("/api/v1/create-user")
public class UserController { | package com.worldjournee.usermanagementservice.controller;
@RestController
@RequestMapping("/api/v1/create-user")
public class UserController { | private final UserService userService; | 1 | 2023-11-13 21:40:58+00:00 | 2k |
daobab-projects/orm-performance-comparator | src/main/java/io/daobab/performance/jpa/JpaController.java | [
{
"identifier": "Actor",
"path": "src/main/java/io/daobab/performance/hibernate/entity/Actor.java",
"snippet": "@Entity\n@Table(name = \"actor\")\n@Getter\n@Setter\n@EqualsAndHashCode\npublic class Actor implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @... | import io.daobab.performance.hibernate.entity.Actor;
import io.daobab.performance.jpa.model.CustomerAddress;
import io.daobab.performance.jpa.repository.ActorJpaService;
import io.daobab.performance.jpa.repository.CustomerJpaService;
import io.daobab.performance.jpa.repository.PaymentJpaService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; | 729 | package io.daobab.performance.jpa;
@RestController
@RequestMapping(path = "/jpa", produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class JpaController {
| package io.daobab.performance.jpa;
@RestController
@RequestMapping(path = "/jpa", produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class JpaController {
| private final ActorJpaService actorService; | 2 | 2023-11-12 21:43:51+00:00 | 2k |
lastnightinparis/tinkoff-investement-bot | bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/users/UserServiceImpl.java | [
{
"identifier": "ResourceNotFoundException",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/system/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends TradingBotException {\n\n private ResourceType type;\n private QueryType ... | import com.itmo.tinkoffinvestementbot.exception.system.ResourceNotFoundException;
import com.itmo.tinkoffinvestementbot.model.domain.User;
import com.itmo.tinkoffinvestementbot.model.enums.bot.BotState;
import com.itmo.tinkoffinvestementbot.model.enums.exceptions.QueryType;
import com.itmo.tinkoffinvestementbot.model.enums.exceptions.ResourceType;
import com.itmo.tinkoffinvestementbot.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
import java.util.Optional; | 1,430 | package com.itmo.tinkoffinvestementbot.service.users;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public Optional<User> findUserByChatId(long chatId) {
return userRepository.findByChatId(chatId);
}
@Override
public Optional<User> findUserByTgUsername(String tgUsername) {
return userRepository.findByTgUsername(tgUsername);
}
@Override
public List<Long> getAdminChatIds() {
return userRepository.findAdminChatIds();
}
@Override
public User getUserById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.ID, id));
}
@Override
public User getUserByChatId(Long chatId) {
return findUserByChatId(chatId)
.orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.CHAT_ID, chatId));
}
@Override
public User save(User user) {
User userFromDb;
if (user.getId() != null) {
userFromDb = getUserByChatId(user.getChatId());
BeanUtils.copyProperties(user, userFromDb, "id");
} else {
userFromDb = User.builder()
.chatId(user.getChatId())
.username(user.getUsername())
.tgUsername(user.getTgUsername())
.active(false)
.blocked(false)
.connectedInvestAccount(false) | package com.itmo.tinkoffinvestementbot.service.users;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public Optional<User> findUserByChatId(long chatId) {
return userRepository.findByChatId(chatId);
}
@Override
public Optional<User> findUserByTgUsername(String tgUsername) {
return userRepository.findByTgUsername(tgUsername);
}
@Override
public List<Long> getAdminChatIds() {
return userRepository.findAdminChatIds();
}
@Override
public User getUserById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.ID, id));
}
@Override
public User getUserByChatId(Long chatId) {
return findUserByChatId(chatId)
.orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.CHAT_ID, chatId));
}
@Override
public User save(User user) {
User userFromDb;
if (user.getId() != null) {
userFromDb = getUserByChatId(user.getChatId());
BeanUtils.copyProperties(user, userFromDb, "id");
} else {
userFromDb = User.builder()
.chatId(user.getChatId())
.username(user.getUsername())
.tgUsername(user.getTgUsername())
.active(false)
.blocked(false)
.connectedInvestAccount(false) | .botState(BotState.FIRST_START) | 2 | 2023-11-13 09:28:00+00:00 | 2k |
toxicity188/InventoryAPI | plugin/src/main/java/kor/toxicity/inventory/generator/FontObjectImpl.java | [
{
"identifier": "GuiObject",
"path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiObject.java",
"snippet": "public interface GuiObject {\n GuiObject EMPTY = new GuiObject() {\n @Override\n public @NotNull GuiObjectGenerator getGenerator() {\n throw new UnsupportedOper... | import kor.toxicity.inventory.api.gui.GuiObject;
import kor.toxicity.inventory.api.gui.GuiObjectGenerator;
import kor.toxicity.inventory.util.AdventureUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextDecoration;
import org.jetbrains.annotations.NotNull; | 798 | package kor.toxicity.inventory.generator;
public class FontObjectImpl implements GuiObject {
private static final Component SPACE_COMPONENT = Component.text(' ');
private final FontObjectGeneratorImpl objectGenerator;
private final Component component;
public FontObjectImpl(FontObjectGeneratorImpl objectGenerator, String text, Style style, int space, int xOffset) {
this.objectGenerator = objectGenerator;
var comp = Component.empty().append(AdventureUtil.getSpaceFont(xOffset));
var spaceComp = AdventureUtil.getSpaceFont(space);
var charArray = text.toCharArray();
var i = 0;
for (char c : charArray) {
if (c == ' ') {
comp = comp.append(SPACE_COMPONENT.font(objectGenerator.getFontKey()));
i += 4;
} else {
var charWidth = objectGenerator.getFont().getFontWidth().get(c);
var t = charWidth != null ? charWidth.apply(objectGenerator.getHeight()) : 0;
if (style.hasDecoration(TextDecoration.BOLD)) t++;
if (style.hasDecoration(TextDecoration.ITALIC)) t++;
comp = comp.append(Component.text(c).style(style.font(objectGenerator.getFontKey()))
.append(AdventureUtil.getSpaceFont(-t))
.append(spaceComp));
i += space;
}
}
component = comp.append(AdventureUtil.getSpaceFont(-i));
}
@Override | package kor.toxicity.inventory.generator;
public class FontObjectImpl implements GuiObject {
private static final Component SPACE_COMPONENT = Component.text(' ');
private final FontObjectGeneratorImpl objectGenerator;
private final Component component;
public FontObjectImpl(FontObjectGeneratorImpl objectGenerator, String text, Style style, int space, int xOffset) {
this.objectGenerator = objectGenerator;
var comp = Component.empty().append(AdventureUtil.getSpaceFont(xOffset));
var spaceComp = AdventureUtil.getSpaceFont(space);
var charArray = text.toCharArray();
var i = 0;
for (char c : charArray) {
if (c == ' ') {
comp = comp.append(SPACE_COMPONENT.font(objectGenerator.getFontKey()));
i += 4;
} else {
var charWidth = objectGenerator.getFont().getFontWidth().get(c);
var t = charWidth != null ? charWidth.apply(objectGenerator.getHeight()) : 0;
if (style.hasDecoration(TextDecoration.BOLD)) t++;
if (style.hasDecoration(TextDecoration.ITALIC)) t++;
comp = comp.append(Component.text(c).style(style.font(objectGenerator.getFontKey()))
.append(AdventureUtil.getSpaceFont(-t))
.append(spaceComp));
i += space;
}
}
component = comp.append(AdventureUtil.getSpaceFont(-i));
}
@Override | public @NotNull GuiObjectGenerator getGenerator() { | 1 | 2023-11-13 00:19:46+00:00 | 2k |
ryosoraa/E-Rapor | src/main/java/com/erapor/erapor/service/StudentsService.java | [
{
"identifier": "StudentsDAO",
"path": "src/main/java/com/erapor/erapor/model/DAO/StudentsDAO.java",
"snippet": "@Data\n@Entity\n@Table(name = \"students\")\npublic class StudentsDAO {\n\n @Id\n @NotBlank\n @Size(max = 50)\n private String id;\n\n @NotBlank\n @Size(max = 100)\n priv... | import com.erapor.erapor.model.DAO.StudentsDAO;
import com.erapor.erapor.model.DAO.ValuesDAO;
import com.erapor.erapor.model.DTO.RankingDTO;
import com.erapor.erapor.model.DTO.StudentsDTO;
import com.erapor.erapor.repository.StudentsRepository;
import com.erapor.erapor.repository.ValuesRepository;
import com.erapor.erapor.utils.Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | 1,488 | package com.erapor.erapor.service;
@Service
public class StudentsService {
@Autowired
StudentsRepository studentsRepository;
@Autowired
ValuesRepository valuesRepository;
@Autowired
Converter converter;
| package com.erapor.erapor.service;
@Service
public class StudentsService {
@Autowired
StudentsRepository studentsRepository;
@Autowired
ValuesRepository valuesRepository;
@Autowired
Converter converter;
| public List<RankingDTO> ranking(Integer page, Integer size){ | 2 | 2023-11-11 19:40:43+00:00 | 2k |
ebandal/jDwgParser | src/structure/header/FileHeader.java | [
{
"identifier": "DwgVersion",
"path": "src/structure/DwgVersion.java",
"snippet": "public enum DwgVersion {\n R13 (1), // AC1012\n R14 (2), // AC1014\n R15 (3),\n R2000 (3), // AC1015\n R18 (4),\n R2004 (4), // AC1018\n R21 (5),\n R2007 (5), ... | import java.util.List;
import structure.DwgVersion;
import structure.SectionLocator;
import structure.sectionpage.header.DataSectionPageHeader;
import structure.sectionpage.header.SystemSectionPageHeader; | 727 | package structure.header;
public class FileHeader {
public String versionId;
public DwgVersion ver;
public int imageSeeker; // R15
public int previewSeeker; // R2004
public byte appVer; // R2004
public byte appMrVer; // R2004
public short codePage; // R15, R2004
// SECTION-LOCATOR RECORDS | package structure.header;
public class FileHeader {
public String versionId;
public DwgVersion ver;
public int imageSeeker; // R15
public int previewSeeker; // R2004
public byte appVer; // R2004
public byte appMrVer; // R2004
public short codePage; // R15, R2004
// SECTION-LOCATOR RECORDS | public List<SectionLocator> sectionLocatorList; // R15 | 1 | 2023-11-11 13:57:18+00:00 | 2k |
KomnisEvangelos/GeoApp | app/src/main/java/gr/ihu/geoapp/ui/profile/ProfileFragment.java | [
{
"identifier": "RegularUser",
"path": "app/src/main/java/gr/ihu/geoapp/models/users/RegularUser.java",
"snippet": "public class RegularUser implements User{\n\n private static RegularUser single_instance = null;\n private String fullName = null;\n private String email = null;\n private Stri... | import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.firebase.auth.FirebaseAuth;
import java.util.Optional;
import gr.ihu.geoapp.databinding.FragmentProfileBinding;
import gr.ihu.geoapp.models.users.RegularUser;
import gr.ihu.geoapp.ui.signin.SignInActivity; | 1,531 | package gr.ihu.geoapp.ui.profile;
public class ProfileFragment extends Fragment {
private FragmentProfileBinding binding;
private ImageView profileImageView;
private TextView nameTextView;
private TextView emailTextView;
private TextView birthdayTextView;
private TextView professionTextView;
private TextView diplomaTextView;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ProfileViewModel profileViewModel =
new ViewModelProvider(this).get(ProfileViewModel.class);
binding = FragmentProfileBinding.inflate(inflater, container, false);
View root = binding.getRoot();
profileImageView = binding.profileImageView;
nameTextView = binding.nameTextView;
emailTextView = binding.emailTextView;
birthdayTextView = binding.birthdayTextView;
professionTextView = binding.professionTextView;
diplomaTextView = binding.diplomaTextView;
RegularUser user = RegularUser.getInstance();
nameTextView.setText(Optional.ofNullable(user.getFullName()).orElse("No data found"));
emailTextView.setText(Optional.ofNullable(user.getEmail()).orElse("No data found"));
birthdayTextView.setText(Optional.ofNullable(user.getDateOfBirth()).orElse("No data found"));
professionTextView.setText(Optional.ofNullable(user.getProfession()).orElse("No data found"));
diplomaTextView.setText(Optional.ofNullable(user.getDiploma()).orElse("No data found"));
Button logoutButton = binding.logoutButton;
logoutButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
RegularUser.getInstance().logout(); | package gr.ihu.geoapp.ui.profile;
public class ProfileFragment extends Fragment {
private FragmentProfileBinding binding;
private ImageView profileImageView;
private TextView nameTextView;
private TextView emailTextView;
private TextView birthdayTextView;
private TextView professionTextView;
private TextView diplomaTextView;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ProfileViewModel profileViewModel =
new ViewModelProvider(this).get(ProfileViewModel.class);
binding = FragmentProfileBinding.inflate(inflater, container, false);
View root = binding.getRoot();
profileImageView = binding.profileImageView;
nameTextView = binding.nameTextView;
emailTextView = binding.emailTextView;
birthdayTextView = binding.birthdayTextView;
professionTextView = binding.professionTextView;
diplomaTextView = binding.diplomaTextView;
RegularUser user = RegularUser.getInstance();
nameTextView.setText(Optional.ofNullable(user.getFullName()).orElse("No data found"));
emailTextView.setText(Optional.ofNullable(user.getEmail()).orElse("No data found"));
birthdayTextView.setText(Optional.ofNullable(user.getDateOfBirth()).orElse("No data found"));
professionTextView.setText(Optional.ofNullable(user.getProfession()).orElse("No data found"));
diplomaTextView.setText(Optional.ofNullable(user.getDiploma()).orElse("No data found"));
Button logoutButton = binding.logoutButton;
logoutButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
RegularUser.getInstance().logout(); | Intent intent = new Intent(getActivity(), SignInActivity.class); | 1 | 2023-11-10 17:43:18+00:00 | 2k |
Nel1yMinecraft/Grim | src/main/java/ac/grim/grimac/manager/init/start/CommandRegister.java | [
{
"identifier": "GrimAPI",
"path": "src/main/java/ac/grim/grimac/GrimAPI.java",
"snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final... | import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.commands.GrimDebug;
import ac.grim.grimac.commands.GrimPerf;
import ac.grim.grimac.manager.init.Initable;
import co.aikar.commands.PaperCommandManager; | 1,029 | package ac.grim.grimac.manager.init.start;
public class CommandRegister implements Initable {
@Override
public void start() {
// This does not make Grim require paper
// It only enables new features such as asynchronous tab completion on paper | package ac.grim.grimac.manager.init.start;
public class CommandRegister implements Initable {
@Override
public void start() {
// This does not make Grim require paper
// It only enables new features such as asynchronous tab completion on paper | PaperCommandManager commandManager = new PaperCommandManager(GrimAPI.INSTANCE.getPlugin()); | 0 | 2023-11-11 05:14:12+00:00 | 2k |
StanCEmpire/Enquestment | src/main/java/stancempire/enquestment/events/UserEvents.java | [
{
"identifier": "ClientSetup",
"path": "src/main/java/stancempire/enquestment/client/ClientSetup.java",
"snippet": "public class ClientSetup\n{\n\n /**\n * Event for basic client setup tasks\n */\n @SubscribeEvent\n public void onClientSetup(final FMLClientSetupEvent event)\n {\n\n ... | import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.TickEvent;
import stancempire.enquestment.client.ClientSetup;
import stancempire.enquestment.network.NetworkManager;
import stancempire.enquestment.network.packets.SBRequestOpenGui;
import stancempire.enquestment.network.util.ModScreen; | 989 | package stancempire.enquestment.events;
/**
* <p>CLIENT CODE</p>
* Class for handling user input events
*/
public class UserEvents
{
/**
* Checks for custom keybinds
*/
@SubscribeEvent
public void onKeyPressed(TickEvent.ClientTickEvent event)
{
if(event.phase == TickEvent.Phase.END) //Prevent logic from being executed twice
{
while(ClientSetup.EMENU_KEY.get().consumeClick()) //EMENU key
{
| package stancempire.enquestment.events;
/**
* <p>CLIENT CODE</p>
* Class for handling user input events
*/
public class UserEvents
{
/**
* Checks for custom keybinds
*/
@SubscribeEvent
public void onKeyPressed(TickEvent.ClientTickEvent event)
{
if(event.phase == TickEvent.Phase.END) //Prevent logic from being executed twice
{
while(ClientSetup.EMENU_KEY.get().consumeClick()) //EMENU key
{
| NetworkManager.NETWORK_INSTANCE.sendToServer(new SBRequestOpenGui(ModScreen.TEST)); | 3 | 2023-11-11 13:16:04+00:00 | 2k |
ImShyMike/QuestCompassPlus | src/main/java/shymike/questcompassplus/mixin/PlayerSpawnPositionMixin.java | [
{
"identifier": "Config",
"path": "src/main/java/shymike/questcompassplus/config/Config.java",
"snippet": "public class Config {\n\tpublic static boolean isModEnabled = true;\n public static double x = 0, y = 0, z = 0;\n\tpublic static boolean chatFeedback = false;\n\tpublic static int color = 0;\n\t... | import shymike.questcompassplus.config.Config;
import shymike.questcompassplus.utils.WaypointManager;
import shymike.questcompassplus.utils.ServerUtils;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.s2c.play.PlayerSpawnPositionS2CPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.util.math.BlockPos; | 1,238 | package shymike.questcompassplus.mixin;
@Environment(EnvType.CLIENT)
@Mixin(ClientPlayNetworkHandler.class)
public class PlayerSpawnPositionMixin {
private double xL = 0, yL = 0, zL = 0;
private MinecraftClient mc = MinecraftClient.getInstance();
@Inject(method = "onPlayerSpawnPosition", at = @At("RETURN"))
private void onPlayerSpawnPosition(PlayerSpawnPositionS2CPacket packet, CallbackInfo ci) {
BlockPos pos = packet.getPos();
double x = pos.getX(), y = pos.getY(), z = pos.getZ();
Config.setCoordinates(x,y,z);
if (ServerUtils.isOnMonumenta()) {
// Anti spam
if (x != xL || y != yL || z != zL) {
this.xL = x;
this.yL = y;
this.zL = z; | package shymike.questcompassplus.mixin;
@Environment(EnvType.CLIENT)
@Mixin(ClientPlayNetworkHandler.class)
public class PlayerSpawnPositionMixin {
private double xL = 0, yL = 0, zL = 0;
private MinecraftClient mc = MinecraftClient.getInstance();
@Inject(method = "onPlayerSpawnPosition", at = @At("RETURN"))
private void onPlayerSpawnPosition(PlayerSpawnPositionS2CPacket packet, CallbackInfo ci) {
BlockPos pos = packet.getPos();
double x = pos.getX(), y = pos.getY(), z = pos.getZ();
Config.setCoordinates(x,y,z);
if (ServerUtils.isOnMonumenta()) {
// Anti spam
if (x != xL || y != yL || z != zL) {
this.xL = x;
this.yL = y;
this.zL = z; | WaypointManager.create(mc, x, y, z); | 1 | 2023-11-14 15:56:39+00:00 | 2k |
kawainime/IOT-Smart_Farming | IOT_Farm_V.2/src/Core/Background/Task_Schedule.java | [
{
"identifier": "Load_Data",
"path": "IOT_Farm_V.2/src/Core/SQL_Lite3/Load_Data.java",
"snippet": "public class Load_Data \n{\n public static String load_condition(String condition)\n {\n String value = null;\n \n String SQL = \"SELECT \"+condition+\" FROM Report WHERE Record_... | import Core.SQL_Lite3.Load_Data;
import static UI.Globle_weather.jLabel14;
import static UI.Globle_weather.jLabel15;
import static UI.Globle_weather.jLabel16;
import static UI.Globle_weather.jLabel18;
import static UI.Globle_weather.jLabel2;
import static UI.Globle_weather.jLabel21;
import static UI.Globle_weather.jLabel24;
import static UI.Globle_weather.jLabel27;
import static UI.Globle_weather.jLabel7;
import java.util.Timer;
import java.util.TimerTask; | 775 | package Core.Background;
public class Task_Schedule
{
public static void load_data()
{
jLabel2.setText(Load_Data.load_condition("Weather"));
jLabel27.setText(Load_Data.load_condition("Weather")+","+Load_Data.load_condition("Weather_description"));
jLabel24.setText(Load_Data.load_condition("Feel_Like")+" F");
jLabel18.setText(Load_Data.load_condition("Wind_Speed")+" km/h");
jLabel21.setText(Load_Data.load_condition("Pressure")+" MB");
jLabel14.setText("Max Temperature : "+Load_Data.load_condition("Max_Temp")+" F");
jLabel15.setText("Min Temperature : "+Load_Data.load_condition("Min_Temp")+ " F");
| package Core.Background;
public class Task_Schedule
{
public static void load_data()
{
jLabel2.setText(Load_Data.load_condition("Weather"));
jLabel27.setText(Load_Data.load_condition("Weather")+","+Load_Data.load_condition("Weather_description"));
jLabel24.setText(Load_Data.load_condition("Feel_Like")+" F");
jLabel18.setText(Load_Data.load_condition("Wind_Speed")+" km/h");
jLabel21.setText(Load_Data.load_condition("Pressure")+" MB");
jLabel14.setText("Max Temperature : "+Load_Data.load_condition("Max_Temp")+" F");
jLabel15.setText("Min Temperature : "+Load_Data.load_condition("Min_Temp")+ " F");
| jLabel7.setText("Temperature In F : "+Load_Data.load_condition("Temperature")+ " F"); | 9 | 2023-11-11 08:23:10+00:00 | 2k |
Outer-Fields/item-server | src/main/java/io/mindspice/itemserver/services/LeaderBoardService.java | [
{
"identifier": "PlayerScore",
"path": "src/main/java/io/mindspice/itemserver/schema/PlayerScore.java",
"snippet": "public class PlayerScore {\n @JsonProperty(\"name\") public final String playerName;\n @JsonProperty(\"won\") public int wins = 0;\n @JsonProperty(\"lost\") public int losses = 0;... | import io.mindspice.databaseservice.client.api.OkraGameAPI;
import io.mindspice.databaseservice.client.schema.MatchResult;
import io.mindspice.itemserver.schema.PlayerScore;
import io.mindspice.itemserver.util.CustomLogger;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List; | 1,006 | package io.mindspice.itemserver.services;
public class LeaderBoardService {
private final OkraGameAPI gameAPI; | package io.mindspice.itemserver.services;
public class LeaderBoardService {
private final OkraGameAPI gameAPI; | public final CustomLogger logger; | 1 | 2023-11-14 14:56:37+00:00 | 2k |
KvRae/Mobile-Exemple-Java-Android | Project/app/src/main/java/com/example/pharmacie2/Views/Activities/SignUpActivity.java | [
{
"identifier": "UserDao",
"path": "Project/app/src/main/java/com/example/pharmacie2/Data/Dao/UserDao.java",
"snippet": "@Dao\npublic interface UserDao {\n @Insert\n void insert(User user);\n @Delete\n void delete(User user);\n\n @Query(\"SELECT * FROM users WHERE email = :email\")\n U... | import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.pharmacie2.Data.Dao.UserDao;
import com.example.pharmacie2.Data.Database.PharmacyDB;
import com.example.pharmacie2.Data.Entities.User;
import com.example.pharmacie2.R; | 1,380 | package com.example.pharmacie2.Views.Activities;
public class SignUpActivity extends AppCompatActivity {
TextView signInBtn;
Button buttonSignUp;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextName = findViewById(R.id.editTextName);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
buttonSignUp = findViewById(R.id.buttonSignUp);
buttonSignUp.setOnClickListener(v -> {
String name = editTextName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
// Check if the email is already registered
new CheckEmailTask().execute(name, email, password);
});
signInBtn = findViewById(R.id.textViewSignInLink);
signInBtn.setOnClickListener(
e -> {
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
finish();
Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();
}
);
}
private class CheckEmailTask extends AsyncTask<String, Void, Boolean> {
private String[] params;
@Override
protected Boolean doInBackground(String... params) {
this.params = params; // Stored the parameters
String name = params[0];
String email = params[1];
String password = params[2];
PharmacyDB userDatabase = PharmacyDB.getInstance(getApplicationContext());
UserDao userDao = userDatabase.userDao();
// Check if the email is already registered | package com.example.pharmacie2.Views.Activities;
public class SignUpActivity extends AppCompatActivity {
TextView signInBtn;
Button buttonSignUp;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextName = findViewById(R.id.editTextName);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
buttonSignUp = findViewById(R.id.buttonSignUp);
buttonSignUp.setOnClickListener(v -> {
String name = editTextName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
// Check if the email is already registered
new CheckEmailTask().execute(name, email, password);
});
signInBtn = findViewById(R.id.textViewSignInLink);
signInBtn.setOnClickListener(
e -> {
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
finish();
Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();
}
);
}
private class CheckEmailTask extends AsyncTask<String, Void, Boolean> {
private String[] params;
@Override
protected Boolean doInBackground(String... params) {
this.params = params; // Stored the parameters
String name = params[0];
String email = params[1];
String password = params[2];
PharmacyDB userDatabase = PharmacyDB.getInstance(getApplicationContext());
UserDao userDao = userDatabase.userDao();
// Check if the email is already registered | User existingUser = userDao.getUserByEmail(email); | 2 | 2023-11-14 22:07:33+00:00 | 2k |
CodecNomad/CodecClient | src/main/java/com/github/codecnomad/codecclient/ui/Config.java | [
{
"identifier": "Client",
"path": "src/main/java/com/github/codecnomad/codecclient/Client.java",
"snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft... | import cc.polyfrost.oneconfig.config.annotations.Number;
import cc.polyfrost.oneconfig.config.annotations.*;
import cc.polyfrost.oneconfig.config.core.OneColor;
import cc.polyfrost.oneconfig.config.core.OneKeyBind;
import cc.polyfrost.oneconfig.config.data.Mod;
import cc.polyfrost.oneconfig.config.data.ModType;
import com.github.codecnomad.codecclient.Client;
import com.github.codecnomad.codecclient.modules.Module;
import org.lwjgl.input.Keyboard; | 1,078 | package com.github.codecnomad.codecclient.ui;
@SuppressWarnings("unused")
public class Config extends cc.polyfrost.oneconfig.config.Config {
@Color(
name = "Color",
category = "Visuals"
)
public static OneColor VisualColor = new OneColor(100, 60, 160, 200);
@KeyBind(
name = "Fishing key-bind",
category = "Macros",
subcategory = "Fishing"
)
public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);
@Number(
name = "Catch delay",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 20
)
public static int FishingDelay = 10;
@Number(
name = "Kill delay",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 40
)
public static int KillDelay = 20;
@Number(
name = "Attack c/s",
category = "Macros",
subcategory = "Fishing",
min = 5,
max = 20
)
public static int AttackCps = 10;
@Number(
name = "Smoothing",
category = "Macros",
subcategory = "Fishing",
min = 2,
max = 10
)
public static int RotationSmoothing = 4;
@Number(
name = "Random movement frequency",
category = "Macros",
subcategory = "Fishing",
min = 5,
max = 50
)
public static int MovementFrequency = 15;
@Switch(
name = "Auto kill",
category = "Macros",
subcategory = "Fishing"
)
public static boolean AutoKill = true;
@Switch(
name = "Only sound failsafe",
category = "Macros",
subcategory = "Fishing"
)
public static boolean OnlySound = false;
@Number(
name = "Weapon slot",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 9
)
public static int WeaponSlot = 9;
@Switch(
name = "Right click attack",
category = "Macros",
subcategory = "Fishing"
)
public static boolean RightClick = false;
@HUD(
name = "Fishing HUD",
category = "Visuals"
)
public FishingHud hudFishing = new FishingHud();
public Config() {
super(new Mod("CodecClient", ModType.UTIL_QOL), "config.json");
initialize();
registerKeyBind(FishingKeybinding, () -> toggle("FishingMacro"));
save();
}
private static void toggle(String name) { | package com.github.codecnomad.codecclient.ui;
@SuppressWarnings("unused")
public class Config extends cc.polyfrost.oneconfig.config.Config {
@Color(
name = "Color",
category = "Visuals"
)
public static OneColor VisualColor = new OneColor(100, 60, 160, 200);
@KeyBind(
name = "Fishing key-bind",
category = "Macros",
subcategory = "Fishing"
)
public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);
@Number(
name = "Catch delay",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 20
)
public static int FishingDelay = 10;
@Number(
name = "Kill delay",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 40
)
public static int KillDelay = 20;
@Number(
name = "Attack c/s",
category = "Macros",
subcategory = "Fishing",
min = 5,
max = 20
)
public static int AttackCps = 10;
@Number(
name = "Smoothing",
category = "Macros",
subcategory = "Fishing",
min = 2,
max = 10
)
public static int RotationSmoothing = 4;
@Number(
name = "Random movement frequency",
category = "Macros",
subcategory = "Fishing",
min = 5,
max = 50
)
public static int MovementFrequency = 15;
@Switch(
name = "Auto kill",
category = "Macros",
subcategory = "Fishing"
)
public static boolean AutoKill = true;
@Switch(
name = "Only sound failsafe",
category = "Macros",
subcategory = "Fishing"
)
public static boolean OnlySound = false;
@Number(
name = "Weapon slot",
category = "Macros",
subcategory = "Fishing",
min = 1,
max = 9
)
public static int WeaponSlot = 9;
@Switch(
name = "Right click attack",
category = "Macros",
subcategory = "Fishing"
)
public static boolean RightClick = false;
@HUD(
name = "Fishing HUD",
category = "Visuals"
)
public FishingHud hudFishing = new FishingHud();
public Config() {
super(new Mod("CodecClient", ModType.UTIL_QOL), "config.json");
initialize();
registerKeyBind(FishingKeybinding, () -> toggle("FishingMacro"));
save();
}
private static void toggle(String name) { | Module helperClassModule = Client.modules.get(name); | 1 | 2023-11-16 10:12:20+00:00 | 2k |
Mightinity/store-management-system | src/main/java/com/systeminventory/controller/productCardController.java | [
{
"identifier": "DeleteProductListener",
"path": "src/main/java/com/systeminventory/interfaces/DeleteProductListener.java",
"snippet": "public interface DeleteProductListener {\n public void clickDeleteProductListener(Product product);\n}"
},
{
"identifier": "DetailsProductListener",
"pat... | import com.systeminventory.interfaces.DeleteProductListener;
import com.systeminventory.interfaces.DetailsProductListener;
import com.systeminventory.interfaces.EditProductListener;
import com.systeminventory.model.Product;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import java.io.File;
import java.io.IOException; | 717 | package com.systeminventory.controller;
public class productCardController {
@FXML
private ImageView productCardImage;
@FXML
private Label productCardPrice;
@FXML
private Label productCardTitle;
@FXML
private Label productCardStock;
@FXML
private Pane deleteButtonProduct;
@FXML
private Pane editButtonProduct;
@FXML
private Pane infoButtonProduct;
@FXML
private Label keyProduct;
private Product product;
private DeleteProductListener deleteProductListener; | package com.systeminventory.controller;
public class productCardController {
@FXML
private ImageView productCardImage;
@FXML
private Label productCardPrice;
@FXML
private Label productCardTitle;
@FXML
private Label productCardStock;
@FXML
private Pane deleteButtonProduct;
@FXML
private Pane editButtonProduct;
@FXML
private Pane infoButtonProduct;
@FXML
private Label keyProduct;
private Product product;
private DeleteProductListener deleteProductListener; | private EditProductListener editProductListener; | 2 | 2023-11-18 02:53:02+00:00 | 2k |
dsntk/dsntk-java-server | src/main/java/io/dsntk/server/rest/controllers/RpcController.java | [
{
"identifier": "ResultDto",
"path": "src/main/java/io/dsntk/server/rest/dto/ResultDto.java",
"snippet": "@Getter\npublic class ResultDto<T> {\n\n /** Data sent as a result. */\n @JsonProperty(\"data\")\n private T data;\n\n /**\n * Creates a new DTO object containing result data.\n *\n * @par... | import io.dsntk.server.rest.dto.ResultDto;
import io.dsntk.server.rest.dto.ValueDto;
import io.dsntk.server.rest.errors.RpcException;
import io.dsntk.server.rest.params.RpcParams;
import io.dsntk.server.services.RpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | 1,329 | package io.dsntk.server.rest.controllers;
/**
* Java RPC controller.
*/
@Slf4j
@RestController
@RequestMapping(RequestMappings.M_RPC_SERVER)
public class RpcController {
private final RpcService rpcService;
/** Initializes RPC controller. */
public RpcController(RpcService rpcService) {
this.rpcService = rpcService;
}
/**
* Returns system info.
*
* @return System info DTO wrapped in ResultDTO.
*/
@PostMapping(RequestMappings.M_V1 + RequestMappings.M_RPC_EVALUATE) | package io.dsntk.server.rest.controllers;
/**
* Java RPC controller.
*/
@Slf4j
@RestController
@RequestMapping(RequestMappings.M_RPC_SERVER)
public class RpcController {
private final RpcService rpcService;
/** Initializes RPC controller. */
public RpcController(RpcService rpcService) {
this.rpcService = rpcService;
}
/**
* Returns system info.
*
* @return System info DTO wrapped in ResultDTO.
*/
@PostMapping(RequestMappings.M_V1 + RequestMappings.M_RPC_EVALUATE) | public ResultDto<ValueDto> evaluate(@RequestBody RpcParams params) throws RpcException { | 2 | 2023-11-10 18:06:05+00:00 | 2k |
JohnTWD/meteor-rejects-vanillacpvp | src/main/java/anticope/rejects/modules/ArrowDmg.java | [
{
"identifier": "MeteorRejectsAddon",
"path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java",
"snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(... | import anticope.rejects.MeteorRejectsAddon;
import anticope.rejects.events.StopUsingItemEvent;
import meteordevelopment.meteorclient.settings.BoolSetting;
import meteordevelopment.meteorclient.settings.IntSetting;
import meteordevelopment.meteorclient.settings.Setting;
import meteordevelopment.meteorclient.settings.SettingGroup;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; | 1,595 | package anticope.rejects.modules;
public class ArrowDmg extends Module {
private final SettingGroup sgGeneral = settings.getDefaultGroup();
public final Setting<Integer> packets = sgGeneral.add(new IntSetting.Builder()
.name("packets")
.description("Amount of packets to send. More packets = higher damage.")
.defaultValue(200)
.min(2)
.sliderMax(2000)
.build()
);
public final Setting<Boolean> tridents = sgGeneral.add(new BoolSetting.Builder()
.name("tridents")
.description("When enabled, tridents fly much further. Doesn't seem to affect damage or Riptide. WARNING: You can easily lose your trident by enabling this option!")
.defaultValue(false)
.build()
);
public ArrowDmg() { | package anticope.rejects.modules;
public class ArrowDmg extends Module {
private final SettingGroup sgGeneral = settings.getDefaultGroup();
public final Setting<Integer> packets = sgGeneral.add(new IntSetting.Builder()
.name("packets")
.description("Amount of packets to send. More packets = higher damage.")
.defaultValue(200)
.min(2)
.sliderMax(2000)
.build()
);
public final Setting<Boolean> tridents = sgGeneral.add(new BoolSetting.Builder()
.name("tridents")
.description("When enabled, tridents fly much further. Doesn't seem to affect damage or Riptide. WARNING: You can easily lose your trident by enabling this option!")
.defaultValue(false)
.build()
);
public ArrowDmg() { | super(MeteorRejectsAddon.CATEGORY, "arrow-damage", "Massively increases arrow damage, but also consumes a lot of hunger and reduces accuracy. Does not work with crossbows and seems to be patched on Paper servers."); | 0 | 2023-11-13 08:11:28+00:00 | 2k |
cosmah/database | src/main/java/com/example/application/service/WorkerService.java | [
{
"identifier": "UserNotFoundException",
"path": "src/main/java/com/example/application/exceptions/UserNotFoundException.java",
"snippet": "public class UserNotFoundException extends RuntimeException {\n public UserNotFoundException(String message) {\n super(message);\n }\n}"
},
{
"... | import com.example.application.exceptions.UserNotFoundException;
import com.example.application.model.Worker;
import com.example.application.repository.WorkerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID; | 738 | package com.example.application.service;
@Service
public class WorkerService {
private final WorkerRepository workerRepository;
@Autowired
public WorkerService(WorkerRepository workerRepository) {
this.workerRepository = workerRepository;
}
| package com.example.application.service;
@Service
public class WorkerService {
private final WorkerRepository workerRepository;
@Autowired
public WorkerService(WorkerRepository workerRepository) {
this.workerRepository = workerRepository;
}
| public Worker addWorker(Worker worker){ | 1 | 2023-11-18 09:36:32+00:00 | 2k |
WallasAR/GUITest | src/main/java/com/example/guitest/RecordController.java | [
{
"identifier": "RecordTable",
"path": "src/main/java/com/table/view/RecordTable.java",
"snippet": "public class RecordTable {\n private int idR;\n private String userR;\n private String medicineR;\n private int amountR;\n private float priceR;\n private String dateR;\n\n public Rec... | import com.table.view.RecordTable;
import com.warning.alert.AlertMsg;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import static com.db.bank.Banco.connection; | 1,074 | package com.example.guitest;
public class RecordController implements Initializable {
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void HomeAction(MouseEvent e) {
Main.changedScene("home");
}
@FXML
protected void FuncAction(MouseEvent e) {
Main.changedScene("func");
}
@FXML
protected void MedAction(MouseEvent e) {
Main.changedScene("med");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("client");
}
@FXML
private TableColumn tcDateRecord;
@FXML
private TableColumn tcIdRecord;
@FXML
private TableColumn tcMedRecord;
@FXML
private TableColumn tcPriceRecord;
@FXML
private TableColumn tcQuantRecord;
@FXML
private TableColumn tcUserRecord;
@FXML
private TableView tvRecord;
public void tableRecord()throws SQLException {
List<RecordTable> order = new ArrayList<>();
String consultaSQLregistro = "SELECT * FROM registros"; | package com.example.guitest;
public class RecordController implements Initializable {
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void HomeAction(MouseEvent e) {
Main.changedScene("home");
}
@FXML
protected void FuncAction(MouseEvent e) {
Main.changedScene("func");
}
@FXML
protected void MedAction(MouseEvent e) {
Main.changedScene("med");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("client");
}
@FXML
private TableColumn tcDateRecord;
@FXML
private TableColumn tcIdRecord;
@FXML
private TableColumn tcMedRecord;
@FXML
private TableColumn tcPriceRecord;
@FXML
private TableColumn tcQuantRecord;
@FXML
private TableColumn tcUserRecord;
@FXML
private TableView tvRecord;
public void tableRecord()throws SQLException {
List<RecordTable> order = new ArrayList<>();
String consultaSQLregistro = "SELECT * FROM registros"; | Statement statement = connection.createStatement(); | 2 | 2023-11-16 14:55:08+00:00 | 2k |
wzh933/Buffer-Manager | src/test/java/cs/adb/wzh/bufferManager/BMgrTest.java | [
{
"identifier": "Buffer",
"path": "src/main/java/cs/adb/wzh/Storage/Buffer.java",
"snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n ... | import cs.adb.wzh.Storage.Buffer;
import cs.adb.wzh.Storage.Disk;
import cs.adb.wzh.bufferControlBlocks.BCB;
import cs.adb.wzh.utils.PageRequestReader;
import cs.adb.wzh.utils.SwapMethod;
import org.junit.jupiter.api.Test; | 1,382 | package cs.adb.wzh.bufferManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
class BMgrTest {
@Test
void bMgrTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk); | package cs.adb.wzh.bufferManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
class BMgrTest {
@Test
void bMgrTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk); | for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) { | 2 | 2023-11-15 16:30:06+00:00 | 2k |
UselessBullets/DragonFly | src/main/java/useless/dragonfly/DragonFly.java | [
{
"identifier": "DebugMain",
"path": "src/main/java/useless/dragonfly/debug/DebugMain.java",
"snippet": "public class DebugMain {\n\tpublic static void init(){\n\t\tItemHelper.createItem(DragonFly.MOD_ID, new ItemDebugStick(\"debug\", 21000), \"debug\").setIconCoord(4, 10);\n\t\tDebugBlocks.init();\n\t\... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.render.TextureFX;
import net.minecraft.core.Global;
import net.minecraft.core.util.helper.Side;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import turniplabs.halplibe.util.GameStartEntrypoint;
import useless.dragonfly.debug.DebugMain;
import useless.dragonfly.model.entity.animation.Animation;
import useless.dragonfly.model.entity.animation.AnimationDeserializer; | 1,562 | package useless.dragonfly;
public class DragonFly implements GameStartEntrypoint {
public static final String MOD_ID = "dragonfly";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static final Gson GSON = new GsonBuilder().registerTypeAdapter(Animation.class, new AnimationDeserializer()).create();
public static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST};
public static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES;
public static String version;
public static boolean isDev;
public static String renderState = "gui";
static {
version = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString();
isDev = version.equals("${version}") || version.contains("dev");
}
@Override
public void beforeGameStart() {
if (isDev){
LOGGER.info("DragonFly " + version + " loading debug assets"); | package useless.dragonfly;
public class DragonFly implements GameStartEntrypoint {
public static final String MOD_ID = "dragonfly";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static final Gson GSON = new GsonBuilder().registerTypeAdapter(Animation.class, new AnimationDeserializer()).create();
public static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST};
public static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES;
public static String version;
public static boolean isDev;
public static String renderState = "gui";
static {
version = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString();
isDev = version.equals("${version}") || version.contains("dev");
}
@Override
public void beforeGameStart() {
if (isDev){
LOGGER.info("DragonFly " + version + " loading debug assets"); | DebugMain.init(); | 0 | 2023-11-16 01:10:52+00:00 | 2k |
AntonyCheng/ai-bi | src/main/java/top/sharehome/springbootinittemplate/config/caffeine/CaffeineConfiguration.java | [
{
"identifier": "CaffeineCondition",
"path": "src/main/java/top/sharehome/springbootinittemplate/config/caffeine/condition/CaffeineCondition.java",
"snippet": "public class CaffeineCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetada... | import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import top.sharehome.springbootinittemplate.config.caffeine.condition.CaffeineCondition;
import top.sharehome.springbootinittemplate.config.caffeine.properties.CaffeineProperties;
import top.sharehome.springbootinittemplate.config.redisson.condition.RedissonCondition;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit; | 683 | package top.sharehome.springbootinittemplate.config.caffeine;
/**
* Caffeine配置
*
* @author AntonyCheng
*/
@Configuration
@EnableConfigurationProperties(CaffeineProperties.class)
@AllArgsConstructor
@Slf4j | package top.sharehome.springbootinittemplate.config.caffeine;
/**
* Caffeine配置
*
* @author AntonyCheng
*/
@Configuration
@EnableConfigurationProperties(CaffeineProperties.class)
@AllArgsConstructor
@Slf4j | @Conditional(CaffeineCondition.class) | 0 | 2023-11-12 07:49:59+00:00 | 2k |
rmheuer/azalea | azalea-core/src/main/java/com/github/rmheuer/azalea/render/opengl/OpenGLShaderProgram.java | [
{
"identifier": "ShaderProgram",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/shader/ShaderProgram.java",
"snippet": "public interface ShaderProgram extends SafeCloseable {\n}"
},
{
"identifier": "ShaderStage",
"path": "azalea-core/src/main/java/com/github/rmheuer/azal... | import com.github.rmheuer.azalea.render.shader.ShaderProgram;
import com.github.rmheuer.azalea.render.shader.ShaderStage;
import com.github.rmheuer.azalea.render.shader.ShaderUniform;
import org.joml.Matrix4fc;
import org.joml.Vector2fc;
import org.joml.Vector3fc;
import org.joml.Vector4fc;
import org.lwjgl.system.MemoryStack;
import java.nio.FloatBuffer;
import java.util.HashMap;
import java.util.Map;
import static org.lwjgl.opengl.GL33C.*; | 725 | package com.github.rmheuer.azalea.render.opengl;
public final class OpenGLShaderProgram implements ShaderProgram {
private final int id;
private final Map<String, ShaderUniform> uniforms;
| package com.github.rmheuer.azalea.render.opengl;
public final class OpenGLShaderProgram implements ShaderProgram {
private final int id;
private final Map<String, ShaderUniform> uniforms;
| public OpenGLShaderProgram(ShaderStage[] stages) { | 1 | 2023-11-16 04:46:53+00:00 | 2k |
jmgarridopaz/tienda-hexa | src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/configurador/TiendaHexaConfiguracion.java | [
{
"identifier": "ClienteService",
"path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/negocio/ClienteService.java",
"snippet": "public interface ClienteService {\n\n\tpublic void darAltaCliente ( String email, String nombre );\n\n\tpublic List<Cliente> obtenerTodosClientes();\n\t\n}"
},
{
... | import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteService;
import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteServiceImpl;
import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteStore;
import es.uhu.etsi.tallerhexagonal.tiendahexa.persistencia.ClienteRepository;
import es.uhu.etsi.tallerhexagonal.tiendahexa.persistencia.ConversorStoreSpringJpa; | 1,104 | package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador;
@Configuration
public class TiendaHexaConfiguracion {
@Bean
public ClienteStore clienteStore ( ClienteRepository clienteRepository) {
return new ConversorStoreSpringJpa(clienteRepository);
}
@Bean
public ClienteService clienteService ( ClienteStore clienteStore ) { | package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador;
@Configuration
public class TiendaHexaConfiguracion {
@Bean
public ClienteStore clienteStore ( ClienteRepository clienteRepository) {
return new ConversorStoreSpringJpa(clienteRepository);
}
@Bean
public ClienteService clienteService ( ClienteStore clienteStore ) { | return new ClienteServiceImpl(clienteStore); | 1 | 2023-11-18 12:57:56+00:00 | 2k |
orijer/IvritInterpreter | src/FlowController.java | [
{
"identifier": "GeneralFileRuntimeException",
"path": "src/IvritExceptions/GeneralFileRuntimeException.java",
"snippet": "public class GeneralFileRuntimeException extends UncheckedIOException {\r\n /**\r\n * Constructor.\r\n * @param cause - What caused this exception.\r\n */\r\n publ... | import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import IvritExceptions.GeneralFileRuntimeException;
import UserInput.UserInput;
import IvritStreams.RestartableReader;
import IvritStreams.RestartableBufferedReader;
| 1,504 |
/**
* Handles controlling the flow of the Interpretor.
*/
public class FlowController {
private UserInput userInput;
//The GUI of the console that the Interpreter uses:
private IvritInterpreterGUI gui;
/**
* Constructor.
*/
public FlowController() {
this.userInput = new UserInput();
this.gui = new IvritInterpreterGUI(this.userInput);
}
/**
* Contains the logic for starting the interpreting process.
* @throws GeneralFileRuntimeException when an exception that cannot be traces happened during runtime.
*/
public void startIvritInterpreter(boolean isFirstRun) {
//We first try to load the file to interpret:
File sourceFile;
try {
sourceFile = handleFileLoad(isFirstRun);
if (sourceFile == null) //sourceFile is null IFF the user requested to end the program.
return;
} catch (Exception exception) {
//If we get an exception, print it and try again:
System.out.println("נתקלנו בשגיאה לא מוכרת בזמן השגת כתובת ההרצה");
System.out.println("ננסה מחדש:");
startIvritInterpreter(isFirstRun);
return;
}
//A simple test to see that the loading works correctly:
|
/**
* Handles controlling the flow of the Interpretor.
*/
public class FlowController {
private UserInput userInput;
//The GUI of the console that the Interpreter uses:
private IvritInterpreterGUI gui;
/**
* Constructor.
*/
public FlowController() {
this.userInput = new UserInput();
this.gui = new IvritInterpreterGUI(this.userInput);
}
/**
* Contains the logic for starting the interpreting process.
* @throws GeneralFileRuntimeException when an exception that cannot be traces happened during runtime.
*/
public void startIvritInterpreter(boolean isFirstRun) {
//We first try to load the file to interpret:
File sourceFile;
try {
sourceFile = handleFileLoad(isFirstRun);
if (sourceFile == null) //sourceFile is null IFF the user requested to end the program.
return;
} catch (Exception exception) {
//If we get an exception, print it and try again:
System.out.println("נתקלנו בשגיאה לא מוכרת בזמן השגת כתובת ההרצה");
System.out.println("ננסה מחדש:");
startIvritInterpreter(isFirstRun);
return;
}
//A simple test to see that the loading works correctly:
| try (RestartableReader reader = new RestartableBufferedReader(sourceFile)) {
| 3 | 2023-11-17 09:15:07+00:00 | 2k |
WuKongOpenSource/Wukong_HRM | hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmSalarySlipTemplateOptionController.java | [
{
"identifier": "Result",
"path": "common/common-web/src/main/java/com/kakarote/core/common/Result.java",
"snippet": "public class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"code\", required = true, example = \"0\")\n ... | import com.kakarote.core.common.Result;
import com.kakarote.hrm.entity.PO.HrmSalarySlipTemplateOption;
import com.kakarote.hrm.service.IHrmSalarySlipTemplateOptionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; | 1,485 | package com.kakarote.hrm.controller;
/**
* <p>
* 工资条模板项 前端控制器
* </p>
*
* @author hmb
* @since 2020-11-03
*/
@RestController
@RequestMapping("/hrmSalarySlipTemplateOption")
@Api(tags = "工资条-工资条模板项接口")
public class HrmSalarySlipTemplateOptionController {
@Autowired
private IHrmSalarySlipTemplateOptionService slipTemplateOptionService;
@PostMapping("/queryTemplateOptionByTemplateId/{templateId}")
@ApiOperation("查询工资模板项") | package com.kakarote.hrm.controller;
/**
* <p>
* 工资条模板项 前端控制器
* </p>
*
* @author hmb
* @since 2020-11-03
*/
@RestController
@RequestMapping("/hrmSalarySlipTemplateOption")
@Api(tags = "工资条-工资条模板项接口")
public class HrmSalarySlipTemplateOptionController {
@Autowired
private IHrmSalarySlipTemplateOptionService slipTemplateOptionService;
@PostMapping("/queryTemplateOptionByTemplateId/{templateId}")
@ApiOperation("查询工资模板项") | public Result<List<HrmSalarySlipTemplateOption>> queryTemplateOptionByTemplateId(@PathVariable("templateId") Long templateId) { | 0 | 2023-10-17 05:49:52+00:00 | 2k |
WisdomShell/codeshell-intellij | src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java | [
{
"identifier": "ChatMaxToken",
"path": "src/main/java/com/codeshell/intellij/enums/ChatMaxToken.java",
"snippet": "public enum ChatMaxToken {\n LOW(\"1024\"),\n MEDIUM(\"2048\"),\n HIGH(\"4096\"),\n ULTRA(\"8192\");\n\n private final String description;\n\n ChatMaxToken(String descrip... | import com.codeshell.intellij.enums.ChatMaxToken;
import com.codeshell.intellij.enums.CompletionMaxToken;
import com.codeshell.intellij.enums.TabActionOption;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects; | 688 | package com.codeshell.intellij.settings;
@State(name = "CodeShellSettings", storages = @Storage("codeshell_settings.xml"))
public class CodeShellSettings implements PersistentStateComponent<Element> {
public static final String SETTINGS_TAG = "CodeShellSettings";
private static final String SERVER_ADDRESS_TAG = "SERVER_ADDRESS_URL";
private static final String SAYT_TAG = "SAYT_ENABLED";
private static final String CPU_RADIO_BUTTON_TAG = "CPU_RADIO_BUTTON_ENABLED";
private static final String GPU_RADIO_BUTTON_TAG = "GPU_RADIO_BUTTON_ENABLED";
private static final String TAB_ACTION_TAG = "TAB_ACTION";
private static final String COMPLETION_MAX_TOKENS_TAG = "COMPLETION_MAX_TOKENS";
private static final String CHAT_MAX_TOKENS_TAG = "CHAT_MAX_TOKENS";
private boolean saytEnabled = true;
private boolean cpuRadioButtonEnabled = true;
private boolean gpuRadioButtonEnabled = false;
private String serverAddressURL = "http://127.0.0.1:8080";
private TabActionOption tabActionOption = TabActionOption.ALL;
private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM; | package com.codeshell.intellij.settings;
@State(name = "CodeShellSettings", storages = @Storage("codeshell_settings.xml"))
public class CodeShellSettings implements PersistentStateComponent<Element> {
public static final String SETTINGS_TAG = "CodeShellSettings";
private static final String SERVER_ADDRESS_TAG = "SERVER_ADDRESS_URL";
private static final String SAYT_TAG = "SAYT_ENABLED";
private static final String CPU_RADIO_BUTTON_TAG = "CPU_RADIO_BUTTON_ENABLED";
private static final String GPU_RADIO_BUTTON_TAG = "GPU_RADIO_BUTTON_ENABLED";
private static final String TAB_ACTION_TAG = "TAB_ACTION";
private static final String COMPLETION_MAX_TOKENS_TAG = "COMPLETION_MAX_TOKENS";
private static final String CHAT_MAX_TOKENS_TAG = "CHAT_MAX_TOKENS";
private boolean saytEnabled = true;
private boolean cpuRadioButtonEnabled = true;
private boolean gpuRadioButtonEnabled = false;
private String serverAddressURL = "http://127.0.0.1:8080";
private TabActionOption tabActionOption = TabActionOption.ALL;
private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM; | private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM; | 0 | 2023-10-18 06:29:13+00:00 | 2k |
djkcyl/Shamrock | qqinterface/src/main/java/tencent/im/msg/im_msg_body.java | [
{
"identifier": "ByteStringMicro",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java",
"snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return ... | import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBRepeatMessageField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.mobileqq.pb.PBUInt64Field; | 1,571 | package tencent.im.msg;
public class im_msg_body {
public static class MsgBody extends MessageMicro<MsgBody> {
public final PBBytesField msg_content;
public final PBBytesField msg_encrypt_content;
public RichText rich_text = new RichText();
public MsgBody() {
ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY;
this.msg_content = PBField.initBytes(byteStringMicro);
this.msg_encrypt_content = PBField.initBytes(byteStringMicro);
}
}
public static class RichText extends MessageMicro<RichText> {
//public im_msg_body$Attr attr = new im_msg_body$Attr(); | package tencent.im.msg;
public class im_msg_body {
public static class MsgBody extends MessageMicro<MsgBody> {
public final PBBytesField msg_content;
public final PBBytesField msg_encrypt_content;
public RichText rich_text = new RichText();
public MsgBody() {
ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY;
this.msg_content = PBField.initBytes(byteStringMicro);
this.msg_encrypt_content = PBField.initBytes(byteStringMicro);
}
}
public static class RichText extends MessageMicro<RichText> {
//public im_msg_body$Attr attr = new im_msg_body$Attr(); | public final PBRepeatMessageField<Elem> elems = PBField.initRepeatMessage(Elem.class); | 4 | 2023-10-20 10:43:47+00:00 | 2k |
ballerina-platform/module-ballerinax-copybook | commons/src/main/java/io/ballerina/lib/copybook/commons/schema/LengthCalculator.java | [
{
"identifier": "isAlphaNumeric",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java",
"snippet": "static boolean isAlphaNumeric(String pictureString) {\n // ex: PIC XXX\n return Pattern.compile(\"^X+$\").matcher(pictureString).find();\n}"
},
{
... | import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isAlphaNumeric;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isAlphaNumericWithCardinality;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimal;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimalWithCardinality;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimalWithSuppressedZeros;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isInt;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isIntWithCardinality;
import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isSignRememberedIntWithCardinality; | 1,116 | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.lib.copybook.commons.schema;
class LengthCalculator {
private LengthCalculator() {
}
static int calculateFractionLength(String pictureString) {
if (!isDecimal(pictureString) && !isDecimalWithCardinality(pictureString) && !isDecimalWithSuppressedZeros(
pictureString)) {
return 0;
}
Matcher matcher = Pattern.compile("^.*\\.(?<fraction>9+)$").matcher(pictureString);
if (matcher.find()) {
return matcher.group("fraction").length();
}
return 0;
}
static int calculateReadLength(String pictureString) {
if (isAlphaNumeric(pictureString) || isInt(pictureString) || isDecimal(pictureString)) {
return pictureString.length();
}
| /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.lib.copybook.commons.schema;
class LengthCalculator {
private LengthCalculator() {
}
static int calculateFractionLength(String pictureString) {
if (!isDecimal(pictureString) && !isDecimalWithCardinality(pictureString) && !isDecimalWithSuppressedZeros(
pictureString)) {
return 0;
}
Matcher matcher = Pattern.compile("^.*\\.(?<fraction>9+)$").matcher(pictureString);
if (matcher.find()) {
return matcher.group("fraction").length();
}
return 0;
}
static int calculateReadLength(String pictureString) {
if (isAlphaNumeric(pictureString) || isInt(pictureString) || isDecimal(pictureString)) {
return pictureString.length();
}
| if (isAlphaNumericWithCardinality(pictureString)) { | 1 | 2023-10-24 04:51:53+00:00 | 2k |
ballerina-platform/copybook-tools | copybook-cli/src/main/java/io/ballerina/tools/copybook/utils/Utils.java | [
{
"identifier": "DiagnosticMessages",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/diagnostic/DiagnosticMessages.java",
"snippet": "public enum DiagnosticMessages {\n COPYBOOK_TYPE_GEN_100(\"COPYBOOK_TYPE_GEN_100\", \"Copybook types generation failed: The input file path argument\"... | import static io.ballerina.tools.copybook.generator.GeneratorConstants.PERIOD;
import io.ballerina.tools.copybook.diagnostic.DiagnosticMessages;
import io.ballerina.tools.copybook.exception.CopybookTypeGenerationException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Objects; | 1,274 | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.tools.copybook.utils;
public class Utils {
private Utils() {
}
public static boolean createOutputDirectory(Path outputPath) {
File outputDir = new File(outputPath.toString());
if (!outputDir.exists()) {
return outputDir.mkdirs();
}
return true;
}
public static void writeFile(Path filePath, String content) throws CopybookTypeGenerationException {
try (FileWriter writer = new FileWriter(filePath.toString(), StandardCharsets.UTF_8)) {
writer.write(content);
} catch (IOException e) {
throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.getMessage());
}
}
public static String resolveSchemaFileName(Path outPath, String fileName) {
if (outPath != null && Files.exists(outPath)) {
final File[] listFiles = new File(String.valueOf(outPath)).listFiles();
if (listFiles != null) {
fileName = checkAvailabilityOfGivenName(fileName, listFiles);
}
}
return fileName;
}
private static String checkAvailabilityOfGivenName(String schemaName, File[] listFiles) {
for (File file : listFiles) {
if (System.console() != null && file.getName().equals(schemaName)) {
String userInput = System.console().readLine("There is already a file named '" + file.getName() +
"' in the target location. Do you want to overwrite the file? [y/N] ");
if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) {
schemaName = setGeneratedFileName(listFiles, schemaName);
}
}
}
return schemaName;
}
private static String setGeneratedFileName(File[] listFiles, String fileName) {
int duplicateCount = 0;
for (File listFile : listFiles) {
String listFileName = listFile.getName();
if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2)
&& (listFileName.split("\\.")[0].equals(fileName.split("\\.")[0]))) {
duplicateCount++;
}
} | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.tools.copybook.utils;
public class Utils {
private Utils() {
}
public static boolean createOutputDirectory(Path outputPath) {
File outputDir = new File(outputPath.toString());
if (!outputDir.exists()) {
return outputDir.mkdirs();
}
return true;
}
public static void writeFile(Path filePath, String content) throws CopybookTypeGenerationException {
try (FileWriter writer = new FileWriter(filePath.toString(), StandardCharsets.UTF_8)) {
writer.write(content);
} catch (IOException e) {
throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.getMessage());
}
}
public static String resolveSchemaFileName(Path outPath, String fileName) {
if (outPath != null && Files.exists(outPath)) {
final File[] listFiles = new File(String.valueOf(outPath)).listFiles();
if (listFiles != null) {
fileName = checkAvailabilityOfGivenName(fileName, listFiles);
}
}
return fileName;
}
private static String checkAvailabilityOfGivenName(String schemaName, File[] listFiles) {
for (File file : listFiles) {
if (System.console() != null && file.getName().equals(schemaName)) {
String userInput = System.console().readLine("There is already a file named '" + file.getName() +
"' in the target location. Do you want to overwrite the file? [y/N] ");
if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) {
schemaName = setGeneratedFileName(listFiles, schemaName);
}
}
}
return schemaName;
}
private static String setGeneratedFileName(File[] listFiles, String fileName) {
int duplicateCount = 0;
for (File listFile : listFiles) {
String listFileName = listFile.getName();
if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2)
&& (listFileName.split("\\.")[0].equals(fileName.split("\\.")[0]))) {
duplicateCount++;
}
} | return fileName.split("\\.")[0] + PERIOD + duplicateCount + PERIOD + fileName.split("\\.")[1]; | 2 | 2023-10-24 05:00:08+00:00 | 2k |
zhaoeryu/eu-backend | eu-admin/src/main/java/cn/eu/system/service/ISysRoleService.java | [
{
"identifier": "IEuService",
"path": "eu-common-core/src/main/java/cn/eu/common/base/service/IEuService.java",
"snippet": "public interface IEuService<T> extends IService<T> {\n\n}"
},
{
"identifier": "PageResult",
"path": "eu-common-core/src/main/java/cn/eu/common/model/PageResult.java",
... | import cn.eu.common.base.service.IEuService;
import cn.eu.common.model.PageResult;
import cn.eu.system.domain.SysRole;
import cn.eu.system.model.dto.ImportResult;
import cn.eu.system.model.dto.SysRoleDto;
import cn.eu.system.model.query.SysRoleQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; | 966 | package cn.eu.system.service;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
public interface ISysRoleService extends IEuService<SysRole> {
PageResult<SysRole> page(SysRoleQueryCriteria criteria, Pageable pageable);
List<SysRole> list(SysRoleQueryCriteria criteria);
List<String> getRolePermissionByUserId(String userId);
List<SysRole> getRolesByUserId(String userId);
List<Integer> getRoleIdsByUserId(String userId);
void createRole(SysRoleDto entity);
void updateRole(SysRoleDto entity);
List<Integer> getMenuIdsByRoleId(Integer roleId);
List<Integer> getDeptIdsByRoleId(Integer roleId);
void exportTemplate(HttpServletResponse response) throws IOException;
| package cn.eu.system.service;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
public interface ISysRoleService extends IEuService<SysRole> {
PageResult<SysRole> page(SysRoleQueryCriteria criteria, Pageable pageable);
List<SysRole> list(SysRoleQueryCriteria criteria);
List<String> getRolePermissionByUserId(String userId);
List<SysRole> getRolesByUserId(String userId);
List<Integer> getRoleIdsByUserId(String userId);
void createRole(SysRoleDto entity);
void updateRole(SysRoleDto entity);
List<Integer> getMenuIdsByRoleId(Integer roleId);
List<Integer> getDeptIdsByRoleId(Integer roleId);
void exportTemplate(HttpServletResponse response) throws IOException;
| ImportResult importData(MultipartFile file, Integer importMode) throws IOException; | 3 | 2023-10-20 07:08:37+00:00 | 2k |
Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/client/GTCMCreativeTabs.java | [
{
"identifier": "texter",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextHandler.java",
"snippet": "public static String texter(String aTextLine, String aKey) {\n\n /**\n * If not in Dev mode , return vanilla forge method directly.\n */\n if (TwistSpaceTechnology.isInDevMode... | import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import com.Nxer.TwistSpaceTechnology.common.item.items.BasicItems;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | 658 | package com.Nxer.TwistSpaceTechnology.client;
public class GTCMCreativeTabs {
/**
* Creative Tab for MetaItem01
*/
public static final CreativeTabs tabMetaItem01 = new CreativeTabs(
texter("TST Meta Items 1", "itemGroup.TST Meta Items 1")) {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() { | package com.Nxer.TwistSpaceTechnology.client;
public class GTCMCreativeTabs {
/**
* Creative Tab for MetaItem01
*/
public static final CreativeTabs tabMetaItem01 = new CreativeTabs(
texter("TST Meta Items 1", "itemGroup.TST Meta Items 1")) {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() { | return BasicItems.MetaItem01; | 1 | 2023-10-16 09:57:15+00:00 | 2k |
wyjsonGo/GoRouter | GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/processor/GenerateApplicationModuleProcessor.java | [
{
"identifier": "APPLICATION",
"path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java",
"snippet": "public static final String APPLICATION = \"android.app.Application\";"
},
{
"identifier": "APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX",
"path": "GoRouter-C... | import static com.wyjson.router.compiler.utils.Constants.APPLICATION;
import static com.wyjson.router.compiler.utils.Constants.APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX;
import static com.wyjson.router.compiler.utils.Constants.APPLICATION_MODULE_PACKAGE_NAME;
import static com.wyjson.router.compiler.utils.Constants.CONFIGURATION;
import static com.wyjson.router.compiler.utils.Constants.CONTEXT;
import static com.wyjson.router.compiler.utils.Constants.FIELD_MAM;
import static com.wyjson.router.compiler.utils.Constants.I_APPLICATION_MODULE_PACKAGE_NAME;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_CONFIGURATION_CHANGED;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_CREATE;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_LOAD_ASYNC;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_LOW_MEMORY;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_TERMINATE;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_TRIM_MEMORY;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_SET_PRIORITY;
import static com.wyjson.router.compiler.utils.Constants.NONNULL;
import static com.wyjson.router.compiler.utils.Constants.PREFIX_OF_LOGGER;
import static com.wyjson.router.compiler.utils.Constants.WARNING_TIPS;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.wyjson.router.annotation.ApplicationModule;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror; | 1,501 | package com.wyjson.router.compiler.processor;
@AutoService(Processor.class)
public class GenerateApplicationModuleProcessor extends BaseProcessor {
TypeMirror mApplication;
TypeMirror mContext;
TypeMirror mConfiguration;
TypeElement mNONNULL;
TypeElement mIApplicationModule;
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(ApplicationModule.class.getCanonicalName());
return set;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
logger.info(moduleName + " >>> GenerateApplicationModuleProcessor init. <<<");
mApplication = elementUtils.getTypeElement(APPLICATION).asType();
mContext = elementUtils.getTypeElement(CONTEXT).asType();
mConfiguration = elementUtils.getTypeElement(CONFIGURATION).asType();
mNONNULL = elementUtils.getTypeElement(NONNULL);
mIApplicationModule = elementUtils.getTypeElement(I_APPLICATION_MODULE_PACKAGE_NAME);
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isEmpty(set))
return false;
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ApplicationModule.class);
if (CollectionUtils.isEmpty(elements))
return false;
logger.info(moduleName + " >>> Found ApplicationModule, size is " + elements.size() + " <<<");
for (Element element : elements) {
verify(element);
String applicationModuleClassName = ((TypeElement) element).getQualifiedName().toString();
String className = String.format(APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX, generateClassName, element.getSimpleName().toString());
TypeSpec.Builder thisClass = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.addSuperinterface(ClassName.get(mIApplicationModule)) | package com.wyjson.router.compiler.processor;
@AutoService(Processor.class)
public class GenerateApplicationModuleProcessor extends BaseProcessor {
TypeMirror mApplication;
TypeMirror mContext;
TypeMirror mConfiguration;
TypeElement mNONNULL;
TypeElement mIApplicationModule;
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(ApplicationModule.class.getCanonicalName());
return set;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
logger.info(moduleName + " >>> GenerateApplicationModuleProcessor init. <<<");
mApplication = elementUtils.getTypeElement(APPLICATION).asType();
mContext = elementUtils.getTypeElement(CONTEXT).asType();
mConfiguration = elementUtils.getTypeElement(CONFIGURATION).asType();
mNONNULL = elementUtils.getTypeElement(NONNULL);
mIApplicationModule = elementUtils.getTypeElement(I_APPLICATION_MODULE_PACKAGE_NAME);
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isEmpty(set))
return false;
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ApplicationModule.class);
if (CollectionUtils.isEmpty(elements))
return false;
logger.info(moduleName + " >>> Found ApplicationModule, size is " + elements.size() + " <<<");
for (Element element : elements) {
verify(element);
String applicationModuleClassName = ((TypeElement) element).getQualifiedName().toString();
String className = String.format(APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX, generateClassName, element.getSimpleName().toString());
TypeSpec.Builder thisClass = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.addSuperinterface(ClassName.get(mIApplicationModule)) | .addJavadoc(WARNING_TIPS); | 16 | 2023-10-18 13:52:07+00:00 | 2k |
trpc-group/trpc-java | trpc-limiter/trpc-limiter-sentinel/src/test/java/com/tencent/trpc/limiter/sentinel/config/datasource/ZookeeperDatasourceConfigTest.java | [
{
"identifier": "LimiterDataSourceException",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/exception/LimiterDataSourceException.java",
"snippet": "public class LimiterDataSourceException extends LimiterException {\n\n public LimiterDataSourceException() {\n }\n\n public LimiterDataSou... | import com.tencent.trpc.core.exception.LimiterDataSourceException;
import com.tencent.trpc.limiter.sentinel.config.datasource.factory.DatasourceConfigFactoryManger;
import com.tencent.trpc.limiter.sentinel.config.datasource.factory.DatasourceType;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.curator.test.TestingServer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; | 1,123 | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.limiter.sentinel.config.datasource;
/**
* ZookeeperDatasourceConfig test class
*/
public class ZookeeperDatasourceConfigTest {
private ZookeeperDatasourceConfig zookeeperDatasourceConfig;
private TestingServer zkServer;
@Before
public void setUp() throws Exception {
int port = 2183;
zkServer = new TestingServer(port, new File("/tmp/sentinel"));
zkServer.start();
Map<String, Object> configMap = new HashMap<>();
configMap.put("remote_address", "127.0.0.1:" + port);
configMap.put("path", "/tmp/sentinel");
zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger
.getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap);
}
@Test
public void testRegister() {
zookeeperDatasourceConfig.register();
}
@Test
public void testValidate1() {
Map<String, Object> configMap = new HashMap<>();
configMap.put("path", "/tmp/sentinel");
zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger
.getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap);
try {
zookeeperDatasourceConfig.validate();
} catch (Exception e) { | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.limiter.sentinel.config.datasource;
/**
* ZookeeperDatasourceConfig test class
*/
public class ZookeeperDatasourceConfigTest {
private ZookeeperDatasourceConfig zookeeperDatasourceConfig;
private TestingServer zkServer;
@Before
public void setUp() throws Exception {
int port = 2183;
zkServer = new TestingServer(port, new File("/tmp/sentinel"));
zkServer.start();
Map<String, Object> configMap = new HashMap<>();
configMap.put("remote_address", "127.0.0.1:" + port);
configMap.put("path", "/tmp/sentinel");
zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger
.getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap);
}
@Test
public void testRegister() {
zookeeperDatasourceConfig.register();
}
@Test
public void testValidate1() {
Map<String, Object> configMap = new HashMap<>();
configMap.put("path", "/tmp/sentinel");
zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger
.getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap);
try {
zookeeperDatasourceConfig.validate();
} catch (Exception e) { | Assert.assertTrue(e instanceof LimiterDataSourceException); | 0 | 2023-10-19 10:54:11+00:00 | 2k |
freedom-introvert/YouTubeSendCommentAntiFraud | YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/HistoryCommentListAdapter.java | [
{
"identifier": "HistoryComment",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/HistoryComment.java",
"snippet": "public abstract class HistoryComment extends Comment{\r\n public static final String STATE_NORMAL = \"NORMAL\";\r\n public static fina... | import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment;
import icu.freedomintrovert.YTSendCommAntiFraud.view.VoidDialogInterfaceOnClickListener;
| 690 | package icu.freedomintrovert.YTSendCommAntiFraud;
public abstract class HistoryCommentListAdapter extends RecyclerView.Adapter<HistoryCommentListAdapter.ViewHolder> {
Context context;
| package icu.freedomintrovert.YTSendCommAntiFraud;
public abstract class HistoryCommentListAdapter extends RecyclerView.Adapter<HistoryCommentListAdapter.ViewHolder> {
Context context;
| List<? extends HistoryComment> commentList;
| 0 | 2023-10-15 01:18:28+00:00 | 2k |
New-Barams/This-Year-Ajaja-BE | src/test/java/com/newbarams/ajaja/module/user/application/RenewNicknameServiceTest.java | [
{
"identifier": "MockTestSupport",
"path": "src/test/java/com/newbarams/ajaja/common/support/MockTestSupport.java",
"snippet": "@ExtendWith(MockitoExtension.class)\npublic abstract class MockTestSupport extends MonkeySupport {\n}"
},
{
"identifier": "ApplyChangePort",
"path": "src/main/java/... | import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import com.newbarams.ajaja.common.support.MockTestSupport;
import com.newbarams.ajaja.module.user.application.port.out.ApplyChangePort;
import com.newbarams.ajaja.module.user.domain.Email;
import com.newbarams.ajaja.module.user.domain.Nickname;
import com.newbarams.ajaja.module.user.domain.User; | 1,264 | package com.newbarams.ajaja.module.user.application;
class RenewNicknameServiceTest extends MockTestSupport {
@InjectMocks
private RenewNicknameService renewNicknameService;
@Mock
private RetrieveUserService retrieveUserService;
@Mock
private ApplyChangePort applyChangePort;
@Test
@DisplayName("닉네임 갱신을 요청하면 새로운 이름으로 변경되어야 한다.")
void renew_Success_WithNewNickname() {
// given
User user = sut.giveMeBuilder(User.class) | package com.newbarams.ajaja.module.user.application;
class RenewNicknameServiceTest extends MockTestSupport {
@InjectMocks
private RenewNicknameService renewNicknameService;
@Mock
private RetrieveUserService retrieveUserService;
@Mock
private ApplyChangePort applyChangePort;
@Test
@DisplayName("닉네임 갱신을 요청하면 새로운 이름으로 변경되어야 한다.")
void renew_Success_WithNewNickname() {
// given
User user = sut.giveMeBuilder(User.class) | .set("email", new Email("Ajaja@me.com")) | 2 | 2023-10-23 07:24:17+00:00 | 2k |
eclipse-jgit/jgit | org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/CommitConfigTest.java | [
{
"identifier": "ConfigInvalidException",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/ConfigInvalidException.java",
"snippet": "public class ConfigInvalidException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Construct an invalid configuration error.\n... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitConfig.CleanupMode;
import org.junit.Test; | 669 | /*
* Copyright (C) 2022, Thomas Wolf <thomas.wolf@paranor.ch> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.lib;
public class CommitConfigTest {
@Test
public void testDefaults() throws Exception {
CommitConfig cfg = parse(""); | /*
* Copyright (C) 2022, Thomas Wolf <thomas.wolf@paranor.ch> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.lib;
public class CommitConfigTest {
@Test
public void testDefaults() throws Exception {
CommitConfig cfg = parse(""); | assertEquals("Unexpected clean-up mode", CleanupMode.DEFAULT, | 1 | 2023-10-20 15:09:17+00:00 | 2k |
starfish-studios/Naturalist | common/src/main/java/com/starfish_studios/naturalist/client/renderer/CatfishRenderer.java | [
{
"identifier": "CatfishModel",
"path": "common/src/main/java/com/starfish_studios/naturalist/client/model/CatfishModel.java",
"snippet": "@Environment(EnvType.CLIENT)\npublic class CatfishModel extends AnimatedGeoModel<Catfish> {\n @Override\n public ResourceLocation getModelResource(Catfish catf... | import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.starfish_studios.naturalist.client.model.CatfishModel;
import com.starfish_studios.naturalist.common.entity.Catfish;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import software.bernie.geckolib3.renderers.geo.GeoEntityRenderer; | 1,244 | package com.starfish_studios.naturalist.client.renderer;
@Environment(EnvType.CLIENT)
public class CatfishRenderer extends GeoEntityRenderer<Catfish> {
public CatfishRenderer(EntityRendererProvider.Context renderManager) { | package com.starfish_studios.naturalist.client.renderer;
@Environment(EnvType.CLIENT)
public class CatfishRenderer extends GeoEntityRenderer<Catfish> {
public CatfishRenderer(EntityRendererProvider.Context renderManager) { | super(renderManager, new CatfishModel()); | 0 | 2023-10-16 21:54:32+00:00 | 2k |
instana/otel-dc | host/src/main/java/com/instana/dc/host/impl/HostDcRegistry.java | [
{
"identifier": "AbstractHostDc",
"path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java",
"snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final St... | import java.util.HashMap;
import java.util.Map;
import com.instana.dc.host.AbstractHostDc;
import com.instana.dc.DcException; | 934 | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class HostDcRegistry {
/* Add all DataCollector implementations here:
**/
private final Map<String, Class<? extends AbstractHostDc>> map = new HashMap<String, Class<? extends AbstractHostDc>>() {{
put("SIMP_HOST", SimpHostDc.class);
}};
| /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class HostDcRegistry {
/* Add all DataCollector implementations here:
**/
private final Map<String, Class<? extends AbstractHostDc>> map = new HashMap<String, Class<? extends AbstractHostDc>>() {{
put("SIMP_HOST", SimpHostDc.class);
}};
| public Class<? extends AbstractHostDc> findHostDc(String hostSystem) throws DcException { | 1 | 2023-10-23 01:16:38+00:00 | 2k |
quarkiverse/quarkus-antivirus | integration-tests/src/main/java/io/quarkiverse/antivirus/it/AntivirusResource.java | [
{
"identifier": "Antivirus",
"path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/Antivirus.java",
"snippet": "@ApplicationScoped\n@JBossLog\npublic class Antivirus {\n\n @Inject\n private Instance<AntivirusEngine> engineInstances;\n\n /**\n * Perform virus scan and throw excepti... | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import io.quarkiverse.antivirus.runtime.Antivirus;
import io.quarkiverse.antivirus.runtime.AntivirusException;
import io.quarkiverse.antivirus.runtime.AntivirusScanResult; | 958 | package io.quarkiverse.antivirus.it;
@Path("/antivirus")
@ApplicationScoped
public class AntivirusResource {
@Inject
Antivirus antivirus;
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/upload")
public List<AntivirusScanResult> upload(@MultipartForm @Valid final UploadRequest fileUploadRequest) {
final String fileName = fileUploadRequest.getFileName();
final InputStream data = fileUploadRequest.getData();
try {
// copy the stream to make it resettable
final ByteArrayInputStream inputStream = new ByteArrayInputStream(
IOUtils.toBufferedInputStream(data).readAllBytes());
// scan the file and check the results
return antivirus.scan(fileName, inputStream); | package io.quarkiverse.antivirus.it;
@Path("/antivirus")
@ApplicationScoped
public class AntivirusResource {
@Inject
Antivirus antivirus;
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/upload")
public List<AntivirusScanResult> upload(@MultipartForm @Valid final UploadRequest fileUploadRequest) {
final String fileName = fileUploadRequest.getFileName();
final InputStream data = fileUploadRequest.getData();
try {
// copy the stream to make it resettable
final ByteArrayInputStream inputStream = new ByteArrayInputStream(
IOUtils.toBufferedInputStream(data).readAllBytes());
// scan the file and check the results
return antivirus.scan(fileName, inputStream); | } catch (AntivirusException | IOException e) { | 1 | 2023-10-22 22:33:05+00:00 | 2k |
Team3256/FRC_MockSeason_2023 | src/main/java/frc/robot/RobotContainer.java | [
{
"identifier": "OperatorConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static class OperatorConstants {\n public static final int kDriverControllerPort = 0;\n}"
},
{
"identifier": "Autos",
"path": "src/main/java/frc/robot/commands/Autos.java",
"snippet... | import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import edu.wpi.first.wpilibj2.command.button.Trigger;
import frc.robot.Constants.OperatorConstants;
import frc.robot.commands.Autos;
import frc.robot.commands.ExampleCommand;
import frc.robot.subsystems.ExampleSubsystem; | 1,167 | // Copyright (c) 2023 FRC 3256
// https://github.com/Team3256
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file at
// the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
// The robot's subsystems and commands are defined here...
private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem();
// Replace with CommandPS4Controller or CommandJoystick if needed
private final CommandXboxController m_driverController =
new CommandXboxController(OperatorConstants.kDriverControllerPort);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
// Configure the trigger bindings
configureBindings();
}
/**
* Use this method to define your trigger->command mappings. Triggers can be created via the
* {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
* predicate, or via the named factories in {@link
* edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link
* CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller
* PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight
* joysticks}.
*/
private void configureBindings() {
// Schedule `ExampleCommand` when `exampleCondition` changes to `true`
new Trigger(m_exampleSubsystem::exampleCondition) | // Copyright (c) 2023 FRC 3256
// https://github.com/Team3256
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file at
// the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
// The robot's subsystems and commands are defined here...
private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem();
// Replace with CommandPS4Controller or CommandJoystick if needed
private final CommandXboxController m_driverController =
new CommandXboxController(OperatorConstants.kDriverControllerPort);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
// Configure the trigger bindings
configureBindings();
}
/**
* Use this method to define your trigger->command mappings. Triggers can be created via the
* {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
* predicate, or via the named factories in {@link
* edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link
* CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller
* PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight
* joysticks}.
*/
private void configureBindings() {
// Schedule `ExampleCommand` when `exampleCondition` changes to `true`
new Trigger(m_exampleSubsystem::exampleCondition) | .onTrue(new ExampleCommand(m_exampleSubsystem)); | 2 | 2023-10-23 21:29:35+00:00 | 2k |
Matheus-FSantos/4log-products | src/java/controller/ProductController.java | [
{
"identifier": "ProductService",
"path": "WebApplication1/src/java/model/service/ProductService.java",
"snippet": "public class ProductService {\n\n private final ProductRepository productRepository;\n \n public ProductService() {\n this.productRepository = new ProductRepository();\n ... | import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.service.ProductService;
import model.domain.Product; | 1,221 | package controller;
@WebServlet(name = "ProductsController", urlPatterns = {"/products"})
public class ProductController extends HttpServlet {
| package controller;
@WebServlet(name = "ProductsController", urlPatterns = {"/products"})
public class ProductController extends HttpServlet {
| private final ProductService productService = new ProductService(); | 0 | 2023-10-19 17:09:59+00:00 | 2k |
robaho/httpserver | src/test/java_default/HttpExchange/AutoCloseableHttpExchange.java | [
{
"identifier": "URIBuilder",
"path": "src/test/java/jdk/test/lib/net/URIBuilder.java",
"snippet": "public class URIBuilder {\n\n public static URIBuilder newBuilder() {\n return new URIBuilder();\n }\n\n private String scheme;\n private String userInfo;\n private String host;\n ... | import jdk.test.lib.net.URIBuilder;
import robaho.net.httpserver.HttpExchangeAccess;
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean; | 1,211 | /*
* Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8203036
* @library /test/lib
* @modules jdk.httpserver/sun.net.httpserver
* @build jdk.httpserver/sun.net.httpserver.HttpExchangeAccess
* AutoCloseableHttpExchange
* @run main/othervm AutoCloseableHttpExchange
* @summary Ensure that HttpExchange closes correctly when utilising the
* AutoCloseable interface e.g. both request InputStream and response
* OutputStream
* are closed, if not already.
*/
public class AutoCloseableHttpExchange {
static HttpServer testHttpServer;
static AtomicBoolean exchangeCloseFail = new AtomicBoolean(false);
static class Handler implements HttpHandler {
private CountDownLatch latch;
Handler(CountDownLatch latch) {
this.latch = latch;
}
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
try (HttpExchange e = t) {
while (is.read() != -1)
;
t.sendResponseHeaders(200, -1);
}
if (!HttpExchangeAccess.isClosed(t)) {
exchangeCloseFail.set(true);
}
latch.countDown();
}
}
static void connectAndCheck(String realm) throws Exception { | /*
* Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8203036
* @library /test/lib
* @modules jdk.httpserver/sun.net.httpserver
* @build jdk.httpserver/sun.net.httpserver.HttpExchangeAccess
* AutoCloseableHttpExchange
* @run main/othervm AutoCloseableHttpExchange
* @summary Ensure that HttpExchange closes correctly when utilising the
* AutoCloseable interface e.g. both request InputStream and response
* OutputStream
* are closed, if not already.
*/
public class AutoCloseableHttpExchange {
static HttpServer testHttpServer;
static AtomicBoolean exchangeCloseFail = new AtomicBoolean(false);
static class Handler implements HttpHandler {
private CountDownLatch latch;
Handler(CountDownLatch latch) {
this.latch = latch;
}
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
try (HttpExchange e = t) {
while (is.read() != -1)
;
t.sendResponseHeaders(200, -1);
}
if (!HttpExchangeAccess.isClosed(t)) {
exchangeCloseFail.set(true);
}
latch.countDown();
}
}
static void connectAndCheck(String realm) throws Exception { | URL url = URIBuilder.newBuilder() | 0 | 2023-10-15 15:56:58+00:00 | 2k |
aabssmc/Skuishy | src/main/java/lol/aabss/skuishy/elements/expressions/skins/ExprPlayerSkin.java | [
{
"identifier": "SkinWrapper",
"path": "src/main/java/lol/aabss/skuishy/other/skins/SkinWrapper.java",
"snippet": "public abstract class SkinWrapper {\n\n public static HashMap<Player, String> skinname = new HashMap<>();\n\n public static BufferedImage get(Player player, @Nullable Number size, boo... | import ch.njol.skript.classes.Changer;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.expressions.base.PropertyExpression;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.registrations.Classes;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
import lol.aabss.skuishy.other.skins.SkinWrapper;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;
import static lol.aabss.skuishy.other.skins.SkinWrapper.skinname; | 1,048 | package lol.aabss.skuishy.elements.expressions.skins;
@Name("Skins - Player Skin")
@Description("Get/Sets a player's skin")
@Examples({
"set skin of player to \"Dinnerbone\"\n#Also sets the cape"
})
@Since("1.4")
public class ExprPlayerSkin extends PropertyExpression<Player, String> {
static {
register(ExprPlayerSkin.class, String.class,
"[minecraft] skin",
"players"
);
}
private Expression<Player> player;
@Override
protected String @NotNull [] get(@NotNull Event event, Player @NotNull [] source) {
String name = skinname.get(source[0]) == null ? source[0].getName() : skinname.get(source[0]);
return new String[]{name};
}
@Override
public void change(@NotNull Event event, Object @NotNull [] delta, Changer.@NotNull ChangeMode mode){
Player p = player.getSingle(event);
if (mode == Changer.ChangeMode.SET) {
assert p != null; | package lol.aabss.skuishy.elements.expressions.skins;
@Name("Skins - Player Skin")
@Description("Get/Sets a player's skin")
@Examples({
"set skin of player to \"Dinnerbone\"\n#Also sets the cape"
})
@Since("1.4")
public class ExprPlayerSkin extends PropertyExpression<Player, String> {
static {
register(ExprPlayerSkin.class, String.class,
"[minecraft] skin",
"players"
);
}
private Expression<Player> player;
@Override
protected String @NotNull [] get(@NotNull Event event, Player @NotNull [] source) {
String name = skinname.get(source[0]) == null ? source[0].getName() : skinname.get(source[0]);
return new String[]{name};
}
@Override
public void change(@NotNull Event event, Object @NotNull [] delta, Changer.@NotNull ChangeMode mode){
Player p = player.getSingle(event);
if (mode == Changer.ChangeMode.SET) {
assert p != null; | SkinWrapper.setSkin(p, (String) delta[0]); | 0 | 2023-10-24 23:48:14+00:00 | 2k |
wevez/YT4J | src/Main.java | [
{
"identifier": "YTDLOption",
"path": "src/tech/tenamen/yt4j/YTDLOption.java",
"snippet": "public class YTDLOption {\n\n private final YTDLType TYPE;\n private final YTDLQuality QUALITY;\n\n public YTDLOption(YTDLType TYPE, YTDLQuality QUALITY) {\n this.TYPE = TYPE;\n this.QUALITY... | import tech.tenamen.yt4j.YTDLOption;
import tech.tenamen.yt4j.YTSearchFilterOption;
import tech.tenamen.yt4j.data.YTVideo; | 1,094 |
public class Main {
public static void main(String[] args) {
// Create an instance of CustomSC4J.
HttpURLConnectionYT4J yt4J = new HttpURLConnectionYT4J();
if (false) {
yt4J.getDownloadURL(
downloadURL -> System.out.println(downloadURL),
"cvZnQ8wN1OQ",
new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST)
);
return;
}
// Start searching with title "blue roar".
yt4J.startSearch(result -> {
// Start second search.
yt4J.continueSearch(result2 -> {
// Print all title and details in the search result.
result2.forEach(r -> System.out.println(r.toString()));
// Print the download URL of the lowest quality music of the first video in the search result
yt4J.getDownloadURL(
downloadURL -> System.out.println(downloadURL),
(YTVideo) result.get(0),
new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST)
);
}); |
public class Main {
public static void main(String[] args) {
// Create an instance of CustomSC4J.
HttpURLConnectionYT4J yt4J = new HttpURLConnectionYT4J();
if (false) {
yt4J.getDownloadURL(
downloadURL -> System.out.println(downloadURL),
"cvZnQ8wN1OQ",
new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST)
);
return;
}
// Start searching with title "blue roar".
yt4J.startSearch(result -> {
// Start second search.
yt4J.continueSearch(result2 -> {
// Print all title and details in the search result.
result2.forEach(r -> System.out.println(r.toString()));
// Print the download URL of the lowest quality music of the first video in the search result
yt4J.getDownloadURL(
downloadURL -> System.out.println(downloadURL),
(YTVideo) result.get(0),
new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST)
);
}); | }, "blue roar", YTSearchFilterOption.VIDEO); | 1 | 2023-10-22 07:36:16+00:00 | 2k |
ImCodist/funny-bfdi | src/main/java/xyz/imcodist/funnybfdi/voice/FunnyBFDIVoice.java | [
{
"identifier": "FunnyBFDI",
"path": "src/main/java/xyz/imcodist/funnybfdi/FunnyBFDI.java",
"snippet": "public class FunnyBFDI implements ModInitializer {\n public static final String MOD_ID = \"funnybfdi\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n @Override\n ... | import de.maxhenkel.voicechat.api.VoicechatApi;
import de.maxhenkel.voicechat.api.VoicechatPlugin;
import de.maxhenkel.voicechat.api.audio.AudioConverter;
import de.maxhenkel.voicechat.api.events.ClientReceiveSoundEvent;
import de.maxhenkel.voicechat.api.events.ClientSoundEvent;
import de.maxhenkel.voicechat.api.events.EventRegistration;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
import xyz.imcodist.funnybfdi.FunnyBFDI;
import xyz.imcodist.funnybfdi.other.MouthManager; | 1,468 | package xyz.imcodist.funnybfdi.voice;
public class FunnyBFDIVoice implements VoicechatPlugin {
@Override
public void initialize(VoicechatApi api) {
VoicechatPlugin.super.initialize(api);
FunnyBFDI.LOGGER.info("Loaded the voice chat stuffs thats cool nice!");
}
@Override
public void registerEvents(EventRegistration registration) {
VoicechatPlugin.super.registerEvents(registration);
registration.registerEvent(ClientReceiveSoundEvent.EntitySound.class, this::onClientReceivedSound);
registration.registerEvent(ClientSoundEvent.class, this::onClientSendSound);
}
@Override
public String getPluginId() {
return FunnyBFDI.MOD_ID;
}
public void onClientReceivedSound(ClientReceiveSoundEvent.EntitySound event) {
float volume = getVolume(event.getRawAudio(), event.getVoicechat());
if (volume < 100) return;
String text = getMessage(volume);
// this is a terrible way to do this but its incredibly easy | package xyz.imcodist.funnybfdi.voice;
public class FunnyBFDIVoice implements VoicechatPlugin {
@Override
public void initialize(VoicechatApi api) {
VoicechatPlugin.super.initialize(api);
FunnyBFDI.LOGGER.info("Loaded the voice chat stuffs thats cool nice!");
}
@Override
public void registerEvents(EventRegistration registration) {
VoicechatPlugin.super.registerEvents(registration);
registration.registerEvent(ClientReceiveSoundEvent.EntitySound.class, this::onClientReceivedSound);
registration.registerEvent(ClientSoundEvent.class, this::onClientSendSound);
}
@Override
public String getPluginId() {
return FunnyBFDI.MOD_ID;
}
public void onClientReceivedSound(ClientReceiveSoundEvent.EntitySound event) {
float volume = getVolume(event.getRawAudio(), event.getVoicechat());
if (volume < 100) return;
String text = getMessage(volume);
// this is a terrible way to do this but its incredibly easy | MouthManager.onPlayerChatted(Text.of(text), event.getId()); | 1 | 2023-10-18 00:31:52+00:00 | 2k |
ItzGreenCat/SkyImprover | src/main/java/me/greencat/skyimprover/feature/dungeonDeathMessage/DungeonDeathMessage.java | [
{
"identifier": "Config",
"path": "src/main/java/me/greencat/skyimprover/config/Config.java",
"snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashE... | import me.greencat.skyimprover.config.Config;
import me.greencat.skyimprover.feature.Module;
import me.greencat.skyimprover.utils.LocationUtils;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text; | 1,573 | package me.greencat.skyimprover.feature.dungeonDeathMessage;
public class DungeonDeathMessage implements Module {
@Override
public void registerEvent() {
ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat);
}
private static boolean onChat(Text text, boolean overlay) {
if(!Config.dungeonDeathMessageEnable){
return true;
} | package me.greencat.skyimprover.feature.dungeonDeathMessage;
public class DungeonDeathMessage implements Module {
@Override
public void registerEvent() {
ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat);
}
private static boolean onChat(Text text, boolean overlay) {
if(!Config.dungeonDeathMessageEnable){
return true;
} | LocationUtils.update(); | 2 | 2023-10-19 09:19:09+00:00 | 2k |
zilliztech/kafka-connect-milvus | src/main/java/com/milvus/io/kafka/helper/MilvusClientHelper.java | [
{
"identifier": "MilvusSinkConnectorConfig",
"path": "src/main/java/com/milvus/io/kafka/MilvusSinkConnectorConfig.java",
"snippet": "public class MilvusSinkConnectorConfig extends AbstractConfig {\n protected static final String URL = \"public.endpoint\";\n protected static final String TOKEN = \"... | import com.milvus.io.kafka.MilvusSinkConnectorConfig;
import com.milvus.io.kafka.utils.Utils;
import io.milvus.client.MilvusServiceClient;
import io.milvus.param.ConnectParam; | 836 | package com.milvus.io.kafka.helper;
public class MilvusClientHelper {
public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) {
ConnectParam connectParam = ConnectParam.newBuilder()
.withUri(config.getUrl()) | package com.milvus.io.kafka.helper;
public class MilvusClientHelper {
public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) {
ConnectParam connectParam = ConnectParam.newBuilder()
.withUri(config.getUrl()) | .withToken(Utils.decryptToken(config.getToken().value())) | 1 | 2023-10-18 02:11:08+00:00 | 2k |
histevehu/12306 | batch/src/main/java/com/steve/train/batch/controller/JobController.java | [
{
"identifier": "CronJobReq",
"path": "batch/src/main/java/com/steve/train/batch/req/CronJobReq.java",
"snippet": "public class CronJobReq {\n private String group;\n private String name;\n private String description;\n private String cronExpression;\n\n @Override\n public String toStr... | import com.steve.train.batch.req.CronJobReq;
import com.steve.train.batch.resp.CronJobResp;
import com.steve.train.common.resp.CommonResp;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | 1,503 | package com.steve.train.batch.controller;
@RestController
@RequestMapping(value = "/admin/job")
public class JobController {
private static Logger LOG = LoggerFactory.getLogger(JobController.class);
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
@RequestMapping(value = "/run") | package com.steve.train.batch.controller;
@RestController
@RequestMapping(value = "/admin/job")
public class JobController {
private static Logger LOG = LoggerFactory.getLogger(JobController.class);
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
@RequestMapping(value = "/run") | public CommonResp<Object> run(@RequestBody CronJobReq cronJobReq) throws SchedulerException { | 2 | 2023-10-23 01:20:56+00:00 | 2k |
artipie/maven-resolver-http3-plugin | mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/HttpTransporterFactory.java | [
{
"identifier": "ChecksumExtractor",
"path": "mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/checksum/ChecksumExtractor.java",
"snippet": "public abstract class ChecksumExtractor {\n /**\n * Tries to extract checksums from response headers, if present, otherwise ret... | import java.util.HashMap;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import com.artipie.aether.transport.http3.checksum.ChecksumExtractor;
import com.artipie.aether.transport.http3.checksum.Nexus2ChecksumExtractor;
import com.artipie.aether.transport.http3.checksum.XChecksumChecksumExtractor;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.spi.connector.transport.Transporter;
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transfer.NoTransporterException;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Collections; | 1,250 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.artipie.aether.transport.http3;
/**
* A transporter factory for repositories using the {@code http:} or {@code https:} protocol. The provided transporters
* support uploads to WebDAV servers and resumable downloads.
*/
@Named("http")
public final class HttpTransporterFactory implements TransporterFactory { | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.artipie.aether.transport.http3;
/**
* A transporter factory for repositories using the {@code http:} or {@code https:} protocol. The provided transporters
* support uploads to WebDAV servers and resumable downloads.
*/
@Named("http")
public final class HttpTransporterFactory implements TransporterFactory { | private static Map<String, ChecksumExtractor> getManuallyCreatedExtractors() { | 0 | 2023-10-23 12:16:24+00:00 | 2k |
VineeTagarwaL-code/30-Java-Projects | shoppingcartecommercejava/src/com/shashi/service/impl/DemandServiceImpl.java | [
{
"identifier": "DemandBean",
"path": "shoppingcartecommercejava/src/com/shashi/beans/DemandBean.java",
"snippet": "@SuppressWarnings(\"serial\")\npublic class DemandBean implements Serializable {\n\n\tprivate String userName;\n\tprivate String prodId;\n\tprivate int demandQty;\n\n\tpublic DemandBean() ... | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.shashi.beans.DemandBean;
import com.shashi.service.DemandService;
import com.shashi.utility.DBUtil; | 1,038 | package com.shashi.service.impl;
//This class is to process the demand items which are
//not available at the time of purchase by any customer
//the customer will receive mail once the product is avaible
//back into the store
public class DemandServiceImpl implements DemandService {
@Override
public boolean addProduct(String userId, String prodId, int demandQty) {
boolean flag = false;
//get the database connection | package com.shashi.service.impl;
//This class is to process the demand items which are
//not available at the time of purchase by any customer
//the customer will receive mail once the product is avaible
//back into the store
public class DemandServiceImpl implements DemandService {
@Override
public boolean addProduct(String userId, String prodId, int demandQty) {
boolean flag = false;
//get the database connection | Connection con = DBUtil.provideConnection(); | 2 | 2023-10-22 10:39:43+00:00 | 2k |
team-moabam/moabam-BE | src/main/java/com/moabam/api/application/payment/PaymentMapper.java | [
{
"identifier": "Order",
"path": "src/main/java/com/moabam/api/domain/payment/Order.java",
"snippet": "@Embeddable\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Order {\n\n\t@Column(name = \"order_id\")\n\tprivate String id;\n\n\t@Column(name = \"order_name\", nullable = fal... | import java.util.Optional;
import com.moabam.api.domain.payment.Order;
import com.moabam.api.domain.payment.Payment;
import com.moabam.api.domain.product.Product;
import com.moabam.api.dto.payment.ConfirmTossPaymentResponse;
import com.moabam.api.dto.payment.PaymentResponse;
import com.moabam.api.dto.payment.RequestConfirmPaymentResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor; | 1,534 | package com.moabam.api.application.payment;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class PaymentMapper {
| package com.moabam.api.application.payment;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class PaymentMapper {
| public static Payment toPayment(Long memberId, Product product) { | 2 | 2023-10-20 06:15:43+00:00 | 2k |
Chocochip101/aws-kendra-demo | src/main/java/com/chocochip/awskendrademo/application/DemoController.java | [
{
"identifier": "IndexRequestDTO",
"path": "src/main/java/com/chocochip/awskendrademo/dto/IndexRequestDTO.java",
"snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class IndexRequestDTO {\n private String name;\n private String clientToken;\n private String roleArn;\n private String de... | import com.chocochip.awskendrademo.dto.IndexRequestDTO;
import com.chocochip.awskendrademo.dto.S3DataSourceRequestDTO;
import com.chocochip.awskendrademo.dto.SearchResultDTO;
import com.chocochip.awskendrademo.service.KendraService;
import com.chocochip.awskendrademo.service.IndexService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | 1,559 | package com.chocochip.awskendrademo.application;
@RestController
@RequiredArgsConstructor
public class DemoController {
private final IndexService indexService;
private final KendraService kendraService;
@GetMapping("/search") | package com.chocochip.awskendrademo.application;
@RestController
@RequiredArgsConstructor
public class DemoController {
private final IndexService indexService;
private final KendraService kendraService;
@GetMapping("/search") | public ResponseEntity<List<SearchResultDTO>> search( | 2 | 2023-10-23 15:47:15+00:00 | 2k |
liukanshan1/PrivateTrace-Core | src/main/java/Priloc/geo/Utils.java | [
{
"identifier": "Constant",
"path": "src/main/java/Priloc/utils/Constant.java",
"snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{216000... | import Priloc.utils.Constant;
import Priloc.utils.Pair;
import Priloc.utils.Turple; | 1,519 | package Priloc.geo;
public class Utils {
private static final double X_PI = Math.PI * 3000.0 / 180.0;
private static final double PI = Math.PI;
private static final double A = 6378245.0;
private static final double EE = 0.00669342162296594323;
private static double transformLat(double lng, double lat) {
double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLon(double lng, double lat) {
double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
/**
* WGS84转GCJ02(火星坐标系)
* @param lng WGS84坐标系的经度
* @param lat WGS84坐标系的纬度
*/
public static Pair<Double, Double> wgs84ToGcj02(double lng, double lat) {
double dLat = transformLat(lng - 105.0, lat - 35.0);
double dLng = transformLon(lng - 105.0, lat - 35.0);
double radLat = lat / 180.0 * PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI);
double mgLat = lat + dLat;
double mgLng = lng + dLng;
return new Pair<>(mgLng, mgLat);
}
/**
* GCJ02(火星坐标系)转XYZ
* @param lng GCJ02坐标系的经度
* @param lat GCJ02坐标系的纬度
* 后期可增加高程信息优化精度
*/
| package Priloc.geo;
public class Utils {
private static final double X_PI = Math.PI * 3000.0 / 180.0;
private static final double PI = Math.PI;
private static final double A = 6378245.0;
private static final double EE = 0.00669342162296594323;
private static double transformLat(double lng, double lat) {
double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLon(double lng, double lat) {
double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
/**
* WGS84转GCJ02(火星坐标系)
* @param lng WGS84坐标系的经度
* @param lat WGS84坐标系的纬度
*/
public static Pair<Double, Double> wgs84ToGcj02(double lng, double lat) {
double dLat = transformLat(lng - 105.0, lat - 35.0);
double dLng = transformLon(lng - 105.0, lat - 35.0);
double radLat = lat / 180.0 * PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI);
double mgLat = lat + dLat;
double mgLng = lng + dLng;
return new Pair<>(mgLng, mgLat);
}
/**
* GCJ02(火星坐标系)转XYZ
* @param lng GCJ02坐标系的经度
* @param lat GCJ02坐标系的纬度
* 后期可增加高程信息优化精度
*/
| public static Turple<Double, Double, Double> gcj02ToXYZ(double lng, double lat) { | 2 | 2023-10-22 06:28:51+00:00 | 2k |
ErickMonteiroMDK/Advocacia_Beckhauser | src/main/java/com/advocacia/Advocacia_Beckhauser/services/AgendaService.java | [
{
"identifier": "Agenda",
"path": "src/main/java/com/advocacia/Advocacia_Beckhauser/models/Agenda.java",
"snippet": "@Entity\npublic class Agenda extends EntityID \n{\n @Column(name = \"dataOcorrencia\", nullable = false)\n private LocalDate dataOcorrencia;\n\n\n @ManyToOne\n @JoinColumn(nam... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.advocacia.Advocacia_Beckhauser.models.Agenda;
import com.advocacia.Advocacia_Beckhauser.repositories.AgendaRepository; | 1,079 | package com.advocacia.Advocacia_Beckhauser.services;
@Service
public class AgendaService
{
@Autowired | package com.advocacia.Advocacia_Beckhauser.services;
@Service
public class AgendaService
{
@Autowired | private AgendaRepository repository; | 1 | 2023-10-24 21:35:12+00:00 | 2k |
Space125/tasklist | src/main/java/org/kurilov/tasklist/config/SecurityConfig.java | [
{
"identifier": "JwtTokenFilter",
"path": "src/main/java/org/kurilov/tasklist/web/security/JwtTokenFilter.java",
"snippet": "@AllArgsConstructor\n@Slf4j\npublic class JwtTokenFilter extends GenericFilterBean {\n\n private final JwtTokenProvider jwtTokenProvider;\n\n @Override\n @SneakyThrows\n ... | import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.security.SecurityScheme.Type;
import lombok.RequiredArgsConstructor;
import org.kurilov.tasklist.web.security.JwtTokenFilter;
import org.kurilov.tasklist.web.security.JwtTokenProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | 1,312 | package org.kurilov.tasklist.config;
/**
* @author Ivan Kurilov on 20.10.2023
*/
@Configuration
@EnableWebSecurity(debug = true)
@EnableMethodSecurity
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class SecurityConfig {
| package org.kurilov.tasklist.config;
/**
* @author Ivan Kurilov on 20.10.2023
*/
@Configuration
@EnableWebSecurity(debug = true)
@EnableMethodSecurity
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class SecurityConfig {
| private final JwtTokenProvider jwtTokenProvider; | 1 | 2023-10-19 05:50:28+00:00 | 2k |
rfresh2/2b2t.vc-rusherhack | src/main/java/vc/command/StatsCommand.java | [
{
"identifier": "VcApi",
"path": "src/main/java/vc/api/VcApi.java",
"snippet": "public class VcApi {\n private final HttpClient httpClient;\n private final ILogger logger;\n private final Gson gson;\n\n public VcApi(final ILogger logger) {\n this.logger = logger;\n this.httpCli... | import org.rusherhack.client.api.feature.command.Command;
import org.rusherhack.client.api.feature.command.arg.PlayerReference;
import org.rusherhack.client.api.utils.ChatUtils;
import org.rusherhack.core.command.annotations.CommandExecutor;
import vc.api.VcApi;
import java.time.Duration;
import java.util.concurrent.ForkJoinPool;
import static vc.util.FormatUtil.formatDuration;
import static vc.util.FormatUtil.getSeenString; | 931 | package vc.command;
public class StatsCommand extends Command {
private final VcApi api;
public StatsCommand(final VcApi api) {
super("stats", "Gets the 2b2t stats of a player");
this.api = api;
}
@CommandExecutor
@CommandExecutor.Argument({"player"})
private String statsPlayerName(final PlayerReference player) {
ForkJoinPool.commonPool().execute(() -> {
var statsResponse = api.getStats(player);
var out = statsResponse.map(s ->
player.name() + " Stats" +
"\nJoins: " + s.joinCount() +
"\nLeaves: " + s.leaveCount() +
"\nFirst Seen: " + getSeenString(s.firstSeen()) +
"\nLast Seen: " + getSeenString(s.lastSeen()) + | package vc.command;
public class StatsCommand extends Command {
private final VcApi api;
public StatsCommand(final VcApi api) {
super("stats", "Gets the 2b2t stats of a player");
this.api = api;
}
@CommandExecutor
@CommandExecutor.Argument({"player"})
private String statsPlayerName(final PlayerReference player) {
ForkJoinPool.commonPool().execute(() -> {
var statsResponse = api.getStats(player);
var out = statsResponse.map(s ->
player.name() + " Stats" +
"\nJoins: " + s.joinCount() +
"\nLeaves: " + s.leaveCount() +
"\nFirst Seen: " + getSeenString(s.firstSeen()) +
"\nLast Seen: " + getSeenString(s.lastSeen()) + | "\nPlaytime: " + formatDuration(Duration.ofSeconds(s.playtimeSeconds())) + | 1 | 2023-10-22 20:22:42+00:00 | 2k |
Dwight-Studio/JArmEmu | src/main/java/fr/dwightstudio/jarmemu/gui/factory/CursorTableCell.java | [
{
"identifier": "MemoryWordView",
"path": "src/main/java/fr/dwightstudio/jarmemu/gui/view/MemoryWordView.java",
"snippet": "public class MemoryWordView {\n private final MemoryAccessor memoryAccessor;\n private final ReadOnlyIntegerProperty addressProperty;\n private final IntegerProperty value... | import fr.dwightstudio.jarmemu.gui.view.MemoryWordView;
import fr.dwightstudio.jarmemu.util.converters.CursorStringConverter;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.Callback; | 1,574 | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.factory;
public class CursorTableCell extends TextFieldTableCell<MemoryWordView, Boolean> {
private CursorTableCell() { | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.factory;
public class CursorTableCell extends TextFieldTableCell<MemoryWordView, Boolean> {
private CursorTableCell() { | super(new CursorStringConverter()); | 1 | 2023-10-17 18:22:09+00:00 | 2k |
lenhathieu96/vision-camera-face-detector | android/src/main/java/com/visioncamerafacedetectorplugin/VisionCameraFaceDetectorPlugin.java | [
{
"identifier": "FaceDetectionStatus",
"path": "android/src/main/java/com/visioncamerafacedetectorplugin/models/FaceDetectionStatus.java",
"snippet": "public enum FaceDetectionStatus{\n STANDBY,\n ERROR,\n SUCCESS\n\n}"
},
{
"identifier": "FaceDetectorException",
"path": "android/src/main... | import android.graphics.Bitmap;
import android.media.Image;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.face.Face;
import com.google.mlkit.vision.face.FaceDetection;
import com.google.mlkit.vision.face.FaceDetector;
import com.google.mlkit.vision.face.FaceDetectorOptions;
import com.mrousavy.camera.frameprocessor.Frame;
import com.mrousavy.camera.frameprocessor.FrameProcessorPlugin;
import com.visioncamerafacedetectorplugin.models.FaceDetectionStatus;
import com.visioncamerafacedetectorplugin.models.FaceDetectorException;
import com.visioncamerafacedetectorplugin.models.FaceDirection;
import java.io.ByteArrayOutputStream;
import java.sql.Time;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 646 | package com.visioncamerafacedetectorplugin;
public class VisionCameraFaceDetectorPlugin extends FrameProcessorPlugin {
private final int MAX_DIFFERENCE = 5;
private Long firstDetectedTime = 0L;
private FaceDirection _prevFaceDirection = FaceDirection.UNKNOWN;
Map<String, Object> resultMap = new HashMap<>();
FaceDetectorOptions faceDetectorOptions =
new FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
.build();
FaceDetector faceDetector = FaceDetection.getClient(faceDetectorOptions);
private void setErrorResult(FaceDetectorException error){ | package com.visioncamerafacedetectorplugin;
public class VisionCameraFaceDetectorPlugin extends FrameProcessorPlugin {
private final int MAX_DIFFERENCE = 5;
private Long firstDetectedTime = 0L;
private FaceDirection _prevFaceDirection = FaceDirection.UNKNOWN;
Map<String, Object> resultMap = new HashMap<>();
FaceDetectorOptions faceDetectorOptions =
new FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
.build();
FaceDetector faceDetector = FaceDetection.getClient(faceDetectorOptions);
private void setErrorResult(FaceDetectorException error){ | resultMap.put("status", FaceDetectionStatus.ERROR.name().toLowerCase()); | 0 | 2023-10-18 02:13:39+00:00 | 2k |
GTNewHorizons/FarmingForEngineers | src/main/java/com/guigs44/farmingforengineers/registry/AbstractRegistry.java | [
{
"identifier": "FarmingForEngineers",
"path": "src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java",
"snippet": "@Mod(\n modid = FarmingForEngineers.MOD_ID,\n name = \"Farming for Engineers\",\n dependencies = \"after:mousetweaks[2.8,);after:forestry;after:agricr... | import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import net.minecraft.util.ResourceLocation;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.guigs44.farmingforengineers.FarmingForEngineers;
import com.guigs44.farmingforengineers.ModConfig; | 1,474 | package com.guigs44.farmingforengineers.registry;
public abstract class AbstractRegistry {
public static List<String> registryErrors = Lists.newArrayList();
protected final String registryName;
private boolean hasChanged;
private boolean refuseSave;
public AbstractRegistry(String registryName) {
this.registryName = registryName;
}
public final void load(File configDir) {
clear();
Gson gson = new Gson();
File configFile = new File(configDir, registryName + ".json");
if (!configFile.exists()) {
try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) {
jsonWriter.setIndent(" ");
gson.toJson(create(), jsonWriter);
} catch (IOException e) { | package com.guigs44.farmingforengineers.registry;
public abstract class AbstractRegistry {
public static List<String> registryErrors = Lists.newArrayList();
protected final String registryName;
private boolean hasChanged;
private boolean refuseSave;
public AbstractRegistry(String registryName) {
this.registryName = registryName;
}
public final void load(File configDir) {
clear();
Gson gson = new Gson();
File configFile = new File(configDir, registryName + ".json");
if (!configFile.exists()) {
try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) {
jsonWriter.setIndent(" ");
gson.toJson(create(), jsonWriter);
} catch (IOException e) { | FarmingForEngineers.logger.error("Failed to create default {} registry: {}", registryName, e); | 0 | 2023-10-17 00:25:50+00:00 | 2k |
mnesimiyilmaz/sql4json | src/main/java/io/github/mnesimiyilmaz/sql4json/grouping/GroupByInput.java | [
{
"identifier": "CriteriaNode",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/condition/CriteriaNode.java",
"snippet": "public interface CriteriaNode {\n\n boolean test(Map<FieldKey, Object> row);\n\n}"
},
{
"identifier": "JsonColumnWithNonAggFunctionDefinion",
"path": "src/main... | import io.github.mnesimiyilmaz.sql4json.condition.CriteriaNode;
import io.github.mnesimiyilmaz.sql4json.definitions.JsonColumnWithNonAggFunctionDefinion;
import io.github.mnesimiyilmaz.sql4json.definitions.SelectColumnDefinition;
import io.github.mnesimiyilmaz.sql4json.utils.FieldKey;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.Map; | 1,083 | package io.github.mnesimiyilmaz.sql4json.grouping;
/**
* @author mnesimiyilmaz
*/
@Getter
@RequiredArgsConstructor
public class GroupByInput {
private final List<Map<FieldKey, Object>> flattenedInputJsonNode;
private final List<SelectColumnDefinition> selectedColumns; | package io.github.mnesimiyilmaz.sql4json.grouping;
/**
* @author mnesimiyilmaz
*/
@Getter
@RequiredArgsConstructor
public class GroupByInput {
private final List<Map<FieldKey, Object>> flattenedInputJsonNode;
private final List<SelectColumnDefinition> selectedColumns; | private final List<JsonColumnWithNonAggFunctionDefinion> groupByColumns; | 1 | 2023-10-24 18:34:33+00:00 | 2k |
AkramLZ/ServerSync | serversync-common/src/main/java/me/akraml/serversync/broker/RabbitMqMessageBrokerService.java | [
{
"identifier": "ConnectionResult",
"path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionResult.java",
"snippet": "public enum ConnectionResult {\n\n /**\n * Indicates a successful connection.\n */\n SUCCESS,\n\n /**\n * Indicates a failed connection.\n... | import com.google.gson.JsonObject;
import com.rabbitmq.client.Connection;
import me.akraml.serversync.connection.ConnectionResult;
import me.akraml.serversync.connection.auth.AuthenticatedConnection;
import me.akraml.serversync.connection.auth.ConnectionCredentials;
import me.akraml.serversync.server.ServersManager; | 1,576 | package me.akraml.serversync.broker;
/**
* A concrete implementation of the {@link MessageBrokerService} that utilizes RabbitMQ as the message broker backend.
* This class is just like {@link RedisMessageBrokerService}, but the main difference is the software which handles
* messages.
*
* TODO Implement RabbitMQ Message broker service.
*/
public class RabbitMqMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<Connection> {
public RabbitMqMessageBrokerService(ServersManager serversManager) {
super(serversManager);
}
@Override
public void startHandler() {
}
@Override
public void stop() {
}
@Override
public void publish(JsonObject message) {
}
@Override | package me.akraml.serversync.broker;
/**
* A concrete implementation of the {@link MessageBrokerService} that utilizes RabbitMQ as the message broker backend.
* This class is just like {@link RedisMessageBrokerService}, but the main difference is the software which handles
* messages.
*
* TODO Implement RabbitMQ Message broker service.
*/
public class RabbitMqMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<Connection> {
public RabbitMqMessageBrokerService(ServersManager serversManager) {
super(serversManager);
}
@Override
public void startHandler() {
}
@Override
public void stop() {
}
@Override
public void publish(JsonObject message) {
}
@Override | public ConnectionResult connect() { | 0 | 2023-10-21 12:47:58+00:00 | 2k |
neftalito/R-Info-Plus | arbol/sentencia/primitiva/LiberarEsquina.java | [
{
"identifier": "Expresion",
"path": "arbol/expresion/Expresion.java",
"snippet": "public abstract class Expresion extends AST {\n public DeclaracionVariable DV;\n public Tipo T;\n public Identificador I;\n public Robot r;\n\n public DeclaracionVariable getDV() {\n return this.DV;\... | import java.util.logging.Level;
import java.util.logging.Logger;
import arbol.expresion.Expresion;
import arbol.DeclaracionVariable; | 807 |
package arbol.sentencia.primitiva;
public class LiberarEsquina extends Primitiva {
int ciclo;
private int Av;
private int Ca; |
package arbol.sentencia.primitiva;
public class LiberarEsquina extends Primitiva {
int ciclo;
private int Av;
private int Ca; | DeclaracionVariable DV; | 1 | 2023-10-20 15:45:37+00:00 | 2k |
wevez/ClientCoderPack | src/tech/tenamen/client/Asset.java | [
{
"identifier": "Main",
"path": "src/tech/tenamen/Main.java",
"snippet": "public class Main {\n public static IDE IDE = new InteliJIDE();\n public static Client client;\n\n public static File WORKING_DIR = new File(System.getProperty(\"user.dir\")),\n ASSETS_DIR = new File(WORKING_DIR, \"ass... | import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import tech.tenamen.Main;
import tech.tenamen.property.OS;
import tech.tenamen.util.NetUtil;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List; | 1,349 | package tech.tenamen.client;
public class Asset implements Downloadable {
private final String ID;
private final String SHA1;
private final long SIZE;
private final long TOTAL_SIZE;
private final String URL;
public Asset(final String ID, final String SHA1, final long SIZE, final long TOTAL_SIZE, final String URL) {
this.ID = ID;
this.SHA1 = SHA1;
this.SIZE = SIZE;
this.TOTAL_SIZE = TOTAL_SIZE;
this.URL = URL;
}
@Override
public void download(OS os) {
JsonObject object = null; | package tech.tenamen.client;
public class Asset implements Downloadable {
private final String ID;
private final String SHA1;
private final long SIZE;
private final long TOTAL_SIZE;
private final String URL;
public Asset(final String ID, final String SHA1, final long SIZE, final long TOTAL_SIZE, final String URL) {
this.ID = ID;
this.SHA1 = SHA1;
this.SIZE = SIZE;
this.TOTAL_SIZE = TOTAL_SIZE;
this.URL = URL;
}
@Override
public void download(OS os) {
JsonObject object = null; | object = new GsonBuilder().setPrettyPrinting().create().fromJson(new StringReader(NetUtil.download(this.URL)), JsonObject.class); | 2 | 2023-10-20 06:56:19+00:00 | 2k |
Invadermonky/Omniwand | src/main/java/com/invadermonky/omniwand/handlers/MouseEventOW.java | [
{
"identifier": "Omniwand",
"path": "src/main/java/com/invadermonky/omniwand/Omniwand.java",
"snippet": "@Mod(\n modid = Omniwand.MOD_ID,\n name = Omniwand.MOD_NAME,\n version = Omniwand.MOD_VERSION,\n acceptedMinecraftVersions = Omniwand.MC_VERSION,\n guiFactory = Omn... | import com.invadermonky.omniwand.Omniwand;
import com.invadermonky.omniwand.network.MessageWandTransform;
import com.invadermonky.omniwand.util.RayTracer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.RayTraceResult;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | 1,390 | package com.invadermonky.omniwand.handlers;
@SideOnly(Side.CLIENT)
public class MouseEventOW {
public static final MouseEventOW INSTANCE = new MouseEventOW();
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onMouseEvent(MouseEvent event) {
EntityPlayerSP playerSP = Minecraft.getMinecraft().player;
ItemStack heldItem = playerSP.getHeldItem(ConfigHandler.getConfiguredHand());
if(TransformHandler.isOmniwand(heldItem)) {
ItemStack newStack = heldItem; | package com.invadermonky.omniwand.handlers;
@SideOnly(Side.CLIENT)
public class MouseEventOW {
public static final MouseEventOW INSTANCE = new MouseEventOW();
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onMouseEvent(MouseEvent event) {
EntityPlayerSP playerSP = Minecraft.getMinecraft().player;
ItemStack heldItem = playerSP.getHeldItem(ConfigHandler.getConfiguredHand());
if(TransformHandler.isOmniwand(heldItem)) {
ItemStack newStack = heldItem; | RayTraceResult result = RayTracer.retrace(playerSP); | 2 | 2023-10-16 00:48:26+00:00 | 2k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.