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
amithkoujalgi/ollama4j
src/test/java/io/github/amithkoujalgi/ollama4j/integrationtests/TestRealAPIs.java
[ { "identifier": "OllamaAPI", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java", "snippet": "@SuppressWarnings(\"DuplicatedCode\")\npublic class OllamaAPI {\n\n private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class);\n private final String host;\n priv...
import static org.junit.jupiter.api.Assertions.*; import io.github.amithkoujalgi.ollama4j.core.OllamaAPI; import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException; import io.github.amithkoujalgi.ollama4j.core.models.OllamaResult; import io.github.amithkoujalgi.ollama4j.core.types.OllamaModelType; import io.github.amithkoujalgi.ollama4j.core.utils.OptionsBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.URISyntaxException; import java.net.http.HttpConnectTimeoutException; import java.util.List; import java.util.Objects; import java.util.Properties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test;
8,892
package io.github.amithkoujalgi.ollama4j.integrationtests; class TestRealAPIs { OllamaAPI ollamaAPI; private Properties loadProperties() { Properties properties = new Properties(); try (InputStream input = getClass().getClassLoader().getResourceAsStream("test-config.properties")) { if (input == null) { throw new RuntimeException("Sorry, unable to find test-config.properties"); } properties.load(input); return properties; } catch (IOException e) { throw new RuntimeException("Error loading properties", e); } } private File getImageFileFromClasspath(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); return new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile()); } @BeforeEach void setUp() { Properties properties = loadProperties(); ollamaAPI = new OllamaAPI(properties.getProperty("ollama.api.url")); ollamaAPI.setRequestTimeoutSeconds(20); } @Test @Order(1) void testWrongEndpoint() { OllamaAPI ollamaAPI = new OllamaAPI("http://wrong-host:11434"); assertThrows(ConnectException.class, ollamaAPI::listModels); } @Test @Order(1) void testEndpointReachability() { try { assertNotNull(ollamaAPI.listModels()); } catch (HttpConnectTimeoutException e) { fail(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } } @Test @Order(2) void testListModels() { testEndpointReachability(); try { assertNotNull(ollamaAPI.listModels()); ollamaAPI.listModels().forEach(System.out::println); } catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) { throw new RuntimeException(e); } } @Test @Order(2) void testPullModel() { testEndpointReachability(); try { ollamaAPI.pullModel(OllamaModelType.LLAMA2); boolean found = ollamaAPI.listModels().stream() .anyMatch(model -> model.getModelName().equals(OllamaModelType.LLAMA2)); assertTrue(found); } catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) { throw new RuntimeException(e); } } @Test @Order(3) void testAskModelWithDefaultOptions() { testEndpointReachability(); try {
package io.github.amithkoujalgi.ollama4j.integrationtests; class TestRealAPIs { OllamaAPI ollamaAPI; private Properties loadProperties() { Properties properties = new Properties(); try (InputStream input = getClass().getClassLoader().getResourceAsStream("test-config.properties")) { if (input == null) { throw new RuntimeException("Sorry, unable to find test-config.properties"); } properties.load(input); return properties; } catch (IOException e) { throw new RuntimeException("Error loading properties", e); } } private File getImageFileFromClasspath(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); return new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile()); } @BeforeEach void setUp() { Properties properties = loadProperties(); ollamaAPI = new OllamaAPI(properties.getProperty("ollama.api.url")); ollamaAPI.setRequestTimeoutSeconds(20); } @Test @Order(1) void testWrongEndpoint() { OllamaAPI ollamaAPI = new OllamaAPI("http://wrong-host:11434"); assertThrows(ConnectException.class, ollamaAPI::listModels); } @Test @Order(1) void testEndpointReachability() { try { assertNotNull(ollamaAPI.listModels()); } catch (HttpConnectTimeoutException e) { fail(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } } @Test @Order(2) void testListModels() { testEndpointReachability(); try { assertNotNull(ollamaAPI.listModels()); ollamaAPI.listModels().forEach(System.out::println); } catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) { throw new RuntimeException(e); } } @Test @Order(2) void testPullModel() { testEndpointReachability(); try { ollamaAPI.pullModel(OllamaModelType.LLAMA2); boolean found = ollamaAPI.listModels().stream() .anyMatch(model -> model.getModelName().equals(OllamaModelType.LLAMA2)); assertTrue(found); } catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) { throw new RuntimeException(e); } } @Test @Order(3) void testAskModelWithDefaultOptions() { testEndpointReachability(); try {
OllamaResult result =
2
2023-10-26 19:12:14+00:00
12k
Changbaiqi/yatori
yatori-console/src/main/java/com/cbq/yatori/console/run/Launch.java
[ { "identifier": "LoginResponseRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java", "snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n...
import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourse; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourseData; import com.cbq.yatori.core.action.enaea.entity.LoginAblesky; import com.cbq.yatori.core.action.enaea.entity.underwayproject.ResultList; import com.cbq.yatori.core.action.enaea.entity.underwayproject.UnderwayProjectRquest; import com.cbq.yatori.core.action.yinghua.CourseAction; import com.cbq.yatori.core.action.yinghua.CourseStudyAction; import com.cbq.yatori.core.action.yinghua.LoginAction; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseInform; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseRequest; import com.cbq.yatori.core.entity.*; import com.cbq.yatori.core.utils.ConfigUtils; import com.cbq.yatori.core.utils.FileUtils; import com.cbq.yatori.core.utils.VerificationCodeUtil; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask;
9,178
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件
config = ConfigUtils.loadingConfig();
11
2023-10-30 04:15:41+00:00
12k
sgware/sabre
src/edu/uky/cs/nil/sabre/hg/Node.java
[ { "identifier": "Settings", "path": "src/edu/uky/cs/nil/sabre/Settings.java", "snippet": "public class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final Str...
import java.io.Serializable; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.Utilities; import edu.uky.cs.nil.sabre.logic.Logical; import edu.uky.cs.nil.sabre.logic.Value;
8,123
package edu.uky.cs.nil.sabre.hg; /** * The parent class of all {@link HeuristicGraph heuristic graph} nodes. * * @author Stephen G. Ware */ public abstract class Node implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The heuristic graph this node belong to */ public HeuristicGraph graph; /** The logical formula this node represents in the graph */ public Logical label; /** * The next node in the graph's linked list of nodes that need to be reset */ Node nextToReset = null; /** * Constructs a new node that belongs to a given graph and represents a * given logical formula. * * @param graph the graph this node belongs to * @param label the logical formula this node represents */ protected Node(HeuristicGraph graph, Logical label) { this.graph = graph; this.label = label; graph.nodes.put(label, this); } @Override public int hashCode() { return label.hashCode(); } @Override public String toString() {
package edu.uky.cs.nil.sabre.hg; /** * The parent class of all {@link HeuristicGraph heuristic graph} nodes. * * @author Stephen G. Ware */ public abstract class Node implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The heuristic graph this node belong to */ public HeuristicGraph graph; /** The logical formula this node represents in the graph */ public Logical label; /** * The next node in the graph's linked list of nodes that need to be reset */ Node nextToReset = null; /** * Constructs a new node that belongs to a given graph and represents a * given logical formula. * * @param graph the graph this node belongs to * @param label the logical formula this node represents */ protected Node(HeuristicGraph graph, Logical label) { this.graph = graph; this.label = label; graph.nodes.put(label, this); } @Override public int hashCode() { return label.hashCode(); } @Override public String toString() {
return Utilities.DEFAULT_PRINTER.toString(this);
1
2023-10-26 18:14:19+00:00
12k
sngular/pact-annotation-processor
src/main/java/com/sngular/annotation/processor/PactDslProcessor.java
[ { "identifier": "PactProcessorException", "path": "src/main/java/com/sngular/annotation/processor/exception/PactProcessorException.java", "snippet": "public class PactProcessorException extends RuntimeException {\n\n private static final String ERROR_MESSAGE = \"Error processing element %s\";\n\n publ...
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableMap; import com.sngular.annotation.pact.DslExclude; import com.sngular.annotation.pact.Example; import com.sngular.annotation.pact.PactDslBodyBuilder; import com.sngular.annotation.processor.exception.PactProcessorException; import com.sngular.annotation.processor.exception.TemplateFactoryException; import com.sngular.annotation.processor.exception.TemplateGenerationException; import com.sngular.annotation.processor.mapping.BigDecimalMapping; import com.sngular.annotation.processor.mapping.BigIntegerMapping; import com.sngular.annotation.processor.mapping.BooleanMapping; import com.sngular.annotation.processor.mapping.ByteMapping; import com.sngular.annotation.processor.mapping.CharMapping; import com.sngular.annotation.processor.mapping.DateMapping; import com.sngular.annotation.processor.mapping.DoubleMapping; import com.sngular.annotation.processor.mapping.FloatMapping; import com.sngular.annotation.processor.mapping.IntegerMapping; import com.sngular.annotation.processor.mapping.LongMapping; import com.sngular.annotation.processor.mapping.ShortMapping; import com.sngular.annotation.processor.mapping.StringMapping; import com.sngular.annotation.processor.mapping.TypeMapping; import com.sngular.annotation.processor.mapping.ZonedDateTimeMapping; import com.sngular.annotation.processor.model.ClassBuilderTemplate; import com.sngular.annotation.processor.model.DslComplexField; import com.sngular.annotation.processor.model.DslComplexTypeEnum; import com.sngular.annotation.processor.model.DslField; import com.sngular.annotation.processor.model.DslSimpleField; import com.sngular.annotation.processor.model.FieldValidations; import com.sngular.annotation.processor.template.ClasspathTemplateLoader; import com.sngular.annotation.processor.template.TemplateFactory; import freemarker.template.TemplateException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IterableUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; import org.jetbrains.annotations.NotNull;
7,771
private List<DslField> getFields(final List<? extends Element> fieldElements) { return IterableUtils.toList(IterableUtils.transformedIterable(fieldElements, fieldElement -> composeDslField(fieldElement, false))); } private List<String> getAnnotationValueAsType(final AnnotationMirror annotationMirror, final String key) { final var valueAsTypeList = new ArrayList<String>(); final var annotationValue = getAnnotationValue(annotationMirror, key); if (annotationValue != null) { valueAsTypeList.addAll(List.of(annotationValue.toString() .replace(" ", "").replace("{", "") .replace("}", "").replace("\"", "") .split(","))); } return valueAsTypeList; } private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) { AnnotationValue annotationValue = null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { annotationValue = entry.getValue(); } } return annotationValue; } private DslField composeDslField(final Element fieldElement, final boolean insideCollection) { final DslField result; final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement); if (mappingOp.isEmpty()) { if (checkIfOwn(fieldElement)) { result = composeDslComplexField(fieldElement); } else { final String type = extractType(fieldElement); if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) { result = composeCollection(fieldElement); } else { result = composeDslComplexField(fieldElement); } } } else { result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection); } return result; } private DslComplexField composeDslComplexField(final Element element) { return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(element.asType().toString()) .needBuilder(checkIfOwn(element)) .complexType(DslComplexTypeEnum.OBJECT) .fieldValidations(extractValidations(element)) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private DslComplexField composeCollection(final Element element) { final var typeStr = cleanType(element); return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(typeStr) .fields(extractTypes(element)) .fieldValidations(extractValidations(element)) .complexType(DslComplexTypeEnum.COLLECTION) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private boolean checkIfOwn(final Element element) { final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString(); final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString(); return parentType.equalsIgnoreCase(typePackage); } private String extractType(final Element element) { return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString(); } private String cleanType(final Element element) { var finalType = element.asType().toString(); for (var annotation : element.asType().getAnnotationMirrors()) { finalType = finalType.replace(annotation.toString(), ""); } return finalType.replace(", ", ""); } private FieldValidations extractValidations(final Element element) { final var validationBuilder = FieldValidations.builder(); int minValue = 0; int maxValue = 0; final var type = element.asType(); if (CollectionUtils.isNotEmpty(type.getAnnotationMirrors())) { for (var annotation : type.getAnnotationMirrors()) { if (annotation.getAnnotationType().toString().toUpperCase().endsWith("MAX")) { maxValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue(); validationBuilder.max(maxValue); } else { minValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue(); validationBuilder.min(minValue); } } //For random size calculation: defaults to +10 elements max if not defined. maxValue = (maxValue == 0) ? (minValue + 10) : maxValue; validationBuilder.randomSize(new Random().nextInt(maxValue - minValue + 1) + minValue); } return validationBuilder.build(); } @NotNull private List<DslField> extractTypes(final Element element) { final List<DslField> listOfFields; final var listOfCustomMods = new ArrayList<>(CollectionUtils.collect(((DeclaredType) element.asType()).getTypeArguments(), typeUtils::asElement)); if (listOfCustomMods.size() > 1) { listOfFields = new ArrayList<>(CollectionUtils.collect(listOfCustomMods, e -> composeDslField(e, true))); } else { listOfFields = List.of( composeDslSimpleField(listOfCustomMods.get(0), extractMappingByType(listOfCustomMods.get(0))
/* * This Source Code Form is subject to the terms of the Mozilla Public * * License, v. 2.0. If a copy of the MPL was not distributed with this * * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package com.sngular.annotation.processor; @Slf4j @AutoService(Processor.class) @SupportedAnnotationTypes("com.sngular.annotation.pact.PactDslBodyBuilder") public class PactDslProcessor extends AbstractProcessor { static final Map<String, TypeMapping<?>> TYPE_MAPPING = ImmutableMap.<String, TypeMapping<?>>builder() .put("int", new IntegerMapping()) .put("Integer", new IntegerMapping()) .put("BigInteger", new BigIntegerMapping()) .put("short", new ShortMapping()) .put("Short", new ShortMapping()) .put("byte", new ByteMapping()) .put("Byte", new ByteMapping()) .put("long", new LongMapping()) .put("Long", new LongMapping()) .put("char", new CharMapping()) .put("Character", new CharMapping()) .put("String", new StringMapping()) .put("float", new FloatMapping()) .put("Float", new FloatMapping()) .put("double", new DoubleMapping()) .put("Double", new DoubleMapping()) .put("BigDecimal", new BigDecimalMapping()) .put("boolean", new BooleanMapping()) .put("Boolean", new BooleanMapping()) .put("date", new DateMapping()) .put("java.time.ZonedDateTime", new ZonedDateTimeMapping()) .put("ZonedDateTime", new ZonedDateTimeMapping()) .put("java.util.Date", new DateMapping()) .put("Date", new DateMapping()) .build(); private static final String CUSTOM_MODIFIERS = "customModifiers"; private Elements elementUtils; private Types typeUtils; private RestorableUniformRandomProvider randomSource = RandomSource.XO_RO_SHI_RO_128_PP.create(); public PactDslProcessor() { } public PactDslProcessor(final RestorableUniformRandomProvider randomSource) { this.randomSource = randomSource; } @NotNull private static List<? extends Element> getFieldElements(final Element element) { return IterableUtils.toList(IterableUtils.filteredIterable(element.getEnclosedElements(), elt -> elt.getKind().isField())); } private static String getFormat(final Element fieldElement, final String defaultFormat) { final String value = fieldElement.getAnnotation(Example.class).format(); return StringUtils.defaultIfEmpty(value, defaultFormat); } @Override public final SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { final TemplateFactory templateFactory; try { templateFactory = new TemplateFactory(); } catch (final TemplateException e) { throw new TemplateFactoryException(e); } elementUtils = processingEnv.getElementUtils(); typeUtils = processingEnv.getTypeUtils(); final Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(PactDslBodyBuilder.class); IteratorUtils .transformedIterator(elementsAnnotatedWith.iterator(), this::composeBuilderTemplate).forEachRemaining(builderTemplate -> { try { final var builderFile = processingEnv.getFiler().createSourceFile(builderTemplate.completePath()); templateFactory.writeTemplateToFile(ClasspathTemplateLoader.TEMPLATE_DSL_BUILDER, builderTemplate, builderFile.openWriter()); } catch (IOException | TemplateException e) { throw new TemplateGenerationException("PactDslBodyBuilder", e); } }); return true; } private ClassBuilderTemplate composeBuilderTemplate(final Element element) { final List<? extends Element> fieldElements = getFieldElements(element); final var qualifiedName = ((TypeElement) element).getQualifiedName().toString(); String packageName = null; final int lastDot = qualifiedName.lastIndexOf('.'); if (lastDot > 0) { packageName = qualifiedName.substring(0, lastDot); } final var builderSimpleClassName = qualifiedName.substring(lastDot + 1); final var builderClassName = builderSimpleClassName + "Builder"; return ClassBuilderTemplate.builder() .fileName(builderClassName) .className(builderSimpleClassName) .modelPackage(packageName) .fieldList(getFields(fieldElements)) .customModifiers(extractCustomModifiers(element)) .build(); } @NotNull private List<DslField> getFields(final List<? extends Element> fieldElements) { return IterableUtils.toList(IterableUtils.transformedIterable(fieldElements, fieldElement -> composeDslField(fieldElement, false))); } private List<String> getAnnotationValueAsType(final AnnotationMirror annotationMirror, final String key) { final var valueAsTypeList = new ArrayList<String>(); final var annotationValue = getAnnotationValue(annotationMirror, key); if (annotationValue != null) { valueAsTypeList.addAll(List.of(annotationValue.toString() .replace(" ", "").replace("{", "") .replace("}", "").replace("\"", "") .split(","))); } return valueAsTypeList; } private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) { AnnotationValue annotationValue = null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { annotationValue = entry.getValue(); } } return annotationValue; } private DslField composeDslField(final Element fieldElement, final boolean insideCollection) { final DslField result; final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement); if (mappingOp.isEmpty()) { if (checkIfOwn(fieldElement)) { result = composeDslComplexField(fieldElement); } else { final String type = extractType(fieldElement); if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) { result = composeCollection(fieldElement); } else { result = composeDslComplexField(fieldElement); } } } else { result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection); } return result; } private DslComplexField composeDslComplexField(final Element element) { return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(element.asType().toString()) .needBuilder(checkIfOwn(element)) .complexType(DslComplexTypeEnum.OBJECT) .fieldValidations(extractValidations(element)) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private DslComplexField composeCollection(final Element element) { final var typeStr = cleanType(element); return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(typeStr) .fields(extractTypes(element)) .fieldValidations(extractValidations(element)) .complexType(DslComplexTypeEnum.COLLECTION) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private boolean checkIfOwn(final Element element) { final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString(); final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString(); return parentType.equalsIgnoreCase(typePackage); } private String extractType(final Element element) { return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString(); } private String cleanType(final Element element) { var finalType = element.asType().toString(); for (var annotation : element.asType().getAnnotationMirrors()) { finalType = finalType.replace(annotation.toString(), ""); } return finalType.replace(", ", ""); } private FieldValidations extractValidations(final Element element) { final var validationBuilder = FieldValidations.builder(); int minValue = 0; int maxValue = 0; final var type = element.asType(); if (CollectionUtils.isNotEmpty(type.getAnnotationMirrors())) { for (var annotation : type.getAnnotationMirrors()) { if (annotation.getAnnotationType().toString().toUpperCase().endsWith("MAX")) { maxValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue(); validationBuilder.max(maxValue); } else { minValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue(); validationBuilder.min(minValue); } } //For random size calculation: defaults to +10 elements max if not defined. maxValue = (maxValue == 0) ? (minValue + 10) : maxValue; validationBuilder.randomSize(new Random().nextInt(maxValue - minValue + 1) + minValue); } return validationBuilder.build(); } @NotNull private List<DslField> extractTypes(final Element element) { final List<DslField> listOfFields; final var listOfCustomMods = new ArrayList<>(CollectionUtils.collect(((DeclaredType) element.asType()).getTypeArguments(), typeUtils::asElement)); if (listOfCustomMods.size() > 1) { listOfFields = new ArrayList<>(CollectionUtils.collect(listOfCustomMods, e -> composeDslField(e, true))); } else { listOfFields = List.of( composeDslSimpleField(listOfCustomMods.get(0), extractMappingByType(listOfCustomMods.get(0))
.orElseThrow(() -> new PactProcessorException(listOfCustomMods.get(0).getSimpleName().toString())),
0
2023-10-25 14:36:38+00:00
12k
granny/Pl3xMap
forge/src/main/java/net/pl3x/map/forge/ForgePlayer.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.authlib.properties.Property; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.UUID; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.markers.Point; import net.pl3x.map.core.player.Player; import net.pl3x.map.core.world.World; import net.pl3x.map.forge.capability.HiddenCapability; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
7,965
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.forge; public class ForgePlayer extends Player { public ForgePlayer(@NotNull ServerPlayer player) { super(player.getScoreboardName(), player); } @Override @SuppressWarnings("unchecked") public @NotNull ServerPlayer getPlayer() { return super.getPlayer(); } @Override public @NotNull String getName() { return getPlayer().getScoreboardName(); } @Override public @NotNull UUID getUUID() { return getPlayer().getUUID(); } @Override public @NotNull World getWorld() { ServerLevel level = (ServerLevel) getPlayer().level(); String name = level.dimension().location().toString();
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.forge; public class ForgePlayer extends Player { public ForgePlayer(@NotNull ServerPlayer player) { super(player.getScoreboardName(), player); } @Override @SuppressWarnings("unchecked") public @NotNull ServerPlayer getPlayer() { return super.getPlayer(); } @Override public @NotNull String getName() { return getPlayer().getScoreboardName(); } @Override public @NotNull UUID getUUID() { return getPlayer().getUUID(); } @Override public @NotNull World getWorld() { ServerLevel level = (ServerLevel) getPlayer().level(); String name = level.dimension().location().toString();
return Pl3xMap.api().getWorldRegistry().getOrDefault(name, () -> new ForgeWorld(level, name));
0
2023-10-26 01:14:31+00:00
12k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/core/SqlAnalysisAspect.java
[ { "identifier": "SqlAnalysis", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysis.java", "snippet": "public class SqlAnalysis {\n\n private static Logger logger = LoggerFactory.getLogger(SqlAnalysis.class);\n\n /**\n * mysql 版本标识\n */\n private static String my...
import com.jd.sql.analysis.analysis.SqlAnalysis; import com.jd.sql.analysis.analysis.SqlAnalysisResultList; import com.jd.sql.analysis.config.JmqConfig; import com.jd.sql.analysis.config.SqlAnalysisConfig; import com.jd.sql.analysis.extract.SqlExtract; import com.jd.sql.analysis.extract.SqlExtractResult; import com.jd.sql.analysis.out.OutModelEnum; import com.jd.sql.analysis.out.SqlScoreResultOutMq; import com.jd.sql.analysis.out.SqlScoreResultOutService; import com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault; import com.jd.sql.analysis.replace.SqlReplace; import com.jd.sql.analysis.replace.SqlReplaceConfig; import com.jd.sql.analysis.rule.SqlScoreRuleLoader; import com.jd.sql.analysis.rule.SqlScoreRuleLoaderRulesEngine; import com.jd.sql.analysis.score.SqlScoreResult; import com.jd.sql.analysis.score.SqlScoreService; import com.jd.sql.analysis.score.SqlScoreServiceRulesEngine; import com.jd.sql.analysis.util.GsonUtil; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.util.Properties;
9,562
package com.jd.sql.analysis.core; /** * @Author huhaitao21 * @Description sql分析切面类 * @Date 22:47 2022/10/25 **/ @Intercepts({@Signature( type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class} ), @Signature( type = Executor.class, method = "update", args = {MappedStatement.class, Object.class} ),@Signature( type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} )}) public class SqlAnalysisAspect implements Interceptor { Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class); /** * 评分规则服务 */ private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine(); /** * 评分结果输出服务 */ private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault(); @Override public Object intercept(Invocation invocation) throws Throwable { try { Object firstArg = invocation.getArgs()[0]; if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){ //sql替换模块 MappedStatement mappedStatement = (MappedStatement)firstArg; String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId()); if(StringUtils.isNotBlank(replaceSql)){ SqlReplace.replace(invocation,replaceSql); } }else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){ //sql 分析模块 //获取入参statement StatementHandler statementHandler = (StatementHandler)invocation.getTarget(); //提取待执行的完整sql语句
package com.jd.sql.analysis.core; /** * @Author huhaitao21 * @Description sql分析切面类 * @Date 22:47 2022/10/25 **/ @Intercepts({@Signature( type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class} ), @Signature( type = Executor.class, method = "update", args = {MappedStatement.class, Object.class} ),@Signature( type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} )}) public class SqlAnalysisAspect implements Interceptor { Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class); /** * 评分规则服务 */ private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine(); /** * 评分结果输出服务 */ private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault(); @Override public Object intercept(Invocation invocation) throws Throwable { try { Object firstArg = invocation.getArgs()[0]; if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){ //sql替换模块 MappedStatement mappedStatement = (MappedStatement)firstArg; String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId()); if(StringUtils.isNotBlank(replaceSql)){ SqlReplace.replace(invocation,replaceSql); } }else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){ //sql 分析模块 //获取入参statement StatementHandler statementHandler = (StatementHandler)invocation.getTarget(); //提取待执行的完整sql语句
SqlExtractResult sqlExtractResult = SqlExtract.extract(statementHandler);
5
2023-10-25 08:59:26+00:00
12k
d0ge/sessionless
src/main/java/one/d4d/sessionless/presenter/KeyPresenter.java
[ { "identifier": "BurpKeysModelPersistence", "path": "src/main/java/burp/config/BurpKeysModelPersistence.java", "snippet": "public class BurpKeysModelPersistence {\n static final String BURP_SETTINGS_NAME = \"one.d4d.sessionless.keys\";\n private final Preferences preferences;\n\n public BurpKey...
import burp.config.BurpKeysModelPersistence; import burp.config.KeysModel; import burp.config.KeysModelListener; import one.d4d.sessionless.forms.WordlistView; import one.d4d.sessionless.forms.dialog.KeyDialog; import one.d4d.sessionless.forms.dialog.NewKeyDialog; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.Utils; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.util.List; import static one.d4d.sessionless.utils.Utils.prettyPrintJSON;
8,539
package one.d4d.sessionless.presenter; public class KeyPresenter extends Presenter { private final KeysModel model; private final PresenterStore presenters; private final WordlistView view; private final DefaultListModel<String> modelSecrets; private final DefaultListModel<String> modelSalts; private final BurpKeysModelPersistence keysModelPersistence; public KeyPresenter(WordlistView view, PresenterStore presenters, KeysModel model, BurpKeysModelPersistence keysModelPersistence, DefaultListModel<String> modelSecrets, DefaultListModel<String> modelSalts) { this.view = view; this.presenters = presenters; this.model = model; this.keysModelPersistence = keysModelPersistence; this.modelSecrets = modelSecrets; this.modelSalts = modelSalts;
package one.d4d.sessionless.presenter; public class KeyPresenter extends Presenter { private final KeysModel model; private final PresenterStore presenters; private final WordlistView view; private final DefaultListModel<String> modelSecrets; private final DefaultListModel<String> modelSalts; private final BurpKeysModelPersistence keysModelPersistence; public KeyPresenter(WordlistView view, PresenterStore presenters, KeysModel model, BurpKeysModelPersistence keysModelPersistence, DefaultListModel<String> modelSecrets, DefaultListModel<String> modelSalts) { this.view = view; this.presenters = presenters; this.model = model; this.keysModelPersistence = keysModelPersistence; this.modelSecrets = modelSecrets; this.modelSalts = modelSalts;
model.addKeyModelListener(new KeysModelListener() {
2
2023-10-30 09:12:06+00:00
12k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/mixin/KeyboardInputMixin.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA...
import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.api.math.vector.Vector3d; import net.leawind.mc.util.math.LMath; import net.minecraft.client.Minecraft; import net.minecraft.client.player.KeyboardInput; import org.apache.logging.log4j.util.PerformanceSensitive; 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;
10,276
package net.leawind.mc.thirdperson.mixin; @Mixin(value=KeyboardInput.class, priority=2000) public class KeyboardInputMixin { /** * 注入到tick的末尾,重新计算 leftImpulse 和 forwardImpulse 的值 */ @Inject(method="tick", at=@At(value="TAIL")) @PerformanceSensitive public void tick_inject_tail (boolean isMoveSlowly, float sneakingSpeedBonus, CallbackInfo ci) { KeyboardInput that = ((KeyboardInput)(Object)this);
package net.leawind.mc.thirdperson.mixin; @Mixin(value=KeyboardInput.class, priority=2000) public class KeyboardInputMixin { /** * 注入到tick的末尾,重新计算 leftImpulse 和 forwardImpulse 的值 */ @Inject(method="tick", at=@At(value="TAIL")) @PerformanceSensitive public void tick_inject_tail (boolean isMoveSlowly, float sneakingSpeedBonus, CallbackInfo ci) { KeyboardInput that = ((KeyboardInput)(Object)this);
if (CameraAgent.isAvailable() && ModReferee.isThirdPerson() && CameraAgent.isControlledCamera()) {
1
2023-10-31 05:52:36+00:00
12k
kandybaby/S3mediaArchival
backend/src/main/java/com/example/mediaarchival/consumers/ArchivingConsumer.java
[ { "identifier": "MediaController", "path": "backend/src/main/java/com/example/mediaarchival/controllers/MediaController.java", "snippet": "@RestController\n@RequestMapping(\"/api/media-objects\")\npublic class MediaController {\n private final MediaRepository mediaRepository;\n\n private final JmsTemp...
import com.example.mediaarchival.controllers.MediaController; import com.example.mediaarchival.models.LibraryModel; import com.example.mediaarchival.models.MediaModel; import com.example.mediaarchival.repositories.MediaRepository; import com.example.mediaarchival.utils.DirectoryUtils; import com.example.mediaarchival.utils.TarUtils; import java.io.File; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload; import software.amazon.awssdk.transfer.s3.model.FileUpload; import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
8,935
package com.example.mediaarchival.consumers; /** * A consumer that processes archiving requests for media objects. * It listens to a JMS queue for paths of media objects to be archived, * creates a TAR archive, and uploads it to an S3 bucket. */ @Component public class ArchivingConsumer { private final S3TransferManager transferManager;
package com.example.mediaarchival.consumers; /** * A consumer that processes archiving requests for media objects. * It listens to a JMS queue for paths of media objects to be archived, * creates a TAR archive, and uploads it to an S3 bucket. */ @Component public class ArchivingConsumer { private final S3TransferManager transferManager;
private final MediaRepository mediaRepository;
3
2023-10-27 01:54:57+00:00
12k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/mapper/GoodsSpecificationOptionMapper.java
[ { "identifier": "GoodsAccessories", "path": "siam-goods/goods-api/src/main/java/com/siam/package_goods/entity/GoodsAccessories.java", "snippet": "@Data\n@TableName(\"tb_goods_accessories\")\n@ApiModel(value = \"商品辅料表\")\npublic class GoodsAccessories {\n\n @TableId(type = IdType.AUTO)\n private In...
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.siam.package_goods.entity.GoodsAccessories; import com.siam.package_goods.entity.GoodsSpecificationOption; import com.siam.package_goods.model.example.GoodsSpecificationOptionExample; import java.math.BigDecimal; import java.util.List;import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import java.util.Map; import com.siam.package_goods.model.dto.GoodsSpecificationOptionDto; import org.apache.ibatis.annotations.*;
8,506
package com.siam.package_goods.mapper; public interface GoodsSpecificationOptionMapper extends BaseMapper<GoodsSpecificationOption> { int countByExample(GoodsSpecificationOptionExample example); int deleteByExample(GoodsSpecificationOptionExample example); int deleteByPrimaryKey(Integer id); int insertSelective(GoodsSpecificationOption record); List<GoodsSpecificationOption> selectByExample(GoodsSpecificationOptionExample example); GoodsSpecificationOption selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") GoodsSpecificationOption record, @Param("example") GoodsSpecificationOptionExample example); int updateByExample(@Param("record") GoodsSpecificationOption record, @Param("example") GoodsSpecificationOptionExample example); int updateByPrimaryKeySelective(GoodsSpecificationOption record); int updateByPrimaryKey(GoodsSpecificationOption record); @ResultMap("BaseResultMap") @Select("<script>select so.* from tb_goods_specification_option so" + "<where> 1=1 " + "<if test=\"specificationOption.id != null\"> AND so.id = #{specificationOption.id} </if>" + "<if test=\"specificationOption.goodsId != null\"> AND so.goods_id = #{specificationOption.goodsId} </if>" + "<if test=\"specificationOption.goodsSpecificationId != null\"> AND so.goods_specification_id = #{specificationOption.goodsSpecificationId} </if>" + "<if test=\"specificationOption.name != null and so.name !=''\"> AND so.name like '%${specificationOption.name}%' </if>" + "<if test=\"specificationOption.price != null\"> AND so.price = #{specificationOption.price} </if>" + "<if test=\"specificationOption.stock != null\"> AND so.stock = #{specificationOption.stock} </if>" + "<if test=\"specificationOption.sortNumber != null\"> AND so.sort_number = #{specificationOption.sortNumber} </if>" + "</where> order by so.id asc" + "</script>") Page<GoodsSpecificationOption> getListByPage(@Param("page") Page page, @Param("specificationOption") GoodsSpecificationOption goodsSpecificationOption); @ResultMap("CustomResultMap") @Select("<script>select so.*, s.name AS specificationName, g.name AS goodsName, g.main_image AS goodsMainImage from tb_goods_specification_option so " + "LEFT JOIN tb_goods_specification s ON s.id = so.goods_specification_id " + "LEFT JOIN tb_goods g ON g.id = s.goods_id " + "<where> 1=1 " + "<if test=\"specificationOptionGoodsDto.id != null\"> AND so.id = #{specificationOptionGoodsDto.id} </if>" + "<if test=\"specificationOptionGoodsDto.goodsId != null\"> AND so.goods_id = #{specificationOptionGoodsDto.goodsId} </if>" + "<if test=\"specificationOptionGoodsDto.goodsSpecificationId != null\"> AND so.goods_specification_id = #{specificationOptionGoodsDto.goodsSpecificationId} </if>" + "<if test=\"specificationOptionGoodsDto.name != null and specificationOptionGoodsDto.name !=''\"> AND so.name like '%${specificationOptionGoodsDto.name}%' </if>" + "<if test=\"specificationOptionGoodsDto.price != null\"> AND so.price = #{specificationOptionGoodsDto.price} </if>" + "<if test=\"specificationOptionGoodsDto.stock != null\"> AND so.stock = #{specificationOptionGoodsDto.stock} </if>" + "<if test=\"specificationOptionGoodsDto.sortNumber != null\"> AND so.sort_number = #{specificationOptionGoodsDto.sortNumber} </if>" + "<if test=\"specificationOptionGoodsDto.specificationName != null and specificationOptionGoodsDto.specificationName !=''\"> AND s.name like '%${specificationOptionGoodsDto.specificationName}%' </if>" + "<if test=\"specificationOptionGoodsDto.goodsName != null and specificationOptionGoodsDto.goodsName !=''\"> AND g.name like '%${specificationOptionGoodsDto.goodsName}%' </if>" + "<if test=\"specificationOptionGoodsDto.goodsMainImage != null and specificationOptionGoodsDto.goodsMainImage !=''\"> AND g.main_image like '%${specificationOptionGoodsDto.goodsMainImage}%' </if>" + "</where> order by g.id desc, s.sort_number asc, so.sort_number asc" + "</script>") Page<Map<String, Object>> getListByPageJoinGoods(@Param("page") Page page, @Param("specificationOptionGoodsDto") GoodsSpecificationOptionDto goodsSpecificationOptionDto); @Select("select IFNULL(max(so.sort_number), 0) from tb_goods_specification_option so where so.goods_specification_id = #{goodsSpecificationId}") int selectMaxSortNumberByGoodsSpecificationId(@Param("goodsSpecificationId") Integer goodsSpecificationId); @Select("<script>select IFNULL(sum(so.price), 0) from tb_goods_specification_option so" + " where so.goods_id = #{goodsId} and so.name in <foreach collection=\"nameList\" item=\"item\" index=\"index\" open=\"(\" separator=\",\" close=\")\">#{item}</foreach>" + "</script>") BigDecimal selectSumPriceByGoodsIdAndName(@Param("goodsId") Integer goodsId, @Param("nameList") List<String> nameList); @Update("update tb_goods_specification_option set price = #{goodsAccessories.price}, stock = #{goodsAccessories.stock}, update_time = now() where name = #{goodsAccessories.name}")
package com.siam.package_goods.mapper; public interface GoodsSpecificationOptionMapper extends BaseMapper<GoodsSpecificationOption> { int countByExample(GoodsSpecificationOptionExample example); int deleteByExample(GoodsSpecificationOptionExample example); int deleteByPrimaryKey(Integer id); int insertSelective(GoodsSpecificationOption record); List<GoodsSpecificationOption> selectByExample(GoodsSpecificationOptionExample example); GoodsSpecificationOption selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") GoodsSpecificationOption record, @Param("example") GoodsSpecificationOptionExample example); int updateByExample(@Param("record") GoodsSpecificationOption record, @Param("example") GoodsSpecificationOptionExample example); int updateByPrimaryKeySelective(GoodsSpecificationOption record); int updateByPrimaryKey(GoodsSpecificationOption record); @ResultMap("BaseResultMap") @Select("<script>select so.* from tb_goods_specification_option so" + "<where> 1=1 " + "<if test=\"specificationOption.id != null\"> AND so.id = #{specificationOption.id} </if>" + "<if test=\"specificationOption.goodsId != null\"> AND so.goods_id = #{specificationOption.goodsId} </if>" + "<if test=\"specificationOption.goodsSpecificationId != null\"> AND so.goods_specification_id = #{specificationOption.goodsSpecificationId} </if>" + "<if test=\"specificationOption.name != null and so.name !=''\"> AND so.name like '%${specificationOption.name}%' </if>" + "<if test=\"specificationOption.price != null\"> AND so.price = #{specificationOption.price} </if>" + "<if test=\"specificationOption.stock != null\"> AND so.stock = #{specificationOption.stock} </if>" + "<if test=\"specificationOption.sortNumber != null\"> AND so.sort_number = #{specificationOption.sortNumber} </if>" + "</where> order by so.id asc" + "</script>") Page<GoodsSpecificationOption> getListByPage(@Param("page") Page page, @Param("specificationOption") GoodsSpecificationOption goodsSpecificationOption); @ResultMap("CustomResultMap") @Select("<script>select so.*, s.name AS specificationName, g.name AS goodsName, g.main_image AS goodsMainImage from tb_goods_specification_option so " + "LEFT JOIN tb_goods_specification s ON s.id = so.goods_specification_id " + "LEFT JOIN tb_goods g ON g.id = s.goods_id " + "<where> 1=1 " + "<if test=\"specificationOptionGoodsDto.id != null\"> AND so.id = #{specificationOptionGoodsDto.id} </if>" + "<if test=\"specificationOptionGoodsDto.goodsId != null\"> AND so.goods_id = #{specificationOptionGoodsDto.goodsId} </if>" + "<if test=\"specificationOptionGoodsDto.goodsSpecificationId != null\"> AND so.goods_specification_id = #{specificationOptionGoodsDto.goodsSpecificationId} </if>" + "<if test=\"specificationOptionGoodsDto.name != null and specificationOptionGoodsDto.name !=''\"> AND so.name like '%${specificationOptionGoodsDto.name}%' </if>" + "<if test=\"specificationOptionGoodsDto.price != null\"> AND so.price = #{specificationOptionGoodsDto.price} </if>" + "<if test=\"specificationOptionGoodsDto.stock != null\"> AND so.stock = #{specificationOptionGoodsDto.stock} </if>" + "<if test=\"specificationOptionGoodsDto.sortNumber != null\"> AND so.sort_number = #{specificationOptionGoodsDto.sortNumber} </if>" + "<if test=\"specificationOptionGoodsDto.specificationName != null and specificationOptionGoodsDto.specificationName !=''\"> AND s.name like '%${specificationOptionGoodsDto.specificationName}%' </if>" + "<if test=\"specificationOptionGoodsDto.goodsName != null and specificationOptionGoodsDto.goodsName !=''\"> AND g.name like '%${specificationOptionGoodsDto.goodsName}%' </if>" + "<if test=\"specificationOptionGoodsDto.goodsMainImage != null and specificationOptionGoodsDto.goodsMainImage !=''\"> AND g.main_image like '%${specificationOptionGoodsDto.goodsMainImage}%' </if>" + "</where> order by g.id desc, s.sort_number asc, so.sort_number asc" + "</script>") Page<Map<String, Object>> getListByPageJoinGoods(@Param("page") Page page, @Param("specificationOptionGoodsDto") GoodsSpecificationOptionDto goodsSpecificationOptionDto); @Select("select IFNULL(max(so.sort_number), 0) from tb_goods_specification_option so where so.goods_specification_id = #{goodsSpecificationId}") int selectMaxSortNumberByGoodsSpecificationId(@Param("goodsSpecificationId") Integer goodsSpecificationId); @Select("<script>select IFNULL(sum(so.price), 0) from tb_goods_specification_option so" + " where so.goods_id = #{goodsId} and so.name in <foreach collection=\"nameList\" item=\"item\" index=\"index\" open=\"(\" separator=\",\" close=\")\">#{item}</foreach>" + "</script>") BigDecimal selectSumPriceByGoodsIdAndName(@Param("goodsId") Integer goodsId, @Param("nameList") List<String> nameList); @Update("update tb_goods_specification_option set price = #{goodsAccessories.price}, stock = #{goodsAccessories.stock}, update_time = now() where name = #{goodsAccessories.name}")
void updateByGoodsAccessories(@Param("goodsAccessories") GoodsAccessories goodsAccessories);
0
2023-10-26 10:45:10+00:00
12k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/view/MozcDrawableFactory.java
[ { "identifier": "MozcLog", "path": "app/src/main/java/sh/eliza/japaneseinput/MozcLog.java", "snippet": "public class MozcLog {\n private MozcLog() {}\n\n public static boolean isLoggable(int logLevel) {\n return Log.isLoggable(MozcUtil.LOGTAG, logLevel);\n }\n\n public static void v(String msg) {...
import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Picture; import android.graphics.RadialGradient; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import androidx.core.content.res.ResourcesCompat; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import sh.eliza.japaneseinput.MozcLog; import sh.eliza.japaneseinput.MozcUtil; import sh.eliza.japaneseinput.vectorgraphic.BufferedDrawable;
8,460
resetStyle(style); parseStyle(stream, skin, style); canvas.drawLine(x1, y1, x2, y2, style.paint); } } break; } case COMMAND_PICTURE_DRAW_RECT: { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); float w = readCompressedFloat(stream); float h = readCompressedFloat(stream); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawRect(x, y, x + w, y + h, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawRect(x, y, x + w, y + h, style.paint); } } break; } case COMMAND_PICTURE_DRAW_CIRCLE: { float cx = readCompressedFloat(stream); float cy = readCompressedFloat(stream); float r = readCompressedFloat(stream); RectF bound = new RectF(cx - r, cy - r, cx + r, cy + r); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawOval(bound, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawOval(bound, style.paint); } } break; } case COMMAND_PICTURE_DRAW_ELLIPSE: { float cx = readCompressedFloat(stream); float cy = readCompressedFloat(stream); float rx = readCompressedFloat(stream); float ry = readCompressedFloat(stream); RectF bound = new RectF(cx - rx, cy - ry, cx + rx, cy + ry); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawOval(bound, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawOval(bound, style.paint); } } break; } case COMMAND_PICTURE_DRAW_GROUP_START: { float m11 = readCompressedFloat(stream); float m21 = readCompressedFloat(stream); float m31 = readCompressedFloat(stream); float m12 = readCompressedFloat(stream); float m22 = readCompressedFloat(stream); float m32 = readCompressedFloat(stream); float m13 = readCompressedFloat(stream); float m23 = readCompressedFloat(stream); float m33 = readCompressedFloat(stream); Matrix matrix = new Matrix(); matrix.setValues(new float[] {m11, m12, m13, m21, m22, m23, m31, m32, m33}); canvas.save(); canvas.concat(matrix); break; } case COMMAND_PICTURE_DRAW_GROUP_END: canvas.restore(); break; case COMMAND_PICTURE_DRAW_TEXT: { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); short stringSize = stream.readShort(); byte[] stringBuffer = new byte[stringSize]; stream.read(stringBuffer); String string = new String(stringBuffer, Charsets.UTF_8); int size = stream.readByte(); if (size == 0) { resetStyle(style); canvas.drawText(string, x, y, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); float drawY = style.dominantBaseline == COMMAND_PICTURE_PAINT_DOMINANTE_BASELINE_AUTO ? y : y - (style.paint.ascent() + style.paint.descent()) / 2; canvas.drawText(string, x, drawY, style.paint); } } break; } default: MozcLog.e("unknown command " + command); } } picture.endRecording(); // H/W accelerated canvas doesn't support Picture so buffering is required.
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput.view; /** * Factory to create Drawables from raw resources which is in mozc original format. * * <p>Implementation note: We decided to use vector-rendering to support various devices which are * different display resolutions. For that purpose, we needed to have some vector format. {@code * PictureDrawable}'s serialization/deserialization seemed what we needed, but it turned out that * its binary format seems not compatible among various devices, unfortunately. So, we decided to * use our original format, and this class parses it. Also, for performance purpose, this class * caches the parsed drawable. */ class MozcDrawableFactory { private static class MozcStyle { final Paint paint = new Paint(); int dominantBaseline = COMMAND_PICTURE_PAINT_DOMINANTE_BASELINE_AUTO; } private static final int DRAWABLE_PICTURE = 1; private static final int DRAWABLE_STATE_LIST = 2; private static final int COMMAND_PICTURE_EOP = 0; private static final int COMMAND_PICTURE_DRAW_PATH = 1; private static final int COMMAND_PICTURE_DRAW_POLYLINE = 2; private static final int COMMAND_PICTURE_DRAW_POLYGON = 3; private static final int COMMAND_PICTURE_DRAW_LINE = 4; private static final int COMMAND_PICTURE_DRAW_RECT = 5; private static final int COMMAND_PICTURE_DRAW_CIRCLE = 6; private static final int COMMAND_PICTURE_DRAW_ELLIPSE = 7; private static final int COMMAND_PICTURE_DRAW_GROUP_START = 8; private static final int COMMAND_PICTURE_DRAW_GROUP_END = 9; private static final int COMMAND_PICTURE_DRAW_TEXT = 10; private static final int COMMAND_PICTURE_PATH_EOP = 0; private static final int COMMAND_PICTURE_PATH_MOVE = 1; private static final int COMMAND_PICTURE_PATH_LINE = 2; private static final int COMMAND_PICTURE_PATH_HORIZONTAL_LINE = 3; private static final int COMMAND_PICTURE_PATH_VERTICAL_LINE = 4; private static final int COMMAND_PICTURE_PATH_CURVE = 5; private static final int COMMAND_PICTURE_PATH_CONTINUED_CURVE = 6; private static final int COMMAND_PICTURE_PATH_CLOSE = 7; private static final int COMMAND_PICTURE_PAINT_EOP = 0; private static final int COMMAND_PICTURE_PAINT_STYLE = 1; private static final int COMMAND_PICTURE_PAINT_COLOR = 2; private static final int COMMAND_PICTURE_PAINT_SHADOW = 3; private static final int COMMAND_PICTURE_PAINT_STROKE_WIDTH = 4; private static final int COMMAND_PICTURE_PAINT_STROKE_CAP = 5; private static final int COMMAND_PICTURE_PAINT_STROKE_JOIN = 6; private static final int COMMAND_PICTURE_PAINT_SHADER = 7; private static final int COMMAND_PICTURE_PAINT_FONT_SIZE = 8; private static final int COMMAND_PICTURE_PAINT_TEXT_ANCHOR = 9; private static final int COMMAND_PICTURE_PAINT_DOMINANT_BASELINE = 10; private static final int COMMAND_PICTURE_PAINT_FONT_WEIGHT = 11; private static final int COMMAND_PICTURE_PAINT_TEXT_ANCHOR_START = 0; private static final int COMMAND_PICTURE_PAINT_TEXT_ANCHOR_MIDDLE = 1; private static final int COMMAND_PICTURE_PAINT_TEXT_ANCHOR_END = 2; private static final int COMMAND_PICTURE_PAINT_DOMINANTE_BASELINE_AUTO = 0; @SuppressWarnings("unused") private static final int COMMAND_PICTURE_PAINT_DOMINANTE_BASELINE_CENTRAL = 1; @SuppressWarnings("unused") private static final int COMMAND_PICTURE_PAINT_FONT_WEIGHT_NORMAL = 0; private static final int COMMAND_PICTURE_PAINT_FONT_WEIGHT_BOLD = 1; private static final int COMMAND_PICTURE_SHADER_LINEAR_GRADIENT = 1; private static final int COMMAND_PICTURE_SHADER_RADIAL_GRADIENT = 2; private static final int[] EMPTY_STATE_LIST = {}; private static final String FONT_PATH = "subset_font.otf"; private final Resources resources; private final WeakDrawableCache cacheMap = new WeakDrawableCache(); private final Skin skin; private static volatile Optional<Typeface> typeface = Optional.absent(); MozcDrawableFactory(Resources resources, Skin skin) { this.resources = Preconditions.checkNotNull(resources); this.skin = Preconditions.checkNotNull(skin); ensureTypeface(resources.getAssets()); } Optional<Drawable> getDrawable(int resourceId) { if (!resources.getResourceTypeName(resourceId).equalsIgnoreCase("raw")) { // For non-"raw" resources, just delegate loading to Resources. return Optional.fromNullable( ResourcesCompat.getDrawable(resources, resourceId, /* theme= */ null)); } Integer key = resourceId; Optional<Drawable> drawable = cacheMap.get(key); if (!drawable.isPresent()) { InputStream stream = resources.openRawResource(resourceId); try { boolean success = false; try { drawable = createDrawable(new DataInputStream(stream), skin); success = true; } finally { MozcUtil.close(stream, !success); } } catch (IOException e) { MozcLog.e("Failed to parse file", e); } if (drawable.isPresent()) { cacheMap.put(key, drawable.get()); } } return drawable; } private static Optional<Drawable> createDrawable(DataInputStream stream, Skin skin) throws IOException { Preconditions.checkNotNull(stream); byte tag = stream.readByte(); switch (tag) { case DRAWABLE_PICTURE: return Optional.of(createBufferedPictureDrawable(stream, skin)); case DRAWABLE_STATE_LIST: return Optional.of(createStateListDrawable(stream, skin)); default: MozcLog.e("Unknown tag: " + tag); } return Optional.absent(); } private static Drawable createBufferedPictureDrawable(DataInputStream stream, Skin skin) throws IOException { Preconditions.checkNotNull(stream); Preconditions.checkNotNull(skin); // The first eight bytes are width and height (four bytes for each). int width = stream.readUnsignedShort(); int height = stream.readUnsignedShort(); Picture picture = new Picture(); Canvas canvas = picture.beginRecording(width, height); MozcStyle style = new MozcStyle(); resetStyle(style); LOOP: while (true) { byte command = stream.readByte(); switch (command) { case COMMAND_PICTURE_EOP: // The end of picture. break LOOP; case COMMAND_PICTURE_DRAW_PATH: { Path path = createPath(stream); int size = stream.readByte(); if (size == 0) { resetStyle(style); canvas.drawPath(path, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawPath(path, style.paint); } } break; } case COMMAND_PICTURE_DRAW_POLYLINE: { int length = stream.readUnsignedByte(); if (length < 2 || length % 2 != 0) { throw new IllegalArgumentException(); } float[] points = new float[length]; for (int i = 0; i < length; ++i) { points[i] = readCompressedFloat(stream); } int size = stream.readByte(); if (size == 0) { resetStyle(style); for (int i = 0; i < length - 2; i += 2) { canvas.drawLine( points[i], points[i + 1], points[i + 2], points[i + 3], style.paint); } } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); for (int j = 0; j < length - 2; j += 2) { canvas.drawLine( points[j], points[j + 1], points[j + 2], points[j + 3], style.paint); } } } break; } case COMMAND_PICTURE_DRAW_POLYGON: { int length = stream.readUnsignedByte(); if (length < 2 || length % 2 != 0) { throw new IllegalArgumentException(); } Path path = new Path(); { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); path.moveTo(x, y); } for (int i = 2; i < length; i += 2) { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); path.lineTo(x, y); } path.close(); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawPath(path, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawPath(path, style.paint); } } break; } case COMMAND_PICTURE_DRAW_LINE: { float x1 = readCompressedFloat(stream); float y1 = readCompressedFloat(stream); float x2 = readCompressedFloat(stream); float y2 = readCompressedFloat(stream); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawLine(x1, y1, x2, y2, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawLine(x1, y1, x2, y2, style.paint); } } break; } case COMMAND_PICTURE_DRAW_RECT: { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); float w = readCompressedFloat(stream); float h = readCompressedFloat(stream); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawRect(x, y, x + w, y + h, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawRect(x, y, x + w, y + h, style.paint); } } break; } case COMMAND_PICTURE_DRAW_CIRCLE: { float cx = readCompressedFloat(stream); float cy = readCompressedFloat(stream); float r = readCompressedFloat(stream); RectF bound = new RectF(cx - r, cy - r, cx + r, cy + r); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawOval(bound, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawOval(bound, style.paint); } } break; } case COMMAND_PICTURE_DRAW_ELLIPSE: { float cx = readCompressedFloat(stream); float cy = readCompressedFloat(stream); float rx = readCompressedFloat(stream); float ry = readCompressedFloat(stream); RectF bound = new RectF(cx - rx, cy - ry, cx + rx, cy + ry); int size = stream.readUnsignedByte(); if (size == 0) { resetStyle(style); canvas.drawOval(bound, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); canvas.drawOval(bound, style.paint); } } break; } case COMMAND_PICTURE_DRAW_GROUP_START: { float m11 = readCompressedFloat(stream); float m21 = readCompressedFloat(stream); float m31 = readCompressedFloat(stream); float m12 = readCompressedFloat(stream); float m22 = readCompressedFloat(stream); float m32 = readCompressedFloat(stream); float m13 = readCompressedFloat(stream); float m23 = readCompressedFloat(stream); float m33 = readCompressedFloat(stream); Matrix matrix = new Matrix(); matrix.setValues(new float[] {m11, m12, m13, m21, m22, m23, m31, m32, m33}); canvas.save(); canvas.concat(matrix); break; } case COMMAND_PICTURE_DRAW_GROUP_END: canvas.restore(); break; case COMMAND_PICTURE_DRAW_TEXT: { float x = readCompressedFloat(stream); float y = readCompressedFloat(stream); short stringSize = stream.readShort(); byte[] stringBuffer = new byte[stringSize]; stream.read(stringBuffer); String string = new String(stringBuffer, Charsets.UTF_8); int size = stream.readByte(); if (size == 0) { resetStyle(style); canvas.drawText(string, x, y, style.paint); } else { for (int i = 0; i < size; ++i) { resetStyle(style); parseStyle(stream, skin, style); float drawY = style.dominantBaseline == COMMAND_PICTURE_PAINT_DOMINANTE_BASELINE_AUTO ? y : y - (style.paint.ascent() + style.paint.descent()) / 2; canvas.drawText(string, x, drawY, style.paint); } } break; } default: MozcLog.e("unknown command " + command); } } picture.endRecording(); // H/W accelerated canvas doesn't support Picture so buffering is required.
return new BufferedDrawable(new MozcPictureDrawable(picture));
1
2023-10-25 07:33:25+00:00
12k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/impl/gui/clickgui/Button.java
[ { "identifier": "TempleClient", "path": "src/main/java/xyz/templecheats/templeclient/TempleClient.java", "snippet": "@Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION)\npublic class TempleClient {\n public static String name = \"Temple Client 1.8.2\";\n\n pu...
import java.util.ArrayList; import net.minecraft.client.renderer.GlStateManager; import xyz.templecheats.templeclient.TempleClient; import xyz.templecheats.templeclient.impl.modules.client.ClickGUI; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.Setting; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.component.Component; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.component.varients.Keybind; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.component.varients.ModeButton; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.component.varients.Slider; import xyz.templecheats.templeclient.impl.modules.Module; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.component.varients.Checkbox; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import xyz.templecheats.templeclient.impl.gui.font.FontUtils;
7,563
package xyz.templecheats.templeclient.impl.gui.clickgui; public class Button extends Component { public Module mod; public Frame parent; public int offset; private boolean isHovered; private ArrayList<Component> subcomponents; public boolean open; public int height; public FontRenderer fr = Minecraft.getMinecraft().fontRenderer; public Button(Module mod, Frame parent, int offset) { this.mod = mod; this.parent = parent; this.offset = offset; this.height = 12; this.subcomponents = new ArrayList<Component>(); this.open = false; int opY = offset + 12; if(TempleClient.settingsManager.getSettingsByMod(mod) != null) { for(Setting s : TempleClient.settingsManager.getSettingsByMod(mod)){ if(s.isCombo()){ this.subcomponents.add(new ModeButton(s, this, mod, opY)); opY += 12; } if(s.isSlider()){ this.subcomponents.add(new Slider(s, this, opY)); opY += 12; } if(s.isCheck()){ this.subcomponents.add(new Checkbox(s, this, opY)); opY += 12; } } }
package xyz.templecheats.templeclient.impl.gui.clickgui; public class Button extends Component { public Module mod; public Frame parent; public int offset; private boolean isHovered; private ArrayList<Component> subcomponents; public boolean open; public int height; public FontRenderer fr = Minecraft.getMinecraft().fontRenderer; public Button(Module mod, Frame parent, int offset) { this.mod = mod; this.parent = parent; this.offset = offset; this.height = 12; this.subcomponents = new ArrayList<Component>(); this.open = false; int opY = offset + 12; if(TempleClient.settingsManager.getSettingsByMod(mod) != null) { for(Setting s : TempleClient.settingsManager.getSettingsByMod(mod)){ if(s.isCombo()){ this.subcomponents.add(new ModeButton(s, this, mod, opY)); opY += 12; } if(s.isSlider()){ this.subcomponents.add(new Slider(s, this, opY)); opY += 12; } if(s.isCheck()){ this.subcomponents.add(new Checkbox(s, this, opY)); opY += 12; } } }
this.subcomponents.add(new Keybind(this, opY));
4
2023-10-28 12:03:50+00:00
12k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/util/PropertiesParsingHelper.java
[ { "identifier": "ContinuityClient", "path": "src/main/java/me/pepperbell/continuity/client/ContinuityClient.java", "snippet": "public class ContinuityClient implements ClientModInitializer {\n\tpublic static final String ID = \"continuity\";\n\tpublic static final String NAME = \"Continuity\";\n\tpublic...
import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.function.Predicate; import org.apache.commons.io.FilenameUtils; import org.jetbrains.annotations.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import me.pepperbell.continuity.client.ContinuityClient; import me.pepperbell.continuity.client.processor.Symmetry; import me.pepperbell.continuity.client.properties.BaseCTMProperties; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.state.property.Property; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; import net.minecraft.util.registry.Registry;
7,867
package me.pepperbell.continuity.client.util; public final class PropertiesParsingHelper { @Nullable public static ImmutableSet<Identifier> parseMatchTiles(Properties properties, String propertyKey, Identifier fileLocation, String packName) { String matchTilesStr = properties.getProperty(propertyKey); if (matchTilesStr != null) { matchTilesStr = matchTilesStr.trim(); String[] matchTileStrs = matchTilesStr.split(" "); if (matchTileStrs.length != 0) { String basePath = FilenameUtils.getPath(fileLocation.getPath()); ImmutableSet.Builder<Identifier> setBuilder = ImmutableSet.builder(); for (int i = 0; i < matchTileStrs.length; i++) { String matchTileStr = matchTileStrs[i]; if (!matchTileStr.isEmpty()) { String[] parts = matchTileStr.split(":", 2); if (parts.length != 0) { String namespace; String path; if (parts.length > 1) { namespace = parts[0]; path = parts[1]; } else { namespace = fileLocation.getNamespace(); path = parts[0]; } if (path.endsWith(".png")) { path = path.substring(0, path.length() - 4); } if (path.startsWith("./")) { path = basePath + path.substring(2); } else if (path.startsWith("~/")) { path = "optifine/" + path.substring(2); } else if (path.startsWith("/")) { path = "optifine/" + path.substring(1); } else if (!path.contains("/")) { namespace = null; path = "textures/block/" + path; } if (path.startsWith("textures/")) { path = path.substring(9); } else if (path.startsWith("optifine/")) { path = BaseCTMProperties.getRedirectPath(path + ".png"); } try { setBuilder.add(new Identifier(namespace, path)); } catch (InvalidIdentifierException e) {
package me.pepperbell.continuity.client.util; public final class PropertiesParsingHelper { @Nullable public static ImmutableSet<Identifier> parseMatchTiles(Properties properties, String propertyKey, Identifier fileLocation, String packName) { String matchTilesStr = properties.getProperty(propertyKey); if (matchTilesStr != null) { matchTilesStr = matchTilesStr.trim(); String[] matchTileStrs = matchTilesStr.split(" "); if (matchTileStrs.length != 0) { String basePath = FilenameUtils.getPath(fileLocation.getPath()); ImmutableSet.Builder<Identifier> setBuilder = ImmutableSet.builder(); for (int i = 0; i < matchTileStrs.length; i++) { String matchTileStr = matchTileStrs[i]; if (!matchTileStr.isEmpty()) { String[] parts = matchTileStr.split(":", 2); if (parts.length != 0) { String namespace; String path; if (parts.length > 1) { namespace = parts[0]; path = parts[1]; } else { namespace = fileLocation.getNamespace(); path = parts[0]; } if (path.endsWith(".png")) { path = path.substring(0, path.length() - 4); } if (path.startsWith("./")) { path = basePath + path.substring(2); } else if (path.startsWith("~/")) { path = "optifine/" + path.substring(2); } else if (path.startsWith("/")) { path = "optifine/" + path.substring(1); } else if (!path.contains("/")) { namespace = null; path = "textures/block/" + path; } if (path.startsWith("textures/")) { path = path.substring(9); } else if (path.startsWith("optifine/")) { path = BaseCTMProperties.getRedirectPath(path + ".png"); } try { setBuilder.add(new Identifier(namespace, path)); } catch (InvalidIdentifierException e) {
ContinuityClient.LOGGER.warn("Invalid '" + propertyKey + "' element '" + matchTileStr + "' at index " + i + " in file '" + fileLocation + "' in pack '" + packName + "'", e);
0
2023-10-29 00:08:50+00:00
12k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs1/F1NEnum.java
[ { "identifier": "Decimal", "path": "src/main/java/yaa/ast/Decimal.java", "snippet": "public class Decimal extends Stmt {\r\n public YaaToken token;\r\n\r\n public Decimal(YaaToken token) {\r\n this.token = token;\r\n }\r\n\r\n @Override\r\n public YaaInfo visit(FileState fs) {\r\n return fs.$...
import yaa.ast.Decimal; import yaa.ast.False; import yaa.ast.NewEnum; import yaa.ast.True; import yaa.parser.TokenUtils; import yaa.pojos.*; import yaa.pojos.jMold.JMold; import java.util.*; import static yaa.pojos.GlobalData.fs1; import static yaa.pojos.GlobalData.int$name; import static yaa.pojos.NameUtils.dottedStoreName;
9,704
package yaa.semantic.passes.fs1; public class F1NEnum { private static final Set<String> enumFunProps = new HashSet<>(3); static { enumFunProps.add("privacy"); } public static YaaInfo f1NewEnum(NewEnum newEnum) { var simpleClzName = newEnum.name.content; var dottedStoreName = dottedStoreName(simpleClzName); var fs1Enum = new YaaClz(dottedStoreName); fs1Enum.isFinal = true; var list = new ArrayList<YaaClz>(1); list.add(fs1Enum); var clz = new JMold().newClz("java.lang.Enum"); fs1Enum.parent = changeClzBounds(clz, list); fs1Enum.category = TypeCategory.enum_c; fs1Enum.startLine = newEnum.start.line; fs1Enum.column = newEnum.start.column; fs1Enum.endLine = newEnum.close.line; // Fs1Utils.isItDefined(simpleClzName, newClass.address()); //define the class in the enclosing scope, so that, sibling constructs can find it fs1.putSymbol(simpleClzName, fs1Enum); fs1.putSymbol(newEnum.placeOfUse(), fs1Enum); fs1.newTable(); //the lowercase is necessary so that pool/Pool won't interfere with pool/pool GlobalData.usedClzNames.get(fs1.path).add(fs1Enum.codeName.toLowerCase()); for (var dec : newEnum.vDeclarations) { F1VDec.f1stmtDec(dec); var fieldName = dec.name.content; var field = (YaaField) fs1.getSymbol(fieldName); field.owner = fs1Enum.codeName; fs1Enum.instance$fields.put(fieldName, field); } for (var def : newEnum.vDefinitions) { F1VDef.f1typeDef(def); var fieldName = def.name.content; var field = (YaaField) fs1.getSymbol(fieldName); field.owner = fs1Enum.codeName; fs1Enum.instance$fields.put(fieldName, field); } for (int i = 0; i < newEnum.enumOptions.size(); i++) { var option = newEnum.enumOptions.get(i); var name = option.name.content; var previouslyDefined = fs1.getAlreadyDefinedSymbolInPass1(name); if (previouslyDefined instanceof YaaField){ throw new YaaError(option.name.placeOfUse(), "'" + name +"' has been used by another symbol at " + previouslyDefined.placeOfUSe()); } var enum_field = new YaaField(name, true); enum_field.itIsWhat = FieldIsWhat.top$field; fs1Enum.enumIndices.put(name, i); enum_field.isEnumField = true; enum_field.data = fs1Enum; fs1Enum.instance$fields.put(name, enum_field); } for (var trait$clz : newEnum.implementations) { F1BlockInClz.f1BlockInClz(trait$clz); } for (var block : newEnum.runBlocks) { fs1.newTable(); for (var stmt : block.stmts) { stmt.visit(fs1); } fs1.storeTable(block); fs1.popTable(); } if (newEnum.inits.size() == 0) { var stubInit = new YaaInit(); fs1Enum.inits.add(stubInit); } else { for (var init : newEnum.inits) { fs1Enum.inits.add(F1Init.f1Init(init)); } } for (var method : newEnum.methods) { var mtdName = method.name.content; var newMethod = (YaaFun) F1NFun.f1NewFun(method); for (var metaCall : method.metaCalls) { var meta = fs1.getSymbol(metaCall.name.content); if (meta instanceof YaaMeta && meta.name.equals(GlobalData.configMetaClzName)) { for (var arg : metaCall.arguments.entrySet()) { var argument = arg.getKey(); switch (argument.content) { case "privacy" -> {
package yaa.semantic.passes.fs1; public class F1NEnum { private static final Set<String> enumFunProps = new HashSet<>(3); static { enumFunProps.add("privacy"); } public static YaaInfo f1NewEnum(NewEnum newEnum) { var simpleClzName = newEnum.name.content; var dottedStoreName = dottedStoreName(simpleClzName); var fs1Enum = new YaaClz(dottedStoreName); fs1Enum.isFinal = true; var list = new ArrayList<YaaClz>(1); list.add(fs1Enum); var clz = new JMold().newClz("java.lang.Enum"); fs1Enum.parent = changeClzBounds(clz, list); fs1Enum.category = TypeCategory.enum_c; fs1Enum.startLine = newEnum.start.line; fs1Enum.column = newEnum.start.column; fs1Enum.endLine = newEnum.close.line; // Fs1Utils.isItDefined(simpleClzName, newClass.address()); //define the class in the enclosing scope, so that, sibling constructs can find it fs1.putSymbol(simpleClzName, fs1Enum); fs1.putSymbol(newEnum.placeOfUse(), fs1Enum); fs1.newTable(); //the lowercase is necessary so that pool/Pool won't interfere with pool/pool GlobalData.usedClzNames.get(fs1.path).add(fs1Enum.codeName.toLowerCase()); for (var dec : newEnum.vDeclarations) { F1VDec.f1stmtDec(dec); var fieldName = dec.name.content; var field = (YaaField) fs1.getSymbol(fieldName); field.owner = fs1Enum.codeName; fs1Enum.instance$fields.put(fieldName, field); } for (var def : newEnum.vDefinitions) { F1VDef.f1typeDef(def); var fieldName = def.name.content; var field = (YaaField) fs1.getSymbol(fieldName); field.owner = fs1Enum.codeName; fs1Enum.instance$fields.put(fieldName, field); } for (int i = 0; i < newEnum.enumOptions.size(); i++) { var option = newEnum.enumOptions.get(i); var name = option.name.content; var previouslyDefined = fs1.getAlreadyDefinedSymbolInPass1(name); if (previouslyDefined instanceof YaaField){ throw new YaaError(option.name.placeOfUse(), "'" + name +"' has been used by another symbol at " + previouslyDefined.placeOfUSe()); } var enum_field = new YaaField(name, true); enum_field.itIsWhat = FieldIsWhat.top$field; fs1Enum.enumIndices.put(name, i); enum_field.isEnumField = true; enum_field.data = fs1Enum; fs1Enum.instance$fields.put(name, enum_field); } for (var trait$clz : newEnum.implementations) { F1BlockInClz.f1BlockInClz(trait$clz); } for (var block : newEnum.runBlocks) { fs1.newTable(); for (var stmt : block.stmts) { stmt.visit(fs1); } fs1.storeTable(block); fs1.popTable(); } if (newEnum.inits.size() == 0) { var stubInit = new YaaInit(); fs1Enum.inits.add(stubInit); } else { for (var init : newEnum.inits) { fs1Enum.inits.add(F1Init.f1Init(init)); } } for (var method : newEnum.methods) { var mtdName = method.name.content; var newMethod = (YaaFun) F1NFun.f1NewFun(method); for (var metaCall : method.metaCalls) { var meta = fs1.getSymbol(metaCall.name.content); if (meta instanceof YaaMeta && meta.name.equals(GlobalData.configMetaClzName)) { for (var arg : metaCall.arguments.entrySet()) { var argument = arg.getKey(); switch (argument.content) { case "privacy" -> {
if (arg.getValue() instanceof Decimal decimal) {
0
2023-10-26 17:41:13+00:00
12k
echcz/web-service
src/main/jooq/cn/echcz/webservice/adapter/repository/Keys.java
[ { "identifier": "ActionLogTable", "path": "src/main/jooq/cn/echcz/webservice/adapter/repository/tables/ActionLogTable.java", "snippet": "@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class ActionLogTable extends TableImpl<ActionLogRecord> {\n\n private static final long serialVe...
import cn.echcz.webservice.adapter.repository.tables.ActionLogTable; import cn.echcz.webservice.adapter.repository.tables.DocumentTable; import cn.echcz.webservice.adapter.repository.tables.records.ActionLogRecord; import cn.echcz.webservice.adapter.repository.tables.records.DocumentRecord; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.Internal;
7,362
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository; /** * A class modelling foreign key relationships and constraints of tables in * the default schema. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Keys { // ------------------------------------------------------------------------- // UNIQUE and PRIMARY KEY definitions // -------------------------------------------------------------------------
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository; /** * A class modelling foreign key relationships and constraints of tables in * the default schema. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Keys { // ------------------------------------------------------------------------- // UNIQUE and PRIMARY KEY definitions // -------------------------------------------------------------------------
public static final UniqueKey<ActionLogRecord> KEY_ACTION_LOG_PRIMARY = Internal.createUniqueKey(ActionLogTable.ACTION_LOG, DSL.name("KEY_action_log_PRIMARY"), new TableField[] { ActionLogTable.ACTION_LOG.ID }, true);
2
2023-10-30 18:55:49+00:00
12k
tom5454/Toms-Peripherals
Forge/src/platform-shared/java/com/tom/peripherals/Content.java
[ { "identifier": "GPUBlock", "path": "Forge/src/platform-shared/java/com/tom/peripherals/block/GPUBlock.java", "snippet": "public class GPUBlock extends Block implements EntityBlock {\n\n\tpublic GPUBlock() {\n\t\tsuper(Block.Properties.of().mapColor(DyeColor.WHITE).sound(SoundType.METAL).strength(5));\n...
import java.util.function.Function; import java.util.function.Supplier; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import com.tom.peripherals.block.GPUBlock; import com.tom.peripherals.block.MonitorBlock; import com.tom.peripherals.block.RedstonePortBlock; import com.tom.peripherals.block.WatchDogTimerBlock; import com.tom.peripherals.block.entity.GPUBlockEntity; import com.tom.peripherals.block.entity.MonitorBlockEntity; import com.tom.peripherals.block.entity.RedstonePortBlockEntity; import com.tom.peripherals.block.entity.WatchDogTimerBlockEntity; import com.tom.peripherals.platform.GameObject; import com.tom.peripherals.platform.GameObject.GameObjectBlockEntity; import com.tom.peripherals.platform.GameObject.GameRegistryBE.BlockEntityFactory; import com.tom.peripherals.platform.Platform;
10,689
package com.tom.peripherals; public class Content { public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new); public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new); public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new); public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new); public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties())); public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties()));
package com.tom.peripherals; public class Content { public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new); public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new); public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new); public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new); public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties())); public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties()));
public static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity("gpu", GPUBlockEntity::new, gpu);
9
2023-10-30 17:05:11+00:00
12k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/ui/assertions/AssertionRule.java
[ { "identifier": "AssertionResult", "path": "src/main/java/com/insidious/plugin/assertions/AssertionResult.java", "snippet": "public class AssertionResult {\n private final Map<String, Boolean> results = new HashMap<>();\n private boolean passing = false;\n\n public void addResult(AtomicAssertio...
import com.insidious.plugin.assertions.AssertionResult; import com.insidious.plugin.assertions.AssertionType; import com.insidious.plugin.assertions.AtomicAssertion; import com.insidious.plugin.assertions.Expression; import com.insidious.plugin.util.LoggerUtil; import com.insidious.plugin.util.UIUtils; import com.intellij.openapi.diagnostic.Logger; import com.intellij.ui.DocumentAdapter; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.event.*;
8,338
@Override public void keyReleased(KeyEvent e) { e.consume(); } }); this.valueField.setText(atomicAssertion.getExpectedValue() != null ? atomicAssertion.getExpectedValue() : ""); setupOptions(); if (atomicAssertion.getAssertionType() == null) { atomicAssertion.setAssertionType(AssertionType.EQUAL); } switch (atomicAssertion.getAssertionType()) { case ALLOF: // cant happen in rule break; case ANYOF: // cant happen in rule break; case NOTALLOF: // cant happen in rule break; case NOTANYOF: // cant happen in rule break; case EQUAL: switch (atomicAssertion.getExpression()) { case SELF: operationSelector.setText("is"); break; case SIZE: operationSelector.setText("size is"); break; case LENGTH: operationSelector.setText("length is"); break; } break; case EQUAL_IGNORE_CASE: operationSelector.setText("equals ignore case"); break; case NOT_EQUAL: switch (atomicAssertion.getExpression()) { case SELF: operationSelector.setText("is not"); break; case SIZE: operationSelector.setText("size is not"); break; case LENGTH: operationSelector.setText("length is not"); break; } break; case FALSE: operationSelector.setText("is false"); break; case MATCHES_REGEX: operationSelector.setText("matches regex"); break; case NOT_MATCHES_REGEX: operationSelector.setText("not matches regex"); break; case TRUE: operationSelector.setText("is true"); break; case LESS_THAN: operationSelector.setText("<"); break; case LESS_THAN_OR_EQUAL: operationSelector.setText("<="); break; case GREATER_THAN: operationSelector.setText(">"); break; case GREATER_THAN_OR_EQUAL: operationSelector.setText(">="); break; case NOT_NULL: operationSelector.setText("is not null"); break; case NULL: operationSelector.setText("is null"); break; case EMPTY: operationSelector.setText("is empty"); break; case NOT_EMPTY: operationSelector.setText("is not empty"); break; case CONTAINS_KEY: operationSelector.setText("contains key in object"); break; case CONTAINS_ITEM: operationSelector.setText("contains item in array"); break; case NOT_CONTAINS_ITEM: operationSelector.setText("not contains item in array"); break; case CONTAINS_STRING: operationSelector.setText("contains substring"); break; case NOT_CONTAINS_KEY: operationSelector.setText("not contains key in object"); break; case NOT_CONTAINS_STRING: operationSelector.setText("not contains substring"); break; } operationSelector.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String selectedItem = (String) operationSelector.getText(); logger.warn("Operator selected: " + selectedItem); switch (selectedItem) { case "is":
package com.insidious.plugin.ui.assertions; public class AssertionRule { private static final Logger logger = LoggerUtil.getInstance(AssertionRule.class); private final AssertionBlock manager; private final AtomicAssertion assertion; private JPanel mainPanel; private JPanel topAligner; private JLabel nameSelector; private JLabel operationSelector; private JLabel valueField; private JButton trashButton; public AssertionRule(AssertionBlock assertionBlock, AtomicAssertion atomicAssertion) { this.assertion = atomicAssertion; this.manager = assertionBlock; this.nameSelector.setText(atomicAssertion.getKey() != null ? atomicAssertion.getKey() : "Nothing selected"); // Color currentBackgroundColor = nameSelector.getBackground(); // nameSelector.setEditable(false); // nameSelector.setBackground(currentBackgroundColor); // nameSelector.setBackground(JBColor.BLACK); // nameSelector.setOpaque(true); // nameSelector.repaint(); nameSelector.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { e.consume(); } @Override public void keyPressed(KeyEvent e) { e.consume(); } @Override public void keyReleased(KeyEvent e) { e.consume(); } }); this.valueField.setText(atomicAssertion.getExpectedValue() != null ? atomicAssertion.getExpectedValue() : ""); setupOptions(); if (atomicAssertion.getAssertionType() == null) { atomicAssertion.setAssertionType(AssertionType.EQUAL); } switch (atomicAssertion.getAssertionType()) { case ALLOF: // cant happen in rule break; case ANYOF: // cant happen in rule break; case NOTALLOF: // cant happen in rule break; case NOTANYOF: // cant happen in rule break; case EQUAL: switch (atomicAssertion.getExpression()) { case SELF: operationSelector.setText("is"); break; case SIZE: operationSelector.setText("size is"); break; case LENGTH: operationSelector.setText("length is"); break; } break; case EQUAL_IGNORE_CASE: operationSelector.setText("equals ignore case"); break; case NOT_EQUAL: switch (atomicAssertion.getExpression()) { case SELF: operationSelector.setText("is not"); break; case SIZE: operationSelector.setText("size is not"); break; case LENGTH: operationSelector.setText("length is not"); break; } break; case FALSE: operationSelector.setText("is false"); break; case MATCHES_REGEX: operationSelector.setText("matches regex"); break; case NOT_MATCHES_REGEX: operationSelector.setText("not matches regex"); break; case TRUE: operationSelector.setText("is true"); break; case LESS_THAN: operationSelector.setText("<"); break; case LESS_THAN_OR_EQUAL: operationSelector.setText("<="); break; case GREATER_THAN: operationSelector.setText(">"); break; case GREATER_THAN_OR_EQUAL: operationSelector.setText(">="); break; case NOT_NULL: operationSelector.setText("is not null"); break; case NULL: operationSelector.setText("is null"); break; case EMPTY: operationSelector.setText("is empty"); break; case NOT_EMPTY: operationSelector.setText("is not empty"); break; case CONTAINS_KEY: operationSelector.setText("contains key in object"); break; case CONTAINS_ITEM: operationSelector.setText("contains item in array"); break; case NOT_CONTAINS_ITEM: operationSelector.setText("not contains item in array"); break; case CONTAINS_STRING: operationSelector.setText("contains substring"); break; case NOT_CONTAINS_KEY: operationSelector.setText("not contains key in object"); break; case NOT_CONTAINS_STRING: operationSelector.setText("not contains substring"); break; } operationSelector.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String selectedItem = (String) operationSelector.getText(); logger.warn("Operator selected: " + selectedItem); switch (selectedItem) { case "is":
assertion.setExpression(Expression.SELF);
3
2023-10-31 09:07:46+00:00
12k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/hook/core/HookItems.java
[ { "identifier": "ItemAttributes", "path": "src/main/java/mixac1/dangerrpg/capability/ItemAttributes.java", "snippet": "public abstract class ItemAttributes {\n\n public static final IALevel LEVEL = new IALevel(\"lvl\");\n public static final IACurrExp CURR_EXP = new IACurrExp(\"curr_exp\");\n p...
import com.google.common.collect.Multimap; import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.PlayerAttributes; import mixac1.dangerrpg.capability.RPGItemHelper; import mixac1.dangerrpg.init.RPGOther.RPGItemRarity; import mixac1.dangerrpg.init.RPGOther.RPGUUIDs; import mixac1.dangerrpg.item.IMaterialSpecial; import mixac1.dangerrpg.util.RPGHelper; import mixac1.hooklib.asm.Hook; import mixac1.hooklib.asm.Hook.ReturnValue; import mixac1.hooklib.asm.ReturnCondition; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound;
8,906
package mixac1.dangerrpg.hook.core; public class HookItems { /** * Hook to creating {@link ItemStack} * Add to stack lvlable and gemable parametres */ @Hook(injectOnExit = true, targetMethod = "<init>") public static void ItemStack(ItemStack stack, Item item, int size, int metadata) { if (RPGItemHelper.isRPGable(stack)) { RPGItemHelper.initRPGItem(stack); } } @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static void readFromNBT(ItemStack stack, NBTTagCompound nbt) { if (RPGItemHelper.isRPGable(stack)) { RPGItemHelper.reinitRPGItem(stack); } } // disabled due to making bugs + it seem that's unneeded , fix https://github.com/quentin452/DangerRPG-Continuation/issues/57 + fix https://github.com/quentin452/DangerRPG-Continuation/issues/59 /* @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static Multimap getAttributeModifiers(Item item, ItemStack stack, @ReturnValue Multimap returnValue) { if (RPGItemHelper.isRPGable(stack)) { if (ItemAttributes.MELEE_DAMAGE.hasIt(stack)) { returnValue.removeAll(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName()); returnValue.put( SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), new AttributeModifier( RPGUUIDs.DEFAULT_DAMAGE, "Weapon modifier", ItemAttributes.MELEE_DAMAGE.get(stack), 0)); } } return returnValue; } */ @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static int getItemEnchantability(Item item, ItemStack stack, @ReturnValue int returnValue) {
package mixac1.dangerrpg.hook.core; public class HookItems { /** * Hook to creating {@link ItemStack} * Add to stack lvlable and gemable parametres */ @Hook(injectOnExit = true, targetMethod = "<init>") public static void ItemStack(ItemStack stack, Item item, int size, int metadata) { if (RPGItemHelper.isRPGable(stack)) { RPGItemHelper.initRPGItem(stack); } } @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static void readFromNBT(ItemStack stack, NBTTagCompound nbt) { if (RPGItemHelper.isRPGable(stack)) { RPGItemHelper.reinitRPGItem(stack); } } // disabled due to making bugs + it seem that's unneeded , fix https://github.com/quentin452/DangerRPG-Continuation/issues/57 + fix https://github.com/quentin452/DangerRPG-Continuation/issues/59 /* @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static Multimap getAttributeModifiers(Item item, ItemStack stack, @ReturnValue Multimap returnValue) { if (RPGItemHelper.isRPGable(stack)) { if (ItemAttributes.MELEE_DAMAGE.hasIt(stack)) { returnValue.removeAll(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName()); returnValue.put( SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), new AttributeModifier( RPGUUIDs.DEFAULT_DAMAGE, "Weapon modifier", ItemAttributes.MELEE_DAMAGE.get(stack), 0)); } } return returnValue; } */ @Hook(injectOnExit = true, returnCondition = ReturnCondition.ALWAYS) public static int getItemEnchantability(Item item, ItemStack stack, @ReturnValue int returnValue) {
if (RPGItemHelper.isRPGable(stack) && (ItemAttributes.ENCHANTABILITY.hasIt(stack))) {
0
2023-10-31 21:00:14+00:00
12k
thinhunan/wonder8-promotion-rule
java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/Strategy.java
[ { "identifier": "Item", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/Item.java", "snippet": "public class Item {\n String category;\n String SPU;\n String SKU;\n String seat;\n\n /// 单位:分 (by cent)\n int price;\n\n public Item(){}\n\n /*\n * @...
import com.github.thinhunan.wonder8.promotion.rule.model.Item; import com.github.thinhunan.wonder8.promotion.rule.model.P; import com.github.thinhunan.wonder8.promotion.rule.model.Rule; import com.github.thinhunan.wonder8.promotion.rule.model.SimplexRule; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Calculator; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType; import com.github.thinhunan.wonder8.promotion.rule.model.validate.RuleValidateResult; import java.util.*;
7,988
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) { BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting); bindSuggestion(bestMatch); return bestMatch; } /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) { return bestChoice(rules, items,type,MatchGroup.CrossedMatch); } /** * 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestMatch(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneRule); } /** * 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果 * 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠 * 匹配的张数是规则的最低要求,价值取最高价格 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneTime); } private static void bindSuggestion(BestMatch best) { if (best != null) { List<RuleValidateResult> ss = suggestions(best.getRules(), best.left()); if (ss != null && ss.size() > 0) { best.setSuggestion(ss.get(0)); } } } /** * 获取所有未匹配但是比当前匹配更好的优惠组合建议 * 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议, * 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议 */ public static List<RuleValidateResult> suggestions(List<Rule> rules, List<Item> items) { //remember discount is negative number int minDiscount = 1; List<Rule> dontMatchedRules = new ArrayList<>(); for (Rule r : rules) { if (r.check(items)) { int discountValue = r.discount(items); if (discountValue < minDiscount) { minDiscount = discountValue; } } else { dontMatchedRules.add(r); } } List<RuleValidateResult> results = new ArrayList<>(); int finalMinDiscount = minDiscount; //要小于已匹配的打折,才是更好的打折 dontMatchedRules.stream().filter(r -> r.discount(items) < finalMinDiscount) .forEach(r -> results.add(r.validate(items))); return results; } /** * 获取当前未匹配,但是最接近的优惠组合拼单建议 * 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议, * 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议 */ public static RuleValidateResult suggestion(List<Rule> rules, List<Item> items) { List<RuleValidateResult> results = Strategy.suggestions(rules, items); //缺张数优先级高还是差总价优先级高,咱讲道理,按每个商品的平均价来 int averagePrice = items.stream().map(Item::getPrice).reduce(0, Integer::sum) / items.size(); RuleValidateResult best = null; int moreCount = 10000, moreSum = 100000000; for (RuleValidateResult r :results) { int[] needs = validateNeeds(r); if(moreCount * averagePrice + moreSum > needs[0]*averagePrice + needs[1]){ moreCount = needs[0]; moreSum = needs[1]; best = r; } } return best; } /* * @Returns int[0] = count,int[1] = sum; */ private static int[] validateNeeds(RuleValidateResult result) { int[] values = new int[2]; List<RuleValidateResult> clauses = result.getClauseResults(); if(clauses == null || clauses.size() == 0){
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) { BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting); bindSuggestion(bestMatch); return bestMatch; } /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) { return bestChoice(rules, items,type,MatchGroup.CrossedMatch); } /** * 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestMatch(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneRule); } /** * 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果 * 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠 * 匹配的张数是规则的最低要求,价值取最高价格 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneTime); } private static void bindSuggestion(BestMatch best) { if (best != null) { List<RuleValidateResult> ss = suggestions(best.getRules(), best.left()); if (ss != null && ss.size() > 0) { best.setSuggestion(ss.get(0)); } } } /** * 获取所有未匹配但是比当前匹配更好的优惠组合建议 * 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议, * 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议 */ public static List<RuleValidateResult> suggestions(List<Rule> rules, List<Item> items) { //remember discount is negative number int minDiscount = 1; List<Rule> dontMatchedRules = new ArrayList<>(); for (Rule r : rules) { if (r.check(items)) { int discountValue = r.discount(items); if (discountValue < minDiscount) { minDiscount = discountValue; } } else { dontMatchedRules.add(r); } } List<RuleValidateResult> results = new ArrayList<>(); int finalMinDiscount = minDiscount; //要小于已匹配的打折,才是更好的打折 dontMatchedRules.stream().filter(r -> r.discount(items) < finalMinDiscount) .forEach(r -> results.add(r.validate(items))); return results; } /** * 获取当前未匹配,但是最接近的优惠组合拼单建议 * 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议, * 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议 */ public static RuleValidateResult suggestion(List<Rule> rules, List<Item> items) { List<RuleValidateResult> results = Strategy.suggestions(rules, items); //缺张数优先级高还是差总价优先级高,咱讲道理,按每个商品的平均价来 int averagePrice = items.stream().map(Item::getPrice).reduce(0, Integer::sum) / items.size(); RuleValidateResult best = null; int moreCount = 10000, moreSum = 100000000; for (RuleValidateResult r :results) { int[] needs = validateNeeds(r); if(moreCount * averagePrice + moreSum > needs[0]*averagePrice + needs[1]){ moreCount = needs[0]; moreSum = needs[1]; best = r; } } return best; } /* * @Returns int[0] = count,int[1] = sum; */ private static int[] validateNeeds(RuleValidateResult result) { int[] values = new int[2]; List<RuleValidateResult> clauses = result.getClauseResults(); if(clauses == null || clauses.size() == 0){
if(result.getRule() instanceof SimplexRule){
3
2023-10-28 09:03:45+00:00
12k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/sql/SqlGenerator.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.util.StringUtils; import org.tinycloud.jdbc.annotation.Column; import org.tinycloud.jdbc.annotation.Table; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.annotation.IdType; import org.tinycloud.jdbc.id.IdUtils; import org.tinycloud.jdbc.util.ReflectUtils; import org.tinycloud.jdbc.util.Triple; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
10,168
package org.tinycloud.jdbc.sql; /** * sql生成器,通过传入的对象,将对象转为要执行的SQL,要绑定到SQL的参数 * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public class SqlGenerator { /** * 构建插入SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider insertSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) {
package org.tinycloud.jdbc.sql; /** * sql生成器,通过传入的对象,将对象转为要执行的SQL,要绑定到SQL的参数 * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public class SqlGenerator { /** * 构建插入SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider insertSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) {
IdType idType = columnAnnotation.idType();
3
2023-10-25 14:44:59+00:00
12k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/health/Location.java
[ { "identifier": "Access", "path": "src/main/java/com/hubsante/model/health/Access.java", "snippet": "@JsonPropertyOrder(\n {Access.JSON_PROPERTY_FLOOR, Access.JSON_PROPERTY_ROOM_NUMBER,\n Access.JSON_PROPERTY_INTERPHONE, Access.JSON_PROPERTY_ACCESS_CODE,\n Access.JSON_PROPERTY_ELEVATOR, Acces...
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.health.Access; import com.hubsante.model.health.City; import com.hubsante.model.health.DetailedAddress; import com.hubsante.model.health.ExternalInfo; import com.hubsante.model.health.Geometry; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty;
7,803
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.health; /** * Location */ @JsonPropertyOrder( {Location.JSON_PROPERTY_LOC_I_D, Location.JSON_PROPERTY_LOC_LABEL, Location.JSON_PROPERTY_NAME, Location.JSON_PROPERTY_DETAILED_ADDRESS, Location.JSON_PROPERTY_CITY, Location.JSON_PROPERTY_ACCESS, Location.JSON_PROPERTY_GEOMETRY, Location.JSON_PROPERTY_EXTERNAL_INFO, Location.JSON_PROPERTY_COUNTRY, Location.JSON_PROPERTY_FREETEXT}) @JsonTypeName("location") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Location { public static final String JSON_PROPERTY_LOC_I_D = "locID"; private String locID; public static final String JSON_PROPERTY_LOC_LABEL = "locLabel"; private String locLabel; public static final String JSON_PROPERTY_NAME = "name"; private String name; public static final String JSON_PROPERTY_DETAILED_ADDRESS = "detailedAddress"; private DetailedAddress detailedAddress; public static final String JSON_PROPERTY_CITY = "city"; private City city; public static final String JSON_PROPERTY_ACCESS = "access";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.health; /** * Location */ @JsonPropertyOrder( {Location.JSON_PROPERTY_LOC_I_D, Location.JSON_PROPERTY_LOC_LABEL, Location.JSON_PROPERTY_NAME, Location.JSON_PROPERTY_DETAILED_ADDRESS, Location.JSON_PROPERTY_CITY, Location.JSON_PROPERTY_ACCESS, Location.JSON_PROPERTY_GEOMETRY, Location.JSON_PROPERTY_EXTERNAL_INFO, Location.JSON_PROPERTY_COUNTRY, Location.JSON_PROPERTY_FREETEXT}) @JsonTypeName("location") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Location { public static final String JSON_PROPERTY_LOC_I_D = "locID"; private String locID; public static final String JSON_PROPERTY_LOC_LABEL = "locLabel"; private String locLabel; public static final String JSON_PROPERTY_NAME = "name"; private String name; public static final String JSON_PROPERTY_DETAILED_ADDRESS = "detailedAddress"; private DetailedAddress detailedAddress; public static final String JSON_PROPERTY_CITY = "city"; private City city; public static final String JSON_PROPERTY_ACCESS = "access";
private Access access;
0
2023-10-25 14:24:31+00:00
12k
MikiP98/HumilityAFM
src/main/java/io/github/mikip98/HumilityAFM.java
[ { "identifier": "ConfigJSON", "path": "src/main/java/io/github/mikip98/config/ConfigJSON.java", "snippet": "public class ConfigJSON {\n\n // Save the configuration to a JSON file in the Minecraft configuration folder\n public static void saveConfigToFile() {\n Gson gson = new GsonBuilder()....
import io.github.mikip98.config.ConfigJSON; import io.github.mikip98.config.ModConfig; import io.github.mikip98.content.blockentities.LEDBlockEntity; import io.github.mikip98.content.blockentities.cabinetBlock.IlluminatedCabinetBlockEntity; import io.github.mikip98.content.blocks.JustHorizontalFacingBlock; import io.github.mikip98.content.blocks.leds.LEDBlock; import io.github.mikip98.content.blocks.stairs.InnerStairs; import io.github.mikip98.content.blocks.stairs.OuterStairs; import io.github.mikip98.content.blocks.cabinet.CabinetBlock; import io.github.mikip98.content.blocks.cabinet.IlluminatedCabinetBlock; import io.github.mikip98.helpers.*; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.block.Block; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.item.*; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.mikip98.content.blockentities.cabinetBlock.CabinetBlockEntity; import java.io.File; import java.nio.file.Path; import static net.fabricmc.loader.api.FabricLoader.getInstance;
9,372
package io.github.mikip98; public class HumilityAFM implements ModInitializer { // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. // That way, it's clear which mod wrote info, warnings, and errors. public static final String MOD_ID = "humility-afm"; public static final String MOD_NAME = "Humility AFM"; public static final String MOD_CAMEL = "HumilityAFM"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL); //Cabinet block private static final float CabinetBlockStrength = 2.0f; private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque(); public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings); public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings()); private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2); public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings); //Cabinet block entity public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY; public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY; // LED block entity public static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY; // Stairs private static final float WoodenStairsBlockStrength = 2.0f; private static final FabricBlockSettings StairsBlockSettings = FabricBlockSettings.create().strength(WoodenStairsBlockStrength).requiresTool(); public static final Block OUTER_STAIRS = new OuterStairs(StairsBlockSettings);
package io.github.mikip98; public class HumilityAFM implements ModInitializer { // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. // That way, it's clear which mod wrote info, warnings, and errors. public static final String MOD_ID = "humility-afm"; public static final String MOD_NAME = "Humility AFM"; public static final String MOD_CAMEL = "HumilityAFM"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL); //Cabinet block private static final float CabinetBlockStrength = 2.0f; private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque(); public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings); public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings()); private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2); public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings); //Cabinet block entity public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY; public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY; // LED block entity public static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY; // Stairs private static final float WoodenStairsBlockStrength = 2.0f; private static final FabricBlockSettings StairsBlockSettings = FabricBlockSettings.create().strength(WoodenStairsBlockStrength).requiresTool(); public static final Block OUTER_STAIRS = new OuterStairs(StairsBlockSettings);
public static final Block INNER_STAIRS = new InnerStairs(StairsBlockSettings);
6
2023-10-30 12:11:22+00:00
12k
HeitorLouzeiro/gerenciador-disciplinas-java
core/src/main/java/com/project/Menu/MenuItens/Listar.java
[ { "identifier": "AlunoDAO", "path": "core/src/main/java/com/project/Dao/AlunoDAO.java", "snippet": "public class AlunoDAO {\n \n /**\n * Conexão com o banco de dados.\n */\n private Connection connection;\n\n /**\n * Construtor da classe AlunoDAO.\n * Inicializa a conexão com...
import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.project.Dao.AlunoDAO; import com.project.Dao.CursoDAO; import com.project.Dao.DisciplinasDAO; import com.project.Dao.FrequenciaDAO; import com.project.Dao.IFPIDAO; import com.project.Dao.NotasDAO; import com.project.Dao.ProfessorDAO; import com.project.Dao.SecretarioDAO;
7,867
package com.project.Menu.MenuItens; /** * Classe responsável por fornecer métodos para listar informações do sistema. * * @Author @HeitorLouzeiro */ public class Listar { static class Space { static String space = "-----------------------------------------------------"; } /** * Lista todos os cursos disponíveis para um determinado usuário. * * @param codUsuario O código do usuário para o qual os cursos serão listados. * @throws IOException Se ocorrer um erro de I/O durante a execução. */ public void listarCursos(int codUsuario) throws IOException{
package com.project.Menu.MenuItens; /** * Classe responsável por fornecer métodos para listar informações do sistema. * * @Author @HeitorLouzeiro */ public class Listar { static class Space { static String space = "-----------------------------------------------------"; } /** * Lista todos os cursos disponíveis para um determinado usuário. * * @param codUsuario O código do usuário para o qual os cursos serão listados. * @throws IOException Se ocorrer um erro de I/O durante a execução. */ public void listarCursos(int codUsuario) throws IOException{
CursoDAO cursoDAO = new CursoDAO();
1
2023-10-30 18:29:39+00:00
12k
llllllxy/tiny-security-boot-starter
src/main/java/org/tinycloud/security/AuthAutoConfiguration.java
[ { "identifier": "AuthenticeInterceptor", "path": "src/main/java/org/tinycloud/security/interceptor/AuthenticeInterceptor.java", "snippet": "public class AuthenticeInterceptor extends HandlerInterceptorAdapter {\n\n /**\n * 存储会话的接口\n */\n private AuthProvider authProvider;\n\n public Aut...
import org.tinycloud.security.interceptor.AuthenticeInterceptor; import org.tinycloud.security.interceptor.PermissionInterceptor; import org.tinycloud.security.interfaces.PermissionInfoInterface; import org.tinycloud.security.provider.AuthProvider; import org.tinycloud.security.provider.JdbcAuthProvider; import org.tinycloud.security.provider.RedisAuthProvider; import org.tinycloud.security.provider.SingleAuthProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate;
9,205
package org.tinycloud.security; /** * <p> * tiny-security 自动配置类 * </p> * * @author liuxingyu01 * @since 2022-12-13 11:45 **/ @Configuration @EnableConfigurationProperties(AuthProperties.class) public class AuthAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class); @Autowired private AuthProperties authProperties; /** * 注入redisAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis") @Bean public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) { if (stringRedisTemplate == null) { logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!"); return null; } logger.info("RedisAuthProvider is running!"); return new RedisAuthProvider(stringRedisTemplate, authProperties); } /** * 注入jdbcAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc") @Bean public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) { if (jdbcTemplate == null) { logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!"); return null; } logger.info("JdbcAuthProvider is running!"); return new JdbcAuthProvider(jdbcTemplate, authProperties); } /** * 注入singleAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "single", matchIfMissing = true) @Bean public AuthProvider singleAuthProvider() { logger.info("SingleAuthProvider is running!"); return new SingleAuthProvider(authProperties); } /** * 添加会话拦截器( 注入AuthStore(可能是redis的,也可能是jdbc的,根据配置来的)) */ @Bean public AuthenticeInterceptor authenticeInterceptor(AuthProvider authProvider) { if (authProvider != null) { return new AuthenticeInterceptor(authProvider); } else { logger.error("AuthAutoConfiguration: Bean AuthProvider Not Defined!"); return null; } } /** * 添加权限拦截器(当存在bean PermissionInfoInterface时,这个配置才生效) * 注入PermissionInfoInterface */ @Bean @ConditionalOnBean(PermissionInfoInterface.class)
package org.tinycloud.security; /** * <p> * tiny-security 自动配置类 * </p> * * @author liuxingyu01 * @since 2022-12-13 11:45 **/ @Configuration @EnableConfigurationProperties(AuthProperties.class) public class AuthAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class); @Autowired private AuthProperties authProperties; /** * 注入redisAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis") @Bean public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) { if (stringRedisTemplate == null) { logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!"); return null; } logger.info("RedisAuthProvider is running!"); return new RedisAuthProvider(stringRedisTemplate, authProperties); } /** * 注入jdbcAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc") @Bean public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) { if (jdbcTemplate == null) { logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!"); return null; } logger.info("JdbcAuthProvider is running!"); return new JdbcAuthProvider(jdbcTemplate, authProperties); } /** * 注入singleAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "single", matchIfMissing = true) @Bean public AuthProvider singleAuthProvider() { logger.info("SingleAuthProvider is running!"); return new SingleAuthProvider(authProperties); } /** * 添加会话拦截器( 注入AuthStore(可能是redis的,也可能是jdbc的,根据配置来的)) */ @Bean public AuthenticeInterceptor authenticeInterceptor(AuthProvider authProvider) { if (authProvider != null) { return new AuthenticeInterceptor(authProvider); } else { logger.error("AuthAutoConfiguration: Bean AuthProvider Not Defined!"); return null; } } /** * 添加权限拦截器(当存在bean PermissionInfoInterface时,这个配置才生效) * 注入PermissionInfoInterface */ @Bean @ConditionalOnBean(PermissionInfoInterface.class)
public PermissionInterceptor permissionInterceptor(PermissionInfoInterface permissionInfoInterface) {
1
2023-10-26 08:13:08+00:00
12k
nailuj1992/OracionesCatolicas
app/src/main/java/com/prayers/app/activity/rosary/RosaryCurrentMysteryActivity.java
[ { "identifier": "AbstractClosableActivity", "path": "app/src/main/java/com/prayers/app/activity/AbstractClosableActivity.java", "snippet": "public abstract class AbstractClosableActivity extends AbstractActivity {\n\n private Button btnHome;\n\n /**\n * Prepare all view fields.\n */\n p...
import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.prayers.app.activity.AbstractClosableActivity; import com.prayers.app.activity.R; import com.prayers.app.constants.GeneralConstants; import com.prayers.app.constants.RedirectionConstants; import com.prayers.app.mapper.RosaryMapper; import com.prayers.app.model.rosary.Mysteries; import com.prayers.app.model.rosary.Mystery; import com.prayers.app.ui.adapter.RosaryMysteryAdapter; import com.prayers.app.utils.FieldsUtils; import com.prayers.app.utils.RedirectionUtils;
7,698
package com.prayers.app.activity.rosary; public class RosaryCurrentMysteryActivity extends AbstractClosableActivity { private Mysteries selectedMysteries; private int selectedMystery; private Mystery mystery; private TextView txtTitleCurrentMystery; private TextView txtTextCurrentMystery; private RecyclerView viewParagraphs; private ImageView imgMysteriesBackground; private Button btnPrev; private Button btnNext; @Override public int getActivity() { return R.layout.rosary_current_mystery_activity; } @Override public void prepareOthersActivity() { txtTitleCurrentMystery = (TextView) findViewById(R.id.title_rosary_current_mystery); txtTextCurrentMystery = (TextView) findViewById(R.id.txt_rosary_current_mystery); viewParagraphs = FieldsUtils.configureRecyclerView(this, R.id.view_paragraphs); imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background); btnPrev = (Button) findViewById(R.id.btn_prev); btnPrev.setOnClickListener(v -> backAction()); btnNext = (Button) findViewById(R.id.btn_next); btnNext.setOnClickListener(v -> nextAction()); } @Override public void updateViewState() { try { selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES); selectedMystery = (int) getIntent().getExtras().getInt(RedirectionConstants.SELECTED_MYSTERY); if (selectedMystery < selectedMysteries.getMysteries().length && selectedMystery >= 0) { mystery = selectedMysteries.getMysteries()[selectedMystery]; } else { mystery = null; } if (mystery != null) {
package com.prayers.app.activity.rosary; public class RosaryCurrentMysteryActivity extends AbstractClosableActivity { private Mysteries selectedMysteries; private int selectedMystery; private Mystery mystery; private TextView txtTitleCurrentMystery; private TextView txtTextCurrentMystery; private RecyclerView viewParagraphs; private ImageView imgMysteriesBackground; private Button btnPrev; private Button btnNext; @Override public int getActivity() { return R.layout.rosary_current_mystery_activity; } @Override public void prepareOthersActivity() { txtTitleCurrentMystery = (TextView) findViewById(R.id.title_rosary_current_mystery); txtTextCurrentMystery = (TextView) findViewById(R.id.txt_rosary_current_mystery); viewParagraphs = FieldsUtils.configureRecyclerView(this, R.id.view_paragraphs); imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background); btnPrev = (Button) findViewById(R.id.btn_prev); btnPrev.setOnClickListener(v -> backAction()); btnNext = (Button) findViewById(R.id.btn_next); btnNext.setOnClickListener(v -> nextAction()); } @Override public void updateViewState() { try { selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES); selectedMystery = (int) getIntent().getExtras().getInt(RedirectionConstants.SELECTED_MYSTERY); if (selectedMystery < selectedMysteries.getMysteries().length && selectedMystery >= 0) { mystery = selectedMysteries.getMysteries()[selectedMystery]; } else { mystery = null; } if (mystery != null) {
txtTitleCurrentMystery.setText(String.format(getString(R.string.txt_rosary_current_mystery), RosaryMapper.getCurrentMysteryLocation(this, selectedMysteries.getValue(), mystery)));
3
2023-10-25 17:17:47+00:00
12k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/components/ADRExplorerComponent.java
[ { "identifier": "ADR", "path": "backup/java/com/buschmais/adr/ADR.java", "snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRConta...
import com.buschmais.backend.adr.ADR; import com.buschmais.backend.adr.ADRTag; import com.buschmais.backend.adr.dataAccess.ADRDao; import com.buschmais.backend.adr.status.ADRStatusType; import com.buschmais.backend.image.Image; import com.buschmais.backend.image.ImageDao; import com.buschmais.backend.users.User; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.frontend.vars.OtherConstantsFrontend; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.vaadin.flow.component.avatar.Avatar; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.HeaderRow; import com.vaadin.flow.component.grid.dataview.GridListDataView; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.textfield.TextFieldVariant; import com.vaadin.flow.data.renderer.ComponentRenderer; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.function.SerializableBiConsumer; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.spring.annotation.UIScope; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors;
8,959
package com.buschmais.frontend.components; @UIScope @Component public class ADRExplorerComponent extends Grid<ADR> {
package com.buschmais.frontend.components; @UIScope @Component public class ADRExplorerComponent extends Grid<ADR> {
private final ADRDao adrDao;
2
2023-10-25 15:18:06+00:00
12k
Java-Game-Engine-Merger/Libgdx-Processing
framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/internal/grammar/Grammar.java
[ { "identifier": "IGrammar", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/grammar/IGrammar.java", "snippet": "public interface IGrammar{\n @Nullable\n String getName();\n String getScopeName();\n Collection<String> getFileTypes();\n ITokenizeLineResult<IToken[]> ...
import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.tm4e.core.grammar.IGrammar; import org.eclipse.tm4e.core.grammar.IStateStack; import org.eclipse.tm4e.core.grammar.IToken; import org.eclipse.tm4e.core.grammar.ITokenizeLineResult; import org.eclipse.tm4e.core.internal.grammar.raw.IRawGrammar; import org.eclipse.tm4e.core.internal.grammar.raw.IRawRepository; import org.eclipse.tm4e.core.internal.grammar.raw.IRawRule; import org.eclipse.tm4e.core.internal.grammar.raw.RawRule; import org.eclipse.tm4e.core.internal.grammar.tokenattrs.EncodedTokenAttributes; import org.eclipse.tm4e.core.internal.matcher.Matcher; import org.eclipse.tm4e.core.internal.matcher.MatcherWithPriority; import org.eclipse.tm4e.core.internal.oniguruma.OnigString; import org.eclipse.tm4e.core.internal.registry.IGrammarRepository; import org.eclipse.tm4e.core.internal.registry.IThemeProvider; import org.eclipse.tm4e.core.internal.rule.IRuleFactoryHelper; import org.eclipse.tm4e.core.internal.rule.Rule; import org.eclipse.tm4e.core.internal.rule.RuleFactory; import org.eclipse.tm4e.core.internal.rule.RuleId; import org.eclipse.tm4e.core.internal.utils.ObjectCloner; import org.eclipse.tm4e.core.internal.utils.StringUtils;
9,248
package org.eclipse.tm4e.core.internal.grammar; public final class Grammar implements IGrammar,IRuleFactoryHelper{ public static boolean trace; // private static final Logger LOGGER=System.getLogger(Grammar.class.getName()); private final String rootScopeName; @Nullable private RuleId _rootId; private int _lastRuleId=0;
package org.eclipse.tm4e.core.internal.grammar; public final class Grammar implements IGrammar,IRuleFactoryHelper{ public static boolean trace; // private static final Logger LOGGER=System.getLogger(Grammar.class.getName()); private final String rootScopeName; @Nullable private RuleId _rootId; private int _lastRuleId=0;
private final Map<RuleId,@Nullable Rule> _ruleId2desc=new HashMap<>();
15
2023-10-27 05:47:39+00:00
12k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/controller/TestController.java
[ { "identifier": "RedisClient", "path": "tinycloud-common/src/main/java/org/tinycloud/common/config/redis/RedisClient.java", "snippet": "public class RedisClient {\n final static Logger log = LoggerFactory.getLogger(RedisClient.class);\n\n private RedisTemplate<String, Object> redisTemplate;\n\n ...
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.tinycloud.common.config.redis.RedisClient; import org.tinycloud.common.model.ApiResult; import org.tinycloud.user.config.TinyCloudUserConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map;
9,091
package org.tinycloud.user.controller; @Api(tags = "用户中心-测试", value = "用户中心-测试") @RestController @RequestMapping("/test") public class TestController { private static final Logger log = LoggerFactory.getLogger(TestController.class); @Autowired private TinyCloudUserConfig tinyCloudUserConfig; @Autowired
package org.tinycloud.user.controller; @Api(tags = "用户中心-测试", value = "用户中心-测试") @RestController @RequestMapping("/test") public class TestController { private static final Logger log = LoggerFactory.getLogger(TestController.class); @Autowired private TinyCloudUserConfig tinyCloudUserConfig; @Autowired
private RedisClient redisClient;
0
2023-10-28 02:05:15+00:00
12k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/common/config/auth/session/AuthClientSessionDao.java
[ { "identifier": "AuthConstant", "path": "src/main/java/com/bluewind/base/common/config/auth/constant/AuthConstant.java", "snippet": "public class AuthConstant {\n\n // 登录用户token-key\n public static final String BLUEWIND_TOKEN_KEY = \"token\";\n\n\n // 用户会话redis的key\n public final static Stri...
import com.bluewind.base.common.config.auth.constant.AuthConstant; import com.bluewind.base.common.config.auth.util.SerializableUtil; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.common.util.spring.SpringContextUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.ValidatingSession; import org.apache.shiro.session.mgt.eis.CachingSessionDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set;
8,656
package com.bluewind.base.common.config.auth.session; /** * @author liuxingyu01 * @date 2022-08-26 12:43 * @description 基于redis的sessionDao,缓存共享session **/ public class AuthClientSessionDao extends CachingSessionDAO { private static final Logger logger = LoggerFactory.getLogger(AuthClientSessionDao.class); private static Map<String, Session> sessionCacheMap = new HashMap<>(); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } @Override protected Serializable doCreate(Session session) { Serializable sessionId = generateSessionId(session); assignSessionId(session, sessionId);
package com.bluewind.base.common.config.auth.session; /** * @author liuxingyu01 * @date 2022-08-26 12:43 * @description 基于redis的sessionDao,缓存共享session **/ public class AuthClientSessionDao extends CachingSessionDAO { private static final Logger logger = LoggerFactory.getLogger(AuthClientSessionDao.class); private static Map<String, Session> sessionCacheMap = new HashMap<>(); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } @Override protected Serializable doCreate(Session session) { Serializable sessionId = generateSessionId(session); assignSessionId(session, sessionId);
getRedisUtils().set(AuthConstant.BLUEWIND_SSO_SHIRO_SESSION_ID + ":" + sessionId, SerializableUtil.serialize(session), (int) session.getTimeout() / 1000);
0
2023-10-26 10:02:07+00:00
12k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/createPacient/EstasSeguro.java
[ { "identifier": "ChoosedPalette", "path": "src/com/context/ChoosedPalette.java", "snippet": "public class ChoosedPalette {\r\n private static final Palette DARK_PALETTE = new Palette(Color.decode(\"#0B0D16\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#4562FF\"),\r\n Colo...
import com.context.ChoosedPalette; import com.helper.PacienteHelper; import com.utils.Tools;
8,114
package com.view.createPacient; /** * * @author Daniel Batres * @version 1.0.0 * @since 3/10/22 */ public class EstasSeguro extends javax.swing.JFrame { /** * Creates new form EstasSeguro */ public EstasSeguro() { initComponents(); setLocationRelativeTo(null);
package com.view.createPacient; /** * * @author Daniel Batres * @version 1.0.0 * @since 3/10/22 */ public class EstasSeguro extends javax.swing.JFrame { /** * Creates new form EstasSeguro */ public EstasSeguro() { initComponents(); setLocationRelativeTo(null);
Tools.setImageLabel(icon, "src/com/images/EmptyBox.png", 340, 20, ChoosedPalette.getMidColor());
0
2023-10-26 19:35:40+00:00
12k
kdetard/koki
app/src/main/java/io/github/kdetard/koki/feature/main/MainController.java
[ { "identifier": "AssetsController", "path": "app/src/main/java/io/github/kdetard/koki/feature/assets/AssetsController.java", "snippet": "public class AssetsController extends MapController {\n @EntryPoint\n @InstallIn(SingletonComponent.class)\n interface AssetsEntryPoint {\n OpenRemoteS...
import android.view.View; import androidx.annotation.NonNull; import com.bluelinelabs.conductor.Router; import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.changehandler.FadeChangeHandler; import com.bluelinelabs.conductor.viewpager2.RouterStateAdapter; import java.util.Map; import java.util.Objects; import io.github.kdetard.koki.R; import io.github.kdetard.koki.databinding.ControllerMainBinding; import io.github.kdetard.koki.feature.assets.AssetsController; import io.github.kdetard.koki.feature.base.BaseController; import io.github.kdetard.koki.feature.home.HomeController; import io.github.kdetard.koki.feature.monitoring.MonitoringController; import io.github.kdetard.koki.feature.settings.SettingsMainController;
8,339
package io.github.kdetard.koki.feature.main; public class MainController extends BaseController { ControllerMainBinding binding; RouterStateAdapter pagerAdapter; private static final Map<Integer, Integer> navBarMap = Map.of( R.id.nav_home, 0, R.id.nav_assets, 1, R.id.nav_monitoring, 2, R.id.nav_settings, 3 ); private int currentNavItemId = R.id.nav_home; public MainController() { super(R.layout.controller_main); pagerAdapter = new RouterStateAdapter(this) { @Override public void configureRouter(@NonNull Router router, int i) { if (!router.hasRootController()) { var page = switch (i) {
package io.github.kdetard.koki.feature.main; public class MainController extends BaseController { ControllerMainBinding binding; RouterStateAdapter pagerAdapter; private static final Map<Integer, Integer> navBarMap = Map.of( R.id.nav_home, 0, R.id.nav_assets, 1, R.id.nav_monitoring, 2, R.id.nav_settings, 3 ); private int currentNavItemId = R.id.nav_home; public MainController() { super(R.layout.controller_main); pagerAdapter = new RouterStateAdapter(this) { @Override public void configureRouter(@NonNull Router router, int i) { if (!router.hasRootController()) { var page = switch (i) {
case 0 -> new HomeController();
2
2023-10-30 00:44:59+00:00
12k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/CSVTransformer.java
[ { "identifier": "DataRetrievalError", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalError.java", "snippet": "public class DataRetrievalError extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalError.class);\n\n ...
import java.io.BufferedWriter; import java.io.OutputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.Duration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.Point; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.TimeSeries;
9,055
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * CSVTransformer. There may be many csv transformer for one column, and some periods can overlap. But these * overlappings are equal. * * @author Andres Bel Alonso */ public abstract class CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(CSVTransformer.class); /** * A time serie with a selected point. Selected period : the period index selected on ts Selected point : the * selected index on ts.getPeriod.getPoint */ public record MarkedTS(TimeSeries ts, int selectedPeriod, int selectedPoint) { /** * The value of the selected point of this time serie * * @return */ public int getSelectedPointValue() { return ts.getPeriod().get(selectedPeriod).getPoint().get(selectedPoint).getQuantity().intValue(); } } ; private final String csvSeparator; private final String csvEscapeChar; private List<ColumnDefinition> columnDefinition = null; public CSVTransformer(String csvSeparator, String csvEscapeChar) { this.csvSeparator = csvSeparator; this.csvEscapeChar = csvEscapeChar; } public List<ColumnDefinition> getColumnDefinition() { if (columnDefinition == null) { columnDefinition = computeColumnDef(); } return columnDefinition; } /** * Writes the next line of the given time stamp.Starts with the separator. * * @param os * @return true if the entry was writed, false otherwise */ public abstract boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os); protected abstract List<ColumnDefinition> computeColumnDef(); /** * * @param startingPoint * @param timeStamp * @return */ protected static List<GLDocumentCSVTransformer.MarkedTS> getPeriodForTimeStamp(List<TimeSeries> timeSeries, LocalDateTime timeStamp) { // search for the correct ts // compute the corresponding positions // we assume that is there is many point of interest, they will be in different ts List<Integer> tsPositions = computeTSPosition(timeSeries,timeStamp); if (tsPositions.isEmpty()) { return new ArrayList<>(); } // start of the time series List<GLDocumentCSVTransformer.MarkedTS> res = new ArrayList<>(); for (int tsPosition : tsPositions) { for (int periodPosition = 0; periodPosition < timeSeries.size(); periodPosition++) { LocalDateTime startDT = timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart(); int resolutionInt = getResolutionInMinutes(timeSeries.get(tsPosition).getPeriod().get(0).getResolution()); long gapMinutes = ChronoUnit.MINUTES.between(startDT, timeStamp); long selectPosition = (gapMinutes / resolutionInt); if (selectPosition > Integer.MAX_VALUE) {
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * CSVTransformer. There may be many csv transformer for one column, and some periods can overlap. But these * overlappings are equal. * * @author Andres Bel Alonso */ public abstract class CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(CSVTransformer.class); /** * A time serie with a selected point. Selected period : the period index selected on ts Selected point : the * selected index on ts.getPeriod.getPoint */ public record MarkedTS(TimeSeries ts, int selectedPeriod, int selectedPoint) { /** * The value of the selected point of this time serie * * @return */ public int getSelectedPointValue() { return ts.getPeriod().get(selectedPeriod).getPoint().get(selectedPoint).getQuantity().intValue(); } } ; private final String csvSeparator; private final String csvEscapeChar; private List<ColumnDefinition> columnDefinition = null; public CSVTransformer(String csvSeparator, String csvEscapeChar) { this.csvSeparator = csvSeparator; this.csvEscapeChar = csvEscapeChar; } public List<ColumnDefinition> getColumnDefinition() { if (columnDefinition == null) { columnDefinition = computeColumnDef(); } return columnDefinition; } /** * Writes the next line of the given time stamp.Starts with the separator. * * @param os * @return true if the entry was writed, false otherwise */ public abstract boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os); protected abstract List<ColumnDefinition> computeColumnDef(); /** * * @param startingPoint * @param timeStamp * @return */ protected static List<GLDocumentCSVTransformer.MarkedTS> getPeriodForTimeStamp(List<TimeSeries> timeSeries, LocalDateTime timeStamp) { // search for the correct ts // compute the corresponding positions // we assume that is there is many point of interest, they will be in different ts List<Integer> tsPositions = computeTSPosition(timeSeries,timeStamp); if (tsPositions.isEmpty()) { return new ArrayList<>(); } // start of the time series List<GLDocumentCSVTransformer.MarkedTS> res = new ArrayList<>(); for (int tsPosition : tsPositions) { for (int periodPosition = 0; periodPosition < timeSeries.size(); periodPosition++) { LocalDateTime startDT = timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart(); int resolutionInt = getResolutionInMinutes(timeSeries.get(tsPosition).getPeriod().get(0).getResolution()); long gapMinutes = ChronoUnit.MINUTES.between(startDT, timeStamp); long selectPosition = (gapMinutes / resolutionInt); if (selectPosition > Integer.MAX_VALUE) {
throw new DataRetrievalError("The position to select is to big. Please use smaller queries");
0
2023-10-30 09:09:53+00:00
12k
EricFan2002/SC2002
src/app/ui/account/ChangePasswordView.java
[ { "identifier": "UserAccountManagementController", "path": "src/app/controller/user/UserAccountManagementController.java", "snippet": "public class UserAccountManagementController {\n /**\n * Private constructor to prevent instantiation.\n */\n private UserAccountManagementController() {\n...
import app.controller.user.UserAccountManagementController; import app.controller.user.UserController; import app.entity.user.Staff; import app.entity.user.Student; import app.ui.overlayactions.OverlayChooseBox; import app.ui.widgets.*; import app.ui.windows.Window; import java.util.ArrayList; import java.util.List;
8,935
package app.ui.account; /** * The ChangePasswordView class represents the UI window for changing a user's password. * It extends the Window class and provides functionality for password change. */ public class ChangePasswordView extends Window { WidgetLabel widgetLabel1; WidgetLabel widgetLabel2; WidgetLabel widgetLabel3; WidgetLabel widgetLabel4; WidgetTextBox widgetTextBox1; WidgetPasswordBox widgetTextBox2; WidgetPasswordBox widgetTextBox3; WidgetPasswordBox widgetTextBox4; WidgetButton button; WidgetToggle toggle; WidgetButton confirmButton; WidgetButton cancelButton; private int loginView; private int studentMainViewIndex; private int staffMainViewIndex; public ChangePasswordView(int loginView, int studentMainViewIndex, int staffMainViewIndex){ super(24, 60, "Password Change"); WidgetLabel widgetLabel = new WidgetLabel(3, 3,40, "Change Your Password", TEXT_ALIGNMENT.ALIGN_MID); addWidget(widgetLabel); widgetLabel1 = new WidgetLabel(1, 5,19, "User:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel1); widgetTextBox1 = new WidgetTextBox(21, 5,29, ""); addWidget(widgetTextBox1); widgetLabel2 = new WidgetLabel(1, 7,19, "Current Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel2); widgetTextBox2 = new WidgetPasswordBox(21, 7,29, ""); addWidget(widgetTextBox2); widgetLabel3 = new WidgetLabel(1, 9,19, "New Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel3); widgetTextBox3 = new WidgetPasswordBox(21, 9,29, ""); addWidget(widgetTextBox3); widgetLabel4 = new WidgetLabel(1, 11,19, "Confirm Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel4); widgetTextBox4 = new WidgetPasswordBox(21, 11,29, ""); addWidget(widgetTextBox4); confirmButton = new WidgetButton(2, 15, 49, "Confirm"); addWidget(confirmButton); cancelButton = new WidgetButton(2, 17, 49, "Back"); addWidget(cancelButton); setPointer(confirmButton); this.loginView = loginView; this.studentMainViewIndex = studentMainViewIndex; this.staffMainViewIndex = staffMainViewIndex; } /** * Checks if a character is a special character. * * @param ch The character to be checked. * @return true if the character is a special character, otherwise false. */ private boolean isSpecialCharacter(char ch) { String specialCharacters = "!@#$%^&*()_-+={}[]|:;\"'<>,.?/"; return specialCharacters.indexOf(ch) != -1; } /** * The main message loop handling user interactions within the ChangePasswordView. * Checks for button presses and performs password change logic based on user input. */ @Override public void messageLoop() { super.messageLoop(); if(confirmButton.getPressed()){ confirmButton.clearPressed(); String name = widgetTextBox1.getText(); String password = widgetTextBox2.getText(); String newPassword = widgetTextBox3.getText(); String confirmPassword = widgetTextBox4.getText(); // Assuming widgetTextBox3 is for confirmPassword // check if name and password is correct if(UserController.login(name, password)){ // if correct, perform password change logic if(newPassword.equals(confirmPassword) && newPassword.length() >= 8 && newPassword.length() <= 20){ boolean hasUpper = false; boolean hasLower = false; boolean hasDigit = false; boolean hasSpecial = false; for (int i = 0; i < newPassword.length(); i++) { char ch = newPassword.charAt(i); if (Character.isUpperCase(ch)) hasUpper = true; else if (Character.isLowerCase(ch)) hasLower = true; else if (Character.isDigit(ch)) hasDigit = true; else if (!Character.isLetterOrDigit(ch)) hasSpecial = true; if (hasUpper && hasLower && hasDigit && hasSpecial) break; } if (hasUpper && hasLower && hasDigit && hasSpecial) { if (UserAccountManagementController.changePassword(name, password, newPassword)) { switchToWindow = loginView; } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2 , 0, "Error changing the password", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Must contain upper, lower, digit, special char", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } else { if (newPassword.length() < 8 || newPassword.length() > 20) { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Password must be between 8 and 20 characters", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "New password and confirm password do not match", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } } else { // if incorrect, show error message List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Incorrect username or password", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } if(cancelButton.getPressed()){ cancelButton.clearPressed(); if (UserController.getCurrentUser().getPassword().equals("password")) { switchToWindow = loginView; } else if (UserController.getCurrentUser() instanceof Staff) { switchToWindow = staffMainViewIndex;
package app.ui.account; /** * The ChangePasswordView class represents the UI window for changing a user's password. * It extends the Window class and provides functionality for password change. */ public class ChangePasswordView extends Window { WidgetLabel widgetLabel1; WidgetLabel widgetLabel2; WidgetLabel widgetLabel3; WidgetLabel widgetLabel4; WidgetTextBox widgetTextBox1; WidgetPasswordBox widgetTextBox2; WidgetPasswordBox widgetTextBox3; WidgetPasswordBox widgetTextBox4; WidgetButton button; WidgetToggle toggle; WidgetButton confirmButton; WidgetButton cancelButton; private int loginView; private int studentMainViewIndex; private int staffMainViewIndex; public ChangePasswordView(int loginView, int studentMainViewIndex, int staffMainViewIndex){ super(24, 60, "Password Change"); WidgetLabel widgetLabel = new WidgetLabel(3, 3,40, "Change Your Password", TEXT_ALIGNMENT.ALIGN_MID); addWidget(widgetLabel); widgetLabel1 = new WidgetLabel(1, 5,19, "User:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel1); widgetTextBox1 = new WidgetTextBox(21, 5,29, ""); addWidget(widgetTextBox1); widgetLabel2 = new WidgetLabel(1, 7,19, "Current Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel2); widgetTextBox2 = new WidgetPasswordBox(21, 7,29, ""); addWidget(widgetTextBox2); widgetLabel3 = new WidgetLabel(1, 9,19, "New Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel3); widgetTextBox3 = new WidgetPasswordBox(21, 9,29, ""); addWidget(widgetTextBox3); widgetLabel4 = new WidgetLabel(1, 11,19, "Confirm Password:", TEXT_ALIGNMENT.ALIGN_RIGHT); addWidget(widgetLabel4); widgetTextBox4 = new WidgetPasswordBox(21, 11,29, ""); addWidget(widgetTextBox4); confirmButton = new WidgetButton(2, 15, 49, "Confirm"); addWidget(confirmButton); cancelButton = new WidgetButton(2, 17, 49, "Back"); addWidget(cancelButton); setPointer(confirmButton); this.loginView = loginView; this.studentMainViewIndex = studentMainViewIndex; this.staffMainViewIndex = staffMainViewIndex; } /** * Checks if a character is a special character. * * @param ch The character to be checked. * @return true if the character is a special character, otherwise false. */ private boolean isSpecialCharacter(char ch) { String specialCharacters = "!@#$%^&*()_-+={}[]|:;\"'<>,.?/"; return specialCharacters.indexOf(ch) != -1; } /** * The main message loop handling user interactions within the ChangePasswordView. * Checks for button presses and performs password change logic based on user input. */ @Override public void messageLoop() { super.messageLoop(); if(confirmButton.getPressed()){ confirmButton.clearPressed(); String name = widgetTextBox1.getText(); String password = widgetTextBox2.getText(); String newPassword = widgetTextBox3.getText(); String confirmPassword = widgetTextBox4.getText(); // Assuming widgetTextBox3 is for confirmPassword // check if name and password is correct if(UserController.login(name, password)){ // if correct, perform password change logic if(newPassword.equals(confirmPassword) && newPassword.length() >= 8 && newPassword.length() <= 20){ boolean hasUpper = false; boolean hasLower = false; boolean hasDigit = false; boolean hasSpecial = false; for (int i = 0; i < newPassword.length(); i++) { char ch = newPassword.charAt(i); if (Character.isUpperCase(ch)) hasUpper = true; else if (Character.isLowerCase(ch)) hasLower = true; else if (Character.isDigit(ch)) hasDigit = true; else if (!Character.isLetterOrDigit(ch)) hasSpecial = true; if (hasUpper && hasLower && hasDigit && hasSpecial) break; } if (hasUpper && hasLower && hasDigit && hasSpecial) { if (UserAccountManagementController.changePassword(name, password, newPassword)) { switchToWindow = loginView; } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2 , 0, "Error changing the password", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Must contain upper, lower, digit, special char", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } else { if (newPassword.length() < 8 || newPassword.length() > 20) { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Password must be between 8 and 20 characters", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } else { List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "New password and confirm password do not match", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } } else { // if incorrect, show error message List<String> options = new ArrayList<String>(); options.add("OK"); OverlayChooseBox overlayChooseBox = new OverlayChooseBox(60, 19 / 2, 0, "Incorrect username or password", options, ChangePasswordView.this); addOverlay(overlayChooseBox); } } if(cancelButton.getPressed()){ cancelButton.clearPressed(); if (UserController.getCurrentUser().getPassword().equals("password")) { switchToWindow = loginView; } else if (UserController.getCurrentUser() instanceof Staff) { switchToWindow = staffMainViewIndex;
} else if (UserController.getCurrentUser() instanceof Student){
3
2023-11-01 05:18:29+00:00
12k
LLNL/response
src/main/java/gov/llnl/gnem/response/TransferFunctionProcessor.java
[ { "identifier": "ChannelMatchPolicy", "path": "src/main/java/com/isti/jevalresp/ChannelMatchPolicy.java", "snippet": "public class ChannelMatchPolicy implements Serializable {\r\n\r\n private static final long serialVersionUID = 6639216586376908870L;\r\n\r\n public static enum Policy {\r\n ...
import com.isti.jevalresp.UnitsStatus; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.measure.Unit; import com.isti.jevalresp.ChannelMatchPolicy; import com.isti.jevalresp.ResponseUnits;
7,676
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class TransferFunctionProcessor { private final SACPZFTransfer sacTransfer; private final EvalrespTransfer evalrespTransfer; private final NDCTransfer ndcTransfer; public TransferFunctionProcessor() { this.sacTransfer = new SACPZFTransfer(); this.evalrespTransfer = new EvalrespTransfer(); this.ndcTransfer = new NDCTransfer(); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, forcedInputUnits); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits) throws IOException { Unit<?> requestedUnits = ResponseUnits.DEFAULT; return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits); } private InverseTransferFunction javaGetToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, null); } private InverseTransferFunction javaGetToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { ChannelMatchPolicy policy = ChannelMatchPolicyHolder.getInstance().getPolicy(); ToResponseLookupKey key = new ToResponseLookupKey(TransferFunctionUtils.next2(nsamp), samprate, network, sta, chan, locid, rmd, policy, requestedUnits, forcedInputUnits); InverseTransferFunction cached = CachedResponseHolder.getInstance().retrieveInverseTransferFunction(key, time); if (cached != null) { return cached; } else { TransferData transferData = getFromTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, policy); if (forcedInputUnits != null && !forcedInputUnits.equals(transferData.getOriginalUnits().getInputUnits())) {
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class TransferFunctionProcessor { private final SACPZFTransfer sacTransfer; private final EvalrespTransfer evalrespTransfer; private final NDCTransfer ndcTransfer; public TransferFunctionProcessor() { this.sacTransfer = new SACPZFTransfer(); this.evalrespTransfer = new EvalrespTransfer(); this.ndcTransfer = new NDCTransfer(); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, forcedInputUnits); } public InverseTransferFunction getToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits) throws IOException { Unit<?> requestedUnits = ResponseUnits.DEFAULT; return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits); } private InverseTransferFunction javaGetToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits) throws IOException { return javaGetToTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, limits, requestedUnits, null); } private InverseTransferFunction javaGetToTransferFunction(int nsamp, double samprate, double time, String network, String sta, String chan, String locid, ResponseMetaData rmd, FreqLimits limits, Unit<?> requestedUnits, Unit<?> forcedInputUnits) throws IOException { ChannelMatchPolicy policy = ChannelMatchPolicyHolder.getInstance().getPolicy(); ToResponseLookupKey key = new ToResponseLookupKey(TransferFunctionUtils.next2(nsamp), samprate, network, sta, chan, locid, rmd, policy, requestedUnits, forcedInputUnits); InverseTransferFunction cached = CachedResponseHolder.getInstance().retrieveInverseTransferFunction(key, time); if (cached != null) { return cached; } else { TransferData transferData = getFromTransferFunction(nsamp, samprate, time, network, sta, chan, locid, rmd, policy); if (forcedInputUnits != null && !forcedInputUnits.equals(transferData.getOriginalUnits().getInputUnits())) {
ResponseUnits tmp = new ResponseUnits(forcedInputUnits, transferData.getOriginalUnits().getUnitObj(), UnitsStatus.FORCED_VALUE);
2
2023-10-30 21:06:43+00:00
12k
TNO/PPS
plugins/nl.esi.pps.architecture.edit/src-gen/nl/esi/pps/architecture/implemented/provider/FunctionItemProvider.java
[ { "identifier": "Function", "path": "plugins/nl.esi.pps.architecture/src-gen/nl/esi/pps/architecture/implemented/Function.java", "snippet": "public interface Function extends NamedArchitectureElement {\n\t/**\n\t * Returns the value of the '<em><b>Operation</b></em>' reference.\n\t * <!-- begin-user-doc...
import java.util.Collection; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.ViewerNotification; import nl.esi.pps.architecture.implemented.Function; import nl.esi.pps.architecture.implemented.ImplementedPackage; import nl.esi.pps.architecture.provider.ArchitectureEditPlugin; import nl.esi.pps.architecture.provider.ArchitectureItemLabelSwitch; import nl.esi.pps.architecture.provider.NamedArchitectureElementItemProvider;
10,088
/** */ package nl.esi.pps.architecture.implemented.provider; /** * This is the item provider adapter for a {@link nl.esi.pps.architecture.implemented.Function} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class FunctionItemProvider extends NamedArchitectureElementItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FunctionItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This adds the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void addPropertyDescriptors(Object object) { super.addPropertyDescriptors(object); addOperationPropertyDescriptor(object); } /** * This adds a property descriptor for the Operation feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOperationPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Function_operation_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Function_operation_feature", "_UI_Function_type"), ImplementedPackage.Literals.FUNCTION__OPERATION, false, false, true, null, getDefaultDescriptorCategory(object), null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(ImplementedPackage.Literals.FUNCTION__PARAMETERS); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns Function.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Function")); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean shouldComposeCreationImage() { return true; } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public String getText(Object object) { return ArchitectureItemLabelSwitch.eINSTANCE.getText(object); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Function.class)) { case ImplementedPackage.FUNCTION__PARAMETERS: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() {
/** */ package nl.esi.pps.architecture.implemented.provider; /** * This is the item provider adapter for a {@link nl.esi.pps.architecture.implemented.Function} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class FunctionItemProvider extends NamedArchitectureElementItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FunctionItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This adds the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void addPropertyDescriptors(Object object) { super.addPropertyDescriptors(object); addOperationPropertyDescriptor(object); } /** * This adds a property descriptor for the Operation feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOperationPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Function_operation_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Function_operation_feature", "_UI_Function_type"), ImplementedPackage.Literals.FUNCTION__OPERATION, false, false, true, null, getDefaultDescriptorCategory(object), null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(ImplementedPackage.Literals.FUNCTION__PARAMETERS); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns Function.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Function")); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean shouldComposeCreationImage() { return true; } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public String getText(Object object) { return ArchitectureItemLabelSwitch.eINSTANCE.getText(object); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Function.class)) { case ImplementedPackage.FUNCTION__PARAMETERS: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() {
return ArchitectureEditPlugin.INSTANCE;
2
2023-10-30 16:00:25+00:00
12k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/block/custom/VoidLilyBlockEntity.java
[ { "identifier": "BMDBlockEntities", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/block/BMDBlockEntities.java", "snippet": "public class BMDBlockEntities {\n public static final DeferredRegister<BlockEntityType<?>> BLOCKS_ENTITIES =\n DeferredRegister.create(ForgeRegistries....
import com.cerbon.bosses_of_mass_destruction.block.BMDBlockEntities; import com.cerbon.bosses_of_mass_destruction.packet.BMDPacketHandler; import com.cerbon.bosses_of_mass_destruction.packet.custom.SendParticleS2CPacket; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.structure.BMDStructures; import com.cerbon.cerbons_api.api.general.event.TimedEvent; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.cerbon.cerbons_api.capability.CerbonsApiCapabilities; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull;
7,782
package com.cerbon.bosses_of_mass_destruction.block.custom; public class VoidLilyBlockEntity extends BlockEntity { private Vec3 structureDirection = null; public VoidLilyBlockEntity(BlockPos pos, BlockState blockState) { super(BMDBlockEntities.VOID_LILY_BLOCK_ENTITY.get(), pos, blockState); } @Override public void load(CompoundTag tag) { if (tag.contains("dirX")) structureDirection = new Vec3(tag.getDouble("dirX"), tag.getDouble("dirY"), tag.getDouble("dirZ")); super.load(tag); } @Override protected void saveAdditional(@NotNull CompoundTag tag) { Vec3 dir = structureDirection; if (dir != null){ tag.putDouble("dirX", dir.x); tag.putDouble("dirY", dir.y); tag.putDouble("dirZ", dir.z); } super.saveAdditional(tag); } public static void tick(Level level, BlockPos pos, BlockState state, VoidLilyBlockEntity entity){ if (RandomUtils.range(0, 30) == 0 && level instanceof ServerLevel serverLevel) { Vec3 direction = entity.structureDirection; if (direction == null) setNearestStructureDirection(serverLevel, pos, entity); if (direction != null)
package com.cerbon.bosses_of_mass_destruction.block.custom; public class VoidLilyBlockEntity extends BlockEntity { private Vec3 structureDirection = null; public VoidLilyBlockEntity(BlockPos pos, BlockState blockState) { super(BMDBlockEntities.VOID_LILY_BLOCK_ENTITY.get(), pos, blockState); } @Override public void load(CompoundTag tag) { if (tag.contains("dirX")) structureDirection = new Vec3(tag.getDouble("dirX"), tag.getDouble("dirY"), tag.getDouble("dirZ")); super.load(tag); } @Override protected void saveAdditional(@NotNull CompoundTag tag) { Vec3 dir = structureDirection; if (dir != null){ tag.putDouble("dirX", dir.x); tag.putDouble("dirY", dir.y); tag.putDouble("dirZ", dir.z); } super.saveAdditional(tag); } public static void tick(Level level, BlockPos pos, BlockState state, VoidLilyBlockEntity entity){ if (RandomUtils.range(0, 30) == 0 && level instanceof ServerLevel serverLevel) { Vec3 direction = entity.structureDirection; if (direction == null) setNearestStructureDirection(serverLevel, pos, entity); if (direction != null)
BMDPacketHandler.sendToAllPlayersTrackingChunk(new SendParticleS2CPacket(pos, direction), serverLevel, VecUtils.asVec3(pos));
1
2023-10-25 16:28:17+00:00
12k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/adapters/converters/InboundsDtoConverter.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.models.AbstractOpenApiSchema; import com.sinch.sdk.domains.sms.models.Inbound; import com.sinch.sdk.domains.sms.models.InboundBinary; import com.sinch.sdk.domains.sms.models.InboundText; import com.sinch.sdk.domains.sms.models.dto.v1.ApiInboundListDto; import com.sinch.sdk.domains.sms.models.dto.v1.InboundDto; import com.sinch.sdk.domains.sms.models.dto.v1.MOBinaryDto; import com.sinch.sdk.domains.sms.models.dto.v1.MOTextDto; import java.util.ArrayList; import java.util.Collection;
10,610
package com.sinch.sdk.domains.sms.adapters.converters; public class InboundsDtoConverter { public static Inbound<?> convert(AbstractOpenApiSchema dto) { Object obj = dto.getActualInstance(); if (obj instanceof MOBinaryDto) { return convert((MOBinaryDto) obj); } else if (obj instanceof MOTextDto) { return convert((MOTextDto) obj); } else { throw new ApiException("Unexpected class:" + obj.getClass().getName()); } } public static Collection<Inbound<?>> convert(ApiInboundListDto dto) {
package com.sinch.sdk.domains.sms.adapters.converters; public class InboundsDtoConverter { public static Inbound<?> convert(AbstractOpenApiSchema dto) { Object obj = dto.getActualInstance(); if (obj instanceof MOBinaryDto) { return convert((MOBinaryDto) obj); } else if (obj instanceof MOTextDto) { return convert((MOTextDto) obj); } else { throw new ApiException("Unexpected class:" + obj.getClass().getName()); } } public static Collection<Inbound<?>> convert(ApiInboundListDto dto) {
Collection<InboundDto> collection = dto.getInbounds();
6
2023-10-31 08:32:59+00:00
12k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/NoteCommand.java
[ { "identifier": "SpCoBot", "path": "src/main/java/top/spco/SpCoBot.java", "snippet": "public class SpCoBot {\n private static SpCoBot instance;\n public static Logger logger;\n public static File dataFolder;\n public static File configFolder;\n public long botId;\n public long botOwner...
import top.spco.SpCoBot; import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.User; import top.spco.api.message.Message; import top.spco.service.FileManipulation; import top.spco.service.command.AbstractCommand; import top.spco.service.command.CommandMeta; import top.spco.user.BotUser; import top.spco.user.UserPermission; import java.io.File;
8,977
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands; /** * @author SpCo * @version 1.2.0 * @since 0.3.2 */ public class NoteCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"note", "n"}; } @Override public String getDescriptions() { return "记录一条文本"; } @Override
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands; /** * @author SpCo * @version 1.2.0 * @since 0.3.2 */ public class NoteCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"note", "n"}; } @Override public String getDescriptions() { return "记录一条文本"; } @Override
public UserPermission needPermission() {
9
2023-10-26 10:27:47+00:00
12k
cty1928/GreenTravel
src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/MapsModule.java
[ { "identifier": "OnLocationChangedListener", "path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/OnLocationChangedListener.java", "snippet": "public abstract class OnLocationChangedListener implements AMapLocationListener {\n\n public abstract void onGaodeLocationChanged(AMapLocati...
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.amap.api.location.AMapLocation; import com.amap.api.location.LocationManagerProxy; import com.amap.api.location.LocationProviderProxy; import com.amap.api.maps.AMap; import com.amap.api.maps.AMapOptions; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.UiSettings; import com.amap.api.maps.model.BitmapDescriptor; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.CameraPosition; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.Marker; import com.amap.api.maps.model.MarkerOptions; import org.zarroboogs.maps.OnLocationChangedListener; import org.zarroboogs.maps.R; import org.zarroboogs.maps.presenters.MapsPresenter; import org.zarroboogs.maps.presenters.MapsPresenterImpl; import org.zarroboogs.maps.presenters.iviews.IGaoDeMapsView; import org.zarroboogs.maps.ui.maps.MapsFragment; import org.zarroboogs.maps.utils.SettingUtils; import java.util.ArrayList; import java.util.List;
7,888
package org.zarroboogs.maps.ui; /** * Created by andforce on 15/7/19. */ public class MapsModule implements IGaoDeMapsView, AMap.OnMapLoadedListener, AMap.OnMapTouchListener, View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private ArrayList<Marker> mMarkers = new ArrayList<>();
package org.zarroboogs.maps.ui; /** * Created by andforce on 15/7/19. */ public class MapsModule implements IGaoDeMapsView, AMap.OnMapLoadedListener, AMap.OnMapTouchListener, View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private ArrayList<Marker> mMarkers = new ArrayList<>();
private MapsPresenter mMapsPresenter;
1
2023-10-31 01:21:54+00:00
12k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/controller/admin/system/user/UserProfileController.java
[ { "identifier": "UserTypeEnum", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/UserTypeEnum.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum UserTypeEnum implements IntArrayValuable {\n\n MEMBER(1, \"会员\"), // 面向 c 端,普通用户\n ADMIN(2, ...
import cn.hutool.core.collection.CollUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; import cn.iocoder.yudao.service.model.system.user.SystemUser; import cn.iocoder.yudao.service.vo.system.user.profile.UserProfileResp; import cn.iocoder.yudao.service.vo.system.user.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.service.vo.system.user.profile.UserProfileUpdateReqVO; import cn.iocoder.yudao.service.convert.system.user.UserConvert; import cn.iocoder.yudao.service.model.system.dept.SystemDept; import cn.iocoder.yudao.service.model.system.dept.SystemPost; import cn.iocoder.yudao.service.model.system.permission.SystemRole; import cn.iocoder.yudao.service.model.infra.social.SystemSocialUser; import cn.iocoder.yudao.service.service.system.dept.DeptService; import cn.iocoder.yudao.service.service.system.dept.PostService; import cn.iocoder.yudao.service.service.system.permission.PermissionService; import cn.iocoder.yudao.service.service.system.permission.RoleService; import cn.iocoder.yudao.service.service.infra.social.SocialUserService; import cn.iocoder.yudao.service.service.system.user.UserService; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Operation; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static cn.iocoder.yudao.service.enums.infra.ErrorCodeConstants.FILE_IS_EMPTY;
9,385
package cn.iocoder.yudao.service.controller.admin.system.user; @Tag(name = "管理后台 - 用户个人中心") @RestController @RequestMapping("/system/user/profile") @Validated public class UserProfileController { @Resource private UserService userService; @Resource private DeptService deptService; @Resource private PostService postService; @Resource private PermissionService permissionService; @Resource private RoleService roleService; @Resource private SocialUserService socialService; @GetMapping("/get") @Operation(summary = "获得登录用户信息") @DataPermission(enable = false) // 关闭数据权限,避免只查看自己时,查询不到部门。
package cn.iocoder.yudao.service.controller.admin.system.user; @Tag(name = "管理后台 - 用户个人中心") @RestController @RequestMapping("/system/user/profile") @Validated public class UserProfileController { @Resource private UserService userService; @Resource private DeptService deptService; @Resource private PostService postService; @Resource private PermissionService permissionService; @Resource private RoleService roleService; @Resource private SocialUserService socialService; @GetMapping("/get") @Operation(summary = "获得登录用户信息") @DataPermission(enable = false) // 关闭数据权限,避免只查看自己时,查询不到部门。
public CommonResult<UserProfileResp> profile() {
1
2023-10-27 06:35:24+00:00
12k
SUFIAG/Hotel-Reservation-System-Java-And-PHP
src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Register_Screen.java
[ { "identifier": "VolleyCallBack", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/dataLayer/VolleyCallBack.java", "snippet": "public interface VolleyCallBack {\n void onSuccess();\n}" }, { "identifier": "writerAndReader", "path": "src/app/src/main/java/com/sameetasadull...
import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Toast; import com.sameetasadullah.i180479_i180531.R; import com.sameetasadullah.i180479_i180531.dataLayer.VolleyCallBack; import com.sameetasadullah.i180479_i180531.dataLayer.writerAndReader; import com.sameetasadullah.i180479_i180531.logicLayer.Customer; import com.sameetasadullah.i180479_i180531.logicLayer.HRS; import com.sameetasadullah.i180479_i180531.logicLayer.Vendor; import de.hdodenhof.circleimageview.CircleImageView;
10,262
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Register_Screen extends AppCompatActivity { String Page; ImageView backButton, addDisplayPic; CircleImageView dp; EditText name,email,contact,card,cnic,address,password; RelativeLayout signup_Button; HRS hrs; Uri imageURI = null; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_screen); Page = getIntent().getStringExtra("Page"); backButton = findViewById(R.id.back_button); name = findViewById(R.id.Name_text); email = findViewById(R.id.Email_text); contact = findViewById(R.id.Contact_text); cnic = findViewById(R.id.CNIC_text); address = findViewById(R.id.Address_text); password = findViewById(R.id.Password_text); card = findViewById(R.id.Card_text); signup_Button = findViewById(R.id.sign_up_button); hrs = HRS.getInstance(Register_Screen.this); addDisplayPic = findViewById(R.id.add_display_pic); dp = findViewById(R.id.display_pic); sharedPreferences = getSharedPreferences("com.sameetasadullah.i180479_180531", MODE_PRIVATE); editor = sharedPreferences.edit(); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); signup_Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String Name=name.getText().toString(); String Cnic=cnic.getText().toString(); String Email=email.getText().toString(); String Contact=contact.getText().toString(); String Address=address.getText().toString(); String Password=password.getText().toString(); String Card=card.getText().toString(); if(Name.equals("") ||Cnic.equals("") ||Password.equals("") ||Card.equals("") ||Address.equals("") ||Contact.equals("") ||Email.equals("") ){ Toast.makeText(Register_Screen.this,"Please Fill All Blocks",Toast.LENGTH_LONG).show(); } else if (imageURI == null) { Toast.makeText(Register_Screen.this, "Please select image", Toast.LENGTH_LONG).show(); } else { if (Page.equals("Customer")){ if (!hrs.validateCustomerEmail(Email)){ Toast.makeText(Register_Screen.this,"Account with this Email / Phone no Already Exists",Toast.LENGTH_LONG).show(); } else { ProgressDialog pd=new ProgressDialog(Register_Screen.this); pd.setMessage("Loading"); pd.setCancelable(false); pd.show(); hrs.registerCustomer(Name, Email, Password, Address, Contact, Cnic, Card, imageURI, new VolleyCallBack() { @Override public void onSuccess() { pd.dismiss(); editor.putString("user", "Customer"); editor.putString("email", Email); editor.putBoolean("loggedIn", true); editor.commit(); editor.apply(); Intent intent=new Intent(Register_Screen.this,Customer_Choose_Option_Screen.class); intent.putExtra("email", Email); startActivity(intent); finish(); } }); } } else { if (!hrs.validateVendorEmail(Email)){ Toast.makeText(Register_Screen.this,"Account with this Email / Phone no Already Exists",Toast.LENGTH_LONG).show(); } else { ProgressDialog pd=new ProgressDialog(Register_Screen.this); pd.setMessage("Loading"); pd.setCancelable(false); pd.show(); hrs.registerVendor(Name,Email,Password,Address,Contact,Cnic,Card,imageURI, new VolleyCallBack(){ @Override public void onSuccess() { pd.dismiss();
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Register_Screen extends AppCompatActivity { String Page; ImageView backButton, addDisplayPic; CircleImageView dp; EditText name,email,contact,card,cnic,address,password; RelativeLayout signup_Button; HRS hrs; Uri imageURI = null; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_screen); Page = getIntent().getStringExtra("Page"); backButton = findViewById(R.id.back_button); name = findViewById(R.id.Name_text); email = findViewById(R.id.Email_text); contact = findViewById(R.id.Contact_text); cnic = findViewById(R.id.CNIC_text); address = findViewById(R.id.Address_text); password = findViewById(R.id.Password_text); card = findViewById(R.id.Card_text); signup_Button = findViewById(R.id.sign_up_button); hrs = HRS.getInstance(Register_Screen.this); addDisplayPic = findViewById(R.id.add_display_pic); dp = findViewById(R.id.display_pic); sharedPreferences = getSharedPreferences("com.sameetasadullah.i180479_180531", MODE_PRIVATE); editor = sharedPreferences.edit(); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); signup_Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String Name=name.getText().toString(); String Cnic=cnic.getText().toString(); String Email=email.getText().toString(); String Contact=contact.getText().toString(); String Address=address.getText().toString(); String Password=password.getText().toString(); String Card=card.getText().toString(); if(Name.equals("") ||Cnic.equals("") ||Password.equals("") ||Card.equals("") ||Address.equals("") ||Contact.equals("") ||Email.equals("") ){ Toast.makeText(Register_Screen.this,"Please Fill All Blocks",Toast.LENGTH_LONG).show(); } else if (imageURI == null) { Toast.makeText(Register_Screen.this, "Please select image", Toast.LENGTH_LONG).show(); } else { if (Page.equals("Customer")){ if (!hrs.validateCustomerEmail(Email)){ Toast.makeText(Register_Screen.this,"Account with this Email / Phone no Already Exists",Toast.LENGTH_LONG).show(); } else { ProgressDialog pd=new ProgressDialog(Register_Screen.this); pd.setMessage("Loading"); pd.setCancelable(false); pd.show(); hrs.registerCustomer(Name, Email, Password, Address, Contact, Cnic, Card, imageURI, new VolleyCallBack() { @Override public void onSuccess() { pd.dismiss(); editor.putString("user", "Customer"); editor.putString("email", Email); editor.putBoolean("loggedIn", true); editor.commit(); editor.apply(); Intent intent=new Intent(Register_Screen.this,Customer_Choose_Option_Screen.class); intent.putExtra("email", Email); startActivity(intent); finish(); } }); } } else { if (!hrs.validateVendorEmail(Email)){ Toast.makeText(Register_Screen.this,"Account with this Email / Phone no Already Exists",Toast.LENGTH_LONG).show(); } else { ProgressDialog pd=new ProgressDialog(Register_Screen.this); pd.setMessage("Loading"); pd.setCancelable(false); pd.show(); hrs.registerVendor(Name,Email,Password,Address,Contact,Cnic,Card,imageURI, new VolleyCallBack(){ @Override public void onSuccess() { pd.dismiss();
editor.putString("user", "Vendor");
4
2023-10-25 20:58:45+00:00
12k
MachineMC/Cogwheel
cogwheel-core/src/main/java/org/machinemc/cogwheel/serialization/Serializers.java
[ { "identifier": "DataVisitor", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/DataVisitor.java", "snippet": "public interface DataVisitor {\n\n int READ_ACCESS = 0x01, WRITE_ACCESS = 0x02, FULL_ACCESS = READ_ACCESS | WRITE_ACCESS;\n\n @Contract(\"_ -> this\")\n DataVisitor visit(St...
import org.jetbrains.annotations.Nullable; import org.machinemc.cogwheel.DataVisitor; import org.machinemc.cogwheel.ErrorHandler; import org.machinemc.cogwheel.config.*; import org.machinemc.cogwheel.util.ArrayUtils; import org.machinemc.cogwheel.util.JavaUtils; import org.machinemc.cogwheel.util.NumberUtils; import org.machinemc.cogwheel.util.classbuilder.ClassBuilder; import org.machinemc.cogwheel.util.classbuilder.ObjectBuilder; import org.machinemc.cogwheel.util.classbuilder.RecordBuilder; import org.machinemc.cogwheel.util.error.ErrorContainer; import org.machinemc.cogwheel.util.error.ErrorEntry; import org.machinemc.cogwheel.util.error.ErrorType; import java.io.File; import java.lang.reflect.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.time.Instant; import java.util.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Stream;
9,275
} public static class EnumSerializer<E extends Enum<E>> implements Serializer<E> { private final Class<E> enumType; public EnumSerializer(Class<E> enumType) { this.enumType = enumType; } @Override public void serialize(E e, DataVisitor visitor) { visitor.writeString(e.toString().toLowerCase(Locale.ENGLISH)); } @Override public @Nullable E deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(string -> { try { return Enum.valueOf(enumType, string.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException ignored) {} errorContainer.error(ErrorType.CUSTOM, "No enum constant " + enumType.getCanonicalName() + "." + string); return null; }) .orElse(null); } } public static class ConfigurationSerializer<C extends Configuration> implements Serializer<C> { private static final Function<Class<?>, String> COULD_NOT_SERIALIZE = as -> "Couldn't serialize type '" + as.getName() + "'. Did you register a serializer for it?"; private static final Function<Class<?>, String> COULD_NOT_DESERIALIZE = as -> "Couldn't deserialize type '" + as.getName() + "'. Did you register a serializer for it?"; private final Class<C> type; private final SerializerContext context; private final ConfigProperties properties; public ConfigurationSerializer(SerializerContext context) { this(JavaUtils.asClass(context.annotatedType()), context); } public ConfigurationSerializer(Class<C> type, SerializerContext context) { this.type = type; this.context = context; this.properties = context.properties(); } @Override public void serialize(C configuration, DataVisitor visitor) { ConfigAdapter<?> configAdapter = context.configAdapter().get(); nodeStream(configuration.getClass()).forEach(node -> { Object primitive = node.getValue(configuration); Serializer<Object> writeWith = context.withNode(node).writeWith(); Object serialized = writeWith == null ? primitive : Serializer.serialize(writeWith, primitive); if (serialized == null && node.isHidden()) return; if (!configAdapter.setPrimitive(node.getFormattedName(), serialized)) { handleError( node, new ErrorEntry(ErrorType.SERIALIZER_NOT_FOUND, COULD_NOT_SERIALIZE.apply(node.getActualType())) ); return; } String[] comments = node.getComments(); String inlineComment = node.getInlineComment(); if (comments != null) { for (int i = 0; i < comments.length; i++) if (comments[i].isEmpty()) comments[i] = null; configAdapter.setComments(node.getFormattedName(), comments); } if (inlineComment != null) configAdapter.setInlineComment(node.getFormattedName(), inlineComment); }); visitor.writeConfig(configAdapter); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public @Nullable C deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Map<String, Object> config = visitor.readConfig().map(ConfigAdapter::getAsMap).orElse(null); if (config == null) return null; Set<String> unhandledKeys = new LinkedHashSet<>(config.keySet()); ErrorHandler errorHandler = properties.errorHandler(); ClassBuilder<C> builder = classBuilder(); nodeStream(builder.getType()).forEach(node -> { String key = node.getFormattedName(); Object primitive = config.get(key); unhandledKeys.remove(key); if (primitive == null) { if (node.isOptional()) return; handleError(node, new ErrorEntry(ErrorType.KEY_NOT_FOUND, "Required key '" + key + "' is missing")); return; } Class<?> type = node.getActualType(); Serializer<?> readWith = context.withNode(node).readWith(); if (readWith == null && !type.isInstance(primitive)) { handleError(node, new ErrorEntry(ErrorType.SERIALIZER_NOT_FOUND, COULD_NOT_DESERIALIZE.apply(type))); return; } Object deserialized = Serializers.deserialize((Serializer) readWith, primitive, type, errorContainer); errorContainer.handleErrors(context); if (deserialized == null) return; builder.setComponent(node.getName(), (Class) type, deserialized); }); unhandledKeys.forEach(key -> errorHandler.handle( context.withNode(null), new ErrorEntry(ErrorType.UNEXPECTED_KEY, "Unexpected key '" + key + "' was found") )); return builder.build(); } private void handleError(ConfigNode<?> node, ErrorEntry error) { context.properties().errorHandler().handle(context.withNode(node), error); } private ClassBuilder<C> classBuilder() { if (type.isRecord()) { //noinspection unchecked,rawtypes
package org.machinemc.cogwheel.serialization; public class Serializers { public static <T extends Serializer<?>> T newSerializer(Class<T> serializerClass, SerializerContext context) { if (JavaUtils.hasConstructor(serializerClass, SerializerContext.class)) return JavaUtils.newInstance(serializerClass, ArrayUtils.array(SerializerContext.class), context); if (JavaUtils.hasConstructor(serializerClass)) return JavaUtils.newInstance(serializerClass); throw new IllegalArgumentException("Cannot instantiate serializer '" + serializerClass + "'. " + "No appropriate constructor found"); } private static AnnotatedType[] validateParameterTypes(AnnotatedType[] parameters) { for (AnnotatedType parameter : parameters) validateParameterType(parameter); return parameters; } private static AnnotatedType validateParameterType(AnnotatedType parameter) { switch (parameter.getType()) { case Class<?> ignore -> {} case ParameterizedType ignore -> {} case GenericArrayType ignore -> {} default -> throw new UnsupportedOperationException("Cannot serialize type '" + parameter + "'"); } return parameter; } @SuppressWarnings("unchecked") private static <T> T deserialize(Serializer<T> deserializer, Object primitive, Class<T> as, ErrorContainer errorContainer) { if (primitive == null) return null; ErrorContainer childContainer = new ErrorContainer(errorContainer); Object deserialized = deserializer != null ? Serializer.deserialize(deserializer, primitive, childContainer) : primitive; if (as.isInstance(primitive) || deserialized != null || childContainer.hasErrors()) return (T) deserialized; childContainer.error(ErrorType.MISMATCHED_TYPES, "Could not deserialize (%s) '%s' as %s".formatted( primitive.getClass().getSimpleName(), JavaUtils.toString(primitive), as.getSimpleName() )); return null; } public static class NumberSerializer<N extends Number> implements Serializer<N> { private final Class<N> type; private final Function<Number, N> numberFunction; public NumberSerializer(Class<N> type, Function<Number, N> numberFunction) { this.type = type; this.numberFunction = numberFunction; } @Override public void serialize(N number, DataVisitor visitor) { visitor.writeNumber(number); } @Override public @Nullable N deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Number number = visitor.readNumber().orElse(null); if (type.isInstance(number)) return type.cast(number); return Optional.ofNullable(number) .map(String::valueOf) .or(visitor::readString) .map(string -> { try { Number parsed = NumberUtils.parse(string); if (type.isInstance(parsed)) return type.cast(parsed); return numberFunction.apply(new NumberUtils.ClampedNumber(parsed)); } catch (NumberFormatException e) { errorContainer.error(ErrorType.CUSTOM, "Could not parse '" + string + "' as a number"); return null; } }) .orElse(null); } } public static class BooleanSerializer implements Serializer<Boolean> { @Override public void serialize(Boolean bool, DataVisitor visitor) { visitor.writeBoolean(bool); } @Override public @Nullable Boolean deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readBoolean() .map(String::valueOf) .or(visitor::readString) .map(BooleanSerializer::parseBoolean) .orElse(null); } private static Boolean parseBoolean(String string) { return switch (string.toLowerCase(Locale.ENGLISH)) { case "true" -> true; case "false" -> false; default -> null; }; } } public static class StringSerializer implements Serializer<String> { @Override public void serialize(String string, DataVisitor visitor) { visitor.writeString(string); } @Override public @Nullable String deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString().orElse(null); } } public static class UUIDSerializer implements Serializer<UUID> { @Override public void serialize(UUID uuid, DataVisitor visitor) { visitor.writeString(uuid.toString()); } @Override public @Nullable UUID deserialize(DataVisitor visitor, ErrorContainer errorContainer) { try { return visitor.readString() .map(UUID::fromString) .orElse(null); } catch (IllegalArgumentException e) { errorContainer.error(e.getMessage()); return null; } } } public static class FileSerializer implements Serializer<File> { @Override public void serialize(File file, DataVisitor visitor) { visitor.writeString(file.toString()); } @Override public @Nullable File deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(File::new) .orElse(null); } } public static class PathSerializer implements Serializer<Path> { @Override public void serialize(Path path, DataVisitor visitor) { visitor.writeString(path.toString()); } @Override public @Nullable Path deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(Path::of) .orElse(null); } } public static class URLSerializer implements Serializer<URL> { @Override public void serialize(URL url, DataVisitor visitor) { visitor.writeString(url.toString()); } @Override public @Nullable URL deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(string -> { try { return new URI(string).toURL(); } catch (MalformedURLException | URISyntaxException ignored) {} errorContainer.error("Malformed URL: " + string); return null; }) .orElse(null); } } public static class URISerializer implements Serializer<URI> { @Override public void serialize(URI uri, DataVisitor visitor) { visitor.writeString(uri.toString()); } @Override public @Nullable URI deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(string -> { try { return new URI(string); } catch (URISyntaxException ignored) {} errorContainer.error("Malformed URI: " + string); return null; }) .orElse(null); } } public static class InstantSerializer implements Serializer<Instant> { @Override public void serialize(Instant instant, DataVisitor visitor) { visitor.writeNumber(instant.toEpochMilli()); } @Override public @Nullable Instant deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readNumber() .map(Number::longValue) .map(Instant::ofEpochMilli) .orElse(null); } } public static class CollectionSerializer<C extends Collection<T>, T> implements Serializer<C> { private final IntFunction<C> factory; private final SerializerContext context; public CollectionSerializer(IntFunction<C> factory, SerializerContext context) { AnnotatedParameterizedType type = (AnnotatedParameterizedType) context.annotatedType(); AnnotatedType argument = validateParameterType(type.getAnnotatedActualTypeArguments()[0]); this.factory = factory; this.context = context.withType(argument); } @Override public void serialize(C collection, DataVisitor visitor) { Serializer<T> serializer = context.writeWith(); visitor.writeArray(collection.stream() .map(object -> serializer != null ? Serializer.serialize(serializer, object) : object) .toArray()); } @Override public @Nullable C deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Class<T> type = JavaUtils.asClass(context.type()); Serializer<T> deserializer = context.readWith(); return visitor.readArray() .map(array -> { C collection = factory.apply(array.length); for (Object primitive : array) { T object = Serializers.deserialize(deserializer, primitive, type, errorContainer); collection.add(object); } return collection; }) .orElse(null); } } public static class MapSerializer<K, V> implements Serializer<Map<K, V>> { private final Class<K> keyType; private final SerializerContext context; @SuppressWarnings("unchecked") public MapSerializer(SerializerContext context) { AnnotatedParameterizedType type = (AnnotatedParameterizedType) context.annotatedType(); AnnotatedType[] parameters = validateParameterTypes(type.getAnnotatedActualTypeArguments()); if (!(parameters[0].getType() instanceof Class<?> keyClass) || (!String.class.isAssignableFrom(keyClass) && !keyClass.isEnum())) throw new IllegalArgumentException("Map keys may only be of types '%s' or '%s'. Not '%s'".formatted( String.class.getTypeName(), Enum.class.getTypeName(), parameters[0].getType().getTypeName() )); this.keyType = (Class<K>) keyClass; this.context = context.withType(parameters[1]); } @Override public void serialize(Map<K, V> map, DataVisitor visitor) { Map<String, Object> serializedMap = HashMap.newHashMap(map.size()); Serializer<V> serializer = context.writeWith(); map.forEach((key, value) -> { Object serialized = serializer != null ? Serializer.serialize(serializer, value) : value; serializedMap.put((key + "").toLowerCase(Locale.ENGLISH), serialized); }); visitor.writeMap(serializedMap); } @Override @SuppressWarnings("unchecked") public @Nullable Map<K, V> deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Map<String, Object> serialized = visitor.readMap().orElse(null); if (serialized == null) return null; Map<K, V> map = LinkedHashMap.newLinkedHashMap(serialized.size()); Class<V> valueType = JavaUtils.asClass(context.type()); Serializer<V> deserializer = context.readWith(); serialized.forEach((key, value) -> { K actualKey; if (keyType.isEnum()) { actualKey = JavaUtils.getEnumConstant(keyType, key.toUpperCase(Locale.ENGLISH)); } else if (String.class.isAssignableFrom(keyType)) { actualKey = (K) key; } else { throw new UnsupportedOperationException("Cannot deserialize key of type: " + keyType.getTypeName()); } map.put(actualKey, Serializers.deserialize(deserializer, value, valueType, errorContainer)); }); return map; } } public static class ArraySerializer<T> implements Serializer<T[]> { private final Class<T[]> arrayType; private final IntFunction<T[]> arrayFactory; private final SerializerContext context; @SuppressWarnings("unchecked") public ArraySerializer(SerializerContext context) { AnnotatedArrayType type = (AnnotatedArrayType) context.annotatedType(); this.arrayType = JavaUtils.asClass(type); this.arrayFactory = length -> (T[]) ArrayUtils.newArrayInstance(arrayType.componentType(), length); this.context = context.withType(type.getAnnotatedGenericComponentType()); } @Override public void serialize(T[] array, DataVisitor visitor) { Serializer<T> serializer = context.writeWith(); Object[] serialized = new Object[array.length]; for (int i = 0; i < array.length; i++) serialized[i] = serializer != null ? Serializer.serialize(serializer, array[i]) : array[i]; visitor.writeArray(serialized); } @Override public T @Nullable [] deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Class<T> type = JavaUtils.asClass(context.type()); Serializer<T> deserializer = context.readWith(); Object[] array = visitor.readArray().orElse(null); if (array == null) return null; return Arrays.stream(array) .map(object -> Serializers.deserialize( deserializer, object, type, errorContainer )) .filter(Objects::nonNull) .toArray(arrayFactory); } } public abstract static class PrimitiveArraySerializer<P, W> implements Serializer<P> { private final IntFunction<W[]> wrapperFactory; private final Function<P, W[]> wrapper; private final Function<W[], P> unwrapper; private final SerializerContext context; public PrimitiveArraySerializer( IntFunction<W[]> wrapperFactory, Function<P, W[]> wrapper, Function<W[], P> unwrapper, SerializerContext context ) { AnnotatedArrayType type = (AnnotatedArrayType) context.annotatedType(); this.wrapperFactory = wrapperFactory; this.wrapper = wrapper; this.unwrapper = unwrapper; this.context = context.withType(type.getAnnotatedGenericComponentType()); } @Override public void serialize(P primitiveArray, DataVisitor visitor) { Serializer<W> serializer = context.writeWith(); if (serializer == null) { visitor.writeArray(wrapper.apply(primitiveArray)); return; } W[] wrapped = wrapper.apply(primitiveArray); Object[] serialized = new Object[wrapped.length]; for (int i = 0; i < wrapped.length; i++) serialized[i] = Serializer.serialize(serializer, wrapped[i]); visitor.writeArray(serialized); } @Override public @Nullable P deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Class<W> type = JavaUtils.asClass(context.type()); Serializer<W> deserializer = context.readWith(); return visitor.readArray().map(objects -> unwrapper.apply(Arrays.stream(objects) .map(object -> Serializers.deserialize(deserializer, object, type, errorContainer)) .filter(Objects::nonNull) .toArray(wrapperFactory))) .orElse(null); } } public static class PrimitiveByteArraySerializer extends PrimitiveArraySerializer<byte[], Byte> { public PrimitiveByteArraySerializer(SerializerContext context) { super(Byte[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveShortArraySerializer extends PrimitiveArraySerializer<short[], Short> { public PrimitiveShortArraySerializer(SerializerContext context) { super(Short[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveIntArraySerializer extends PrimitiveArraySerializer<int[], Integer> { public PrimitiveIntArraySerializer(SerializerContext context) { super(Integer[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveLongArraySerializer extends PrimitiveArraySerializer<long[], Long> { public PrimitiveLongArraySerializer(SerializerContext context) { super(Long[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveFloatArraySerializer extends PrimitiveArraySerializer<float[], Float> { public PrimitiveFloatArraySerializer(SerializerContext context) { super(Float[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveDoubleArraySerializer extends PrimitiveArraySerializer<double[], Double> { public PrimitiveDoubleArraySerializer(SerializerContext context) { super(Double[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class PrimitiveBooleanArraySerializer extends PrimitiveArraySerializer<boolean[], Boolean> { public PrimitiveBooleanArraySerializer(SerializerContext context) { super(Boolean[]::new, ArrayUtils::wrapArray, ArrayUtils::unwrapArray, context); } } public static class EnumSerializer<E extends Enum<E>> implements Serializer<E> { private final Class<E> enumType; public EnumSerializer(Class<E> enumType) { this.enumType = enumType; } @Override public void serialize(E e, DataVisitor visitor) { visitor.writeString(e.toString().toLowerCase(Locale.ENGLISH)); } @Override public @Nullable E deserialize(DataVisitor visitor, ErrorContainer errorContainer) { return visitor.readString() .map(string -> { try { return Enum.valueOf(enumType, string.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException ignored) {} errorContainer.error(ErrorType.CUSTOM, "No enum constant " + enumType.getCanonicalName() + "." + string); return null; }) .orElse(null); } } public static class ConfigurationSerializer<C extends Configuration> implements Serializer<C> { private static final Function<Class<?>, String> COULD_NOT_SERIALIZE = as -> "Couldn't serialize type '" + as.getName() + "'. Did you register a serializer for it?"; private static final Function<Class<?>, String> COULD_NOT_DESERIALIZE = as -> "Couldn't deserialize type '" + as.getName() + "'. Did you register a serializer for it?"; private final Class<C> type; private final SerializerContext context; private final ConfigProperties properties; public ConfigurationSerializer(SerializerContext context) { this(JavaUtils.asClass(context.annotatedType()), context); } public ConfigurationSerializer(Class<C> type, SerializerContext context) { this.type = type; this.context = context; this.properties = context.properties(); } @Override public void serialize(C configuration, DataVisitor visitor) { ConfigAdapter<?> configAdapter = context.configAdapter().get(); nodeStream(configuration.getClass()).forEach(node -> { Object primitive = node.getValue(configuration); Serializer<Object> writeWith = context.withNode(node).writeWith(); Object serialized = writeWith == null ? primitive : Serializer.serialize(writeWith, primitive); if (serialized == null && node.isHidden()) return; if (!configAdapter.setPrimitive(node.getFormattedName(), serialized)) { handleError( node, new ErrorEntry(ErrorType.SERIALIZER_NOT_FOUND, COULD_NOT_SERIALIZE.apply(node.getActualType())) ); return; } String[] comments = node.getComments(); String inlineComment = node.getInlineComment(); if (comments != null) { for (int i = 0; i < comments.length; i++) if (comments[i].isEmpty()) comments[i] = null; configAdapter.setComments(node.getFormattedName(), comments); } if (inlineComment != null) configAdapter.setInlineComment(node.getFormattedName(), inlineComment); }); visitor.writeConfig(configAdapter); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public @Nullable C deserialize(DataVisitor visitor, ErrorContainer errorContainer) { Map<String, Object> config = visitor.readConfig().map(ConfigAdapter::getAsMap).orElse(null); if (config == null) return null; Set<String> unhandledKeys = new LinkedHashSet<>(config.keySet()); ErrorHandler errorHandler = properties.errorHandler(); ClassBuilder<C> builder = classBuilder(); nodeStream(builder.getType()).forEach(node -> { String key = node.getFormattedName(); Object primitive = config.get(key); unhandledKeys.remove(key); if (primitive == null) { if (node.isOptional()) return; handleError(node, new ErrorEntry(ErrorType.KEY_NOT_FOUND, "Required key '" + key + "' is missing")); return; } Class<?> type = node.getActualType(); Serializer<?> readWith = context.withNode(node).readWith(); if (readWith == null && !type.isInstance(primitive)) { handleError(node, new ErrorEntry(ErrorType.SERIALIZER_NOT_FOUND, COULD_NOT_DESERIALIZE.apply(type))); return; } Object deserialized = Serializers.deserialize((Serializer) readWith, primitive, type, errorContainer); errorContainer.handleErrors(context); if (deserialized == null) return; builder.setComponent(node.getName(), (Class) type, deserialized); }); unhandledKeys.forEach(key -> errorHandler.handle( context.withNode(null), new ErrorEntry(ErrorType.UNEXPECTED_KEY, "Unexpected key '" + key + "' was found") )); return builder.build(); } private void handleError(ConfigNode<?> node, ErrorEntry error) { context.properties().errorHandler().handle(context.withNode(node), error); } private ClassBuilder<C> classBuilder() { if (type.isRecord()) { //noinspection unchecked,rawtypes
return new RecordBuilder<>((Class) type);
7
2023-10-25 11:31:02+00:00
12k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/IEXCloudClient.java
[ { "identifier": "CompanyData", "path": "src/main/java/io/github/f4pl0/companydata/CompanyData.java", "snippet": "public class CompanyData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n\n /**\n * Company I...
import io.github.f4pl0.companydata.CompanyData; import io.github.f4pl0.config.ConfigInjector; import io.github.f4pl0.config.IEXCloudConfig; import io.github.f4pl0.equitiesmarketdata.EquitiesMarketData; import io.github.f4pl0.historicaldata.HistoricalData; import io.github.f4pl0.reference.Reference;
7,979
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData; private final Reference reference;
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData; private final Reference reference;
private final CompanyData companyData;
0
2023-10-27 17:56:14+00:00
12k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/util/LogFiles.java
[ { "identifier": "DriveConstants", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/DriveConstants.java", "snippet": "@Config\npublic class DriveConstants {\n\n /*\n * These are motor constants that should be listed online for your motors.\n */\n public static...
import android.annotation.SuppressLint; import android.content.Context; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerImpl; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerNotifier; import com.qualcomm.robotcore.util.RobotLog; import com.qualcomm.robotcore.util.WebHandlerManager; import org.firstinspires.ftc.ftccommon.external.WebHandlerRegistrar; import org.firstinspires.ftc.robotcore.internal.system.AppUtil; import org.firstinspires.ftc.teamcode.RoadRunner.drive.DriveConstants; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleTankDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.StandardTrackingWheelLocalizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import fi.iki.elonen.NanoHTTPD;
7,580
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL; public double mecTransP = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kP; public double mecTransI = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kI; public double mecTransD = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kD; public double mecHeadingP = SampleMecanumDrive.HEADING_PID.kP; public double mecHeadingI = SampleMecanumDrive.HEADING_PID.kI; public double mecHeadingD = SampleMecanumDrive.HEADING_PID.kD; public double mecLateralMultiplier = SampleMecanumDrive.LATERAL_MULTIPLIER; public double tankAxialP = SampleTankDrive.AXIAL_PID.kP; public double tankAxialI = SampleTankDrive.AXIAL_PID.kI; public double tankAxialD = SampleTankDrive.AXIAL_PID.kD; public double tankCrossTrackP = SampleTankDrive.CROSS_TRACK_PID.kP; public double tankCrossTrackI = SampleTankDrive.CROSS_TRACK_PID.kI; public double tankCrossTrackD = SampleTankDrive.CROSS_TRACK_PID.kD; public double tankHeadingP = SampleTankDrive.HEADING_PID.kP; public double tankHeadingI = SampleTankDrive.HEADING_PID.kI; public double tankHeadingD = SampleTankDrive.HEADING_PID.kD;
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL; public double mecTransP = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kP; public double mecTransI = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kI; public double mecTransD = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kD; public double mecHeadingP = SampleMecanumDrive.HEADING_PID.kP; public double mecHeadingI = SampleMecanumDrive.HEADING_PID.kI; public double mecHeadingD = SampleMecanumDrive.HEADING_PID.kD; public double mecLateralMultiplier = SampleMecanumDrive.LATERAL_MULTIPLIER; public double tankAxialP = SampleTankDrive.AXIAL_PID.kP; public double tankAxialI = SampleTankDrive.AXIAL_PID.kI; public double tankAxialD = SampleTankDrive.AXIAL_PID.kD; public double tankCrossTrackP = SampleTankDrive.CROSS_TRACK_PID.kP; public double tankCrossTrackI = SampleTankDrive.CROSS_TRACK_PID.kI; public double tankCrossTrackD = SampleTankDrive.CROSS_TRACK_PID.kD; public double tankHeadingP = SampleTankDrive.HEADING_PID.kP; public double tankHeadingI = SampleTankDrive.HEADING_PID.kI; public double tankHeadingD = SampleTankDrive.HEADING_PID.kD;
public double trackingTicksPerRev = StandardTrackingWheelLocalizer.TICKS_PER_REV;
3
2023-10-31 16:06:46+00:00
12k
slatepowered/slate
slate-master/src/main/java/slatepowered/slate/cluster/IntegratedClusterInstance.java
[ { "identifier": "ClusterAllocationChecker", "path": "slate-cluster/src/main/java/slatepowered/slate/allocation/ClusterAllocationChecker.java", "snippet": "public interface ClusterAllocationChecker {\r\n\r\n /**\r\n * Check whether the node could be allocated on this\r\n * cluster.\r\n *\r...
import slatepowered.slate.allocation.ClusterAllocationChecker; import slatepowered.slate.allocation.NodeAllocationRequest; import slatepowered.slate.allocation.NodeAllocationResult; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.model.ClusterManagedNode; import slatepowered.slate.model.ManagedNode; import slatepowered.slate.model.Node; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.local.LocalJavaPackage; import slatepowered.slate.plugin.SlatePluginManager; import java.util.ArrayList;
9,214
package slatepowered.slate.cluster; /** * The integrated cluster instance. */ public class IntegratedClusterInstance extends ClusterInstance { /** * The allocation checker. */ protected ClusterAllocationChecker allocationChecker = (cluster, clusterInstance, name, parent, tags) -> true; // The node which represents this virtual integrated cluster private final ManagedNode localNode; public IntegratedClusterInstance(IntegratedCluster cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(cluster, communicationKey, communicationStrategy); if (cluster.theInstance != null) throw new IllegalStateException("Attempt to construct second cluster instance on an integrated cluster"); cluster.theInstance = this; register(PackageManager.KEY, cluster.getLocalPackageManager());
package slatepowered.slate.cluster; /** * The integrated cluster instance. */ public class IntegratedClusterInstance extends ClusterInstance { /** * The allocation checker. */ protected ClusterAllocationChecker allocationChecker = (cluster, clusterInstance, name, parent, tags) -> true; // The node which represents this virtual integrated cluster private final ManagedNode localNode; public IntegratedClusterInstance(IntegratedCluster cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(cluster, communicationKey, communicationStrategy); if (cluster.theInstance != null) throw new IllegalStateException("Attempt to construct second cluster instance on an integrated cluster"); cluster.theInstance = this; register(PackageManager.KEY, cluster.getLocalPackageManager());
register(SlatePluginManager.KEY, cluster.getPluginManager());
10
2023-10-30 08:58:02+00:00
12k
Melledy/LunarCore
src/main/java/emu/lunarcore/game/rogue/RogueRoomData.java
[ { "identifier": "GameData", "path": "src/main/java/emu/lunarcore/data/GameData.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2O...
import emu.lunarcore.data.GameData; import emu.lunarcore.data.GameDepot; import emu.lunarcore.data.excel.RogueMapExcel; import emu.lunarcore.data.excel.RogueRoomExcel; import emu.lunarcore.proto.RogueRoomOuterClass.RogueRoom; import emu.lunarcore.proto.RogueRoomStatusOuterClass.RogueRoomStatus; import emu.lunarcore.util.Utils; import lombok.Getter;
10,574
package emu.lunarcore.game.rogue; @Getter public class RogueRoomData { private int roomId; private int siteId; private int status; private int[] nextSiteIds;
package emu.lunarcore.game.rogue; @Getter public class RogueRoomData { private int roomId; private int siteId; private int status; private int[] nextSiteIds;
private transient RogueRoomExcel excel;
3
2023-10-10 12:57:35+00:00
12k
jar-analyzer/jar-analyzer
src/main/java/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java
[ { "identifier": "ClassNode", "path": "src/main/java/org/jetbrains/java/decompiler/main/ClassesProcessor.java", "snippet": "public static class ClassNode {\n public static final int CLASS_ROOT = 0;\n public static final int CLASS_MEMBER = 1;\n public static final int CLASS_ANONYMOUS = 2;\n public sta...
import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; import org.jetbrains.java.decompiler.main.DecompilerContext; import org.jetbrains.java.decompiler.struct.StructClass; import org.jetbrains.java.decompiler.struct.StructContext; import org.jetbrains.java.decompiler.struct.StructField; import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; import org.jetbrains.java.decompiler.struct.attr.StructInnerClassesAttribute; import org.jetbrains.java.decompiler.util.TextBuffer; import java.util.*; import java.util.stream.Collectors;
8,471
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler.main.collectors; public class ImportCollector { private static final String JAVA_LANG_PACKAGE = "java.lang"; private final Map<String, String> mapSimpleNames = new HashMap<>(); private final Set<String> setNotImportedNames = new HashSet<>(); // set of field names in this class and all its predecessors. private final Set<String> setFieldNames = new HashSet<>(); private final Set<String> setInnerClassNames = new HashSet<>(); private final String currentPackageSlash; private final String currentPackagePoint; public ImportCollector(ClassNode root) { String clName = root.classStruct.qualifiedName; int index = clName.lastIndexOf('/'); if (index >= 0) { String packageName = clName.substring(0, index); currentPackageSlash = packageName + '/'; currentPackagePoint = packageName.replace('/', '.'); } else { currentPackageSlash = ""; currentPackagePoint = ""; }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler.main.collectors; public class ImportCollector { private static final String JAVA_LANG_PACKAGE = "java.lang"; private final Map<String, String> mapSimpleNames = new HashMap<>(); private final Set<String> setNotImportedNames = new HashSet<>(); // set of field names in this class and all its predecessors. private final Set<String> setFieldNames = new HashSet<>(); private final Set<String> setInnerClassNames = new HashSet<>(); private final String currentPackageSlash; private final String currentPackagePoint; public ImportCollector(ClassNode root) { String clName = root.classStruct.qualifiedName; int index = clName.lastIndexOf('/'); if (index >= 0) { String packageName = clName.substring(0, index); currentPackageSlash = packageName + '/'; currentPackagePoint = packageName.replace('/', '.'); } else { currentPackageSlash = ""; currentPackagePoint = ""; }
Map<String, StructClass> classes = DecompilerContext.getStructContext().getClasses();
2
2023-10-07 15:42:35+00:00
12k
lunasaw/gb28181-proxy
gb28181-test/src/test/java/io/github/lunasaw/gbproxy/test/subscribe/SubscribeServerTest.java
[ { "identifier": "CmdTypeEnum", "path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/CmdTypeEnum.java", "snippet": "public enum CmdTypeEnum {\n\n /**\n * 请求类型\n */\n DEVICE_INFO(\"DeviceInfo\", \"查询设备信息\"),\n DEVICE_STATUS(\"DeviceStatus\", \"查询设备状态\"),\n ...
import io.github.lunasaw.gb28181.common.entity.enums.CmdTypeEnum; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import io.github.lunasaw.gbproxy.server.transimit.cmd.ServerSendCmd; import io.github.lunasaw.gbproxy.test.Gb28181ApplicationTest; import io.github.lunasaw.gbproxy.test.config.DeviceConfig; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.utils.DynamicTask; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j;
10,505
package io.github.lunasaw.gbproxy.test.subscribe; /** * @author luna * @date 2023/10/12 */ @Slf4j @SpringBootTest(classes = Gb28181ApplicationTest.class) public class SubscribeServerTest { @Autowired @Qualifier("serverFrom") private Device fromDevice; @Autowired @Qualifier("serverTo") private Device toDevice; @Autowired private DynamicTask dynamicTask; @Autowired private SipLayer sipLayer; @BeforeEach public void before() { // 本地端口监听 log.info("before::服务端初始化 fromDevice.ip : {} , fromDevice.port : {}", fromDevice.getIp(), fromDevice.getPort()); sipLayer.addListeningPoint(DeviceConfig.LOOP_IP, 8117, true); } @Test public void test_register_server() throws Exception { } @Test public void test_subscribe() { dynamicTask.startDelay("test_subscribe", () -> { Device device = DeviceConfig.DEVICE_SERVER_VIEW_MAP.get("33010602011187000001"); if (device == null) { test_subscribe(); return; } String invitePlay =
package io.github.lunasaw.gbproxy.test.subscribe; /** * @author luna * @date 2023/10/12 */ @Slf4j @SpringBootTest(classes = Gb28181ApplicationTest.class) public class SubscribeServerTest { @Autowired @Qualifier("serverFrom") private Device fromDevice; @Autowired @Qualifier("serverTo") private Device toDevice; @Autowired private DynamicTask dynamicTask; @Autowired private SipLayer sipLayer; @BeforeEach public void before() { // 本地端口监听 log.info("before::服务端初始化 fromDevice.ip : {} , fromDevice.port : {}", fromDevice.getIp(), fromDevice.getPort()); sipLayer.addListeningPoint(DeviceConfig.LOOP_IP, 8117, true); } @Test public void test_register_server() throws Exception { } @Test public void test_subscribe() { dynamicTask.startDelay("test_subscribe", () -> { Device device = DeviceConfig.DEVICE_SERVER_VIEW_MAP.get("33010602011187000001"); if (device == null) { test_subscribe(); return; } String invitePlay =
ServerSendCmd.deviceCatalogSubscribe((FromDevice)fromDevice, (ToDevice)device, 30, CmdTypeEnum.CATALOG.getType());
5
2023-10-11 06:56:28+00:00
12k
1415181920/yamis-admin
cocoyam-modules/cocoyam-module-auth/src/main/java/io/xiaoyu/auth/modular/login/service/impl/SystemUsersServiceImpl.java
[ { "identifier": "AdminUsersEntity", "path": "cocoyam-modules/cocoyam-module-auth/src/main/java/io/xiaoyu/auth/modular/login/entity/AdminUsersEntity.java", "snippet": "@Data\n@TableName(\"admin_users\")\npublic class AdminUsersEntity implements Serializable {\n\n private static final long serialVersio...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Console; import cn.hutool.crypto.digest.DigestUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.xiaoyu.auth.modular.login.entity.AdminUsersEntity; import io.xiaoyu.auth.modular.login.mapper.AdminUsersMapper; import io.xiaoyu.auth.modular.login.param.AuthAccountPasswordLoginParam; import io.xiaoyu.auth.modular.login.resp.SystemCurrentUserResp; import io.xiaoyu.auth.modular.login.service.SystemUserService; import io.xiaoyu.common.exception.CommonException; import io.xiaoyu.common.util.CaptchaCodeImage; import io.xiaoyu.common.util.CommonUrlUtil; import io.xiaoyu.common.yaims.AmisFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource;
7,438
package io.xiaoyu.auth.modular.login.service.impl; @Service public class SystemUsersServiceImpl extends ServiceImpl<AdminUsersMapper, AdminUsersEntity> implements SystemUserService{ @Resource private AdminUsersMapper adminUsersMapper; @Resource private CommonUrlUtil commonUrlUtil; @Override public String doLogin(AuthAccountPasswordLoginParam authAccountPasswordLoginParam) { //检测验证码是否正确 checkCaptcha(authAccountPasswordLoginParam); //检测密码是否正确 AdminUsersEntity adminUsers = checkPassword(authAccountPasswordLoginParam); if (BeanUtil.isEmpty(adminUsers)) { throw new CommonException("账号或密码错误"); } return execLogin(adminUsers); } private String execLogin(AdminUsersEntity adminUsers) { StpUtil.login(adminUsers.getId()); StpUtil.getTokenSession().set("loginUser", adminUsers); // 返回token String tokenValue = StpUtil.getTokenValue(); Console.log("tokenValue", tokenValue); Console.log("权限", StpUtil.hasPermission("user.add1")); Console.log("权限",StpUtil.hasPermission("/admin-api/login")); Console.log("当前会话是否登录:" + StpUtil.isLogin()); Console.log(StpUtil.getTokenInfo()); Console.log(StpUtil.getTokenSession().get("loginUser")); return tokenValue; } @Override public AdminUsersEntity getUserInfo(int id) { return null; } @Override public AdminUsersEntity checkPassword(AuthAccountPasswordLoginParam authAccountPassword) { System.out.println(authAccountPassword.getPassword()); String password = DigestUtil.md5Hex(authAccountPassword.getPassword()); System.out.println(password); return this.getOne(new LambdaQueryWrapper<AdminUsersEntity>() .eq(AdminUsersEntity::getUsername, authAccountPassword.getUsername()) .eq(AdminUsersEntity::getPassword,password)); } @Override public void checkCaptcha(AuthAccountPasswordLoginParam authAccountPasswordLoginParam) { String captcha = new CaptchaCodeImage(authAccountPasswordLoginParam.getCaptcha()).getSys_captcha(); String sys_captcha = authAccountPasswordLoginParam.getSys_captcha(); if (!captcha.equals(sys_captcha)){ throw new CommonException("验证码错误"); } } @Override
package io.xiaoyu.auth.modular.login.service.impl; @Service public class SystemUsersServiceImpl extends ServiceImpl<AdminUsersMapper, AdminUsersEntity> implements SystemUserService{ @Resource private AdminUsersMapper adminUsersMapper; @Resource private CommonUrlUtil commonUrlUtil; @Override public String doLogin(AuthAccountPasswordLoginParam authAccountPasswordLoginParam) { //检测验证码是否正确 checkCaptcha(authAccountPasswordLoginParam); //检测密码是否正确 AdminUsersEntity adminUsers = checkPassword(authAccountPasswordLoginParam); if (BeanUtil.isEmpty(adminUsers)) { throw new CommonException("账号或密码错误"); } return execLogin(adminUsers); } private String execLogin(AdminUsersEntity adminUsers) { StpUtil.login(adminUsers.getId()); StpUtil.getTokenSession().set("loginUser", adminUsers); // 返回token String tokenValue = StpUtil.getTokenValue(); Console.log("tokenValue", tokenValue); Console.log("权限", StpUtil.hasPermission("user.add1")); Console.log("权限",StpUtil.hasPermission("/admin-api/login")); Console.log("当前会话是否登录:" + StpUtil.isLogin()); Console.log(StpUtil.getTokenInfo()); Console.log(StpUtil.getTokenSession().get("loginUser")); return tokenValue; } @Override public AdminUsersEntity getUserInfo(int id) { return null; } @Override public AdminUsersEntity checkPassword(AuthAccountPasswordLoginParam authAccountPassword) { System.out.println(authAccountPassword.getPassword()); String password = DigestUtil.md5Hex(authAccountPassword.getPassword()); System.out.println(password); return this.getOne(new LambdaQueryWrapper<AdminUsersEntity>() .eq(AdminUsersEntity::getUsername, authAccountPassword.getUsername()) .eq(AdminUsersEntity::getPassword,password)); } @Override public void checkCaptcha(AuthAccountPasswordLoginParam authAccountPasswordLoginParam) { String captcha = new CaptchaCodeImage(authAccountPasswordLoginParam.getCaptcha()).getSys_captcha(); String sys_captcha = authAccountPasswordLoginParam.getSys_captcha(); if (!captcha.equals(sys_captcha)){ throw new CommonException("验证码错误"); } } @Override
public SystemCurrentUserResp getCurrentUser() {
3
2023-10-09 06:04:30+00:00
12k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_importworld.java
[ { "identifier": "InvalidWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/InvalidWorldException.java", "snippet": "public class InvalidWorldException extends SlimeException {\n\n public InvalidWorldException(File worldDir) {\n super(\"Directory \" + w...
import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import net.swofty.swm.api.exceptions.InvalidWorldException; import net.swofty.swm.api.exceptions.WorldAlreadyExistsException; import net.swofty.swm.api.exceptions.WorldLoadedException; import net.swofty.swm.api.exceptions.WorldTooBigException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.plugin.SWMPlugin; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.loader.LoaderUtils; import net.swofty.swm.plugin.log.Logging; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit;
9,673
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Imports a world into SWM saves it", inGameOnly = false, permission = "swm.importworld") public class subCommand_importworld extends SWMCommand { private final Cache<String, String[]> importCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(); @Override public void run(CommandSource sender, String[] args) { if (args.length <= 1) { sender.send("§cUsage: /swm importworld <path-to-world> <datasource> [new-world-name]"); return; } String dataSource = args[1]; SlimeLoader loader = LoaderUtils.getLoader(dataSource); if (loader == null) {
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Imports a world into SWM saves it", inGameOnly = false, permission = "swm.importworld") public class subCommand_importworld extends SWMCommand { private final Cache<String, String[]> importCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(); @Override public void run(CommandSource sender, String[] args) { if (args.length <= 1) { sender.send("§cUsage: /swm importworld <path-to-world> <datasource> [new-world-name]"); return; } String dataSource = args[1]; SlimeLoader loader = LoaderUtils.getLoader(dataSource); if (loader == null) {
sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Data source " + dataSource + " does not exist.");
9
2023-10-08 10:54:28+00:00
12k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/NMod.java
[ { "identifier": "ProfileCache", "path": "src/main/java/fifthcolumn/n/client/ProfileCache.java", "snippet": "public class ProfileCache {\n private final Map<UUID, TextureResult> textureMap = new ConcurrentHashMap();\n private final UserCache cache;\n\n public ProfileCache() {\n this.cache = ne...
import fifthcolumn.n.client.ProfileCache; import fifthcolumn.n.client.ui.copenheimer.servers.CopeMultiplayerScreen; import fifthcolumn.n.collar.CollarLogin; import fifthcolumn.n.copenheimer.CopeService; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import meteordevelopment.meteorclient.MeteorClient; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.network.ServerInfo; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.SoundEvent; import net.minecraft.util.Identifier; import net.minecraft.util.NameGenerator;
8,938
package fifthcolumn.n; public class NMod implements ModInitializer { // You can set this to false to enable cope service. DO THIS AT YOUR OWN RISK due to security reasons as the mod would connect to servers on the internet. public static boolean COPE_OFFLINE_MODE = true; private static final Pattern STRIP_PATTERN = Pattern.compile("(?<!<@)[&§](?i)[0-9a-fklmnorx]"); private static NMod INSTANCE; public static final CopeService copeService = new CopeService(); public static final Identifier CAPE_TEXTURE = new Identifier("nc:cape.png"); public static final Identifier cockSound = new Identifier("nc:cock"); public static final Identifier shotgunSound = new Identifier("nc:shot"); public static SoundEvent shotgunSoundEvent; public static SoundEvent cockSoundEvent; public static ProfileCache profileCache; public static GenericNames genericNames;
package fifthcolumn.n; public class NMod implements ModInitializer { // You can set this to false to enable cope service. DO THIS AT YOUR OWN RISK due to security reasons as the mod would connect to servers on the internet. public static boolean COPE_OFFLINE_MODE = true; private static final Pattern STRIP_PATTERN = Pattern.compile("(?<!<@)[&§](?i)[0-9a-fklmnorx]"); private static NMod INSTANCE; public static final CopeService copeService = new CopeService(); public static final Identifier CAPE_TEXTURE = new Identifier("nc:cape.png"); public static final Identifier cockSound = new Identifier("nc:cock"); public static final Identifier shotgunSound = new Identifier("nc:shot"); public static SoundEvent shotgunSoundEvent; public static SoundEvent cockSoundEvent; public static ProfileCache profileCache; public static GenericNames genericNames;
private CopeMultiplayerScreen multiplayerScreen;
1
2023-10-14 19:18:35+00:00
12k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/Parser.java
[ { "identifier": "PreProcess", "path": "src/main/java/zju/cst/aces/api/PreProcess.java", "snippet": "public interface PreProcess {\n\n void process();\n\n}" }, { "identifier": "Task", "path": "src/main/java/zju/cst/aces/api/Task.java", "snippet": "public class Task {\n\n Config conf...
import lombok.Data; import zju.cst.aces.api.PreProcess; import zju.cst.aces.api.Task; import zju.cst.aces.api.config.Config; import zju.cst.aces.parser.ProjectParser; import zju.cst.aces.api.PreProcess;
8,383
package zju.cst.aces.api.impl; @Data public class Parser implements PreProcess { ProjectParser parser; Config config; public Parser(Config config) { this.config = config; this.parser = new ProjectParser(config); } @Override public void process() { this.parse(); } public void parse() { try {
package zju.cst.aces.api.impl; @Data public class Parser implements PreProcess { ProjectParser parser; Config config; public Parser(Config config) { this.config = config; this.parser = new ProjectParser(config); } @Override public void process() { this.parse(); } public void parse() { try {
Task.checkTargetFolder(config.getProject());
1
2023-10-14 07:15:10+00:00
12k
jmdevall/opencodeplan
src/main/java/jmdevall/opencodeplan/application/CodePlan.java
[ { "identifier": "Oracle", "path": "src/main/java/jmdevall/opencodeplan/application/port/out/oracle/Oracle.java", "snippet": "public interface Oracle {\n\n\tDeltaSeeds oracle(Repository r);\n\n}" }, { "identifier": "DependencyGraphConstructor", "path": "src/main/java/jmdevall/opencodeplan/app...
import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import jmdevall.opencodeplan.application.port.out.oracle.Oracle; import jmdevall.opencodeplan.application.port.out.parser.DependencyGraphConstructor; import jmdevall.opencodeplan.application.port.out.parser.Parser; import jmdevall.opencodeplan.application.port.out.repository.Repository; import jmdevall.opencodeplan.domain.BI; import jmdevall.opencodeplan.domain.BlockRelationPair; import jmdevall.opencodeplan.domain.Fragment; import jmdevall.opencodeplan.domain.LlmResult; import jmdevall.opencodeplan.domain.dependencygraph.DependencyGraph; import jmdevall.opencodeplan.domain.dependencygraph.DependencyRelation; import jmdevall.opencodeplan.domain.dependencygraph.Node; import jmdevall.opencodeplan.domain.instruction.DeltaSeeds; import jmdevall.opencodeplan.domain.plangraph.CMIRelation; import jmdevall.opencodeplan.domain.plangraph.ClasifiedChange; import jmdevall.opencodeplan.domain.plangraph.Obligation; import jmdevall.opencodeplan.domain.plangraph.PlanGraph; import jmdevall.opencodeplan.domain.plangraph.WhatD; import jmdevall.opencodeplan.domain.promptmaker.Context; import jmdevall.opencodeplan.domain.promptmaker.PromptMaker; import lombok.AllArgsConstructor; import lombok.Getter;
7,682
package jmdevall.opencodeplan.application; @AllArgsConstructor public class CodePlan { private Parser parser; private DependencyGraphConstructor dependencyGraphConstructor; private PromptMaker promptMaker;
package jmdevall.opencodeplan.application; @AllArgsConstructor public class CodePlan { private Parser parser; private DependencyGraphConstructor dependencyGraphConstructor; private PromptMaker promptMaker;
private Oracle oracle;
0
2023-10-14 18:27:18+00:00
12k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java
[ { "identifier": "GeneratorContent", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/GeneratorContent.java", "snippet": "@Slf4j\n@Getter\n@Builder\npublic class GeneratorContent {\n\n private final String title;\n\n private final String desc;\n\n private final HttpMeth...
import com.github.eahau.openapi.douyin.generator.GeneratorContent; import com.github.eahau.openapi.douyin.generator.Misc; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenApiListApi.ApiListResponse; import com.github.eahau.openapi.douyin.generator.parser.HtmlParser; import com.github.eahau.openapi.douyin.generator.parser.JsonDocParser; import com.google.common.collect.Lists; import feign.Param; import feign.RequestLine; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.collections4.CollectionUtils; import java.util.Collections; import java.util.List;
10,597
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator.api; public interface DouYinOpenDocApi { @RequestLine("GET {path}?__loader=" + Misc.DOC_LANGUAGE + "/$") DocResponse docs(@Param("path") String path); @Getter @ToString @Setter class DocResponse { /** * content 类型,据观察 2=html. */ private int type; private String title; private String keywords; private String description; private String content; private boolean isShowUpdateTime; private String updateTime; private String arcositeId; public String path; public boolean isJson() { return type == 1; } public boolean isMarkdownHeadHtmlBody() { return type == 2; } public GeneratorContent toGeneratorContext() { if (isJson()) {
/* * Copyright 2023 eahau@foxmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator.api; public interface DouYinOpenDocApi { @RequestLine("GET {path}?__loader=" + Misc.DOC_LANGUAGE + "/$") DocResponse docs(@Param("path") String path); @Getter @ToString @Setter class DocResponse { /** * content 类型,据观察 2=html. */ private int type; private String title; private String keywords; private String description; private String content; private boolean isShowUpdateTime; private String updateTime; private String arcositeId; public String path; public boolean isJson() { return type == 1; } public boolean isMarkdownHeadHtmlBody() { return type == 2; } public GeneratorContent toGeneratorContext() { if (isJson()) {
final ApiListResponse apiListResponse = ApiListResponse.fromJson(getContent());
2
2023-10-07 09:09:15+00:00
12k
Aywen1/wispy
src/fr/nicolas/wispy/Panels/GamePanel.java
[ { "identifier": "Runner", "path": "src/fr/nicolas/wispy/Runner.java", "snippet": "public class Runner implements Runnable {\n\n\tprivate boolean isRunning = false;\n\tprivate GamePanel gamePanel;\n\tprivate int maxFps = 80;\n\tprivate long waitTime = 4;\n\n\tpublic Runner(GamePanel gamePanel) {\n\t\tthi...
import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import fr.nicolas.wispy.Runner; import fr.nicolas.wispy.Frames.MainFrame; import fr.nicolas.wispy.Panels.Components.Game.Player; import fr.nicolas.wispy.Panels.Components.Menu.EscapeMenu; import fr.nicolas.wispy.Panels.Components.Menu.WPanel; import fr.nicolas.wispy.Panels.Fonctions.MapManager; import fr.nicolas.wispy.Panels.Fonctions.MapManager.RefreshPaintMap;
7,235
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps
setFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT));
1
2023-10-13 13:10:56+00:00
12k
PfauMC/CyanWorld
cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Cyan1dex.java
[ { "identifier": "EventListener", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/listeners/EventListener.java", "snippet": "public class EventListener\n implements Listener {\n public static Random random = new Random();\n public static DecimalFormat decimalFormat = new Deci...
import org.bukkit.Server; import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import ru.cyanworld.cyan1dex.commands.*; import ru.cyanworld.cyan1dex.listeners.EventListener; import ru.cyanworld.cyan1dex.messages.Msg; import ru.cyanworld.cyan1dex.messages.YandexTranslator; import ru.cyanworld.cyan1dex.query.MCQuery; import ru.cyanworld.cyan1dex.query.QueryResponse; import ru.cyanworld.cyan1dex.rcon.RconManager; import ru.cyanworld.cyan1dex.utils.ChatUtils; import java.io.File; import java.io.IOException; import java.util.*;
9,486
try { cfg.save(new File(dataFolder, name)); } catch (IOException e) { e.printStackTrace(); } } public static void mainRcon(String cmd) { System.out.println("[MainRCON] /" + cmd); Cyan1dex.rcon(35001, cmd, "4HJU9VPONRUFKE8A1PH4"); } public static void rcon(String servername, String cmd) { switch (servername) { case "auth": { Cyan1dex.rcon(35000, cmd, "3CyanPetuh3"); break; } case "survival": { Cyan1dex.rcon(35002, cmd, "3CyanPetuh3"); break; } case "mw": { Cyan1dex.rcon(35003, cmd, "3CyanPetuh3"); break; } case "bw1": { Cyan1dex.rcon(35101, cmd, "3CyanPetuh3"); break; } case "bw2": { Cyan1dex.rcon(35102, cmd, "3CyanPetuh3"); break; } default: { Cyan1dex.rcon(35001, cmd, "3CyanPetuh3"); } } } public static void rcon(int port, String cmd, String pass) { try { RconManager rcon = new RconManager("localhost", port, pass.getBytes()); rcon.command(cmd); rcon.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } public void onEnable() { server = this.getServer(); instance = this; dataFolder = this.getDataFolder(); try { configuration = this.getConfig(); configuration.save(new File(dataFolder, "config.yml")); cfgplayers = YamlConfiguration.loadConfiguration(new File(dataFolder, "players.yml")); cfguuid = YamlConfiguration.loadConfiguration(new File(dataFolder, "uuid.yml")); new Config(); new Msg(); chatUtils = new ChatUtils(); new RebootManager(); ecoMap = new HashMap<Player, Integer>(); world = server.getWorld("world"); new BungeeBridge(); new EventListener(); translator = new YandexTranslator(Arrays.asList("trnsl.1.1.20170422T093752Z.2a56bcc7b9a144df.80639eb6042f852255fab658bc107a0f6995554d", "trnsl.1.1.20170422T093801Z.6c7589690cd72e17.17c8b7df162fcb00389d50d025aead63ab97f20c", "trnsl.1.1.20170422T093823Z.09bb4567c9157c9c.4c4f9c6b07defe91494a26b4720b3f9532274cba")); lang = new LanguageUtils(); this.initCommands(); System.out.println("[Cyan1dex] Запуск для сервера " + Config.servername); server.getScheduler().scheduleSyncDelayedTask(instance, () -> { server.getOnlinePlayers().forEach(players -> { players.sendMessage("§aПлагины перезапущены!"); } ); } ); } catch (Exception ex) { ex.printStackTrace(); server.shutdown(); } } public void onDisable() { Cyan1dex.saveCfg(cfgplayers, "players.yml"); Cyan1dex.saveCfg(cfguuid, "uuid.yml"); Cyan1dex.saveCfg(CmdTrack.trackcfg, "track.yml"); server.getWorlds().forEach(World2 -> { World2.getEntities().forEach(Entity2 -> { if (!(Entity2 instanceof ArmorStand)) { return; } ArmorStand as = (ArmorStand) Entity2; if (as.getScoreboardTags().contains("tempholo")) { as.remove(); } } ); } ); } private void initCommands() { new CmdCyan1dex(); new CmdBroadcast(); new CmdPlayerInfo(); new CmdTell(); new CmdKick(); new CmdLang(); new CmdMe(); new CmdBan(); new CmdTrack(); new CmdG(); } private void initOnlineUpdate() { if (!Config.isMainServer) { return; }
package ru.cyanworld.cyan1dex; public class Cyan1dex extends JavaPlugin { public static Server server; public static Cyan1dex instance; public static File dataFolder; public static Random random; public static YandexTranslator translator; public static LanguageUtils lang; public static EffectManager effectManager; public static ChatUtils chatUtils; public static FileConfiguration configuration; public static YamlConfiguration cfgplayers; public static YamlConfiguration cfguuid; public static YamlConfiguration goodbyedear; public static Map<String, QueryResponse> queryResponseMap; public static Map<Player, Integer> ecoMap; public static World world; public static List<ArmorStand> tempHolo; static { random = new Random(); queryResponseMap = new HashMap<String, QueryResponse>(); tempHolo = new ArrayList<ArmorStand>(); } public static void saveCfg(FileConfiguration cfg, String name) { try { cfg.save(new File(dataFolder, name)); } catch (IOException e) { e.printStackTrace(); } } public static void mainRcon(String cmd) { System.out.println("[MainRCON] /" + cmd); Cyan1dex.rcon(35001, cmd, "4HJU9VPONRUFKE8A1PH4"); } public static void rcon(String servername, String cmd) { switch (servername) { case "auth": { Cyan1dex.rcon(35000, cmd, "3CyanPetuh3"); break; } case "survival": { Cyan1dex.rcon(35002, cmd, "3CyanPetuh3"); break; } case "mw": { Cyan1dex.rcon(35003, cmd, "3CyanPetuh3"); break; } case "bw1": { Cyan1dex.rcon(35101, cmd, "3CyanPetuh3"); break; } case "bw2": { Cyan1dex.rcon(35102, cmd, "3CyanPetuh3"); break; } default: { Cyan1dex.rcon(35001, cmd, "3CyanPetuh3"); } } } public static void rcon(int port, String cmd, String pass) { try { RconManager rcon = new RconManager("localhost", port, pass.getBytes()); rcon.command(cmd); rcon.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } public void onEnable() { server = this.getServer(); instance = this; dataFolder = this.getDataFolder(); try { configuration = this.getConfig(); configuration.save(new File(dataFolder, "config.yml")); cfgplayers = YamlConfiguration.loadConfiguration(new File(dataFolder, "players.yml")); cfguuid = YamlConfiguration.loadConfiguration(new File(dataFolder, "uuid.yml")); new Config(); new Msg(); chatUtils = new ChatUtils(); new RebootManager(); ecoMap = new HashMap<Player, Integer>(); world = server.getWorld("world"); new BungeeBridge(); new EventListener(); translator = new YandexTranslator(Arrays.asList("trnsl.1.1.20170422T093752Z.2a56bcc7b9a144df.80639eb6042f852255fab658bc107a0f6995554d", "trnsl.1.1.20170422T093801Z.6c7589690cd72e17.17c8b7df162fcb00389d50d025aead63ab97f20c", "trnsl.1.1.20170422T093823Z.09bb4567c9157c9c.4c4f9c6b07defe91494a26b4720b3f9532274cba")); lang = new LanguageUtils(); this.initCommands(); System.out.println("[Cyan1dex] Запуск для сервера " + Config.servername); server.getScheduler().scheduleSyncDelayedTask(instance, () -> { server.getOnlinePlayers().forEach(players -> { players.sendMessage("§aПлагины перезапущены!"); } ); } ); } catch (Exception ex) { ex.printStackTrace(); server.shutdown(); } } public void onDisable() { Cyan1dex.saveCfg(cfgplayers, "players.yml"); Cyan1dex.saveCfg(cfguuid, "uuid.yml"); Cyan1dex.saveCfg(CmdTrack.trackcfg, "track.yml"); server.getWorlds().forEach(World2 -> { World2.getEntities().forEach(Entity2 -> { if (!(Entity2 instanceof ArmorStand)) { return; } ArmorStand as = (ArmorStand) Entity2; if (as.getScoreboardTags().contains("tempholo")) { as.remove(); } } ); } ); } private void initCommands() { new CmdCyan1dex(); new CmdBroadcast(); new CmdPlayerInfo(); new CmdTell(); new CmdKick(); new CmdLang(); new CmdMe(); new CmdBan(); new CmdTrack(); new CmdG(); } private void initOnlineUpdate() { if (!Config.isMainServer) { return; }
MCQuery hub = new MCQuery("localhost", 25001);
3
2023-10-08 17:50:55+00:00
12k
vaaako/Vakraft
src/main/java/com/magenta/main/Game.java
[ { "identifier": "Camera", "path": "src/main/java/com/magenta/engine/Camera.java", "snippet": "public class Camera {\n\tprivate final Window window;\n\t// private int width, height;\n\n\t// Camera movement vectors\n\tprivate Vector3f position = new Vector3f(0.0f, 0.0f, 0.0f);\n\tprivate Vector3f rotation...
import org.joml.Vector2f; import org.joml.Vector3f; import org.lwjgl.glfw.GLFW; import com.magenta.engine.Camera; import com.magenta.engine.HitRay; import com.magenta.engine.IGameLogic; import com.magenta.engine.KeyboardInput; import com.magenta.engine.Window; import com.magenta.game.World; import com.magenta.game.block.BlocksEnum; import com.magenta.engine.MouseInput;
8,197
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer;
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer;
private Camera camera;
0
2023-10-08 04:08:22+00:00
12k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/service/DiscordService.java
[ { "identifier": "DiscordMjJavaException", "path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java", "snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n ...
import cn.hutool.core.util.StrUtil; import com.github.dmj.error.DiscordMjJavaException; import com.github.dmj.model.*; import com.github.dmj.queue.TaskQueue; import com.github.dmj.service.api.DiscordApi; import com.github.dmj.util.UniqueUtil; import java.io.File; import java.net.URLConnection; import java.util.Map;
8,187
package com.github.dmj.service; /** * @author ljjy1 * @classname DiscordService * @description API接口服务 * @date 2023/10/11 16:31 */ public class DiscordService { private final Map<String, DiscordApi> discordApiMap; public DiscordService(Map<String, DiscordApi> discordApiMap) { this.discordApiMap = discordApiMap; } /** * 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine */ public Integer imagine(ImagineInRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerImagine,request); return triggerId; } /** * 图片细节增强 对应图片U1 U2 U3 U4 * @return */ public Integer upscale(UpscaleVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerUpscale,request); return triggerId; } /** * 图片变化 对应图片 V1 V2 V3 V4 */ public Integer variation(UpscaleVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerVariation,request); return triggerId; } /** * 图片重绘 对应刷新按钮 */ public Integer reset(ResetRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerReset,request); return triggerId; } /** * 单张图片 微改变Subtle */ public Integer soloLowVariation(SoloVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerSoloLowVariation,request); return triggerId; } /** * 单张图片 较大改变Strong */ public Integer soloHighVariation(SoloVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerSoloHighVariation,request); return triggerId; } /** * 对单张图片进行缩小操作zoomout(2x:50 1.5X 75) */ public Integer zoomOut(ZoomOutRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerZoomOut,request); return triggerId; } /** * 图片进行某方向的扩展 (left/right/up/down) */ public Integer expand(ExpandRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerExpand,request); return triggerId; } /** * 上传文件 * @param userKey * @param file * @return */ public UploadDiscordResponse uploadFileToDiscord(String userKey, File file){ if(file == null || file.length() == 0){ throw new DiscordMjJavaException("上传的文件不能为空,且需要有数据 [The file to be uploaded cannot be empty and must contain data]"); } if(StrUtil.isBlank(userKey)){ throw new DiscordMjJavaException("用户key不能为空 [The userKey cannot be empty]"); } //判断文件需要是图片 String contentType = URLConnection.guessContentTypeFromName(file.getName()); if(!contentType.startsWith("image/")){ throw new DiscordMjJavaException("上传的文件必须为图片类型 [The file to be uploaded must be an image]"); } String uuid = StrUtil.uuid().replace("-", ""); String fileName = uuid+".png"; DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); }
package com.github.dmj.service; /** * @author ljjy1 * @classname DiscordService * @description API接口服务 * @date 2023/10/11 16:31 */ public class DiscordService { private final Map<String, DiscordApi> discordApiMap; public DiscordService(Map<String, DiscordApi> discordApiMap) { this.discordApiMap = discordApiMap; } /** * 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine */ public Integer imagine(ImagineInRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerImagine,request); return triggerId; } /** * 图片细节增强 对应图片U1 U2 U3 U4 * @return */ public Integer upscale(UpscaleVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerUpscale,request); return triggerId; } /** * 图片变化 对应图片 V1 V2 V3 V4 */ public Integer variation(UpscaleVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerVariation,request); return triggerId; } /** * 图片重绘 对应刷新按钮 */ public Integer reset(ResetRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerReset,request); return triggerId; } /** * 单张图片 微改变Subtle */ public Integer soloLowVariation(SoloVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerSoloLowVariation,request); return triggerId; } /** * 单张图片 较大改变Strong */ public Integer soloHighVariation(SoloVariationRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerSoloHighVariation,request); return triggerId; } /** * 对单张图片进行缩小操作zoomout(2x:50 1.5X 75) */ public Integer zoomOut(ZoomOutRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerZoomOut,request); return triggerId; } /** * 图片进行某方向的扩展 (left/right/up/down) */ public Integer expand(ExpandRequest request){ request.check(); String userKey = request.getUserKey(); DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); } Integer triggerId = request.getTriggerId(); //加入队列 TaskQueue.getInstance().putTask(userKey,discordApi::triggerExpand,request); return triggerId; } /** * 上传文件 * @param userKey * @param file * @return */ public UploadDiscordResponse uploadFileToDiscord(String userKey, File file){ if(file == null || file.length() == 0){ throw new DiscordMjJavaException("上传的文件不能为空,且需要有数据 [The file to be uploaded cannot be empty and must contain data]"); } if(StrUtil.isBlank(userKey)){ throw new DiscordMjJavaException("用户key不能为空 [The userKey cannot be empty]"); } //判断文件需要是图片 String contentType = URLConnection.guessContentTypeFromName(file.getName()); if(!contentType.startsWith("image/")){ throw new DiscordMjJavaException("上传的文件必须为图片类型 [The file to be uploaded must be an image]"); } String uuid = StrUtil.uuid().replace("-", ""); String fileName = uuid+".png"; DiscordApi discordApi = discordApiMap.get(userKey); if(discordApi == null){ throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey); }
Integer triggerId = UniqueUtil.generateUniqueId();
3
2023-10-11 01:12:39+00:00
12k
weizen-w/Educational-Management-System-BE
src/main/java/de/ait/ems/controllers/GroupsController.java
[ { "identifier": "GroupsApi", "path": "src/main/java/de/ait/ems/controllers/api/GroupsApi.java", "snippet": "@RequestMapping(\"/api/groups\")\n@Tags(value = {\n @Tag(name = \"Groups\", description = \"This controller realized management of usersgroups\")\n})\n@Validated\npublic interface GroupsApi {\n...
import de.ait.ems.controllers.api.GroupsApi; import de.ait.ems.dto.GroupDto; import de.ait.ems.dto.LessonDto; import de.ait.ems.dto.MaterialDto; import de.ait.ems.dto.NewGroupDto; import de.ait.ems.dto.NewLessonDto; import de.ait.ems.dto.UpdateGroupDto; import de.ait.ems.dto.UserDto; import de.ait.ems.security.details.AuthenticatedUser; import de.ait.ems.services.GroupsService; import de.ait.ems.services.LessonService; import de.ait.ems.services.MaterialsService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.RestController;
7,536
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi { private final GroupsService groupsService; private final LessonService lessonService; private final MaterialsService materialsService; @Override public List<LessonDto> getLessonsByGroup(Long groupId) { return lessonService.getLessonByGroup(groupId); } @Override public LessonDto addLesson(NewLessonDto newLesson, Long groupId) { return lessonService.addLesson(newLesson, groupId); } @Override public List<MaterialDto> getMaterialsByGroup(Long groupId) { return materialsService.getMaterialsByGroupId(groupId); } @Override
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi { private final GroupsService groupsService; private final LessonService lessonService; private final MaterialsService materialsService; @Override public List<LessonDto> getLessonsByGroup(Long groupId) { return lessonService.getLessonByGroup(groupId); } @Override public LessonDto addLesson(NewLessonDto newLesson, Long groupId) { return lessonService.addLesson(newLesson, groupId); } @Override public List<MaterialDto> getMaterialsByGroup(Long groupId) { return materialsService.getMaterialsByGroupId(groupId); } @Override
public GroupDto addGroup(NewGroupDto newGroup) {
1
2023-10-07 16:00:02+00:00
12k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/Level/levels.java
[ { "identifier": "Big_Bloated", "path": "src/entities/Big_Bloated.java", "snippet": "public class Big_Bloated extends Enemy {\n\t\n\tprivate int attackBoxOffsetX;\n\n\tpublic Big_Bloated(float x, float y) {\n\t\tsuper(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED);\n\t\tinitHitbox(22,30);\n\t\...
import java.awt.Point; import java.awt.image.BufferedImage; import java.util.ArrayList; import entities.Big_Bloated; import entities.Carnivorous; import entities.Turtle; import main.Game; import objects.Cannon; import objects.GameContainer; import objects.Potion; import objects.Spike; import utilz.HelpMethods; import static utilz.HelpMethods.*;
8,759
package Level; public class levels { private BufferedImage img; private int[][] lvlData; private int lvlTilesWide; private int maxTilesOffset; private int maxLvlOffsetX; private Point playerSpawn; private ArrayList<Carnivorous> Carnivorous;
package Level; public class levels { private BufferedImage img; private int[][] lvlData; private int lvlTilesWide; private int maxTilesOffset; private int maxLvlOffsetX; private Point playerSpawn; private ArrayList<Carnivorous> Carnivorous;
private ArrayList<Turtle> Turtle;
2
2023-10-07 12:07:45+00:00
12k
yc-huang/bsdb
src/main/java/tech/bsdb/bench/AsyncParquetQueryBench.java
[ { "identifier": "AsyncReader", "path": "src/main/java/tech/bsdb/read/AsyncReader.java", "snippet": "public class AsyncReader extends Reader {\n private KVReader kvReader;\n private final AsyncIndexReader idxReader;\n Logger logger = LoggerFactory.getLogger(AsyncReader.class);\n\n public Asyn...
import tech.bsdb.read.AsyncReader; import tech.bsdb.serde.ParquetSer; import tech.bsdb.util.Common; import com.google.common.base.Strings; import com.google.common.util.concurrent.RateLimiter; import org.apache.commons.cli.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import java.io.File; import java.nio.channels.CompletionHandler; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.LongAdder;
7,354
package tech.bsdb.bench; public class AsyncParquetQueryBench { static Logger logger = LoggerFactory.getLogger(AsyncParquetQueryBench.class); public static void main(String[] args) throws Exception { CommandLine cmd = parseArgs(args); if (!cmd.hasOption("k")) { logger.error("Must specify file contains query keys."); System.exit(1); } String dbPath = cmd.getOptionValue("d", "./rdb"); boolean indexDirect = cmd.hasOption("id"); boolean kvDirect = cmd.hasOption("kd"); String keyFile = cmd.getOptionValue("k"); String keyFieldName = cmd.getOptionValue("kf", null); boolean approximate = cmd.hasOption('a'); boolean verify = cmd.hasOption('v'); Path inPath = new Path(keyFile); Configuration config = new Configuration(); String nameNodeUrl = cmd.getOptionValue("nn"); if (!Strings.isNullOrEmpty(nameNodeUrl)) config.set("fs.defaultFS", nameNodeUrl); FileSystem fs = FileSystem.get(config); FileStatus status = fs.getFileStatus(inPath); if (status == null) { logger.error("input file not exist: {}", keyFile); System.exit(1); } List<FileStatus> files = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus sub : fs.listStatus(inPath)) { if (!sub.isDirectory() && sub.getPath().getName().endsWith(".parquet")) { files.add(sub); } } } else { files.add(status); } if (files.isEmpty()) { logger.error("no valid input file found."); System.exit(1); } LongAdder submits = new LongAdder(); LongAdder successCount = new LongAdder(); LongAdder failedCount = new LongAdder(); AtomicBoolean finished = new AtomicBoolean(false); AsyncReader db = new AsyncReader(new File(dbPath), approximate, indexDirect, kvDirect); final RateLimiter rateLimiter = RateLimiter.create(460 * 1000); new Thread(() -> { int printInterval = 1; while (!finished.get()) { try { long last = successCount.sum(); Thread.sleep(printInterval * 1000); long rate = (successCount.sum() - last) / printInterval; rateLimiter.setRate((rate + 1) * 1.5); logger.info("submit:{}, finished {}, handled {} queries per seconds, failed {}", submits.sum(), successCount.sum(), rate, failedCount.sum()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); ParquetSer parquetReader = new ParquetSer();
package tech.bsdb.bench; public class AsyncParquetQueryBench { static Logger logger = LoggerFactory.getLogger(AsyncParquetQueryBench.class); public static void main(String[] args) throws Exception { CommandLine cmd = parseArgs(args); if (!cmd.hasOption("k")) { logger.error("Must specify file contains query keys."); System.exit(1); } String dbPath = cmd.getOptionValue("d", "./rdb"); boolean indexDirect = cmd.hasOption("id"); boolean kvDirect = cmd.hasOption("kd"); String keyFile = cmd.getOptionValue("k"); String keyFieldName = cmd.getOptionValue("kf", null); boolean approximate = cmd.hasOption('a'); boolean verify = cmd.hasOption('v'); Path inPath = new Path(keyFile); Configuration config = new Configuration(); String nameNodeUrl = cmd.getOptionValue("nn"); if (!Strings.isNullOrEmpty(nameNodeUrl)) config.set("fs.defaultFS", nameNodeUrl); FileSystem fs = FileSystem.get(config); FileStatus status = fs.getFileStatus(inPath); if (status == null) { logger.error("input file not exist: {}", keyFile); System.exit(1); } List<FileStatus> files = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus sub : fs.listStatus(inPath)) { if (!sub.isDirectory() && sub.getPath().getName().endsWith(".parquet")) { files.add(sub); } } } else { files.add(status); } if (files.isEmpty()) { logger.error("no valid input file found."); System.exit(1); } LongAdder submits = new LongAdder(); LongAdder successCount = new LongAdder(); LongAdder failedCount = new LongAdder(); AtomicBoolean finished = new AtomicBoolean(false); AsyncReader db = new AsyncReader(new File(dbPath), approximate, indexDirect, kvDirect); final RateLimiter rateLimiter = RateLimiter.create(460 * 1000); new Thread(() -> { int printInterval = 1; while (!finished.get()) { try { long last = successCount.sum(); Thread.sleep(printInterval * 1000); long rate = (successCount.sum() - last) / printInterval; rateLimiter.setRate((rate + 1) * 1.5); logger.info("submit:{}, finished {}, handled {} queries per seconds, failed {}", submits.sum(), successCount.sum(), rate, failedCount.sum()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); ParquetSer parquetReader = new ParquetSer();
Common.runParallel(Integer.parseInt(System.getProperty("bsdb.query.read.threads", "8")), (pool, futures) -> {
2
2023-10-07 03:32:27+00:00
12k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/controller/UserController.java
[ { "identifier": "BaseController", "path": "src/main/java/io/github/reinershir/boot/common/BaseController.java", "snippet": "@Slf4j\npublic class BaseController {\n\t\n\n\t@InitBinder \n\tpublic void initBinder(WebDataBinder binder){\n\t\t//解除spring mvc list参数限制长度问题\n binder.setAutoGrowCollectionL...
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.util.CollectionUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.github.reinershir.auth.annotation.OptionType; import io.github.reinershir.auth.annotation.Permission; import io.github.reinershir.auth.annotation.PermissionMapping; import io.github.reinershir.auth.core.model.Menu; import io.github.reinershir.auth.core.model.Role; import io.github.reinershir.auth.core.support.AuthorizeManager; import io.github.reinershir.auth.entity.TokenInfo; import io.github.reinershir.boot.common.BaseController; import io.github.reinershir.boot.common.Result; import io.github.reinershir.boot.common.ValidateGroups; import io.github.reinershir.boot.contract.ShirBootContracts; import io.github.reinershir.boot.core.international.IMessager; import io.github.reinershir.boot.core.query.QueryHelper; import io.github.reinershir.boot.dto.req.LoginDTO; import io.github.reinershir.boot.dto.req.ResetPasswordDTO; import io.github.reinershir.boot.dto.req.UpdatePasswordDTO; import io.github.reinershir.boot.dto.req.UserReqDTO; import io.github.reinershir.boot.dto.res.LoginRespDTO; import io.github.reinershir.boot.dto.res.UserInfoDTO; import io.github.reinershir.boot.model.User; import io.github.reinershir.boot.service.impl.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest;
8,493
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login") public Result<LoginRespDTO> login(@Validated @RequestBody LoginDTO loginDTO) throws Exception{ User user = userService.login(loginDTO.getLoginName(), loginDTO.getPassword()); if(user==null) { return Result.failed(IMessager.getInstance().getMessage("message.notmatch")); } LoginRespDTO resp = new LoginRespDTO(); resp.setAccessToken(user.getPassword()); resp.setId(user.getId()); resp.setLoginName(user.getLoginName()); resp.setNickName(user.getNickName()); //resp.setMenus(authorizeManager.getMenusByUser(user.getId().toString())); return Result.ok(resp); } @Operation(summary="User list", description = "User list") @Parameters({ @Parameter(name="pageNo",description="pageNo",required = true,in = ParameterIn.QUERY), @Parameter(name="pageSize",description="pageSize",required = true,in = ParameterIn.QUERY), }) @GetMapping(value = "/list") public Result<IPage<User>> queryPageList(User entity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) { QueryWrapper<User> queryWrapper = QueryHelper.initQueryWrapper(entity); Page<User> page = new Page<User>(pageNo, pageSize); IPage<User> pageList = userService.page(page, queryWrapper); pageList.getRecords().forEach(u->u.setPassword(null)); return Result.ok(pageList); } @ResponseStatus(code = HttpStatus.CREATED) @Permission(name = "Insert user",value = OptionType.ADD) @Operation(summary = "Insert user",description = "Insert user") @PostMapping public Result<User> addUser(@Validated(value = ValidateGroups.AddGroup.class) @RequestBody UserReqDTO user){ User result = userService.insert(user); if(result!=null) { return Result.ok(user); } return Result.failed(); } @Permission(name = "Update user",value = OptionType.UPDATE) @Operation(summary = "Update user",description = "Update user") @PutMapping public Result<User> updateUser(@Validated(value = ValidateGroups.UpdateGroup.class) @RequestBody UserReqDTO user){ if(userService.updateUser(user)>0) { return Result.ok(user); } return Result.failed(); } @Permission(name = "Remove user",value = OptionType.DELETE) @Parameter(name = "id",description = "User ID",required = true) @Operation(summary = "Remove user",description = "Remove user") @DeleteMapping("/{id}") public Result<Object> delete(@PathVariable("id") Long id){ if(userService.logicDeleteUser(id)>0) { try { authorizeManager.logout(id.toString()); } catch (Exception e) { e.printStackTrace(); return Result.failed("删除失败!"); } return Result.ok("删除成功!"); } return Result.failed("删除失败!"); } @Permission(name = "获取用户所绑定的角色ID",value = OptionType.LOGIN) @Parameter(name = "userId",description = "用户ID",required = true) @Operation(summary = "获取用户所绑定的角色ID",description = "获取用户所绑定的角色") @GetMapping("/{userId}/roleIds") public Result<List<Long>> getRoleIdByUser(@PathVariable("userId") Long userId){ return Result.ok(userService.getRoleByUser(userId+"")); } @Permission(name = "Update password",value = OptionType.LOGIN) @Operation(summary = "Update password",description = "Update password") @PatchMapping("password") public Result<Object> updatePassword(@Validated @RequestBody UpdatePasswordDTO dto,HttpServletRequest request){ return userService.updatePassword(request, dto.getPassword(),dto.getNewPassword()); } @Permission(name = "Rest password",value = OptionType.CUSTOM,customPermissionCode = "RESETPASSWORD") @Operation(summary = "Rest password",description = "Rest password") @PatchMapping("/password/reset")
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login") public Result<LoginRespDTO> login(@Validated @RequestBody LoginDTO loginDTO) throws Exception{ User user = userService.login(loginDTO.getLoginName(), loginDTO.getPassword()); if(user==null) { return Result.failed(IMessager.getInstance().getMessage("message.notmatch")); } LoginRespDTO resp = new LoginRespDTO(); resp.setAccessToken(user.getPassword()); resp.setId(user.getId()); resp.setLoginName(user.getLoginName()); resp.setNickName(user.getNickName()); //resp.setMenus(authorizeManager.getMenusByUser(user.getId().toString())); return Result.ok(resp); } @Operation(summary="User list", description = "User list") @Parameters({ @Parameter(name="pageNo",description="pageNo",required = true,in = ParameterIn.QUERY), @Parameter(name="pageSize",description="pageSize",required = true,in = ParameterIn.QUERY), }) @GetMapping(value = "/list") public Result<IPage<User>> queryPageList(User entity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) { QueryWrapper<User> queryWrapper = QueryHelper.initQueryWrapper(entity); Page<User> page = new Page<User>(pageNo, pageSize); IPage<User> pageList = userService.page(page, queryWrapper); pageList.getRecords().forEach(u->u.setPassword(null)); return Result.ok(pageList); } @ResponseStatus(code = HttpStatus.CREATED) @Permission(name = "Insert user",value = OptionType.ADD) @Operation(summary = "Insert user",description = "Insert user") @PostMapping public Result<User> addUser(@Validated(value = ValidateGroups.AddGroup.class) @RequestBody UserReqDTO user){ User result = userService.insert(user); if(result!=null) { return Result.ok(user); } return Result.failed(); } @Permission(name = "Update user",value = OptionType.UPDATE) @Operation(summary = "Update user",description = "Update user") @PutMapping public Result<User> updateUser(@Validated(value = ValidateGroups.UpdateGroup.class) @RequestBody UserReqDTO user){ if(userService.updateUser(user)>0) { return Result.ok(user); } return Result.failed(); } @Permission(name = "Remove user",value = OptionType.DELETE) @Parameter(name = "id",description = "User ID",required = true) @Operation(summary = "Remove user",description = "Remove user") @DeleteMapping("/{id}") public Result<Object> delete(@PathVariable("id") Long id){ if(userService.logicDeleteUser(id)>0) { try { authorizeManager.logout(id.toString()); } catch (Exception e) { e.printStackTrace(); return Result.failed("删除失败!"); } return Result.ok("删除成功!"); } return Result.failed("删除失败!"); } @Permission(name = "获取用户所绑定的角色ID",value = OptionType.LOGIN) @Parameter(name = "userId",description = "用户ID",required = true) @Operation(summary = "获取用户所绑定的角色ID",description = "获取用户所绑定的角色") @GetMapping("/{userId}/roleIds") public Result<List<Long>> getRoleIdByUser(@PathVariable("userId") Long userId){ return Result.ok(userService.getRoleByUser(userId+"")); } @Permission(name = "Update password",value = OptionType.LOGIN) @Operation(summary = "Update password",description = "Update password") @PatchMapping("password") public Result<Object> updatePassword(@Validated @RequestBody UpdatePasswordDTO dto,HttpServletRequest request){ return userService.updatePassword(request, dto.getPassword(),dto.getNewPassword()); } @Permission(name = "Rest password",value = OptionType.CUSTOM,customPermissionCode = "RESETPASSWORD") @Operation(summary = "Rest password",description = "Rest password") @PatchMapping("/password/reset")
public Result<Object> resetPassword(@RequestBody ResetPasswordDTO dto){
7
2023-10-10 13:06:54+00:00
12k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/MiscInfoLabel.java
[ { "identifier": "PlayerBuild", "path": "src/main/java/net/wiseoldman/beans/PlayerBuild.java", "snippet": "@AllArgsConstructor\npublic enum PlayerBuild\n{\n @SerializedName(\"1def\")\n ONE_DEF_PURE(\"1 Def Pure\"),\n\n @SerializedName(\"lvl3\")\n LEVEL_3(\"Level 3\"),\n\n @SerializedName(\...
import net.wiseoldman.beans.PlayerBuild; import net.wiseoldman.ui.CountryIcon; import net.wiseoldman.util.Format; import net.wiseoldman.util.Utils; import net.wiseoldman.beans.PlayerInfo; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import javax.swing.*; import javax.swing.border.EmptyBorder;
7,725
package net.wiseoldman.panel; public class MiscInfoLabel extends JLabel { MiscInfo info; public MiscInfoLabel(MiscInfo info) { this.info = info; setFont(FontManager.getRunescapeSmallFont()); setBorder(new EmptyBorder(5, 10, 5, 5)); setText(info.getDefaultText()); setToolTipText(info.getHoverText()); if (info != MiscInfo.LAST_UPDATED) { setBackground(ColorScheme.DARKER_GRAY_COLOR); setOpaque(true); setIcon(info.getIcon()); } else { setHorizontalAlignment(JLabel.CENTER); } } public void format(PlayerInfo result, boolean relative) { switch (info) { case COUNTRY: String country = result.getCountry(); String countryText = country == null ? "--" : country; String countryCode = country == null ? "default" : country.toLowerCase();
package net.wiseoldman.panel; public class MiscInfoLabel extends JLabel { MiscInfo info; public MiscInfoLabel(MiscInfo info) { this.info = info; setFont(FontManager.getRunescapeSmallFont()); setBorder(new EmptyBorder(5, 10, 5, 5)); setText(info.getDefaultText()); setToolTipText(info.getHoverText()); if (info != MiscInfo.LAST_UPDATED) { setBackground(ColorScheme.DARKER_GRAY_COLOR); setOpaque(true); setIcon(info.getIcon()); } else { setHorizontalAlignment(JLabel.CENTER); } } public void format(PlayerInfo result, boolean relative) { switch (info) { case COUNTRY: String country = result.getCountry(); String countryText = country == null ? "--" : country; String countryCode = country == null ? "default" : country.toLowerCase();
setIcon(CountryIcon.loadSquareImage(countryCode));
1
2023-10-09 14:23:06+00:00
12k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/level/tile/CalmLiquidTile.java
[ { "identifier": "Level", "path": "src/main/java/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tpublic int width;\n\tpublic int height;\n\tpublic int depth;\n\tpublic byte[] blocks;\n\tpublic String na...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.Liquid; import java.util.Random;
8,483
package com.mojang.minecraft.level.tile; public final class CalmLiquidTile extends LiquidTile { protected CalmLiquidTile(int var1, Liquid var2) { super(var1, var2); this.tileId = var1 - 1; this.calmTileId = var1; this.setTicking(false); }
package com.mojang.minecraft.level.tile; public final class CalmLiquidTile extends LiquidTile { protected CalmLiquidTile(int var1, Liquid var2) { super(var1, var2); this.tileId = var1 - 1; this.calmTileId = var1; this.setTicking(false); }
public final void tick(Level var1, int var2, int var3, int var4, Random var5) {
0
2023-10-10 17:10:45+00:00
12k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/parser/reader/ParserFileReader.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import org.apache.log4j.Logger; import com.monitor.agent.server.FileState; import com.monitor.agent.server.LogFormat; import com.monitor.agent.server.filter.Filter; import com.monitor.parser.PMParser; import com.monitor.parser.TJParser; import com.monitor.parser.LogParser; import com.monitor.parser.ParserParameters; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
7,359
package com.monitor.parser.reader; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public class ParserFileReader { private static final Logger logger = Logger.getLogger(ParserFileReader.class); protected int spoolSize = 0; private final ParserRecordsStorage records; private Map<File, Long> pointerMap; private int recordsCount; private final HashMap<LogFormat, LogParser> parsers; private final Filter filter; private final boolean draft;
package com.monitor.parser.reader; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public class ParserFileReader { private static final Logger logger = Logger.getLogger(ParserFileReader.class); protected int spoolSize = 0; private final ParserRecordsStorage records; private Map<File, Long> pointerMap; private int recordsCount; private final HashMap<LogFormat, LogParser> parsers; private final Filter filter; private final boolean draft;
private final ParserParameters parserParameters;
6
2023-10-11 20:25:12+00:00
12k
giteecode/bookmanage2-public
nhXJH-common/src/main/java/com/nhXJH/common/core/controller/BaseController.java
[ { "identifier": "SnowFlakeUtil", "path": "nhXJH-common/src/main/java/com/nhXJH/common/config/SnowFlakeUtil.java", "snippet": "@Component(\"snowFlakeUtil\")\npublic class SnowFlakeUtil {\n\tprivate long workerId=0L;\n\tprivate long datacenterId=1L;\n\tprivate Snowflake snowflake= IdUtil.createSnowflake(w...
import java.beans.PropertyEditorSupport; import java.util.Date; import java.util.List; import com.nhXJH.common.config.SnowFlakeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.nhXJH.common.constant.HttpStatus; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.common.core.page.PageDomain; import com.nhXJH.common.core.page.TableDataInfo; import com.nhXJH.common.core.page.TableSupport; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.common.utils.PageUtils; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.sql.SqlUtil;
10,763
package com.nhXJH.common.core.controller; /** * web层通用数据处理 * * @author nhXJH */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
package com.nhXJH.common.core.controller; /** * web层通用数据处理 * * @author nhXJH */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
11
2023-10-13 07:19:20+00:00
12k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/datagen/AITModDataGenerator.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.core.AITBlocks; import mdteam.ait.core.AITItems; import mdteam.ait.core.AITSounds; import mdteam.ait.datagen.datagen_providers.*; import mdteam.ait.datagen.datagen_providers.loot.AITBlockLootTables; import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint; import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricRecipeProvider; import net.minecraft.data.server.recipe.ShapedRecipeJsonBuilder; import net.minecraft.data.server.recipe.ShapelessRecipeJsonBuilder; import net.minecraft.data.server.recipe.SmithingTransformRecipeJsonBuilder; import net.minecraft.item.Items; import net.minecraft.recipe.Ingredient; import net.minecraft.recipe.book.RecipeCategory; import net.minecraft.registry.RegistryWrapper; import net.minecraft.util.Identifier; import java.util.concurrent.CompletableFuture;
8,459
.input('R', Items.REDSTONE_BLOCK) .criterion(FabricRecipeProvider.hasItem(Items.COPPER_INGOT), FabricRecipeProvider.conditionsFromItem(Items.COPPER_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.RIFT_SCANNER, 1) .pattern(" A ") .pattern("IDI") .pattern("QRQ") .input('A', Items.AMETHYST_SHARD) .input('I', Items.IRON_INGOT) .input('D', Items.DIAMOND) .input('R', Items.REDSTONE_BLOCK) .input('Q', Items.QUARTZ) .criterion(FabricRecipeProvider.hasItem(Items.AMETHYST_SHARD), FabricRecipeProvider.conditionsFromItem(Items.AMETHYST_SHARD)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.DIAMOND), FabricRecipeProvider.conditionsFromItem(Items.DIAMOND)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) .criterion(FabricRecipeProvider.hasItem(Items.QUARTZ), FabricRecipeProvider.conditionsFromItem(Items.QUARTZ)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.BUILDING_BLOCKS, AITBlocks.CORAL_PLANT, 1) .pattern("SRS") .pattern("BCB") .pattern("ERE") .input('C', Items.DEAD_BRAIN_CORAL) .input('R', Items.END_CRYSTAL) .input('E', Items.ENDER_EYE) .input('S', Items.BLAZE_ROD) .input('B', Items.REDSTONE_BLOCK) .criterion(FabricRecipeProvider.hasItem(Items.DEAD_BRAIN_CORAL), FabricRecipeProvider.conditionsFromItem(Items.DEAD_BRAIN_CORAL)) .criterion(FabricRecipeProvider.hasItem(Items.END_CRYSTAL), FabricRecipeProvider.conditionsFromItem(Items.END_CRYSTAL)) .criterion(FabricRecipeProvider.hasItem(Items.ENDER_EYE), FabricRecipeProvider.conditionsFromItem(Items.ENDER_EYE)) .criterion(FabricRecipeProvider.hasItem(Items.BLAZE_ROD), FabricRecipeProvider.conditionsFromItem(Items.BLAZE_ROD)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.MECHANICAL_SONIC_SCREWDRIVER, 1) .pattern(" IE") .pattern("ICI") .pattern("BI ") .input('I', Items.IRON_INGOT) .input('E', Items.ENDER_EYE) .input('C', Items.COMPARATOR) .input('B', Items.BLAZE_ROD) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.ENDER_EYE), FabricRecipeProvider.conditionsFromItem(Items.ENDER_EYE)) .criterion(FabricRecipeProvider.hasItem(Items.COMPARATOR), FabricRecipeProvider.conditionsFromItem(Items.COMPARATOR)) .criterion(FabricRecipeProvider.hasItem(Items.BLAZE_ROD), FabricRecipeProvider.conditionsFromItem(Items.BLAZE_ROD))); provider.addShapelessRecipe(ShapelessRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.RENAISSANCE_SONIC_SCREWDRIVER, 1) .input(AITItems.CORAL_SONIC_SCREWDRIVER) .criterion(FabricRecipeProvider.hasItem(AITItems.CORAL_SONIC_SCREWDRIVER), FabricRecipeProvider.conditionsFromItem(AITItems.CORAL_SONIC_SCREWDRIVER))); provider.addShapelessRecipe(ShapelessRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.CORAL_SONIC_SCREWDRIVER, 1) .input(AITItems.MECHANICAL_SONIC_SCREWDRIVER) .criterion(FabricRecipeProvider.hasItem(AITItems.MECHANICAL_SONIC_SCREWDRIVER), FabricRecipeProvider.conditionsFromItem(AITItems.MECHANICAL_SONIC_SCREWDRIVER))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITBlocks.CONSOLE, 1) .pattern(" G ") .pattern("CEC") .pattern(" I ") .input('G', Items.GLASS) .input('C', Items.COMPARATOR) .input('E', Items.END_CRYSTAL) .input('I', Items.IRON_INGOT) .criterion(FabricRecipeProvider.hasItem(Items.GLASS), FabricRecipeProvider.conditionsFromItem(Items.GLASS)) .criterion(FabricRecipeProvider.hasItem(Items.COMPARATOR), FabricRecipeProvider.conditionsFromItem(Items.COMPARATOR)) .criterion(FabricRecipeProvider.hasItem(Items.END_CRYSTAL), FabricRecipeProvider.conditionsFromItem(Items.END_CRYSTAL)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITBlocks.DOOR_BLOCK, 1) .pattern("GCG") .pattern("CDC") .pattern("CCC") .input('D', Items.IRON_DOOR) .input('G', Items.GLASS_PANE) .input('C', Items.LIGHT_GRAY_CONCRETE) .criterion(FabricRecipeProvider.hasItem(Items.IRON_DOOR), FabricRecipeProvider.conditionsFromItem(Items.IRON_DOOR)) .criterion(FabricRecipeProvider.hasItem(Items.GLASS_PANE), FabricRecipeProvider.conditionsFromItem(Items.GLASS_PANE)) .criterion(FabricRecipeProvider.hasItem(Items.LIGHT_GRAY_CONCRETE), FabricRecipeProvider.conditionsFromItem(Items.LIGHT_GRAY_CONCRETE))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.WAYPOINT_CARTRIDGE, 1) .pattern("III") .pattern("IBI") .pattern("CGC") .input('I', Items.IRON_INGOT) .input('B', Items.REDSTONE_BLOCK) .input('C', Items.GREEN_DYE) .input('G', Items.GOLD_NUGGET) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) .criterion(FabricRecipeProvider.hasItem(Items.GREEN_DYE), FabricRecipeProvider.conditionsFromItem(Items.GREEN_DYE)) .criterion(FabricRecipeProvider.hasItem(Items.GOLD_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.GOLD_NUGGET))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.HAMMER, 1) .pattern("DSD") .pattern(" A ") .pattern(" T ") .input('D', Items.DRIED_KELP) .input('S', Items.STRING) .input('A', Items.IRON_AXE) .input('T', Items.STICK) .criterion(FabricRecipeProvider.hasItem(Items.DRIED_KELP), FabricRecipeProvider.conditionsFromItem(Items.DRIED_KELP)) .criterion(FabricRecipeProvider.hasItem(Items.STRING), FabricRecipeProvider.conditionsFromItem(Items.STRING)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_AXE), FabricRecipeProvider.conditionsFromItem(Items.IRON_AXE)) .criterion(FabricRecipeProvider.hasItem(Items.STICK), FabricRecipeProvider.conditionsFromItem(Items.STICK))); generateSmithingRecipes(provider); return provider; }))); } public void generateSmithingRecipes(AITRecipeProvider provider) { provider.addSmithingTransformRecipe(SmithingTransformRecipeJsonBuilder.create( Ingredient.ofItems(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE), Ingredient.ofItems(AITItems.IRON_KEY), Ingredient.ofItems(Items.GOLD_NUGGET), RecipeCategory.TOOLS, AITItems.GOLD_KEY) .criterion(FabricRecipeProvider.hasItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE), FabricRecipeProvider.conditionsFromItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE)) .criterion(FabricRecipeProvider.hasItem(AITItems.IRON_KEY), FabricRecipeProvider.conditionsFromItem(AITItems.IRON_KEY)) .criterion(FabricRecipeProvider.hasItem(Items.GOLD_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.GOLD_NUGGET)) .criterion(FabricRecipeProvider.hasItem(AITItems.GOLD_KEY), FabricRecipeProvider.conditionsFromItem(AITItems.GOLD_KEY)),
package mdteam.ait.datagen; public class AITModDataGenerator implements DataGeneratorEntrypoint { @Override public void onInitializeDataGenerator(FabricDataGenerator fabricDataGenerator) { FabricDataGenerator.Pack pack = fabricDataGenerator.createPack(); generateLanguages(pack); generateItemTags(pack); // fixme im not sure why this is being silly goofy generateRecipes(pack); generateBlockModels(pack); generateSoundData(pack); generateAdvancements(pack); generateLoot(pack); } public void generateLoot(FabricDataGenerator.Pack pack) { pack.addProvider(AITBlockLootTables::new); } private void generateAdvancements(FabricDataGenerator.Pack pack) { pack.addProvider(AITAchievementProvider::new); } public void generateRecipes(FabricDataGenerator.Pack pack) { pack.addProvider((((output, registriesFuture) -> { AITRecipeProvider provider = new AITRecipeProvider(output); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.IRON_KEY, 1) .pattern(" N ") .pattern("IEI") .pattern("IRI") .input('N', Items.IRON_NUGGET) .input('I', Items.IRON_INGOT) .input('E', Items.ENDER_PEARL) .input('R', Items.REDSTONE) .criterion(FabricRecipeProvider.hasItem(Items.IRON_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.IRON_NUGGET)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.ENDER_PEARL), FabricRecipeProvider.conditionsFromItem(Items.ENDER_PEARL)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE, 1) .pattern("GGG") .pattern("GNG") .pattern("GGG") .input('N', Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE) .input('G', Items.GOLD_NUGGET) .criterion(FabricRecipeProvider.hasItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE), FabricRecipeProvider.conditionsFromItem(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE)) .criterion(FabricRecipeProvider.hasItem(Items.GOLD_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.GOLD_NUGGET)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITItems.NETHERITE_KEY_UPGRADE_SMITHING_TEMPLATE, 1) .pattern("SSS") .pattern("SGS") .pattern("SSS") .input('G', AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE) .input('S', Items.NETHERITE_SCRAP) .criterion(FabricRecipeProvider.hasItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE), FabricRecipeProvider.conditionsFromItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE)) .criterion(FabricRecipeProvider.hasItem(Items.NETHERITE_SCRAP), FabricRecipeProvider.conditionsFromItem(Items.NETHERITE_SCRAP)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITItems.CLASSIC_KEY_UPGRADE_SMITHING_TEMPLATE, 1) .pattern("SAS") .pattern("INI") .pattern("SAS") .input('I', Items.NETHERITE_INGOT) .input('N', AITItems.NETHERITE_KEY_UPGRADE_SMITHING_TEMPLATE) .input('S', Items.NETHERITE_SCRAP) .input('A', Items.AMETHYST_SHARD) .criterion(FabricRecipeProvider.hasItem(Items.NETHERITE_INGOT), FabricRecipeProvider.conditionsFromItem(Items.NETHERITE_INGOT)) .criterion(FabricRecipeProvider.hasItem(AITItems.NETHERITE_KEY_UPGRADE_SMITHING_TEMPLATE), FabricRecipeProvider.conditionsFromItem(AITItems.NETHERITE_KEY_UPGRADE_SMITHING_TEMPLATE)) .criterion(FabricRecipeProvider.hasItem(Items.NETHERITE_SCRAP), FabricRecipeProvider.conditionsFromItem(Items.NETHERITE_SCRAP)) .criterion(FabricRecipeProvider.hasItem(Items.AMETHYST_SHARD), FabricRecipeProvider.conditionsFromItem(Items.AMETHYST_SHARD)) ); /*provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.REMOTE_ITEM, 1) .pattern(" R ") .pattern("ICI") .pattern("IPI") .input('R', Items.REDSTONE_BLOCK) .input('I', Items.NETHERITE_INGOT) .input('C', Items.COPPER_INGOT) .input('P', Items.REPEATER) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) .criterion(FabricRecipeProvider.hasItem(Items.NETHERITE_INGOT), FabricRecipeProvider.conditionsFromItem(Items.NETHERITE_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.COPPER_INGOT), FabricRecipeProvider.conditionsFromItem(Items.COPPER_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.REPEATER), FabricRecipeProvider.conditionsFromItem(Items.REPEATER)) );*/ provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.ARTRON_COLLECTOR, 1) .pattern("CCC") .pattern("IRI") .pattern("CCC") .input('C', Items.COPPER_INGOT) .input('I', Items.IRON_INGOT) .input('R', Items.REDSTONE_BLOCK) .criterion(FabricRecipeProvider.hasItem(Items.COPPER_INGOT), FabricRecipeProvider.conditionsFromItem(Items.COPPER_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.RIFT_SCANNER, 1) .pattern(" A ") .pattern("IDI") .pattern("QRQ") .input('A', Items.AMETHYST_SHARD) .input('I', Items.IRON_INGOT) .input('D', Items.DIAMOND) .input('R', Items.REDSTONE_BLOCK) .input('Q', Items.QUARTZ) .criterion(FabricRecipeProvider.hasItem(Items.AMETHYST_SHARD), FabricRecipeProvider.conditionsFromItem(Items.AMETHYST_SHARD)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.DIAMOND), FabricRecipeProvider.conditionsFromItem(Items.DIAMOND)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) .criterion(FabricRecipeProvider.hasItem(Items.QUARTZ), FabricRecipeProvider.conditionsFromItem(Items.QUARTZ)) ); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.BUILDING_BLOCKS, AITBlocks.CORAL_PLANT, 1) .pattern("SRS") .pattern("BCB") .pattern("ERE") .input('C', Items.DEAD_BRAIN_CORAL) .input('R', Items.END_CRYSTAL) .input('E', Items.ENDER_EYE) .input('S', Items.BLAZE_ROD) .input('B', Items.REDSTONE_BLOCK) .criterion(FabricRecipeProvider.hasItem(Items.DEAD_BRAIN_CORAL), FabricRecipeProvider.conditionsFromItem(Items.DEAD_BRAIN_CORAL)) .criterion(FabricRecipeProvider.hasItem(Items.END_CRYSTAL), FabricRecipeProvider.conditionsFromItem(Items.END_CRYSTAL)) .criterion(FabricRecipeProvider.hasItem(Items.ENDER_EYE), FabricRecipeProvider.conditionsFromItem(Items.ENDER_EYE)) .criterion(FabricRecipeProvider.hasItem(Items.BLAZE_ROD), FabricRecipeProvider.conditionsFromItem(Items.BLAZE_ROD)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.MECHANICAL_SONIC_SCREWDRIVER, 1) .pattern(" IE") .pattern("ICI") .pattern("BI ") .input('I', Items.IRON_INGOT) .input('E', Items.ENDER_EYE) .input('C', Items.COMPARATOR) .input('B', Items.BLAZE_ROD) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.ENDER_EYE), FabricRecipeProvider.conditionsFromItem(Items.ENDER_EYE)) .criterion(FabricRecipeProvider.hasItem(Items.COMPARATOR), FabricRecipeProvider.conditionsFromItem(Items.COMPARATOR)) .criterion(FabricRecipeProvider.hasItem(Items.BLAZE_ROD), FabricRecipeProvider.conditionsFromItem(Items.BLAZE_ROD))); provider.addShapelessRecipe(ShapelessRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.RENAISSANCE_SONIC_SCREWDRIVER, 1) .input(AITItems.CORAL_SONIC_SCREWDRIVER) .criterion(FabricRecipeProvider.hasItem(AITItems.CORAL_SONIC_SCREWDRIVER), FabricRecipeProvider.conditionsFromItem(AITItems.CORAL_SONIC_SCREWDRIVER))); provider.addShapelessRecipe(ShapelessRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.CORAL_SONIC_SCREWDRIVER, 1) .input(AITItems.MECHANICAL_SONIC_SCREWDRIVER) .criterion(FabricRecipeProvider.hasItem(AITItems.MECHANICAL_SONIC_SCREWDRIVER), FabricRecipeProvider.conditionsFromItem(AITItems.MECHANICAL_SONIC_SCREWDRIVER))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITBlocks.CONSOLE, 1) .pattern(" G ") .pattern("CEC") .pattern(" I ") .input('G', Items.GLASS) .input('C', Items.COMPARATOR) .input('E', Items.END_CRYSTAL) .input('I', Items.IRON_INGOT) .criterion(FabricRecipeProvider.hasItem(Items.GLASS), FabricRecipeProvider.conditionsFromItem(Items.GLASS)) .criterion(FabricRecipeProvider.hasItem(Items.COMPARATOR), FabricRecipeProvider.conditionsFromItem(Items.COMPARATOR)) .criterion(FabricRecipeProvider.hasItem(Items.END_CRYSTAL), FabricRecipeProvider.conditionsFromItem(Items.END_CRYSTAL)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.MISC, AITBlocks.DOOR_BLOCK, 1) .pattern("GCG") .pattern("CDC") .pattern("CCC") .input('D', Items.IRON_DOOR) .input('G', Items.GLASS_PANE) .input('C', Items.LIGHT_GRAY_CONCRETE) .criterion(FabricRecipeProvider.hasItem(Items.IRON_DOOR), FabricRecipeProvider.conditionsFromItem(Items.IRON_DOOR)) .criterion(FabricRecipeProvider.hasItem(Items.GLASS_PANE), FabricRecipeProvider.conditionsFromItem(Items.GLASS_PANE)) .criterion(FabricRecipeProvider.hasItem(Items.LIGHT_GRAY_CONCRETE), FabricRecipeProvider.conditionsFromItem(Items.LIGHT_GRAY_CONCRETE))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.WAYPOINT_CARTRIDGE, 1) .pattern("III") .pattern("IBI") .pattern("CGC") .input('I', Items.IRON_INGOT) .input('B', Items.REDSTONE_BLOCK) .input('C', Items.GREEN_DYE) .input('G', Items.GOLD_NUGGET) .criterion(FabricRecipeProvider.hasItem(Items.IRON_INGOT), FabricRecipeProvider.conditionsFromItem(Items.IRON_INGOT)) .criterion(FabricRecipeProvider.hasItem(Items.REDSTONE_BLOCK), FabricRecipeProvider.conditionsFromItem(Items.REDSTONE_BLOCK)) .criterion(FabricRecipeProvider.hasItem(Items.GREEN_DYE), FabricRecipeProvider.conditionsFromItem(Items.GREEN_DYE)) .criterion(FabricRecipeProvider.hasItem(Items.GOLD_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.GOLD_NUGGET))); provider.addShapedRecipe(ShapedRecipeJsonBuilder.create(RecipeCategory.TOOLS, AITItems.HAMMER, 1) .pattern("DSD") .pattern(" A ") .pattern(" T ") .input('D', Items.DRIED_KELP) .input('S', Items.STRING) .input('A', Items.IRON_AXE) .input('T', Items.STICK) .criterion(FabricRecipeProvider.hasItem(Items.DRIED_KELP), FabricRecipeProvider.conditionsFromItem(Items.DRIED_KELP)) .criterion(FabricRecipeProvider.hasItem(Items.STRING), FabricRecipeProvider.conditionsFromItem(Items.STRING)) .criterion(FabricRecipeProvider.hasItem(Items.IRON_AXE), FabricRecipeProvider.conditionsFromItem(Items.IRON_AXE)) .criterion(FabricRecipeProvider.hasItem(Items.STICK), FabricRecipeProvider.conditionsFromItem(Items.STICK))); generateSmithingRecipes(provider); return provider; }))); } public void generateSmithingRecipes(AITRecipeProvider provider) { provider.addSmithingTransformRecipe(SmithingTransformRecipeJsonBuilder.create( Ingredient.ofItems(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE), Ingredient.ofItems(AITItems.IRON_KEY), Ingredient.ofItems(Items.GOLD_NUGGET), RecipeCategory.TOOLS, AITItems.GOLD_KEY) .criterion(FabricRecipeProvider.hasItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE), FabricRecipeProvider.conditionsFromItem(AITItems.GOLD_KEY_UPGRADE_SMITHING_TEMPLATE)) .criterion(FabricRecipeProvider.hasItem(AITItems.IRON_KEY), FabricRecipeProvider.conditionsFromItem(AITItems.IRON_KEY)) .criterion(FabricRecipeProvider.hasItem(Items.GOLD_NUGGET), FabricRecipeProvider.conditionsFromItem(Items.GOLD_NUGGET)) .criterion(FabricRecipeProvider.hasItem(AITItems.GOLD_KEY), FabricRecipeProvider.conditionsFromItem(AITItems.GOLD_KEY)),
new Identifier(AITMod.MOD_ID, "gold_key_smithing"));
0
2023-10-08 00:38:53+00:00
12k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/system/SysLoginController.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import java.util.List; import java.util.Set; import net.bytebuddy.implementation.bind.annotation.Origin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.core.domain.entity.SysMenu; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginBody; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.framework.web.service.SysLoginService; import com.nhXJH.framework.web.service.SysPermissionService; import com.nhXJH.system.service.ISysMenuService;
8,685
package com.nhXJH.web.controller.system; /** * 登录验证 * * @author nhXJH */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") @CrossOrigin
package com.nhXJH.web.controller.system; /** * 登录验证 * * @author nhXJH */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") @CrossOrigin
public AjaxResult login(@RequestBody LoginBody loginBody) {
4
2023-10-14 04:57:42+00:00
12k
aleksandarsusnjar/paniql
print/src/main/java/net/susnjar/paniql/print/InvoicePrinter.java
[ { "identifier": "ElementModel", "path": "core/src/main/java/net/susnjar/paniql/models/ElementModel.java", "snippet": "public abstract class ElementModel<D extends DirectivesContainer<D>> {\n public static final double LOG_BASE_0_95 = Math.log(0.95d);\n public static final double LOG_BASE_1_9 = Mat...
import net.susnjar.paniql.models.ElementModel; import net.susnjar.paniql.pricing.Bounds; import net.susnjar.paniql.pricing.Invoice; import net.susnjar.paniql.pricing.Price; import net.susnjar.paniql.pricing.WorkType; import java.io.PrintStream; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.function.Function;
7,371
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() {
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() {
lineWidth = nameWidth + 1 + 3 + WorkType.values().length * columnWidth;
4
2023-10-10 01:58:56+00:00
12k
quan100/quan
quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/command/service/SitemapService.java
[ { "identifier": "SitemapAssembler", "path": "quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/command/convert/SitemapAssembler.java", "snippet": "@Mapper\npublic interface SitemapAssembler {\n SitemapAssembler INSTANCE = Mappers.getMapper(SitemapAssembler.class);\n\n String TAG = \":\...
import cn.javaquan.app.pm.bff.command.convert.SitemapAssembler; import cn.javaquan.app.common.module.article.ArticleDTO; import cn.javaquan.app.common.module.auth.convert.AuthAssembler; import cn.javaquan.app.common.module.system.UserPermissionDTO; import cn.javaquan.app.common.module.system.UserPermissionTreeDTO; import cn.javaquan.app.common.util.Validate; import cn.javaquan.common.base.constant.AppTypeEnum; import cn.javaquan.common.base.message.Result; import cn.javaquan.app.pm.bff.command.feign.ArticleSitemapFeign; import cn.javaquan.app.pm.bff.command.feign.PermissionFeign; import cn.javaquan.tools.sitemap.Sitemap; import cn.javaquan.tools.sitemap.SitemapUtil; import cn.javaquan.tools.sitemap.XmlUtil; import lombok.RequiredArgsConstructor; import org.dom4j.Document; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
9,027
package cn.javaquan.app.pm.bff.command.service; /** * @author wangquan */ @RequiredArgsConstructor @Service public class SitemapService { private final PermissionFeign permissionFeign; private final ArticleSitemapFeign articleSitemapFeign; private final static String ARTICLE_CONTENT_NAME = "article_content"; @Value("${quan.site.domain.url:}") private String siteDomainUrl; public Document refreshSitemap() { Sitemap sitemap = new Sitemap(); List<UserPermissionTreeDTO> filterDtos = new ArrayList<>(); // Open角色权限菜单路径 Result<List<UserPermissionTreeDTO>> permissionResult = permissionFeign.getUserPermission(AuthAssembler.INSTANCE.appType(AppTypeEnum.CLIENT_BFF.name())); List<Sitemap.Url> urls = SitemapAssembler.INSTANCE.toSitemapList(siteDomainUrl, permissionResult.getData(), filterDtos); // 文章路径
package cn.javaquan.app.pm.bff.command.service; /** * @author wangquan */ @RequiredArgsConstructor @Service public class SitemapService { private final PermissionFeign permissionFeign; private final ArticleSitemapFeign articleSitemapFeign; private final static String ARTICLE_CONTENT_NAME = "article_content"; @Value("${quan.site.domain.url:}") private String siteDomainUrl; public Document refreshSitemap() { Sitemap sitemap = new Sitemap(); List<UserPermissionTreeDTO> filterDtos = new ArrayList<>(); // Open角色权限菜单路径 Result<List<UserPermissionTreeDTO>> permissionResult = permissionFeign.getUserPermission(AuthAssembler.INSTANCE.appType(AppTypeEnum.CLIENT_BFF.name())); List<Sitemap.Url> urls = SitemapAssembler.INSTANCE.toSitemapList(siteDomainUrl, permissionResult.getData(), filterDtos); // 文章路径
Map<String, UserPermissionTreeDTO> dtoMap = filterDtos.stream().collect(Collectors.toMap(UserPermissionDTO::getName, (p1) -> p1));
3
2023-10-08 06:48:41+00:00
12k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java
[ { "identifier": "CommandManager", "path": "src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandManager.java", "snippet": "public interface CommandManager{\n /**\n * This is a interface to allow addons to register the subcommand into quickshop command manager.\n *\n * @param c...
import com.ghostchu.plugins.dodosrv.command.bukkit.CommandManager; import com.ghostchu.plugins.dodosrv.command.bukkit.SimpleCommandManager; import com.ghostchu.plugins.dodosrv.database.DatabaseManager; import com.ghostchu.plugins.dodosrv.dodo.DodoManager; import com.ghostchu.plugins.dodosrv.dodo.UserBindManager; import com.ghostchu.plugins.dodosrv.listener.bukkit.BukkitListener; import com.ghostchu.plugins.dodosrv.listener.dodo.DoDoListener; import com.ghostchu.plugins.dodosrv.text.TextManager; import com.ghostchu.plugins.dodosrv.util.JsonUtil; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.gson.JsonObject; import net.deechael.dodo.API; import net.deechael.dodo.api.Channel; import net.deechael.dodo.api.TextChannel; import net.deechael.dodo.content.Message; import net.deechael.dodo.content.TextMessage; import net.deechael.dodo.gate.Gateway; import net.deechael.dodo.impl.ChannelImpl; import net.deechael.dodo.impl.DodoBot; import net.deechael.dodo.network.Route; import net.deechael.dodo.types.MessageType; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.lang.reflect.Field; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit;
10,023
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot;
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot;
private DatabaseManager databaseManager;
2
2023-10-11 16:16:54+00:00
12k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/controller/MapServerTilesetsRestController.java
[ { "identifier": "MapServerDataCenter", "path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java", "snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n ...
import io.github.qmjy.mapbox.MapServerDataCenter; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.MbtilesOfMerge; import io.github.qmjy.mapbox.model.MbtilesOfMergeProgress; import io.github.qmjy.mapbox.model.MetaData; import io.github.qmjy.mapbox.service.AsyncService; import io.github.qmjy.mapbox.util.ResponseMapUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*;
7,837
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return ResponseEntity.ok().body(ResponseMapUtil.ok(wrapMap(maps))); } catch (EmptyResultDataAccessException e) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } } } if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_TPK)) {
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return ResponseEntity.ok().body(ResponseMapUtil.ok(wrapMap(maps))); } catch (EmptyResultDataAccessException e) { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponseMapUtil.notFound()); } } } if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_TPK)) {
MetaData tpkMetaData = mapServerDataCenter.getTpkMetaData(tileset);
4
2023-10-09 03:18:52+00:00
12k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/handlers/RenderGameOverlayHandler.java
[ { "identifier": "ZombiesUtilsConfig", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/config/ZombiesUtilsConfig.java", "snippet": "public class ZombiesUtilsConfig {\n public static Configuration config;\n private static Property slaToggle;\n private static Property slaShortener;...
import com.github.stachelbeere1248.zombiesutils.config.ZombiesUtilsConfig; import com.github.stachelbeere1248.zombiesutils.game.sla.SLA; import com.github.stachelbeere1248.zombiesutils.game.waves.Waves; import com.github.stachelbeere1248.zombiesutils.game.windows.Room; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.Scoreboard; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; import java.util.Objects;
9,311
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return; Timer.getInstance().ifPresent(timer -> { renderTime(timer.roundTime()); renderSpawnTime(
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return; Timer.getInstance().ifPresent(timer -> { renderTime(timer.roundTime()); renderSpawnTime(
Waves.get(
2
2023-10-11 01:30:28+00:00
12k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/system/menu/controller/MenuController.java
[ { "identifier": "UserConstants", "path": "src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public class UserConstants\n{\n /** 正常状态 */\n public static final String NORMAL = \"0\";\n\n /** 异常状态 */\n public static final String EXCEPTION = \"1\";\n\n /** 用户封禁状态 */\n ...
import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.utils.security.AuthorizationUtils; import com.ruoyi.framework.aspectj.lang.annotation.Log; import com.ruoyi.framework.aspectj.lang.enums.BusinessType; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.domain.Ztree; import com.ruoyi.project.system.menu.domain.Menu; import com.ruoyi.project.system.menu.service.IMenuService; import com.ruoyi.project.system.role.domain.Role;
8,905
package com.ruoyi.project.system.menu.controller; /** * 菜单信息 * * @author ruoyi */ @Controller @RequestMapping("/system/menu") public class MenuController extends BaseController { private String prefix = "system/menu"; @Autowired private IMenuService menuService; @RequiresPermissions("system:menu:view") @GetMapping() public String menu() { return prefix + "/menu"; } @RequiresPermissions("system:menu:list") @PostMapping("/list") @ResponseBody public List<Menu> list(Menu menu) { List<Menu> menuList = menuService.selectMenuList(menu); return menuList; } /** * 删除菜单 */ @Log(title = "菜单管理", businessType = BusinessType.DELETE) @RequiresPermissions("system:menu:remove") @GetMapping("/remove/{menuId}") @ResponseBody public AjaxResult remove(@PathVariable("menuId") Long menuId) { if (menuService.selectCountMenuByParentId(menuId) > 0) { return AjaxResult.warn("存在子菜单,不允许删除"); } if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) { return AjaxResult.warn("菜单已分配,不允许删除"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.deleteMenuById(menuId)); } /** * 新增 */ @GetMapping("/add/{parentId}") public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) { Menu menu = null; if (0L != parentId) { menu = menuService.selectMenuById(parentId); } else { menu = new Menu(); menu.setMenuId(0L); menu.setMenuName("主目录"); } mmap.put("menu", menu); return prefix + "/add"; } /** * 新增保存菜单 */ @Log(title = "菜单管理", businessType = BusinessType.INSERT) @RequiresPermissions("system:menu:add") @PostMapping("/add") @ResponseBody public AjaxResult addSave(@Validated Menu menu) { if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.insertMenu(menu)); } /** * 修改菜单 */ @RequiresPermissions("system:menu:edit") @GetMapping("/edit/{menuId}") public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap) { mmap.put("menu", menuService.selectMenuById(menuId)); return prefix + "/edit"; } /** * 修改保存菜单 */ @Log(title = "菜单管理", businessType = BusinessType.UPDATE) @RequiresPermissions("system:menu:edit") @PostMapping("/edit") @ResponseBody public AjaxResult editSave(@Validated Menu menu) { if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.updateMenu(menu)); } /** * 选择菜单图标 */ @GetMapping("/icon") public String icon() { return prefix + "/icon"; } /** * 校验菜单名称 */ @PostMapping("/checkMenuNameUnique") @ResponseBody public String checkMenuNameUnique(Menu menu) { return menuService.checkMenuNameUnique(menu); } /** * 加载角色菜单列表树 */ @GetMapping("/roleMenuTreeData") @ResponseBody
package com.ruoyi.project.system.menu.controller; /** * 菜单信息 * * @author ruoyi */ @Controller @RequestMapping("/system/menu") public class MenuController extends BaseController { private String prefix = "system/menu"; @Autowired private IMenuService menuService; @RequiresPermissions("system:menu:view") @GetMapping() public String menu() { return prefix + "/menu"; } @RequiresPermissions("system:menu:list") @PostMapping("/list") @ResponseBody public List<Menu> list(Menu menu) { List<Menu> menuList = menuService.selectMenuList(menu); return menuList; } /** * 删除菜单 */ @Log(title = "菜单管理", businessType = BusinessType.DELETE) @RequiresPermissions("system:menu:remove") @GetMapping("/remove/{menuId}") @ResponseBody public AjaxResult remove(@PathVariable("menuId") Long menuId) { if (menuService.selectCountMenuByParentId(menuId) > 0) { return AjaxResult.warn("存在子菜单,不允许删除"); } if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) { return AjaxResult.warn("菜单已分配,不允许删除"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.deleteMenuById(menuId)); } /** * 新增 */ @GetMapping("/add/{parentId}") public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) { Menu menu = null; if (0L != parentId) { menu = menuService.selectMenuById(parentId); } else { menu = new Menu(); menu.setMenuId(0L); menu.setMenuName("主目录"); } mmap.put("menu", menu); return prefix + "/add"; } /** * 新增保存菜单 */ @Log(title = "菜单管理", businessType = BusinessType.INSERT) @RequiresPermissions("system:menu:add") @PostMapping("/add") @ResponseBody public AjaxResult addSave(@Validated Menu menu) { if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.insertMenu(menu)); } /** * 修改菜单 */ @RequiresPermissions("system:menu:edit") @GetMapping("/edit/{menuId}") public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap) { mmap.put("menu", menuService.selectMenuById(menuId)); return prefix + "/edit"; } /** * 修改保存菜单 */ @Log(title = "菜单管理", businessType = BusinessType.UPDATE) @RequiresPermissions("system:menu:edit") @PostMapping("/edit") @ResponseBody public AjaxResult editSave(@Validated Menu menu) { if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } AuthorizationUtils.clearAllCachedAuthorizationInfo(); return toAjax(menuService.updateMenu(menu)); } /** * 选择菜单图标 */ @GetMapping("/icon") public String icon() { return prefix + "/icon"; } /** * 校验菜单名称 */ @PostMapping("/checkMenuNameUnique") @ResponseBody public String checkMenuNameUnique(Menu menu) { return menuService.checkMenuNameUnique(menu); } /** * 加载角色菜单列表树 */ @GetMapping("/roleMenuTreeData") @ResponseBody
public List<Ztree> roleMenuTreeData(Role role)
8
2023-10-14 02:27:47+00:00
12k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/config/Config.java
[ { "identifier": "SCMain", "path": "src/main/java/net/shadowclient/main/SCMain.java", "snippet": "public class SCMain {\n\n public static final String ClientModId = \"shadowclient\";\n public static final String ClientName = \"ShadowClient\";\n public static final String ClientVersion = \"0.2.0\...
import com.google.gson.*; import net.fabricmc.loader.api.FabricLoader; import net.shadowclient.main.SCMain; import net.shadowclient.main.annotations.DontSaveState; import net.shadowclient.main.annotations.OneClick; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleManager; import net.shadowclient.main.setting.Setting; import net.shadowclient.main.setting.settings.BooleanSetting; import net.shadowclient.main.setting.settings.EnumSetting; import net.shadowclient.main.setting.settings.NumberSetting; import net.shadowclient.main.setting.settings.StringSetting; import net.shadowclient.main.ui.clickgui.Frame; import net.shadowclient.main.util.FileUtils; import net.shadowclient.main.util.JavaUtils; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*;
10,167
json.add("settings", scsettings); json.add("modules", modulescontainer); json.add("ui", uisettings); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String out = gson.toJson(json); FileUtils.writeFile(getConfigFile(), out); } @SuppressWarnings("unchecked") public static void loadConfig() { String text; try { text = FileUtils.readFile(getConfigFile()); } catch (Exception ignored) { saveConfig(); return; } JsonObject json = (new Gson()).fromJson(text, JsonObject.class); JsonObject clientdata = json.getAsJsonObject("client"); JsonObject scsettings = json.getAsJsonObject("settings"); JsonObject uisettings = json.getAsJsonObject("ui"); String version = clientdata.get("version").getAsString(); if (!version.equals(SCMain.ClientVersion)) { SCMain.warn("Config version " + version + " does not match current version " + SCMain.ClientVersion); } json = json.getAsJsonObject("modules"); Map<String, JsonObject> modules = new HashMap<>(); JsonObject finalJson = json; json.keySet().forEach((name) -> modules.put(name, finalJson.get(name).getAsJsonObject())); if (scsettings != null) { scsettings.keySet().forEach((setting) -> { JsonPrimitive value = scsettings.getAsJsonPrimitive(setting); Setting settingobj = SCSettings.getSetting(setting); if (settingobj != null) { if (value.isBoolean()) { settingobj.setBooleanValue(value.getAsBoolean()); } if (value.isNumber()) { settingobj.setNumberValue(value.getAsNumber()); } if (value.isString()) { ((StringSetting) settingobj).setStringValue(value.getAsString()); } } }); } modules.forEach((name, object) -> { Module module = ModuleManager.getModule(name); JsonObject settings = object.get("settings").getAsJsonObject(); settings.keySet().forEach((setting) -> { JsonElement settingjson = settings.get(setting); if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isNumber()) { Number value = settingjson.getAsNumber(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { settingobj.shouldCallCallbacks(false); settingobj.setNumberValue(value); settingobj.shouldCallCallbacks(true); } }); } if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isBoolean()) { boolean value = settingjson.getAsBoolean(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { settingobj.shouldCallCallbacks(false); settingobj.setBooleanValue(value); settingobj.shouldCallCallbacks(true); } }); } if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isString()) { String value = settingjson.getAsString(); if (!setting.endsWith("_ENUMPATH")) { if (settings.keySet().contains(setting + "_ENUMPATH")) { String enumpath = settings.get(setting + "_ENUMPATH").getAsString().replace("class ", ""); String enumvalue = settings.get(setting).getAsString(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { try { Class<?> enumClass = Class.forName(enumpath); Enum<?> enumConstant = Enum.valueOf((Class<Enum>) enumClass, enumvalue); settingobj.shouldCallCallbacks(false); ((EnumSetting) settingobj).setEnumValue(enumConstant); settingobj.shouldCallCallbacks(true); } catch (Exception e) { throw new RuntimeException(e); } } }); } else { module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting) && settingobj instanceof StringSetting) { settingobj.shouldCallCallbacks(false); ((StringSetting) settingobj).setStringValue(value); settingobj.shouldCallCallbacks(true); } }); } } } }); try { if (!module.getClass().isAnnotationPresent(OneClick.class)) { SCMain.setModuleEnabled(name, object.get("enabled").getAsBoolean(), true, false); } if (module.moduleButton != null) { if (object.get("extended").getAsBoolean()) { module.moduleButton.extended = true; module.moduleButton.parent.updateButtons(); } } } catch (Exception e) {
package net.shadowclient.main.config; public class Config { public static File getConfigFile() { return FabricLoader.getInstance().getConfigDir().resolve(SCMain.ClientModId + ".config.json").toFile(); } public static void saveConfig() { SCMain.info("Saving config"); JsonObject json = new JsonObject(); JsonObject modulescontainer = new JsonObject(); JsonObject clientdata = new JsonObject(); JsonObject scsettings = new JsonObject(); JsonObject uisettings = new JsonObject(); Map<String, Module> modules = ModuleManager.getAllModules(); modules.forEach((name, module) -> { if (!module.getClass().isAnnotationPresent(DontSaveState.class)) { JsonObject modulejson = new JsonObject(); modulejson.addProperty("enabled", module.enabled); if (module.moduleButton != null) { modulejson.addProperty("extended", module.moduleButton.extended); } else { modulejson.addProperty("extended", false); } JsonObject settings = new JsonObject(); module.settings.forEach(setting -> { if (setting instanceof BooleanSetting) { settings.addProperty(setting.name, setting.booleanValue()); } if (setting instanceof NumberSetting) { settings.addProperty(setting.name, setting.numberValue()); } if (setting instanceof StringSetting) { settings.addProperty(setting.name, ((StringSetting) setting).stringValue()); } if (setting instanceof EnumSetting<?>) { Enum<?> value = ((EnumSetting<?>) setting).getEnumValue(); settings.addProperty(setting.name, value.name()); settings.addProperty(setting.name + "_ENUMPATH", value.getClass().toString()); } }); modulejson.add("settings", settings); modulescontainer.add(name, modulejson); } }); clientdata.addProperty("version", SCMain.ClientVersion); Arrays.stream(SCSettings.class.getDeclaredFields()).forEach((field) -> { try { Setting setting = (Setting) field.get(null); if (setting instanceof BooleanSetting) { scsettings.addProperty(field.getName(), setting.booleanValue()); } if (setting instanceof NumberSetting) { scsettings.addProperty(field.getName(), setting.numberValue()); } if (setting instanceof StringSetting) { scsettings.addProperty(field.getName(), ((StringSetting) setting).stringValue()); } } catch (Exception ignored) {} }); JsonObject uiframes = new JsonObject(); JsonObject mainuiframe = new JsonObject(); JsonObject settingsframe = new JsonObject(); List<Frame> mainuiframes = new ArrayList<>(SCMain.clickGui.frames); mainuiframes.add(SCMain.clickGui.searchFrame); mainuiframes.forEach((frame) -> { JsonObject frameobj = new JsonObject(); frameobj.addProperty("offset_x", frame.x); frameobj.addProperty("offset_y", frame.y); frameobj.addProperty("extended", frame.extended); mainuiframe.add(frame.name, frameobj); }); List<Frame> settingsframes = new ArrayList<>(SCMain.settingsGui.frames); settingsframes.add(SCMain.settingsGui.searchFrame); settingsframes.forEach((frame) -> { JsonObject frameobj = new JsonObject(); frameobj.addProperty("offset_x", frame.x); frameobj.addProperty("offset_y", frame.y); frameobj.addProperty("extended", frame.extended); settingsframe.add(frame.name, frameobj); }); uiframes.add("main", mainuiframe); uiframes.add("settings", settingsframe); uisettings.add("frames", uiframes); json.add("client", clientdata); json.add("settings", scsettings); json.add("modules", modulescontainer); json.add("ui", uisettings); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String out = gson.toJson(json); FileUtils.writeFile(getConfigFile(), out); } @SuppressWarnings("unchecked") public static void loadConfig() { String text; try { text = FileUtils.readFile(getConfigFile()); } catch (Exception ignored) { saveConfig(); return; } JsonObject json = (new Gson()).fromJson(text, JsonObject.class); JsonObject clientdata = json.getAsJsonObject("client"); JsonObject scsettings = json.getAsJsonObject("settings"); JsonObject uisettings = json.getAsJsonObject("ui"); String version = clientdata.get("version").getAsString(); if (!version.equals(SCMain.ClientVersion)) { SCMain.warn("Config version " + version + " does not match current version " + SCMain.ClientVersion); } json = json.getAsJsonObject("modules"); Map<String, JsonObject> modules = new HashMap<>(); JsonObject finalJson = json; json.keySet().forEach((name) -> modules.put(name, finalJson.get(name).getAsJsonObject())); if (scsettings != null) { scsettings.keySet().forEach((setting) -> { JsonPrimitive value = scsettings.getAsJsonPrimitive(setting); Setting settingobj = SCSettings.getSetting(setting); if (settingobj != null) { if (value.isBoolean()) { settingobj.setBooleanValue(value.getAsBoolean()); } if (value.isNumber()) { settingobj.setNumberValue(value.getAsNumber()); } if (value.isString()) { ((StringSetting) settingobj).setStringValue(value.getAsString()); } } }); } modules.forEach((name, object) -> { Module module = ModuleManager.getModule(name); JsonObject settings = object.get("settings").getAsJsonObject(); settings.keySet().forEach((setting) -> { JsonElement settingjson = settings.get(setting); if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isNumber()) { Number value = settingjson.getAsNumber(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { settingobj.shouldCallCallbacks(false); settingobj.setNumberValue(value); settingobj.shouldCallCallbacks(true); } }); } if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isBoolean()) { boolean value = settingjson.getAsBoolean(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { settingobj.shouldCallCallbacks(false); settingobj.setBooleanValue(value); settingobj.shouldCallCallbacks(true); } }); } if (settingjson.isJsonPrimitive() && settingjson.getAsJsonPrimitive().isString()) { String value = settingjson.getAsString(); if (!setting.endsWith("_ENUMPATH")) { if (settings.keySet().contains(setting + "_ENUMPATH")) { String enumpath = settings.get(setting + "_ENUMPATH").getAsString().replace("class ", ""); String enumvalue = settings.get(setting).getAsString(); module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting)) { try { Class<?> enumClass = Class.forName(enumpath); Enum<?> enumConstant = Enum.valueOf((Class<Enum>) enumClass, enumvalue); settingobj.shouldCallCallbacks(false); ((EnumSetting) settingobj).setEnumValue(enumConstant); settingobj.shouldCallCallbacks(true); } catch (Exception e) { throw new RuntimeException(e); } } }); } else { module.settings.forEach((settingobj) -> { if (settingobj.name.equals(setting) && settingobj instanceof StringSetting) { settingobj.shouldCallCallbacks(false); ((StringSetting) settingobj).setStringValue(value); settingobj.shouldCallCallbacks(true); } }); } } } }); try { if (!module.getClass().isAnnotationPresent(OneClick.class)) { SCMain.setModuleEnabled(name, object.get("enabled").getAsBoolean(), true, false); } if (module.moduleButton != null) { if (object.get("extended").getAsBoolean()) { module.moduleButton.extended = true; module.moduleButton.parent.updateButtons(); } } } catch (Exception e) {
SCMain.error(JavaUtils.stackTraceFromThrowable(e));
10
2023-10-07 06:55:12+00:00
12k
Spider-Admin/Frost
src/main/java/frost/fcp/fcp07/FcpRequest.java
[ { "identifier": "DataNotFoundException", "path": "src/main/java/frost/fcp/DataNotFoundException.java", "snippet": "@SuppressWarnings(\"serial\")\r\npublic class DataNotFoundException extends FcpToolsException {\r\n \r\n public DataNotFoundException() {\r\n super(\"Data Not Found.\");\r\n ...
import java.io.File; import java.io.IOException; import java.net.ConnectException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.fcp.DataNotFoundException; import frost.fcp.FcpResultGet; import frost.fcp.FcpToolsException; import frost.fileTransfer.download.FrostDownloadItem; import frost.util.FileAccess;
9,720
/* FcpRequest.java / Frost Copyright (C) 2003 Jan-Thomas Czornack <jantho@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fcp.fcp07; /** * Requests a key from freenet */ // while requesting / inserting, show chunks left to try (incl. trying chunks) -> Warte (9) / 18% (9) public class FcpRequest { private static final Logger logger = LoggerFactory.getLogger(FcpRequest.class); final static boolean DEBUG = true; /** * getFile retrieves a file from Freenet. It does detect if this file is a redirect, a splitfile or * just a simple file. It checks the size for the file and returns false if sizes do not match. * Size is ignored if it is NULL * * @param key The key to retrieve. All to Freenet known key formats are allowed (passed to node via FCP). * @param size Size of the file in bytes. Is ignored if not an integer value or -1 (splitfiles do not need this setting). * @param target Target path * @param htl request htl * @param doRedirect If true, getFile redirects if possible and downloads the file it was redirected to. * @return True if download was successful, else false. */
/* FcpRequest.java / Frost Copyright (C) 2003 Jan-Thomas Czornack <jantho@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fcp.fcp07; /** * Requests a key from freenet */ // while requesting / inserting, show chunks left to try (incl. trying chunks) -> Warte (9) / 18% (9) public class FcpRequest { private static final Logger logger = LoggerFactory.getLogger(FcpRequest.class); final static boolean DEBUG = true; /** * getFile retrieves a file from Freenet. It does detect if this file is a redirect, a splitfile or * just a simple file. It checks the size for the file and returns false if sizes do not match. * Size is ignored if it is NULL * * @param key The key to retrieve. All to Freenet known key formats are allowed (passed to node via FCP). * @param size Size of the file in bytes. Is ignored if not an integer value or -1 (splitfiles do not need this setting). * @param target Target path * @param htl request htl * @param doRedirect If true, getFile redirects if possible and downloads the file it was redirected to. * @return True if download was successful, else false. */
public static FcpResultGet getFile(
1
2023-10-07 22:25:20+00:00
12k
Milosz08/screen-sharing-system
client/src/main/java/pl/polsl/screensharing/client/view/ClientWindow.java
[ { "identifier": "BottomInfobarController", "path": "client/src/main/java/pl/polsl/screensharing/client/controller/BottomInfobarController.java", "snippet": "public class BottomInfobarController extends AbstractBottomInfobarController {\n private final ClientWindow clientWindow;\n private final Tim...
import lombok.Getter; import lombok.Setter; import pl.polsl.screensharing.client.controller.BottomInfobarController; import pl.polsl.screensharing.client.net.ClientDatagramSocket; import pl.polsl.screensharing.client.net.ClientTcpSocket; import pl.polsl.screensharing.client.state.ClientState; import pl.polsl.screensharing.client.view.dialog.*; import pl.polsl.screensharing.client.view.fragment.BottomInfobar; import pl.polsl.screensharing.client.view.fragment.TopMenuBar; import pl.polsl.screensharing.client.view.fragment.TopToolbar; import pl.polsl.screensharing.client.view.fragment.VideoCanvas; import pl.polsl.screensharing.client.view.tabbed.TabbedPaneWindow; import pl.polsl.screensharing.lib.AppType; import pl.polsl.screensharing.lib.gui.AbstractRootFrame; import javax.swing.*; import java.awt.*;
7,892
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view; @Getter public class ClientWindow extends AbstractRootFrame { private final ClientState clientState; private final TopMenuBar topMenuBar;
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.client.view; @Getter public class ClientWindow extends AbstractRootFrame { private final ClientState clientState; private final TopMenuBar topMenuBar;
private final TopToolbar topToolbar;
6
2023-10-11 16:12:02+00:00
12k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/integrations/llms/aigateway/AIGatewayServiceProvider.java
[ { "identifier": "DevPilotVersion", "path": "src/main/java/com/zhongan/devpilot/DevPilotVersion.java", "snippet": "public class DevPilotVersion {\n public static String getDevPilotVersion() {\n var pluginId = PluginId.getId(\"com.zhongan.devPilot\");\n var plugin = PluginManagerCore.getP...
import com.fasterxml.jackson.databind.ObjectMapper; import com.intellij.openapi.components.Service; import com.intellij.openapi.project.Project; import com.zhongan.devpilot.DevPilotVersion; import com.zhongan.devpilot.enums.ModelTypeEnum; import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService; import com.zhongan.devpilot.integrations.llms.LlmProvider; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionResponse; import com.zhongan.devpilot.integrations.llms.entity.DevPilotFailedResponse; import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage; import com.zhongan.devpilot.integrations.llms.entity.DevPilotSuccessResponse; import com.zhongan.devpilot.settings.state.AIGatewaySettingsState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.OkhttpUtils; import com.zhongan.devpilot.webview.model.MessageModel; import java.io.IOException; import java.util.Objects; import java.util.function.Consumer; import org.apache.commons.lang3.StringUtils; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.sse.EventSource;
7,616
package com.zhongan.devpilot.integrations.llms.aigateway; @Service(Service.Level.PROJECT) public final class AIGatewayServiceProvider implements LlmProvider { private final ObjectMapper objectMapper = new ObjectMapper(); private EventSource es;
package com.zhongan.devpilot.integrations.llms.aigateway; @Service(Service.Level.PROJECT) public final class AIGatewayServiceProvider implements LlmProvider { private final ObjectMapper objectMapper = new ObjectMapper(); private EventSource es;
private DevPilotChatToolWindowService toolWindowService;
2
2023-11-29 06:37:51+00:00
12k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/tileprocess/tile/PointCloudTiler.java
[ { "identifier": "GaiaBoundingBox", "path": "core/src/main/java/com/gaia3d/basic/geometry/GaiaBoundingBox.java", "snippet": "@Slf4j\n@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class GaiaBoundingBox {\n private double minX, minY, minZ;\n private double maxX, maxY, maxZ;\n p...
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.gaia3d.basic.geometry.GaiaBoundingBox; import com.gaia3d.basic.pointcloud.GaiaPointCloud; import com.gaia3d.process.ProcessOptions; import com.gaia3d.process.TilerOptions; import com.gaia3d.process.tileprocess.Tiler; import com.gaia3d.process.tileprocess.tile.tileset.Tileset; import com.gaia3d.process.tileprocess.tile.tileset.asset.*; import com.gaia3d.process.tileprocess.tile.tileset.node.BoundingVolume; import com.gaia3d.process.tileprocess.tile.tileset.node.Content; import com.gaia3d.process.tileprocess.tile.tileset.node.Node; import com.gaia3d.util.GlobeUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.joml.Matrix4d; import org.joml.Vector3d; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List;
8,616
package com.gaia3d.process.tileprocess.tile; @Slf4j public class PointCloudTiler implements Tiler { private static final int DEFUALT_MAX_COUNT = 20000; private final CommandLine command; private final TilerOptions options; public PointCloudTiler(TilerOptions tilerOptions, CommandLine command) { this.options = tilerOptions; this.command = command; } @Override public Tileset run(List<TileInfo> tileInfos) { double geometricError = calcGeometricError(tileInfos); GaiaBoundingBox globalBoundingBox = calcBoundingBox(tileInfos); double minX = globalBoundingBox.getMinX(); double maxX = globalBoundingBox.getMaxX(); double minY = globalBoundingBox.getMinY(); double maxY = globalBoundingBox.getMaxY(); double minZ = globalBoundingBox.getMinZ(); double maxZ = globalBoundingBox.getMaxZ(); double x = (maxX - minX); double y = (maxY - minY); double maxLength = Math.max(x, y); double xoffset = maxLength - x; double yoffset = maxLength - y; maxX += xoffset; maxY += yoffset; GaiaBoundingBox cubeBoundingBox = new GaiaBoundingBox(); cubeBoundingBox.addPoint(new Vector3d(minX, minY, minZ)); cubeBoundingBox.addPoint(new Vector3d(maxX, maxY, maxZ)); globalBoundingBox = cubeBoundingBox; Matrix4d transformMatrix = getTransformMatrix(globalBoundingBox); rotateX90(transformMatrix);
package com.gaia3d.process.tileprocess.tile; @Slf4j public class PointCloudTiler implements Tiler { private static final int DEFUALT_MAX_COUNT = 20000; private final CommandLine command; private final TilerOptions options; public PointCloudTiler(TilerOptions tilerOptions, CommandLine command) { this.options = tilerOptions; this.command = command; } @Override public Tileset run(List<TileInfo> tileInfos) { double geometricError = calcGeometricError(tileInfos); GaiaBoundingBox globalBoundingBox = calcBoundingBox(tileInfos); double minX = globalBoundingBox.getMinX(); double maxX = globalBoundingBox.getMaxX(); double minY = globalBoundingBox.getMinY(); double maxY = globalBoundingBox.getMaxY(); double minZ = globalBoundingBox.getMinZ(); double maxZ = globalBoundingBox.getMaxZ(); double x = (maxX - minX); double y = (maxY - minY); double maxLength = Math.max(x, y); double xoffset = maxLength - x; double yoffset = maxLength - y; maxX += xoffset; maxY += yoffset; GaiaBoundingBox cubeBoundingBox = new GaiaBoundingBox(); cubeBoundingBox.addPoint(new Vector3d(minX, minY, minZ)); cubeBoundingBox.addPoint(new Vector3d(maxX, maxY, maxZ)); globalBoundingBox = cubeBoundingBox; Matrix4d transformMatrix = getTransformMatrix(globalBoundingBox); rotateX90(transformMatrix);
Node root = createRoot();
8
2023-11-30 01:59:44+00:00
12k
xuemingqi/x-cloud
x-config/src/main/java/com/x/config/aspect/AccessLimitAspect.java
[ { "identifier": "OperationEnum", "path": "x-common/src/main/java/com/x/common/enums/OperationEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum OperationEnum {\n\n /**\n * 读\n */\n READ,\n\n /**\n * 写\n */\n WRITE\n}" }, { "identifier": "ResponseCodeEnu...
import com.x.common.enums.OperationEnum; import com.x.common.enums.ResponseCodeEnum; import com.x.common.response.ResultUtil; import com.x.common.utils.ServletUtil; import com.x.config.annotation.AccessLimit; import com.x.config.redis.util.RedisUtil; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.redisson.api.RateIntervalUnit; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.lang.reflect.Method;
8,281
package com.x.config.aspect; @Aspect @Component @ConditionalOnBean(RedisUtil.class) public class AccessLimitAspect { @Resource private RedisUtil redisUtil; @Pointcut("@annotation(com.x.config.annotation.AccessLimit)") private void accessLimitPointcut() { } @Around(value = "accessLimitPointcut() && @annotation(accessLimit)") public Object round(ProceedingJoinPoint joinPoint, AccessLimit accessLimit) throws Throwable { //限流规则 int counts = accessLimit.counts();
package com.x.config.aspect; @Aspect @Component @ConditionalOnBean(RedisUtil.class) public class AccessLimitAspect { @Resource private RedisUtil redisUtil; @Pointcut("@annotation(com.x.config.annotation.AccessLimit)") private void accessLimitPointcut() { } @Around(value = "accessLimitPointcut() && @annotation(accessLimit)") public Object round(ProceedingJoinPoint joinPoint, AccessLimit accessLimit) throws Throwable { //限流规则 int counts = accessLimit.counts();
OperationEnum operationEnum = accessLimit.types();
0
2023-11-27 08:23:38+00:00
12k
okx/OKBund
aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/simulation/v6/EntryPointSimulationsV6.java
[ { "identifier": "ChainDebugUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/ChainDebugUtil.java", "snippet": "public class ChainDebugUtil {\n\n @SneakyThrows\n public static CallTraceTransaction callTraceTransaction(String txHash, boolean onlyTopCall, IChain chain) {\n ...
import com.alibaba.fastjson2.JSON; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.okcoin.dapp.bundler.infra.chain.ChainDebugUtil; import com.okcoin.dapp.bundler.infra.chain.ChainErrorUtil; import com.okcoin.dapp.bundler.infra.chain.IChain; import com.okcoin.dapp.bundler.infra.chain.TransactionUtil; import com.okcoin.dapp.bundler.infra.chain.constant.Web3Constant; import com.okcoin.dapp.bundler.infra.chain.error.ChainErrorMsg; import com.okcoin.dapp.bundler.infra.chain.error.UnKnowError; import com.okcoin.dapp.bundler.infra.chain.web3j.req.OverrideAccount; import com.okcoin.dapp.bundler.infra.chain.web3j.req.StateOverride; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.config.ValidationConfig; import com.okcoin.dapp.bundler.pool.constant.OpCodeConstant; import com.okcoin.dapp.bundler.pool.domain.UserOperationDO; import com.okcoin.dapp.bundler.pool.domain.debug.*; import com.okcoin.dapp.bundler.pool.domain.error.*; import com.okcoin.dapp.bundler.pool.exception.AAException; import com.okcoin.dapp.bundler.pool.exception.AAExceptionData; import com.okcoin.dapp.bundler.pool.exception.AAExceptionEnum; import com.okcoin.dapp.bundler.pool.exception.UnexpectedException; import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations; import com.okcoin.dapp.bundler.pool.util.ValidateTimeUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.FunctionReturnDecoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.*; import org.web3j.abi.datatypes.generated.Bytes32; import org.web3j.protocol.core.methods.response.EthCall; import org.web3j.utils.Numeric; import org.web3j.utils.Strings; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.okcoin.dapp.bundler.pool.constant.Eip4377CommonConstant.*;
7,783
package com.okcoin.dapp.bundler.pool.simulation.v6; @Service(EntryPointSimulationsV6.VERSION) @Slf4j public class EntryPointSimulationsV6 implements IEntryPointSimulations {
package com.okcoin.dapp.bundler.pool.simulation.v6; @Service(EntryPointSimulationsV6.VERSION) @Slf4j public class EntryPointSimulationsV6 implements IEntryPointSimulations {
private static final String MAX_BALANCE = Web3Constant.HEX_PREFIX + "7" + Strings.repeat('f', 63);
4
2023-11-27 10:54:49+00:00
12k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/PlayerConfig.java
[ { "identifier": "IRConnectionManager", "path": "core/src/bms/player/beatoraja/ir/IRConnectionManager.java", "snippet": "public class IRConnectionManager {\n\t\n\t/**\n\t * 検出されたIRConnection\n\t */\n\tprivate static Class<IRConnection>[] irconnections;\n\n\n\t/**\n\t * 利用可能な全てのIRConnectionの名称を返す\n\t * \n...
import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.logging.Logger; import bms.player.beatoraja.ir.IRConnectionManager; import bms.player.beatoraja.pattern.*; import bms.player.beatoraja.play.GrooveGauge; import bms.player.beatoraja.select.BarSorter; import bms.player.beatoraja.skin.SkinType; import bms.model.Mode; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonWriter; import com.badlogic.gdx.utils.SerializationException;
8,525
public boolean isShowhiddennote() { return showhiddennote; } public void setShowhiddennote(boolean showhiddennote) { this.showhiddennote = showhiddennote; } public boolean isShowpastnote() { return showpastnote; } public void setShowpastnote(boolean showpastnote) { this.showpastnote = showpastnote; } public String getTwitterConsumerKey() { return twitterConsumerKey; } public void setTwitterConsumerKey(String twitterConsumerKey) { this.twitterConsumerKey = twitterConsumerKey; } public String getTwitterConsumerSecret() { return twitterConsumerSecret; } public void setTwitterConsumerSecret(String twitterConsumerSecret) { this.twitterConsumerSecret = twitterConsumerSecret; } public String getTwitterAccessToken() { return twitterAccessToken; } public void setTwitterAccessToken(String twitterAccessToken) { this.twitterAccessToken = twitterAccessToken; } public String getTwitterAccessTokenSecret() { return twitterAccessTokenSecret; } public void setTwitterAccessTokenSecret(String twitterAccessTokenSecret) { this.twitterAccessTokenSecret = twitterAccessTokenSecret; } // --Stream public boolean getRequestEnable() { return enableRequest; } public boolean getRequestNotify() { return notifyRequest; } public void setRequestEnable(boolean requestEnable) { this.enableRequest = requestEnable; } public void setRequestNotify(boolean notifyEnable) { this.notifyRequest = notifyEnable; } public int getMaxRequestCount() { return maxRequestCount; } public void setMaxRequestCount(int maxRequestCount) { this.maxRequestCount = maxRequestCount; } public void validate() { if(skin == null) { skin = new SkinConfig[SkinType.getMaxSkinTypeID() + 1]; } if(skinHistory == null) { skinHistory = new SkinConfig[0]; } if(skin.length != SkinType.getMaxSkinTypeID() + 1) { skin = Arrays.copyOf(skin, SkinType.getMaxSkinTypeID() + 1); } for(int i = 0;i < skin.length;i++) { if(skin[i] == null) { skin[i] = SkinConfig.getDefault(i); } skin[i].validate(); } if(mode5 == null) { mode5 = new PlayModeConfig(Mode.BEAT_5K); } if(mode7 == null) { mode7 = new PlayModeConfig(Mode.BEAT_7K); } if(mode14 == null) { mode14 = new PlayModeConfig(Mode.BEAT_14K); } if(mode10 == null) { mode10 = new PlayModeConfig(Mode.BEAT_10K); } if(mode9 == null) { mode9 = new PlayModeConfig(Mode.POPN_9K); } if(mode24 == null) { mode24 = new PlayModeConfig(Mode.KEYBOARD_24K); } if(mode24double == null) { mode24double = new PlayModeConfig(Mode.KEYBOARD_24K_DOUBLE); } mode5.validate(7); mode7.validate(9); mode10.validate(14); mode14.validate(18); mode9.validate(9); mode24.validate(26); mode24double.validate(52);
package bms.player.beatoraja; /** * プレイヤー毎の設定項目 * * @author exch */ public class PlayerConfig { static final Path configpath_old = Paths.get("config.json"); static final Path configpath = Paths.get("config_player.json"); private String id; /** * プレイヤーネーム */ private String name = "NO NAME"; /** * ゲージの種類 */ private int gauge = 0; /** * 譜面オプション */ private int random; /** * 譜面オプション(2P) */ private int random2; /** * DP用オプション */ private int doubleoption; /** * スコアターゲット */ private String targetid = "MAX"; private String[] targetlist = new String[] {"RATE_A-","RATE_A", "RATE_A+","RATE_AA-","RATE_AA", "RATE_AA+", "RATE_AAA-", "RATE_AAA", "RATE_AAA+", "MAX" ,"RANK_NEXT", "IR_NEXT_1", "IR_NEXT_2", "IR_NEXT_3", "IR_NEXT_4", "IR_NEXT_5", "IR_NEXT_10" , "IR_RANK_1", "IR_RANK_5", "IR_RANK_10", "IR_RANK_20", "IR_RANK_30", "IR_RANK_40", "IR_RANK_50" , "IR_RANKRATE_5", "IR_RANKRATE_10", "IR_RANKRATE_15", "IR_RANKRATE_20", "IR_RANKRATE_25", "IR_RANKRATE_30", "IR_RANKRATE_35", "IR_RANKRATE_40", "IR_RANKRATE_45","IR_RANKRATE_50" ,"RIVAL_RANK_1","RIVAL_RANK_2","RIVAL_RANK_3","RIVAL_NEXT_1","RIVAL_NEXT_2","RIVAL_NEXT_3"}; /** * 判定タイミング */ private int judgetiming = 0; public static final int JUDGETIMING_MAX = 500; public static final int JUDGETIMING_MIN = -500; /** * ディスプレイ表示タイミング自動調整 */ private boolean notesDisplayTimingAutoAdjust = false; /** * 選曲時のモードフィルター */ private Mode mode = null; /** * 指定がない場合のミスレイヤー表示時間(ms) */ private int misslayerDuration = 500; /** * LNモード */ private int lnmode = 0; /** * スクロール追加/削除モード */ private int scrollMode = 0; private int scrollSection = 4; private double scrollRate = 0.5; /** * ロングノート追加/削除モード */ private int longnoteMode = 0; private double longnoteRate = 1.0; /** * アシストオプション:カスタムジャッジ */ private boolean customJudge = false; private int keyJudgeWindowRatePerfectGreat = 400; private int keyJudgeWindowRateGreat = 400; private int keyJudgeWindowRateGood = 100; private int scratchJudgeWindowRatePerfectGreat = 400; private int scratchJudgeWindowRateGreat = 400; private int scratchJudgeWindowRateGood = 100; /** * 地雷モード */ private int mineMode = 0; /** * アシストオプション:BPMガイド */ private boolean bpmguide = false; private int extranoteType = 0; private int extranoteDepth = 0; private boolean extranoteScratch = false; private boolean showjudgearea = false; private boolean markprocessednote = false; /** * H-RANDOM連打しきい値BPM */ private int hranThresholdBPM = 120; /** * プレイ中のゲージ切替 */ private int gaugeAutoShift = GAUGEAUTOSHIFT_NONE; /** * GASで遷移可能なゲージの下限 ASSIST EASY, EASY, NORMALから選択 */ private int bottomShiftableGauge = GrooveGauge.ASSISTEASY; public static final int GAUGEAUTOSHIFT_NONE = 0; public static final int GAUGEAUTOSHIFT_CONTINUE = 1; public static final int GAUGEAUTOSHIFT_SURVIVAL_TO_GROOVE = 2; public static final int GAUGEAUTOSHIFT_BESTCLEAR = 3; public static final int GAUGEAUTOSHIFT_SELECT_TO_UNDER = 4; private int autosavereplay[]; /** * 7to9 スクラッチ鍵盤位置関係 0:OFF 1:SC1KEY2~8 2:SC1KEY3~9 3:SC2KEY3~9 4:SC8KEY1~7 5:SC9KEY1~7 6:SC9KEY2~8 */ private int sevenToNinePattern = 0; /** * 7to9 スクラッチ処理タイプ 0:そのまま 1:連打回避 2:交互 */ private int sevenToNineType = 0; /** * START+SELECTを押すと終了するまでの時間 */ private int exitPressDuration = 1000; /** * Guide SE */ private boolean isGuideSE = false; /** * Window Hold */ private boolean isWindowHold = false; /** * Enable folder random select bar */ private boolean isRandomSelect = false; private SkinConfig[] skin = new SkinConfig[SkinType.getMaxSkinTypeID() + 1]; private SkinConfig[] skinHistory; private PlayModeConfig mode5 = new PlayModeConfig(Mode.BEAT_5K); private PlayModeConfig mode7 = new PlayModeConfig(Mode.BEAT_7K); private PlayModeConfig mode10 = new PlayModeConfig(Mode.BEAT_10K); private PlayModeConfig mode14 = new PlayModeConfig(Mode.BEAT_14K); private PlayModeConfig mode9 = new PlayModeConfig(Mode.POPN_9K); private PlayModeConfig mode24 = new PlayModeConfig(Mode.KEYBOARD_24K); private PlayModeConfig mode24double = new PlayModeConfig(Mode.KEYBOARD_24K_DOUBLE); /** * HIDDENノートを表示するかどうか */ private boolean showhiddennote = false; /** * 通過ノートを表示するかどうか */ private boolean showpastnote = false; /** * チャートプレビューを使用するかどうか */ private boolean chartPreview = false; /** * 選択中の選曲時ソート */ private int sort; /** * 選曲時でのキー入力方式 */ private int musicselectinput = 0; private IRConfig[] irconfig; private String twitterConsumerKey; private String twitterConsumerSecret; private String twitterAccessToken; private String twitterAccessTokenSecret; // -- Stream private boolean enableRequest = false; private boolean notifyRequest = false; private int maxRequestCount = 30; public PlayerConfig() { validate(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGauge() { return gauge; } public void setGauge(int gauge) { this.gauge = gauge; } public int getRandom() { return random; } public void setRandom(int random) { this.random = random; } public int getJudgetiming() { return judgetiming; } public void setJudgetiming(int judgetiming) { this.judgetiming = judgetiming; } public boolean isNotesDisplayTimingAutoAdjust() { return notesDisplayTimingAutoAdjust; } public void setNotesDisplayTimingAutoAdjust(boolean notesDisplayTimingAutoAdjust) { this.notesDisplayTimingAutoAdjust = notesDisplayTimingAutoAdjust; } public boolean isBpmguide() { return bpmguide; } public void setBpmguide(boolean bpmguide) { this.bpmguide = bpmguide; } public int getGaugeAutoShift() { return gaugeAutoShift; } public void setGaugeAutoShift(int gaugeAutoShift) { this.gaugeAutoShift = gaugeAutoShift; } public int getBottomShiftableGauge() { return bottomShiftableGauge; } public void setBottomShiftableGauge(int bottomShiftableGauge) { this.bottomShiftableGauge = bottomShiftableGauge; } public int getLnmode() { return lnmode; } public void setLnmode(int lnmode) { this.lnmode = lnmode; } public int getRandom2() { return random2; } public void setRandom2(int random2) { this.random2 = random2; } public int getDoubleoption() { return doubleoption; } public void setDoubleoption(int doubleoption) { this.doubleoption = doubleoption; } public int getExtranoteDepth() { return extranoteDepth; } public void setExtranoteDepth(int extranoteDepth) { this.extranoteDepth = extranoteDepth; } public int getExtranoteType() { return extranoteType; } public void setExtranoteType(int extranoteType) { this.extranoteType = extranoteType; } public boolean isExtranoteScratch() { return extranoteScratch; } public void setExtranoteScratch(boolean extranoteScratch) { this.extranoteScratch = extranoteScratch; } public boolean isShowjudgearea() { return showjudgearea; } public void setShowjudgearea(boolean showjudgearea) { this.showjudgearea = showjudgearea; } public boolean isMarkprocessednote() { return markprocessednote; } public void setMarkprocessednote(boolean markprocessednote) { this.markprocessednote = markprocessednote; } public PlayModeConfig getPlayConfig(Mode modeId) { switch (modeId != null ? modeId : Mode.BEAT_7K) { case BEAT_5K: return getMode5(); case BEAT_7K: return getMode7(); case BEAT_10K: return getMode10(); case BEAT_14K: return getMode14(); case POPN_9K: return getMode9(); case KEYBOARD_24K: return getMode24(); case KEYBOARD_24K_DOUBLE: return getMode24double(); default: return getMode7(); } } public PlayModeConfig getPlayConfig(int modeId) { switch (modeId) { case 7: return getMode7(); case 5: return getMode5(); case 14: return getMode14(); case 10: return getMode10(); case 9: return getMode9(); case 25: return getMode24(); case 50: return getMode24double(); default: return getMode7(); } } public PlayModeConfig getMode5() { return mode5; } public void setMode5(PlayModeConfig mode5) { this.mode5 = mode5; } public PlayModeConfig getMode7() { return mode7; } public void setMode7(PlayModeConfig mode7) { this.mode7 = mode7; } public PlayModeConfig getMode10() { if(mode10 == null || mode10.getController().length < 2) { mode10 = new PlayModeConfig(Mode.BEAT_10K); Logger.getGlobal().warning("mode10のPlayConfigを再構成"); } return mode10; } public void setMode10(PlayModeConfig mode10) { this.mode10 = mode10; } public PlayModeConfig getMode14() { if(mode14 == null || mode14.getController().length < 2) { mode14 = new PlayModeConfig(Mode.BEAT_14K); Logger.getGlobal().warning("mode14のPlayConfigを再構成"); } return mode14; } public void setMode14(PlayModeConfig mode14) { this.mode14 = mode14; } public PlayModeConfig getMode9() { return mode9; } public void setMode9(PlayModeConfig mode9) { this.mode9 = mode9; } public PlayModeConfig getMode24() { return mode24; } public void setMode24(PlayModeConfig mode24) { this.mode24 = mode24; } public PlayModeConfig getMode24double() { if(mode24double == null || mode24double.getController().length < 2) { mode24double = new PlayModeConfig(Mode.KEYBOARD_24K_DOUBLE); Logger.getGlobal().warning("mode24doubleのPlayConfigを再構成"); } return mode24double; } public void setMode24double(PlayModeConfig mode24double) { this.mode24double = mode24double; } public void setMode(Mode m) { this.mode = m; } public Mode getMode() { return mode; } public int getSort() { return this.sort ; } public void setSort(int sort) { this.sort = sort; } public int getMusicselectinput() { return musicselectinput; } public void setMusicselectinput(int musicselectinput) { this.musicselectinput = musicselectinput; } public SkinConfig[] getSkin() { if(skin.length <= SkinType.getMaxSkinTypeID()) { skin = Arrays.copyOf(skin, SkinType.getMaxSkinTypeID() + 1); Logger.getGlobal().warning("skinを再構成"); } return skin; } public void setSkin(SkinConfig[] skin) { this.skin = skin; } public SkinConfig[] getSkinHistory() { return skinHistory; } public void setSkinHistory(SkinConfig[] skinHistory) { this.skinHistory = skinHistory; } public IRConfig[] getIrconfig() { return irconfig; } public void setIrconfig(IRConfig[] irconfig) { this.irconfig = irconfig; } public String getTargetid() { return targetid; } public void setTargetid(String targetid) { this.targetid = targetid; } public String[] getTargetlist() { return targetlist; } public void setTargetlist(String[] targetlist) { this.targetlist = targetlist; } public int getMisslayerDuration() { if(misslayerDuration < 0) { misslayerDuration = 0; } return misslayerDuration; } public void setMisslayerDuration(int misslayerTime) { this.misslayerDuration = misslayerTime; } public boolean isCustomJudge() { return customJudge; } public void setCustomJudge(boolean customJudge) { this.customJudge = customJudge; } public int getKeyJudgeWindowRatePerfectGreat() { return keyJudgeWindowRatePerfectGreat; } public void setKeyJudgeWindowRatePerfectGreat(int judgeWindowRatePerfectGreat) { this.keyJudgeWindowRatePerfectGreat = judgeWindowRatePerfectGreat; } public int getKeyJudgeWindowRateGreat() { return keyJudgeWindowRateGreat; } public void setKeyJudgeWindowRateGreat(int judgeWindowRateGreat) { this.keyJudgeWindowRateGreat = judgeWindowRateGreat; } public int getKeyJudgeWindowRateGood() { return keyJudgeWindowRateGood; } public void setKeyJudgeWindowRateGood(int judgeWindowRateGood) { this.keyJudgeWindowRateGood = judgeWindowRateGood; } public int getScratchJudgeWindowRatePerfectGreat() { return scratchJudgeWindowRatePerfectGreat; } public void setScratchJudgeWindowRatePerfectGreat(int judgeWindowRatePerfectGreat) { this.scratchJudgeWindowRatePerfectGreat = judgeWindowRatePerfectGreat; } public int getScratchJudgeWindowRateGreat() { return scratchJudgeWindowRateGreat; } public void setScratchJudgeWindowRateGreat(int judgeWindowRateGreat) { this.scratchJudgeWindowRateGreat = judgeWindowRateGreat; } public int getScratchJudgeWindowRateGood() { return scratchJudgeWindowRateGood; } public void setScratchJudgeWindowRateGood(int judgeWindowRateGood) { this.scratchJudgeWindowRateGood = judgeWindowRateGood; } public int getHranThresholdBPM() { return hranThresholdBPM; } public void setHranThresholdBPM(int hranThresholdBPM) { this.hranThresholdBPM = hranThresholdBPM; } public int getSevenToNinePattern() { return sevenToNinePattern; } public void setSevenToNinePattern(int sevenToNinePattern) { this.sevenToNinePattern = sevenToNinePattern; } public int getSevenToNineType() { return sevenToNineType; } public void setSevenToNineType(int sevenToNineType) { this.sevenToNineType = sevenToNineType; } public int getExitPressDuration() { return exitPressDuration; } public void setExitPressDuration(int exitPressDuration) { this.exitPressDuration = exitPressDuration; } public boolean isGuideSE() { return isGuideSE; } public void setGuideSE(boolean isGuideSE) { this.isGuideSE = isGuideSE; } public boolean isWindowHold() { return isWindowHold; } public void setWindowHold(boolean isWindowHold) { this.isWindowHold = isWindowHold; } public boolean isRandomSelect() { return isRandomSelect; } public void setRandomSelect(boolean isRandomSelect) { this.isRandomSelect = isRandomSelect; } public boolean isChartPreview() { return chartPreview; } public void setChartPreview(boolean chartPreview) { this.chartPreview = chartPreview; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setAutoSaveReplay(int autoSaveReplay[]){ this.autosavereplay = autoSaveReplay; } public int[] getAutoSaveReplay(){ return autosavereplay; } public boolean isShowhiddennote() { return showhiddennote; } public void setShowhiddennote(boolean showhiddennote) { this.showhiddennote = showhiddennote; } public boolean isShowpastnote() { return showpastnote; } public void setShowpastnote(boolean showpastnote) { this.showpastnote = showpastnote; } public String getTwitterConsumerKey() { return twitterConsumerKey; } public void setTwitterConsumerKey(String twitterConsumerKey) { this.twitterConsumerKey = twitterConsumerKey; } public String getTwitterConsumerSecret() { return twitterConsumerSecret; } public void setTwitterConsumerSecret(String twitterConsumerSecret) { this.twitterConsumerSecret = twitterConsumerSecret; } public String getTwitterAccessToken() { return twitterAccessToken; } public void setTwitterAccessToken(String twitterAccessToken) { this.twitterAccessToken = twitterAccessToken; } public String getTwitterAccessTokenSecret() { return twitterAccessTokenSecret; } public void setTwitterAccessTokenSecret(String twitterAccessTokenSecret) { this.twitterAccessTokenSecret = twitterAccessTokenSecret; } // --Stream public boolean getRequestEnable() { return enableRequest; } public boolean getRequestNotify() { return notifyRequest; } public void setRequestEnable(boolean requestEnable) { this.enableRequest = requestEnable; } public void setRequestNotify(boolean notifyEnable) { this.notifyRequest = notifyEnable; } public int getMaxRequestCount() { return maxRequestCount; } public void setMaxRequestCount(int maxRequestCount) { this.maxRequestCount = maxRequestCount; } public void validate() { if(skin == null) { skin = new SkinConfig[SkinType.getMaxSkinTypeID() + 1]; } if(skinHistory == null) { skinHistory = new SkinConfig[0]; } if(skin.length != SkinType.getMaxSkinTypeID() + 1) { skin = Arrays.copyOf(skin, SkinType.getMaxSkinTypeID() + 1); } for(int i = 0;i < skin.length;i++) { if(skin[i] == null) { skin[i] = SkinConfig.getDefault(i); } skin[i].validate(); } if(mode5 == null) { mode5 = new PlayModeConfig(Mode.BEAT_5K); } if(mode7 == null) { mode7 = new PlayModeConfig(Mode.BEAT_7K); } if(mode14 == null) { mode14 = new PlayModeConfig(Mode.BEAT_14K); } if(mode10 == null) { mode10 = new PlayModeConfig(Mode.BEAT_10K); } if(mode9 == null) { mode9 = new PlayModeConfig(Mode.POPN_9K); } if(mode24 == null) { mode24 = new PlayModeConfig(Mode.KEYBOARD_24K); } if(mode24double == null) { mode24double = new PlayModeConfig(Mode.KEYBOARD_24K_DOUBLE); } mode5.validate(7); mode7.validate(9); mode10.validate(14); mode14.validate(18); mode9.validate(9); mode24.validate(26); mode24double.validate(52);
sort = MathUtils.clamp(sort, 0 , BarSorter.values().length - 1);
2
2023-12-02 23:41:17+00:00
12k
Tofaa2/EntityLib
src/main/java/me/tofaa/entitylib/MetaConverterRegistry.java
[ { "identifier": "EntityMeta", "path": "src/main/java/me/tofaa/entitylib/meta/EntityMeta.java", "snippet": "public class EntityMeta implements EntityMetadataProvider {\n\n public static final byte OFFSET = 0;\n public static final byte MAX_OFFSET = OFFSET + 8;\n\n private final static byte ON_FI...
import com.github.retrooper.packetevents.protocol.entity.type.EntityType; import me.tofaa.entitylib.meta.EntityMeta; import me.tofaa.entitylib.meta.Metadata; import me.tofaa.entitylib.meta.display.BlockDisplayMeta; import me.tofaa.entitylib.meta.display.ItemDisplayMeta; import me.tofaa.entitylib.meta.display.TextDisplayMeta; import me.tofaa.entitylib.meta.mobs.*; import me.tofaa.entitylib.meta.mobs.DonkeyMeta; import me.tofaa.entitylib.meta.mobs.cuboid.MagmaCubeMeta; import me.tofaa.entitylib.meta.mobs.cuboid.SlimeMeta; import me.tofaa.entitylib.meta.mobs.golem.IronGolemMeta; import me.tofaa.entitylib.meta.mobs.golem.ShulkerMeta; import me.tofaa.entitylib.meta.mobs.golem.SnowGolemMeta; import me.tofaa.entitylib.meta.mobs.horse.*; import me.tofaa.entitylib.meta.mobs.monster.*; import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinBruteMeta; import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinMeta; import me.tofaa.entitylib.meta.mobs.monster.raider.*; import me.tofaa.entitylib.meta.mobs.monster.skeleton.SkeletonMeta; import me.tofaa.entitylib.meta.mobs.monster.skeleton.StrayMeta; import me.tofaa.entitylib.meta.mobs.monster.skeleton.WitherSkeletonMeta; import me.tofaa.entitylib.meta.mobs.monster.zombie.*; import me.tofaa.entitylib.meta.mobs.passive.*; import me.tofaa.entitylib.meta.mobs.water.*; import me.tofaa.entitylib.meta.mobs.minecart.*; import me.tofaa.entitylib.meta.mobs.tameable.CatMeta; import me.tofaa.entitylib.meta.mobs.tameable.ParrotMeta; import me.tofaa.entitylib.meta.mobs.tameable.WolfMeta; import me.tofaa.entitylib.meta.mobs.villager.VillagerMeta; import me.tofaa.entitylib.meta.mobs.villager.WanderingTraderMeta; import me.tofaa.entitylib.meta.other.*; import me.tofaa.entitylib.meta.projectile.*; import me.tofaa.entitylib.meta.types.PlayerMeta; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import static com.github.retrooper.packetevents.protocol.entity.type.EntityTypes.*;
8,750
package me.tofaa.entitylib; @SuppressWarnings("unchecked") final class MetaConverterRegistry {
package me.tofaa.entitylib; @SuppressWarnings("unchecked") final class MetaConverterRegistry {
private final Map<EntityType, BiFunction<Integer, Metadata, EntityMeta>> converters = new HashMap<>();
0
2023-11-27 02:17:41+00:00
12k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/TrustListCommand.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import java.util.Optional; import java.util.StringJoiner; import java.util.UUID; import java.util.stream.Collectors; import de.themoep.minedown.adventure.MineDown; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.config.Locales; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.user.OnlineUser; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
9,483
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.command; public class TrustListCommand extends InClaimCommand { protected TrustListCommand(@NotNull HuskClaims plugin) { super( List.of("trustlist"), "", TrustLevel.Privilege.MANAGE_TRUSTEES, plugin ); } @Override public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world,
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.command; public class TrustListCommand extends InClaimCommand { protected TrustListCommand(@NotNull HuskClaims plugin) { super( List.of("trustlist"), "", TrustLevel.Privilege.MANAGE_TRUSTEES, plugin ); } @Override public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world,
@NotNull Claim claim, @NotNull String[] args) {
1
2023-11-28 01:09:43+00:00
12k
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/process/DataPlaceholderProcess.java
[ { "identifier": "HttpStatus", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/HttpStatus.java", "snippet": "public class HttpStatus\n{\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static fin...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.metax.common.core.constant.HttpStatus; import com.metax.common.core.constant.MetaxDataConstants; import com.metax.common.core.web.domain.AjaxResult; import com.metax.web.config.ChannelConfig; import com.metax.web.domain.*; import com.metax.web.domain.content.ProcessContent; import com.metax.web.domain.content.SendContent; import com.metax.web.domain.content.SendTaskParamContent; import com.metax.web.dto.content.SmsContentModel; import com.metax.web.dto.content.WeChatServiceAccountContentModel; import com.metax.web.service.IMessageTemplateService; import com.metax.web.util.ContentHolderUtil; import com.metax.web.util.RedisKeyUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.*; import static com.metax.common.core.constant.MetaxDataConstants.SMS; import static com.metax.common.core.constant.MetaxDataConstants.WECHAT_SERVICE_ACCOUNT;
8,354
package com.metax.web.process; /** * 为发送前进行数据填充 * * @Author: hanabi */ @Service @Slf4j public class DataPlaceholderProcess implements BusinessProcess { @Autowired private IMessageTemplateService messageTemplateService; @Autowired private ChannelConfig channelConfig; @Autowired private ContentHolderUtil contentHolderUtil; @Override public ProcessContent process(ProcessContent context) { if (!(context instanceof SendTaskParamContent)) { context.setIsNeedBreak(true); context.setResponse(AjaxResult.error(HttpStatus.ERROR, "发送流程上下文断裂")); return context; } SendTaskParamContent sendTaskParamContext = (SendTaskParamContent) context; Long templateId = sendTaskParamContext.getMessageTemplateId(); MessageTemplate messageTemplate = messageTemplateService.getById(templateId); //设置发送状态 messageTemplate.setMsgStatus(MetaxDataConstants.MSG_SENDING); //生成本次发送任务id Long sendTaskId = RedisKeyUtil.createSendTaskId(); //无占位符发送 只有一个sendTask if (sendTaskParamContext.getIsExitVariables() == 0) { //生成发送任务redisKey String messageRedisKey = RedisKeyUtil.createMessageRedisKey(sendTaskParamContext.getSender()); //需要特殊处理的渠道 因为有些渠道不需要自己提取替换占位符 channelConfig.needSkid.forEach(channel -> { if (channel.equals(sendTaskParamContext.getSendChannel())) { //无占位符 不用传参到第三方服务 直接发送 processingSpecialChannel(channel,messageTemplate); } }); SendTaskInfo sendTask = SendTaskInfo.builder().messageTemplate(messageTemplate) .receivers(sendTaskParamContext.getSendTaskParams().get(StrUtil.EMPTY)) .messageId(RedisKeyUtil.createMessageId()) .sendMessageKey(messageRedisKey) .sendTaskId(sendTaskId) .sendStartTime(LocalDateTime.now()) .build();
package com.metax.web.process; /** * 为发送前进行数据填充 * * @Author: hanabi */ @Service @Slf4j public class DataPlaceholderProcess implements BusinessProcess { @Autowired private IMessageTemplateService messageTemplateService; @Autowired private ChannelConfig channelConfig; @Autowired private ContentHolderUtil contentHolderUtil; @Override public ProcessContent process(ProcessContent context) { if (!(context instanceof SendTaskParamContent)) { context.setIsNeedBreak(true); context.setResponse(AjaxResult.error(HttpStatus.ERROR, "发送流程上下文断裂")); return context; } SendTaskParamContent sendTaskParamContext = (SendTaskParamContent) context; Long templateId = sendTaskParamContext.getMessageTemplateId(); MessageTemplate messageTemplate = messageTemplateService.getById(templateId); //设置发送状态 messageTemplate.setMsgStatus(MetaxDataConstants.MSG_SENDING); //生成本次发送任务id Long sendTaskId = RedisKeyUtil.createSendTaskId(); //无占位符发送 只有一个sendTask if (sendTaskParamContext.getIsExitVariables() == 0) { //生成发送任务redisKey String messageRedisKey = RedisKeyUtil.createMessageRedisKey(sendTaskParamContext.getSender()); //需要特殊处理的渠道 因为有些渠道不需要自己提取替换占位符 channelConfig.needSkid.forEach(channel -> { if (channel.equals(sendTaskParamContext.getSendChannel())) { //无占位符 不用传参到第三方服务 直接发送 processingSpecialChannel(channel,messageTemplate); } }); SendTaskInfo sendTask = SendTaskInfo.builder().messageTemplate(messageTemplate) .receivers(sendTaskParamContext.getSendTaskParams().get(StrUtil.EMPTY)) .messageId(RedisKeyUtil.createMessageId()) .sendMessageKey(messageRedisKey) .sendTaskId(sendTaskId) .sendStartTime(LocalDateTime.now()) .build();
return SendContent.builder().sendTasks(Collections.singletonList(sendTask))
5
2023-12-04 05:10:13+00:00
12k
ydb-platform/yoj-project
repository-ydb-v2/src/main/java/tech/ydb/yoj/repository/ydb/yql/YqlListingQuery.java
[ { "identifier": "AndExpr", "path": "databind/src/main/java/tech/ydb/yoj/databind/expression/AndExpr.java", "snippet": "@Value\n@AllArgsConstructor\npublic class AndExpr<T> implements FilterExpression<T> {\n @NonNull\n Schema<T> schema;\n\n @NonNull\n List<FilterExpression<T>> children;\n\n ...
import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import lombok.NonNull; import tech.ydb.yoj.databind.expression.AndExpr; import tech.ydb.yoj.databind.expression.FilterExpression; import tech.ydb.yoj.databind.expression.LeafExpression; import tech.ydb.yoj.databind.expression.ListExpr; import tech.ydb.yoj.databind.expression.NotExpr; import tech.ydb.yoj.databind.expression.NullExpr; import tech.ydb.yoj.databind.expression.OrExpr; import tech.ydb.yoj.databind.expression.OrderExpression; import tech.ydb.yoj.databind.expression.OrderExpression.SortKey; import tech.ydb.yoj.databind.expression.ScalarExpr; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntityIdSchema; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static tech.ydb.yoj.databind.expression.OrderExpression.SortOrder.ASCENDING;
9,587
package tech.ydb.yoj.repository.ydb.yql; public final class YqlListingQuery { private static final FilterExpression.Visitor<?, String> FIELD_NAME_VISITOR = new FilterExpression.Visitor.Simple<>() { @Override protected String visitLeaf(@NonNull LeafExpression<Object> leaf) { return leaf.getFieldName(); } @Override protected String visitComposite(@NonNull FilterExpression<Object> composite) { return null; } }; private static final CharMatcher LIKE_PATTERN_CHARS = CharMatcher.anyOf("%_").precomputed(); /** * Default escape character for {@code LIKE} operator. Unfortunately, YDB does not currently support using {@code \} * as an escape, so we choose a reasonable rare character instead. */ private static final char LIKE_ESCAPE_CHAR = '^'; private YqlListingQuery() { } @VisibleForTesting public static <T extends Entity<T>> YqlPredicate toYqlPredicate(@NonNull FilterExpression<T> filter) { return filter.visit(new FilterExpression.Visitor<>() { @Override public YqlPredicate visitScalarExpr(@NonNull ScalarExpr<T> scalarExpr) { String fieldPath = scalarExpr.getFieldPath(); Type fieldType = scalarExpr.getFieldType(); YqlPredicate.FieldPredicateBuilder pred = YqlPredicate.where(fieldPath); Object expected = scalarExpr.getValue().getRaw(fieldType); return switch (scalarExpr.getOperator()) { case EQ -> pred.eq(expected); case NEQ -> pred.neq(expected); case LT -> pred.lt(expected); case LTE -> pred.lte(expected); case GT -> pred.gt(expected); case GTE -> pred.gte(expected); case CONTAINS -> pred.like(likePatternForContains((String) expected), LIKE_ESCAPE_CHAR); case NOT_CONTAINS -> pred.notLike(likePatternForContains((String) expected), LIKE_ESCAPE_CHAR); }; } @Override public YqlPredicate visitNullExpr(@NonNull NullExpr<T> nullExpr) { String fieldPath = nullExpr.getFieldPath(); YqlPredicate.FieldPredicateBuilder pred = YqlPredicate.where(fieldPath); switch (nullExpr.getOperator()) { case IS_NULL: return pred.isNull(); case IS_NOT_NULL: return pred.isNotNull(); default: throw new UnsupportedOperationException("Unknown relation in nullability expression: " + nullExpr.getOperator()); } } @Override public YqlPredicate visitListExpr(@NonNull ListExpr<T> listExpr) { String fieldPath = listExpr.getFieldPath(); Type fieldType = listExpr.getFieldType(); List<?> expected = listExpr.getValues().stream().map(v -> v.getRaw(fieldType)).collect(toList()); switch (listExpr.getOperator()) { case IN: return YqlPredicate.where(fieldPath).in(expected); case NOT_IN: return YqlPredicate.where(fieldPath).notIn(expected); default: throw new UnsupportedOperationException("Unknown relation in filter expression: " + listExpr.getOperator()); } } @Override
package tech.ydb.yoj.repository.ydb.yql; public final class YqlListingQuery { private static final FilterExpression.Visitor<?, String> FIELD_NAME_VISITOR = new FilterExpression.Visitor.Simple<>() { @Override protected String visitLeaf(@NonNull LeafExpression<Object> leaf) { return leaf.getFieldName(); } @Override protected String visitComposite(@NonNull FilterExpression<Object> composite) { return null; } }; private static final CharMatcher LIKE_PATTERN_CHARS = CharMatcher.anyOf("%_").precomputed(); /** * Default escape character for {@code LIKE} operator. Unfortunately, YDB does not currently support using {@code \} * as an escape, so we choose a reasonable rare character instead. */ private static final char LIKE_ESCAPE_CHAR = '^'; private YqlListingQuery() { } @VisibleForTesting public static <T extends Entity<T>> YqlPredicate toYqlPredicate(@NonNull FilterExpression<T> filter) { return filter.visit(new FilterExpression.Visitor<>() { @Override public YqlPredicate visitScalarExpr(@NonNull ScalarExpr<T> scalarExpr) { String fieldPath = scalarExpr.getFieldPath(); Type fieldType = scalarExpr.getFieldType(); YqlPredicate.FieldPredicateBuilder pred = YqlPredicate.where(fieldPath); Object expected = scalarExpr.getValue().getRaw(fieldType); return switch (scalarExpr.getOperator()) { case EQ -> pred.eq(expected); case NEQ -> pred.neq(expected); case LT -> pred.lt(expected); case LTE -> pred.lte(expected); case GT -> pred.gt(expected); case GTE -> pred.gte(expected); case CONTAINS -> pred.like(likePatternForContains((String) expected), LIKE_ESCAPE_CHAR); case NOT_CONTAINS -> pred.notLike(likePatternForContains((String) expected), LIKE_ESCAPE_CHAR); }; } @Override public YqlPredicate visitNullExpr(@NonNull NullExpr<T> nullExpr) { String fieldPath = nullExpr.getFieldPath(); YqlPredicate.FieldPredicateBuilder pred = YqlPredicate.where(fieldPath); switch (nullExpr.getOperator()) { case IS_NULL: return pred.isNull(); case IS_NOT_NULL: return pred.isNotNull(); default: throw new UnsupportedOperationException("Unknown relation in nullability expression: " + nullExpr.getOperator()); } } @Override public YqlPredicate visitListExpr(@NonNull ListExpr<T> listExpr) { String fieldPath = listExpr.getFieldPath(); Type fieldType = listExpr.getFieldType(); List<?> expected = listExpr.getValues().stream().map(v -> v.getRaw(fieldType)).collect(toList()); switch (listExpr.getOperator()) { case IN: return YqlPredicate.where(fieldPath).in(expected); case NOT_IN: return YqlPredicate.where(fieldPath).notIn(expected); default: throw new UnsupportedOperationException("Unknown relation in filter expression: " + listExpr.getOperator()); } } @Override
public YqlPredicate visitAndExpr(@NonNull AndExpr<T> andExpr) {
0
2023-12-05 15:57:58+00:00
12k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/JREUtils.java
[ { "identifier": "ARCH_X86", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java", "snippet": "public static final int ARCH_X86 = 0x4;" }, { "identifier": "is64BitsDevice", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java", "snippet...
import static net.kdt.pojavlaunch.Architecture.ARCH_X86; import static net.kdt.pojavlaunch.Architecture.is64BitsDevice; import static net.kdt.pojavlaunch.Tools.LOCAL_RENDERER; import static net.kdt.pojavlaunch.Tools.NATIVE_LIB_DIR; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.Tools.shareLog; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.*; import android.app.*; import android.content.*; import android.os.Build; import android.system.*; import android.util.*; import android.widget.Toast; import com.oracle.dalvik.*; import java.io.*; import java.util.*; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.plugins.FFmpegPlugin; import net.kdt.pojavlaunch.prefs.*; import org.lwjgl.glfw.*; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay;
8,821
returnValue.addAll(locateLibs(f)); } } } return returnValue; } public static void initJavaRuntime(String jreHome) { dlopen(findInLdLibPath("libjli.so")); if(!dlopen("libjvm.so")){ Log.w("DynamicLoader","Failed to load with no path, trying with full path"); dlopen(jvmLibraryPath+"/libjvm.so"); } dlopen(findInLdLibPath("libverify.so")); dlopen(findInLdLibPath("libjava.so")); // dlopen(findInLdLibPath("libjsig.so")); dlopen(findInLdLibPath("libnet.so")); dlopen(findInLdLibPath("libnio.so")); dlopen(findInLdLibPath("libawt.so")); dlopen(findInLdLibPath("libawt_headless.so")); dlopen(findInLdLibPath("libfreetype.so")); dlopen(findInLdLibPath("libfontmanager.so")); for(File f : locateLibs(new File(jreHome, Tools.DIRNAME_HOME_JRE))) { dlopen(f.getAbsolutePath()); } dlopen(NATIVE_LIB_DIR + "/libopenal.so"); } public static void redirectAndPrintJRELog() { Log.v("jrelog","Log starts here"); new Thread(new Runnable(){ int failTime = 0; ProcessBuilder logcatPb; @Override public void run() { try { if (logcatPb == null) { logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true); } Log.i("jrelog-logcat","Clearing logcat"); new ProcessBuilder().command("logcat", "-c").redirectErrorStream(true).start(); Log.i("jrelog-logcat","Starting logcat"); java.lang.Process p = logcatPb.start(); byte[] buf = new byte[1024]; int len; while ((len = p.getInputStream().read(buf)) != -1) { String currStr = new String(buf, 0, len); Logger.appendToLog(currStr); } if (p.waitFor() != 0) { Log.e("jrelog-logcat", "Logcat exited with code " + p.exitValue()); failTime++; Log.i("jrelog-logcat", (failTime <= 10 ? "Restarting logcat" : "Too many restart fails") + " (attempt " + failTime + "/10"); if (failTime <= 10) { run(); } else { Logger.appendToLog("ERROR: Unable to get more log."); } } } catch (Throwable e) { Log.e("jrelog-logcat", "Exception on logging thread", e); Logger.appendToLog("Exception on logging thread:\n" + Log.getStackTraceString(e)); } } }).start(); Log.i("jrelog-logcat","Logcat thread started"); } public static void relocateLibPath(Runtime runtime, String jreHome) { String JRE_ARCHITECTURE = runtime.arch; if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){ JRE_ARCHITECTURE = "i386/i486/i586"; } for (String arch : JRE_ARCHITECTURE.split("/")) { File f = new File(jreHome, "lib/" + arch); if (f.exists() && f.isDirectory()) { Tools.DIRNAME_HOME_JRE = "lib/" + arch; } } String libName = is64BitsDevice() ? "lib64" : "lib"; StringBuilder ldLibraryPath = new StringBuilder(); if(FFmpegPlugin.isAvailable) { ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":"); } ldLibraryPath.append(jreHome) .append("/").append(Tools.DIRNAME_HOME_JRE) .append("/jli:").append(jreHome).append("/").append(Tools.DIRNAME_HOME_JRE) .append(":"); ldLibraryPath.append("/system/").append(libName).append(":") .append("/vendor/").append(libName).append(":") .append("/vendor/").append(libName).append("/hw:") .append(NATIVE_LIB_DIR); LD_LIBRARY_PATH = ldLibraryPath.toString(); } public static void setJavaEnvironment(Activity activity, String jreHome) throws Throwable { Map<String, String> envMap = new ArrayMap<>(); envMap.put("POJAV_NATIVEDIR", NATIVE_LIB_DIR); envMap.put("JAVA_HOME", jreHome); envMap.put("HOME", Tools.DIR_GAME_HOME); envMap.put("TMPDIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("LIBGL_MIPMAP", "3"); // Prevent OptiFine (and other error-reporting stuff in Minecraft) from balooning the log envMap.put("LIBGL_NOERROR", "1"); // On certain GLES drivers, overloading default functions shader hack fails, so disable it envMap.put("LIBGL_NOINTOVLHACK", "1"); // Fix white color on banner and sheep, since GL4ES 1.1.5 envMap.put("LIBGL_NORMALIZE", "1"); // The OPEN GL version is changed according
package net.kdt.pojavlaunch.utils; public class JREUtils { private JREUtils() {} public static String LD_LIBRARY_PATH; public static String jvmLibraryPath; public static String findInLdLibPath(String libName) { if(Os.getenv("LD_LIBRARY_PATH")==null) { try { if (LD_LIBRARY_PATH != null) { Os.setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, true); } }catch (ErrnoException e) { e.printStackTrace(); } return libName; } for (String libPath : Os.getenv("LD_LIBRARY_PATH").split(":")) { File f = new File(libPath, libName); if (f.exists() && f.isFile()) { return f.getAbsolutePath(); } } return libName; } public static ArrayList<File> locateLibs(File path) { ArrayList<File> returnValue = new ArrayList<>(); File[] list = path.listFiles(); if(list != null) { for(File f : list) { if(f.isFile() && f.getName().endsWith(".so")) { returnValue.add(f); }else if(f.isDirectory()) { returnValue.addAll(locateLibs(f)); } } } return returnValue; } public static void initJavaRuntime(String jreHome) { dlopen(findInLdLibPath("libjli.so")); if(!dlopen("libjvm.so")){ Log.w("DynamicLoader","Failed to load with no path, trying with full path"); dlopen(jvmLibraryPath+"/libjvm.so"); } dlopen(findInLdLibPath("libverify.so")); dlopen(findInLdLibPath("libjava.so")); // dlopen(findInLdLibPath("libjsig.so")); dlopen(findInLdLibPath("libnet.so")); dlopen(findInLdLibPath("libnio.so")); dlopen(findInLdLibPath("libawt.so")); dlopen(findInLdLibPath("libawt_headless.so")); dlopen(findInLdLibPath("libfreetype.so")); dlopen(findInLdLibPath("libfontmanager.so")); for(File f : locateLibs(new File(jreHome, Tools.DIRNAME_HOME_JRE))) { dlopen(f.getAbsolutePath()); } dlopen(NATIVE_LIB_DIR + "/libopenal.so"); } public static void redirectAndPrintJRELog() { Log.v("jrelog","Log starts here"); new Thread(new Runnable(){ int failTime = 0; ProcessBuilder logcatPb; @Override public void run() { try { if (logcatPb == null) { logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true); } Log.i("jrelog-logcat","Clearing logcat"); new ProcessBuilder().command("logcat", "-c").redirectErrorStream(true).start(); Log.i("jrelog-logcat","Starting logcat"); java.lang.Process p = logcatPb.start(); byte[] buf = new byte[1024]; int len; while ((len = p.getInputStream().read(buf)) != -1) { String currStr = new String(buf, 0, len); Logger.appendToLog(currStr); } if (p.waitFor() != 0) { Log.e("jrelog-logcat", "Logcat exited with code " + p.exitValue()); failTime++; Log.i("jrelog-logcat", (failTime <= 10 ? "Restarting logcat" : "Too many restart fails") + " (attempt " + failTime + "/10"); if (failTime <= 10) { run(); } else { Logger.appendToLog("ERROR: Unable to get more log."); } } } catch (Throwable e) { Log.e("jrelog-logcat", "Exception on logging thread", e); Logger.appendToLog("Exception on logging thread:\n" + Log.getStackTraceString(e)); } } }).start(); Log.i("jrelog-logcat","Logcat thread started"); } public static void relocateLibPath(Runtime runtime, String jreHome) { String JRE_ARCHITECTURE = runtime.arch; if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){ JRE_ARCHITECTURE = "i386/i486/i586"; } for (String arch : JRE_ARCHITECTURE.split("/")) { File f = new File(jreHome, "lib/" + arch); if (f.exists() && f.isDirectory()) { Tools.DIRNAME_HOME_JRE = "lib/" + arch; } } String libName = is64BitsDevice() ? "lib64" : "lib"; StringBuilder ldLibraryPath = new StringBuilder(); if(FFmpegPlugin.isAvailable) { ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":"); } ldLibraryPath.append(jreHome) .append("/").append(Tools.DIRNAME_HOME_JRE) .append("/jli:").append(jreHome).append("/").append(Tools.DIRNAME_HOME_JRE) .append(":"); ldLibraryPath.append("/system/").append(libName).append(":") .append("/vendor/").append(libName).append(":") .append("/vendor/").append(libName).append("/hw:") .append(NATIVE_LIB_DIR); LD_LIBRARY_PATH = ldLibraryPath.toString(); } public static void setJavaEnvironment(Activity activity, String jreHome) throws Throwable { Map<String, String> envMap = new ArrayMap<>(); envMap.put("POJAV_NATIVEDIR", NATIVE_LIB_DIR); envMap.put("JAVA_HOME", jreHome); envMap.put("HOME", Tools.DIR_GAME_HOME); envMap.put("TMPDIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("LIBGL_MIPMAP", "3"); // Prevent OptiFine (and other error-reporting stuff in Minecraft) from balooning the log envMap.put("LIBGL_NOERROR", "1"); // On certain GLES drivers, overloading default functions shader hack fails, so disable it envMap.put("LIBGL_NOINTOVLHACK", "1"); // Fix white color on banner and sheep, since GL4ES 1.1.5 envMap.put("LIBGL_NORMALIZE", "1"); // The OPEN GL version is changed according
envMap.put("LIBGL_ES", (String) ExtraCore.getValue(ExtraConstants.OPEN_GL_VERSION));
8
2023-12-01 16:16:12+00:00
12k
kawashirov/distant-horizons
fabric/src/main/java/com/seibel/distanthorizons/fabric/FabricClientProxy.java
[ { "identifier": "SeamlessOverdraw", "path": "common/src/main/java/com/seibel/distanthorizons/common/rendering/SeamlessOverdraw.java", "snippet": "public class SeamlessOverdraw\n{\n\t/**\n\t * Proof-of-concept experimental option, not intended for normal use. <br>\n\t * (Poorly) replaces Minecraft's far ...
import com.seibel.distanthorizons.common.rendering.SeamlessOverdraw; import com.seibel.distanthorizons.common.wrappers.McObjectConverter; import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper; import com.seibel.distanthorizons.core.api.internal.ClientApi; import com.mojang.blaze3d.platform.InputConstants; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.core.api.internal.SharedApi; import com.seibel.distanthorizons.core.config.Config; import com.seibel.distanthorizons.core.dependencyInjection.ModAccessorInjector; import com.seibel.distanthorizons.core.dependencyInjection.SingletonInjector; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IMinecraftClientWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.modAccessor.ISodiumAccessor; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import com.seibel.distanthorizons.coreapi.ModInfo; import com.seibel.distanthorizons.fabric.wrappers.modAccessor.SodiumAccessor; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientChunkEvents; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.player.AttackBlockCallback; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.TitleScreen; import java.nio.FloatBuffer; import java.util.HashSet; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.InteractionResult; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.phys.HitResult; import org.apache.logging.log4j.Logger; import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL15;
10,213
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.fabric; //import io.netty.buffer.ByteBuf; /** * This handles all events sent to the client, * and is the starting point for most of the mod. * * @author coolGi * @author Ran * @version 2023-7-27 */ @Environment(EnvType.CLIENT) public class FabricClientProxy { private final ClientApi clientApi = ClientApi.INSTANCE; private static final IMinecraftClientWrapper MC = SingletonInjector.INSTANCE.get(IMinecraftClientWrapper.class); private static final Logger LOGGER = DhLoggerBuilder.getLogger(); // TODO we shouldn't be filtering keys on the Forge/Fabric side, only in ClientApi private static final int[] KEY_TO_CHECK_FOR = { GLFW.GLFW_KEY_F6, GLFW.GLFW_KEY_F8, GLFW.GLFW_KEY_P}; HashSet<Integer> previouslyPressKeyCodes = new HashSet<>(); /** * Registers Fabric Events * @author Ran */ public void registerEvents() { LOGGER.info("Registering Fabric Client Events"); //========================// // register mod accessors // //========================//
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.fabric; //import io.netty.buffer.ByteBuf; /** * This handles all events sent to the client, * and is the starting point for most of the mod. * * @author coolGi * @author Ran * @version 2023-7-27 */ @Environment(EnvType.CLIENT) public class FabricClientProxy { private final ClientApi clientApi = ClientApi.INSTANCE; private static final IMinecraftClientWrapper MC = SingletonInjector.INSTANCE.get(IMinecraftClientWrapper.class); private static final Logger LOGGER = DhLoggerBuilder.getLogger(); // TODO we shouldn't be filtering keys on the Forge/Fabric side, only in ClientApi private static final int[] KEY_TO_CHECK_FOR = { GLFW.GLFW_KEY_F6, GLFW.GLFW_KEY_F8, GLFW.GLFW_KEY_P}; HashSet<Integer> previouslyPressKeyCodes = new HashSet<>(); /** * Registers Fabric Events * @author Ran */ public void registerEvents() { LOGGER.info("Registering Fabric Client Events"); //========================// // register mod accessors // //========================//
SodiumAccessor sodiumAccessor = (SodiumAccessor) ModAccessorInjector.INSTANCE.get(ISodiumAccessor.class);
4
2023-12-04 11:41:46+00:00
12k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/generators/JurorPoolGeneratorUtil.java
[ { "identifier": "ExcusableCode", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ExcusableCode.java", "snippet": "@Getter\npublic enum ExcusableCode {\n\n CRIMINAL_RECORD(\"K\"),\n DECEASED(\"D\"),\n OVER_69(\"V\"),\n RECENTLY_SERVED(\"S\"),\n THE_FORCES(\"F\"),\n MEDICAL_...
import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.sql.entity.ExcusableCode; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.service.SqlSupportService; import java.time.LocalDate; import java.util.Arrays;
7,450
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList())); jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now())); //Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool return jurorPoolGenerator; } public static JurorPoolGenerator reassigned(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false)); return jurorPoolGenerator; } public static JurorPoolGenerator transferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setTransferDate( new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now()) ); return jurorPoolGenerator; } public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO); } public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND); generator.setNoAttendances(new FixedValueGeneratorImpl<>(0)); generator.setNoAttended(new FixedValueGeneratorImpl<>(0)); return generator; } public static JurorPoolGenerator completed(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED); generator.setNextDate(new NullValueGeneratorImpl<>()); return generator; } private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) { JurorPoolGenerator generator = new JurorPoolGenerator(); generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId())); if (isCourtOwned) { generator.setOwner(new RandomFromCollectionGeneratorImpl<>(SqlSupportService.getCourtOwners())); } else { generator.setOwner(new FixedValueGeneratorImpl<>("400")); } return generator; }
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList())); jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now())); //Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool return jurorPoolGenerator; } public static JurorPoolGenerator reassigned(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false)); return jurorPoolGenerator; } public static JurorPoolGenerator transferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setTransferDate( new LocalDateGeneratorImpl( LocalDate.now().minusDays(200), LocalDate.now()) ); return jurorPoolGenerator; } public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO); } public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND); generator.setNoAttendances(new FixedValueGeneratorImpl<>(0)); generator.setNoAttended(new FixedValueGeneratorImpl<>(0)); return generator; } public static JurorPoolGenerator completed(boolean isCourtOwned) { JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED); generator.setNextDate(new NullValueGeneratorImpl<>()); return generator; } private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) { JurorPoolGenerator generator = new JurorPoolGenerator(); generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId())); if (isCourtOwned) { generator.setOwner(new RandomFromCollectionGeneratorImpl<>(SqlSupportService.getCourtOwners())); } else { generator.setOwner(new FixedValueGeneratorImpl<>("400")); } return generator; }
public static JurorPoolGenerator create(Juror juror, PoolRequest pool) {
3
2023-12-01 11:38:42+00:00
12k
vvbbnn00/JavaWeb-CanteenSystem
JavaBackend/src/main/java/cn/vvbbnn00/canteen/controller/rest/CanteenResource.java
[ { "identifier": "CanteenListRequest", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dto/request/CanteenListRequest.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@JavaBean\npublic class CanteenListRequest extends BasicListRequest{\n @Pattern(regexp = \"^(canteenId|name|locat...
import cn.vvbbnn00.canteen.annotation.CheckRole; import cn.vvbbnn00.canteen.dto.request.CanteenListRequest; import cn.vvbbnn00.canteen.dto.response.BasicDataResponse; import cn.vvbbnn00.canteen.dto.response.BasicListResponse; import cn.vvbbnn00.canteen.model.Canteen; import cn.vvbbnn00.canteen.model.Comment; import cn.vvbbnn00.canteen.service.CanteenAdminService; import cn.vvbbnn00.canteen.service.CanteenService; import cn.vvbbnn00.canteen.service.CommentService; import cn.vvbbnn00.canteen.util.RequestValidatorUtils; import jakarta.enterprise.context.RequestScoped; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext;
9,248
package cn.vvbbnn00.canteen.controller.rest; @Path("/canteen") @RequestScoped public class CanteenResource { @Context SecurityContext securityContext; CanteenService canteenService = new CanteenService(); CommentService commentService = new CommentService();
package cn.vvbbnn00.canteen.controller.rest; @Path("/canteen") @RequestScoped public class CanteenResource { @Context SecurityContext securityContext; CanteenService canteenService = new CanteenService(); CommentService commentService = new CommentService();
CanteenAdminService canteenAdminService = new CanteenAdminService();
5
2023-12-01 04:55:12+00:00
12k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/Main.java
[ { "identifier": "Config", "path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java", "snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static fin...
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages;
9,914
package net.superricky.tpaplusplus; // The value here should match an entry in the META-INF/mods.toml file @Mod(Main.MOD_ID) public class Main { // Our mod id public static final String MOD_ID = "tpaplusplus"; public static final String MOD_VERSION = "1.3-1.20.x-BETA-3"; public Main() { MinecraftForge.EVENT_BUS.register(this); // Instantiate the mod's messages ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Messages.SPEC, "tpaplusplus-messages.toml"); // Instantiate the mod's configuration
package net.superricky.tpaplusplus; // The value here should match an entry in the META-INF/mods.toml file @Mod(Main.MOD_ID) public class Main { // Our mod id public static final String MOD_ID = "tpaplusplus"; public static final String MOD_VERSION = "1.3-1.20.x-BETA-3"; public Main() { MinecraftForge.EVENT_BUS.register(this); // Instantiate the mod's messages ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Messages.SPEC, "tpaplusplus-messages.toml"); // Instantiate the mod's configuration
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC, "tpaplusplus-common.toml");
0
2023-12-02 05:41:24+00:00
12k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/db/ActivityDiaryContentProvider.java
[ { "identifier": "ActivityHelper", "path": "app/src/main/java/de/rampro/activitydiary/helpers/ActivityHelper.java", "snippet": "public class ActivityHelper extends AsyncQueryHandler{\n private static final String TAG = ActivityHelper.class.getName();\n\n private static final int QUERY_ALL_ACTIVITIE...
import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.rampro.activitydiary.R; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.model.Achievement; import de.rampro.activitydiary.model.DiaryActivity; import static android.app.SearchManager.SUGGEST_COLUMN_ICON_1; import static android.app.SearchManager.SUGGEST_COLUMN_INTENT_ACTION; import static android.app.SearchManager.SUGGEST_COLUMN_INTENT_DATA; import static android.app.SearchManager.SUGGEST_COLUMN_QUERY; import static android.app.SearchManager.SUGGEST_COLUMN_TEXT_1; import static de.rampro.activitydiary.model.conditions.Condition.mOpenHelper;
10,785
public String searchDate(Long dateInMillis) { // TODO: move this into the method query, for the case diary, // similar to diary_stats, we can modify selection and selection args there // or maybe better, invent a new URI like "diary/number" where number is the dateInMillis // Alternative: move all this directly into HistoryActivity.onCreateLoader String querySelection = " ", id; long searchedValue = dateInMillis; long searchedValuePlusDay = searchedValue + 86400000; // TODO: replace magic numbers by the formula to calculate them... long searchSpecialCase = searchedValue + 86399999; //used for searching for still running activity Cursor allRowsStart = null; try { // TODO: -> this query should not be executed outside of the method ActivityDiaryContentProvider.query allRowsStart = mOpenHelper.getReadableDatabase().rawQuery( "SELECT " + ActivityDiaryContract.Diary._ID + " FROM " + ActivityDiaryContract.Diary.TABLE_NAME + " WHERE " + "(" + searchedValue + " >= " + ActivityDiaryContract.Diary.START + " AND " + searchedValue + " <= " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchedValuePlusDay + " >= " + ActivityDiaryContract.Diary.START + " AND " + searchedValuePlusDay + " <= " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchedValue + " < " + ActivityDiaryContract.Diary.START + " AND " + searchedValuePlusDay + " > " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchSpecialCase + " >= " + ActivityDiaryContract.Diary.START + " AND " + ActivityDiaryContract.Diary.END + " IS NULL" + ")", null); if (allRowsStart.moveToFirst()) { do { for (String name : allRowsStart.getColumnNames()) { id = (allRowsStart.getString(allRowsStart.getColumnIndex(name))); querySelection += querySelection.equals(" ") ? ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary._ID + " =" + id : " OR " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary._ID + " =" + id ; } } while (allRowsStart.moveToNext()); } } catch (Exception e) { // TODO: add proper exception handling. Also "Exception" seems quite generic -> catch all exceptions that can occur directly }finally{ if(allRowsStart != null){ allRowsStart.close(); } } // if there is no matching dates it returns query which links to find nothings // otherwise it will return query with IDs of matching dates return querySelection.equals(" ") ? " start=null" : querySelection; } public static int countSleepActivitiesInLast24Hours() { int count = 0; // if(mOpenHelper == null)onCreate(); SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和24小时前的时间戳 long currentTime = System.currentTimeMillis(); long oneDayAgo = currentTime - 86400000; // 构建查询 String query = "SELECT COUNT(*) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(oneDayAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { count = cursor.getInt(0); } cursor.close(); return count; } public static int countSleepActivitiesInLast48Hours() { int count = 0; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和48小时前的时间戳 long currentTime = System.currentTimeMillis(); long twoDaysAgo = currentTime - (2 * 86400000); // 2天的毫秒数 // 构建查询 String query = "SELECT COUNT(*) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(twoDaysAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { count = cursor.getInt(0); } cursor.close(); return count; } public static int getTotalSleepHoursInLastWeek() { int totalHours = 0; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和一周前的时间戳 long currentTime = System.currentTimeMillis(); long oneWeekAgo = currentTime - (7 * 86400000); // 7天的毫秒数 // 构建查询来计算总睡眠时间 String query = "SELECT SUM(d.'end' - d.start) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(oneWeekAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { // 将毫秒转换为小时 totalHours = cursor.getInt(0) / (3600000); } cursor.close(); return totalHours; }
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Bc. Ondrej Janitor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.db; /* * Why a new Content Provider for Diary Activities? * * According https://developer.android.com/guide/topics/providers/content-provider-creating.html * we need it to do searching, syncing or widget use of the data -> which in the long we all want to do. * * Additionally it is used as SearchProvider these days. * */ public class ActivityDiaryContentProvider extends ContentProvider { private static final int activities = 1; private static final int activities_ID = 2; private static final int conditions = 3; private static final int conditions_ID = 4; private static final int diary = 5; private static final int diary_ID = 6; private static final int diary_image = 7; private static final int diary_image_ID = 8; private static final int diary_location = 9; private static final int diary_location_ID = 10; private static final int diary_stats = 11; private static final int search_recent_suggestion = 12; private static final int search_suggestion = 13; private static final int diary_suggestion = 14; private static final String TAG = ActivityDiaryContentProvider.class.getName(); public static final String SEARCH_ACTIVITY = "de.rampro.activitydiary.action.SEARCH_ACTIVITY"; public static final String SEARCH_NOTE = "de.rampro.activitydiary.action.SEARCH_NOTE"; public static final String SEARCH_GLOBAL = "de.rampro.activitydiary.action.SEARCH_GLOBAL"; public static final String SEARCH_DATE = "de.rampro.activitydiary.action.SEARCH_DATE"; // TODO: isn't this already somewhere else? public static final Uri SEARCH_URI = Uri.parse("content://" + ActivityDiaryContract.AUTHORITY); private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryActivity.CONTENT_URI.getPath().replaceAll("^/+", ""), activities); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryActivity.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#", activities_ID); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.Diary.CONTENT_URI.getPath().replaceAll("^/+", ""), diary); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.Diary.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#", diary_ID); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryImage.CONTENT_URI.getPath().replaceAll("^/+", ""), diary_image); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryImage.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#", diary_image_ID); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryStats.CONTENT_URI.getPath().replaceAll("^/+", ""), diary_stats); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryStats.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#/#", diary_stats); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryLocation.CONTENT_URI.getPath().replaceAll("^/+", ""), diary_location); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryLocation.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#", diary_location_ID); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryLocation.CONTENT_URI.getPath().replaceAll("^/+", ""), diary_location); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiaryLocation.CONTENT_URI.getPath().replaceAll("^/+", "") + "/#", diary_location_ID); // TODO: sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, "history/" + SearchManager.SUGGEST_URI_PATH_QUERY + "/", search_recent_suggestion); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, "history/" + SearchManager.SUGGEST_URI_PATH_QUERY + "/*", search_suggestion); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, ActivityDiaryContract.DiarySearchSuggestion.CONTENT_URI.getPath().replaceAll("^/+", ""), diary_suggestion); /* TODO #18 */ sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, "conditions", conditions); sUriMatcher.addURI(ActivityDiaryContract.AUTHORITY, "conditions/#", conditions_ID); } private static LocalDBHelper mOpenHelper; @Override public boolean onCreate() { mOpenHelper = new LocalDBHelper(getContext()); return true; /* successfully loaded */ } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); boolean useRawQuery = false; String grouping = null; String sql = ""; Cursor c; int id = 0; if(selection == null){ selection = ""; } MatrixCursor result = new MatrixCursor(new String[]{ BaseColumns._ID, SUGGEST_COLUMN_TEXT_1, SUGGEST_COLUMN_ICON_1, SUGGEST_COLUMN_INTENT_ACTION, SUGGEST_COLUMN_INTENT_DATA, SUGGEST_COLUMN_QUERY }); if (sUriMatcher.match(uri) < 1) { /* URI is not recognized, return an empty Cursor */ return null; } switch (sUriMatcher.match(uri)) { case activities_ID: case conditions_ID: case diary_ID: case diary_image_ID: case diary_location_ID: if (selection != null) { selection = selection + " AND "; } else { selection = ""; } selection = selection + "_id=" + uri.getLastPathSegment(); default: /* empty */ } switch (sUriMatcher.match(uri)) { case activities_ID: /* intended fall through */ case activities: int n; boolean hasDiaryJoin = false; String tables = ActivityDiaryContract.DiaryActivity.TABLE_NAME; if (TextUtils.isEmpty(sortOrder)) { sortOrder = ActivityDiaryContract.DiaryActivity.SORT_ORDER_DEFAULT; } n = 0; while(n < projection.length){ if(ActivityDiaryContract.DiaryActivity.X_AVG_DURATION.equals(projection[n])){ projection[n] = "AVG(" + ActivityDiaryContract.Diary.END + " - " + ActivityDiaryContract.Diary.START + ") AS " + ActivityDiaryContract.DiaryActivity.X_AVG_DURATION; hasDiaryJoin = true; } if(ActivityDiaryContract.DiaryActivity.X_START_OF_LAST.equals(projection[n])){ projection[n] = "xx_start AS " + ActivityDiaryContract.DiaryActivity.X_START_OF_LAST; hasDiaryJoin = true; } n++; } if(hasDiaryJoin){ n = 0; while(n < projection.length) { if(ActivityDiaryContract.DiaryActivity._ID.equals(projection[n])){ projection[n] = ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID; } n++; } selection = selection.replaceAll(" " + ActivityDiaryContract.DiaryActivity._ID, " " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID); selection = selection.replaceAll(ActivityDiaryContract.DiaryActivity._DELETED, ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._DELETED); tables = tables + ", " + ActivityDiaryContract.Diary.TABLE_NAME; tables = tables + ", (SELECT xx_ref, " + ActivityDiaryContract.Diary.START + " as xx_start FROM " + ActivityDiaryContract.Diary.TABLE_NAME + "," + "(SELECT " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + " AS xx_ref," + " MAX(" + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.END + ") AS xx_ref_end" + " FROM " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + ", " + ActivityDiaryContract.Diary.TABLE_NAME + " WHERE " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.ACT_ID + " = " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + " GROUP BY " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + ")" + " WHERE " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.END + " = xx_ref_end" + ")" ; selection = selection + " AND " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + " = " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.ACT_ID + " AND " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + " = xx_ref"; grouping = ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID; } qBuilder.setTables(tables); break; case diary_image_ID: /* intended fall through */ case diary_image: qBuilder.setTables(ActivityDiaryContract.DiaryImage.TABLE_NAME); if (TextUtils.isEmpty(sortOrder)) sortOrder = ActivityDiaryContract.DiaryImage.SORT_ORDER_DEFAULT; break; case diary_location_ID: /* intended fall through */ case diary_location: qBuilder.setTables(ActivityDiaryContract.DiaryLocation.TABLE_NAME); if (TextUtils.isEmpty(sortOrder)) sortOrder = ActivityDiaryContract.DiaryLocation.SORT_ORDER_DEFAULT; break; case diary_ID: /* intended fall through */ case diary: /* rewrite projection, to prefix with tables */ qBuilder.setTables(ActivityDiaryContract.Diary.TABLE_NAME + " INNER JOIN " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + " ON " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.ACT_ID + " = " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID ); if (TextUtils.isEmpty(sortOrder)) sortOrder = ActivityDiaryContract.Diary.SORT_ORDER_DEFAULT; break; case diary_stats: useRawQuery = true; List<String> l = uri.getPathSegments(); String start; String end; if(l.size() == 3){ // we have a range query with start and end timestamps here start = l.get(1); end = l.get(2); }else{ start = "0"; end = "6156000000000"; // this is roughly 200 year since epoch, congratulations if this lasted so long... } String subselect = "SELECT SUM(MIN(IFNULL(" + ActivityDiaryContract.Diary.END + ",strftime('%s','now') * 1000), " + end + ") - " + "MAX(" + ActivityDiaryContract.Diary.START + ", " + start + ")) from " + ActivityDiaryContract.Diary.TABLE_NAME + " WHERE ((start >= " + start + " AND start < " + end + ") OR (end > " + start + " AND end <= " + end + ") OR (start < " + start + " AND end > " + end + "))"; if (selection != null && selection.length() > 0) { subselect += " AND (" + selection + ")"; } sql = "SELECT " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity.NAME + " as " + ActivityDiaryContract.DiaryStats.NAME + ", " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity.COLOR + " as " + ActivityDiaryContract.DiaryStats.COLOR + ", SUM(MIN(IFNULL(" + ActivityDiaryContract.Diary.END + ",strftime('%s','now') * 1000), " + end + ") - MAX(" + start + ", " + ActivityDiaryContract.Diary.START + ")) as " + ActivityDiaryContract.DiaryStats.DURATION + ", (SUM(MIN(IFNULL(" + ActivityDiaryContract.Diary.END + ",strftime('%s','now') * 1000), " + end + ") - MAX(" + start + ", " + ActivityDiaryContract.Diary.START + ")) * 100.0 " + "/ (" + subselect + ")) as " + ActivityDiaryContract.DiaryStats.PORTION + " FROM " + ActivityDiaryContract.Diary.TABLE_NAME + ", " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + " WHERE " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary.ACT_ID + " = " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID + " AND" + " ((start >= " + start + " AND start < " + end + ") OR (end > " + start + " AND end <= " + end + ") OR (start < " + start + " AND end > " + end + "))" ; if(selection != null && selection.length() > 0) { sql += " AND (" + selection + ")"; String[] newArgs = Arrays.copyOf(selectionArgs, selectionArgs.length * 2); System.arraycopy(selectionArgs, 0, newArgs, selectionArgs.length, selectionArgs.length); selectionArgs = newArgs; } sql += " GROUP BY " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + "." + ActivityDiaryContract.DiaryActivity._ID; if (sortOrder != null && sortOrder.length() > 0) { sql += " ORDER by " + sortOrder; } break; case search_recent_suggestion: sql = "SELECT " + ActivityDiaryContract.DiarySearchSuggestion.SUGGESTION + ", " + ActivityDiaryContract.DiarySearchSuggestion.ACTION + " FROM " + ActivityDiaryContract.DiarySearchSuggestion.TABLE_NAME + " ORDER BY " + ActivityDiaryContract.DiarySearchSuggestion._ID + " DESC"; c = mOpenHelper.getReadableDatabase().rawQuery(sql, selectionArgs); if (c != null && c.moveToFirst()) { do { Object icon = null; String action = c.getString(1); String q = c.getString(0); // what do we want to display if(action.equals(SEARCH_ACTIVITY)) { /* icon stays null */ int i = Integer.parseInt(q); q = ActivityHelper.helper.activityWithId(i).getName(); }else if(action.equals(SEARCH_NOTE)){ q = getContext().getResources().getString(R.string.search_notes, q); icon = R.drawable.ic_search; }else if(action.equals(SEARCH_GLOBAL) || action.equals(Intent.ACTION_SEARCH)){ q = getContext().getResources().getString(R.string.search_diary, q); icon = R.drawable.ic_search; }else if(action.equals(SEARCH_DATE)){ q = getContext().getResources().getString(R.string.search_date, q); icon = R.drawable.ic_calendar; } result.addRow(new Object[]{id++, q, /* icon */ icon, /* intent action */ action, /* intent data */ Uri.withAppendedPath(SEARCH_URI, c.getString(0)), /* rewrite query */c.getString(0) }); } while (c.moveToNext()); } return result; case search_suggestion: String query = uri.getLastPathSegment(); //.toLowerCase(); if (query != null && query.length() > 0) { // activities matching the current search ArrayList<DiaryActivity> filtered = ActivityHelper.helper.sortedActivities(query); // TODO: make the amount of activities shown configurable for (int i = 0; i < 3; i++) { if (i < filtered.size()) { result.addRow(new Object[]{id++, filtered.get(i).getName(), /* icon */ null, /* intent action */ SEARCH_ACTIVITY, /* intent data */ Uri.withAppendedPath(SEARCH_URI, Integer.toString(filtered.get(i).getId())), /* rewrite query */filtered.get(i).getName() }); } } // Notes result.addRow(new Object[]{id++, getContext().getResources().getString(R.string.search_notes, query), /* icon */ R.drawable.ic_search, /* intent action */ SEARCH_NOTE, /* intent data */ Uri.withAppendedPath(SEARCH_URI, query), /* rewrite query */ query }); // Global search result.addRow(new Object[]{id++, getContext().getResources().getString(R.string.search_diary, query), /* icon */ R.drawable.ic_search, /* intent action */ SEARCH_GLOBAL, /* intent data */ Uri.withAppendedPath(SEARCH_URI, query), /* rewrite query */ query }); // Date result.addRow(new Object[]{id++, getContext().getResources().getString(R.string.search_date, query), /* icon */ R.drawable.ic_calendar, /* intent action */ SEARCH_DATE, /* intent data */ Uri.withAppendedPath(SEARCH_URI, query), /* rewrite query */ query }); // has Pictures // TODO: add picture search // Location (GPS) // TODO: add location search } return result; case conditions_ID: /* intended fall through */ case conditions: // qBuilder.setTables(ActivityDiaryContract.Condition.TABLE_NAME); /* TODO #18 if (TextUtils.isEmpty(sortOrder)) sortOrder = ActivityDiaryContract.Conditions.SORT_ORDER_DEFAULT; */ default: /* empty */ } if (useRawQuery) { c = mOpenHelper.getReadableDatabase().rawQuery(sql, selectionArgs); } else { c = qBuilder.query(mOpenHelper.getReadableDatabase(), projection, selection, selectionArgs, grouping, null, sortOrder); } c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Nullable @Override public String getType(@NonNull Uri uri) { switch (sUriMatcher.match(uri)) { case activities: return ActivityDiaryContract.DiaryActivity.CONTENT_TYPE; case activities_ID: return ActivityDiaryContract.DiaryActivity.CONTENT_ITEM_TYPE; case diary: return ActivityDiaryContract.Diary.CONTENT_TYPE; case diary_ID: return ActivityDiaryContract.Diary.CONTENT_ITEM_TYPE; case diary_location: return ActivityDiaryContract.DiaryLocation.CONTENT_TYPE; case diary_location_ID: return ActivityDiaryContract.DiaryLocation.CONTENT_ITEM_TYPE; case diary_stats: return ActivityDiaryContract.DiaryStats.CONTENT_TYPE; // TODO #18: add other types default: Log.e(TAG, "MIME type for " + uri + " not defined."); return ""; } } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { String table; Uri resultUri; switch (sUriMatcher.match(uri)) { case activities: table = ActivityDiaryContract.DiaryActivity.TABLE_NAME; resultUri = ActivityDiaryContract.DiaryActivity.CONTENT_URI; break; case diary: table = ActivityDiaryContract.Diary.TABLE_NAME; resultUri = ActivityDiaryContract.Diary.CONTENT_URI; break; case diary_image: table = ActivityDiaryContract.DiaryImage.TABLE_NAME; resultUri = ActivityDiaryContract.DiaryImage.CONTENT_URI; break; case diary_location: table = ActivityDiaryContract.DiaryLocation.TABLE_NAME; resultUri = ActivityDiaryContract.DiaryLocation.CONTENT_URI; break; case diary_suggestion: table = ActivityDiaryContract.DiarySearchSuggestion.TABLE_NAME; resultUri = ActivityDiaryContract.DiarySearchSuggestion.CONTENT_URI; break; case conditions: // table = ActivityDiaryContract.Condition.TABLE_NAME; // TODO #18 resultUri = ActivityDiaryContract.Condition.CONTENT_URI; // break; case diary_stats: /* intended fall-through */ default: throw new IllegalArgumentException( "Unsupported URI for insertion: " + uri); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long id = db.insertOrThrow(table, null, values); if(id > 0) { resultUri = ContentUris.withAppendedId(resultUri, id); getContext(). getContentResolver(). notifyChange(resultUri, null); return resultUri; } else { throw new SQLException( "Problem while inserting into uri: " + uri + " values " + values.toString()); } } /** * Implement this to handle requests to delete one or more rows. * The implementation should apply the selection clause when performing * deletion, allowing the operation to affect multiple rows in a directory. * As a courtesy, call ContentResolver#notifyChange(Uri, ContentObserver) notifyChange() * after deleting. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * <p> * <p>The implementation is responsible for parsing out a row ID at the end * of the URI, if a specific row is being deleted. That is, the client would * pass in <code>content://contacts/people/22</code> and the implementation is * responsible for parsing the record number (22) when creating a SQL statement. * * @param uri The full URI to query, including a row ID (if a specific record is requested). * @param selection An optional restriction to apply to rows when deleting. * @param selectionArgs * @return The number of rows affected. * @throws SQLException */ @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { boolean isGlobalDelete = false; String table; ContentValues values = new ContentValues(); switch (sUriMatcher.match(uri)) { case activities_ID: table = ActivityDiaryContract.DiaryActivity.TABLE_NAME; break; case diary: isGlobalDelete = true; /* fall though */ case diary_ID: table = ActivityDiaryContract.Diary.TABLE_NAME; break; case diary_image: isGlobalDelete = true; /* fall though */ case diary_image_ID: table = ActivityDiaryContract.DiaryImage.TABLE_NAME; break; case diary_location: isGlobalDelete = true; /* fall though */ case diary_location_ID: table = ActivityDiaryContract.DiaryLocation.TABLE_NAME; break; case diary_suggestion: table = ActivityDiaryContract.DiarySearchSuggestion.TABLE_NAME; SQLiteDatabase db = mOpenHelper.getWritableDatabase(); return db.delete(table, selection, selectionArgs); case conditions_ID: // table = ActivityDiaryContract.Condition.TABLE_NAME; // break; case diary_stats: /* intended fall-through */ default: throw new IllegalArgumentException( "Unsupported URI for deletion: " + uri); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if (!isGlobalDelete) { if (selection != null) { selection = selection + " AND "; } else { selection = ""; } selection = selection + "_id=" + uri.getLastPathSegment(); } values.put(ActivityDiaryContract.DiaryActivity._DELETED, "1"); int upds = db.update(table, values, selection, selectionArgs); if (upds > 0) { getContext(). getContentResolver(). notifyChange(uri, null); } else { Log.i(TAG, "Could not delete anything for uri: " + uri + " with selection '" + selection + "'"); } return upds; } /** * Implement this to handle requests to update one or more rows. * The implementation should update all rows matching the selection * to set the columns according to the provided values map. * As a courtesy, call ContentResolver#notifyChange(Uri, ContentObserver) notifyChange() * after updating. * This method can be called from multiple threads, as described in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes * and Threads</a>. * * @param uri The URI to query. This can potentially have a record ID if this * is an update request for a specific record. * @param values A set of column_name/value pairs to update in the database. * This must not be {@code null}. * @param selection An optional filter to match rows to update. * @param selectionArgs * @return the number of rows affected. */ @Override public int update(@NonNull Uri uri, @NonNull ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { String table; boolean isID = false; switch (sUriMatcher.match(uri)) { case activities_ID: isID = true; table = ActivityDiaryContract.DiaryActivity.TABLE_NAME; break; case diary_ID: isID = true; case diary: table = ActivityDiaryContract.Diary.TABLE_NAME; break; case diary_image: table = ActivityDiaryContract.DiaryImage.TABLE_NAME; break; case diary_location_ID: isID = true; case diary_location: table = ActivityDiaryContract.DiaryLocation.TABLE_NAME; break; case conditions_ID: isID = true; // table = ActivityDiaryContract.Condition.TABLE_NAME; // break; case diary_stats: /* intended fall-through */ default: throw new IllegalArgumentException( "Unsupported URI for update: " + uri); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if (isID) { if (selection != null) { selection = selection + " AND "; } else { selection = ""; } selection = selection + "_id=" + uri.getLastPathSegment(); } int upds = db.update(table, values, selection, selectionArgs); if (upds > 0) { getContext(). getContentResolver(). notifyChange(uri, null); } else if (isID) { throw new SQLException( "Problem while updating uri: " + uri + " with selection '" + selection + "'"); } return upds; } public void resetDatabase() { mOpenHelper.close(); } /** * Search for all dates in database which match start/end date or are in range (between start and end date) * @param dateInMillis - date is searched * @return query (string) with ids that fulfills defined conditions */ public String searchDate(Long dateInMillis) { // TODO: move this into the method query, for the case diary, // similar to diary_stats, we can modify selection and selection args there // or maybe better, invent a new URI like "diary/number" where number is the dateInMillis // Alternative: move all this directly into HistoryActivity.onCreateLoader String querySelection = " ", id; long searchedValue = dateInMillis; long searchedValuePlusDay = searchedValue + 86400000; // TODO: replace magic numbers by the formula to calculate them... long searchSpecialCase = searchedValue + 86399999; //used for searching for still running activity Cursor allRowsStart = null; try { // TODO: -> this query should not be executed outside of the method ActivityDiaryContentProvider.query allRowsStart = mOpenHelper.getReadableDatabase().rawQuery( "SELECT " + ActivityDiaryContract.Diary._ID + " FROM " + ActivityDiaryContract.Diary.TABLE_NAME + " WHERE " + "(" + searchedValue + " >= " + ActivityDiaryContract.Diary.START + " AND " + searchedValue + " <= " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchedValuePlusDay + " >= " + ActivityDiaryContract.Diary.START + " AND " + searchedValuePlusDay + " <= " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchedValue + " < " + ActivityDiaryContract.Diary.START + " AND " + searchedValuePlusDay + " > " + ActivityDiaryContract.Diary.END + ")" + " OR " + "(" + searchSpecialCase + " >= " + ActivityDiaryContract.Diary.START + " AND " + ActivityDiaryContract.Diary.END + " IS NULL" + ")", null); if (allRowsStart.moveToFirst()) { do { for (String name : allRowsStart.getColumnNames()) { id = (allRowsStart.getString(allRowsStart.getColumnIndex(name))); querySelection += querySelection.equals(" ") ? ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary._ID + " =" + id : " OR " + ActivityDiaryContract.Diary.TABLE_NAME + "." + ActivityDiaryContract.Diary._ID + " =" + id ; } } while (allRowsStart.moveToNext()); } } catch (Exception e) { // TODO: add proper exception handling. Also "Exception" seems quite generic -> catch all exceptions that can occur directly }finally{ if(allRowsStart != null){ allRowsStart.close(); } } // if there is no matching dates it returns query which links to find nothings // otherwise it will return query with IDs of matching dates return querySelection.equals(" ") ? " start=null" : querySelection; } public static int countSleepActivitiesInLast24Hours() { int count = 0; // if(mOpenHelper == null)onCreate(); SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和24小时前的时间戳 long currentTime = System.currentTimeMillis(); long oneDayAgo = currentTime - 86400000; // 构建查询 String query = "SELECT COUNT(*) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(oneDayAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { count = cursor.getInt(0); } cursor.close(); return count; } public static int countSleepActivitiesInLast48Hours() { int count = 0; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和48小时前的时间戳 long currentTime = System.currentTimeMillis(); long twoDaysAgo = currentTime - (2 * 86400000); // 2天的毫秒数 // 构建查询 String query = "SELECT COUNT(*) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(twoDaysAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { count = cursor.getInt(0); } cursor.close(); return count; } public static int getTotalSleepHoursInLastWeek() { int totalHours = 0; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获取当前时间和一周前的时间戳 long currentTime = System.currentTimeMillis(); long oneWeekAgo = currentTime - (7 * 86400000); // 7天的毫秒数 // 构建查询来计算总睡眠时间 String query = "SELECT SUM(d.'end' - d.start) FROM diary d " + "JOIN activity a ON d.act_id = a._id " + "WHERE d.start >= ? AND d.'end' <= ? AND a.name = 'Sleeping' AND a._deleted = 0"; // 执行查询 Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(oneWeekAgo), String.valueOf(currentTime) }); // 处理结果 if (cursor.moveToFirst()) { // 将毫秒转换为小时 totalHours = cursor.getInt(0) / (3600000); } cursor.close(); return totalHours; }
public static List<Achievement> getAllAchievements() {
1
2023-12-02 12:36:40+00:00
12k
RabbitHareLu/K-Tools
frontend/src/main/java/com/ktools/frontend/frame/JDBCConnectionFrame.java
[ { "identifier": "KToolsContext", "path": "warehouse/src/main/java/com/ktools/warehouse/KToolsContext.java", "snippet": "@Getter\npublic class KToolsContext {\n\n private static volatile KToolsContext INSTANCE;\n\n private final MybatisContext mybatisContext;\n\n private final Properties propert...
import com.ktools.warehouse.KToolsContext; import com.ktools.frontend.action.CancelDisposeFrameAction; import com.ktools.frontend.action.TestConnectionAction; import com.ktools.frontend.action.TreeJDBCNodeAction; import com.ktools.warehouse.api.DataSourceApi; import com.ktools.frontend.common.utils.BoxUtil; import com.ktools.frontend.component.ImageLoad; import com.ktools.frontend.component.Tree; import com.ktools.warehouse.exception.KToolException; import com.ktools.warehouse.manager.datasource.model.KDataSourceMetadata; import com.ktools.warehouse.mybatis.entity.TreeEntity; import com.ktools.frontend.panel.AdvancedPanel; import com.ktools.frontend.panel.RegularPanel; import lombok.Data; import lombok.extern.slf4j.Slf4j; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.*; import java.util.Objects;
7,221
package com.ktools.frontend.frame; /** * @author lsl * @version 1.0 * @date 2023年12月18日 17:34 */ @Slf4j @Data public class JDBCConnectionFrame extends JFrame { public static boolean openFlag = true; private static final int WIDTH = 600; private static final int HEIGHT = 700; private KDataSourceMetadata kDataSourceMetadata; private TreeEntity treeEntity; private TreePath treePath; private RegularPanel regularPanel; private AdvancedPanel advancedPanel; private JTextField nameField; private JTextField commentField; public JDBCConnectionFrame() { Tree instance = Tree.getInstance(); this.treePath = instance.getCurrentTreePath(); this.treeEntity = instance.getCurrentTreeEntity(treePath); try { this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType()); } catch (KToolException e) { throw new RuntimeException(e); } setTitle("编辑" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initEdit(); frameEndInit(); } public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) { Tree instance = Tree.getInstance(); this.kDataSourceMetadata = kDataSourceMetadata; this.treePath = instance.getCurrentTreePath(); setTitle("新建" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initNew(); frameEndInit(); } private void frameStartInit() { openFlag = false;
package com.ktools.frontend.frame; /** * @author lsl * @version 1.0 * @date 2023年12月18日 17:34 */ @Slf4j @Data public class JDBCConnectionFrame extends JFrame { public static boolean openFlag = true; private static final int WIDTH = 600; private static final int HEIGHT = 700; private KDataSourceMetadata kDataSourceMetadata; private TreeEntity treeEntity; private TreePath treePath; private RegularPanel regularPanel; private AdvancedPanel advancedPanel; private JTextField nameField; private JTextField commentField; public JDBCConnectionFrame() { Tree instance = Tree.getInstance(); this.treePath = instance.getCurrentTreePath(); this.treeEntity = instance.getCurrentTreeEntity(treePath); try { this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType()); } catch (KToolException e) { throw new RuntimeException(e); } setTitle("编辑" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initEdit(); frameEndInit(); } public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) { Tree instance = Tree.getInstance(); this.kDataSourceMetadata = kDataSourceMetadata; this.treePath = instance.getCurrentTreePath(); setTitle("新建" + kDataSourceMetadata.getName() + "连接"); frameStartInit(); initNew(); frameEndInit(); } private void frameStartInit() { openFlag = false;
setIconImage(ImageLoad.getInstance().buildIcon(kDataSourceMetadata.getLogo()).getImage());
6
2023-11-30 03:26:25+00:00
12k
ChrisGenti/VPL
velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java
[ { "identifier": "PluginCommand", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/PluginCommand.java", "snippet": "public interface PluginCommand extends SimpleCommand {\n String name();\n\n default String usage() { return \"/\" + this.name(); };\n}" }, { "identi...
import com.github.chrisgenti.vpl.velocity.commands.PluginCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.VPLCommand; import com.github.chrisgenti.vpl.velocity.commands.user.PremiumCommand; import com.github.chrisgenti.vpl.velocity.configurations.config.ConfigFile; import com.github.chrisgenti.vpl.velocity.configurations.language.LanguageFile; import com.github.chrisgenti.vpl.velocity.data.DataProvider; import com.github.chrisgenti.vpl.velocity.data.mysql.MySQLProvider; import com.github.chrisgenti.vpl.velocity.listeners.Listener; import com.github.chrisgenti.vpl.velocity.listeners.chat.ChatListener; import com.github.chrisgenti.vpl.velocity.listeners.command.CommandListener; import com.github.chrisgenti.vpl.velocity.listeners.disconnect.DisconnectListener; import com.github.chrisgenti.vpl.velocity.listeners.login.PreLoginListener; import com.github.chrisgenti.vpl.velocity.listeners.login.post.PostLoginListener; import com.github.chrisgenti.vpl.velocity.listeners.message.PluginMessageListener; import com.github.chrisgenti.vpl.velocity.listeners.profile.ProfileRequestListener; import com.github.chrisgenti.vpl.velocity.listeners.server.InitialServerListener; import com.github.chrisgenti.vpl.velocity.listeners.tab.TabCompleteListener; import com.github.chrisgenti.vpl.velocity.players.PlayerManager; import com.github.chrisgenti.vpl.velocity.servers.ServerManager; import com.github.chrisgenti.vpl.velocity.tasks.PluginTask; import com.github.chrisgenti.vpl.velocity.tasks.register.RegisterTask; import com.google.inject.Inject; import com.velocitypowered.api.command.CommandManager; import com.velocitypowered.api.command.CommandMeta; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.event.EventManager; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.api.proxy.messages.LegacyChannelIdentifier; import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier; import lombok.Getter; import net.kyori.adventure.text.minimessage.MiniMessage; import org.slf4j.Logger; import java.io.File; import java.nio.file.Path; import java.util.Arrays;
10,283
package com.github.chrisgenti.vpl.velocity; @Plugin( id = "vpl", name = "VPL", version = "1.0.0", description = "", authors = {"ChrisGenti"} ) @Getter public class VPLPlugin { public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main"); public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main"); @Inject private ProxyServer proxy; @Inject private Logger logger; @Inject private EventManager eventManager; @Inject @DataDirectory Path directory; private ConfigFile configFile; private LanguageFile languageFile; private PlayerManager playerManager; private ServerManager serverManager; private DataProvider provider; private PluginTask registerTask; @Subscribe public void onInitialization(ProxyInitializeEvent event) { /* * FILES */ this.configFile = new ConfigFile(directory.toFile(), "config.toml"); this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE); /* * SETUP MESSAGE */ this.sendMessage( "<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>" ); /* * MANAGERS */ this.playerManager = new PlayerManager(); this.serverManager = new ServerManager(this); /* * PROVIDERS */ this.provider = new MySQLProvider(this, configFile.CREDENTIALS); this.provider.init(); /* * COMMANDS */ this.registerCommands( new VPLCommand(this), new PremiumCommand(this) ); /* * LISTENERS */ this.registerListeners( new PluginMessageListener(this), new ChatListener(this), new CommandListener(this), new TabCompleteListener(this),
package com.github.chrisgenti.vpl.velocity; @Plugin( id = "vpl", name = "VPL", version = "1.0.0", description = "", authors = {"ChrisGenti"} ) @Getter public class VPLPlugin { public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main"); public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main"); @Inject private ProxyServer proxy; @Inject private Logger logger; @Inject private EventManager eventManager; @Inject @DataDirectory Path directory; private ConfigFile configFile; private LanguageFile languageFile; private PlayerManager playerManager; private ServerManager serverManager; private DataProvider provider; private PluginTask registerTask; @Subscribe public void onInitialization(ProxyInitializeEvent event) { /* * FILES */ this.configFile = new ConfigFile(directory.toFile(), "config.toml"); this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE); /* * SETUP MESSAGE */ this.sendMessage( "<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>" ); /* * MANAGERS */ this.playerManager = new PlayerManager(); this.serverManager = new ServerManager(this); /* * PROVIDERS */ this.provider = new MySQLProvider(this, configFile.CREDENTIALS); this.provider.init(); /* * COMMANDS */ this.registerCommands( new VPLCommand(this), new PremiumCommand(this) ); /* * LISTENERS */ this.registerListeners( new PluginMessageListener(this), new ChatListener(this), new CommandListener(this), new TabCompleteListener(this),
new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this)
14
2023-11-28 10:12:04+00:00
12k
Ethylene9160/Chess
src/chess/panels/GamePanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import chess.pieces.Chess; import chess.recorder.Loader; import chess.recorder.Record; import chess.recorder.Saver; import chess.util.Constants; import chess.util.ImagePath; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.ArrayList; import static java.awt.event.KeyEvent.VK_A; import static java.awt.event.KeyEvent.VK_E;
7,588
package chess.panels; public class GamePanel extends PanelBase implements ActionListener, MouseListener, KeyListener { @Override public void init() { super.init(); creatChess(Chess.FIRST_COLOR); } // private int[] xs, ys; public GamePanel(JLabel hint) { type = PanelType.Local; this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! addKeyListener(this); } @Override public void paint(Graphics g) { super.paint(g);//clear
package chess.panels; public class GamePanel extends PanelBase implements ActionListener, MouseListener, KeyListener { @Override public void init() { super.init(); creatChess(Chess.FIRST_COLOR); } // private int[] xs, ys; public GamePanel(JLabel hint) { type = PanelType.Local; this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! addKeyListener(this); } @Override public void paint(Graphics g) { super.paint(g);//clear
this.setBounds(0, 0, Constants.FRAME_LENGTH - 200, Constants.FRAME_HEIGHT);
4
2023-12-01 02:33:32+00:00
12k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/parser/Parser.java
[ { "identifier": "AssignStatement", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/AssignStatement.java", "snippet": "public class AssignStatement extends Statement {\n\n private final String leftHand;\n private final Expression rightHand;\n\n public AssignStatement(String leftHand,...
import java.util.ArrayList; import java.util.List; import org.vectorlang.compiler.ast.AssignStatement; import org.vectorlang.compiler.ast.BinaryExpression; import org.vectorlang.compiler.ast.BinaryOperator; import org.vectorlang.compiler.ast.BlockStatement; import org.vectorlang.compiler.ast.CallExpression; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.ast.DeclareStatement; import org.vectorlang.compiler.ast.Expression; import org.vectorlang.compiler.ast.ForStatement; import org.vectorlang.compiler.ast.FunctionStatement; import org.vectorlang.compiler.ast.GroupingExpression; import org.vectorlang.compiler.ast.IdentifierExpression; import org.vectorlang.compiler.ast.IfStatement; import org.vectorlang.compiler.ast.IndexExpression; import org.vectorlang.compiler.ast.LiteralExpression; import org.vectorlang.compiler.ast.PrintStatement; import org.vectorlang.compiler.ast.ReturnStatement; import org.vectorlang.compiler.ast.Statement; import org.vectorlang.compiler.ast.UnaryExpression; import org.vectorlang.compiler.ast.UnaryOperator; import org.vectorlang.compiler.ast.VectorExpression; import org.vectorlang.compiler.ast.WhileStatement; import org.vectorlang.compiler.compiler.BaseType; import org.vectorlang.compiler.compiler.Type;
7,241
Expression expression = equality.apply(state); while (state.matches(TokenType.AMPERSAND)) { expression = new BinaryExpression(expression, equality.apply(state), BinaryOperator.AND); } return expression; } private Expression equality(ParserState state) { Expression expression = comparison.apply(state); while (state.matches(new TokenType[]{TokenType.EQUALS_EQUALS, TokenType.BANG_EQUALS})) { BinaryOperator operator = switch (state.previous().type()) { case EQUALS_EQUALS -> BinaryOperator.EQUAL; case BANG_EQUALS -> BinaryOperator.NOT_EQUAL; default -> null; }; expression = new BinaryExpression(expression, comparison.apply(state), operator); } return expression; } private GroupingExpression groupingExpression(ParserState state) { state.consume(TokenType.OPEN_PAREN); Expression expr = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); return new GroupingExpression(expr); } private VectorExpression vectorExpression(ParserState state) { List<Expression> expressions = new ArrayList<>(); state.consume(TokenType.OPEN_BRACKET); do { expressions.add(expression.apply(state)); } while (state.matches(TokenType.COMMA)); state.consume(TokenType.CLOSE_BRACKET); return new VectorExpression(expressions.toArray(new Expression[0])); } private ForStatement forStatement(ParserState state) { state.consume(TokenType.FOR); state.consume(TokenType.OPEN_PAREN); Statement initial = statement.apply(state); Expression condition = expression.apply(state); state.consume(TokenType.SEMICOLON); Statement each = assignStatement2.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new ForStatement(condition, initial, each, body); } private WhileStatement whileStatement(ParserState state) { state.consume(TokenType.WHILE); state.consume(TokenType.OPEN_PAREN); Expression condition = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new WhileStatement(condition, body); } private AssignStatement assignStatement(ParserState state, boolean semicolon) { state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); } else if (state.matches(TokenType.PLUS_PLUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.ADD ); } else if (state.matches(TokenType.MINUS_MINUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.SUBTRACT ); } else { BinaryOperator operator = null; if (state.matches(TokenType.PLUS_EQUALs)) { operator = BinaryOperator.ADD; } else if (state.matches(TokenType.MINUS_EQUALS)) { operator = BinaryOperator.SUBTRACT; } else if (state.matches(TokenType.STAR_EQUALS)) { operator = BinaryOperator.MULTIPLY; } else if (state.matches(TokenType.SLASH_EQUALS)) { operator = BinaryOperator.DIVIDE; } else if (state.matches(TokenType.BAR_EQUALS)) { operator = BinaryOperator.OR; } else if (state.matches(TokenType.AMPERSAND_EQUALS)) { operator = BinaryOperator.AND; } else { return null; } expr = new BinaryExpression( new IdentifierExpression(name), expression.apply(state), operator); } if (semicolon) { state.consume(TokenType.SEMICOLON); } return new AssignStatement(name, expr); } private Statement statement(ParserState state) { if (state.matches(TokenType.OPEN_BRACE)) { List<Statement> statements = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new BlockStatement(statements.toArray(new Statement[0])); } else if (state.matches(TokenType.PRINT)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new PrintStatement(expr); } else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) { boolean constant = state.previous().type() == TokenType.CONST; state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); }
package org.vectorlang.compiler.parser; public class Parser { private ParseRule<Expression> literalExpression, identifierExpression, value, unary, indexedValue, factor, term, comparison, equality, and, or, groupingExpression, vectorExpression, expression; private ParseRule<Statement> forStatement, whileStatement, assignStatement, assignStatement2, statement; private ParseRule<FunctionStatement> function; public Parser() { literalExpression = new ParseRule<>(this::literalExpression, TokenType.SEMICOLON); identifierExpression = new ParseRule<>(this::identifierExpression, TokenType.SEMICOLON); value = new ParseRule<>(this::value, TokenType.SEMICOLON); unary = new ParseRule<>(this::unary, TokenType.SEMICOLON); indexedValue = new ParseRule<>(this::indexedValue, TokenType.SEMICOLON); factor = new ParseRule<>(this::factor, TokenType.SEMICOLON); term = new ParseRule<>(this::term, TokenType.SEMICOLON); comparison = new ParseRule<>(this::comparison, TokenType.SEMICOLON); equality = new ParseRule<>(this::equality, TokenType.SEMICOLON); and = new ParseRule<>(this::and, TokenType.SEMICOLON); or = new ParseRule<>(this::or, TokenType.SEMICOLON); groupingExpression = new ParseRule<>(this::groupingExpression, TokenType.SEMICOLON); vectorExpression = new ParseRule<>(this::vectorExpression, TokenType.SEMICOLON); expression = or; forStatement = new ParseRule<>(this::forStatement, TokenType.CLOSE_BRACE); whileStatement = new ParseRule<>(this::whileStatement, TokenType.CLOSE_BRACE); assignStatement = new ParseRule<>((ParserState state) -> assignStatement(state, true), TokenType.SEMICOLON); assignStatement2 = new ParseRule<>((ParserState state) -> assignStatement(state, false), TokenType.SEMICOLON); statement = new ParseRule<>(this::statement, TokenType.CLOSE_BRACE); function = new ParseRule<>(this::function, TokenType.CLOSE_BRACE); } private LiteralExpression literalExpression(ParserState state) { if (state.matches(TokenType.TRUE)) { return new LiteralExpression(true); } else if (state.matches(TokenType.FALSE)) { return new LiteralExpression(false); } else if (state.matches(TokenType.INT_LITERAL)) { return new LiteralExpression(Integer.parseInt(state.previous().value())); } else if (state.matches(TokenType.FLOAT_LITERAL)) { return new LiteralExpression(Double.parseDouble(state.previous().value())); } else { return null; } } private Expression identifierExpression(ParserState state) { state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); if (state.matches(TokenType.OPEN_PAREN)) { boolean flag = false; List<Expression> expressions = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_PAREN)) { if (flag) { state.consume(TokenType.COMMA); } expressions.add(expression.apply(state)); flag = true; } return new CallExpression(name, expressions.toArray(new Expression[0]), null); } return new IdentifierExpression(name); } private Expression value(ParserState state) { if (state.peek().type() == TokenType.OPEN_PAREN) { return groupingExpression.apply(state); } else if (state.peek().type() == TokenType.IDENTIFIER) { return identifierExpression.apply(state); } else if (state.peek().type() == TokenType.OPEN_BRACKET) { return vectorExpression.apply(state); } else { return literalExpression.apply(state); } } private Expression indexedValue(ParserState state) { Expression expr = value.apply(state); while (state.matches(TokenType.OPEN_BRACKET)) { Expression index = expression.apply(state); expr = new IndexExpression(expr, index); state.consume(TokenType.CLOSE_BRACKET); } return expr; } private Expression unary(ParserState state) { if (state.matches(TokenType.BANG)) { return new UnaryExpression(unary.apply(state), UnaryOperator.NEGATE); } else if (state.matches(TokenType.DASH)) { return new UnaryExpression(unary.apply(state), UnaryOperator.INVERSE); } else { return indexedValue.apply(state); } } private Expression factor(ParserState state) { Expression expression = unary.apply(state); while (state.matches(new TokenType[]{TokenType.STAR, TokenType.SLASH, TokenType.DOT_STAR, TokenType.DOT_SLASH})) { BinaryOperator operator = switch (state.previous().type()) { case STAR -> BinaryOperator.MULTIPLY; case SLASH -> BinaryOperator.DIVIDE; case DOT_STAR -> BinaryOperator.DOT_MULTIPLY; case DOT_SLASH -> BinaryOperator.DOT_DIVIDE; case DOT_DOT -> BinaryOperator.CONCAT; default -> null; }; expression = new BinaryExpression(expression, unary.apply(state), operator); } return expression; } private Expression term(ParserState state) { Expression expression = factor.apply(state); while (state.matches(new TokenType[]{TokenType.PLUS, TokenType.DASH, TokenType.DOT_PLUS, TokenType.DOT_DASH})) { BinaryOperator operator = switch (state.previous().type()) { case PLUS -> BinaryOperator.ADD; case DASH -> BinaryOperator.SUBTRACT; case DOT_PLUS -> BinaryOperator.DOT_ADD; case DOT_DASH -> BinaryOperator.DOT_SUBTRACT; default -> null; }; expression = new BinaryExpression(expression, factor.apply(state), operator); } return expression; } private Expression comparison(ParserState state) { Expression expression = term.apply(state); while (state.matches(new TokenType[]{TokenType.LEFT_ARROW, TokenType.LEFT_ARROW_EQUALS, TokenType.RIGHT_ARROW, TokenType.RIGHT_ARROW_EQUALS})) { BinaryOperator operator = switch (state.previous().type()) { case LEFT_ARROW -> BinaryOperator.LESS_THAN; case RIGHT_ARROW -> BinaryOperator.GREATER_THAN; case LEFT_ARROW_EQUALS -> BinaryOperator.EQUAL_LESS_THAN; case RIGHT_ARROW_EQUALS -> BinaryOperator.EQUAL_GREATER_THAN; default -> null; }; expression = new BinaryExpression(expression, term.apply(state), operator); } return expression; } private Expression or(ParserState state) { Expression expression = and.apply(state); while (state.matches(TokenType.BAR)) { expression = new BinaryExpression(expression, and.apply(state), BinaryOperator.OR); } return expression; } private Expression and(ParserState state) { Expression expression = equality.apply(state); while (state.matches(TokenType.AMPERSAND)) { expression = new BinaryExpression(expression, equality.apply(state), BinaryOperator.AND); } return expression; } private Expression equality(ParserState state) { Expression expression = comparison.apply(state); while (state.matches(new TokenType[]{TokenType.EQUALS_EQUALS, TokenType.BANG_EQUALS})) { BinaryOperator operator = switch (state.previous().type()) { case EQUALS_EQUALS -> BinaryOperator.EQUAL; case BANG_EQUALS -> BinaryOperator.NOT_EQUAL; default -> null; }; expression = new BinaryExpression(expression, comparison.apply(state), operator); } return expression; } private GroupingExpression groupingExpression(ParserState state) { state.consume(TokenType.OPEN_PAREN); Expression expr = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); return new GroupingExpression(expr); } private VectorExpression vectorExpression(ParserState state) { List<Expression> expressions = new ArrayList<>(); state.consume(TokenType.OPEN_BRACKET); do { expressions.add(expression.apply(state)); } while (state.matches(TokenType.COMMA)); state.consume(TokenType.CLOSE_BRACKET); return new VectorExpression(expressions.toArray(new Expression[0])); } private ForStatement forStatement(ParserState state) { state.consume(TokenType.FOR); state.consume(TokenType.OPEN_PAREN); Statement initial = statement.apply(state); Expression condition = expression.apply(state); state.consume(TokenType.SEMICOLON); Statement each = assignStatement2.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new ForStatement(condition, initial, each, body); } private WhileStatement whileStatement(ParserState state) { state.consume(TokenType.WHILE); state.consume(TokenType.OPEN_PAREN); Expression condition = expression.apply(state); state.consume(TokenType.CLOSE_PAREN); Statement body = statement.apply(state); return new WhileStatement(condition, body); } private AssignStatement assignStatement(ParserState state, boolean semicolon) { state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); } else if (state.matches(TokenType.PLUS_PLUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.ADD ); } else if (state.matches(TokenType.MINUS_MINUS)) { expr = new BinaryExpression( new IdentifierExpression(name), new LiteralExpression(1), BinaryOperator.SUBTRACT ); } else { BinaryOperator operator = null; if (state.matches(TokenType.PLUS_EQUALs)) { operator = BinaryOperator.ADD; } else if (state.matches(TokenType.MINUS_EQUALS)) { operator = BinaryOperator.SUBTRACT; } else if (state.matches(TokenType.STAR_EQUALS)) { operator = BinaryOperator.MULTIPLY; } else if (state.matches(TokenType.SLASH_EQUALS)) { operator = BinaryOperator.DIVIDE; } else if (state.matches(TokenType.BAR_EQUALS)) { operator = BinaryOperator.OR; } else if (state.matches(TokenType.AMPERSAND_EQUALS)) { operator = BinaryOperator.AND; } else { return null; } expr = new BinaryExpression( new IdentifierExpression(name), expression.apply(state), operator); } if (semicolon) { state.consume(TokenType.SEMICOLON); } return new AssignStatement(name, expr); } private Statement statement(ParserState state) { if (state.matches(TokenType.OPEN_BRACE)) { List<Statement> statements = new ArrayList<>(); while (!state.matches(TokenType.CLOSE_BRACE)) { statements.add(statement.apply(state)); } return new BlockStatement(statements.toArray(new Statement[0])); } else if (state.matches(TokenType.PRINT)) { Expression expr = expression.apply(state); state.consume(TokenType.SEMICOLON); return new PrintStatement(expr); } else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) { boolean constant = state.previous().type() == TokenType.CONST; state.consume(TokenType.IDENTIFIER); String name = state.previous().value(); Expression expr = null; if (state.matches(TokenType.EQUALS)) { expr = expression.apply(state); }
Type type = type(state);
23
2023-11-30 04:22:36+00:00
12k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
9,704
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans;
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans;
private MainGame main_game;
9
2023-12-03 13:36:00+00:00
12k
godheaven/klib-data-jdbc
src/test/java/cl/kanopus/jdbc/impl/DAOTest.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.example.entity.TestData; import cl.kanopus.jdbc.util.SQLQueryDynamic; import java.util.HashMap; import java.util.List;
8,960
package cl.kanopus.jdbc.impl; public interface DAOTest extends DAOInterface<TestData, Long> { Integer queryForInteger(String sql, HashMap<String, ?> params); Long queryForLong(String sql, HashMap<String, ?> params); String queryForString(String sql, HashMap<String, ?> params); List<TestData> find(String sql, HashMap<String, ?> params);
package cl.kanopus.jdbc.impl; public interface DAOTest extends DAOInterface<TestData, Long> { Integer queryForInteger(String sql, HashMap<String, ?> params); Long queryForLong(String sql, HashMap<String, ?> params); String queryForString(String sql, HashMap<String, ?> params); List<TestData> find(String sql, HashMap<String, ?> params);
List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz);
1
2023-11-27 18:25:00+00:00
12k
victor-vilar/coleta
backend/src/main/java/com/victorvilar/projetoempresa/services/ContractService.java
[ { "identifier": "ContractCreateDto", "path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/contract/ContractCreateDto.java", "snippet": "public class ContractCreateDto {\n\n\n\n @NotBlank(message =\"The contract must have a number\")\n private String number;\n\n @NotNull(message = \...
import com.victorvilar.projetoempresa.dto.contract.ContractCreateDto; import com.victorvilar.projetoempresa.dto.contract.ContractResponseDto; import com.victorvilar.projetoempresa.dto.contract.ContractUpdateDto; import com.victorvilar.projetoempresa.dto.contract.ItemContractCreateDto; import com.victorvilar.projetoempresa.domain.Customer; import com.victorvilar.projetoempresa.enums.ContractStatus; import com.victorvilar.projetoempresa.exceptions.CustomerNotFoundException; import com.victorvilar.projetoempresa.exceptions.ContractNotFoundException; import com.victorvilar.projetoempresa.domain.Contract; import com.victorvilar.projetoempresa.domain.ItemContract; import com.victorvilar.projetoempresa.exceptions.ItemContractNotFoundException; import com.victorvilar.projetoempresa.mappers.ContractMapper; import com.victorvilar.projetoempresa.mappers.ItemContractMapper; import com.victorvilar.projetoempresa.repository.ContractRepository; import com.victorvilar.projetoempresa.repository.CustomerRepository; import com.victorvilar.projetoempresa.repository.ItemContractRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; import java.util.List;
8,767
package com.victorvilar.projetoempresa.services; @Service public class ContractService {
package com.victorvilar.projetoempresa.services; @Service public class ContractService {
private final ContractRepository contractRepository;
13
2023-12-02 21:29:33+00:00
12k
GiulianoVianna/Prototipo-Ferramenta-de-Backup-em-Java
src/main/java/com/mycompany/ferramentadebackup/view/FerramentaDeBackupView.java
[ { "identifier": "BancoDeDadosDAO", "path": "src/main/java/com/mycompany/ferramentadebackup/dao/BancoDeDadosDAO.java", "snippet": "public class BancoDeDadosDAO {\n\n // URL de conexão com o banco de dados SQLite\n String url = \"jdbc:sqlite:dados_backup.db\";\n\n // Lista para armazenar objetos ...
import com.mycompany.ferramentadebackup.dao.BancoDeDadosDAO; import com.mycompany.ferramentadebackup.dto.BancoDeDadosDTO; import com.mycompany.ferramentadebackup.compactadorzip.CompactadorZip; import javax.swing.*; import java.awt.*; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.Optional;
9,572
/** * Define o ícone da janela com base em um arquivo de imagem. * <p> * Este método carrega uma imagem de ícone da classe {@link ImageIcon} com o * caminho especificado. Em seguida, define essa imagem como o ícone da * janela atual usando {@link #setIconImage(java.awt.Image)}. * </p> * * <p> * <b>Nota:</b> Este método é usado para configurar o ícone da janela e não * retorna nenhum valor. * </p> */ private void iconeJanela() { ImageIcon icone = new ImageIcon(getClass().getClassLoader().getResource("images/iconeJanela.png")); setIconImage(icone.getImage()); } /** * Configura o estado dos botões da interface com base em parâmetros * booleanos. * <p> * Este método permite configurar o estado de vários botões da interface de * acordo com os valores booleanos fornecidos como parâmetros. Cada * parâmetro corresponde a um botão e define se ele deve estar habilitado * (true) ou desabilitado (false). * </p> * * @param diretorioOrigem Define se os botões de seleção de diretório de * origem devem estar habilitados. * @param diretorioDestino Define se os botões de seleção de diretório de * destino devem estar habilitados. * @param novo Define se o botão "Novo" deve estar habilitado. * @param atualizar Define se o botão "Atualizar" deve estar habilitado. * @param salvar Define se o botão "Salvar" deve estar habilitado. * @param editar Define se o botão "Editar" deve estar habilitado. * @param excluir Define se o botão "Excluir" deve estar habilitado. * @param cancelar Define se o botão "Cancelar" deve estar habilitado. */ public void configurarBotoes(boolean diretorioOrigem, boolean diretorioDestino, boolean novo, boolean atualizar, boolean salvar, boolean editar, boolean excluir, boolean cancelar) { btnSelecionarArquivoDiretorio.setEnabled(diretorioOrigem); btnSelecionarDiretorioDestino.setEnabled(diretorioOrigem); btnNovo.setEnabled(novo); btnAtualizar.setEnabled(atualizar); btnSalvar.setEnabled(salvar); btnEditar.setEnabled(editar); btnExcluir.setEnabled(excluir); btnCancelar.setEnabled(cancelar); } /** * Habilita ou desabilita campos da interface com base em parâmetros * booleanos. * <p> * Este método permite habilitar ou desabilitar vários campos da interface * com base nos valores booleanos fornecidos como parâmetros. Cada parâmetro * corresponde a um campo e define se ele deve estar habilitado (true) ou * desabilitado (false). * </p> * * @param arquivoDiretorio Define se o campo de arquivo/diretório deve estar * habilitado. * @param diretorio Define se o campo de diretório deve estar habilitado. * @param data Define se o campo de data deve estar habilitado. * @param nomeBackup Define se o campo de nome de backup deve estar * habilitado. * @param desligarPC Define se a opção de desligar o PC deve estar * habilitada. * @param hora Define se o campo de hora deve estar habilitado. */ private void habilitarCampos(boolean arquivoDiretorio, boolean diretorio, boolean data, boolean nomeBackup, boolean desligarPC, boolean hora) { txtArquivoDiretorio.setEnabled(arquivoDiretorio); txtDiretorio.setEnabled(diretorio); jdData.setEnabled(data); txtNomeBackup.setEnabled(nomeBackup); rdbPC.setEnabled(desligarPC); jsHora.setEnabled(hora); } /** * Salva um agendamento de backup com base nos campos preenchidos na interface. * <p> * Este método realiza as seguintes ações: * 1. Verifica se os campos obrigatórios contendo endereços de diretórios estão preenchidos. * 2. Coleta os valores dos campos da interface, como arquivo/diretório, diretório de destino, data, hora, * opção de desligar o PC e nome do backup. * 3. Configura um objeto de transferência de dados (DTO) com os valores coletados. * 4. Chama o método para salvar os dados no banco de dados usando um objeto de acesso a dados (DAO). * 5. Limpa os campos da interface. * 6. Desabilita campos e configura os botões na interface de acordo com a lógica. * 7. Atualiza a tabela de agendamento de backup na interface. * </p> */ public void salvarAgendamentoBackup() { //Método verifica se os campos tem os endereços dos diretórios if (verificarCampos()) { return; } String arquivoDiretorio = txtArquivoDiretorio.getText(); String diretorioDestino = txtDiretorio.getText(); Date dataSelecionada = jdData.getDate(); String dataFormatada = formatarData(dataSelecionada); JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm"); jsHora.setEditor(editor); Date dataHora = (Date) jsHora.getValue(); String horaFormatada = formatarHora(dataHora); String desligarPC = rdbPC.isSelected() ? "Sim" : "Não"; String nomeBackup = txtNomeBackup.getText(); // Criando e configurando o DTO
package com.mycompany.ferramentadebackup.view; /** * * @author Giuliano Vianna */ public class FerramentaDeBackupView extends javax.swing.JFrame { /** * Creates new form frmFerramentaDeBackupView */ public FerramentaDeBackupView() { initComponents(); verificarBancoDeDados(); iconeJanela(); popularTabelaAgendamentoBackup(); // Centraliza a janela this.setLocationRelativeTo(null); formatarJSpinner(); new Timer(delay, taskPerformer).start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); txtArquivoDiretorio = new javax.swing.JTextField(); btnSelecionarArquivoDiretorio = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); txtDiretorio = new javax.swing.JTextField(); btnSelecionarDiretorioDestino = new javax.swing.JButton(); jdData = new com.toedter.calendar.JDateChooser(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtTabela = new javax.swing.JTable(); rdbPC = new javax.swing.JRadioButton(); jPanel1 = new javax.swing.JPanel(); btnNovo = new javax.swing.JButton(); btnSalvar = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); btnEditar = new javax.swing.JButton(); btnExcluir = new javax.swing.JButton(); btnAtualizar = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); txtID = new javax.swing.JTextField(); txtNomeBackup = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jsHora = new javax.swing.JSpinner(); jLabel6 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Ferramenta de Backup"); setResizable(false); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel1.setText("Arquivo ou Diretório"); txtArquivoDiretorio.setEditable(false); txtArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtArquivoDiretorio.setEnabled(false); btnSelecionarArquivoDiretorio.setBackground(new java.awt.Color(153, 0, 255)); btnSelecionarArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnSelecionarArquivoDiretorio.setForeground(new java.awt.Color(255, 255, 255)); btnSelecionarArquivoDiretorio.setText("Selecionar"); btnSelecionarArquivoDiretorio.setEnabled(false); btnSelecionarArquivoDiretorio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelecionarArquivoDiretorioActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel2.setText("Diretório de Destino"); txtDiretorio.setEditable(false); txtDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtDiretorio.setEnabled(false); btnSelecionarDiretorioDestino.setBackground(new java.awt.Color(153, 0, 255)); btnSelecionarDiretorioDestino.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnSelecionarDiretorioDestino.setForeground(new java.awt.Color(255, 255, 255)); btnSelecionarDiretorioDestino.setText("Selecionar"); btnSelecionarDiretorioDestino.setEnabled(false); btnSelecionarDiretorioDestino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelecionarDiretorioDestinoActionPerformed(evt); } }); jdData.setDateFormatString("dd'/'MM'/'yy"); jdData.setEnabled(false); jdData.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel3.setText("Data"); jtTabela.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jtTabela.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "ID", "Nome Backup", "Arquivo/Diretório de Origem", "Diretório de Destino", "Data", "Hora", "Desligar PC" } )); jtTabela.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); jtTabela.setShowGrid(false); jtTabela.setShowVerticalLines(true); jScrollPane1.setViewportView(jtTabela); if (jtTabela.getColumnModel().getColumnCount() > 0) { jtTabela.getColumnModel().getColumn(0).setMinWidth(80); jtTabela.getColumnModel().getColumn(0).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(0).setMaxWidth(80); jtTabela.getColumnModel().getColumn(1).setMinWidth(200); jtTabela.getColumnModel().getColumn(2).setMinWidth(420); jtTabela.getColumnModel().getColumn(2).setPreferredWidth(420); jtTabela.getColumnModel().getColumn(2).setMaxWidth(420); jtTabela.getColumnModel().getColumn(3).setMinWidth(420); jtTabela.getColumnModel().getColumn(3).setPreferredWidth(420); jtTabela.getColumnModel().getColumn(3).setMaxWidth(420); jtTabela.getColumnModel().getColumn(4).setMinWidth(80); jtTabela.getColumnModel().getColumn(4).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(4).setMaxWidth(80); jtTabela.getColumnModel().getColumn(5).setMinWidth(80); jtTabela.getColumnModel().getColumn(5).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(5).setMaxWidth(80); jtTabela.getColumnModel().getColumn(6).setMinWidth(80); jtTabela.getColumnModel().getColumn(6).setPreferredWidth(80); jtTabela.getColumnModel().getColumn(6).setMaxWidth(80); } rdbPC.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N rdbPC.setForeground(new java.awt.Color(153, 0, 255)); rdbPC.setText("Desligar o PC ao finalizar o backup"); rdbPC.setEnabled(false); btnNovo.setBackground(new java.awt.Color(153, 0, 255)); btnNovo.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnNovo.setForeground(new java.awt.Color(255, 255, 255)); btnNovo.setText("Novo"); btnNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNovoActionPerformed(evt); } }); btnSalvar.setBackground(new java.awt.Color(153, 0, 255)); btnSalvar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnSalvar.setForeground(new java.awt.Color(255, 255, 255)); btnSalvar.setText("Salvar"); btnSalvar.setEnabled(false); btnSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarActionPerformed(evt); } }); btnCancelar.setBackground(new java.awt.Color(153, 0, 255)); btnCancelar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnCancelar.setForeground(new java.awt.Color(255, 255, 255)); btnCancelar.setText("Cancelar"); btnCancelar.setEnabled(false); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } }); btnEditar.setBackground(new java.awt.Color(153, 0, 255)); btnEditar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnEditar.setForeground(new java.awt.Color(255, 255, 255)); btnEditar.setText("Editar"); btnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditarActionPerformed(evt); } }); btnExcluir.setBackground(new java.awt.Color(153, 0, 255)); btnExcluir.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnExcluir.setForeground(new java.awt.Color(255, 255, 255)); btnExcluir.setText("Excluir"); btnExcluir.setEnabled(false); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); btnAtualizar.setBackground(new java.awt.Color(153, 0, 255)); btnAtualizar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N btnAtualizar.setForeground(new java.awt.Color(255, 255, 255)); btnAtualizar.setText("Atualizar"); btnAtualizar.setEnabled(false); btnAtualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAtualizarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(15, Short.MAX_VALUE) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(25, Short.MAX_VALUE)) ); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel4.setText("ID"); txtID.setEditable(false); txtID.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtID.setForeground(new java.awt.Color(255, 255, 255)); txtID.setEnabled(false); txtNomeBackup.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N txtNomeBackup.setEnabled(false); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel5.setText("Horas"); jsHora.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jsHora.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.HOUR_OF_DAY) ); jsHora.setToolTipText(""); jsHora.setEnabled(false); jLabel6.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jLabel6.setText("Nome do Backup"); jMenu1.setText("File"); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1374, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSelecionarArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnSelecionarDiretorioDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jdData, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(67, 67, 67))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jsHora, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(rdbPC, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(24, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSelecionarArquivoDiretorio)) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSelecionarDiretorioDestino)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jsHora, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rdbPC)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jdData, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnSelecionarArquivoDiretorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarArquivoDiretorioActionPerformed selecionarDiretorioOuArquivo(); }//GEN-LAST:event_btnSelecionarArquivoDiretorioActionPerformed private void btnSelecionarDiretorioDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarDiretorioDestinoActionPerformed selecionarDiretorio(); }//GEN-LAST:event_btnSelecionarDiretorioDestinoActionPerformed private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed configurarBotoes(true, true, false, false, true, false, false, true); habilitarCampos(true, true, true, true, true, true); }//GEN-LAST:event_btnNovoActionPerformed private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed configurarBotoes(false, false, true, false, false, true, false, false); habilitarCampos(false, false, false, false, false, false); limparCampos(); }//GEN-LAST:event_btnCancelarActionPerformed private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed salvarAgendamentoBackup(); }//GEN-LAST:event_btnSalvarActionPerformed private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed editarAgendamentoBackup(); }//GEN-LAST:event_btnEditarActionPerformed private void btnAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtualizarActionPerformed atualizarAgendamentoBuckup(); }//GEN-LAST:event_btnAtualizarActionPerformed private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed excluirAgendamentoBackup(); }//GEN-LAST:event_btnExcluirActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FerramentaDeBackupView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new FerramentaDeBackupView().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAtualizar; private javax.swing.JButton btnCancelar; private javax.swing.JButton btnEditar; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnNovo; private javax.swing.JButton btnSalvar; private javax.swing.JButton btnSelecionarArquivoDiretorio; private javax.swing.JButton btnSelecionarDiretorioDestino; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private com.toedter.calendar.JDateChooser jdData; private javax.swing.JSpinner jsHora; private javax.swing.JTable jtTabela; private javax.swing.JRadioButton rdbPC; private javax.swing.JTextField txtArquivoDiretorio; private javax.swing.JTextField txtDiretorio; private javax.swing.JTextField txtID; private javax.swing.JTextField txtNomeBackup; // End of variables declaration//GEN-END:variables /** * Permite ao usuário escolher entre selecionar um diretório ou um arquivo. * <p> * Este método exibe uma caixa de diálogo com duas opções: "Diretório" e * "Arquivo". A escolha do usuário determina se o {@link JFileChooser} será * configurado para selecionar apenas diretórios ou apenas arquivos. Após a * seleção, o caminho absoluto do diretório ou arquivo escolhido é retornado * dentro de um {@link java.util.Optional}. * </p> * * <p> * Se o usuário selecionar um item, o caminho absoluto é retornado * encapsulado em um {@code Optional<String>}. Se o usuário cancelar a * operação ou se ocorrer um erro, um {@code Optional<String>} vazio é * retornado. * </p> * * <p> * Exceções são tratadas internamente, e uma mensagem de erro é exibida em * caso de falha. * </p> * * @return Um {@link java.util.Optional<String>} contendo o caminho do * arquivo ou diretório selecionado, ou um {@code Optional} vazio em caso de * cancelamento ou erro. */ public Optional<String> selecionarDiretorioOuArquivo() { Object[] options = {"Diretório", "Arquivo"}; int choice = JOptionPane.showOptionDialog( null, "Você deseja selecionar um diretório ou um arquivo?", "Selecionar Diretório ou Arquivo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(choice == JOptionPane.YES_OPTION ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); try { int option = fileChooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (selectedFile != null) { String caminhoArquivoDiretorio = selectedFile.getAbsolutePath(); txtArquivoDiretorio.setText(caminhoArquivoDiretorio); // Ajuste conforme sua lógica de interface return Optional.of(caminhoArquivoDiretorio); } } } catch (HeadlessException error) { JOptionPane.showMessageDialog(null, "Ocorreu um erro ao selecionar o arquivo ou diretório " + error, "Erro", JOptionPane.ERROR_MESSAGE); } return Optional.empty(); } /** * Abre uma caixa de diálogo para o usuário selecionar um diretório. * <p> * Este método utiliza o {@link JFileChooser} configurado para permitir que * o usuário selecione apenas diretórios. Após a seleção, o caminho absoluto * do diretório escolhido é atribuído a uma variável de instância. * </p> * * <p> * Se o usuário selecionar um diretório, o caminho absoluto é armazenado na * variável {@code txtDiretorio}. Em caso de cancelamento da operação, * nenhuma ação é tomada. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, mas atualiza * diretamente a interface do usuário com o caminho do diretório * selecionado. * </p> */ public void selecionarDiretorio() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Configura para selecionar apenas diretórios int option = fileChooser.showOpenDialog(null); // Abre a caixa de diálogo centralizada if (option == JFileChooser.APPROVE_OPTION) { File selectedDirectory = fileChooser.getSelectedFile(); if (selectedDirectory != null) { // Atribui o caminho à variável de instância String caminhoDoDiretorio = selectedDirectory.getAbsolutePath(); txtDiretorio.setText(caminhoDoDiretorio); } } } /** * Verifica a existência do banco de dados e o cria, se necessário. * <p> * Este método utiliza a classe {@link BancoDeDadosDAO} para verificar se o * banco de dados já existe. Se o banco de dados não existir, ele é criado * por meio do método {@link BancoDeDadosDAO#verificarECriarBancoDeDados()}. * </p> * * <p> * <b>Nota:</b> Este método não retorna nenhum valor, pois sua função é * verificar e criar o banco de dados, se necessário, sem fornecer * resultados diretos. * </p> */ public final void verificarBancoDeDados() { BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO(); objBancoDeDadosDAO.verificarECriarBancoDeDados(); } /** * Define o ícone da janela com base em um arquivo de imagem. * <p> * Este método carrega uma imagem de ícone da classe {@link ImageIcon} com o * caminho especificado. Em seguida, define essa imagem como o ícone da * janela atual usando {@link #setIconImage(java.awt.Image)}. * </p> * * <p> * <b>Nota:</b> Este método é usado para configurar o ícone da janela e não * retorna nenhum valor. * </p> */ private void iconeJanela() { ImageIcon icone = new ImageIcon(getClass().getClassLoader().getResource("images/iconeJanela.png")); setIconImage(icone.getImage()); } /** * Configura o estado dos botões da interface com base em parâmetros * booleanos. * <p> * Este método permite configurar o estado de vários botões da interface de * acordo com os valores booleanos fornecidos como parâmetros. Cada * parâmetro corresponde a um botão e define se ele deve estar habilitado * (true) ou desabilitado (false). * </p> * * @param diretorioOrigem Define se os botões de seleção de diretório de * origem devem estar habilitados. * @param diretorioDestino Define se os botões de seleção de diretório de * destino devem estar habilitados. * @param novo Define se o botão "Novo" deve estar habilitado. * @param atualizar Define se o botão "Atualizar" deve estar habilitado. * @param salvar Define se o botão "Salvar" deve estar habilitado. * @param editar Define se o botão "Editar" deve estar habilitado. * @param excluir Define se o botão "Excluir" deve estar habilitado. * @param cancelar Define se o botão "Cancelar" deve estar habilitado. */ public void configurarBotoes(boolean diretorioOrigem, boolean diretorioDestino, boolean novo, boolean atualizar, boolean salvar, boolean editar, boolean excluir, boolean cancelar) { btnSelecionarArquivoDiretorio.setEnabled(diretorioOrigem); btnSelecionarDiretorioDestino.setEnabled(diretorioOrigem); btnNovo.setEnabled(novo); btnAtualizar.setEnabled(atualizar); btnSalvar.setEnabled(salvar); btnEditar.setEnabled(editar); btnExcluir.setEnabled(excluir); btnCancelar.setEnabled(cancelar); } /** * Habilita ou desabilita campos da interface com base em parâmetros * booleanos. * <p> * Este método permite habilitar ou desabilitar vários campos da interface * com base nos valores booleanos fornecidos como parâmetros. Cada parâmetro * corresponde a um campo e define se ele deve estar habilitado (true) ou * desabilitado (false). * </p> * * @param arquivoDiretorio Define se o campo de arquivo/diretório deve estar * habilitado. * @param diretorio Define se o campo de diretório deve estar habilitado. * @param data Define se o campo de data deve estar habilitado. * @param nomeBackup Define se o campo de nome de backup deve estar * habilitado. * @param desligarPC Define se a opção de desligar o PC deve estar * habilitada. * @param hora Define se o campo de hora deve estar habilitado. */ private void habilitarCampos(boolean arquivoDiretorio, boolean diretorio, boolean data, boolean nomeBackup, boolean desligarPC, boolean hora) { txtArquivoDiretorio.setEnabled(arquivoDiretorio); txtDiretorio.setEnabled(diretorio); jdData.setEnabled(data); txtNomeBackup.setEnabled(nomeBackup); rdbPC.setEnabled(desligarPC); jsHora.setEnabled(hora); } /** * Salva um agendamento de backup com base nos campos preenchidos na interface. * <p> * Este método realiza as seguintes ações: * 1. Verifica se os campos obrigatórios contendo endereços de diretórios estão preenchidos. * 2. Coleta os valores dos campos da interface, como arquivo/diretório, diretório de destino, data, hora, * opção de desligar o PC e nome do backup. * 3. Configura um objeto de transferência de dados (DTO) com os valores coletados. * 4. Chama o método para salvar os dados no banco de dados usando um objeto de acesso a dados (DAO). * 5. Limpa os campos da interface. * 6. Desabilita campos e configura os botões na interface de acordo com a lógica. * 7. Atualiza a tabela de agendamento de backup na interface. * </p> */ public void salvarAgendamentoBackup() { //Método verifica se os campos tem os endereços dos diretórios if (verificarCampos()) { return; } String arquivoDiretorio = txtArquivoDiretorio.getText(); String diretorioDestino = txtDiretorio.getText(); Date dataSelecionada = jdData.getDate(); String dataFormatada = formatarData(dataSelecionada); JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm"); jsHora.setEditor(editor); Date dataHora = (Date) jsHora.getValue(); String horaFormatada = formatarHora(dataHora); String desligarPC = rdbPC.isSelected() ? "Sim" : "Não"; String nomeBackup = txtNomeBackup.getText(); // Criando e configurando o DTO
BancoDeDadosDTO objBancoDeDadosDTO = new BancoDeDadosDTO();
1
2023-12-02 02:23:51+00:00
12k