hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e16da4c984e2f78331905f3b8fc4abd73f2aeef | 508 | java | Java | book-stack.persistence/src/main/java/bookstack/persistence/dao/BookDAO.java | Ludovit-Laca/WAP | 06a968c8d8df7d909c83157cf2381a3438ddacac | [
"MIT"
] | null | null | null | book-stack.persistence/src/main/java/bookstack/persistence/dao/BookDAO.java | Ludovit-Laca/WAP | 06a968c8d8df7d909c83157cf2381a3438ddacac | [
"MIT"
] | null | null | null | book-stack.persistence/src/main/java/bookstack/persistence/dao/BookDAO.java | Ludovit-Laca/WAP | 06a968c8d8df7d909c83157cf2381a3438ddacac | [
"MIT"
] | null | null | null | 21.166667 | 80 | 0.728346 | 9,738 | package bookstack.persistence.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import bookstack.persistence.entities.Book;
@Stateless
public class BookDAO extends AbstractDAO<Book>{
public BookDAO() {
super(Book.class);
}
public List<Book> getBooksByTitle(String title) {
TypedQuery<Book> query = em.createNamedQuery("findBooksByTitle", Book.class);
query.setParameter("title", title);
return query.getResultList();
}
}
|
3e16dafd7a6000d32569802f3bba789501ebb03d | 2,392 | java | Java | server/src/main/java/umm3601/journal/JournalController.java | corde171/iteration-4-secure-super-group | e65f15898b8e5b9dabc2fac0275cf3af37c5c28e | [
"MIT"
] | null | null | null | server/src/main/java/umm3601/journal/JournalController.java | corde171/iteration-4-secure-super-group | e65f15898b8e5b9dabc2fac0275cf3af37c5c28e | [
"MIT"
] | 29 | 2018-04-20T17:25:39.000Z | 2018-05-04T01:35:45.000Z | server/src/main/java/umm3601/journal/JournalController.java | corde171/iteration-4-secure-super-group | e65f15898b8e5b9dabc2fac0275cf3af37c5c28e | [
"MIT"
] | 2 | 2019-01-03T02:53:33.000Z | 2020-03-30T16:05:41.000Z | 30.666667 | 144 | 0.629181 | 9,739 | package umm3601.journal;
import com.google.gson.Gson;
import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
import org.bson.Document;
import org.bson.types.ObjectId;
import umm3601.SuperController;
import java.util.Iterator;
import java.util.Map;
import java.util.Date;
import static com.mongodb.client.model.Filters.eq;
public class JournalController extends SuperController {
/**
* journalController constructor
*
* @param database
*/
public JournalController(MongoDatabase database) {
gson = new Gson();
this.database = database;
collection = database.getCollection("journals");
}
public String addNewJournal(String subject, String body, String userID) {
Document newJournal = new Document();
newJournal.append("subject", subject);
newJournal.append("body", body);
newJournal.append("userID", userID);
Date now = new Date();
newJournal.append("date", now.toString());
try {
collection.insertOne(newJournal);
ObjectId id = newJournal.getObjectId("_id");
System.err.println("Successfully added new journal [_id=" + id + ", subject=" + subject + ", body=" + body + ", date=" + now + ']');
return JSON.serialize(id);
} catch(MongoException me) {
me.printStackTrace();
return null;
}
}
public String editJournal(String id, String subject, String body){
System.out.println("Right here again");
Document newJournal = new Document();
newJournal.append("subject", subject);
newJournal.append("body", body);
Document setQuery = new Document();
setQuery.append("$set", newJournal);
Document searchQuery = new Document().append("_id", new ObjectId(id));
System.out.println(id);
try {
collection.updateOne(searchQuery, setQuery);
ObjectId id1 = searchQuery.getObjectId("_id");
System.err.println("Successfully updated journal [_id=" + id1 + ", subject=" + subject + ", body=" + body + ']');
return JSON.serialize(id1);
} catch(MongoException me) {
me.printStackTrace();
return null;
}
}
}
|
3e16dcf9728dbd7523ff304f9bb3e7677a0c9169 | 2,454 | java | Java | web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/grpcweb/Grpc.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 55 | 2021-05-11T16:01:59.000Z | 2022-03-30T14:30:33.000Z | web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/grpcweb/Grpc.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 943 | 2021-05-10T14:00:02.000Z | 2022-03-31T21:28:15.000Z | web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/grpcweb/Grpc.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 29 | 2021-05-10T11:33:16.000Z | 2022-03-30T21:01:54.000Z | 37.753846 | 107 | 0.784434 | 9,740 | package io.deephaven.javascript.proto.dhinternal.grpcweb;
import io.deephaven.javascript.proto.dhinternal.grpcweb.grpc.Client;
import io.deephaven.javascript.proto.dhinternal.grpcweb.grpc.ClientRpcOptions;
import io.deephaven.javascript.proto.dhinternal.grpcweb.invoke.InvokeRpcOptions;
import io.deephaven.javascript.proto.dhinternal.grpcweb.invoke.Request;
import io.deephaven.javascript.proto.dhinternal.grpcweb.transports.http.http.CrossBrowserHttpTransportInit;
import io.deephaven.javascript.proto.dhinternal.grpcweb.transports.http.xhr.XhrTransportInit;
import io.deephaven.javascript.proto.dhinternal.grpcweb.transports.transport.TransportFactory;
import io.deephaven.javascript.proto.dhinternal.grpcweb.unary.UnaryRpcOptions;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
@JsType(isNative = true, name = "dhinternal.grpcWeb.grpc", namespace = JsPackage.GLOBAL)
public class Grpc {
@JsFunction
public interface CrossBrowserHttpTransportFn {
TransportFactory onInvoke(CrossBrowserHttpTransportInit p0);
}
@JsFunction
public interface FetchReadableStreamTransportFn {
TransportFactory onInvoke(Object p0);
}
@JsFunction
public interface InvokeFn {
Request onInvoke(Object p0, InvokeRpcOptions<Object, Object> p1);
}
@JsFunction
public interface SetDefaultTransportFn {
void onInvoke(TransportFactory p0);
}
@JsFunction
public interface UnaryFn {
Request onInvoke(Object p0, UnaryRpcOptions<Object, Object> p1);
}
@JsFunction
public interface WebsocketTransportFn {
TransportFactory onInvoke();
}
@JsFunction
public interface XhrTransportFn {
TransportFactory onInvoke(XhrTransportInit p0);
}
public static Grpc.CrossBrowserHttpTransportFn CrossBrowserHttpTransport;
public static Grpc.FetchReadableStreamTransportFn FetchReadableStreamTransport;
public static Grpc.WebsocketTransportFn WebsocketTransport;
public static Grpc.XhrTransportFn XhrTransport;
public static Grpc.InvokeFn invoke;
public static Grpc.SetDefaultTransportFn setDefaultTransport;
public static Grpc.UnaryFn unary;
public static native <TRequest, TResponse, M> Client<TRequest, TResponse> client(
M methodDescriptor, ClientRpcOptions props);
public static native int httpStatusToCode(double httpStatus);
}
|
3e16de8b107a866fd0586a0d29f6ebb03423bdc0 | 442 | java | Java | src/main/java/tech/toparvion/analog/remote/agent/si/package-info.java | Toparvion/analog | 94a523ec41d707f8afdec96c8844874f5916a76e | [
"MIT"
] | 15 | 2018-02-17T17:08:37.000Z | 2022-03-18T03:31:59.000Z | src/main/java/tech/toparvion/analog/remote/agent/si/package-info.java | Toparvion/analog | 94a523ec41d707f8afdec96c8844874f5916a76e | [
"MIT"
] | 46 | 2017-11-06T15:42:56.000Z | 2020-12-31T09:30:57.000Z | src/main/java/tech/toparvion/analog/remote/agent/si/package-info.java | Toparvion/analog | 94a523ec41d707f8afdec96c8844874f5916a76e | [
"MIT"
] | 3 | 2020-04-30T16:17:05.000Z | 2021-12-17T08:31:49.000Z | 49.111111 | 115 | 0.764706 | 9,741 | /**
* Classes of this package were initially taken from Spring Integration source code. They were modified in order to
* support tailing with arbitrary external processes, not {@code tail} OS utility only. This feature will be tested
* in AnaLog and, in case of success, may be proposed as a Pull Request for inclusion back into Spring Integration.
*
* @author Toparvion
* @since v0.11
*/
package tech.toparvion.analog.remote.agent.si; |
3e16df2059c0cfa25ab2f45eb8fe15b3e6dde20b | 2,698 | java | Java | src/main/java/org/gitlab4j/api/HookManager.java | filippobuletto/gitlab4j-api | a1c36764592ec0bad7f7a49b8740e8ec559213bd | [
"MIT"
] | 1 | 2018-08-17T13:17:00.000Z | 2018-08-17T13:17:00.000Z | src/main/java/org/gitlab4j/api/HookManager.java | filippobuletto/gitlab4j-api | a1c36764592ec0bad7f7a49b8740e8ec559213bd | [
"MIT"
] | null | null | null | src/main/java/org/gitlab4j/api/HookManager.java | filippobuletto/gitlab4j-api | a1c36764592ec0bad7f7a49b8740e8ec559213bd | [
"MIT"
] | 1 | 2019-11-07T14:12:02.000Z | 2019-11-07T14:12:02.000Z | 35.038961 | 107 | 0.664937 | 9,742 |
package org.gitlab4j.api;
import javax.servlet.http.HttpServletRequest;
/**
* This class provides a base class handler for processing GitLab Web Hook and System Hook callouts.
*/
public abstract class HookManager {
private String secretToken;
/**
* Create a HookManager to handle GitLab hook events.
*/
public HookManager() {
this.secretToken = null;
}
/**
* Create a HookManager to handle GitLab hook events which will be verified
* against the specified secretToken.
*
* @param secretToken the secret token to verify against
*/
public HookManager(String secretToken) {
this.secretToken = secretToken;
}
/**
* Set the secret token that received hook events should be validated against.
*
* @param secretToken the secret token to verify against
*/
public void setSecretToken(String secretToken) {
this.secretToken = secretToken;
}
/**
* Validate the provided secret token against the reference secret token. Returns true if
* the secret token is valid or there is no reference secret token to validate against,
* otherwise returns false.
*
* @param secretToken the token to validate
* @return true if the secret token is valid or there is no reference secret token to validate against
*/
public boolean isValidSecretToken(String secretToken) {
return (this.secretToken == null || this.secretToken.equals(secretToken) ? true : false);
}
/**
* Validate the provided secret token found in the HTTP header against the reference secret token.
* Returns true if the secret token is valid or there is no reference secret token to validate
* against, otherwise returns false.
*
* @param request the HTTP request to verify the secret token
* @return true if the secret token is valid or there is no reference secret token to validate against
*/
public boolean isValidSecretToken(HttpServletRequest request) {
if (this.secretToken != null) {
String secretToken = request.getHeader("X-Gitlab-Token");
return (isValidSecretToken(secretToken));
}
return (true);
}
/**
* Parses and verifies an Event instance from the HTTP request and
* fires it off to the registered listeners.
*
* @param request the HttpServletRequest to read the Event instance from
* @throws GitLabApiException if the parsed event is not supported
*/
public abstract void handleEvent(HttpServletRequest request) throws GitLabApiException;
} |
3e16dfb6c0f4790e03fe0486676fd90a0cb66302 | 243 | java | Java | quiz_1/src/t1.java | dev2727/NetBeansProjects | 05abaaf0a919827ba860799a95b71ed1e85517d6 | [
"Apache-2.0"
] | null | null | null | quiz_1/src/t1.java | dev2727/NetBeansProjects | 05abaaf0a919827ba860799a95b71ed1e85517d6 | [
"Apache-2.0"
] | null | null | null | quiz_1/src/t1.java | dev2727/NetBeansProjects | 05abaaf0a919827ba860799a95b71ed1e85517d6 | [
"Apache-2.0"
] | null | null | null | 17.357143 | 79 | 0.679012 | 9,743 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author anubhav chhillar
*/
class t1 {
}
|
3e16dfb892f1cfd9c05ba38c6d562564d2f25a69 | 6,007 | java | Java | pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java12Test.java | l0s/pmd | bf2bece0856dd7c9d1a6a8ea976bc0f798e67413 | [
"Apache-2.0"
] | 1 | 2019-12-09T20:07:13.000Z | 2019-12-09T20:07:13.000Z | pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java12Test.java | l0s/pmd | bf2bece0856dd7c9d1a6a8ea976bc0f798e67413 | [
"Apache-2.0"
] | null | null | null | pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java12Test.java | l0s/pmd | bf2bece0856dd7c9d1a6a8ea976bc0f798e67413 | [
"Apache-2.0"
] | null | null | null | 51.34188 | 133 | 0.761112 | 9,744 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.java.ParserTstUtil;
public class Java12Test {
private static String loadSource(String name) {
try {
return IOUtils.toString(Java12Test.class.getResourceAsStream("jdkversiontests/java12/" + name),
StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test(expected = ParseException.class)
public void testMultipleCaseLabelsJava11() {
ParserTstUtil.parseAndTypeResolveJava("11", loadSource("MultipleCaseLabels.java"));
}
@Test
public void testMultipleCaseLabels() {
ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("12-preview",
loadSource("MultipleCaseLabels.java"));
Assert.assertNotNull(compilationUnit);
ASTSwitchStatement switchStatement = compilationUnit.getFirstDescendantOfType(ASTSwitchStatement.class);
Assert.assertTrue(switchStatement.jjtGetChild(0) instanceof ASTExpression);
Assert.assertTrue(switchStatement.jjtGetChild(1) instanceof ASTSwitchLabel);
ASTSwitchLabel switchLabel = switchStatement.getFirstChildOfType(ASTSwitchLabel.class);
Assert.assertEquals(3, switchLabel.findChildrenOfType(ASTExpression.class).size());
}
@Test(expected = ParseException.class)
public void testSwitchRulesJava11() {
ParserTstUtil.parseAndTypeResolveJava("11", loadSource("SwitchRules.java"));
}
@Test
public void testSwitchRules() {
ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("12-preview",
loadSource("SwitchRules.java"));
Assert.assertNotNull(compilationUnit);
ASTSwitchStatement switchStatement = compilationUnit.getFirstDescendantOfType(ASTSwitchStatement.class);
Assert.assertTrue(switchStatement.jjtGetChild(0) instanceof ASTExpression);
Assert.assertTrue(switchStatement.jjtGetChild(1) instanceof ASTSwitchLabeledExpression);
ASTSwitchLabeledExpression switchLabeledExpression = (ASTSwitchLabeledExpression) switchStatement.jjtGetChild(1);
Assert.assertEquals(2, switchLabeledExpression.jjtGetNumChildren());
Assert.assertTrue(switchLabeledExpression.jjtGetChild(0) instanceof ASTSwitchLabel);
Assert.assertTrue(switchLabeledExpression.jjtGetChild(1) instanceof ASTExpression);
ASTSwitchLabeledBlock switchLabeledBlock = (ASTSwitchLabeledBlock) switchStatement.jjtGetChild(4);
Assert.assertEquals(2, switchLabeledBlock.jjtGetNumChildren());
Assert.assertTrue(switchLabeledBlock.jjtGetChild(0) instanceof ASTSwitchLabel);
Assert.assertTrue(switchLabeledBlock.jjtGetChild(1) instanceof ASTBlock);
ASTSwitchLabeledThrowStatement switchLabeledThrowStatement = (ASTSwitchLabeledThrowStatement) switchStatement.jjtGetChild(5);
Assert.assertEquals(2, switchLabeledThrowStatement.jjtGetNumChildren());
Assert.assertTrue(switchLabeledThrowStatement.jjtGetChild(0) instanceof ASTSwitchLabel);
Assert.assertTrue(switchLabeledThrowStatement.jjtGetChild(1) instanceof ASTThrowStatement);
}
@Test(expected = ParseException.class)
public void testSwitchExpressionsJava11() {
ParserTstUtil.parseAndTypeResolveJava("11", loadSource("SwitchExpressions.java"));
}
@Test
public void testSwitchExpressions() {
ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("12-preview",
loadSource("SwitchExpressions.java"));
Assert.assertNotNull(compilationUnit);
ASTSwitchExpression switchExpression = compilationUnit.getFirstDescendantOfType(ASTSwitchExpression.class);
Assert.assertEquals(6, switchExpression.jjtGetNumChildren());
Assert.assertTrue(switchExpression.jjtGetChild(0) instanceof ASTExpression);
Assert.assertEquals(5, switchExpression.findChildrenOfType(ASTSwitchLabeledRule.class).size());
ASTLocalVariableDeclaration localVar = compilationUnit.findDescendantsOfType(ASTLocalVariableDeclaration.class).get(1);
ASTVariableDeclarator localVarDecl = localVar.getFirstChildOfType(ASTVariableDeclarator.class);
Assert.assertEquals(Integer.TYPE, localVarDecl.getType());
Assert.assertEquals(Integer.TYPE, switchExpression.getType());
}
@Test
public void testSwitchExpressionsBreak() {
ASTCompilationUnit compilationUnit = ParserTstUtil.parseAndTypeResolveJava("12-preview",
loadSource("SwitchExpressionsBreak.java"));
Assert.assertNotNull(compilationUnit);
ASTSwitchExpression switchExpression = compilationUnit.getFirstDescendantOfType(ASTSwitchExpression.class);
Assert.assertEquals(11, switchExpression.jjtGetNumChildren());
Assert.assertTrue(switchExpression.jjtGetChild(0) instanceof ASTExpression);
Assert.assertEquals(5, switchExpression.findChildrenOfType(ASTSwitchLabel.class).size());
ASTBreakStatement breakStatement = switchExpression.getFirstDescendantOfType(ASTBreakStatement.class);
Assert.assertEquals("SwitchExpressionsBreak.SIX", breakStatement.getImage());
Assert.assertTrue(breakStatement.jjtGetChild(0) instanceof ASTExpression);
ASTLocalVariableDeclaration localVar = compilationUnit.findDescendantsOfType(ASTLocalVariableDeclaration.class).get(1);
ASTVariableDeclarator localVarDecl = localVar.getFirstChildOfType(ASTVariableDeclarator.class);
Assert.assertEquals(Integer.TYPE, localVarDecl.getType());
Assert.assertEquals(Integer.TYPE, switchExpression.getType());
}
}
|
3e16e0252491400a580e39622961b3c4a1dca828 | 7,904 | java | Java | src/main/java/bjc/data/Tree.java | bculkin2442/esodata | 6ccd5d885084f983013584db35df60a22b76e521 | [
"Apache-2.0"
] | null | null | null | src/main/java/bjc/data/Tree.java | bculkin2442/esodata | 6ccd5d885084f983013584db35df60a22b76e521 | [
"Apache-2.0"
] | null | null | null | src/main/java/bjc/data/Tree.java | bculkin2442/esodata | 6ccd5d885084f983013584db35df60a22b76e521 | [
"Apache-2.0"
] | null | null | null | 27.54007 | 81 | 0.628543 | 9,745 | package bjc.data;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import bjc.funcdata.ListEx;
import bjc.funcdata.bst.TreeLinearizationMethod;
/**
* A node in a homogeneous tree with a unlimited amount of children.
*
* @author ben
*
* @param <ContainedType>
* The type of data contained in the tree nodes.
*
*/
public interface Tree<ContainedType> {
/**
* Append a child to this node.
*
* @param child
* The child to append to this node.
*/
void addChild(Tree<ContainedType> child);
/**
* Append a child to this node.
*
* @param child
* The child to append to this node.
*/
void addChild(ContainedType child);
/**
* Prepend a child to this node.
*
* @param child
* The child to prepend to this node.
*/
void prependChild(Tree<ContainedType> child);
/**
* Collapse a tree into a single version.
*
* @param <NewType>
* The intermediate type being folded.
*
* @param <ReturnedType>
* The type that is the end result.
*
* @param leafTransform
* The function to use to convert leaf values.
*
* @param nodeCollapser
* The function to use to convert internal nodes and
* their children.
*
* @param resultTransformer
* The function to use to convert a state to the
* returned version.
*
* @return The final transformed state.
*/
<NewType, ReturnedType> ReturnedType collapse(
Function<ContainedType, NewType> leafTransform,
BiFunction<ContainedType, ListEx<NewType>, NewType> nodeCollapser,
Function<NewType, ReturnedType> resultTransformer);
/**
* Execute a given action for each of this tree's children.
*
* @param action
* The action to execute for each child.
*/
void doForChildren(Consumer<Tree<ContainedType>> action);
/**
* Expand the nodes of a tree into trees, and then merge the contents of those
* trees into a single tree.
*
* @param mapper
* The function to use to map values into trees.
*
* @return A tree, with some nodes expanded into trees.
*/
default Tree<ContainedType>
flatMapTree(final Function<ContainedType, Tree<ContainedType>> mapper) {
return topDownTransform(dat -> TopDownTransformResult.PUSHDOWN, node -> {
if (node.getChildrenCount() > 0) {
final Tree<ContainedType> parent = node.transformHead(mapper);
node.doForChildren(parent::addChild);
return parent;
}
return node.transformHead(mapper);
});
}
/**
* Get the specified child of this tree.
*
* @param childNo
* The number of the child to get.
*
* @return The specified child of this tree.
*/
default Tree<ContainedType> getChild(final int childNo) {
return transformChild(childNo, child -> child);
}
/**
* Get a count of the number of direct children this node has.
*
* @return The number of direct children this node has.
*/
int getChildrenCount();
/**
* Get a count of the number of direct children this node has.
*
* @return The number of direct children this node has.
*/
default int size() {
return getChildrenCount();
}
/**
* Get the data stored in this node.
*
* @return The data stored in this node.
*/
default ContainedType getHead() {
return transformHead(head -> head);
}
/**
* Rebuild the tree with the same structure, but different nodes.
*
* @param <MappedType>
* The type of the new tree.
*
* @param leafTransformer
* The function to use to transform leaf tokens.
*
* @param internalTransformer
* The function to use to transform internal tokens.
*
* @return The tree, with the nodes changed.
*/
<MappedType> Tree<MappedType> rebuildTree(
Function<ContainedType, MappedType> leafTransformer,
Function<ContainedType, MappedType> internalTransformer);
/**
* Transform some of the nodes in this tree.
*
* @param nodePicker
* The predicate to use to pick nodes to transform.
*
* @param transformer
* The function to use to transform picked nodes.
*/
void selectiveTransform(Predicate<ContainedType> nodePicker,
UnaryOperator<ContainedType> transformer);
/**
* Do a top-down transform of the tree.
*
* @param transformPicker
* The function to use to pick how to progress.
*
* @param transformer
* The function used to transform picked subtrees.
*
* @return The tree with the transform applied to picked subtrees.
*/
Tree<ContainedType> topDownTransform(
Function<ContainedType, TopDownTransformResult> transformPicker,
UnaryOperator<Tree<ContainedType>> transformer);
/**
* Transform one of this nodes children.
*
* @param <TransformedType>
* The type of the transformed value.
*
* @param childNo
* The number of the child to transform.
*
* @param transformer
* The function to use to transform the value.
*
* @return The transformed value.
*
* @throws IllegalArgumentException
* if the childNo is out of bounds (0 <=
* childNo <= childCount()).
*/
<TransformedType> TransformedType transformChild(int childNo,
Function<Tree<ContainedType>, TransformedType> transformer);
/**
* Transform the value that is the head of this node.
*
* @param <TransformedType>
* The type of the transformed value.
*
* @param transformer
* The function to use to transform the value.
*
* @return The transformed value.
*/
<TransformedType> TransformedType
transformHead(Function<ContainedType, TransformedType> transformer);
/**
* Transform the tree into a tree with a different type of token.
*
* @param <MappedType>
* The type of the new tree.
*
* @param transformer
* The function to use to transform tokens.
*
* @return A tree with the token types transformed.
*/
default <MappedType> Tree<MappedType>
transformTree(final Function<ContainedType, MappedType> transformer) {
return rebuildTree(transformer, transformer);
}
/**
* Perform an action on each part of the tree.
*
* @param linearizationMethod
* The way to traverse the tree.
*
* @param action
* The action to perform on each tree node.
*/
void traverse(TreeLinearizationMethod linearizationMethod,
Consumer<ContainedType> action);
/**
* Find the farthest to right child that satisfies the given predicate.
*
* @param childPred
* The predicate to satisfy.
*
* @return The index of the right-most child that satisfies the predicate, or -1
* if one doesn't exist.
*/
int revFind(Predicate<Tree<ContainedType>> childPred);
/**
* Check if this tree contains any nodes that satisfy the predicate.
*
* @param pred
* The predicate to look for.
*
* @return Whether or not any items satisfied the predicate.
*/
default boolean containsMatching(Predicate<ContainedType> pred) {
Toggle<Boolean> tog = new OneWayToggle<>(false, true);
traverse(TreeLinearizationMethod.POSTORDER, val -> {
if (pred.test(val)) tog.get();
});
return tog.get();
}
/**
* Set the head of the tree.
*
* @param dat
* The value to set as the head of the tree.
*/
void setHead(ContainedType dat);
}
|
3e16e0913a8a6837819f5f330a64bde87951d775 | 2,822 | java | Java | DungeonDiver7/src/com/puttysoftware/dungeondiver7/dungeon/objects/DisruptedHotWall.java | retropipes/dungeon-diver-7 | 169e74e70d777ebdbe20d2f89134c681a9ae67d1 | [
"Apache-2.0"
] | null | null | null | DungeonDiver7/src/com/puttysoftware/dungeondiver7/dungeon/objects/DisruptedHotWall.java | retropipes/dungeon-diver-7 | 169e74e70d777ebdbe20d2f89134c681a9ae67d1 | [
"Apache-2.0"
] | null | null | null | DungeonDiver7/src/com/puttysoftware/dungeondiver7/dungeon/objects/DisruptedHotWall.java | retropipes/dungeon-diver-7 | 169e74e70d777ebdbe20d2f89134c681a9ae67d1 | [
"Apache-2.0"
] | null | null | null | 34.950617 | 116 | 0.788414 | 9,746 | /* DungeonDiver7: A Dungeon-Diving RPG
Copyright (C) 2021-present Eric Ahnell
Any questions should be directed to the author via email at: anpch@example.com
*/
package com.puttysoftware.dungeondiver7.dungeon.objects;
import com.puttysoftware.dungeondiver7.DungeonDiver7;
import com.puttysoftware.dungeondiver7.dungeon.abstractobjects.AbstractDungeonObject;
import com.puttysoftware.dungeondiver7.dungeon.abstractobjects.AbstractDisruptedObject;
import com.puttysoftware.dungeondiver7.loaders.SoundConstants;
import com.puttysoftware.dungeondiver7.loaders.SoundLoader;
import com.puttysoftware.dungeondiver7.utilities.Direction;
import com.puttysoftware.dungeondiver7.utilities.ArrowTypeConstants;
import com.puttysoftware.dungeondiver7.utilities.MaterialConstants;
import com.puttysoftware.dungeondiver7.utilities.TypeConstants;
public class DisruptedHotWall extends AbstractDisruptedObject {
// Fields
private int disruptionLeft;
private static final int DISRUPTION_START = 20;
// Constructors
public DisruptedHotWall() {
super();
this.type.set(TypeConstants.TYPE_PLAIN_WALL);
this.disruptionLeft = DisruptedHotWall.DISRUPTION_START;
this.activateTimer(1);
this.setMaterial(MaterialConstants.MATERIAL_FIRE);
}
DisruptedHotWall(final int disruption) {
super();
this.type.set(TypeConstants.TYPE_PLAIN_WALL);
this.disruptionLeft = disruption;
this.activateTimer(1);
this.setMaterial(MaterialConstants.MATERIAL_FIRE);
}
@Override
public Direction laserEnteredAction(final int locX, final int locY, final int locZ, final int dirX, final int dirY,
final int laserType, final int forceUnits) {
if (laserType == ArrowTypeConstants.LASER_TYPE_STUNNER) {
// Cool off disrupted hot wall
SoundLoader.playSound(SoundConstants.SOUND_COOL_OFF);
DungeonDiver7.getApplication().getGameManager().morph(new DisruptedWall(this.disruptionLeft), locX, locY, locZ,
this.getLayer());
return Direction.NONE;
} else {
// Stop laser
return super.laserEnteredAction(locX, locY, locZ, dirX, dirY, laserType, forceUnits);
}
}
@Override
public void timerExpiredAction(final int locX, final int locY) {
this.disruptionLeft--;
if (this.disruptionLeft == 0) {
SoundLoader.playSound(SoundConstants.SOUND_DISRUPT_END);
final int z = DungeonDiver7.getApplication().getGameManager().getPlayerManager().getPlayerLocationZ();
DungeonDiver7.getApplication().getGameManager().morph(new HotWall(), locX, locY, z, this.getLayer());
} else {
this.activateTimer(1);
}
}
@Override
public final int getStringBaseID() {
return 59;
}
@Override
public AbstractDungeonObject changesToOnExposure(final int materialID) {
switch (materialID) {
case MaterialConstants.MATERIAL_ICE:
return new DisruptedWall(this.disruptionLeft);
default:
return this;
}
}
} |
3e16e1127f9773349eca6114f80cf2de6e83909f | 3,774 | java | Java | custom-markers/src/test/hu/kecskesk/custommarker/handlers/RadioHandlerTest.java | kecskesk/org.eclipsecon2012.jdt.tutorial | 362dc0f7b176fd9e62c3d22121ee7f2e5497bffc | [
"MIT"
] | null | null | null | custom-markers/src/test/hu/kecskesk/custommarker/handlers/RadioHandlerTest.java | kecskesk/org.eclipsecon2012.jdt.tutorial | 362dc0f7b176fd9e62c3d22121ee7f2e5497bffc | [
"MIT"
] | null | null | null | custom-markers/src/test/hu/kecskesk/custommarker/handlers/RadioHandlerTest.java | kecskesk/org.eclipsecon2012.jdt.tutorial | 362dc0f7b176fd9e62c3d22121ee7f2e5497bffc | [
"MIT"
] | null | null | null | 32.534483 | 83 | 0.790143 | 9,747 | package hu.kecskesk.custommarker.handlers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.eclipse.core.commands.CommandManager;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.State;
import org.eclipse.ui.handlers.RadioState;
import org.junit.jupiter.api.Test;
import hu.kecskesk.custommarker.Activator;
import hu.kecskesk.custommarker.TestBase;
import hu.kecskesk.custommarker.handlers.markervisitors.AnonymusClassVisitor;
import hu.kecskesk.custommarker.handlers.markervisitors.ForEachVisitor;
import hu.kecskesk.custommarker.handlers.markervisitors.TryResourceVisitor;
import hu.kecskesk.utils.Constants;
class RadioHandlerTest extends TestBase {
@Test
void testRadioHandleDefault() throws ExecutionException {
// Arrange
String immutableValue = "Immutable";
parameterMap.put(RadioState.PARAMETER_ID, immutableValue);
commandState = new State();
commandState.setValue(immutableValue);
command = new CommandManager().getCommand("commandID");
command.addState(RadioState.STATE_ID, commandState);
new Activator();
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.IMMUTABLE_CONSTANT);
assertEquals(Activator.activeMarkerVisitor.size(), 0);
}
@Test
void testRadioHandleImmutable() throws ExecutionException {
// Arrange
String immutableValue = "Immutable";
parameterMap.put(RadioState.PARAMETER_ID, immutableValue);
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.IMMUTABLE_CONSTANT);
assertEquals(Activator.activeMarkerVisitor.size(), 0);
}
@Test
void testRadioHandleOptional() throws ExecutionException {
// Arrange
String optionalValue = "Optional";
parameterMap.put(RadioState.PARAMETER_ID, optionalValue);
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.OPTIONAL_CONSTANT);
assertEquals(Activator.activeMarkerVisitor.size(), 2);
}
@Test
void testRadioHandleForEach() throws ExecutionException {
// Arrange
String optionalValue = "For Each";
parameterMap.put(RadioState.PARAMETER_ID, optionalValue);
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.FOR_EACH_CONSTANT);
assertTrue(Activator.activeMarkerVisitor.get(0) instanceof ForEachVisitor);
}
@Test
void testRadioHandleTryResource() throws ExecutionException {
// Arrange
String optionalValue = "Try with Resources";
parameterMap.put(RadioState.PARAMETER_ID, optionalValue);
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.TRY_RES_CONSTANT);
assertTrue(Activator.activeMarkerVisitor.get(0) instanceof TryResourceVisitor);
}
@Test
void testRadioHandleDiamond() throws ExecutionException {
// Arrange
String optionalValue = "Diamond Operator";
parameterMap.put(RadioState.PARAMETER_ID, optionalValue);
// Act
radioEvent = new ExecutionEvent(command, parameterMap, null, null);
radioHandler.execute(radioEvent);
// Assert
assertEquals(Activator.ACTIVE_CONSTANT, Constants.ANONYM_CONSTANT);
assertTrue(Activator.activeMarkerVisitor.get(0) instanceof AnonymusClassVisitor);
}
}
|
3e16e119a33682a76c58ce95478748fc3f252437 | 4,128 | java | Java | src/ch/epfl/tchu/net/Helpers.java | edouardmichelin/tchu | 7662f44a5fe8eed6c3a38e560bd224f03d058c83 | [
"MIT"
] | null | null | null | src/ch/epfl/tchu/net/Helpers.java | edouardmichelin/tchu | 7662f44a5fe8eed6c3a38e560bd224f03d058c83 | [
"MIT"
] | 4 | 2021-06-08T01:57:35.000Z | 2021-06-08T01:57:36.000Z | src/ch/epfl/tchu/net/Helpers.java | edouardmichelin/tchu | 7662f44a5fe8eed6c3a38e560bd224f03d058c83 | [
"MIT"
] | null | null | null | 30.131387 | 93 | 0.55063 | 9,748 | package ch.epfl.tchu.net;
import ch.epfl.tchu.Preconditions;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Classe d'outils pour le package <i>ch.epfl.tchu.net</i>
*
* @author Edouard Michelin (314770)
* @author Julien Jordan (315429)
*/
final class Helpers {
private Helpers() {}
/**
* Repprésente un gestionnaire de messages envoyés sur le réseau
*/
public static class MessageHandler {
private final BufferedReader reader;
private final BufferedWriter writer;
private MessageHandler() {
this.reader = null;
this.writer = null;
}
protected MessageHandler(BufferedReader reader, BufferedWriter writer) {
this.reader = Objects.requireNonNull(reader);
this.writer = Objects.requireNonNull(writer);
}
/**
* Libère l'espace pris par le lecteur et l'écrivain
* @throws IOException
*/
public void dispose() throws IOException {
Preconditions.checkArgument(this.reader != null);
Preconditions.checkArgument(this.writer != null);
this.reader.close();
this.writer.close();
}
/**
* Retourne <i>true</i> ssi le lecteur est prêt à lire un message sur le réseau
* @return <code>true</code> ssi le lecteur est prêt à lire un message sur le réseau
*/
public boolean ready() {
if (this.reader == null) return false;
try {
return this.reader.ready();
} catch (IOException ignored) {
return false;
}
}
private static String formatMessage(MessageId messageId, String message) {
return String.format("%s %s\n", messageId.name(), message);
}
/**
* Envois un message sur le réseau
* @param messageId id du message
* @param message contenu seérialisé du message
*/
public void post(MessageId messageId, String message) {
Preconditions.checkArgument(this.writer != null);
try {
this.writer.write(formatMessage(messageId, message));
this.writer.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Cherche un message sur le réseau et le récupère
* @return un <code>Payload</code> qui contient le message
*/
public Payload get() {
Preconditions.checkArgument(this.reader != null);
try {
return new Payload(this.reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
/**
* Représente le contenu d'un message qui transit sur le réseau
*/
public static class Payload {
private final MessageId id;
private final List<String> content;
/**
* Construit un message destiné à être envoyé sur le réseau
* @param message
*/
public Payload(String message) {
String[] messageParts = message.split(Pattern.quote(" "), -1);
Preconditions.checkArgument(messageParts.length >= 1);
this.id = MessageId.valueOf(messageParts[0]);
this.content = List.of(messageParts).subList(1, messageParts.length);
}
/**
* Retourne l'id du message
* @return l'id du message
*/
public MessageId id() {
return this.id;
}
/**
* Retourne le contenu sérialisé du message
* @return le contenu sérialisé du message
*/
public List<String> content() {
return this.content;
}
}
}
|
3e16e139fba6241a53446b00241a837a7be2b5a3 | 2,384 | java | Java | bundles/org.connectorio.plc4x.decorator.retry/src/test/java/org/connectorio/plc4x/decorator/retry/SimulatedProtocolLogic.java | ConnectorIO/connectorio-addons | 11fccfe938063441d03bd9a6bb8a8b5daa3a9219 | [
"Apache-2.0"
] | 8 | 2020-10-14T17:49:40.000Z | 2022-03-30T10:48:24.000Z | bundles/org.connectorio.plc4x.decorator.retry/src/test/java/org/connectorio/plc4x/decorator/retry/SimulatedProtocolLogic.java | ConnectorIO/connectorio-addons | 11fccfe938063441d03bd9a6bb8a8b5daa3a9219 | [
"Apache-2.0"
] | 4 | 2021-08-12T10:08:33.000Z | 2021-08-18T13:29:16.000Z | bundles/org.connectorio.plc4x.decorator.retry/src/test/java/org/connectorio/plc4x/decorator/retry/SimulatedProtocolLogic.java | ConnectorIO/connectorio-addons | 11fccfe938063441d03bd9a6bb8a8b5daa3a9219 | [
"Apache-2.0"
] | null | null | null | 35.58209 | 115 | 0.797819 | 9,749 | /*
* Copyright (C) 2019-2021 ConnectorIO Sp. z o.o.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.connectorio.plc4x.decorator.retry;
import java.util.concurrent.CompletableFuture;
import org.apache.plc4x.java.api.messages.PlcReadRequest;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.apache.plc4x.java.api.messages.PlcSubscriptionRequest;
import org.apache.plc4x.java.api.messages.PlcSubscriptionResponse;
import org.apache.plc4x.java.api.messages.PlcUnsubscriptionRequest;
import org.apache.plc4x.java.api.messages.PlcUnsubscriptionResponse;
import org.apache.plc4x.java.api.messages.PlcWriteRequest;
import org.apache.plc4x.java.api.messages.PlcWriteResponse;
import org.apache.plc4x.java.simulated.connection.SimulatedConnection;
import org.apache.plc4x.java.spi.ConversationContext;
import org.apache.plc4x.java.spi.Plc4xProtocolBase;
public class SimulatedProtocolLogic<T> extends Plc4xProtocolBase<T> {
public final SimulatedConnection connection;
public SimulatedProtocolLogic(SimulatedConnection connection) {
this.connection = connection;
}
@Override
public CompletableFuture<PlcReadResponse> read(PlcReadRequest readRequest) {
return connection.read(readRequest);
}
@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
return connection.write(writeRequest);
}
@Override
public CompletableFuture<PlcSubscriptionResponse> subscribe(PlcSubscriptionRequest subscriptionRequest) {
return connection.subscribe(subscriptionRequest);
}
@Override
public CompletableFuture<PlcUnsubscriptionResponse> unsubscribe(PlcUnsubscriptionRequest unsubscriptionRequest) {
return connection.unsubscribe(unsubscriptionRequest);
}
@Override
public void close(ConversationContext<T> context) {
}
}
|
3e16e18f047026e368e899485bfce62fdbdd992e | 7,107 | java | Java | java/java.editor/test/unit/data/org/netbeans/modules/java/editor/javadocsnippet/data/HighlightTag.java | blackleg/netbeans | 030c2f302a8d67fedc4ccff789fcf1acfb977986 | [
"Apache-2.0"
] | null | null | null | java/java.editor/test/unit/data/org/netbeans/modules/java/editor/javadocsnippet/data/HighlightTag.java | blackleg/netbeans | 030c2f302a8d67fedc4ccff789fcf1acfb977986 | [
"Apache-2.0"
] | null | null | null | java/java.editor/test/unit/data/org/netbeans/modules/java/editor/javadocsnippet/data/HighlightTag.java | blackleg/netbeans | 030c2f302a8d67fedc4ccff789fcf1acfb977986 | [
"Apache-2.0"
] | null | null | null | 35.713568 | 202 | 0.488814 | 9,750 | package test;
public class Test {
public record R(int ff) {
}
/**
* A simple program.
*
* {@link System#out}
* {@snippet :
* class HelloWorld {
* public static void main(String... args) {
* System.out.println("Hello World!"); // @highlight substring="println"
* }
* }
* }
*/
private static void method(R r) {
int i = r.ff();
}
/**
* {@snippet :
* public static void main(String... args) {
* for (var arg : args) { // @highlight substring = "args"
* if (!arg.isBlankarg()) { // @highlight substring = "arg"
* System.out.println(arg); // @highlight substring = "arg" @highlight substring = "println"
* }
* }
* }
* }
*/
public void highlightUsingSubstring() {
}
/**
* {@snippet :
* public static void main(String... args1) {
* for (var arg : args1) { // @highlight regex="[0-9]+"
* if (!arg.isBlankarg()) { // @highlight regex = "\barg\b"
* System.out.println(args1); // @highlight regex = "out"
* }
* }
* }
* }
*/
public void highlightUsingRegex() {
}
/**
* {@snippet :
* public static void main(String... args1) {
* for (var arg : args1) { // @highlight regex="[0-9]+" @highlight substring="var"
* if (!arg.isBlankarg()) { // @highlight regex = "\barg\b" @highlight substring = "()"
* System.out.println("outs"); // @highlight regex = "\bout\b" @highlight substring="System"
* }
* }
* }
* }
*/
public void highlightUsingSubstringAndRegex() {
}
/**
* {@snippet :
* public static void main(String... substring) {
* for (var regex : substring) {
* if (!arg.isBlank()) {
* System.out.println("italic"); // @highlight substring="italic" type="italic"
* System.out.println("bold"); // @highlight substring="bold"
* System.out.println("highlight"); // @highlight substring="highlight" type="highlighted"
* // @highlight substring="italic" type="italic" @highlight substring="bold" @highlight substring="highlight" type="highlighted":
* System.out.println("italic and highlight and bold");
* // @highlight substring="italic-cum-highlight-cum-bold" @highlight substring="italic-cum-highlight-cum-bold" type="italic" @highlight substring="italic-cum-highlight-cum-bold" type="highlighted":
* System.out.println("italic-cum-highlight-cum-bold");
* System.out.println("Highlight all "+ substring + ":" + "subsubstringstring");// @highlight substring="substring"
*
* System.out.println("no mark up tag");//to-do
* // @highlight substring="substring" type = "italic" @highlight substring="substring" type = "highlighted" @highlight substring="substring" :
* System.out.println("Highlight/bold/italic all "+ substring + ":" + "subsubstringstring");
* System.out.println("Highlight all regular exp :regex:"+ regex + " :" + "regexregex" +" regex ");//@highlight regex = "\bregex\b"
* // @highlight regex = "\bregex\b" @highlight regex = "\bregex\b" type="italic" @highlight regex = "\bregex\b" type="highlighted":
* System.out.println("Highlight/bold/italic all regular exp :regex:"+ regex + ":" + "regexregex"+" regex ");
* }
* }
* }
* }
*/
public void highlightUsingSubstringRegexAndType() {
}
/**
* {@snippet :
* public static void main(String... args) {
* for (var arg : args) { // @highlight region substring = "arg"
* if (!arg.isBlankarg()) {
* System.out.println(arg);
* }
* } // @end
* }
* }
* {@snippet :
* public static void main(String... args) {
* for (var arg : args) { // @highlight region regex = "\barg\b"
* if (!arg.isBlankarg()) {
* System.out.println(arg);
* }
* } // @end
* }
* }
*/
public void highlightUsingMultipleSnippetTagInOneJavaDocWithRegion() {
}
/**
* {@snippet :
* public static void \bmain\b(String... args) {// @highlight regex = "\bmain\b"
* //@highlight substring="str" region = rg1 @highlight region=here substring = "arg" @highlight type="italic" substring="arg":
* for (var arg : args) {
* if (!arg.isBlargk()) {
* System.arg.println("arg");// @end region = here
* System.arg.println("arg");
* System.arg.println("tests");// @highlight substring = "tests" type = "highlighted"
* System.out.println("\barg\b"); // @highlight substring = "\barg\b" @end
* System.out.println("\barg\b"); // to-do
* }
* }
* }
* }
*/
public void highlightUsingNestedRegions() {
}
/**
* {@snippet :
* public static void \bmain\b(String... args) {
* for (var arg : args) { //@highlight substring="arg" region = rg1 type="highlighted": @highlight substring = "is"::
* if (!arg.isBlargk()) {
* System.arg.println("arg");
* System.arg.println("arg");
* System.arg.println("tests");
* System.out.println("\barg\b"); // @highlight substring = "\barg\b" @end
* System.out.println("\barg\b"); // to-do
* }
* }
* }
* }
*/
public void highlightUsingRegionsEndedWithDoubleColon() {
}
/**
* {@snippet :
* public static void main(String... args) {
* System.out.println("args"); // highligh substring = "args"
* }
* }
*/
public void noMarkupTagPresent() {
}
/**
* {@snippet :
* public static void main(String... args) {
* // @highlight substring = "args" :
* System.out.println("args"); // to-do args
* }
* }
*/
public void highlightTagSubstringApplyToNextLine() {
}
/**
* {@snippet :
* public static void main(String... args) {
* // @highlight regex = ".*" :
* System.out.println("args"); // to-do args
* }
* }
*/
public void highlightTagRegexWithAllCharacterChange() {
}
/**
* {@snippet :
* public static void main(String... args) {
* // @highlight regex = "." :
* System.out.println("args"); // to-do args
* }
* }
*/
public void highlightTagRegexWithAllCharacterChangeUsingDot() {
}
}
|
3e16e1932ca9145a69cc41c236fd1d6cb00245eb | 6,166 | java | Java | ls-eclipse/code/lsclipse/lsd/tyRuBa/engine/RuleBase.java | UCLA-SEAL/LSDiff | bf1a83c4ac444fc8354d2aaaae7a2ab5cb89feb7 | [
"BSD-3-Clause"
] | null | null | null | ls-eclipse/code/lsclipse/lsd/tyRuBa/engine/RuleBase.java | UCLA-SEAL/LSDiff | bf1a83c4ac444fc8354d2aaaae7a2ab5cb89feb7 | [
"BSD-3-Clause"
] | null | null | null | ls-eclipse/code/lsclipse/lsd/tyRuBa/engine/RuleBase.java | UCLA-SEAL/LSDiff | bf1a83c4ac444fc8354d2aaaae7a2ab5cb89feb7 | [
"BSD-3-Clause"
] | null | null | null | 29.797101 | 102 | 0.728923 | 9,751 | /*
* Logical Structural Diff (LSDiff)
* Copyright (C) <2015> <Dr. Miryung Kim hzdkv@example.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tyRuBa.engine;
import java.io.PrintStream;
import tyRuBa.engine.compilation.CompilationContext;
import tyRuBa.engine.compilation.Compiled;
import tyRuBa.engine.compilation.SemiDetCompiled;
import tyRuBa.modes.BindingList;
import tyRuBa.modes.Mode;
import tyRuBa.modes.Multiplicity;
import tyRuBa.modes.PredicateMode;
import tyRuBa.modes.TupleType;
import tyRuBa.modes.TypeModeError;
/**
* A RuleBase stores a collection of Logic inference rules and facts.
* It has a dependency tracking mechanism that holds on to its
* dependents weakly. Dependents are notified of a change to
* the rulebase by means of an update message.
*/
public abstract class RuleBase {
private QueryEngine engine;
long upToDateWith = -1;
private boolean uptodateCheck() {
if (upToDateWith < engine.frontend().updateCounter) {
forceRecompilation();
return false;
} else {
return true;
}
}
private void forceRecompilation() {
compiledRules = null;
semidetCompiledRules = null;
}
private Compiled compiledRules = null;
private SemiDetCompiled semidetCompiledRules = null;
/** Use a cache which remember query results ? */
public static boolean useCache = true;
/** If true Cache will use SoftValueMap which allows entries to be reclaimed
* by the garbage collector when low on memory */
public static boolean softCache = true;
/** Do not print Ho. characters while computing queries */
public static boolean silent = false;
/**
* This flag controls whether the QueryEngine will
* check for Bucket updates before running any query.
*/
public static boolean autoUpdate = true;
static final public boolean debug_tracing = false;
static final public boolean debug_checking = false;
// /** A collection of my dependents. They will get an update
// * message whenever my contents changes. The collection is
// * weak so that dependents can be gc-ed */
// private WeakCollection dependents = null;
//
// /** Add a dependend to my Weak collection of dependents */
// public void addDependent(Dependent d) {
// if (dependents == null)
// dependents = new WeakCollection();
// dependents.add(d);
// }
//
// /** Remove a depedent from my Weak collection of dependents */
// public void removeDependent(Dependent d) {
// if (dependents != null)
// dependents.remove(d);
// }
// /** Ask all my dependents to update themselves */
// public void update() {
// if (dependents != null) {
// Object[] deps = dependents.toArray();
// for (int i = 0; i < deps.length; i++) {
// ((Dependent) deps[i]).update();
// }
// }
// }
private PredicateMode predMode;
/**
* @category preparedSQLQueries
*/
private boolean isPersistent;
protected RuleBase(QueryEngine engine,PredicateMode predMode,boolean isSQLAble) {
this.engine = engine;
this.predMode = predMode;
this.isPersistent = isSQLAble;
}
/** return the predicate mode of this moded rulebase */
public PredicateMode getPredMode() {
return predMode;
}
/** return the list of binding modes of the predicate mode */
public BindingList getParamModes() {
return getPredMode().getParamModes();
}
/** return the expected mode of the predicate mode */
public Mode getMode() {
return getPredMode().getMode();
}
/**
* Returns true if this rulebase mode is expected to produce fewer results than other
*/
public boolean isBetterThan(RuleBase other) {
return getMode().isBetterThan(other.getMode());
}
public static BasicModedRuleBaseIndex make(FrontEnd frontEnd) {
return new BasicModedRuleBaseIndex(frontEnd, null);
}
/** Factory method for creating RuleBases **/
public static BasicModedRuleBaseIndex make(FrontEnd frontEnd, String identifier, boolean temporary) {
// if(identifier != null)
// engine.addGroup(identifier, temporary);
return new BasicModedRuleBaseIndex(frontEnd, identifier);
}
/** Add a rule to the rulebase */
abstract public void insert(RBComponent r, ModedRuleBaseIndex rulebases,
TupleType resultTypes) throws TypeModeError;
/** Retract a fact from the rulebase. This operation is not supported for
all kinds of RBComponents or all configurations of RuleBase implementations.
Not all concrete rulebases support the operation */
public void retract(RBFact f) {
throw new Error("Unsupported operation RETRACT");
}
/** Don't implement this for most rule bases */
public RuleBase addCondition(RBExpression e) {
throw new Error("Operation not implemented");
}
public void dumpFacts(PrintStream out) {
}
public Compiled getCompiled() {
uptodateCheck();
if (compiledRules == null) {
compiledRules = compile(new CompilationContext());
if (RuleBase.useCache)
compiledRules = Compiled.makeCachedRuleBase(compiledRules);
upToDateWith = engine.frontend().updateCounter;
}
return compiledRules;
}
public SemiDetCompiled getSemiDetCompiledRules() {
uptodateCheck();
if (semidetCompiledRules == null) {
Compiled compiled = getCompiled();
if (compiled.getMode().hi.compareTo(Multiplicity.one)>0)
semidetCompiledRules = compiled.first();
else
semidetCompiledRules = (SemiDetCompiled)compiled;
upToDateWith = engine.frontend().updateCounter;
}
return semidetCompiledRules;
}
protected abstract Compiled compile(CompilationContext context);
/**
* @category preparedSQLQueries
*/
public boolean isPersistent() {
return isPersistent;
}
}
|
3e16e289373bc1c1cda75ea74eba1c51083f070d | 5,761 | java | Java | app/src/main/java/com/seamk/mobile/FragmentExtras.java | alaviivarantala/seamklukkari | 41547e3581f9987748d45faa8e744d29777b7391 | [
"MIT"
] | null | null | null | app/src/main/java/com/seamk/mobile/FragmentExtras.java | alaviivarantala/seamklukkari | 41547e3581f9987748d45faa8e744d29777b7391 | [
"MIT"
] | 22 | 2018-02-27T11:55:40.000Z | 2018-02-27T12:06:30.000Z | app/src/main/java/com/seamk/mobile/FragmentExtras.java | alaviivarantala/seamklukkari | 41547e3581f9987748d45faa8e744d29777b7391 | [
"MIT"
] | null | null | null | 48.478992 | 166 | 0.635119 | 9,752 | package com.seamk.mobile;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.IItem;
import com.mikepenz.fastadapter.adapters.ItemAdapter;
import com.mikepenz.fastadapter.listeners.OnClickListener;
import com.seamk.mobile.objects.Extra;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Juha Ala-Rantala on 28.3.2018.
*/
public class FragmentExtras extends UtilityFragment {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
ItemAdapter<IItem> itemAdapter;
FastAdapter<IItem> fastAdapter;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_recycler_view, container, false);
ButterKnife.bind(this, v);
getActivity().setTitle(getString(R.string.extra_features));
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
itemAdapter = new ItemAdapter<>();
fastAdapter = FastAdapter.with(itemAdapter);
recyclerView.setAdapter(fastAdapter);
itemAdapter.clear();
itemAdapter.add(createExtras());
fastAdapter.withSelectable(true);
fastAdapter.withOnClickListener(new OnClickListener<IItem>() {
@Override
public boolean onClick(View v, @NonNull IAdapter<IItem> adapter, @NonNull IItem item, int position) {
switch (position){
case 0:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.frame, new FragmentPremiums(), "PREMIUMS_FRAGMENT");
fragmentTransaction.addToBackStack("TAG");
fragmentTransaction.commit();
break;
case 1:
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
transaction.replace(R.id.frame, new FragmentLinks(), "LINKS_FRAGMENT");
transaction.addToBackStack("TAG");
transaction.commit();
break;
case 2:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto: ychag@example.com"));
startActivity(Intent.createChooser(emailIntent, getString(R.string.send_feedback)));
break;
case 3:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getContext().getApplicationInfo());
String sAux = getResources().getString(R.string.download_app_message) + "\n";
sAux = sAux + "http://play.google.com/store/apps/details?id=" + getContext().getPackageName();
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, getResources().getString(R.string.choose_app)));
break;
case 4:
Uri uri = Uri.parse("market://details?id=" + getContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getContext().getPackageName())));
}
break;
}
return true;
}
});
return v;
}
private List<IItem> createExtras(){
List<IItem> extras = new ArrayList<>();
extras.add(new Extra(getResources().getString(R.string.support), getString(R.string.support_developer), "€", "ic_thumb_up", "extrasGoldColor"));
extras.add(new Extra(getResources().getString(R.string.links), getString(R.string.collection_useful_links), "", "ic_link_white", "colorPrimary"));
extras.add(new Extra(getResources().getString(R.string.feedback), getString(R.string.send_feedback), "", "ic_email", "colorPrimary"));
extras.add(new Extra(getResources().getString(R.string.share), getString(R.string.share_app), "", "ic_share", "colorPrimary"));
extras.add(new Extra(getResources().getString(R.string.rate), getString(R.string.rate_app_on_gplay), "", "ic_star", "colorPrimary"));
return extras;
}
}
|
3e16e2c6be25728f5aa17c41eb74f3e0a7ab57f8 | 2,480 | java | Java | gmall-wms/src/main/java/com/atguigu/gmall/wms/controller/PurchaseDetailController.java | XiaJava2021/gmall-0923 | c355859fdbd3271fc344578cfb92b5972fea1e3b | [
"Apache-2.0"
] | null | null | null | gmall-wms/src/main/java/com/atguigu/gmall/wms/controller/PurchaseDetailController.java | XiaJava2021/gmall-0923 | c355859fdbd3271fc344578cfb92b5972fea1e3b | [
"Apache-2.0"
] | null | null | null | gmall-wms/src/main/java/com/atguigu/gmall/wms/controller/PurchaseDetailController.java | XiaJava2021/gmall-0923 | c355859fdbd3271fc344578cfb92b5972fea1e3b | [
"Apache-2.0"
] | null | null | null | 26.404255 | 97 | 0.732071 | 9,753 | package com.atguigu.gmall.wms.controller;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gmall.wms.entity.PurchaseDetailEntity;
import com.atguigu.gmall.wms.service.PurchaseDetailService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.bean.PageParamVo;
/**
*
*
* @author xiatian
* @email nnheo@example.com
* @date 2021-03-08 19:42:55
*/
@Api(tags = " 管理")
@RestController
@RequestMapping("wms/purchasedetail")
public class PurchaseDetailController {
@Autowired
private PurchaseDetailService purchaseDetailService;
/**
* 列表
*/
@GetMapping
@ApiOperation("分页查询")
public ResponseVo<PageResultVo> queryPurchaseDetailByPage(PageParamVo paramVo){
PageResultVo pageResultVo = purchaseDetailService.queryPage(paramVo);
return ResponseVo.ok(pageResultVo);
}
/**
* 信息
*/
@GetMapping("{id}")
@ApiOperation("详情查询")
public ResponseVo<PurchaseDetailEntity> queryPurchaseDetailById(@PathVariable("id") Long id){
PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(id);
return ResponseVo.ok(purchaseDetail);
}
/**
* 保存
*/
@PostMapping
@ApiOperation("保存")
public ResponseVo<Object> save(@RequestBody PurchaseDetailEntity purchaseDetail){
purchaseDetailService.save(purchaseDetail);
return ResponseVo.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@ApiOperation("修改")
public ResponseVo update(@RequestBody PurchaseDetailEntity purchaseDetail){
purchaseDetailService.updateById(purchaseDetail);
return ResponseVo.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@ApiOperation("删除")
public ResponseVo delete(@RequestBody List<Long> ids){
purchaseDetailService.removeByIds(ids);
return ResponseVo.ok();
}
}
|
3e16e2ecb29731f7bfb44a0fd41a1d580dae6e47 | 2,304 | java | Java | src/main/java/jp/ossc/nimbus/util/crypt/OverLimitExpiresException.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 26 | 2018-01-16T10:21:31.000Z | 2021-09-10T02:28:47.000Z | src/main/java/jp/ossc/nimbus/util/crypt/OverLimitExpiresException.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 473 | 2018-02-08T06:51:43.000Z | 2021-09-08T07:35:59.000Z | src/main/java/jp/ossc/nimbus/util/crypt/OverLimitExpiresException.java | nimbus-org/nimbus | 43a511499e9cd7f27515ddb8d493b2af44346abc | [
"BSD-3-Clause"
] | 1 | 2018-05-31T14:30:33.000Z | 2018-05-31T14:30:33.000Z | 39.050847 | 80 | 0.693142 | 9,754 | /*
* This software is distributed under following license based on modified BSD
* style license.
* ----------------------------------------------------------------------
*
* Copyright 2003 The Nimbus Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NIMBUS PROJECT ``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 NIMBUS PROJECT 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the Nimbus Project.
*/
package jp.ossc.nimbus.util.crypt;
/**
* 有効期限が過ぎてしまった事を示す例外クラス。<p>
*
* @author M.Takata
*/
public class OverLimitExpiresException extends Exception{
private static final long serialVersionUID = -4194168020512092039L;
/**
* インスタンスを生成する。<p>
*/
public OverLimitExpiresException(){
super();
}
/**
* インスタンスを生成する。<p>
*
* @param message メッセージ
*/
public OverLimitExpiresException(String message){
super(message);
}
}
|
3e16e387eeda17428ff8042f979ea727f116050c | 663 | java | Java | src/main/java/org/sakaiproject/nakamura/lite/types/BooleanType.java | danjung/sparsemapcontent | ef66f954e19bee75754192961b93b2a9163dbf54 | [
"Apache-2.0"
] | 1 | 2019-02-22T03:06:40.000Z | 2019-02-22T03:06:40.000Z | src/main/java/org/sakaiproject/nakamura/lite/types/BooleanType.java | danjung/sparsemapcontent | ef66f954e19bee75754192961b93b2a9163dbf54 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sakaiproject/nakamura/lite/types/BooleanType.java | danjung/sparsemapcontent | ef66f954e19bee75754192961b93b2a9163dbf54 | [
"Apache-2.0"
] | null | null | null | 21.387097 | 77 | 0.68175 | 9,755 | package org.sakaiproject.nakamura.lite.types;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class BooleanType implements Type<Boolean> {
public int getTypeId() {
return 5;
}
public void save(DataOutputStream dos, Object value) throws IOException {
dos.writeBoolean((Boolean) value);
}
public Boolean load(DataInputStream in) throws IOException {
return in.readBoolean();
}
public Class<Boolean> getTypeClass() {
return Boolean.class;
}
public boolean accepts(Object object) {
return (object instanceof Boolean);
}
}
|
3e16e3c68f950d12c8263a9e85d3458be71186b9 | 647 | java | Java | src/test/java/com/saasquatch/jsonschemainferrer/TestJunkDrawer.java | peiyuwang/json-schema-inferrer | 2245ab1c9255ff3e0479f9173da3f038cc10d595 | [
"Apache-2.0"
] | 76 | 2019-10-28T23:53:55.000Z | 2022-03-19T08:44:01.000Z | src/test/java/com/saasquatch/jsonschemainferrer/TestJunkDrawer.java | HaloAlessia/json-schema-inferrer | eb2c50a03c6abd5c3a7696f0ec78554005bdbe71 | [
"Apache-2.0"
] | 14 | 2019-10-28T23:52:52.000Z | 2021-11-01T14:51:46.000Z | src/test/java/com/saasquatch/jsonschemainferrer/TestJunkDrawer.java | HaloAlessia/json-schema-inferrer | eb2c50a03c6abd5c3a7696f0ec78554005bdbe71 | [
"Apache-2.0"
] | 22 | 2020-03-12T11:30:12.000Z | 2022-03-28T02:33:26.000Z | 28.130435 | 69 | 0.772798 | 9,756 | package com.saasquatch.jsonschemainferrer;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
public final class TestJunkDrawer {
private TestJunkDrawer() {}
public static final JsonNodeFactory jnf = JsonNodeFactory.instance;
public static final ObjectMapper mapper = new ObjectMapper();
public static Set<String> toStringSet(JsonNode arrayNode) {
final Set<String> result = new HashSet<>();
arrayNode.forEach(j -> result.add(j.textValue()));
return result;
}
}
|
3e16e5c7a689ff2f1dc9bb76bd2347b8a16f2c8a | 6,864 | java | Java | strongbox-web-core/src/test/java/org/carlspring/strongbox/config/IntegrationTest.java | tigeroster/strongbox | b2e9c733394267ed14346375e3ddd1aa5e709a89 | [
"Apache-2.0"
] | 530 | 2015-04-06T19:42:22.000Z | 2022-03-25T06:02:28.000Z | strongbox-web-core/src/test/java/org/carlspring/strongbox/config/IntegrationTest.java | tigeroster/strongbox | b2e9c733394267ed14346375e3ddd1aa5e709a89 | [
"Apache-2.0"
] | 1,589 | 2016-03-10T15:07:50.000Z | 2022-03-20T01:13:20.000Z | strongbox-web-core/src/test/java/org/carlspring/strongbox/config/IntegrationTest.java | tigeroster/strongbox | b2e9c733394267ed14346375e3ddd1aa5e709a89 | [
"Apache-2.0"
] | 848 | 2015-02-27T15:23:59.000Z | 2022-03-22T03:40:51.000Z | 40.857143 | 127 | 0.710227 | 9,757 | package org.carlspring.strongbox.config;
import org.carlspring.strongbox.MockedRemoteRepositoriesHeartbeatConfig;
import org.carlspring.strongbox.app.StrongboxSpringBootApplication;
import org.carlspring.strongbox.controllers.logging.SseEmitterAwareTailerListenerAdapter;
import org.carlspring.strongbox.cron.services.CronJobSchedulerService;
import org.carlspring.strongbox.data.CacheManagerTestExecutionListener;
import org.carlspring.strongbox.rest.client.MockMvcRequestSpecificationProxyTarget;
import org.carlspring.strongbox.rest.client.RestAssuredArtifactClient;
import org.carlspring.strongbox.storage.indexing.remote.MockedIndexResourceFetcher;
import org.carlspring.strongbox.storage.indexing.remote.ResourceFetcherFactory;
import org.carlspring.strongbox.testing.MavenMetadataServiceHelper;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Function;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.config.ObjectMapperConfig;
import io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import io.restassured.module.mockmvc.internal.MockMvcFactory;
import io.restassured.module.mockmvc.internal.MockMvcRequestSpecificationImpl;
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.maven.index.updater.ResourceFetcher;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* Helper meta annotation for all rest-assured based tests. Specifies tests that
* require web server and remote HTTP protocol.
*
* @author Alex Oreshkevich
* @author Przemyslaw Fusik
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(classes = { StrongboxSpringBootApplication.class,
MockedRemoteRepositoriesHeartbeatConfig.class,
IntegrationTest.IntegrationTestsConfiguration.class,
TestingCoreConfig.class })
@WebAppConfiguration("classpath:")
@WithUserDetails("admin")
@ActiveProfiles("test")
@TestExecutionListeners(listeners = CacheManagerTestExecutionListener.class,
mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
@Execution(ExecutionMode.SAME_THREAD)
public @interface IntegrationTest
{
@Configuration
class IntegrationTestsConfiguration
{
@Bean
@Primary
CronJobSchedulerService mockCronJobSchedulerService()
{
return Mockito.mock(CronJobSchedulerService.class);
}
@Bean
@Primary
ResourceFetcher mockedIndexResourceFetcher()
{
return new MockedIndexResourceFetcher();
}
@Bean
@Primary
ResourceFetcherFactory mockedResourceFetcherMockFactory(ResourceFetcher resourceFetcher)
{
final ResourceFetcherFactory resourceFetcherFactory = Mockito.mock(ResourceFetcherFactory.class);
Mockito.when(resourceFetcherFactory.createIndexResourceFetcher(ArgumentMatchers.anyString(),
ArgumentMatchers.any(
CloseableHttpClient.class)))
.thenReturn(resourceFetcher);
return resourceFetcherFactory;
}
@Bean
public MavenMetadataServiceHelper mavenMetadataServiceHelper()
{
return new MavenMetadataServiceHelper();
}
@Bean
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MockMvcRequestSpecification mockMvc(ApplicationContext applicationContext)
{
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(
(WebApplicationContext) applicationContext);
ObjectMapper objectMapper = applicationContext.getBean(ObjectMapper.class);
ObjectMapperConfig objectMapperFactory = new ObjectMapperConfig().jackson2ObjectMapperFactory((aClass,
s) -> objectMapper);
RestAssuredMockMvcConfig config = RestAssuredMockMvcConfig.config().objectMapperConfig(objectMapperFactory);
return new MockMvcRequestSpecificationProxyTarget(
new MockMvcRequestSpecificationImpl(new MockMvcFactory(builder), config, null, null,
null, null, null, null));
}
@Bean
public RestAssuredArtifactClient artifactClient(MockMvcRequestSpecification mockMvc)
{
return new RestAssuredArtifactClient(mockMvc);
}
@Primary
@Bean
public Function<SseEmitter, SseEmitterAwareTailerListenerAdapter> testTailerListenerAdapterPrototypeFactory()
{
return sseEmitter -> testTailerListener(sseEmitter);
}
@Primary
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public SseEmitterAwareTailerListenerAdapter testTailerListener(SseEmitter sseEmitter)
{
return new TestSseEmitterAwareTailerListenerAdapter(sseEmitter);
}
static class TestSseEmitterAwareTailerListenerAdapter
extends SseEmitterAwareTailerListenerAdapter
{
public TestSseEmitterAwareTailerListenerAdapter(final SseEmitter sseEmitter)
{
super(sseEmitter);
}
@Override
public void handle(final String line)
{
super.handle(line);
if (sseEmitter != null)
{
sseEmitter.complete();
}
}
}
}
}
|
3e16e62047b683090841480c17137e838aa45067 | 4,634 | java | Java | src/main/java/org/jpy/PyLibConfig.java | gbaier/jpy | dfb8eadfcaf8a2e12e4831ee149e381f42d26c37 | [
"Apache-2.0"
] | 210 | 2015-03-19T14:07:16.000Z | 2022-03-31T19:28:13.000Z | src/main/java/org/jpy/PyLibConfig.java | gbaier/jpy | dfb8eadfcaf8a2e12e4831ee149e381f42d26c37 | [
"Apache-2.0"
] | 141 | 2015-01-07T03:04:55.000Z | 2021-08-05T09:23:22.000Z | src/main/java/org/jpy/PyLibConfig.java | gbaier/jpy | dfb8eadfcaf8a2e12e4831ee149e381f42d26c37 | [
"Apache-2.0"
] | 40 | 2015-10-17T13:53:41.000Z | 2021-07-18T20:09:11.000Z | 33.338129 | 123 | 0.617393 | 9,758 | /*
* Copyright 2015 Brockmann Consult GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jpy;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;
import java.util.Set;
/**
* Provides configuration for {@link org.jpy.PyLib}.
*
* @author Norman Fomferra
* @since 0.7
*/
class PyLibConfig {
private static final boolean DEBUG = Boolean.getBoolean("jpy.debug");
public static final String PYTHON_LIB_KEY = "jpy.pythonLib";
public static final String JPY_LIB_KEY = "jpy.jpyLib";
public static final String JPY_CONFIG_KEY = "jpy.config";
public static final String JPY_CONFIG_RESOURCE = "jpyconfig.properties";
public enum OS {
WINDOWS,
UNIX,
MAC_OS,
SUNOS,
}
private static final Properties properties = new Properties();
static {
if (DEBUG) System.out.println("org.jpy.PyLibConfig: entered static initializer");
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(JPY_CONFIG_RESOURCE);
if (stream != null) {
loadConfig(stream, JPY_CONFIG_RESOURCE);
}
String path = System.getProperty(JPY_CONFIG_KEY);
if (path != null) {
File file = new File(path);
if (file.isFile()) {
loadConfig(file);
}
}
File file = new File(JPY_CONFIG_RESOURCE).getAbsoluteFile();
if (file.isFile()) {
loadConfig(file);
}
if (DEBUG) System.out.println("org.jpy.PyLibConfig: exited static initializer");
}
private static void loadConfig(InputStream stream, String name) {
try {
if (DEBUG)
System.out.printf(String.format("org.jpy.PyLibConfig: loading configuration resource %s\n", name));
try (Reader reader = new InputStreamReader(stream)) {
loadConfig(reader);
}
} catch (IOException e) {
if (DEBUG) e.printStackTrace(System.err);
}
}
private static void loadConfig(File file) {
try {
if (DEBUG)
System.out.printf(String.format("%s: loading configuration file %s\n", PyLibConfig.class.getName(), file));
try (Reader reader = new FileReader(file)) {
loadConfig(reader);
}
} catch (IOException e) {
System.err.printf("org.jpy.PyLibConfig: %s: %s\n", file, e.getMessage());
if (DEBUG) e.printStackTrace(System.err);
}
}
private static void loadConfig(Reader reader) throws IOException {
properties.load(reader);
Set<String> propertyNames = properties.stringPropertyNames();
for (String propertyName : propertyNames) {
String propertyValue = properties.getProperty(propertyName);
if (propertyValue != null) {
System.setProperty(propertyName, propertyValue);
}
}
}
public static Properties getProperties() {
return new Properties(properties);
}
public static String getProperty(String key, boolean mustHave) {
// System properties overwrite .jpy properties
String property = System.getProperty(key);
if (property != null) {
return property;
}
property = properties.getProperty(key);
if (property == null && mustHave) {
throw new RuntimeException("missing configuration property '" + key + "'");
}
return property;
}
public static OS getOS() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
return OS.WINDOWS;
} else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
return OS.UNIX;
} else if (os.contains("mac")) {
return OS.MAC_OS;
} else if (os.contains("sunos")) {
return OS.SUNOS;
}
return null;
}
}
|
3e16e6849f466d7d2a097df80119f10f4035487d | 211 | java | Java | users-center/src/main/java/com/github/users/center/services/IConfirmService.java | HellcrowAndrey/fenix | b461e552a969c146b6306d8d9c0a3d8c6f3821e1 | [
"Apache-2.0"
] | null | null | null | users-center/src/main/java/com/github/users/center/services/IConfirmService.java | HellcrowAndrey/fenix | b461e552a969c146b6306d8d9c0a3d8c6f3821e1 | [
"Apache-2.0"
] | null | null | null | users-center/src/main/java/com/github/users/center/services/IConfirmService.java | HellcrowAndrey/fenix | b461e552a969c146b6306d8d9c0a3d8c6f3821e1 | [
"Apache-2.0"
] | 1 | 2020-09-09T15:56:36.000Z | 2020-09-09T15:56:36.000Z | 23.444444 | 51 | 0.791469 | 9,759 | package com.github.users.center.services;
import com.github.users.center.entity.ConfirmToken;
public interface IConfirmService {
void create(ConfirmToken ct);
ConfirmToken readByToken(String token);
}
|
3e16e6911a0bedc7324b334aaa8e2edd17369d3c | 6,141 | java | Java | modules/flowable-ui-idm/flowable-ui-idm-logic/src/main/java/org/flowable/ui/idm/service/UserCacheImpl.java | gaoyida/flowable-engine | b6875949741c9807da6d2c34121bc4dee1e63b3f | [
"Apache-2.0"
] | 3 | 2019-05-07T02:58:38.000Z | 2021-03-12T05:50:45.000Z | modules/flowable-ui-idm/flowable-ui-idm-logic/src/main/java/org/flowable/ui/idm/service/UserCacheImpl.java | gaoyida/flowable-engine | b6875949741c9807da6d2c34121bc4dee1e63b3f | [
"Apache-2.0"
] | 6 | 2018-10-16T06:04:06.000Z | 2021-12-08T05:59:47.000Z | modules/flowable-ui-idm/flowable-ui-idm-logic/src/main/java/org/flowable/ui/idm/service/UserCacheImpl.java | gaoyida/flowable-engine | b6875949741c9807da6d2c34121bc4dee1e63b3f | [
"Apache-2.0"
] | 2 | 2018-12-03T11:14:18.000Z | 2018-12-03T13:09:27.000Z | 40.137255 | 188 | 0.666992 | 9,760 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.ui.idm.service;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.idm.api.User;
import org.flowable.spring.boot.ldap.FlowableLdapProperties;
import org.flowable.ui.common.properties.FlowableCommonAppProperties;
import org.flowable.ui.idm.cache.UserCache;
import org.flowable.ui.idm.model.UserInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
* Cache containing User objects to prevent too much DB-traffic (users exist separately from the Flowable tables, they need to be fetched afterward one by one to join with those entities).
* <p>
* TODO: This could probably be made more efficient with bulk getting. The Google cache impl allows this: override loadAll and use getAll() to fetch multiple entities.
*
* @author Frederik Heremans
* @author Joram Barrez
* @author Filip Hrisafov
*/
@Service
public class UserCacheImpl implements UserCache {
@Autowired
protected FlowableCommonAppProperties properties;
protected FlowableLdapProperties ldapProperties;
@Autowired
protected IdmIdentityService identityService;
@Autowired
protected UserService userService;
protected LoadingCache<String, CachedUser> userCache;
@PostConstruct
protected void initCache() {
FlowableCommonAppProperties.Cache cache = properties.getCacheUsers();
long userCacheMaxSize = cache.getMaxSize();
long userCacheMaxAge = cache.getMaxAge();
userCache = CacheBuilder.newBuilder().maximumSize(userCacheMaxSize)
.expireAfterAccess(userCacheMaxAge, TimeUnit.SECONDS).recordStats().build(new CacheLoader<String, CachedUser>() {
public CachedUser load(final String userId) throws Exception {
User userFromDatabase = null;
if (ldapProperties == null || !ldapProperties.isEnabled()) {
userFromDatabase = identityService.createUserQuery().userIdIgnoreCase(userId.toLowerCase()).singleResult();
} else {
userFromDatabase = identityService.createUserQuery().userId(userId).singleResult();
}
if (userFromDatabase == null) {
throw new UsernameNotFoundException("User " + userId + " was not found in the database");
}
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
UserInformation userInformation = userService.getUserInformation(userFromDatabase.getId());
for (String privilege : userInformation.getPrivileges()) {
grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
}
return new CachedUser(userFromDatabase, grantedAuthorities);
}
});
}
public void putUser(String userId, CachedUser cachedUser) {
userCache.put(userId, cachedUser);
}
public CachedUser getUser(String userId) {
return getUser(userId, false, false, true); // always check validity by default
}
public CachedUser getUser(String userId, boolean throwExceptionOnNotFound, boolean throwExceptionOnInactive, boolean checkValidity) {
try {
// The cache is a LoadingCache and will fetch the value itself
CachedUser cachedUser = userCache.get(userId);
return cachedUser;
} catch (ExecutionException e) {
return null;
} catch (UncheckedExecutionException uee) {
// Some magic with the exceptions is needed:
// the exceptions like UserNameNotFound and Locked cannot
// bubble up, since Spring security will react on them otherwise
if (uee.getCause() instanceof RuntimeException) {
RuntimeException runtimeException = (RuntimeException) uee.getCause();
if (runtimeException instanceof UsernameNotFoundException) {
if (throwExceptionOnNotFound) {
throw runtimeException;
} else {
return null;
}
}
if (runtimeException instanceof LockedException) {
if (throwExceptionOnNotFound) {
throw runtimeException;
} else {
return null;
}
}
}
throw uee;
}
}
@Override
public void invalidate(String userId) {
userCache.invalidate(userId);
}
@Autowired(required = false)
public void setLdapProperties(FlowableLdapProperties ldapProperties) {
this.ldapProperties = ldapProperties;
}
}
|
3e16e7ebda8ebc9f5ea81066122e0b9407a62110 | 687 | java | Java | OODFinal/src/Drink/HotDrink.java | bbobbylon/OODFinal | e43ea3d2306a5274393c54d962ea5641352743eb | [
"MIT"
] | null | null | null | OODFinal/src/Drink/HotDrink.java | bbobbylon/OODFinal | e43ea3d2306a5274393c54d962ea5641352743eb | [
"MIT"
] | null | null | null | OODFinal/src/Drink/HotDrink.java | bbobbylon/OODFinal | e43ea3d2306a5274393c54d962ea5641352743eb | [
"MIT"
] | null | null | null | 20.205882 | 54 | 0.585153 | 9,761 | package Drink;
public abstract class HotDrink implements Drink {
public abstract double costOfDrink();
public abstract String getDescription();
public abstract void prepare();
public abstract void addOns();
boolean addOnOption(){
return true;
}
// here is the template method
@Override
public void prepareADrink(){
boilWater();
prepare();
serveADrink();
if (addOnOption()){
addOns();
}
}
private void serveADrink() {
System.out.println(" :Serving your drink...");
}
private void boilWater() {
System.out.println(" :Boiling some water...");
}
}
|
3e16e7f2a17c03f313c0d9995960581b52a43320 | 1,098 | java | Java | mantis-tests/src/test/java/stqa/pft/mantis/application_manager/FtpHelper.java | pazuzuz/homework_lecture_0_and_1 | 7578163d6e6c059159dd35c86840bc17bdc7906d | [
"Apache-2.0"
] | null | null | null | mantis-tests/src/test/java/stqa/pft/mantis/application_manager/FtpHelper.java | pazuzuz/homework_lecture_0_and_1 | 7578163d6e6c059159dd35c86840bc17bdc7906d | [
"Apache-2.0"
] | null | null | null | mantis-tests/src/test/java/stqa/pft/mantis/application_manager/FtpHelper.java | pazuzuz/homework_lecture_0_and_1 | 7578163d6e6c059159dd35c86840bc17bdc7906d | [
"Apache-2.0"
] | null | null | null | 30.5 | 84 | 0.673042 | 9,762 | package stqa.pft.mantis.application_manager;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpHelper {
private ApplicationManager app;
private FTPClient ftp;
public FtpHelper(ApplicationManager app){
this.app = app;
this.ftp = new FTPClient();
}
public void upload(File file, String target, String backup) throws IOException {
ftp.connect(app.getProperty("ftp.Host"));
ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password"));
ftp.deleteFile(backup);
ftp.rename(target, backup);
ftp.enterLocalPassiveMode();
ftp.storeFile(target, new FileInputStream(file));
ftp.disconnect();
}
public void restore(String backup, String target) throws IOException {
ftp.connect(app.getProperty("ftp.Host"));
ftp.login(app.getProperty("ftp.login"), app.getProperty("ftp.password"));
ftp.deleteFile(target);
ftp.rename(backup, target);
ftp.disconnect();
}
}
|
3e16e8110586aa84aec2c97fc72f68ec64c5130c | 1,055 | java | Java | test/it/marteEngine/test/helloWorld/HelloWorld.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 13 | 2015-01-28T01:23:57.000Z | 2021-07-10T18:40:52.000Z | test/it/marteEngine/test/helloWorld/HelloWorld.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 11 | 2015-12-19T15:33:23.000Z | 2018-10-13T09:55:33.000Z | test/it/marteEngine/test/helloWorld/HelloWorld.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 8 | 2015-08-30T01:37:38.000Z | 2021-12-31T06:07:52.000Z | 30.142857 | 78 | 0.739336 | 9,763 | package it.marteEngine.test.helloWorld;
import it.marteEngine.ME;
import it.marteEngine.World;
import it.marteEngine.resource.ResourceManager;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
public class HelloWorld extends StateBasedGame {
public HelloWorld(String title) {
super(title);
}
@Override
public void initStatesList(GameContainer container) throws SlickException {
ResourceManager.loadResources("data/helloWorld/resources.xml");
World world = new TextOnlyWorld(0, container);
addState(world);
}
public static void main(String[] argv) throws SlickException {
ME.keyToggleDebug = Input.KEY_1;
AppGameContainer container = new AppGameContainer(
new HelloWorld("Hello World Marte Engine")
);
container.setDisplayMode(800, 600, false);
container.setTargetFrameRate(60);
container.start();
}
}
|
3e16e82529e0e96714d39dbfb26d454acd57cd1c | 2,728 | java | Java | core/src/main/java/com/vzome/core/edits/SelectByBoundary.java | lgarron/vzome | 60ad7b845074b649870e19d22cd54ebc9036a303 | [
"Apache-2.0"
] | 9 | 2019-01-16T04:15:31.000Z | 2021-09-18T22:36:14.000Z | core/src/main/java/com/vzome/core/edits/SelectByBoundary.java | vorth/vzome | f987a1002969574db660cc7a58f082f09a725e31 | [
"Apache-2.0"
] | 82 | 2017-10-28T21:09:20.000Z | 2022-02-27T00:10:07.000Z | core/src/main/java/com/vzome/core/edits/SelectByBoundary.java | vorth/vzome | f987a1002969574db660cc7a58f082f09a725e31 | [
"Apache-2.0"
] | 8 | 2017-10-28T21:55:34.000Z | 2021-12-11T04:38:31.000Z | 29.021277 | 93 | 0.601173 | 9,764 | package com.vzome.core.edits;
import com.vzome.core.algebra.AlgebraicVector;
import com.vzome.core.commands.Command;
import com.vzome.core.commands.Command.Failure;
import com.vzome.core.editor.api.ChangeManifestations;
import com.vzome.core.editor.api.EditorModel;
import com.vzome.core.model.Connector;
import com.vzome.core.model.Panel;
import com.vzome.core.model.Strut;
public abstract class SelectByBoundary extends ChangeManifestations {
public SelectByBoundary( EditorModel editor )
{
super( editor );
}
public abstract String usage();
@Override
protected void fail(String message) throws Failure {
final StringBuilder errorMsg = new StringBuilder();
String usage = usage();
if(usage != null) {
errorMsg.append(usage);
}
if(message != null) {
if(errorMsg.length() > 0) {
errorMsg.append("\n");
}
errorMsg.append(message);
}
super.fail(errorMsg.toString());
}
/**
* Sets the boundary criteria based on the selection
* @return null if successful, otherwise a string describing the error.
*/
protected abstract String setBoundary();
@Override
public void perform() throws Command.Failure {
// Derived classes should setOrderedSelection() if applicable
String errMsg = setBoundary();
if(errMsg != null) {
fail(errMsg); // throw an exception and we're done.
}
unselectAll();
selectBoundedManifestations();
redo(); // commit any selects
}
protected void selectBoundedManifestations() {
for(Connector connector : this.getConnectors()) {
if( boundaryContains(connector) ) {
select(connector);
}
}
for(Strut strut : this.getStruts()) {
if( boundaryContains(strut) ) {
select(strut);
}
}
for(Panel panel : this.getPanels()) {
if( boundaryContains(panel) ) {
select(panel);
}
}
}
private boolean boundaryContains(Connector connector) {
return boundaryContains( connector.getLocation() );
}
private boolean boundaryContains(Strut strut) {
return boundaryContains( strut.getLocation() ) && boundaryContains( strut.getEnd() );
}
private boolean boundaryContains(Panel panel) {
for(AlgebraicVector vertex : panel) {
if(! boundaryContains( vertex )) {
return false;
}
}
return true;
}
protected abstract boolean boundaryContains(AlgebraicVector v);
}
|
3e16e9f91940305a0183dbe20093df560c9043a5 | 2,625 | java | Java | cogroo-eval/BaselineCogrooAE/src/main/java/cogroo/uima/ae/UimaSentenceDetector.java | evelinamorim/cogroo4 | cb5000fd977bff36ce055d880afec45b21709a6b | [
"Apache-2.0"
] | 40 | 2015-09-26T05:51:24.000Z | 2021-11-09T11:10:33.000Z | cogroo-eval/BaselineCogrooAE/src/main/java/cogroo/uima/ae/UimaSentenceDetector.java | evelinamorim/cogroo4 | cb5000fd977bff36ce055d880afec45b21709a6b | [
"Apache-2.0"
] | 19 | 2015-03-14T17:19:13.000Z | 2020-07-07T11:55:53.000Z | cogroo-eval/BaselineCogrooAE/src/main/java/cogroo/uima/ae/UimaSentenceDetector.java | evelinamorim/cogroo4 | cb5000fd977bff36ce055d880afec45b21709a6b | [
"Apache-2.0"
] | 20 | 2015-03-20T17:15:25.000Z | 2021-05-13T21:38:31.000Z | 30.172414 | 76 | 0.641905 | 9,765 | /**
* Copyright (C) 2012 cogroo <lyhxr@example.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 cogroo.uima.ae;
import java.util.ArrayList;
import java.util.List;
import opennlp.tools.util.Span;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.TypeSystem;
import org.apache.uima.jcas.tcas.Annotation;
import br.usp.pcs.lta.cogroo.entity.Sentence;
import br.usp.pcs.lta.cogroo.tools.sentencedetector.SentenceDetectorI;
public class UimaSentenceDetector extends AnnotationService implements
SentenceDetectorI {
private Type sentenceType;
public UimaSentenceDetector() throws AnnotationServiceException {
super("UIMASentenceDetector");
}
public List<Sentence> process(String text) {
// ************************************
// Add text to the CAS
// ************************************
cas.setDocumentText(text);
List<Sentence> sentences = new ArrayList<Sentence>();
// ************************************
// Analyze text
// ************************************
try {
ae.process(cas);
} catch (Exception e) {
throw new RuntimeException("Error processing a text.", e);
}
// ************************************
// Extract the result using annotated CAS
// ************************************
FSIterator<Annotation> iterator = cas.getAnnotationIndex(sentenceType)
.iterator();
while (iterator.hasNext()) {
Annotation a = iterator.next();
Sentence s = new Sentence();
s.setSpan(new Span(a.getBegin(), a.getEnd()));
s.setSentence(a.getCoveredText());
s.setOffset(a.getBegin());
sentences.add(s);
}
cas.reset();
return sentences;
}
@Override
protected void initTypes(TypeSystem typeSystem) {
sentenceType = cas.getTypeSystem().getType("opennlp.uima.Sentence");
}
public static void main(String[] args) throws AnnotationServiceException {
UimaSentenceDetector sd = new UimaSentenceDetector();
System.out.println(sd.process("O sr. José chegou. Vamos sair."));
}
}
|
3e16eab0115a258fbffa4f56d08d796399cbbed8 | 3,375 | java | Java | backend/src/main/java/solvas/authentication/jwt/JwtTokenFactory.java | domien96/SolvasFleet | dab2e9da4c9ee9cf172c4f981c647b7550f6edec | [
"MIT"
] | null | null | null | backend/src/main/java/solvas/authentication/jwt/JwtTokenFactory.java | domien96/SolvasFleet | dab2e9da4c9ee9cf172c4f981c647b7550f6edec | [
"MIT"
] | null | null | null | backend/src/main/java/solvas/authentication/jwt/JwtTokenFactory.java | domien96/SolvasFleet | dab2e9da4c9ee9cf172c4f981c647b7550f6edec | [
"MIT"
] | null | null | null | 32.451923 | 98 | 0.699259 | 9,766 | package solvas.authentication.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import solvas.authentication.user.UserContext;
import solvas.authentication.jwt.token.AccessToken;
import solvas.authentication.jwt.token.JwtToken;
import solvas.authentication.jwt.token.Scopes;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Factory to create access tokens and refresh tokens
*/
@Component
public class JwtTokenFactory {
private JwtSettings settings;
private static final int MILLISECONDS_PER_MINUTE = 60*1000;
/**
* Create instance
* @param settings The Jwt Settings
*/
@Autowired
public JwtTokenFactory(JwtSettings settings) {
this.settings = settings;
}
/**
* Create an access token from the userContent
* @param userContext UserContext containing principal and roles
* @return AccessToken
*/
public AccessToken createAccessJwtToken(UserDetails userContext) {
validateUserDetails(userContext);
Claims claims = buildClaims(
userContext,
userContext.getAuthorities()
);
String token = buildToken(claims, settings.getTokenExpirationTime()).compact();
return new AccessToken(token, claims);
}
/**
* Create a refresh token from the userContent
* @param userContext UserContext containing principal and roles
* @return RefreshToken
*/
public JwtToken createRefreshToken(UserDetails userContext) {
validateUserDetails(userContext);
Claims claims = buildClaims(userContext,
Collections.singletonList(Scopes.REFRESH_TOKEN.authority()));
String token = buildToken(claims, settings.getRefreshTokenExpTime())
.setId(UUID.randomUUID().toString())
.compact();
return new AccessToken(token, claims);
}
protected JwtBuilder buildToken(Claims claims, int duration) {
Date currentTime = new Date();
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(currentTime)
.setIssuer(settings.getTokenIssuer())
.setExpiration(new Date(currentTime.getTime() + duration*MILLISECONDS_PER_MINUTE))
.signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey());
}
protected Claims buildClaims(UserDetails userDetails, Collection<?> scopes) {
Claims claims = Jwts.claims().setSubject(userDetails.getUsername());
claims.put("scopes", scopes);
return claims;
}
/**
* @param userDetails UserDetails to validate
* @throws IllegalArgumentException if atleast one validation failed
*/
protected void validateUserDetails(UserDetails userDetails) {
if (StringUtils.isBlank(userDetails.getUsername())) {
throw new IllegalArgumentException("Cannot create JWT Token without username");
}
}
} |
3e16eb1f76fecfff386bc56d83c146aab25f0291 | 236 | java | Java | gunnel-common/src/main/java/com/nekoimi/gunnel/common/protocol/message/GuError.java | nekoimi/gunnel | 2ae6caf5540991b88b551d8ed5c8b06855fb0e97 | [
"MIT"
] | null | null | null | gunnel-common/src/main/java/com/nekoimi/gunnel/common/protocol/message/GuError.java | nekoimi/gunnel | 2ae6caf5540991b88b551d8ed5c8b06855fb0e97 | [
"MIT"
] | null | null | null | gunnel-common/src/main/java/com/nekoimi/gunnel/common/protocol/message/GuError.java | nekoimi/gunnel | 2ae6caf5540991b88b551d8ed5c8b06855fb0e97 | [
"MIT"
] | null | null | null | 16.857143 | 51 | 0.737288 | 9,767 | package com.nekoimi.gunnel.common.protocol.message;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* nekoimi 2021/8/15 12:24
*/
@Data
@AllArgsConstructor(staticName = "of")
public class GuError {
private int code;
}
|
3e16ed0e9f3374ae7ef3d38a82ed6738711627dc | 1,175 | java | Java | nabl2.terms/src/main/java/mb/nabl2/terms/ITerm.java | Taeir/nabl | 820b2c1086eb301e5775706782db0d506ee62ee8 | [
"Apache-2.0"
] | null | null | null | nabl2.terms/src/main/java/mb/nabl2/terms/ITerm.java | Taeir/nabl | 820b2c1086eb301e5775706782db0d506ee62ee8 | [
"Apache-2.0"
] | null | null | null | nabl2.terms/src/main/java/mb/nabl2/terms/ITerm.java | Taeir/nabl | 820b2c1086eb301e5775706782db0d506ee62ee8 | [
"Apache-2.0"
] | null | null | null | 20.614035 | 79 | 0.66383 | 9,768 | package mb.nabl2.terms;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.Multiset;
public interface ITerm {
boolean isGround();
Multiset<ITermVar> getVars();
ImmutableClassToInstanceMap<Object> getAttachments();
ITerm withAttachments(ImmutableClassToInstanceMap<Object> value);
<T> T match(Cases<T> cases);
interface Cases<T> {
T caseAppl(IApplTerm appl);
T caseList(IListTerm cons);
T caseString(IStringTerm string);
T caseInt(IIntTerm integer);
T caseBlob(IBlobTerm integer);
T caseVar(ITermVar var);
}
<T, E extends Throwable> T matchOrThrow(CheckedCases<T, E> cases) throws E;
interface CheckedCases<T, E extends Throwable> {
T caseAppl(IApplTerm appl) throws E;
T caseList(IListTerm cons) throws E;
T caseString(IStringTerm string) throws E;
T caseInt(IIntTerm integer) throws E;
T caseBlob(IBlobTerm integer) throws E;
T caseVar(ITermVar var) throws E;
default T caseLock(ITerm term) throws E {
return term.matchOrThrow(this);
}
}
} |
3e16edcc88b0d12c3308fe8ade768402071d875f | 2,270 | java | Java | src/main/java/com/zgb/test/utils/config/UploadConfig.java | lsyzx/zgb_code | f770aa6e2808a69d99c0c95916298cb631c063fb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zgb/test/utils/config/UploadConfig.java | lsyzx/zgb_code | f770aa6e2808a69d99c0c95916298cb631c063fb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zgb/test/utils/config/UploadConfig.java | lsyzx/zgb_code | f770aa6e2808a69d99c0c95916298cb631c063fb | [
"Apache-2.0"
] | null | null | null | 40.607143 | 134 | 0.73219 | 9,769 | /*
* Copyright (c) 2018-2025, Nanjing Zhengebang Software Corp.,Ltd 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 the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lsyzx (ychag@example.com)
*/
package com.zgb.test.utils.config;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: lsyzx (ychag@example.com)
* 创建时间: 2019-08-07 00:18:27
* 描述: 上传地址映射
* 历史修改:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
@Configuration
@EnableConfigurationProperties(UploadProperties.class)
public class UploadConfig implements WebMvcConfigurer {
private UploadProperties properties;
@Autowired
public UploadConfig(UploadProperties properties) {
this.properties = properties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String[] ysUrls = properties.getYsUrls().split(",");
String[] localUrls = properties.getLocalUrls().split(",");
String newLocalUrls = StrUtil.EMPTY;
for (String url : localUrls) {
newLocalUrls += "file:" + url + ",";
}
registry.addResourceHandler(ysUrls).addResourceLocations(newLocalUrls.substring(0, newLocalUrls.lastIndexOf(",")).split(","));
}
} |
3e16edfc2925eac1c6fd8c1f70f60aa6262b7933 | 6,929 | java | Java | storage/sis-gdal/src/test/java/org/apache/sis/storage/gdal/PJTest.java | Matthieu-Bastianelli/sis | 069e51bba86ebdaf8561d7ca6a5fff231eef3ed2 | [
"Apache-2.0"
] | 1 | 2019-03-17T03:07:12.000Z | 2019-03-17T03:07:12.000Z | storage/sis-gdal/src/test/java/org/apache/sis/storage/gdal/PJTest.java | Matthieu-Bastianelli/sis | 069e51bba86ebdaf8561d7ca6a5fff231eef3ed2 | [
"Apache-2.0"
] | null | null | null | storage/sis-gdal/src/test/java/org/apache/sis/storage/gdal/PJTest.java | Matthieu-Bastianelli/sis | 069e51bba86ebdaf8561d7ca6a5fff231eef3ed2 | [
"Apache-2.0"
] | 1 | 2019-02-25T14:09:55.000Z | 2019-02-25T14:09:55.000Z | 38.071429 | 118 | 0.654929 | 9,770 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.storage.gdal;
import org.opengis.util.FactoryException;
import org.opengis.referencing.operation.TransformException;
import org.apache.sis.metadata.iso.citation.Citations;
import org.apache.sis.test.TestCase;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assume.assumeTrue;
import static org.apache.sis.test.Assert.*;
/**
* Tests the {@link PJ} class.
*
* @author Martin Desruisseaux (Geomatys)
* @version 0.8
* @since 0.8
* @module
*/
public final strictfp class PJTest extends TestCase {
/**
* If the {@literal Proj.4} library has been successfully initialized, an empty string.
* Otherwise, the reason why the library is not available.
*/
private static String status;
/**
* Verifies if the {@literal Proj.4} library is available.
*/
@BeforeClass
public static synchronized void verifyNativeLibraryAvailability() {
if (status == null) try {
out.println("Proj.4 version: " + PJ.getRelease());
status = "";
} catch (UnsatisfiedLinkError e) {
status = e.toString();
}
assumeTrue(status, status.isEmpty());
}
/**
* Ensures that the given object is the WGS84 definition.
*/
private static void assertIsWGS84(final PJ pj) {
assertEquals("+proj=latlong +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0", pj.getCode());
assertEquals("Proj4", pj.getCodeSpace());
assertSame (Citations.PROJ4, pj.getAuthority());
assertTrue (Character.isDigit( pj.getVersion().codePointAt(0)));
assertEquals(PJ.Type.GEOGRAPHIC, pj.getType());
final double[] ellps = pj.getEllipsoidDefinition();
assertEquals(2, ellps.length);
ellps[1] = 1 / (1 - StrictMath.sqrt(1 - ellps[1])); // Replace eccentricity squared by inverse flattening.
assertArrayEquals(new double[] {6378137.0, 298.257223563}, ellps, 1E-9);
}
/**
* Tests the creation of a simple WGS84 object.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
*/
@Test
public void testWGS84() throws FactoryException {
final PJ pj = new PJ("+proj=latlong +datum=WGS84");
assertIsWGS84(pj);
}
/**
* Tests the creation of the EPSG:3395 projected CRS.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
*/
@Test
public void testEPSG3395() throws FactoryException {
final PJ pj = new PJ("+init=epsg:3395");
assertEquals(PJ.Type.PROJECTED, pj.getType());
final String definition = pj.getCode();
assertTrue(definition, definition.contains("+proj=merc"));
assertTrue(definition, definition.contains("+datum=WGS84"));
assertTrue(definition, definition.contains("+units=m"));
assertIsWGS84(new PJ(pj));
}
/**
* Tests the units of measurement.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
*/
@Test
public void testGetLinearUnit() throws FactoryException {
PJ pj;
pj = new PJ("+proj=merc +to_meter=1");
String definition = pj.getCode();
assertTrue(definition, definition.contains("+to_meter=1"));
pj = new PJ("+proj=merc +to_meter=0.001");
definition = pj.getCode();
assertTrue(definition, definition.contains("+to_meter=0.001"));
}
/**
* Ensures that the native code correctly detects the case of null pointers.
* This is important in order to ensure that we don't have a JVM crash.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
* @throws TransformException should never happen.
*/
@Test
public void testNullPointerException() throws FactoryException, TransformException {
final PJ pj = new PJ("+proj=latlong +datum=WGS84");
try {
pj.transform(null, 2, null, 0, 1);
fail("Expected an exception to be thrown.");
} catch (NullPointerException e) {
// This is the expected exception.
}
}
/**
* Ensures that the native code correctly detects the case of index out of bounds.
* This is important in order to ensure that we don't have a JVM crash.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
* @throws TransformException should never happen.
*/
@Test
public void testIndexOutOfBoundsException() throws FactoryException, TransformException {
final PJ pj = new PJ("+proj=latlong +datum=WGS84");
try {
pj.transform(pj, 2, new double[5], 2, 2);
fail("Expected an exception to be thrown.");
} catch (IndexOutOfBoundsException e) {
// This is the expected exception.
}
}
/**
* Tests a method that returns NaN. The native code is expected to returns the
* {@link java.lang.Double#NaN} constant, because not all C/C++ compiler define
* a {@code NAN} constant.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
*/
@Test
@SuppressWarnings("FinalizeCalledExplicitly")
public void testNaN() throws FactoryException {
final PJ pj = new PJ("+proj=latlong +datum=WGS84");
pj.finalize(); // This cause the disposal of the internal PJ structure.
assertNull(pj.getCode());
assertNull(pj.getType());
assertNull(pj.getEllipsoidDefinition());
}
/**
* Tests serialization. Since we can not serialize native resources, {@link PJ} is expected
* to serialize the Proj.4 definition string instead.
*
* @throws FactoryException if the Proj.4 definition string used in this test is invalid.
*/
@Test
public void testSerialization() throws FactoryException {
final PJ pj = new PJ("+proj=latlong +datum=WGS84");
assertNotSame(pj, assertSerializedEquals(pj));
}
}
|
3e16ef28cb261e5565891cb3b0780273c6f1b4c4 | 978 | java | Java | src/main/java/seedu/address/logic/parser/DoneCommandParser.java | kieron560/tp | dbdebc6d074e4559f54b729c742c3370e0253577 | [
"MIT"
] | 1 | 2021-02-08T14:02:40.000Z | 2021-02-08T14:02:40.000Z | src/main/java/seedu/address/logic/parser/DoneCommandParser.java | kieron560/tp | dbdebc6d074e4559f54b729c742c3370e0253577 | [
"MIT"
] | 145 | 2021-02-08T13:15:31.000Z | 2021-04-12T12:39:26.000Z | src/main/java/seedu/address/logic/parser/DoneCommandParser.java | kieron560/tp | dbdebc6d074e4559f54b729c742c3370e0253577 | [
"MIT"
] | 5 | 2021-02-17T02:52:03.000Z | 2021-02-28T14:50:35.000Z | 36.222222 | 85 | 0.683027 | 9,771 | package seedu.address.logic.parser;
import static java.util.Objects.requireNonNull;
import seedu.address.commons.core.identifier.Identifier;
import seedu.address.logic.commands.DoneCommand;
import seedu.address.logic.parser.exceptions.ParseException;
public class DoneCommandParser implements Parser<DoneCommand> {
@Override
public DoneCommand parse(String userInput) throws ParseException {
requireNonNull(userInput);
try {
Identifier identifier = ParserUtil.parseIdentifier(userInput);
return new DoneCommand(identifier);
} catch (ParseException pe) {
if (pe.getMessage().equals(ParserUtil.MESSAGE_ADDITIONAL_ARTEFACTS)
|| pe.getMessage().equals(ParserUtil.MESSAGE_EMPTY_IDENTIFIER)) {
throw new ParseException(pe.getMessage()
+ DoneCommand.MESSAGE_USAGE);
}
throw new ParseException(pe.getMessage());
}
}
}
|
3e16ef7c2641c76aa8256b73d0e12fc1d5741e18 | 4,085 | java | Java | libs/fotolib2/src/de/k3b/media/MetaApiWrapper.java | openthos/oto_packages_apps_OtoPhotoManager | 9eca07b857a6b625bbe973060f70dfd91b0aa907 | [
"Apache-2.0"
] | null | null | null | libs/fotolib2/src/de/k3b/media/MetaApiWrapper.java | openthos/oto_packages_apps_OtoPhotoManager | 9eca07b857a6b625bbe973060f70dfd91b0aa907 | [
"Apache-2.0"
] | null | null | null | libs/fotolib2/src/de/k3b/media/MetaApiWrapper.java | openthos/oto_packages_apps_OtoPhotoManager | 9eca07b857a6b625bbe973060f70dfd91b0aa907 | [
"Apache-2.0"
] | 2 | 2019-05-28T01:16:41.000Z | 2020-04-02T09:38:10.000Z | 27.416107 | 106 | 0.650428 | 9,772 | /*
* Copyright (c) 2016-2017 by k3b.
*
* This file is part of AndroFotoFinder / #APhotoManager.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package de.k3b.media;
import java.util.Date;
import java.util.List;
import de.k3b.io.VISIBILITY;
/**
* (Default) Implementation of {@link IMetaApi} to forward all methods to an inner child {@link IMetaApi}.
*
* Created by k3b on 09.10.2016.
*/
public class MetaApiWrapper implements IMetaApi {
protected final IMetaApi readChild;
protected final IMetaApi writeChild;
/** count the non path write calls */
private int modifyCount = 0;
public MetaApiWrapper(IMetaApi child) {
this(child, child);
}
public MetaApiWrapper(IMetaApi readChild, IMetaApi writeChild) {
this.readChild = readChild;
this.writeChild = writeChild;
}
@Override
public Date getDateTimeTaken() {
return (readChild == null) ? null : readChild.getDateTimeTaken();
}
@Override
public MetaApiWrapper setDateTimeTaken(Date value) {
modifyCount++;
if (writeChild != null) writeChild.setDateTimeTaken(value);
return this;
}
@Override public IMetaApi setLatitudeLongitude(Double latitude, Double longitude) {
modifyCount++;
if (writeChild != null) writeChild.setLatitudeLongitude(latitude, longitude);
return this;
}
@Override
public Double getLatitude() {
return (readChild == null) ? null : readChild.getLatitude();
}
@Override
public Double getLongitude() {
return (readChild == null) ? null : readChild.getLongitude();
}
public String getTitle() {
return (readChild == null) ? null : readChild.getTitle();
}
public MetaApiWrapper setTitle(String title) {
modifyCount++;
if (writeChild != null) writeChild.setTitle(title);
return this;
}
public String getDescription() {
return (readChild == null) ? null : readChild.getDescription();
}
public MetaApiWrapper setDescription(String description) {
modifyCount++;
if (writeChild != null) writeChild.setDescription(description);
return this;
}
public List<String> getTags() {
return (readChild == null) ? null : readChild.getTags();
}
public MetaApiWrapper setTags(List<String> tags) {
modifyCount++;
if (writeChild != null) writeChild.setTags(tags);
return this;
}
/**
* 5=best .. 1=worst or 0/null unknown
*/
@Override
public Integer getRating() {
return (readChild == null) ? null : readChild.getRating();
}
@Override
public IMetaApi setRating(Integer value) {
modifyCount++;
if (writeChild != null) writeChild.setRating(value);
return this;
}
@Override
public VISIBILITY getVisibility() {
return (readChild == null) ? null : readChild.getVisibility();
}
@Override
public IMetaApi setVisibility(VISIBILITY value) {
modifyCount++;
if (writeChild != null) writeChild.setVisibility(value);
return this;
}
public String getPath() {
return (readChild == null) ? null : readChild.getPath();
}
public MetaApiWrapper setPath(String filePath) {
if (writeChild != null) writeChild.setPath(filePath);
return this;
}
@Override
public String toString() {
return MediaUtil.toString(this);
}
}
|
3e16f0436f835e8568890ddbcf70372132cd4867 | 834 | java | Java | app/controllers/CakeReservations.java | atabari/igraonice_bg | 39c0e97b20adde0d4ebdaeefbd6b46566b53d917 | [
"Apache-2.0"
] | null | null | null | app/controllers/CakeReservations.java | atabari/igraonice_bg | 39c0e97b20adde0d4ebdaeefbd6b46566b53d917 | [
"Apache-2.0"
] | null | null | null | app/controllers/CakeReservations.java | atabari/igraonice_bg | 39c0e97b20adde0d4ebdaeefbd6b46566b53d917 | [
"Apache-2.0"
] | null | null | null | 32.076923 | 101 | 0.773381 | 9,773 | package controllers;
import helpers.UserAccessLevel;
import models.CakeReservation;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.List;
/**
* Created by User on 6/21/2016.
*/
public class CakeReservations extends Controller {
public Result pastryReservationsRender(Integer pastryId) {
List<CakeReservation> reservations = CakeReservation.findCakeReservationByPastryId(pastryId);
Integer userId = UserAccessLevel.getCurrentUser(ctx()).id;
return ok(views.html.pastry.pastryReservations.render(reservations, userId));
}
public Result deleteCakeReservation(Integer reservationId) {
Integer pastryId = CakeReservation.deleteCakeReservationByReservationId(reservationId);
return redirect(routes.CakeReservations.pastryReservationsRender(pastryId));
}
}
|
3e16f14c4ff339903c147912fe68cc9bc4c0aec7 | 1,046 | java | Java | compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderFactory.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 45,293 | 2015-01-01T06:23:46.000Z | 2022-03-31T21:55:51.000Z | compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderFactory.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 3,386 | 2015-01-12T13:28:50.000Z | 2022-03-31T17:48:15.000Z | compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderFactory.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 6,351 | 2015-01-03T12:30:09.000Z | 2022-03-31T20:46:54.000Z | 29.885714 | 75 | 0.756214 | 9,774 | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
public interface ClassBuilderFactory {
@NotNull
ClassBuilderMode getClassBuilderMode();
@NotNull
ClassBuilder newClassBuilder(@NotNull JvmDeclarationOrigin origin);
String asText(ClassBuilder builder);
byte[] asBytes(ClassBuilder builder);
void close();
}
|
3e16f282679fcaa3a49dc1ff00d043ab6d7f7066 | 345 | java | Java | src/main/java/org/midnightbsd/advisory/repository/ConfigNodeCpeRepository.java | MidnightBSD/security-advisory | ddbf982f54a01dcec86cab13425f8047dcb250f3 | [
"BSD-2-Clause"
] | 1 | 2018-12-17T00:01:55.000Z | 2018-12-17T00:01:55.000Z | src/main/java/org/midnightbsd/advisory/repository/ConfigNodeCpeRepository.java | Acidburn0zzz/security-advisory | 9f219a8fe202cac2847302596a3fa756419ba525 | [
"BSD-2-Clause"
] | 54 | 2020-08-01T01:38:11.000Z | 2022-03-31T20:27:56.000Z | src/main/java/org/midnightbsd/advisory/repository/ConfigNodeCpeRepository.java | acidburn0zzz/security-advisory | 9f219a8fe202cac2847302596a3fa756419ba525 | [
"BSD-2-Clause"
] | 3 | 2018-12-17T00:01:48.000Z | 2020-02-11T06:08:09.000Z | 26.538462 | 88 | 0.828986 | 9,775 | package org.midnightbsd.advisory.repository;
import org.midnightbsd.advisory.model.ConfigNodeCpe;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @author Lucas Holt
*/
@Repository
public interface ConfigNodeCpeRepository extends JpaRepository<ConfigNodeCpe, Integer> {
}
|
3e16f3ce9133a5030773ba560140c7abdb78b462 | 1,220 | java | Java | src/main/java/com/lunatech/library/api/UserAPI.java | lunatech-labs/lunatech-library-app | 90b7d7323737ae2747e178b98c796872af87e28f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lunatech/library/api/UserAPI.java | lunatech-labs/lunatech-library-app | 90b7d7323737ae2747e178b98c796872af87e28f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lunatech/library/api/UserAPI.java | lunatech-labs/lunatech-library-app | 90b7d7323737ae2747e178b98c796872af87e28f | [
"Apache-2.0"
] | null | null | null | 30.5 | 84 | 0.768852 | 9,776 | package com.lunatech.library.api;
import com.lunatech.library.dto.UserDTO;
import com.lunatech.library.dto.UserInfoDTO;
import com.lunatech.library.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/user")
@Slf4j
@RequiredArgsConstructor
@Api("The authenticated user")
public class UserAPI {
final UserService userService;
@GetMapping(produces = "application/json")
@ApiOperation(value = "Get the authenticated user", response = UserDTO.class)
@ResponseBody
public UserDTO getUser() {
return userService.getUser();
}
@GetMapping(path = "/info", produces = "application/json")
@ApiOperation(value = "Get the info for the user", response = UserInfoDTO.class)
@ResponseBody
public UserInfoDTO getUserInfo() {
return userService.getUserInfo();
}
}
|
3e16f4e5741df68cdb6c577898dcb2f179df5c27 | 1,075 | java | Java | src/main/java/frc/robot/commands/SetSnap.java | Team3039/2022-RapidReact-Venetian | be0924e81bc66eb48aadecefc0f4c56d19412821 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/SetSnap.java | Team3039/2022-RapidReact-Venetian | be0924e81bc66eb48aadecefc0f4c56d19412821 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/SetSnap.java | Team3039/2022-RapidReact-Venetian | be0924e81bc66eb48aadecefc0f4c56d19412821 | [
"BSD-3-Clause"
] | null | null | null | 25 | 74 | 0.728372 | 9,777 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants;
import frc.robot.subsystems.Drive;
public class SetSnap extends CommandBase {
double snapAngle;
/** Creates a new SetSnap. */
public SetSnap(double snapAngle) {
// this.snapAngle = snapAngle;
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
Drive.getInstance().startSnap(snapAngle);
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
Drive.getInstance().setModuleStates(Constants.Swerve.ZERO_STATES);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return true;
}
} |
3e16f5be36804c18c6683de9ee26319944d4279b | 139 | java | Java | src/com/go/App.java | jingyiqiu/go | 0c231d31b7e5df32dea15e2ba903efe8f5b47d7f | [
"Apache-2.0"
] | null | null | null | src/com/go/App.java | jingyiqiu/go | 0c231d31b7e5df32dea15e2ba903efe8f5b47d7f | [
"Apache-2.0"
] | null | null | null | src/com/go/App.java | jingyiqiu/go | 0c231d31b7e5df32dea15e2ba903efe8f5b47d7f | [
"Apache-2.0"
] | null | null | null | 12.636364 | 42 | 0.57554 | 9,778 | package com.go;
public class App {
public static void main(String[] args) {
AppFrame frame=new AppFrame();
}
}
|
3e16f5d77241724ba028acb16206ed6289dafc3f | 351 | java | Java | gulimall-order/src/main/java/com/zwx/gulimall/order/dao/OrderDao.java | coderZ666/gulimall | a8570dcc9ce7ad1b6773a4aebf8212edac3c7158 | [
"Apache-2.0"
] | 1 | 2021-04-04T13:26:40.000Z | 2021-04-04T13:26:40.000Z | gulimall-order/src/main/java/com/zwx/gulimall/order/dao/OrderDao.java | coderZ666/gulimall | a8570dcc9ce7ad1b6773a4aebf8212edac3c7158 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/zwx/gulimall/order/dao/OrderDao.java | coderZ666/gulimall | a8570dcc9ce7ad1b6773a4aebf8212edac3c7158 | [
"Apache-2.0"
] | 1 | 2021-04-04T13:26:48.000Z | 2021-04-04T13:26:48.000Z | 19.555556 | 59 | 0.75 | 9,779 | package com.zwx.gulimall.order.dao;
import com.zwx.gulimall.order.entity.OrderEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 订单
*
* @author zwx
* @email dycjh@example.com
* @date 2021-01-03 15:15:37
*/
@Mapper
public interface OrderDao extends BaseMapper<OrderEntity> {
}
|
3e16f63bd210c511efc0d901832aabe8b70b9614 | 1,223 | java | Java | jokelibrary/src/main/java/com/kieranjohnmoore/jokelibrary/JokeActivity.java | Aman2028/project-5-udacity | 9a1e94146e752b4b3f6f6e5d34b26e3e3db8dc4b | [
"MIT"
] | null | null | null | jokelibrary/src/main/java/com/kieranjohnmoore/jokelibrary/JokeActivity.java | Aman2028/project-5-udacity | 9a1e94146e752b4b3f6f6e5d34b26e3e3db8dc4b | [
"MIT"
] | null | null | null | jokelibrary/src/main/java/com/kieranjohnmoore/jokelibrary/JokeActivity.java | Aman2028/project-5-udacity | 9a1e94146e752b4b3f6f6e5d34b26e3e3db8dc4b | [
"MIT"
] | null | null | null | 30.575 | 99 | 0.748978 | 9,780 | package com.kieranjohnmoore.jokelibrary;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.kieranjohnmoore.jokelibrary.databinding.ActivityJokeBinding;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import android.util.Log;
import android.view.View;
public class JokeActivity extends AppCompatActivity {
private static final String LOGTAG = JokeActivity.class.getSimpleName();
public static final String JOKE = "JOKE_TO_DISPLAY";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityJokeBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_joke);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
if (intent.hasExtra(JOKE)) {
binding.jokeText.setText(intent.getStringExtra(JOKE));
} else {
Log.e(LOGTAG, "NO JOKE WAS PASSED IN");
}
}
}
|
3e16f6754102fd5c1cee6fa3dcd0998482a8efbd | 1,037 | java | Java | src/main/java/athena/events/resource/download/template/scoring/EventRewardTier.java | PizzaCrust/Athena-1 | 7a8bcbe355195b858b991caa34d2ff58b09f76f7 | [
"MIT"
] | 26 | 2019-05-04T18:02:05.000Z | 2022-01-18T20:35:55.000Z | src/main/java/athena/events/resource/download/template/scoring/EventRewardTier.java | PizzaCrust/Athena-1 | 7a8bcbe355195b858b991caa34d2ff58b09f76f7 | [
"MIT"
] | 7 | 2019-05-22T17:27:34.000Z | 2020-05-29T21:13:41.000Z | src/main/java/athena/events/resource/download/template/scoring/EventRewardTier.java | PizzaCrust/Athena-1 | 7a8bcbe355195b858b991caa34d2ff58b09f76f7 | [
"MIT"
] | 10 | 2019-04-28T20:10:46.000Z | 2021-03-09T23:01:22.000Z | 22.06383 | 94 | 0.607522 | 9,781 | package athena.events.resource.download.template.scoring;
/**
* Represents a singular reward tier for a {@link EventScoringRule}
* <p>
* "trackedStat": "PLACEMENT_STAT_INDEX",
* "matchRule": "lte",
* "rewardTiers": [
* {
* "keyValue": 1,
* "pointsEarned": 3,
* "multiplicative": false
* },
*/
public final class EventRewardTier {
/**
* key value I think is what their earned, for example "5" for placing 5th.
* Then the points earned for placing 5th would be {@code pointsEarned}, 3 points for 5th?
*/
private int keyValue, pointsEarned;
/**
* Don't know really
*/
private boolean multiplicative;
/**
* @return the key value
*/
public int keyValue() {
return keyValue;
}
/**
* @return points earned for achieving the key value?
*/
public int pointsEarned() {
return pointsEarned;
}
/**
* @return {@code true} if multiplicative
*/
public boolean multiplicative() {
return multiplicative;
}
}
|
3e16f6f199f02bdd83edc3259d040962283a1a6e | 2,019 | java | Java | com-niubility-service/com-niubility-service-base2/src/main/java/combookservice/service/rabbit/MsgRabbitSend.java | xpxwo100/niubility | 23cbd613db034bdc375723578bcefb6cef2e6741 | [
"Apache-2.0"
] | 2 | 2019-09-04T13:16:33.000Z | 2021-06-28T12:12:55.000Z | com-niubility-service/com-niubility-service-base2_A/src/main/java/combookservice/service/rabbit/MsgRabbitSend.java | xpxwo100/niubility | 23cbd613db034bdc375723578bcefb6cef2e6741 | [
"Apache-2.0"
] | null | null | null | com-niubility-service/com-niubility-service-base2_A/src/main/java/combookservice/service/rabbit/MsgRabbitSend.java | xpxwo100/niubility | 23cbd613db034bdc375723578bcefb6cef2e6741 | [
"Apache-2.0"
] | null | null | null | 33.65 | 112 | 0.719663 | 9,782 | package combookservice.service.rabbit;
import boot.util.FSTUtil;
import boot.util.MsgDto;
import combookservice.service.config.RabbitConfig;
import combookservice.service.entity.Boy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class MsgRabbitSend implements RabbitTemplate.ConfirmCallback {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
//由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE,所以不能自动注入
private RabbitTemplate rabbitTemplate;
@Autowired
public MsgRabbitSend(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话,那回调就是最后设置的内容
}
public void sendMsg(Object content) {
MsgDto msgDto = new MsgDto();
msgDto.setObj(content);
CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
byte[] bytes = FSTUtil.encodeBuf(msgDto,msgDto.getClass());
rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_A, RabbitConfig.ROUTINGKEY_A, bytes, correlationId);
}
@Override
public void confirm(CorrelationData correlationData, boolean ack, String s) {
logger.info(" 回调id:" + correlationData);
if (ack) {
logger.info("消息成功消费");
} else {
logger.info("消息消费失败:" + s);
}
}
public static void main(String[] args) {
Boy boy = new Boy(15,"tom",23);
MsgDto objectDto = new MsgDto();
objectDto.setObj(boy);
byte[] a = FSTUtil.encodeBuf(objectDto,objectDto.getClass());
MsgDto b = (MsgDto)FSTUtil.decodeBuf(a,MsgDto.class);
System.out.println(b.getObj().toString());
}
}
|
3e16f720a435c83f0172b5efb8e9bbe692ece14b | 1,863 | java | Java | src/main/java/com/juniormascarenhas/assemblyvoting/entity/Assembly.java | juniorug/assembly-voting | 9c71542e0d0edd1a33a66e9179f5f45afc7c8246 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/juniormascarenhas/assemblyvoting/entity/Assembly.java | juniorug/assembly-voting | 9c71542e0d0edd1a33a66e9179f5f45afc7c8246 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/juniormascarenhas/assemblyvoting/entity/Assembly.java | juniorug/assembly-voting | 9c71542e0d0edd1a33a66e9179f5f45afc7c8246 | [
"Apache-2.0"
] | null | null | null | 26.239437 | 79 | 0.765969 | 9,783 | package com.juniormascarenhas.assemblyvoting.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.juniormascarenhas.assemblyvoting.response.AssemblyResponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "T_ASSEMBLY")
public class Assembly implements Serializable {
private static final long serialVersionUID = 8662339341215044485L;
@Id
@Column(name = "ASSEMBLY_ID")
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private String id;
@Column(name = "DESCRIPTION", length = 1024)
private String description;
@Column(name = "REALIZATION_DATE")
@DateTimeFormat(pattern = "yyyy.MM.dd HH:mm:ss")
private LocalDateTime realizationDate;
@Column(name = "CREATED_AT")
private LocalDateTime createdAt;
@Column(name = "UPDATED_AT")
private LocalDateTime updatedAt;
@JsonIgnore
@Builder.Default
@OneToMany(orphanRemoval = true, mappedBy = "assembly")
private List<TopicSession> topicSessions = List.of();
public AssemblyResponse toResponse() {
return AssemblyResponse.builder()
.id(id)
.description(description)
.realizationDate(realizationDate)
.createdAt(createdAt)
.updatedAt(updatedAt)
.topicSessions(topicSessions)
.build();
}
}
|
3e16f771e8ad72ae19de4aa66e46897dfeb93849 | 34,661 | java | Java | cloudtower-java-sdk-okhttp-gson/src/main/java/com/smartx/tower/api/VmPlacementGroupApi.java | Sczlog/cloudtower-java-sdk | efc33c88433214b887c13a41043380d220f46372 | [
"MIT"
] | null | null | null | cloudtower-java-sdk-okhttp-gson/src/main/java/com/smartx/tower/api/VmPlacementGroupApi.java | Sczlog/cloudtower-java-sdk | efc33c88433214b887c13a41043380d220f46372 | [
"MIT"
] | null | null | null | cloudtower-java-sdk-okhttp-gson/src/main/java/com/smartx/tower/api/VmPlacementGroupApi.java | Sczlog/cloudtower-java-sdk | efc33c88433214b887c13a41043380d220f46372 | [
"MIT"
] | null | null | null | 50.89721 | 247 | 0.70249 | 9,784 | /*
* Tower SDK API
* cloudtower operation API and SDK
*
* The version of the OpenAPI document: 1.7.0
*
*
* 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.smartx.tower.api;
import com.smartx.tower.ApiCallback;
import com.smartx.tower.ApiClient;
import com.smartx.tower.ApiException;
import com.smartx.tower.ApiResponse;
import com.smartx.tower.Configuration;
import com.smartx.tower.Pair;
import com.smartx.tower.ProgressRequestBody;
import com.smartx.tower.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import com.smartx.tower.model.GetVmPlacementGroupsConnectionRequestBody;
import com.smartx.tower.model.GetVmPlacementGroupsRequestBody;
import com.smartx.tower.model.VmPlacementGroup;
import com.smartx.tower.model.VmPlacementGroupConnection;
import com.smartx.tower.model.VmPlacementGroupCreationParams;
import com.smartx.tower.model.VmPlacementGroupDeletionParams;
import com.smartx.tower.model.VmPlacementGroupUpdationParams;
import com.smartx.tower.model.WithTaskDeleteVmPlacementGroup;
import com.smartx.tower.model.WithTaskVmPlacementGroup;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VmPlacementGroupApi {
private ApiClient localVarApiClient;
public VmPlacementGroupApi() {
this(Configuration.getDefaultApiClient());
}
public VmPlacementGroupApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
/**
* Build call for createVmPlacementGroup
* @param vmPlacementGroupCreationParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call createVmPlacementGroupCall(List<VmPlacementGroupCreationParams> vmPlacementGroupCreationParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = vmPlacementGroupCreationParams;
// create path and map variables
String localVarPath = "/create-vm-placement-group";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentLanguage != null) {
localVarHeaderParams.put("content-language", localVarApiClient.parameterToString(contentLanguage));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "Authorization" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call createVmPlacementGroupValidateBeforeCall(List<VmPlacementGroupCreationParams> vmPlacementGroupCreationParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'vmPlacementGroupCreationParams' is set
if (vmPlacementGroupCreationParams == null) {
throw new ApiException("Missing the required parameter 'vmPlacementGroupCreationParams' when calling createVmPlacementGroup(Async)");
}
okhttp3.Call localVarCall = createVmPlacementGroupCall(vmPlacementGroupCreationParams, contentLanguage, _callback);
return localVarCall;
}
/**
*
*
* @param vmPlacementGroupCreationParams (required)
* @param contentLanguage (optional, default to en-US)
* @return List<WithTaskVmPlacementGroup>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public List<WithTaskVmPlacementGroup> createVmPlacementGroup(List<VmPlacementGroupCreationParams> vmPlacementGroupCreationParams, String contentLanguage) throws ApiException {
ApiResponse<List<WithTaskVmPlacementGroup>> localVarResp = createVmPlacementGroupWithHttpInfo(vmPlacementGroupCreationParams, contentLanguage);
return localVarResp.getData();
}
/**
*
*
* @param vmPlacementGroupCreationParams (required)
* @param contentLanguage (optional, default to en-US)
* @return ApiResponse<List<WithTaskVmPlacementGroup>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<WithTaskVmPlacementGroup>> createVmPlacementGroupWithHttpInfo(List<VmPlacementGroupCreationParams> vmPlacementGroupCreationParams, String contentLanguage) throws ApiException {
okhttp3.Call localVarCall = createVmPlacementGroupValidateBeforeCall(vmPlacementGroupCreationParams, contentLanguage, null);
Type localVarReturnType = new TypeToken<List<WithTaskVmPlacementGroup>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param vmPlacementGroupCreationParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call createVmPlacementGroupAsync(List<VmPlacementGroupCreationParams> vmPlacementGroupCreationParams, String contentLanguage, final ApiCallback<List<WithTaskVmPlacementGroup>> _callback) throws ApiException {
okhttp3.Call localVarCall = createVmPlacementGroupValidateBeforeCall(vmPlacementGroupCreationParams, contentLanguage, _callback);
Type localVarReturnType = new TypeToken<List<WithTaskVmPlacementGroup>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for deleteVmPlacementGroup
* @param vmPlacementGroupDeletionParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteVmPlacementGroupCall(VmPlacementGroupDeletionParams vmPlacementGroupDeletionParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = vmPlacementGroupDeletionParams;
// create path and map variables
String localVarPath = "/delete-vm-placement-group";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentLanguage != null) {
localVarHeaderParams.put("content-language", localVarApiClient.parameterToString(contentLanguage));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "Authorization" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call deleteVmPlacementGroupValidateBeforeCall(VmPlacementGroupDeletionParams vmPlacementGroupDeletionParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'vmPlacementGroupDeletionParams' is set
if (vmPlacementGroupDeletionParams == null) {
throw new ApiException("Missing the required parameter 'vmPlacementGroupDeletionParams' when calling deleteVmPlacementGroup(Async)");
}
okhttp3.Call localVarCall = deleteVmPlacementGroupCall(vmPlacementGroupDeletionParams, contentLanguage, _callback);
return localVarCall;
}
/**
*
*
* @param vmPlacementGroupDeletionParams (required)
* @param contentLanguage (optional, default to en-US)
* @return List<WithTaskDeleteVmPlacementGroup>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public List<WithTaskDeleteVmPlacementGroup> deleteVmPlacementGroup(VmPlacementGroupDeletionParams vmPlacementGroupDeletionParams, String contentLanguage) throws ApiException {
ApiResponse<List<WithTaskDeleteVmPlacementGroup>> localVarResp = deleteVmPlacementGroupWithHttpInfo(vmPlacementGroupDeletionParams, contentLanguage);
return localVarResp.getData();
}
/**
*
*
* @param vmPlacementGroupDeletionParams (required)
* @param contentLanguage (optional, default to en-US)
* @return ApiResponse<List<WithTaskDeleteVmPlacementGroup>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<WithTaskDeleteVmPlacementGroup>> deleteVmPlacementGroupWithHttpInfo(VmPlacementGroupDeletionParams vmPlacementGroupDeletionParams, String contentLanguage) throws ApiException {
okhttp3.Call localVarCall = deleteVmPlacementGroupValidateBeforeCall(vmPlacementGroupDeletionParams, contentLanguage, null);
Type localVarReturnType = new TypeToken<List<WithTaskDeleteVmPlacementGroup>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param vmPlacementGroupDeletionParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call deleteVmPlacementGroupAsync(VmPlacementGroupDeletionParams vmPlacementGroupDeletionParams, String contentLanguage, final ApiCallback<List<WithTaskDeleteVmPlacementGroup>> _callback) throws ApiException {
okhttp3.Call localVarCall = deleteVmPlacementGroupValidateBeforeCall(vmPlacementGroupDeletionParams, contentLanguage, _callback);
Type localVarReturnType = new TypeToken<List<WithTaskDeleteVmPlacementGroup>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for getVmPlacementGroups
* @param getVmPlacementGroupsRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getVmPlacementGroupsCall(GetVmPlacementGroupsRequestBody getVmPlacementGroupsRequestBody, String contentLanguage, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = getVmPlacementGroupsRequestBody;
// create path and map variables
String localVarPath = "/get-vm-placement-groups";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentLanguage != null) {
localVarHeaderParams.put("content-language", localVarApiClient.parameterToString(contentLanguage));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "Authorization" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getVmPlacementGroupsValidateBeforeCall(GetVmPlacementGroupsRequestBody getVmPlacementGroupsRequestBody, String contentLanguage, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'getVmPlacementGroupsRequestBody' is set
if (getVmPlacementGroupsRequestBody == null) {
throw new ApiException("Missing the required parameter 'getVmPlacementGroupsRequestBody' when calling getVmPlacementGroups(Async)");
}
okhttp3.Call localVarCall = getVmPlacementGroupsCall(getVmPlacementGroupsRequestBody, contentLanguage, _callback);
return localVarCall;
}
/**
*
*
* @param getVmPlacementGroupsRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @return List<VmPlacementGroup>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public List<VmPlacementGroup> getVmPlacementGroups(GetVmPlacementGroupsRequestBody getVmPlacementGroupsRequestBody, String contentLanguage) throws ApiException {
ApiResponse<List<VmPlacementGroup>> localVarResp = getVmPlacementGroupsWithHttpInfo(getVmPlacementGroupsRequestBody, contentLanguage);
return localVarResp.getData();
}
/**
*
*
* @param getVmPlacementGroupsRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @return ApiResponse<List<VmPlacementGroup>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<VmPlacementGroup>> getVmPlacementGroupsWithHttpInfo(GetVmPlacementGroupsRequestBody getVmPlacementGroupsRequestBody, String contentLanguage) throws ApiException {
okhttp3.Call localVarCall = getVmPlacementGroupsValidateBeforeCall(getVmPlacementGroupsRequestBody, contentLanguage, null);
Type localVarReturnType = new TypeToken<List<VmPlacementGroup>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param getVmPlacementGroupsRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getVmPlacementGroupsAsync(GetVmPlacementGroupsRequestBody getVmPlacementGroupsRequestBody, String contentLanguage, final ApiCallback<List<VmPlacementGroup>> _callback) throws ApiException {
okhttp3.Call localVarCall = getVmPlacementGroupsValidateBeforeCall(getVmPlacementGroupsRequestBody, contentLanguage, _callback);
Type localVarReturnType = new TypeToken<List<VmPlacementGroup>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for getVmPlacementGroupsConnection
* @param getVmPlacementGroupsConnectionRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getVmPlacementGroupsConnectionCall(GetVmPlacementGroupsConnectionRequestBody getVmPlacementGroupsConnectionRequestBody, String contentLanguage, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = getVmPlacementGroupsConnectionRequestBody;
// create path and map variables
String localVarPath = "/get-vm-placement-groups-connection";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentLanguage != null) {
localVarHeaderParams.put("content-language", localVarApiClient.parameterToString(contentLanguage));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "Authorization" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getVmPlacementGroupsConnectionValidateBeforeCall(GetVmPlacementGroupsConnectionRequestBody getVmPlacementGroupsConnectionRequestBody, String contentLanguage, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'getVmPlacementGroupsConnectionRequestBody' is set
if (getVmPlacementGroupsConnectionRequestBody == null) {
throw new ApiException("Missing the required parameter 'getVmPlacementGroupsConnectionRequestBody' when calling getVmPlacementGroupsConnection(Async)");
}
okhttp3.Call localVarCall = getVmPlacementGroupsConnectionCall(getVmPlacementGroupsConnectionRequestBody, contentLanguage, _callback);
return localVarCall;
}
/**
*
*
* @param getVmPlacementGroupsConnectionRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @return VmPlacementGroupConnection
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public VmPlacementGroupConnection getVmPlacementGroupsConnection(GetVmPlacementGroupsConnectionRequestBody getVmPlacementGroupsConnectionRequestBody, String contentLanguage) throws ApiException {
ApiResponse<VmPlacementGroupConnection> localVarResp = getVmPlacementGroupsConnectionWithHttpInfo(getVmPlacementGroupsConnectionRequestBody, contentLanguage);
return localVarResp.getData();
}
/**
*
*
* @param getVmPlacementGroupsConnectionRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @return ApiResponse<VmPlacementGroupConnection>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<VmPlacementGroupConnection> getVmPlacementGroupsConnectionWithHttpInfo(GetVmPlacementGroupsConnectionRequestBody getVmPlacementGroupsConnectionRequestBody, String contentLanguage) throws ApiException {
okhttp3.Call localVarCall = getVmPlacementGroupsConnectionValidateBeforeCall(getVmPlacementGroupsConnectionRequestBody, contentLanguage, null);
Type localVarReturnType = new TypeToken<VmPlacementGroupConnection>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param getVmPlacementGroupsConnectionRequestBody (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getVmPlacementGroupsConnectionAsync(GetVmPlacementGroupsConnectionRequestBody getVmPlacementGroupsConnectionRequestBody, String contentLanguage, final ApiCallback<VmPlacementGroupConnection> _callback) throws ApiException {
okhttp3.Call localVarCall = getVmPlacementGroupsConnectionValidateBeforeCall(getVmPlacementGroupsConnectionRequestBody, contentLanguage, _callback);
Type localVarReturnType = new TypeToken<VmPlacementGroupConnection>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for updateVmPlacementGroup
* @param vmPlacementGroupUpdationParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call updateVmPlacementGroupCall(VmPlacementGroupUpdationParams vmPlacementGroupUpdationParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = vmPlacementGroupUpdationParams;
// create path and map variables
String localVarPath = "/update-vm-placement-group";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (contentLanguage != null) {
localVarHeaderParams.put("content-language", localVarApiClient.parameterToString(contentLanguage));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "Authorization" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call updateVmPlacementGroupValidateBeforeCall(VmPlacementGroupUpdationParams vmPlacementGroupUpdationParams, String contentLanguage, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'vmPlacementGroupUpdationParams' is set
if (vmPlacementGroupUpdationParams == null) {
throw new ApiException("Missing the required parameter 'vmPlacementGroupUpdationParams' when calling updateVmPlacementGroup(Async)");
}
okhttp3.Call localVarCall = updateVmPlacementGroupCall(vmPlacementGroupUpdationParams, contentLanguage, _callback);
return localVarCall;
}
/**
*
*
* @param vmPlacementGroupUpdationParams (required)
* @param contentLanguage (optional, default to en-US)
* @return List<WithTaskVmPlacementGroup>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public List<WithTaskVmPlacementGroup> updateVmPlacementGroup(VmPlacementGroupUpdationParams vmPlacementGroupUpdationParams, String contentLanguage) throws ApiException {
ApiResponse<List<WithTaskVmPlacementGroup>> localVarResp = updateVmPlacementGroupWithHttpInfo(vmPlacementGroupUpdationParams, contentLanguage);
return localVarResp.getData();
}
/**
*
*
* @param vmPlacementGroupUpdationParams (required)
* @param contentLanguage (optional, default to en-US)
* @return ApiResponse<List<WithTaskVmPlacementGroup>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<WithTaskVmPlacementGroup>> updateVmPlacementGroupWithHttpInfo(VmPlacementGroupUpdationParams vmPlacementGroupUpdationParams, String contentLanguage) throws ApiException {
okhttp3.Call localVarCall = updateVmPlacementGroupValidateBeforeCall(vmPlacementGroupUpdationParams, contentLanguage, null);
Type localVarReturnType = new TypeToken<List<WithTaskVmPlacementGroup>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param vmPlacementGroupUpdationParams (required)
* @param contentLanguage (optional, default to en-US)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Ok </td><td> - </td></tr>
<tr><td> 400 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call updateVmPlacementGroupAsync(VmPlacementGroupUpdationParams vmPlacementGroupUpdationParams, String contentLanguage, final ApiCallback<List<WithTaskVmPlacementGroup>> _callback) throws ApiException {
okhttp3.Call localVarCall = updateVmPlacementGroupValidateBeforeCall(vmPlacementGroupUpdationParams, contentLanguage, _callback);
Type localVarReturnType = new TypeToken<List<WithTaskVmPlacementGroup>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}
|
3e16f7814688d9000f3ef21bea1c0029da126a93 | 2,180 | java | Java | officefloor/tutorials/TestHttpServer/src/test/java/net/officefloor/tutorial/testhttpserver/TemplateLogicTest.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 17 | 2019-09-30T08:23:01.000Z | 2021-12-20T04:51:03.000Z | officefloor/tutorials/TestHttpServer/src/test/java/net/officefloor/tutorial/testhttpserver/TemplateLogicTest.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 880 | 2019-07-08T04:31:14.000Z | 2022-03-16T20:16:03.000Z | officefloor/tutorials/TestHttpServer/src/test/java/net/officefloor/tutorial/testhttpserver/TemplateLogicTest.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 3 | 2019-09-30T08:22:37.000Z | 2021-10-13T10:05:24.000Z | 29.459459 | 101 | 0.758716 | 9,785 | package net.officefloor.tutorial.testhttpserver;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.officefloor.OfficeFloorMain;
import net.officefloor.server.http.HttpMethod;
import net.officefloor.server.http.mock.MockHttpResponse;
import net.officefloor.server.http.mock.MockHttpServer;
import net.officefloor.tutorial.testhttpserver.TemplateLogic.Parameters;
import net.officefloor.woof.mock.MockWoofServerExtension;
/**
* Tests the {@link TemplateLogic}.
*
* @author Daniel Sagenschneider
*/
public class TemplateLogicTest {
/**
* Main to run for manual testing.
*/
public static void main(String[] args) throws Exception {
OfficeFloorMain.main(args);
}
// START SNIPPET: unit
@Test
public void unitTest() {
// Load the parameters
Parameters parameters = new Parameters();
parameters.setA("1");
parameters.setB("2");
assertNull(parameters.getResult(), "Shoud not have result");
// Test
TemplateLogic logic = new TemplateLogic();
logic.add(parameters, new Calculator());
assertEquals("3", parameters.getResult(), "Incorrect result");
}
// END SNIPPET: unit
// START SNIPPET: system
@RegisterExtension
public final MockWoofServerExtension server = new MockWoofServerExtension();
@Test
public void systemTest() throws Exception {
// Send request to add
MockHttpResponse response = this.server
.sendFollowRedirect(MockHttpServer.mockRequest("/template+add?a=1&b=2").method(HttpMethod.POST));
assertEquals(200, response.getStatus().getStatusCode(), "Should be successful");
// Ensure added the values
String entity = response.getEntity(null);
assertTrue(entity.contains("= 3"), "Should have added the values");
}
// END SNIPPET: system
// START SNIPPET: inject-dependency
@Test
public void injectDependency(Calculator calculator) {
int result = calculator.plus(1, 2);
assertEquals(3, result, "Should calculate correct result");
}
// END SNIPPET: inject-dependency
} |
3e16f7b661eeb36fafdbd4300acf1f6e590e22f8 | 6,221 | java | Java | services/drs/src/main/java/com/huaweicloud/sdk/drs/v3/model/ListUsersResponse.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 50 | 2020-05-18T11:35:20.000Z | 2022-03-15T02:07:05.000Z | services/drs/src/main/java/com/huaweicloud/sdk/drs/v3/model/ListUsersResponse.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 45 | 2020-07-06T03:34:12.000Z | 2022-03-31T09:41:54.000Z | services/drs/src/main/java/com/huaweicloud/sdk/drs/v3/model/ListUsersResponse.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 27 | 2020-05-28T11:08:44.000Z | 2022-03-30T03:30:37.000Z | 28.536697 | 106 | 0.641215 | 9,786 | package com.huaweicloud.sdk.drs.v3.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** Response Object */
public class ListUsersResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "job_id")
private String jobId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "is_global_password")
private String isGlobalPassword;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "message")
private String message;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "user_list")
private List<QueryUserDetailResp> userList = null;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "roles_list")
private List<QueryRoleDetailResp> rolesList = null;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "is_success")
private Boolean isSuccess;
public ListUsersResponse withJobId(String jobId) {
this.jobId = jobId;
return this;
}
/** 任务id
*
* @return jobId */
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public ListUsersResponse withIsGlobalPassword(String isGlobalPassword) {
this.isGlobalPassword = isGlobalPassword;
return this;
}
/** 是否使用全局密码
*
* @return isGlobalPassword */
public String getIsGlobalPassword() {
return isGlobalPassword;
}
public void setIsGlobalPassword(String isGlobalPassword) {
this.isGlobalPassword = isGlobalPassword;
}
public ListUsersResponse withMessage(String message) {
this.message = message;
return this;
}
/** 错误码
*
* @return message */
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ListUsersResponse withUserList(List<QueryUserDetailResp> userList) {
this.userList = userList;
return this;
}
public ListUsersResponse addUserListItem(QueryUserDetailResp userListItem) {
if (this.userList == null) {
this.userList = new ArrayList<>();
}
this.userList.add(userListItem);
return this;
}
public ListUsersResponse withUserList(Consumer<List<QueryUserDetailResp>> userListSetter) {
if (this.userList == null) {
this.userList = new ArrayList<>();
}
userListSetter.accept(this.userList);
return this;
}
/** 用户列表数据
*
* @return userList */
public List<QueryUserDetailResp> getUserList() {
return userList;
}
public void setUserList(List<QueryUserDetailResp> userList) {
this.userList = userList;
}
public ListUsersResponse withRolesList(List<QueryRoleDetailResp> rolesList) {
this.rolesList = rolesList;
return this;
}
public ListUsersResponse addRolesListItem(QueryRoleDetailResp rolesListItem) {
if (this.rolesList == null) {
this.rolesList = new ArrayList<>();
}
this.rolesList.add(rolesListItem);
return this;
}
public ListUsersResponse withRolesList(Consumer<List<QueryRoleDetailResp>> rolesListSetter) {
if (this.rolesList == null) {
this.rolesList = new ArrayList<>();
}
rolesListSetter.accept(this.rolesList);
return this;
}
/** 角色列表数据
*
* @return rolesList */
public List<QueryRoleDetailResp> getRolesList() {
return rolesList;
}
public void setRolesList(List<QueryRoleDetailResp> rolesList) {
this.rolesList = rolesList;
}
public ListUsersResponse withIsSuccess(Boolean isSuccess) {
this.isSuccess = isSuccess;
return this;
}
/** 是否成功
*
* @return isSuccess */
public Boolean getIsSuccess() {
return isSuccess;
}
public void setIsSuccess(Boolean isSuccess) {
this.isSuccess = isSuccess;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListUsersResponse listUsersResponse = (ListUsersResponse) o;
return Objects.equals(this.jobId, listUsersResponse.jobId)
&& Objects.equals(this.isGlobalPassword, listUsersResponse.isGlobalPassword)
&& Objects.equals(this.message, listUsersResponse.message)
&& Objects.equals(this.userList, listUsersResponse.userList)
&& Objects.equals(this.rolesList, listUsersResponse.rolesList)
&& Objects.equals(this.isSuccess, listUsersResponse.isSuccess);
}
@Override
public int hashCode() {
return Objects.hash(jobId, isGlobalPassword, message, userList, rolesList, isSuccess);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ListUsersResponse {\n");
sb.append(" jobId: ").append(toIndentedString(jobId)).append("\n");
sb.append(" isGlobalPassword: ").append(toIndentedString(isGlobalPassword)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" userList: ").append(toIndentedString(userList)).append("\n");
sb.append(" rolesList: ").append(toIndentedString(rolesList)).append("\n");
sb.append(" isSuccess: ").append(toIndentedString(isSuccess)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e16f89a512096c87fb4a46f4e6b2b8625a54909 | 2,411 | java | Java | src/main/java/com/google/devtools/common/options/BoolOrEnumConverter.java | pbekambo/bazel.0.5.1 | 843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea | [
"Apache-2.0"
] | 64 | 2016-12-07T08:04:06.000Z | 2021-12-09T09:27:59.000Z | src/main/java/com/google/devtools/common/options/BoolOrEnumConverter.java | pbekambo/bazel.0.5.1 | 843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea | [
"Apache-2.0"
] | 5 | 2017-10-30T21:45:25.000Z | 2018-11-14T18:24:20.000Z | src/main/java/com/google/devtools/common/options/BoolOrEnumConverter.java | pbekambo/bazel.0.5.1 | 843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea | [
"Apache-2.0"
] | 7 | 2017-01-10T08:10:57.000Z | 2021-03-19T07:00:37.000Z | 38.269841 | 96 | 0.719618 | 9,787 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.common.options;
import com.google.devtools.common.options.Converters.BooleanConverter;
/**
* Converter that can also convert from booleans and enumerations.
*
* <p> This is able to additionally convert from the standard set of
* boolean string values. If there is an overlap in values, those from
* the underlying enumeration will be taken.
*/
public abstract class BoolOrEnumConverter<T extends Enum<T>> extends EnumConverter<T>{
private T falseValue;
private T trueValue;
/**
* You *must* implement a zero-argument constructor that delegates
* to this constructor, passing in the appropriate parameters. This
* comes from the base {@link EnumConverter} class.
*
* @param enumType The type of your enumeration; usually a class literal
* like MyEnum.class
* @param typeName The intuitive name of your enumeration, for example, the
* type name for CompilationMode might be "compilation mode".
* @param trueValue The enumeration value to associate with {@code true}.
* @param falseValue The enumeration value to associate with {@code false}.
*/
protected BoolOrEnumConverter(Class<T> enumType, String typeName, T trueValue, T falseValue) {
super(enumType, typeName);
this.trueValue = trueValue;
this.falseValue = falseValue;
}
@Override
public T convert(String input) throws OptionsParsingException {
try {
return super.convert(input);
} catch (OptionsParsingException eEnum) {
try {
BooleanConverter booleanConverter = new BooleanConverter();
boolean value = booleanConverter.convert(input);
return value ? trueValue : falseValue;
} catch (OptionsParsingException eBoolean) {
throw eEnum;
}
}
}
}
|
3e16f94845c90558bd2bae3b3da0037b627f3812 | 328 | java | Java | officemaps/src/main/java/com/blagoy/officemaps/repository/FloorRepository.java | Lascor22/HackatonWartsila | b1d65deed5f14670a6c9cfaa7978d98617243471 | [
"MIT"
] | 1 | 2020-02-17T14:24:03.000Z | 2020-02-17T14:24:03.000Z | officemaps/src/main/java/com/blagoy/officemaps/repository/FloorRepository.java | Lascor22/HackatonWartsila | b1d65deed5f14670a6c9cfaa7978d98617243471 | [
"MIT"
] | null | null | null | officemaps/src/main/java/com/blagoy/officemaps/repository/FloorRepository.java | Lascor22/HackatonWartsila | b1d65deed5f14670a6c9cfaa7978d98617243471 | [
"MIT"
] | null | null | null | 27.333333 | 69 | 0.829268 | 9,788 | package com.blagoy.officemaps.repository;
import com.blagoy.officemaps.domain.Floor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FloorRepository extends JpaRepository<Floor, Long> {
public Floor findByNumber(long number);
}
|
3e16f9e747a1f303307cc9dd066f9cce27499e8d | 4,320 | java | Java | src/main/java/org/hzero/platform/domain/entity/DashboardTenantCard.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | 7 | 2020-09-27T09:09:27.000Z | 2021-06-11T12:48:32.000Z | src/main/java/org/hzero/platform/domain/entity/DashboardTenantCard.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | null | null | null | src/main/java/org/hzero/platform/domain/entity/DashboardTenantCard.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | 17 | 2020-09-23T07:51:40.000Z | 2021-11-23T13:52:08.000Z | 23.527174 | 102 | 0.673597 | 9,789 | package org.hzero.platform.domain.entity;
import java.util.Date;
import java.util.Objects;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hzero.core.base.BaseConstants;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.hzero.platform.domain.repository.DashboardTenantCardRepository;
import org.hzero.platform.infra.constant.HpfmMsgCodeConstants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.annotation.ModifyAudit;
import io.choerodon.mybatis.annotation.VersionAudit;
import io.choerodon.mybatis.domain.AuditDomain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hzero.starter.keyencrypt.core.Encrypt;
/**
* 租户卡片分配
*
* @author nnheo@example.com 2019-01-24 09:30:19
*/
@ApiModel("租户卡片分配")
@VersionAudit
@ModifyAudit
@Table(name = "hpfm_dashboard_tenant_card")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DashboardTenantCard extends AuditDomain {
public static final String FIELD_ID = "id";
public static final String FIELD_TENANT_ID = "tenantId";
public static final String FIELD_CARD_ID = "cardId";
//
// 业务方法(按public protected private顺序排列)
// ------------------------------------------------------------------------------
/**
* 校验数据是否已经存在
*/
public void validate(DashboardTenantCardRepository tenantCardRepository) {
int count = tenantCardRepository.selectCountByCondition(Condition.builder(DashboardTenantCard.class)
.andWhere(Sqls.custom()
.andEqualTo(FIELD_CARD_ID, cardId)
.andEqualTo(FIELD_TENANT_ID, tenantId)
)
.build());
if (count != 0) {
throw new CommonException(BaseConstants.ErrorCode.DATA_EXISTS);
}
}
//
// 数据库字段
// ------------------------------------------------------------------------------
@ApiModelProperty("表ID,主键,供其他表做外键")
@Id
@GeneratedValue
@Encrypt
private Long id;
@ApiModelProperty(value = "租户表hpfm_tenant.tenant_id")
@NotNull
private Long tenantId;
@ApiModelProperty(value = "卡片表hpfm_dashboard_card.id")
@NotNull
@Encrypt
private Long cardId;
//
// 非数据库字段
// ------------------------------------------------------------------------------
@Transient
@ApiModelProperty("租户名称")
private String tenantName;
@Transient
@ApiModelProperty("租户编码")
private String tenantNum;
@Transient
@ApiModelProperty("起始时间-筛选注册时间使用")
@JsonIgnore
private Date beginDate;
@Transient
@JsonIgnore
@ApiModelProperty("结束时间-筛选注册时间使用")
private Date endDate;
//
// getter/setter
// ------------------------------------------------------------------------------
/**
* @return 表ID,主键,供其他表做外键
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @return 租户表hpfm_tenant.tenant_id
*/
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
/**
* @return 卡片表hpfm_dashboard_card.id
*/
public Long getCardId() {
return cardId;
}
public void setCardId(Long cardId) {
this.cardId = cardId;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
}
public String getTenantNum() {
return tenantNum;
}
public void setTenantNum(String tenantNum) {
this.tenantNum = tenantNum;
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof DashboardTenantCard))
return false;
DashboardTenantCard that = (DashboardTenantCard) o;
return getTenantId().equals(that.getTenantId()) && getCardId().equals(that.getCardId());
}
@Override
public int hashCode() {
return Objects.hash(getTenantId(), getCardId());
}
}
|
3e16fa005fa27c703c4706f3376ab42b457aac23 | 561 | java | Java | src/main/java/com/example/demo/config/RestTemplateConfig.java | stableShip/spring_learn | fd7de7a8272ecb09b72aad57a9e10cedc5a15487 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/config/RestTemplateConfig.java | stableShip/spring_learn | fd7de7a8272ecb09b72aad57a9e10cedc5a15487 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/config/RestTemplateConfig.java | stableShip/spring_learn | fd7de7a8272ecb09b72aad57a9e10cedc5a15487 | [
"MIT"
] | null | null | null | 24.391304 | 63 | 0.782531 | 9,790 | package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateConfig {
@Autowired
private RestTemplateBuilder builder;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = builder.build();
return restTemplate;
}
}
|
3e16fa1fb0a44d4b3bfeebb4d43efd9df20c8c46 | 2,531 | java | Java | src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java | Ben-Liao/twilio-java | 5073c0f3fe613f51937983c0551d797c309377a7 | [
"MIT"
] | 295 | 2015-01-04T17:00:48.000Z | 2022-03-29T21:51:49.000Z | src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java | Ben-Liao/twilio-java | 5073c0f3fe613f51937983c0551d797c309377a7 | [
"MIT"
] | 349 | 2015-01-14T19:08:16.000Z | 2022-03-09T15:50:13.000Z | src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java | Ben-Liao/twilio-java | 5073c0f3fe613f51937983c0551d797c309377a7 | [
"MIT"
] | 376 | 2015-01-03T22:31:01.000Z | 2022-03-31T08:23:17.000Z | 33.746667 | 113 | 0.646385 | 9,791 | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.api.v2010.account;
import com.twilio.base.Deleter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
public class ConnectAppDeleter extends Deleter<ConnectApp> {
private String pathAccountSid;
private final String pathSid;
/**
* Construct a new ConnectAppDeleter.
*
* @param pathSid The unique string that identifies the resource
*/
public ConnectAppDeleter(final String pathSid) {
this.pathSid = pathSid;
}
/**
* Construct a new ConnectAppDeleter.
*
* @param pathAccountSid The SID of the Account that created the resource to
* fetch
* @param pathSid The unique string that identifies the resource
*/
public ConnectAppDeleter(final String pathAccountSid,
final String pathSid) {
this.pathAccountSid = pathAccountSid;
this.pathSid = pathSid;
}
/**
* Make the request to the Twilio API to perform the delete.
*
* @param client TwilioRestClient with which to make the request
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public boolean delete(final TwilioRestClient client) {
this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
Request request = new Request(
HttpMethod.DELETE,
Domains.API.toString(),
"/2010-04-01/Accounts/" + this.pathAccountSid + "/ConnectApps/" + this.pathSid + ".json"
);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("ConnectApp delete failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(restException);
}
return response.getStatusCode() == 204;
}
} |
3e16fa7c6d99dd08013fdf7a682e01fcbfd6effa | 1,908 | java | Java | src/main/java/com/qmdx00/onenet/mq/SslUtil.java | qmdx00/onenet-iot-project | 09d2c54660713e2748253d40ca598495e2a17d76 | [
"MIT"
] | 27 | 2019-06-21T08:01:03.000Z | 2022-01-21T05:50:10.000Z | src/main/java/com/qmdx00/onenet/mq/SslUtil.java | SteveAndy/onenet-iot-project | 09d2c54660713e2748253d40ca598495e2a17d76 | [
"MIT"
] | null | null | null | src/main/java/com/qmdx00/onenet/mq/SslUtil.java | SteveAndy/onenet-iot-project | 09d2c54660713e2748253d40ca598495e2a17d76 | [
"MIT"
] | 30 | 2019-06-21T07:45:29.000Z | 2022-03-28T14:48:18.000Z | 34.690909 | 113 | 0.666143 | 9,792 | package com.qmdx00.onenet.mq;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author yuanweimin
* @date 19/06/12 17:07
* @description 证书加载类
*/
@SuppressWarnings("ALL")
public class SslUtil {
public static SSLSocketFactory getSocketFactory(final InputStream caCrtFile) throws NoSuchAlgorithmException,
IOException, KeyStoreException, CertificateException, KeyManagementException {
Security.addProvider(new BouncyCastleProvider());
//===========加载 ca 证书==================================
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
if (null != caCrtFile) {
// 加载本地指定的 ca 证书
PEMReader reader = new PEMReader(new InputStreamReader(caCrtFile));
X509Certificate caCert = (X509Certificate) reader.readObject();
reader.close();
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
// 把ca作为信任的 ca 列表,来验证服务器证书
tmf.init(caKs);
} else {
//使用系统默认的安全证书
tmf.init((KeyStore) null);
}
// ============finally, create SSL socket factory==============
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
}
|
3e16fb03d7350aac16b20df8037aed32a847849d | 4,224 | java | Java | imsspringboot/src/main/java/com/ims/controllers/JwtAuthenticationRestController.java | pradeepjava/springbootIMS | 8e34d82f89f39bf6a62759dc536be385345a3976 | [
"Unlicense"
] | null | null | null | imsspringboot/src/main/java/com/ims/controllers/JwtAuthenticationRestController.java | pradeepjava/springbootIMS | 8e34d82f89f39bf6a62759dc536be385345a3976 | [
"Unlicense"
] | null | null | null | imsspringboot/src/main/java/com/ims/controllers/JwtAuthenticationRestController.java | pradeepjava/springbootIMS | 8e34d82f89f39bf6a62759dc536be385345a3976 | [
"Unlicense"
] | null | null | null | 39.476636 | 114 | 0.817708 | 9,793 | package com.ims.controllers;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ims.exception.AuthenticationException;
import com.ims.jwt.dto.JwtTokenRequest;
import com.ims.jwt.dto.JwtTokenResponse;
import com.ims.jwt.utility.JwtTokenUtil;
import com.ims.userdetails.CredentialStatus;
@RestController
@CrossOrigin(origins = "${allowed.origin}")
public class JwtAuthenticationRestController {
@Value("${jwt.http.request.header}")
private String tokenHeader;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService jwtUsrDetailsService;
@RequestMapping(value = "${jwt.get.token.uri}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtTokenRequest authenticationRequest)
throws AuthenticationException {
CredentialStatus credentialStatus = authenticate(authenticationRequest.getUsername(),
authenticationRequest.getPassword());
return getResponse(authenticationRequest, credentialStatus);
}
private ResponseEntity<?> getResponse(JwtTokenRequest authenticationRequest, CredentialStatus credentialStatus) {
switch (credentialStatus) {
case INVALID_CREDENTIALS:
case USER_DISABLED:
return ResponseEntity.ok(new JwtTokenResponse(credentialStatus.name()));
default:
final UserDetails userDetails = jwtUsrDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtTokenResponse(token));
}
}
@RequestMapping(value = "${jwt.refresh.token.uri}", method = RequestMethod.GET)
public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
String authToken = request.getHeader(tokenHeader);
final String token = authToken.substring(7);
// String username = jwtTokenUtil.getUsernameFromToken(token);
// JwtUserDetails user = (JwtUserDetails) jwtUsrDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.canTokenBeRefreshed(token)) {
String refreshedToken = jwtTokenUtil.refreshToken(token);
return ResponseEntity.ok(new JwtTokenResponse(refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
@ExceptionHandler({ AuthenticationException.class })
public ResponseEntity<String> handleAuthenticationException(AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
private CredentialStatus authenticate(String username, String password) {
CredentialStatus status = null;
try {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
status = CredentialStatus.VALID;
}
catch (BadCredentialsException e) {
status = CredentialStatus.INVALID_CREDENTIALS;
throw new AuthenticationException("INVALID_CREDENTIALS", e);
}
catch (DisabledException e) {
status = CredentialStatus.USER_DISABLED;
throw new AuthenticationException("USER_DISABLED", e);
} finally {
return status;
}
}
} |
3e16fd1616fecbeb2673135d06ec07ad67cb42e2 | 7,593 | java | Java | bboss-persistent/test/com/frameworkset/orm/engine/model/NameFactoryTest.java | bbossgroups/bboss | 09c505a2d14943aa28463da9403f222419711e20 | [
"Apache-2.0"
] | 246 | 2015-10-29T03:02:48.000Z | 2022-03-31T03:58:17.000Z | bboss-persistent/test/com/frameworkset/orm/engine/model/NameFactoryTest.java | bbossgroups/bboss | 09c505a2d14943aa28463da9403f222419711e20 | [
"Apache-2.0"
] | 4 | 2016-11-17T08:27:47.000Z | 2021-07-28T09:31:56.000Z | bboss-persistent/test/com/frameworkset/orm/engine/model/NameFactoryTest.java | bbossgroups/bboss | 09c505a2d14943aa28463da9403f222419711e20 | [
"Apache-2.0"
] | 148 | 2015-01-19T06:35:15.000Z | 2022-01-07T04:53:04.000Z | 32.857143 | 83 | 0.555072 | 9,794 | /*
* Copyright 2008 biaoping.yin
*
* 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.frameworkset.orm.engine.model;
/*
*
* 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.
*/
import com.frameworkset.orm.engine.EngineException;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <p>Unit tests for class <code>NameFactory</code> and known
* <code>NameGenerator</code> implementations.</p>
*
* <p>To add more tests, add entries to the <code>ALGORITHMS</code>,
* <code>INPUTS</code>, and <code>OUTPUTS</code> arrays, and code to
* the <code>makeInputs()</code> method.</p>
*
* <p>This test assumes that it's being run using the MySQL database
* adapter, <code>DBMM</code>. MySQL has a column length limit of 64
* characters.</p>
*
* @author <a href="mailto:ychag@example.com">Daniel Rall</a>
* @version $Id: NameFactoryTest.java,v 1.6 2005/02/23 17:32:09 tfischer Exp $
*/
public class NameFactoryTest extends TestCase
{
/** The database to mimic in generating the SQL. */
private static final String DATABASE_TYPE = "mysql";
/**
* The list of known name generation algorithms, specified as the
* fully qualified class names to <code>NameGenerator</code>
* implementations.
*/
private static final String[] ALGORITHMS =
{ NameFactory.CONSTRAINT_GENERATOR, NameFactory.JAVA_GENERATOR };
/**
* Two dimensional arrays of inputs for each algorithm.
*/
private static final Object[][][] INPUTS =
{ { { makeString(61), "I", new Integer(1)}, {
makeString(61), "I", new Integer(2)
}, {
makeString(65), "I", new Integer(3)
}, {
makeString(4), "FK", new Integer(1)
}, {
makeString(5), "FK", new Integer(2)
}
}, {
{
"MY_USER",
NameGenerator.CONV_METHOD_UNDERSCORE }, {
"MY_USER",
NameGenerator.CONV_METHOD_UNDERSCORE_OMIT_SCHEMA }, {
"MY_USER",
NameGenerator.CONV_METHOD_JAVANAME }, {
"MY_USER",
NameGenerator.CONV_METHOD_NOCHANGE }, {
"MY_SCHEMA.MY_USER",
NameGenerator.CONV_METHOD_UNDERSCORE }, {
"MY_SCHEMA.MY_USER",
NameGenerator.CONV_METHOD_UNDERSCORE_OMIT_SCHEMA }, {
"MY_SCHEMA.MY_USER",
NameGenerator.CONV_METHOD_JAVANAME } , {
"MY_SCHEMA.MY_USER",
NameGenerator.CONV_METHOD_NOCHANGE }
}
};
/**
* Given the known inputs, the expected name outputs.
*/
private static final String[][] OUTPUTS =
{
{
makeString(60) + "_I_1",
makeString(60) + "_I_2",
makeString(60) + "_I_3",
makeString(4) + "_FK_1",
makeString(5) + "_FK_2" },
{
"MyUser",
"MyUser",
"MYUSER",
"MY_USER",
"MySchemaMyUser",
"MyUser",
"MYSCHEMAMYUSER",
"MY_SCHEMA.MY_USER"
}
};
/**
* Used as an input.
*/
private Database database;
/**
* Creates a new instance.
*
* @param name the name of the test to run
*/
public NameFactoryTest(String name)
{
super(name);
}
/**
* Creates a string of the specified length consisting entirely of
* the character <code>A</code>. Useful for simulating table
* names, etc.
*
* @param len the number of characters to include in the string
* @return a string of length <code>len</code> with every character an 'A'
*/
private static final String makeString(int len)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < len; i++)
{
buf.append('A');
}
return buf.toString();
}
/** Sets up the Torque model. */
public void setUp()
{
database = new Database(DATABASE_TYPE);
database.setDatabaseType(DATABASE_TYPE);
}
/**
* @throws Exception on fail
*/
public void testNames() throws Exception
{
for (int algoIndex = 0; algoIndex < ALGORITHMS.length; algoIndex++)
{
String algo = ALGORITHMS[algoIndex];
Object[][] algoInputs = INPUTS[algoIndex];
for (int i = 0; i < algoInputs.length; i++)
{
List inputs = makeInputs(algo, algoInputs[i]);
String generated = NameFactory.generateName(algo, inputs,false);
String expected = OUTPUTS[algoIndex][i];
assertEquals(
"Algorithm " + algo + " failed to generate an unique name",
generated,
expected);
}
}
}
/**
* @throws Exception on fail
*/
public void testException() throws Exception
{
try
{
NameFactory.generateName("non.existing.class", new ArrayList(),false);
assertTrue("Expected an EngineException", false);
}
catch (EngineException ex)
{
}
}
/**
* Creates the list of arguments to pass to the specified type of
* <code>NameGenerator</code> implementation.
*
* @param algo The class name of the <code>NameGenerator</code> to
* create an argument list for.
* @param inputs The (possibly partial) list inputs from which to
* generate the final list.
* @return the list of arguments to pass to the <code>NameGenerator</code>
*/
private final List makeInputs(String algo, Object[] inputs)
{
List list = null;
if (NameFactory.CONSTRAINT_GENERATOR.equals(algo))
{
list = new ArrayList(inputs.length + 1);
list.add(0, database);
list.addAll(Arrays.asList(inputs));
}
else if (NameFactory.JAVA_GENERATOR.equals(algo))
{
list = Arrays.asList(inputs);
}
return list;
}
}
|
3e16fe022dba3c134fa33fdd5a26ba9957ab91d4 | 413 | java | Java | src/main/java/protocol/response/CreateGroupResponsePacket.java | December26/CmdChat | 7efaaa66d5e6681f1240aa2fae457e35b74f3771 | [
"MIT"
] | null | null | null | src/main/java/protocol/response/CreateGroupResponsePacket.java | December26/CmdChat | 7efaaa66d5e6681f1240aa2fae457e35b74f3771 | [
"MIT"
] | null | null | null | src/main/java/protocol/response/CreateGroupResponsePacket.java | December26/CmdChat | 7efaaa66d5e6681f1240aa2fae457e35b74f3771 | [
"MIT"
] | null | null | null | 17.208333 | 61 | 0.750605 | 9,795 | package protocol.response;
import lombok.Data;
import protocol.Packet;
import java.util.List;
import static protocol.command.Command.CREATE_GROUP_RESPONSE;
@Data
public class CreateGroupResponsePacket extends Packet {
private boolean success;
private String groupId;
private List<String> userNameList;
@Override
public Byte getCommand() {
return CREATE_GROUP_RESPONSE;
}
}
|
3e16fe895df7f64e568e87063ed8ebff530f781c | 2,806 | java | Java | syhthems-db/src/main/java/top/sunriseydy/syhthems/db/service/impl/MenuServiceImpl.java | ASDwood/syhthems-platform | 96f4c5801943f802178424bf7f300151535d0c21 | [
"MIT"
] | 126 | 2019-06-23T08:14:33.000Z | 2022-03-11T06:41:25.000Z | syhthems-db/src/main/java/top/sunriseydy/syhthems/db/service/impl/MenuServiceImpl.java | ASDwood/syhthems-platform | 96f4c5801943f802178424bf7f300151535d0c21 | [
"MIT"
] | 5 | 2019-07-24T03:02:49.000Z | 2020-05-25T03:38:45.000Z | syhthems-db/src/main/java/top/sunriseydy/syhthems/db/service/impl/MenuServiceImpl.java | ASDwood/syhthems-platform | 96f4c5801943f802178424bf7f300151535d0c21 | [
"MIT"
] | 49 | 2019-06-24T12:23:55.000Z | 2022-03-07T09:50:48.000Z | 38.972222 | 101 | 0.738774 | 9,796 | package top.sunriseydy.syhthems.db.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import top.sunriseydy.syhthems.db.mapper.RoleMenuMapper;
import top.sunriseydy.syhthems.db.model.Menu;
import top.sunriseydy.syhthems.db.model.Role;
import top.sunriseydy.syhthems.db.model.RoleMenu;
import top.sunriseydy.syhthems.db.service.MenuService;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author SunriseYDY
* @date 2019-03-26 17:23
*/
@Service
@CacheConfig(cacheNames = "MenuServiceImpl")
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {
@Autowired
RoleMenuMapper roleMenuMapper;
@Override
public List<Menu> selectByRoles(List<Role> roles) {
Assert.notEmpty(roles, "用户角色不能为空");
Example roleMenuExample = new Example(RoleMenu.class);
roleMenuExample.createCriteria().andIn(RoleMenu.ROLE_ID,
roles.stream().map(Role::getRoleId).collect(Collectors.toList()));
List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(roleMenuExample);
if (CollectionUtils.isEmpty(roleMenus)) {
return null;
}
Example menuExample = new Example(Menu.class);
menuExample.createCriteria().andIn(Menu.MENU_ID,
roleMenus.stream().map(RoleMenu::getMenuId).distinct().collect(Collectors.toList()));
return super.selectByExample(menuExample);
}
@Override
public Menu selectByMenuCode(String menuCode) {
Assert.hasText(menuCode, "菜单代码不能为空");
Example menuExample = new Example(Menu.class);
menuExample.createCriteria().andEqualTo(Menu.MENU_CODE, menuCode);
return super.selectOneByExample(menuExample);
}
@Override
public List<Menu> selectByParentId(Long parentId) {
Assert.notNull(parentId, "父菜单id不能为空");
Example menuExample = new Example(Menu.class);
menuExample.createCriteria().andEqualTo(Menu.PARENT_ID, parentId);
return super.selectByExample(menuExample);
}
@Override
public List<Menu> selectByPermission(String permission) {
Assert.hasText(permission, "权限不能为空");
Example menuExample = new Example(Menu.class);
menuExample.createCriteria().andEqualTo(Menu.PERMISSION, permission);
return super.selectByExample(menuExample);
}
}
|
3e16fe96aa8a53208c81a30025cacba1bdaf740c | 1,817 | java | Java | tendril-domain/src/main/java/edu/colorado/cs/cirrus/domain/model/Result.java | tendril-cirrus/4308Cirrus | aa0147d3466f554f3e1ea1cc5a3696d01e713aa1 | [
"Apache-2.0"
] | 1 | 2015-10-28T23:14:44.000Z | 2015-10-28T23:14:44.000Z | tendril-domain/src/main/java/edu/colorado/cs/cirrus/domain/model/Result.java | tendril-cirrus/4308Cirrus | aa0147d3466f554f3e1ea1cc5a3696d01e713aa1 | [
"Apache-2.0"
] | null | null | null | tendril-domain/src/main/java/edu/colorado/cs/cirrus/domain/model/Result.java | tendril-cirrus/4308Cirrus | aa0147d3466f554f3e1ea1cc5a3696d01e713aa1 | [
"Apache-2.0"
] | null | null | null | 20.188889 | 99 | 0.733627 | 9,797 | package edu.colorado.cs.cirrus.domain.model;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Order;
@Order(elements={"setpoint", "mode", "temperatureScale", "currentTemp", "activeLoadControlEvent"})
public class Result {
public Result(){}
@Attribute(required=false)
private String type;
@Element(required=false)
private String setpoint;
@Element(required=false)
private String mode;
@Element(required=false)
private String temperatureScale;
@Element(required=false)
private String currentTemp;
@Element(required=false)
private boolean activeLoadControlEvent;
public String getSetpoint() {
return setpoint;
}
public void setSetpoint(String setpoint) {
this.setpoint = setpoint;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getTemperatureScale() {
return temperatureScale;
}
public void setTemperatureScale(String temperatureScale) {
this.temperatureScale = temperatureScale;
}
public String getCurrentTemp() {
return currentTemp;
}
public void setCurrentTemp(String currentTemp) {
this.currentTemp = currentTemp;
}
public boolean isActiveLoadControlEvent() {
return activeLoadControlEvent;
}
public void setActiveLoadControlEvent(boolean activeLoadControlEvent) {
this.activeLoadControlEvent = activeLoadControlEvent;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Result [type=" + type + ", setpoint=" + setpoint + ", mode="
+ mode + ", temperatureScale=" + temperatureScale
+ ", currentTemp=" + currentTemp + ", activeLoadControlEvent="
+ activeLoadControlEvent + "]";
}
}
|
3e16ff32ec3f286801436e7b32f9df48c66322b8 | 37 | java | Java | java/java-tests/testData/inspection/localCanBeFinal/Record.java | msoxzw/intellij-community | b8452521640cca4cd379a0a0335341f362bc09a9 | [
"Apache-2.0"
] | null | null | null | java/java-tests/testData/inspection/localCanBeFinal/Record.java | msoxzw/intellij-community | b8452521640cca4cd379a0a0335341f362bc09a9 | [
"Apache-2.0"
] | null | null | null | java/java-tests/testData/inspection/localCanBeFinal/Record.java | msoxzw/intellij-community | b8452521640cca4cd379a0a0335341f362bc09a9 | [
"Apache-2.0"
] | null | null | null | 7.4 | 20 | 0.405405 | 9,798 | record A(String s) {
A {
}
} |
3e16ff73f99d202469088c20cd6cf8190009bd0e | 831 | java | Java | src/main/java/instantcoffee/cinemaxx/repo/MovieRepo.java | juaninicolai/CinemaXX | ba8607900f644e59563066b20ba95151b72c35c8 | [
"MIT"
] | null | null | null | src/main/java/instantcoffee/cinemaxx/repo/MovieRepo.java | juaninicolai/CinemaXX | ba8607900f644e59563066b20ba95151b72c35c8 | [
"MIT"
] | null | null | null | src/main/java/instantcoffee/cinemaxx/repo/MovieRepo.java | juaninicolai/CinemaXX | ba8607900f644e59563066b20ba95151b72c35c8 | [
"MIT"
] | 2 | 2022-02-12T11:27:42.000Z | 2022-02-15T22:48:34.000Z | 34.625 | 95 | 0.753309 | 9,799 | package instantcoffee.cinemaxx.repo;
import instantcoffee.cinemaxx.entities.Movie;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.List;
@Repository
public interface MovieRepo extends JpaRepository<Movie,Integer> {
@RestResource(
path = "getAllByRange",
rel = "getAllByRange")
@Query("SELECT m FROM Movie m WHERE m.startDate <= :endRange and m.endDate >= :startRange")
List<Movie> getAllByRange(
@Param("startRange") LocalDate startRange,
@Param("endRange") LocalDate endRange);
} |
3e16ffcc8932c049bf5465a1e4e54e888dbcab0a | 732 | java | Java | src/main/java/graphics/Spritesheet.java | guassmith/Towny | 49f604a50546921fcb8dbef6f335e5782b875ad7 | [
"MIT"
] | null | null | null | src/main/java/graphics/Spritesheet.java | guassmith/Towny | 49f604a50546921fcb8dbef6f335e5782b875ad7 | [
"MIT"
] | null | null | null | src/main/java/graphics/Spritesheet.java | guassmith/Towny | 49f604a50546921fcb8dbef6f335e5782b875ad7 | [
"MIT"
] | null | null | null | 20.333333 | 55 | 0.729508 | 9,800 | package graphics;
import graphics.opengl.OpenGLUtils;
import util.TextureInfo;
import java.nio.ByteBuffer;
//picture with all the sprites in it
public class Spritesheet {
private final int id; // OpenGL texture id
private final int width; // width of the spritesheet
private final int height; // height of the spritesheet
private final ByteBuffer buffer;
public Spritesheet(String path) {
TextureInfo img = OpenGLUtils.loadTexture(path);
this.id = img.id;
this.width = img.width;
this.height = img.height;
this.buffer = img.buffer;
}
public int getId() {return id;}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public ByteBuffer getBuffer() {return buffer;}
}
|
3e17006799b85c09595c0409b1450cf5cec959fb | 1,968 | java | Java | stabilizer/src/main/java/com/hazelcast/stabilizer/communicator/Communicator.java | peter-lawrey/hazelcast-stabilizer | c7362648c38a5bed2ea629506af7de03b6114657 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:54:09.000Z | 2020-02-28T02:54:09.000Z | stabilizer/src/main/java/com/hazelcast/stabilizer/communicator/Communicator.java | peter-lawrey/hazelcast-stabilizer | c7362648c38a5bed2ea629506af7de03b6114657 | [
"Apache-2.0"
] | null | null | null | stabilizer/src/main/java/com/hazelcast/stabilizer/communicator/Communicator.java | peter-lawrey/hazelcast-stabilizer | c7362648c38a5bed2ea629506af7de03b6114657 | [
"Apache-2.0"
] | null | null | null | 33.931034 | 95 | 0.716463 | 9,801 | package com.hazelcast.stabilizer.communicator;
import com.hazelcast.stabilizer.Utils;
import com.hazelcast.stabilizer.common.AgentAddress;
import com.hazelcast.stabilizer.common.AgentsFile;
import com.hazelcast.stabilizer.common.messaging.Message;
import com.hazelcast.stabilizer.common.messaging.MessageAddress;
import com.hazelcast.stabilizer.common.messaging.UseAllMemoryMessage;
import com.hazelcast.stabilizer.coordinator.remoting.AgentsClient;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.hazelcast.stabilizer.Utils.getVersion;
import static java.lang.String.format;
public class Communicator {
private final static Logger log = Logger.getLogger(Communicator.class.getName());
private final static String STABILIZER_HOME = Utils.getStablizerHome().getAbsolutePath();
public File agentsFile;
protected AgentsClient agentsClient;
public Message message;
public static void main(String[] args) throws IOException {
log.info("Stabilizer Communicator");
log.info(format("Version: %s", getVersion()));
log.info(format("STABILIZER_HOME: %s", STABILIZER_HOME));
Communicator communicator = new Communicator();
CommunicatorCli cli = new CommunicatorCli(communicator);
cli.init(args);
log.info(format("Loading agents file: %s", communicator.agentsFile.getAbsolutePath()));
try {
communicator.run();
System.exit(0);
} catch (Exception e) {
log.error("Failed to communicate", e);
System.exit(1);
}
}
private void run() throws Exception {
initAgents();
agentsClient.sendMessage(message);
}
private void initAgents() throws Exception {
List<AgentAddress> agentAddresses = AgentsFile.load(agentsFile);
agentsClient = new AgentsClient(agentAddresses);
agentsClient.start();
}
}
|
3e1700f1ae283520a1789a8228b8ba943ee568e3 | 1,528 | java | Java | fop-core/src/main/java/org/apache/fop/render/txt/border/DottedBorderElement.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 40 | 2019-10-15T06:00:14.000Z | 2022-03-30T05:17:34.000Z | fop-core/src/main/java/org/apache/fop/render/txt/border/DottedBorderElement.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 6 | 2019-10-07T16:33:08.000Z | 2021-12-11T09:00:42.000Z | fop-core/src/main/java/org/apache/fop/render/txt/border/DottedBorderElement.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 44 | 2019-11-13T04:52:48.000Z | 2022-03-08T10:33:46.000Z | 32.510638 | 77 | 0.713351 | 9,803 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.render.txt.border;
/**
* This class is responsible for managing of dotted border elements.
*/
public class DottedBorderElement extends AbstractBorderElement {
private static final char MIDDLE_DOT = '\u00B7';
/**
* Merges dotted border element with another border element. Here merging
* is quite simple: returning <code>this</code> without any comparing.
*
* @param e instance of AbstractBorderElement
* @return instance of DottedBorderElement
*/
public AbstractBorderElement merge(AbstractBorderElement e) {
return this;
}
/**
* {@inheritDoc}
*/
public char convert2Char() {
return MIDDLE_DOT;
}
}
|
3e17029abcf66c07f9f379c1bfc920a9e9702da5 | 2,177 | java | Java | app/src/main/java/com/example/user/qrcode/ScanQRActivity.java | AlhaadiDev/QrCodeScanner-Generator | 826a894f3de38d63ae3fae4a24c1f073ecd07c94 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/user/qrcode/ScanQRActivity.java | AlhaadiDev/QrCodeScanner-Generator | 826a894f3de38d63ae3fae4a24c1f073ecd07c94 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/user/qrcode/ScanQRActivity.java | AlhaadiDev/QrCodeScanner-Generator | 826a894f3de38d63ae3fae4a24c1f073ecd07c94 | [
"Apache-2.0"
] | null | null | null | 33.492308 | 98 | 0.682131 | 9,804 | package com.example.user.qrcode;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;
public class ScanQRActivity extends AppCompatActivity {
Button btnScan;
TextView txtDesc;
String QRResult = "";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
btnScan = findViewById(R.id.btn_scan);
txtDesc = findViewById(R.id.txt_desc);
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scanNow();
}
});
}
private void scanNow() {
IntentIntegrator integrator = new IntentIntegrator(ScanQRActivity.this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
integrator.setPrompt("Scanning");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.setOrientationLocked(true);
integrator.setCaptureActivity(CaptureActivityPotrait.class);
integrator.initiateScan();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
} else {
QRResult = result.getContents();
txtDesc.setText(QRResult);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
3e1703863b3ca322408f8b3bb40589b2b9ff31af | 1,660 | java | Java | src/main/java/de/stklcode/jvault/connector/exception/InvalidRequestException.java | stklcode/jvaultconnector | 75561a0540715a241df1c2d9d04c2626f0270bb3 | [
"Apache-2.0"
] | 1 | 2017-04-03T02:37:42.000Z | 2017-04-03T02:37:42.000Z | src/main/java/de/stklcode/jvault/connector/exception/InvalidRequestException.java | stklcode/jvaultconnector | 75561a0540715a241df1c2d9d04c2626f0270bb3 | [
"Apache-2.0"
] | 43 | 2016-09-27T10:05:24.000Z | 2022-03-06T17:25:09.000Z | src/main/java/de/stklcode/jvault/connector/exception/InvalidRequestException.java | stklcode/jvaultconnector | 75561a0540715a241df1c2d9d04c2626f0270bb3 | [
"Apache-2.0"
] | null | null | null | 27.666667 | 81 | 0.683735 | 9,805 | /*
* Copyright 2016-2021 Stefan Kalscheuer
*
* 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 de.stklcode.jvault.connector.exception;
/**
* Exception thrown when trying to send malformed request.
*
* @author Stefan Kalscheuer
* @since 0.1
*/
public class InvalidRequestException extends VaultConnectorException {
/**
* Constructs a new empty exception.
*/
public InvalidRequestException() {
}
/**
* Constructs a new exception with the specified detail message.
*
* @param message the detail message
*/
public InvalidRequestException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause the cause
*/
public InvalidRequestException(final Throwable cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message the detail message
* @param cause the cause
*/
public InvalidRequestException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
3e17038fb2840d07a5a688291fb1ce9908ee1114 | 236 | java | Java | binders/difido-testng/src/test/java/il/co/topq/difido/AbstractTestCase.java | siklu/difido-reports | 62b1fa91e36ad1c5640f81814efa2c257a1e059d | [
"Apache-2.0"
] | 42 | 2016-05-30T07:00:31.000Z | 2021-08-08T21:21:37.000Z | binders/difido-testng/src/test/java/il/co/topq/difido/AbstractTestCase.java | siklu/difido-reports | 62b1fa91e36ad1c5640f81814efa2c257a1e059d | [
"Apache-2.0"
] | 165 | 2016-06-02T15:48:03.000Z | 2022-03-30T06:11:34.000Z | binders/difido-testng/src/test/java/il/co/topq/difido/AbstractTestCase.java | siklu/difido-reports | 62b1fa91e36ad1c5640f81814efa2c257a1e059d | [
"Apache-2.0"
] | 35 | 2016-06-06T04:24:50.000Z | 2022-03-16T15:57:59.000Z | 21.454545 | 65 | 0.809322 | 9,806 | package il.co.topq.difido;
import org.testng.annotations.Listeners;
@Listeners(il.co.topq.difido.ReportManagerHook.class)
public abstract class AbstractTestCase {
protected ReportDispatcher report = ReportManager.getInstance();
}
|
3e17058192f7140c6ae957030b1d3260047fbf74 | 1,402 | java | Java | engine/src/main/java/org/camunda/bpm/engine/impl/cmd/RemoveTaskVariablesCmd.java | meyerdan/camunda-bpm-platform | 4f2ff13fb28937d625079f4663534702b8e200e1 | [
"Apache-2.0"
] | 1 | 2022-02-09T03:34:49.000Z | 2022-02-09T03:34:49.000Z | engine/src/main/java/org/camunda/bpm/engine/impl/cmd/RemoveTaskVariablesCmd.java | ivyy/camunda-bpm-platform | 03a0269dd9e51d22d687daa9befa88c45b998413 | [
"Apache-2.0"
] | null | null | null | engine/src/main/java/org/camunda/bpm/engine/impl/cmd/RemoveTaskVariablesCmd.java | ivyy/camunda-bpm-platform | 03a0269dd9e51d22d687daa9befa88c45b998413 | [
"Apache-2.0"
] | null | null | null | 26.961538 | 99 | 0.721826 | 9,807 | package org.camunda.bpm.engine.impl.cmd;
import java.io.Serializable;
import java.util.Collection;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
/**
* @author roman.smirnov
*/
public class RemoveTaskVariablesCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
private final String taskId;
private final Collection<String> variableNames;
private final boolean isLocal;
public RemoveTaskVariablesCmd(String taskId, Collection<String> variableNames, boolean isLocal) {
this.taskId = taskId;
this.variableNames = variableNames;
this.isLocal = isLocal;
}
public Void execute(CommandContext commandContext) {
if(taskId == null) {
throw new ProcessEngineException("taskId is null");
}
TaskEntity task = Context
.getCommandContext()
.getTaskManager()
.findTaskById(taskId);
if (task == null) {
throw new ProcessEngineException("task "+taskId+" doesn't exist");
}
if (isLocal) {
task.removeVariablesLocal(variableNames);
} else {
task.removeVariables(variableNames);
}
return null;
}
}
|
3e1705b75c43af3253481343dd5a8163c01669d0 | 1,506 | java | Java | backend/src/main/java/hr/trio/realestatetracker/service/impl/UserServiceImpl.java | vpericki/ReTracker-seminarski-rad | ead0921342fc35e5dcfe709b1c1b36a86e57ae1f | [
"MIT"
] | null | null | null | backend/src/main/java/hr/trio/realestatetracker/service/impl/UserServiceImpl.java | vpericki/ReTracker-seminarski-rad | ead0921342fc35e5dcfe709b1c1b36a86e57ae1f | [
"MIT"
] | null | null | null | backend/src/main/java/hr/trio/realestatetracker/service/impl/UserServiceImpl.java | vpericki/ReTracker-seminarski-rad | ead0921342fc35e5dcfe709b1c1b36a86e57ae1f | [
"MIT"
] | null | null | null | 33.466667 | 109 | 0.747012 | 9,808 | package hr.trio.realestatetracker.service.impl;
import hr.trio.realestatetracker.converter.UserConverter;
import hr.trio.realestatetracker.dto.UserDto;
import hr.trio.realestatetracker.exception.NotFoundException;
import hr.trio.realestatetracker.repository.UserRepository;
import hr.trio.realestatetracker.service.CurrentUserService;
import hr.trio.realestatetracker.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final CurrentUserService currentUserService;
private final UserConverter userConverter;
@Override
public UserDto getUserById(final Long userId) {
if (currentUserService.isLoggedIn() && currentUserService.getLoggedInUser().getId().equals(userId)) {
return getUserDto(userId);
}
return removePrivateInfo(getUserDto(userId));
}
private UserDto getUserDto(final Long userId) {
return userConverter.convert(userRepository.findById(userId)
.orElseThrow(() -> new NotFoundException("User with ID " + userId + " not found.")));
}
private UserDto removePrivateInfo(final UserDto userDto) {
userDto.setId(null);
userDto.setFirstName(null);
userDto.setLastName(null);
userDto.setDateOfBirth(null);
userDto.setRoleDto(null);
return userDto;
}
}
|
3e17061b20cb40b44d3b59b5b002a5a8b65f2588 | 972 | java | Java | ses-app/ses-mobile-rps/src/main/java/com/redescooter/ses/mobile/rps/vo/productwaitinwh/ProductWaitInWhIdItemEnter.java | moutainhigh/ses-server | e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5 | [
"MIT"
] | null | null | null | ses-app/ses-mobile-rps/src/main/java/com/redescooter/ses/mobile/rps/vo/productwaitinwh/ProductWaitInWhIdItemEnter.java | moutainhigh/ses-server | e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5 | [
"MIT"
] | null | null | null | ses-app/ses-mobile-rps/src/main/java/com/redescooter/ses/mobile/rps/vo/productwaitinwh/ProductWaitInWhIdItemEnter.java | moutainhigh/ses-server | e1ee6ac34499950ef4b1b97efa0aaf4c4fec67c5 | [
"MIT"
] | 2 | 2021-08-31T07:59:28.000Z | 2021-10-16T10:55:44.000Z | 23.707317 | 62 | 0.752058 | 9,809 | package com.redescooter.ses.mobile.rps.vo.productwaitinwh;
import com.redescooter.ses.api.common.vo.base.GeneralEnter;
import com.redescooter.ses.api.common.vo.base.PageEnter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
/**
* @ClassNameProWaitInWHIdEnter
* @Description
* @Author kyle
* @Date2020/4/18 10:27
* @Version V1.0
**/
@ApiModel(value = "整车部件入库项操作入参", description = "整车部件入库项操作入参")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = true)
public class ProductWaitInWhIdItemEnter extends GeneralEnter {
@ApiModelProperty(value = "子单id")
private Long id;
@ApiModelProperty(value = "单据类型")
private String sourceType;
@ApiModelProperty(value = "本次应该入库数量")
private Integer shouldInWhNum;
@ApiModelProperty(value = "本次入库数量")
private Integer inWhNum;
@ApiModelProperty(value = "产品序列号")
private String productSerialNum;
}
|
3e170685984848eb94572949e1c63e9186675bec | 261 | java | Java | src/main/java/roger/training/util/validation/Customer.java | RogerRocco/rest-spring-boot | e5700994d31699a0cf178b506b223d53162912eb | [
"MIT"
] | null | null | null | src/main/java/roger/training/util/validation/Customer.java | RogerRocco/rest-spring-boot | e5700994d31699a0cf178b506b223d53162912eb | [
"MIT"
] | null | null | null | src/main/java/roger/training/util/validation/Customer.java | RogerRocco/rest-spring-boot | e5700994d31699a0cf178b506b223d53162912eb | [
"MIT"
] | null | null | null | 17.4 | 52 | 0.716475 | 9,810 | package roger.training.util.validation;
public class Customer extends DataValidation {
public static boolean isValid(String customerStr) {
boolean valid = false;
if (customerStr.equals(""))
valid = false;
else
valid = true;
return valid;
}
}
|
3e1706cc925578ecc9aed8a53d0ffc8b1dfbca0f | 1,620 | java | Java | src/main/java/net/maritimeconnectivity/identityregistry/exception/McpExceptionResolver.java | MaritimeCloud/identity-registry | 27f7f90973e0e858146a6d1b84894bd01e692390 | [
"Apache-2.0"
] | 9 | 2017-12-22T05:59:17.000Z | 2020-11-30T15:16:58.000Z | src/main/java/net/maritimeconnectivity/identityregistry/exception/McpExceptionResolver.java | MaritimeCloud/identity-registry | 27f7f90973e0e858146a6d1b84894bd01e692390 | [
"Apache-2.0"
] | 5 | 2018-04-09T13:02:32.000Z | 2020-05-14T08:05:10.000Z | src/main/java/net/maritimeconnectivity/identityregistry/exception/McpExceptionResolver.java | MaritimeCloud/identity-registry | 27f7f90973e0e858146a6d1b84894bd01e692390 | [
"Apache-2.0"
] | 7 | 2018-03-21T06:58:43.000Z | 2021-01-08T11:59:32.000Z | 43.783784 | 137 | 0.770988 | 9,811 | /*
* Copyright 2017 Danish Maritime Authority.
*
* 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.maritimeconnectivity.identityregistry.exception;
import net.maritimeconnectivity.identityregistry.model.data.ExceptionModel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class McpExceptionResolver {
@ExceptionHandler(McpBasicRestException.class)
public ResponseEntity<ExceptionModel> processRestError(McpBasicRestException ex) {
// mimics the standard spring error structure on exceptions
ExceptionModel exp = new ExceptionModel(ex.getTimestamp(), ex.getStatus().value(), ex.getError(), ex.getErrorMessage(), ex.path);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<>(exp, httpHeaders, ex.getStatus());
}
}
|
3e1707688551dfe2a1ddf957ea2ad9dbf32f40fb | 11,283 | java | Java | src/main/java/hu/ibello/search/SearchTool.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | 1 | 2021-04-21T15:06:43.000Z | 2021-04-21T15:06:43.000Z | src/main/java/hu/ibello/search/SearchTool.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | null | null | null | src/main/java/hu/ibello/search/SearchTool.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | null | null | null | 41.481618 | 113 | 0.702118 | 9,812 | /*
* Ark-Sys Kft. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package hu.ibello.search;
import hu.ibello.elements.WebElement;
import hu.ibello.elements.WebElements;
/**
* <p>
* Interface for searching elements on a page.
* It offers a fluent interface for element search. Examples:
* </p>
* <p>Search a single element:</p>
* <pre>
* SearchTool find = ...;
* WebElement element = find.using(By.LABEL, "Field #${0}:", 1).first();
* </pre>
* <p>Search multiple elements (below a specific one):</p>
* <pre>
* WebElement currentRow = ...;
* SearchTool find = ...;
* WebElements element = find.using(By.TAG_NAME, "tr").below(currentRow).all();
* </pre>
* <p>About <em>ibello</em> search engine see {@link hu.ibello.search}.</p>
* @author Kornél Simon
*/
public interface SearchTool {
/**
* <p>
* Sets the main search conditions for the element search.
* </p>
* <p>
* The <code>by</code> argument specifies the main search algorithm. It is an enum constant of {@link By}.
* </p>
* <p>
* The meaning of <code>pattern</code> argument depends on the value of <code>by</code>. For more information,
* see enum constants of {@link By}.
* </p>
* <p>
* The <code>parameters</code> is a vararg. It specifies parameters in the <code>pattern</code> argument.
* If <code>pattern</code> contain parameter substitution markers then the method will substitute
* the parameters into those places. A parameter substitution marker is a 0-based index surrounded by
* <code>${</code> and <code>}</code>. For example, if <code>pattern</code> is <code>"${0}-${1}"</code>,
* then the method will replace <code>${0}</code> with the first parameter, and <code>${1}</code>
* with the second parameter. If the parameters are <code>"a"</code> and <code>1</code>, then the
* result pattern will be <code>"a-1"</code>.
* </p>
* @param by search algorithm
* @param pattern search pattern
* @param parameters substitute parameters of <code>pattern</code>
* @return this {@link SearchTool} instance
* @see Find
*/
public SearchTool using(By by, String pattern, Object ... parameters);
/**
* <p>
* Sets the main search conditions for the element search.
* </p>
* <p>
* The search algorithm of the anchor is {@link By#CSS_SELECTOR}. The <code>pattern</code> argument
* should be a CSS selector.
* </p>
* <p>
* The <code>parameters</code> is a vararg. It specifies parameters in the <code>pattern</code> argument.
* If <code>pattern</code> contain parameter substitution markers then the method will substitute
* the parameters into those places. A parameter substitution marker is a 0-based index surrounded by
* <code>${</code> and <code>}</code>. For example, if <code>pattern</code> is <code>"#${0}-${1}"</code>,
* then the method will replace <code>${0}</code> with the first parameter, and <code>${1}</code>
* with the second parameter. If the parameters are <code>"a"</code> and <code>1</code>, then the
* result pattern will be <code>"#a-1"</code>.
* </p>
* @param pattern search pattern
* @param parameters substitute parameters of <code>pattern</code>
* @return this {@link SearchTool} instance
* @see SearchTool#using(By, String, Object...)
* @see Find
*/
public default SearchTool using(String pattern, Object ... parameters) {
return using(By.CSS_SELECTOR, pattern, parameters);
}
/**
* Modifies the element search so the desired element should be in the same row as the anchor element.
* It means that the horizontal center line of the anchor should fit into the boundaries of the desired
* element.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#ROW
*/
public SearchTool inRowOf(WebElement anchor);
/**
* Modifies the element search so the desired element should be in the same column as the anchor element.
* It means that the vertical center line of the anchor should fit into the boundaries of the desired
* element.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#COLUMN
*/
public SearchTool inColumnOf(WebElement anchor);
/**
* Modifies the element search so the desired element should be left from the anchor element.
* It means that the x coordinate of the desired element's right edge if less than or equal to the x coordinate
* of the anchor element's left edge.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#LEFT_FROM
*/
public SearchTool leftFrom(WebElement anchor);
/**
* Modifies the element search so the desired element should be right from the anchor element.
* It means that the x coordinate of the desired element's left edge if greater than or equal to the x
* coordinate of the anchor element's right edge.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#RIGHT_FROM
*/
public SearchTool rightFrom(WebElement anchor);
/**
* Modifies the element search so the desired element should be above the anchor element.
* It means that the bottom y coordinate of the desired element is less than or equal to the top y coordinate
* of the anchor element.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#ABOVE
*/
public SearchTool above(WebElement anchor);
/**
* Modifies the element search so the desired element should be below the anchor element.
* It means that the top y coordinate of the desired element is greater than or equal to the bottom y coordinate
* of the anchor element.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
* @see Position
* @see PositionType#BELOW
*/
public SearchTool below(WebElement anchor);
/**
* Modifies the element search so the desired element should be the ancestor of the anchor element.
* The anchor element is specified by it's search conditions.
* <p>
* The <code>by</code> argument specifies the search algorithm. It is an enum constant of {@link By}.
* </p>
* <p>
* The meaning of <code>pattern</code> argument depends on the value of <code>by</code>. For more information,
* see enum constants of {@link By}.
* </p>
* <p>
* The <code>parameters</code> is a vararg. It specifies parameters in the <code>pattern</code> argument.
* If <code>pattern</code> contain parameter substitution markers then the method will substitute
* the parameters into those places. A parameter substitution marker is a 0-based index surrounded by
* <code>${</code> and <code>}</code>. For example, if <code>pattern</code> is <code>"${0}-${1}"</code>,
* then the method will replace <code>${0}</code> with the first parameter, and <code>${1}</code>
* with the second parameter. If the parameters are <code>"a"</code> and <code>1</code>, then the
* result pattern will be <code>"a-1"</code>.
* </p>
* @param by search algorithm of anchor element
* @param pattern search pattern of anchor element
* @param parameters search parameters of anchor element
* @return this {@link SearchTool} instance
* @see Relation
* @see RelationType#ANCESTOR_OF
*/
public SearchTool asAncestorOf(By by, String pattern, Object ... parameters);
/**
* Modifies the element search so the desired element should be the ancestor of the anchor element.
* The anchor element is specified by it's search conditions.
* <p>
* The search algorithm of the anchor is {@link By#CSS_SELECTOR}. The <code>pattern</code> argument
* should be a CSS selector.
* </p>
* <p>
* The <code>parameters</code> is a vararg. It specifies parameters in the <code>pattern</code> argument.
* If <code>pattern</code> contain parameter substitution markers then the method will substitute
* the parameters into those places. A parameter substitution marker is a 0-based index surrounded by
* <code>${</code> and <code>}</code>. For example, if <code>pattern</code> is <code>"#${0}-${1}"</code>,
* then the method will replace <code>${0}</code> with the first parameter, and <code>${1}</code>
* with the second parameter. If the parameters are <code>"a"</code> and <code>1</code>, then the
* result pattern will be <code>"#a-1"</code>.
* </p>
* @param pattern search pattern of anchor element
* @param parameters search parameters of anchor element
* @return this {@link SearchTool} instance
* @see Relation
* @see RelationType#ANCESTOR_OF
*/
public default SearchTool asAncestorOf(String pattern, Object ... parameters) {
return asAncestorOf(By.CSS_SELECTOR, pattern, parameters);
}
/**
* Modifies the element search to capture the nearest elements to the given anchor element.
* @param anchor another element on the page
* @return this {@link SearchTool} instance
*/
public SearchTool nearestTo(WebElement anchor);
/**
* <p>
* Get only the first element on the page which matches the conditions.
* </p>
* <p>
* This method always returns a non-null object, even if the element is not present on the
* page at the time of the search. The returned {@link WebElement} instance can be used for
* different actions and assertions later - there is no need to search with the same arguments
* again.
* </p>
* @return the first element which matches the conditions
*/
public WebElement first();
/**
* <p>
* Get the nth element on the page which matches the conditions. The index of the element should
* be specified with the parameter. It is 0-based, so the index of the first element is 0, the second is 1,
* and so on.
* </p>
* <p>
* This method always returns a non-null object, even if the element is not present on the
* page at the time of the search. The returned {@link WebElement} instance can be used for
* different actions and assertions later - there is no need to search with the same arguments
* again.
* </p>
* @param index 0-based index of the element
* @return the element with the given index
*/
public default WebElement nth(int index) {
return all().get(index);
}
/**
* <p>
* Get all elements on the page that match the conditions.
* </p>
* <p>
* This method always returns a non-null object, even if the elements are not present on the
* page at the time of the search. The returned {@link WebElements} instance can be used for
* different actions and assertions later - there is no need to search with the same arguments
* again.
* </p>
* @return all elements that match the conditions
*/
public WebElements all();
}
|
3e170862d385fc7e60025d28b6cc398ce20d98d1 | 3,603 | java | Java | src/main/java/com/hellonms/platforms/emp_orange/client_swt/page/fault/event/DataTable4Event.java | paul-hyun/emp | 2dd66647c5522cbc59c786d413ed790a1f14f46c | [
"Apache-2.0"
] | 2 | 2020-04-04T04:36:01.000Z | 2022-02-24T00:07:19.000Z | src/main/java/com/hellonms/platforms/emp_orange/client_swt/page/fault/event/DataTable4Event.java | paul-hyun/emp | 2dd66647c5522cbc59c786d413ed790a1f14f46c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hellonms/platforms/emp_orange/client_swt/page/fault/event/DataTable4Event.java | paul-hyun/emp | 2dd66647c5522cbc59c786d413ed790a1f14f46c | [
"Apache-2.0"
] | null | null | null | 22.51875 | 102 | 0.718845 | 9,813 | package com.hellonms.platforms.emp_orange.client_swt.page.fault.event;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import com.hellonms.platforms.emp_core.share.error.EmpException;
import com.hellonms.platforms.emp_core.share.language.UtilLanguage;
import com.hellonms.platforms.emp_onion.client_swt.data.table.DataTableAt;
import com.hellonms.platforms.emp_orange.client_swt.page.network.network_tree.ModelClient4NetworkTree;
import com.hellonms.platforms.emp_orange.client_swt.util.resource.UtilResource4Orange;
import com.hellonms.platforms.emp_orange.share.message.MESSAGE_CODE_ORANGE;
import com.hellonms.platforms.emp_orange.share.model.fault.event.Model4Event;
import com.hellonms.platforms.emp_util.date.UtilDate;
/**
* <p>
* DataTable4Event
* </p>
*
* @since 1.6
* @create 2015. 5. 19.
* @modified 2015. 6. 3.
* @author jungsun
*/
public class DataTable4Event extends DataTableAt {
/**
* 컬럼명 배열
*/
protected String[] COLUMN_NAMES = { UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.SEVERITY), //
UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.GEN_TIME), //
UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.NE), //
UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.LOCATION), //
UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.CAUSE), //
UtilLanguage.getMessage(MESSAGE_CODE_ORANGE.DESCRIPTION), //
};
/**
* 컬럼 너비 배열
*/
protected int[] COLUMN_WIDTHS = { 100, 135, 120, 200, 200, 320 };
/**
* 현재알람 모델 배열
*/
protected Model4Event[] model4Events = {};
@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String getColumnTitle(int column) {
return COLUMN_NAMES[column];
}
@Override
public int getColumnStyle(int column) {
return SWT.NONE;
}
@Override
public int getColumnWidth(int column) {
return COLUMN_WIDTHS[column];
}
@Override
public Object getInput() {
return this;
}
@Override
public Object[] getElements(Object inputElement) {
return model4Events;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
Model4Event events = (Model4Event) element;
switch (columnIndex) {
case 0:
return UtilResource4Orange.getImage(events.getSeverity(), false);
default:
return null;
}
}
@Override
public String getColumnText(Object element, int columnIndex) {
Model4Event event = (Model4Event) element;
switch (columnIndex) {
case 0:
return event.getSeverity().name();
case 1:
return UtilDate.format(event.getGen_time());
case 2:
try {
return ModelClient4NetworkTree.getInstance().getNe(event.getNe_id()).getName();
} catch (EmpException e) {
return "";
}
case 3:
return event.getLocation_display();
case 4:
try {
return event.getEvent_def().getSpecific_problem();
} catch (Exception e) {
return "";
}
case 5:
return event.getDescription();
default:
return event.toString();
}
}
@Override
public Color getForeground(Object element) {
return null;
}
@Override
public Color getBackground(Object element) {
return null;
}
@Override
public void clear() {
this.model4Events = new Model4Event[] {};
}
@Override
public void setDatas(Object... datas) {
if (datas.length == 1 && datas[0] instanceof Model4Event[]) {
setData((Model4Event[]) datas[0]);
refresh();
}
}
/**
* 데이터를 설정합니다.
*
* @param events
* 현재알람 모델 배열
*/
protected void setData(Model4Event[] model4Events) {
this.model4Events = model4Events;
}
@Override
public Model4Event[] getData() {
return model4Events;
}
}
|
3e1708f3ddcd1e7e877153cb055fea295b9e5ea8 | 7,501 | java | Java | src/test/java/com/google/devtools/build/lib/packages/SkylarkSemanticsConsistencyTest.java | timm-gs/bazel | d16012774f97d8a3d0f7732e116dba8ab636a4cb | [
"Apache-2.0"
] | 3 | 2019-09-10T15:23:53.000Z | 2021-11-17T10:58:08.000Z | src/test/java/com/google/devtools/build/lib/packages/SkylarkSemanticsConsistencyTest.java | snnn/bazel | d16012774f97d8a3d0f7732e116dba8ab636a4cb | [
"Apache-2.0"
] | null | null | null | src/test/java/com/google/devtools/build/lib/packages/SkylarkSemanticsConsistencyTest.java | snnn/bazel | d16012774f97d8a3d0f7732e116dba8ab636a4cb | [
"Apache-2.0"
] | 1 | 2022-03-06T10:55:14.000Z | 2022-03-06T10:55:14.000Z | 47.474684 | 100 | 0.738168 | 9,814 | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.skyframe.serialization.testutils.TestUtils;
import com.google.devtools.build.lib.syntax.SkylarkSemantics;
import com.google.devtools.common.options.Options;
import com.google.devtools.common.options.OptionsParser;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for the flow of flags from {@link SkylarkSemanticsOptions} to {@link SkylarkSemantics}, and
* to and from {@code SkylarkSemantics}' serialized representation.
*
* <p>When adding a new option, it is trivial to make a transposition error or a copy/paste error.
* These tests guard against such errors. The following possible bugs are considered:
* <ul>
* <li>If a new option is added to {@code SkylarkSemantics} but not to {@code
* SkylarkSemanticsOptions}, or vice versa, then the programmer will either be unable to
* implement its behavior, or unable to test it from the command line and add user
* documentation. We hope that the programmer notices this on their own.
*
* <li>If {@link SkylarkSemanticsOptions#toSkylarkSemantics} or {@link
* SkylarkSemanticsCodec#deserialize} is not updated to set all fields of {@code
* SkylarkSemantics}, then it will fail immediately because all fields of {@link
* SkylarkSemantics.Builder} are mandatory.
*
* <li>To catch a copy/paste error where the wrong field's data is threaded through {@code
* toSkylarkSemantics()} or {@code deserialize(...)}, we repeatedly generate matching random
* instances of the input and expected output objects.
*
* <li>The {@link #checkDefaultsMatch} test ensures that there is no divergence between the
* default values of the two classes.
*
* <li>There is no test coverage for failing to update the non-generated webpage documentation.
* So don't forget that!
* </ul>
*/
@RunWith(JUnit4.class)
public class SkylarkSemanticsConsistencyTest {
private static final int NUM_RANDOM_TRIALS = 10;
/**
* Checks that a randomly generated {@link SkylarkSemanticsOptions} object can be converted to a
* {@link SkylarkSemantics} object with the same field values.
*/
@Test
public void optionsToSemantics() throws Exception {
for (int i = 0; i < NUM_RANDOM_TRIALS; i++) {
long seed = i;
SkylarkSemanticsOptions options = buildRandomOptions(new Random(seed));
SkylarkSemantics semantics = buildRandomSemantics(new Random(seed));
SkylarkSemantics semanticsFromOptions = options.toSkylarkSemantics();
assertThat(semanticsFromOptions).isEqualTo(semantics);
}
}
/*
* Checks that a randomly generated {@link SkylarkSemantics} object can be serialized and
* deserialized to an equivalent object.
*/
@Test
public void serializationRoundTrip() throws Exception {
SkylarkSemanticsCodec codec = new SkylarkSemanticsCodec();
for (int i = 0; i < NUM_RANDOM_TRIALS; i++) {
SkylarkSemantics semantics = buildRandomSemantics(new Random(i));
SkylarkSemantics deserialized =
TestUtils.fromBytes(codec, TestUtils.toBytes(codec, semantics));
assertThat(deserialized).isEqualTo(semantics);
}
}
@Test
public void checkDefaultsMatch() {
SkylarkSemanticsOptions defaultOptions = Options.getDefaults(SkylarkSemanticsOptions.class);
SkylarkSemantics defaultSemantics = SkylarkSemantics.DEFAULT_SEMANTICS;
SkylarkSemantics semanticsFromOptions = defaultOptions.toSkylarkSemantics();
assertThat(semanticsFromOptions).isEqualTo(defaultSemantics);
}
/**
* Constructs a {@link SkylarkSemanticsOptions} object with random fields. Must access {@code
* rand} using the same sequence of operations (for the same fields) as {@link
* #buildRandomSemantics}.
*/
private static SkylarkSemanticsOptions buildRandomOptions(Random rand) throws Exception {
return parseOptions(
// <== Add new options here in alphabetic order ==>
"--incompatible_bzl_disallow_load_after_statement=" + rand.nextBoolean(),
"--incompatible_checked_arithmetic=" + rand.nextBoolean(),
"--incompatible_comprehension_variables_do_not_leak=" + rand.nextBoolean(),
"--incompatible_depset_is_not_iterable=" + rand.nextBoolean(),
"--incompatible_dict_literal_has_no_duplicates=" + rand.nextBoolean(),
"--incompatible_disallow_dict_plus=" + rand.nextBoolean(),
"--incompatible_disallow_keyword_only_args=" + rand.nextBoolean(),
"--incompatible_disallow_set_constructor=" + rand.nextBoolean(),
"--incompatible_disallow_toplevel_if_statement=" + rand.nextBoolean(),
"--incompatible_list_plus_equals_inplace=" + rand.nextBoolean(),
"--incompatible_load_argument_is_label=" + rand.nextBoolean(),
"--incompatible_new_actions_api=" + rand.nextBoolean(),
"--incompatible_string_is_not_iterable=" + rand.nextBoolean(),
"--internal_do_not_export_builtins=" + rand.nextBoolean(),
"--internal_skylark_flag_test_canary=" + rand.nextBoolean()
);
}
/**
* Constructs a {@link SkylarkSemantics} object with random fields. Must access {@code rand} using
* the same sequence of operations (for the same fields) as {@link #buildRandomOptions}.
*/
private static SkylarkSemantics buildRandomSemantics(Random rand) {
return SkylarkSemantics.builder()
// <== Add new options here in alphabetic order ==>
.incompatibleBzlDisallowLoadAfterStatement(rand.nextBoolean())
.incompatibleCheckedArithmetic(rand.nextBoolean())
.incompatibleComprehensionVariablesDoNotLeak(rand.nextBoolean())
.incompatibleDepsetIsNotIterable(rand.nextBoolean())
.incompatibleDictLiteralHasNoDuplicates(rand.nextBoolean())
.incompatibleDisallowDictPlus(rand.nextBoolean())
.incompatibleDisallowKeywordOnlyArgs(rand.nextBoolean())
.incompatibleDisallowSetConstructor(rand.nextBoolean())
.incompatibleDisallowToplevelIfStatement(rand.nextBoolean())
.incompatibleListPlusEqualsInplace(rand.nextBoolean())
.incompatibleLoadArgumentIsLabel(rand.nextBoolean())
.incompatibleNewActionsApi(rand.nextBoolean())
.incompatibleStringIsNotIterable(rand.nextBoolean())
.internalDoNotExportBuiltins(rand.nextBoolean())
.internalSkylarkFlagTestCanary(rand.nextBoolean())
.build();
}
private static SkylarkSemanticsOptions parseOptions(String... args) throws Exception {
OptionsParser parser = OptionsParser.newOptionsParser(SkylarkSemanticsOptions.class);
parser.setAllowResidue(false);
parser.parse(Arrays.asList(args));
return parser.getOptions(SkylarkSemanticsOptions.class);
}
}
|
3e1709c923a56ca7ac8dc066d5b7103ac22f29d7 | 88 | java | Java | CleanCode/4-tdd-example/src/main/java/tddexample/FlightNotFoundException.java | jsvegam/solid | 36cbb4a37051b1178ef01d9319bed92220b296e1 | [
"MIT"
] | 3 | 2021-11-20T11:16:40.000Z | 2022-03-19T22:56:39.000Z | CleanCode/4-tdd-example/src/main/java/tddexample/FlightNotFoundException.java | jsvegam/solid | 36cbb4a37051b1178ef01d9319bed92220b296e1 | [
"MIT"
] | null | null | null | CleanCode/4-tdd-example/src/main/java/tddexample/FlightNotFoundException.java | jsvegam/solid | 36cbb4a37051b1178ef01d9319bed92220b296e1 | [
"MIT"
] | 9 | 2021-03-15T23:54:52.000Z | 2022-03-28T17:35:18.000Z | 14.666667 | 63 | 0.840909 | 9,815 | package tddexample;
public class FlightNotFoundException extends RuntimeException {
}
|
3e1709d1e9b5a7b101f3183adc6c7386577c3d08 | 5,461 | java | Java | vehicle/android/CanDataSender/src/com/example/candatasender/CarLinkData/CanData.java | yk-fujii/Autoware | 470b04b95eee435d2bb529d978d4c91bf57f34b0 | [
"BSD-3-Clause"
] | 64 | 2018-11-19T02:34:05.000Z | 2021-12-27T06:19:48.000Z | vehicle/android/CanDataSender/src/com/example/candatasender/CarLinkData/CanData.java | yk-fujii/Autoware | 470b04b95eee435d2bb529d978d4c91bf57f34b0 | [
"BSD-3-Clause"
] | 1 | 2017-12-06T11:35:14.000Z | 2017-12-06T11:35:14.000Z | vehicle/android/CanDataSender/src/com/example/candatasender/CarLinkData/CanData.java | yk-fujii/Autoware | 470b04b95eee435d2bb529d978d4c91bf57f34b0 | [
"BSD-3-Clause"
] | 34 | 2018-11-27T08:57:32.000Z | 2022-02-18T08:06:04.000Z | 30.338889 | 126 | 0.688335 | 9,816 | /*
* Copyright (c) 2015, Nagoya University
* 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 Autoware 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 HOLDER 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 com.example.candatasender.CarLinkData;
import java.io.Serializable;
public class CanData implements Serializable {
private static final long serialVersionUID = 5868650586794237676L;
private static final int USB_COLUMN_NR = 5;
private static final int BT_COLUMN_NR = 2;
public static final String name = "CarLinkCanData";
public long timestamp;
public double value;
public CanDataType type;
//private static int dummyNum = 1; // dummysend
public enum UsbBt {
USB,
BT,
UNKNOWN;
}
public enum CanDataType {
str(0x025),
vel(0x610),
gas(0x245),
brake(0x224),
seatbelt(0x620),
unknown(0x000);
private final int canId;
private CanDataType(final int canId) {
this.canId = canId;
}
public int getCanId() {
return canId;
}
public static CanDataType valueOf(int canId) {
for (CanDataType type: values()) {
if (type.getCanId() == canId) {
return type;
}
}
return unknown;
}
}
public static CanData parseUsb(String line) throws NumberFormatException {
CanData can = new CanData();
String[] data = line.split(",");
if (data.length != USB_COLUMN_NR) throw new NumberFormatException(name + "(USB) CSV format error: column = " + data.length);
// SysTimeStamp[ms],TimeStamp[us],ID(hhh),DataLength(h),Data(hh...)
can.timestamp = Long.parseLong(data[0]);
can.type = CanDataType.valueOf(Integer.parseInt(data[2], 16));
switch (can.type) {
case str:
short sstr = (short)Integer.parseInt(data[4].substring(1, 4) + "0", 16);
can.value = (double)(sstr >> 4) * 1.5;
break;
case vel:
int ivel = Integer.parseInt(data[4].substring(4, 6), 16);
can.value = (double)ivel;
break;
case gas:
int igas = Integer.parseInt(data[4].substring(4, 6), 16);
can.value = (double)igas * 0.5;
break;
case brake:
int ibrake = Integer.parseInt(data[4].substring(8, 12), 16);
can.value = (double)ibrake * 0.00125;
break;
case seatbelt:
int isb = Integer.parseInt(data[4].substring(14, 15), 16);
can.value = (double)isb * 0.015625;
break;
case unknown:
//can.type = CanDataType.str; // dummysend
//can.value = dummyNum++; // dummysend
default:
break;
}
return can;
}
public static CanData parseBt(String line) throws NumberFormatException {
CanData can = new CanData();
String[] data = line.split(",");
if (data.length != BT_COLUMN_NR) throw new NumberFormatException(name + "(BT) CSV format error: column = " + data.length);
// TimeStamp[ms],RawMsg['t'+ID(hhh)+DataLength(h)+Data(hh...)]
can.timestamp = Long.parseLong(data[0]);
can.type = CanDataType.valueOf(Integer.parseInt(data[1].substring(1, 4), 16));
switch (can.type) {
case str:
short sstr = (short)Integer.parseInt(data[1].substring(6, 9) + "0", 16);
can.value = (double)(sstr >> 4) * 1.5;
break;
case vel:
int ivel = Integer.parseInt(data[1].substring(9, 11), 16);
can.value = (double)ivel;
break;
case gas:
int igas = Integer.parseInt(data[1].substring(9, 11), 16);
can.value = (double)igas * 0.5;
break;
case brake:
int ibrake = Integer.parseInt(data[1].substring(13, 17), 16);
can.value = (double)ibrake * 0.00125;
break;
case seatbelt:
int isb = Integer.parseInt(data[1].substring(19, 20), 16);
can.value = (double)isb * 0.015625;
break;
case unknown:
default:
break;
}
return can;
}
public static CanData parse(String line, UsbBt usbbt) throws NumberFormatException {
CanData can = null;
switch (usbbt) {
case USB:
can = parseUsb(line);
break;
case BT:
can = parseBt(line);
break;
default:
break;
}
return can;
}
public static UsbBt parseUsbBt(String line) {
String[] data = line.split(",");
switch (data.length) {
case USB_COLUMN_NR:
return UsbBt.USB;
case BT_COLUMN_NR:
return UsbBt.BT;
default:
return UsbBt.UNKNOWN;
}
}
}
|
3e170b1cc684ff8e5eced1053bfdad345af38bf0 | 3,480 | java | Java | app/src/main/java/com/hdev/sicbotogel/view/NotificationHistoryActivity.java | Hendriyawan/Sicbotogel | d71dabce0658ee2a7a435555a1f027df311197c2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hdev/sicbotogel/view/NotificationHistoryActivity.java | Hendriyawan/Sicbotogel | d71dabce0658ee2a7a435555a1f027df311197c2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hdev/sicbotogel/view/NotificationHistoryActivity.java | Hendriyawan/Sicbotogel | d71dabce0658ee2a7a435555a1f027df311197c2 | [
"Apache-2.0"
] | null | null | null | 28.064516 | 137 | 0.716092 | 9,817 | package com.hdev.sicbotogel.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.hdev.sicbotogel.R;
import com.hdev.sicbotogel.adapter.NotificationAdapter;
import com.hdev.sicbotogel.database.helper.NotificationHelper;
import com.hdev.sicbotogel.database.model.Notifications;
import com.hdev.sicbotogel.interfaces.NotificationView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NotificationHistoryActivity extends AppCompatActivity implements NotificationView, NotificationAdapter.OnNotificationClick {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.text_view_empty_notification)
TextView textViewDataEmpty;
@BindView(R.id.recycler_view_notification)
RecyclerView recyclerViewNotification;
private NotificationHelper notificationHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_history);
ButterKnife.bind(this);
initialize();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
notificationHelper.getAllNotifications(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onNotificationFirstLoaded(List<Notifications> notifications) {
}
@Override
public void onNotificationLoaded(List<Notifications> notifications) {
initRecyclerView(notifications);
}
@Override
public void onDataEmpty() {
recyclerViewNotification.setVisibility(View.GONE);
textViewDataEmpty.setVisibility(View.VISIBLE);
}
/*
Initialize
*/
private void initialize() {
initToolbar();
notificationHelper = new NotificationHelper(this);
notificationHelper.open();
notificationHelper.getAllNotifications(this);
}
/*
Init Toolbar
*/
private void initToolbar() {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
}
/*
Init RecyclerView
*/
private void initRecyclerView(List<Notifications> notificationsList) {
NotificationAdapter adapter = new NotificationAdapter(this, notificationsList, this);
recyclerViewNotification.setAdapter(adapter);
}
@Override
public void onClick(Notifications notifications) {
Intent viewNotificationIntent = new Intent(this, ViewNotification.class);
viewNotificationIntent.putExtra("parcelable_notification", notifications);
startActivity(viewNotificationIntent);
}
@Override
public void onDelete(int id) {
notificationHelper.delete(id);
notificationHelper.getAllNotifications(this);
}
} |
3e170bbfbf8574db9d357e75973687fdb50a6fbc | 1,130 | java | Java | src/org/usfirst/frc3550/Julius2018/commands/PickupCubeCommand.java | FRCteam3550/3550-PowerUp | 18555d3a857fed72456e4c79a878671bb26ae1bc | [
"BSD-3-Clause"
] | null | null | null | src/org/usfirst/frc3550/Julius2018/commands/PickupCubeCommand.java | FRCteam3550/3550-PowerUp | 18555d3a857fed72456e4c79a878671bb26ae1bc | [
"BSD-3-Clause"
] | null | null | null | src/org/usfirst/frc3550/Julius2018/commands/PickupCubeCommand.java | FRCteam3550/3550-PowerUp | 18555d3a857fed72456e4c79a878671bb26ae1bc | [
"BSD-3-Clause"
] | null | null | null | 24.565217 | 79 | 0.675221 | 9,818 | package org.usfirst.frc3550.Julius2018.commands;
//import org.omg.CORBA.TIMEOUT;
import org.usfirst.frc3550.Julius2018.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class PickupCubeCommand extends Command {
public PickupCubeCommand() {
// Use requires() here to declare subsystem dependencies
requires(Robot.pinceSubsystem);
}
// Called just before this Command runs the first time
protected void initialize() {
setTimeout(3);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.pinceSubsystem.PickupCube();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isTimedOut();
}
// Called once after isFinished returns true
protected void end() {
Robot.pinceSubsystem.Stop();
//new HoldCubeCommand();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
//isTimedOut();
end();
}
}
|
3e170d3ad6cc0c5cc2181cd6dc118d7edd9a5646 | 513 | java | Java | src/org/tensorflow/yolo/Book.java | Beakjiyeon/English_Planet | fea8871452125559d64b5488bc197550e0019f88 | [
"WTFPL"
] | null | null | null | src/org/tensorflow/yolo/Book.java | Beakjiyeon/English_Planet | fea8871452125559d64b5488bc197550e0019f88 | [
"WTFPL"
] | null | null | null | src/org/tensorflow/yolo/Book.java | Beakjiyeon/English_Planet | fea8871452125559d64b5488bc197550e0019f88 | [
"WTFPL"
] | null | null | null | 16.03125 | 42 | 0.565302 | 9,819 | package org.tensorflow.yolo;
public class Book {
private String b_text;
private int p_id;
private int b_id;
public String getB_text() {
return b_text;
}
public void setB_text(String b_text) {
this.b_text = b_text;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
}
public int getB_id() {
return b_id;
}
public void setB_id(int b_id) {
this.b_id = b_id;
}
}
|
3e170f16db222e1d66ef93a33085160728977eed | 13,703 | java | Java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DefaultHyperParameterRanges.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DefaultHyperParameterRanges.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DefaultHyperParameterRanges.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 40.54142 | 157 | 0.697876 | 9,820 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Specifies the hyperparameters and their default ranges. Hyperparameters can be categorical, continuous, or
* integer-valued.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DefaultHyperParameterRanges"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DefaultHyperParameterRanges implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The integer-valued hyperparameters and their default ranges.
* </p>
*/
private java.util.List<DefaultIntegerHyperParameterRange> integerHyperParameterRanges;
/**
* <p>
* The continuous hyperparameters and their default ranges.
* </p>
*/
private java.util.List<DefaultContinuousHyperParameterRange> continuousHyperParameterRanges;
/**
* <p>
* The categorical hyperparameters and their default ranges.
* </p>
*/
private java.util.List<DefaultCategoricalHyperParameterRange> categoricalHyperParameterRanges;
/**
* <p>
* The integer-valued hyperparameters and their default ranges.
* </p>
*
* @return The integer-valued hyperparameters and their default ranges.
*/
public java.util.List<DefaultIntegerHyperParameterRange> getIntegerHyperParameterRanges() {
return integerHyperParameterRanges;
}
/**
* <p>
* The integer-valued hyperparameters and their default ranges.
* </p>
*
* @param integerHyperParameterRanges
* The integer-valued hyperparameters and their default ranges.
*/
public void setIntegerHyperParameterRanges(java.util.Collection<DefaultIntegerHyperParameterRange> integerHyperParameterRanges) {
if (integerHyperParameterRanges == null) {
this.integerHyperParameterRanges = null;
return;
}
this.integerHyperParameterRanges = new java.util.ArrayList<DefaultIntegerHyperParameterRange>(integerHyperParameterRanges);
}
/**
* <p>
* The integer-valued hyperparameters and their default ranges.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setIntegerHyperParameterRanges(java.util.Collection)} or
* {@link #withIntegerHyperParameterRanges(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param integerHyperParameterRanges
* The integer-valued hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withIntegerHyperParameterRanges(DefaultIntegerHyperParameterRange... integerHyperParameterRanges) {
if (this.integerHyperParameterRanges == null) {
setIntegerHyperParameterRanges(new java.util.ArrayList<DefaultIntegerHyperParameterRange>(integerHyperParameterRanges.length));
}
for (DefaultIntegerHyperParameterRange ele : integerHyperParameterRanges) {
this.integerHyperParameterRanges.add(ele);
}
return this;
}
/**
* <p>
* The integer-valued hyperparameters and their default ranges.
* </p>
*
* @param integerHyperParameterRanges
* The integer-valued hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withIntegerHyperParameterRanges(java.util.Collection<DefaultIntegerHyperParameterRange> integerHyperParameterRanges) {
setIntegerHyperParameterRanges(integerHyperParameterRanges);
return this;
}
/**
* <p>
* The continuous hyperparameters and their default ranges.
* </p>
*
* @return The continuous hyperparameters and their default ranges.
*/
public java.util.List<DefaultContinuousHyperParameterRange> getContinuousHyperParameterRanges() {
return continuousHyperParameterRanges;
}
/**
* <p>
* The continuous hyperparameters and their default ranges.
* </p>
*
* @param continuousHyperParameterRanges
* The continuous hyperparameters and their default ranges.
*/
public void setContinuousHyperParameterRanges(java.util.Collection<DefaultContinuousHyperParameterRange> continuousHyperParameterRanges) {
if (continuousHyperParameterRanges == null) {
this.continuousHyperParameterRanges = null;
return;
}
this.continuousHyperParameterRanges = new java.util.ArrayList<DefaultContinuousHyperParameterRange>(continuousHyperParameterRanges);
}
/**
* <p>
* The continuous hyperparameters and their default ranges.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setContinuousHyperParameterRanges(java.util.Collection)} or
* {@link #withContinuousHyperParameterRanges(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param continuousHyperParameterRanges
* The continuous hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withContinuousHyperParameterRanges(DefaultContinuousHyperParameterRange... continuousHyperParameterRanges) {
if (this.continuousHyperParameterRanges == null) {
setContinuousHyperParameterRanges(new java.util.ArrayList<DefaultContinuousHyperParameterRange>(continuousHyperParameterRanges.length));
}
for (DefaultContinuousHyperParameterRange ele : continuousHyperParameterRanges) {
this.continuousHyperParameterRanges.add(ele);
}
return this;
}
/**
* <p>
* The continuous hyperparameters and their default ranges.
* </p>
*
* @param continuousHyperParameterRanges
* The continuous hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withContinuousHyperParameterRanges(
java.util.Collection<DefaultContinuousHyperParameterRange> continuousHyperParameterRanges) {
setContinuousHyperParameterRanges(continuousHyperParameterRanges);
return this;
}
/**
* <p>
* The categorical hyperparameters and their default ranges.
* </p>
*
* @return The categorical hyperparameters and their default ranges.
*/
public java.util.List<DefaultCategoricalHyperParameterRange> getCategoricalHyperParameterRanges() {
return categoricalHyperParameterRanges;
}
/**
* <p>
* The categorical hyperparameters and their default ranges.
* </p>
*
* @param categoricalHyperParameterRanges
* The categorical hyperparameters and their default ranges.
*/
public void setCategoricalHyperParameterRanges(java.util.Collection<DefaultCategoricalHyperParameterRange> categoricalHyperParameterRanges) {
if (categoricalHyperParameterRanges == null) {
this.categoricalHyperParameterRanges = null;
return;
}
this.categoricalHyperParameterRanges = new java.util.ArrayList<DefaultCategoricalHyperParameterRange>(categoricalHyperParameterRanges);
}
/**
* <p>
* The categorical hyperparameters and their default ranges.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setCategoricalHyperParameterRanges(java.util.Collection)} or
* {@link #withCategoricalHyperParameterRanges(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param categoricalHyperParameterRanges
* The categorical hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withCategoricalHyperParameterRanges(DefaultCategoricalHyperParameterRange... categoricalHyperParameterRanges) {
if (this.categoricalHyperParameterRanges == null) {
setCategoricalHyperParameterRanges(new java.util.ArrayList<DefaultCategoricalHyperParameterRange>(categoricalHyperParameterRanges.length));
}
for (DefaultCategoricalHyperParameterRange ele : categoricalHyperParameterRanges) {
this.categoricalHyperParameterRanges.add(ele);
}
return this;
}
/**
* <p>
* The categorical hyperparameters and their default ranges.
* </p>
*
* @param categoricalHyperParameterRanges
* The categorical hyperparameters and their default ranges.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DefaultHyperParameterRanges withCategoricalHyperParameterRanges(
java.util.Collection<DefaultCategoricalHyperParameterRange> categoricalHyperParameterRanges) {
setCategoricalHyperParameterRanges(categoricalHyperParameterRanges);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getIntegerHyperParameterRanges() != null)
sb.append("IntegerHyperParameterRanges: ").append(getIntegerHyperParameterRanges()).append(",");
if (getContinuousHyperParameterRanges() != null)
sb.append("ContinuousHyperParameterRanges: ").append(getContinuousHyperParameterRanges()).append(",");
if (getCategoricalHyperParameterRanges() != null)
sb.append("CategoricalHyperParameterRanges: ").append(getCategoricalHyperParameterRanges());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DefaultHyperParameterRanges == false)
return false;
DefaultHyperParameterRanges other = (DefaultHyperParameterRanges) obj;
if (other.getIntegerHyperParameterRanges() == null ^ this.getIntegerHyperParameterRanges() == null)
return false;
if (other.getIntegerHyperParameterRanges() != null && other.getIntegerHyperParameterRanges().equals(this.getIntegerHyperParameterRanges()) == false)
return false;
if (other.getContinuousHyperParameterRanges() == null ^ this.getContinuousHyperParameterRanges() == null)
return false;
if (other.getContinuousHyperParameterRanges() != null
&& other.getContinuousHyperParameterRanges().equals(this.getContinuousHyperParameterRanges()) == false)
return false;
if (other.getCategoricalHyperParameterRanges() == null ^ this.getCategoricalHyperParameterRanges() == null)
return false;
if (other.getCategoricalHyperParameterRanges() != null
&& other.getCategoricalHyperParameterRanges().equals(this.getCategoricalHyperParameterRanges()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getIntegerHyperParameterRanges() == null) ? 0 : getIntegerHyperParameterRanges().hashCode());
hashCode = prime * hashCode + ((getContinuousHyperParameterRanges() == null) ? 0 : getContinuousHyperParameterRanges().hashCode());
hashCode = prime * hashCode + ((getCategoricalHyperParameterRanges() == null) ? 0 : getCategoricalHyperParameterRanges().hashCode());
return hashCode;
}
@Override
public DefaultHyperParameterRanges clone() {
try {
return (DefaultHyperParameterRanges) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.personalize.model.transform.DefaultHyperParameterRangesMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
3e17102c8f5ff48f1dccf12371053ae0362da60c | 5,414 | java | Java | src/main/java/seedu/address/model/Calendar.java | JingYuOng/main | 8c5bafbc55c3af4a1a89966b085b5997f61aea5c | [
"MIT"
] | null | null | null | src/main/java/seedu/address/model/Calendar.java | JingYuOng/main | 8c5bafbc55c3af4a1a89966b085b5997f61aea5c | [
"MIT"
] | null | null | null | src/main/java/seedu/address/model/Calendar.java | JingYuOng/main | 8c5bafbc55c3af4a1a89966b085b5997f61aea5c | [
"MIT"
] | null | null | null | 30.761364 | 119 | 0.665866 | 9,821 | package seedu.address.model;
import static java.util.Objects.requireNonNull;
import java.util.List;
import javafx.collections.ObservableList;
import seedu.address.model.entity.CalendarItem;
import seedu.address.model.entity.Module;
import seedu.address.model.entity.UniqueCalendarItemList;
import seedu.address.model.entity.UniqueModuleList;
/**
* Wraps all data at the calendar level
* Duplicates are not allowed (by .isSameModule comparison)
*/
public class Calendar implements ReadOnlyCalendar {
private final UniqueCalendarItemList calendarItems;
private final UniqueModuleList modules;
/*
* The 'unusual' code block below is a non-static initialization block, sometimes used to avoid duplication
* between constructors. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
*
* Note that non-static init blocks are not recommended to use. There are other ways to avoid duplication
* among constructors.
*/
{
calendarItems = new UniqueCalendarItemList();
modules = new UniqueModuleList();
}
public Calendar() {
}
/**
* Creates an AddressBook using the Persons in the {@code toBeCopied}
*/
public Calendar(ReadOnlyCalendar toBeCopied) {
this();
resetData(toBeCopied);
}
//// list overwrite operations
/**
* Replaces the contents of the person list with {@code persons}.
* {@code persons} must not contain duplicate persons.
*/
public void setModules(List<Module> modules) {
this.modules.setModules(modules);
}
/**
* Returns true if a person with the same identity as {@code person} exists in the address book.
*/
public boolean hasModule(Module module) {
requireNonNull(module);
return modules.contains(module);
}
/**
* Adds a person to the address book.
* The person must not already exist in the address book.
*/
public void addModule(Module module) {
modules.add(module);
}
/**
* Replaces the given person {@code target} in the list with {@code editedPerson}.
* {@code target} must exist in the address book.
* The person identity of {@code editedPerson} must not be the same as another existing person in the address book.
*/
public void setModule(Module target, Module editedModule) {
requireNonNull(editedModule);
modules.setModule(target, editedModule);
}
/**
* Removes {@code key} from this {@code AddressBook}.
* {@code key} must exist in the address book.
*/
public void removeModule(Module key) {
modules.remove(key);
}
/**
* Replaces the contents of the person list with {@code persons}.
* {@code persons} must not contain duplicate persons.
*/
public void setCalendarItems(List<CalendarItem> calendarItems) {
this.calendarItems.setCalendarItems(calendarItems);
}
/**
* Replaces the given person {@code target} in the list with {@code editedPerson}.
* {@code target} must exist in the address book.
* The person identity of {@code editedPerson} must not be the same as another existing person in the address book.
*/
public void setCalendarItems(CalendarItem target, CalendarItem editedCalendarItem) {
requireNonNull(editedCalendarItem);
calendarItems.setCalendarItem(target, editedCalendarItem);
}
/**
* Resets the existing data of this {@code AddressBook} with {@code newData}.
*/
public void resetData(ReadOnlyCalendar newData) {
requireNonNull(newData);
setCalendarItems(newData.getCalendarItemList());
setModules(newData.getModuleList());
}
//// person-level operations
/**
* Returns true if a person with the same identity as {@code person} exists in the address book.
*/
public boolean hasCalendarItem(CalendarItem calendarItem) {
requireNonNull(calendarItem);
// System.out.println("Calendar item !!!!!!!!!!!!!!!"+ calendarItem);
return calendarItems.contains(calendarItem);
}
/**
* Adds a person to the address book.
* The person must not already exist in the address book.
*/
public void addCalendarItem(CalendarItem calendarItem) {
calendarItems.add(calendarItem);
}
/**
* Removes {@code key} from this {@code AddressBook}.
* {@code key} must exist in the address book.
*/
public void removeCalendarItem(CalendarItem key) {
calendarItems.remove(key);
}
//// util methods
@Override
public String toString() {
return calendarItems.asUnmodifiableObservableList().size() + " calendar items";
// TODO: refine later
}
@Override
public ObservableList<CalendarItem> getCalendarItemList() {
return calendarItems.asUnmodifiableObservableList();
}
@Override
public ObservableList<Module> getModuleList() {
return modules.asUnmodifiableObservableList();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Calendar // instanceof handles nulls
&& calendarItems.equals(((Calendar) other).calendarItems));
}
@Override
public int hashCode() {
return calendarItems.hashCode();
}
}
|
3e17104521b03677eca1d377796b95e6f4e8a2cb | 1,482 | java | Java | chapter4/core/src/com/packt/flappeebee/GameScreen.java | burningrain/libGDX-book-gameDelopmentByExample | 14ce2f5236744cbc1c1bcc9514adc7781f026426 | [
"MIT"
] | 2 | 2017-05-08T23:10:07.000Z | 2017-10-25T21:50:39.000Z | chapter4/core/src/com/packt/flappeebee/GameScreen.java | burningrain/libGDX-book-gameDelopmentByExample | 14ce2f5236744cbc1c1bcc9514adc7781f026426 | [
"MIT"
] | 1 | 2017-07-21T09:28:19.000Z | 2017-07-21T09:28:19.000Z | chapter4/core/src/com/packt/flappeebee/GameScreen.java | burningrain/libGDX-book-gameDelopmentByExample | 14ce2f5236744cbc1c1bcc9514adc7781f026426 | [
"MIT"
] | 1 | 2018-04-19T19:44:21.000Z | 2018-04-19T19:44:21.000Z | 31.531915 | 96 | 0.690958 | 9,822 | package com.packt.flappeebee;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.packt.flappeebee.model.GameWorld;
import com.packt.flappeebee.model.GameWorldSettings;
public class GameScreen extends ScreenAdapter {
private GameWorld gameWorld;
@Override
public void show() {
boolean npotSupported = Gdx.graphics.supportsExtension("GL_OES_texture_npot")
|| Gdx.graphics.supportsExtension("GL_ARB_texture_non_power_of_two");
System.out.println("isNpotSupported: " + npotSupported);
GameWorldSettings gameWorldSettings = new GameWorldSettings();
gameWorldSettings.virtualWidth = 1024;
gameWorldSettings.virtualHeight = 768;
gameWorld = new GameWorld(gameWorldSettings);
}
@Override
public void resize(int width, int height) {
gameWorld.resize(width, height);
}
@Override
public void render(float delta) {
clearScreen(); // очищаем экран
// обработка клавиш теперь размазана по коду
gameWorld.render(delta); // обновление игрового мира (состояние и рендеринг)
//TODO пробросить вывод runtime-ошибок на экран
}
private void clearScreen() {
Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
}
|
3e171164748b6da32902bbedb8cfaf32d5bb1939 | 1,986 | java | Java | kzingsdk/src/main/java/com/kzingsdk/requests/GetBannersAPI.java | K-zing/androidsdk | 39baf638c1bc5b5eff7528d90e5fd1685bfd6297 | [
"Apache-2.0"
] | null | null | null | kzingsdk/src/main/java/com/kzingsdk/requests/GetBannersAPI.java | K-zing/androidsdk | 39baf638c1bc5b5eff7528d90e5fd1685bfd6297 | [
"Apache-2.0"
] | null | null | null | kzingsdk/src/main/java/com/kzingsdk/requests/GetBannersAPI.java | K-zing/androidsdk | 39baf638c1bc5b5eff7528d90e5fd1685bfd6297 | [
"Apache-2.0"
] | null | null | null | 27.205479 | 91 | 0.632427 | 9,823 | package com.kzingsdk.requests;
import android.content.Context;
import com.kzingsdk.core.CoreRequest;
import com.kzingsdk.entity.ActivityItem;
import com.kzingsdk.entity.Banner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.reactivex.Observable;
public class GetBannersAPI extends CoreRequest {
GetBannersAPI() {
super();
}
@Override
protected String getAction() {
return Action.getBanners;
}
@Override
protected Observable<String> validateParams() {
return super.validateParams();
}
@Override
protected JSONObject generateParamsJson() {
return super.generateParamsJson();
}
@Override
public Observable<ArrayList<Banner>> requestRx(Context context) {
return super.baseExecute(context)
.map(jsonResponse -> {
ArrayList<Banner> bannerArrayList = new ArrayList<>();
JSONArray response = jsonResponse.optJSONArray("data");
for (int i = 0; i < response.length(); i++) {
bannerArrayList.add(Banner.newInstance(response.optJSONObject(i)));
}
return bannerArrayList;
});
}
@Override
public void request(Context context) {
requestRx(context).subscribe(bannerList -> {
if (kzingCallBackList.size() > 0) {
for (KzingCallBack kzingCallBack : kzingCallBackList) {
((GetBannersCallBack) kzingCallBack).onSuccess(bannerList);
}
}
}, defaultOnErrorConsumer);
}
public GetBannersAPI addGetBannersCallBack(GetBannersCallBack getBannersCallBack) {
kzingCallBackList.add(getBannersCallBack);
return this;
}
public interface GetBannersCallBack extends KzingCallBack {
void onSuccess(ArrayList<Banner> bannerList);
}
}
|
3e1711888abf5525da11a9d0722b5cc0fff38179 | 2,464 | java | Java | doc/openjdk/hotspot/test/runtime/7100935/TestConjointAtomicArraycopy.java | renshuaibing-aaron/jdk1.8-source-analysis | 3233a942039cdf8af53689c072be2d49edfc3990 | [
"Apache-2.0"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | HotSpot1.7/test/runtime/7100935/TestConjointAtomicArraycopy.java | yibaolin/Open-Source-Research | 0cbdc9ed3fbdaf8b055682369fcc6c6112dd85d5 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | HotSpot1.7/test/runtime/7100935/TestConjointAtomicArraycopy.java | yibaolin/Open-Source-Research | 0cbdc9ed3fbdaf8b055682369fcc6c6112dd85d5 | [
"Apache-2.0"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | 31.265823 | 76 | 0.669636 | 9,824 | /*
* Copyright 2011 SAP AG. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test TestConjointAtomicArraycopy
* @bug 7100935
* @summary verify that oops are copied element-wise atomic
* @run main/othervm -Xint TestConjointAtomicArraycopy
* @run main/othervm -Xcomp -Xbatch TestConjointAtomicArraycopy
* @author efpyi@example.com
*/
public class TestConjointAtomicArraycopy {
static volatile Object [] testArray = new Object [4];
static short[] a1 = new short[8];
static short[] a2 = new short[8];
static short[] a3 = new short[8];
static volatile boolean keepRunning = true;
static void testOopsCopy() throws InterruptedException{
}
public static void main(String[] args ) throws InterruptedException{
for (int i = 0; i < testArray.length; i++){
testArray[i] = new String("A");
}
Thread writer = new Thread (new Runnable(){
public void run(){
for (int i = 0 ; i < 1000000; i++) {
System.arraycopy(testArray, 1, testArray, 0, 3);
testArray[2] = new String("a");
}
}
});
Thread reader = new Thread( new Runnable(){
public void run(){
while (keepRunning){
String name = testArray[2].getClass().getName();
if(!(name.endsWith("String"))){
throw new RuntimeException("got wrong class name");
}
}
}
});
keepRunning = true;
reader.start();
writer.start();
writer.join();
keepRunning = false;
reader.join();
}
}
|
3e1712067e3910318ddf42f6bcfced4503f60f29 | 281 | java | Java | src/chapter04/section01/thread_4_1_1/project_1_ReentrantLockTest/MyThread.java | yzrds/untitled | 7c8759c2e1bfb409b5871ad88c30a7e8865953d6 | [
"MIT"
] | 266 | 2019-03-21T13:16:54.000Z | 2022-03-30T03:24:46.000Z | src/chapter04/section01/thread_4_1_1/project_1_ReentrantLockTest/MyThread.java | yzrds/untitled | 7c8759c2e1bfb409b5871ad88c30a7e8865953d6 | [
"MIT"
] | 1 | 2019-02-02T09:15:15.000Z | 2019-02-02T09:15:15.000Z | src/chapter04/section01/thread_4_1_1/project_1_ReentrantLockTest/MyThread.java | yzrds/untitled | 7c8759c2e1bfb409b5871ad88c30a7e8865953d6 | [
"MIT"
] | 92 | 2019-03-21T07:55:17.000Z | 2021-12-17T02:35:54.000Z | 15.611111 | 69 | 0.747331 | 9,825 | package chapter04.section01.thread_4_1_1.project_1_ReentrantLockTest;
public class MyThread extends Thread {
private MyService service;
public MyThread(MyService service) {
super();
this.service = service;
}
@Override
public void run() {
service.testMethod();
}
}
|
3e171289262cdcabc66ed34aa483f45cf45b39ab | 1,928 | java | Java | src/main/java/com/Da_Technomancer/crossroads/particles/ParticleDripColor.java | MrDrProfNo/Crossroads | 742c71d245cc446b72e545f372d5744cc7761a04 | [
"MIT"
] | 20 | 2016-08-12T20:56:06.000Z | 2021-09-21T03:04:45.000Z | src/main/java/com/Da_Technomancer/crossroads/particles/ParticleDripColor.java | MrDrProfNo/Crossroads | 742c71d245cc446b72e545f372d5744cc7761a04 | [
"MIT"
] | 143 | 2016-08-12T21:31:24.000Z | 2021-09-16T12:56:15.000Z | src/main/java/com/Da_Technomancer/crossroads/particles/ParticleDripColor.java | MrDrProfNo/Crossroads | 742c71d245cc446b72e545f372d5744cc7761a04 | [
"MIT"
] | 21 | 2016-08-29T14:52:52.000Z | 2021-01-11T22:32:47.000Z | 28.352941 | 155 | 0.712137 | 9,826 | package com.Da_Technomancer.crossroads.particles;
import net.minecraft.client.particle.*;
import net.minecraft.client.world.ClientWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import java.awt.*;
@OnlyIn(Dist.CLIENT)
public class ParticleDripColor extends SpriteTexturedParticle{
private final IAnimatedSprite sprite;
private ParticleDripColor(ClientWorld worldIn, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed, Color c, IAnimatedSprite s){
super(worldIn, x, y, z);
setSize(0.02F, 0.02F);
hasPhysics = false;
sprite = s;
// setParticleTextureIndex(17);
scale(random.nextFloat() * 0.6F + 0.6F);
xd = xSpeed;//Suggestion: (Math.random() * 2D - 1D) * 0.02D
yd = ySpeed;//Suggestion: (Math.random() - 1D) * 0.02D
zd = zSpeed;//Suggestion: (Math.random() * 2D - 1D) * 0.02D
setLifetime((int) (7.0D / (Math.random() * 0.8D + 0.2D)));
setColor(c.getRed() / 255F, c.getGreen() / 255F, c.getBlue() / 255F);
setAlpha(c.getAlpha() / 255F);
setSpriteFromAge(sprite);
}
@Override
public void tick(){
xo = x;
yo = y;
zo = z;
move(xd, yd, zd);
xd *= 0.85D;
yd *= 0.85D;
zd *= 0.85D;
setSpriteFromAge(sprite);
if(age++ >= lifetime){
remove();
}
}
@Override
public IParticleRenderType getRenderType(){
return IParticleRenderType.PARTICLE_SHEET_OPAQUE;
}
@OnlyIn(Dist.CLIENT)
public static class Factory implements IParticleFactory<ColorParticleData>{
private final IAnimatedSprite sprite;
protected Factory(IAnimatedSprite spriteIn){
sprite = spriteIn;
}
@Nullable
@Override
public Particle createParticle(ColorParticleData typeIn, ClientWorld worldIn, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed){
return new ParticleDripColor(worldIn, x, y, z, xSpeed, ySpeed, zSpeed, typeIn.getColor(), sprite);
}
}
}
|
3e1712d68db29e2a058b9a03eb50911b64ef3849 | 300 | java | Java | spring-35-websocket/spring-01-websocket/src/main/java/tian/pusen/Application.java | pustian/learn-spring-boot | 9fe44b486d4f4d155e65147a4daface52e76d32d | [
"MIT"
] | 1 | 2020-04-19T14:48:54.000Z | 2020-04-19T14:48:54.000Z | spring-40-security/spring-06-security-Oauth2/security-oauth2/src/main/java/tian/pusen/Application.java | pustian/learn-spring-boot | 9fe44b486d4f4d155e65147a4daface52e76d32d | [
"MIT"
] | null | null | null | spring-40-security/spring-06-security-Oauth2/security-oauth2/src/main/java/tian/pusen/Application.java | pustian/learn-spring-boot | 9fe44b486d4f4d155e65147a4daface52e76d32d | [
"MIT"
] | null | null | null | 27.272727 | 68 | 0.786667 | 9,827 | package tian.pusen;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} |
3e17133ea2217ce83074d221f8c4313831d49bde | 4,443 | java | Java | src/main/java/com/urbanairship/api/push/model/notification/mpns/MPNSCycleTileData.java | afasseco/java-library | 8376d87bc35ea3b5f88398df9956d77df52795c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/urbanairship/api/push/model/notification/mpns/MPNSCycleTileData.java | afasseco/java-library | 8376d87bc35ea3b5f88398df9956d77df52795c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/urbanairship/api/push/model/notification/mpns/MPNSCycleTileData.java | afasseco/java-library | 8376d87bc35ea3b5f88398df9956d77df52795c1 | [
"Apache-2.0"
] | null | null | null | 30.22449 | 137 | 0.567184 | 9,828 | /*
* Copyright (c) 2013-2014. Urban Airship and Contributors
*/
package com.urbanairship.api.push.model.notification.mpns;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import static com.google.common.base.Preconditions.checkArgument;
public class MPNSCycleTileData extends MPNSTileData
{
private final Optional<String> smallBackgroundImage;
private final Optional<ImmutableList<String>> images;
private MPNSCycleTileData(Optional<String> id,
Optional<String> title,
Optional<Integer> count,
Optional<String> smallBackgroundImage,
Optional<ImmutableList<String>> images)
{
super(id, title, count);
this.smallBackgroundImage = smallBackgroundImage;
this.images = images;
}
public static Builder newBuilder() {
return new Builder();
}
@Override
public String getTemplate() {
return "CycleTile";
}
public Optional<String> getSmallBackgroundImage() {
return smallBackgroundImage;
}
public Optional<ImmutableList<String>> getImages() {
return images;
}
public int getImageCount() {
return images.isPresent() ? images.get().size() : 0;
}
public String getImage(int i) {
return images.isPresent() ? images.get().get(i) : null;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
MPNSCycleTileData that = (MPNSCycleTileData)o;
if (smallBackgroundImage != null ? !smallBackgroundImage.equals(that.smallBackgroundImage) : that.smallBackgroundImage != null) {
return false;
}
if (images != null ? !images.equals(that.images) : that.images != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (smallBackgroundImage != null ? smallBackgroundImage.hashCode() : 0);
result = 31 * result + (images != null ? images.hashCode() : 0);
return result;
}
public static class Builder {
private String id;
private String title;
private Integer count;
private String smallBackgroundImage;
private ImmutableList.Builder<String> imagesBuilder = ImmutableList.builder();
public Builder setId(String value) {
this.id = value;
return this;
}
public Builder setTitle(String value) {
this.title = value;
return this;
}
public Builder setCount(int value) {
this.count = new Integer(value);
return this;
}
public Builder setSmallBackgroundImage(String value) {
this.smallBackgroundImage = value;
return this;
}
public Builder addImage(String value) {
if (imagesBuilder == null) { imagesBuilder = ImmutableList.builder(); }
this.imagesBuilder.add(value);
return this;
}
public Builder addAllImages(Iterable<String> values) {
if (imagesBuilder == null) { imagesBuilder = ImmutableList.builder(); }
this.imagesBuilder.addAll(values);
return this;
}
public Builder clearImages() {
this.imagesBuilder = null;
return this;
}
public MPNSCycleTileData build() {
Validation.validateStringValue(title, "title");
ImmutableList<String> images = null;
if (imagesBuilder != null) {
images = imagesBuilder.build();
for (String image : images) {
Validation.validatePath(image, "cycle_image");
}
}
return new MPNSCycleTileData(Optional.fromNullable(id),
Optional.fromNullable(title),
Optional.fromNullable(count),
Optional.fromNullable(smallBackgroundImage),
Optional.fromNullable(images));
}
}
}
|
3e171506aee24f91086b8670d63e70f4ae05732e | 271 | java | Java | app/src/main/java/di/scopes/PresenterScope.java | NeriaNa/happy-birthday | 8b4d3efc9d46eb05724e7dd4a40848ea40546c60 | [
"MIT"
] | null | null | null | app/src/main/java/di/scopes/PresenterScope.java | NeriaNa/happy-birthday | 8b4d3efc9d46eb05724e7dd4a40848ea40546c60 | [
"MIT"
] | null | null | null | app/src/main/java/di/scopes/PresenterScope.java | NeriaNa/happy-birthday | 8b4d3efc9d46eb05724e7dd4a40848ea40546c60 | [
"MIT"
] | null | null | null | 19.357143 | 44 | 0.822878 | 9,829 | package di.scopes;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Documented
@Retention(value= RetentionPolicy.RUNTIME)
public @interface PresenterScope
{
} |
3e1715118ce0455f15a0ef03b9b253159bd9691c | 7,106 | java | Java | javasource/privatescheduledevents/PrivateScheduledEvents.java | McDoyen/yavasource | fe15e7d9c3d230465583764d01daedd6157060a8 | [
"MIT"
] | null | null | null | javasource/privatescheduledevents/PrivateScheduledEvents.java | McDoyen/yavasource | fe15e7d9c3d230465583764d01daedd6157060a8 | [
"MIT"
] | null | null | null | javasource/privatescheduledevents/PrivateScheduledEvents.java | McDoyen/yavasource | fe15e7d9c3d230465583764d01daedd6157060a8 | [
"MIT"
] | null | null | null | 41.555556 | 141 | 0.73065 | 9,830 | package privatescheduledevents;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import privatescheduledevents.proxies.ScheduledEvent;
import privatescheduledevents.proxies.ScheduledEventAudit;
import com.mendix.core.Core;
import com.mendix.core.CoreException;
import com.mendix.logging.ILogNode;
public class PrivateScheduledEvents {
private final static ILogNode logger = Core.getLogger("PrivateScheduledEvents");
private static Map<String,ScheduledExecutorService> scheduledEventServices = new ConcurrentHashMap<String,ScheduledExecutorService>();
private static Map<String,PrivateScheduledEventThread> scheduledEventThreads = new ConcurrentHashMap<String,PrivateScheduledEventThread>();
private static AtomicInteger privateID = new AtomicInteger();
public static int getNumberOfScheduledEventsRunning() {
return scheduledEventServices.size();
}
public static boolean startScheduledEvent(ScheduledEvent scheduledEvent) {
String name = scheduledEvent.getMicroflowName();
if (scheduledEventServices.containsKey(name)) {
stopScheduledEvent(name);
}
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.set(year, month, day, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
long millisecondsOnDay = now - calendar.getTimeInMillis();
long delay = scheduledEvent.getOffset() - millisecondsOnDay;
while (delay<0) delay += scheduledEvent.getFrequency();
/*ScheduledFuture<?> thread = */
PrivateScheduledEventThread privateScheduledEventThread = new PrivateScheduledEventThread(scheduledEvent);
scheduler.scheduleAtFixedRate(privateScheduledEventThread, delay, scheduledEvent.getFrequency(), TimeUnit.MILLISECONDS);
scheduledEventServices.put(name, scheduler);
scheduledEventThreads.put(name, privateScheduledEventThread);
logger.info("Started dynamic scheduled event " + name);
return true;
}
public static boolean stopScheduledEvent(ScheduledEvent scheduledEvent) {
return stopScheduledEvent(scheduledEvent.getMicroflowName());
}
private static boolean stopScheduledEvent(String name) {
PrivateScheduledEventThread privateScheduledEventThread = scheduledEventThreads.get(name);
if (privateScheduledEventThread==null) return false;
privateScheduledEventThread.stop();
scheduledEventThreads.remove(name);
ScheduledExecutorService scheduler = scheduledEventServices.get(name);
scheduledEventServices.remove(name);
if (scheduler!=null && !scheduler.isShutdown() && !scheduler.isTerminated()) {
try {
scheduler.shutdown();
} catch (Exception e) {
logger.warn("Cannot shutdown ScheduledExecutorService, but thread is inactivated and will not be started again.", e);
try {
scheduler.shutdownNow();
} catch (Exception e1) {
logger.warn("Cannot shutdownNow ScheduledExecutorService.", e1);
try {
scheduler.awaitTermination(30, TimeUnit.SECONDS);
} catch (Exception e2) {
logger.warn("Cannot awaitTermination ScheduledExecutorService.", e2);
return false;
}
}
}
}
logger.info("Stopped dynamic scheduled event " + name);
return true;
}
public static boolean isRunningScheduledEvent(ScheduledEvent scheduledEvent) {
String name = scheduledEvent.getMicroflowName();
if (name==null) return false;
ScheduledExecutorService scheduler = scheduledEventServices.get(name);
if (scheduler!=null && !scheduler.isShutdown() && !scheduler.isTerminated()) {
return true;
} else {
return false;
}
}
public static boolean stopAllScheduledEvent() {
boolean result = true;
for (String schedulerKey:scheduledEventServices.keySet()) {
if (!stopScheduledEvent(schedulerKey)) result = false;
}
return result;
}
private static class PrivateScheduledEventThread implements Runnable {
private ScheduledEvent scheduledEvent1;
private String MicroflowName1;
private volatile boolean active = true;
PrivateScheduledEventThread(ScheduledEvent scheduledEvent) {
this.scheduledEvent1 = scheduledEvent;
this.MicroflowName1 = scheduledEvent.getMicroflowName();
}
public void stop() {
active = false;
}
public void run() {
if (!active || Thread.currentThread().isInterrupted()) return;
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.error("uncaughtException "+e.getMessage()+"in " + MicroflowName1, e);
}
});
Thread.currentThread().setName("PrivateScheduledEvent " + privateID.incrementAndGet() + " for microflow " + MicroflowName1);
Date start = new Date();
ScheduledEventAudit scheduledEventAudit = new ScheduledEventAudit(Core.createSystemContext());
scheduledEventAudit.setScheduledEventAudit_ScheduledEvent(scheduledEvent1);
try {
if (!active || Thread.currentThread().isInterrupted()) return;
scheduledEventAudit.commit();
} catch (CoreException e1) {
logger.error("Error committing new ScheduledEventAudit record in " + MicroflowName1, e1);
}
try {
if (!active || Thread.currentThread().isInterrupted()) return;
logger.trace("Running executing dynamic scheduled event microflow " + MicroflowName1);
Core.execute(Core.createSystemContext(), MicroflowName1);
logger.trace("Finished executing dynamic scheduled event microflow " + MicroflowName1 );
if (!active || Thread.currentThread().isInterrupted()) return;
} catch (Exception e) {
logger.error("Failed to execute dynamic scheduled event microflow " + MicroflowName1 + ".", e);
}
Date end = new Date();
Long millis = end.getTime() - start.getTime();
scheduledEventAudit.setDuration(millis);
scheduledEventAudit.setIsFinished(true);
scheduledEventAudit.setStop(end);
try {
if (!active || Thread.currentThread().isInterrupted()) return;
scheduledEventAudit.commit();
} catch (CoreException e1) {
logger.error("Error committing updated ScheduledEventAudit record in " + MicroflowName1, e1);
}
scheduledEvent1.setLastRun(end);
try {
if (!active || Thread.currentThread().isInterrupted()) return;
scheduledEvent1.commit();
} catch (CoreException e1) {
logger.error("Error committing updated ScheduledEvent record in " + MicroflowName1, e1);
}
logger.debug("Executed dynamic scheduled event microflow " + MicroflowName1 + " in " + millis + " ms.");
}
}
}
|
3e171528fdc2d91b70908a44916e0755c0acc958 | 2,181 | java | Java | src/main/java/gutenberg/font/FontAwesome.java | Arnauld/gutenberg | 18d761ddba378ee58a3f3dc6316f66742df8d985 | [
"MIT"
] | 2 | 2015-05-22T07:32:42.000Z | 2016-10-31T22:09:57.000Z | src/main/java/gutenberg/font/FontAwesome.java | moritzfl/gutenberg | fa9deb6a440120f1f58f48860e0cf11cb63ce7ad | [
"MIT"
] | 2 | 2019-02-09T11:06:17.000Z | 2019-02-13T11:44:05.000Z | src/main/java/gutenberg/font/FontAwesome.java | moritzfl/gutenberg | fa9deb6a440120f1f58f48860e0cf11cb63ce7ad | [
"MIT"
] | 3 | 2015-02-25T03:05:31.000Z | 2019-02-09T09:49:05.000Z | 33.045455 | 90 | 0.62586 | 9,831 | package gutenberg.font;
import com.google.common.collect.FluentIterable;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <a href="http://twitter.com/aloyer">@aloyer</a>
*/
public class FontAwesome {
public static FontAwesome getInstance() {
return new FontAwesome().loadVariablesFromResources("/font/variables.less");
}
private Map<String, String> codeByMap = new ConcurrentHashMap<String, String>(512);
protected static Pattern variablePattern() {
// @fa-var-adjust: "\f042";
return Pattern.compile("@fa\\-var\\-([^:]+):\\s+\"\\\\([^\"]+)\";");
}
protected FontAwesome loadVariablesFromResources(String resourcePath) {
InputStream in = getClass().getResourceAsStream(resourcePath);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8"));
String line;
Pattern variable = variablePattern();
while ((line = reader.readLine()) != null) {
Matcher matcher = variable.matcher(line);
if (matcher.matches()) {
String key = matcher.group(1);
String wat = matcher.group(2);
char character = (char) Integer.parseInt(wat, 16);
codeByMap.put(key, String.valueOf(character));
}
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("We're in trouble!", e);
} catch (IOException e) {
throw new RuntimeException("Failed to load variables definition for font", e);
} finally {
IOUtils.closeQuietly(in);
}
return this;
}
public String get(String key) {
return codeByMap.get(key);
}
public FluentIterable<String> keys() {
return FluentIterable.from(codeByMap.keySet());
}
}
|
3e17156a18157afcda696a59b461acb312682a36 | 3,069 | java | Java | sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/models/MabJobExtendedInfo.java | luisCavalcantiDev/azure-sdk-for-java | e4b9f41f4ba695fef58112401bc85ca64abd760f | [
"MIT"
] | 1 | 2022-01-08T06:43:30.000Z | 2022-01-08T06:43:30.000Z | sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/models/MabJobExtendedInfo.java | luisCavalcantiDev/azure-sdk-for-java | e4b9f41f4ba695fef58112401bc85ca64abd760f | [
"MIT"
] | null | null | null | sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/models/MabJobExtendedInfo.java | luisCavalcantiDev/azure-sdk-for-java | e4b9f41f4ba695fef58112401bc85ca64abd760f | [
"MIT"
] | null | null | null | 28.95283 | 94 | 0.667644 | 9,832 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.recoveryservicesbackup.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
/** Additional information for the MAB workload-specific job. */
@Fluent
public final class MabJobExtendedInfo {
/*
* List of tasks for this job.
*/
@JsonProperty(value = "tasksList")
private List<MabJobTaskDetails> tasksList;
/*
* The job properties.
*/
@JsonProperty(value = "propertyBag")
@JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS)
private Map<String, String> propertyBag;
/*
* Non localized error message specific to this job.
*/
@JsonProperty(value = "dynamicErrorMessage")
private String dynamicErrorMessage;
/**
* Get the tasksList property: List of tasks for this job.
*
* @return the tasksList value.
*/
public List<MabJobTaskDetails> tasksList() {
return this.tasksList;
}
/**
* Set the tasksList property: List of tasks for this job.
*
* @param tasksList the tasksList value to set.
* @return the MabJobExtendedInfo object itself.
*/
public MabJobExtendedInfo withTasksList(List<MabJobTaskDetails> tasksList) {
this.tasksList = tasksList;
return this;
}
/**
* Get the propertyBag property: The job properties.
*
* @return the propertyBag value.
*/
public Map<String, String> propertyBag() {
return this.propertyBag;
}
/**
* Set the propertyBag property: The job properties.
*
* @param propertyBag the propertyBag value to set.
* @return the MabJobExtendedInfo object itself.
*/
public MabJobExtendedInfo withPropertyBag(Map<String, String> propertyBag) {
this.propertyBag = propertyBag;
return this;
}
/**
* Get the dynamicErrorMessage property: Non localized error message specific to this job.
*
* @return the dynamicErrorMessage value.
*/
public String dynamicErrorMessage() {
return this.dynamicErrorMessage;
}
/**
* Set the dynamicErrorMessage property: Non localized error message specific to this job.
*
* @param dynamicErrorMessage the dynamicErrorMessage value to set.
* @return the MabJobExtendedInfo object itself.
*/
public MabJobExtendedInfo withDynamicErrorMessage(String dynamicErrorMessage) {
this.dynamicErrorMessage = dynamicErrorMessage;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (tasksList() != null) {
tasksList().forEach(e -> e.validate());
}
}
}
|
3e1715efd823c2c374873a5faea2b6762301a863 | 2,318 | java | Java | sdk/storagecache/azure-resourcemanager-storagecache/src/main/java/com/azure/resourcemanager/storagecache/models/CachesListResult.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/storagecache/azure-resourcemanager-storagecache/src/main/java/com/azure/resourcemanager/storagecache/models/CachesListResult.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/storagecache/azure-resourcemanager-storagecache/src/main/java/com/azure/resourcemanager/storagecache/models/CachesListResult.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 28.268293 | 120 | 0.652718 | 9,833 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storagecache.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.storagecache.fluent.models.CacheInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Result of the request to list Caches. It contains a list of Caches and a URL link to get the next set of results. */
@Fluent
public final class CachesListResult {
@JsonIgnore private final ClientLogger logger = new ClientLogger(CachesListResult.class);
/*
* URL to get the next set of Cache list results, if there are any.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/*
* List of Caches.
*/
@JsonProperty(value = "value")
private List<CacheInner> value;
/**
* Get the nextLink property: URL to get the next set of Cache list results, if there are any.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: URL to get the next set of Cache list results, if there are any.
*
* @param nextLink the nextLink value to set.
* @return the CachesListResult object itself.
*/
public CachesListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Get the value property: List of Caches.
*
* @return the value value.
*/
public List<CacheInner> value() {
return this.value;
}
/**
* Set the value property: List of Caches.
*
* @param value the value value to set.
* @return the CachesListResult object itself.
*/
public CachesListResult withValue(List<CacheInner> value) {
this.value = value;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
|
3e1716bffca1ff4fed3fedb159001727e4be8880 | 1,479 | java | Java | src/skaro/pokedex/data_processor/LearnMethodData.java | SirSkaro/Pokedex | e91f44ad8625d3c3509c43d7c4b17bc8029a9034 | [
"Apache-2.0"
] | 23 | 2017-11-09T00:45:49.000Z | 2022-03-11T07:02:15.000Z | src/skaro/pokedex/data_processor/LearnMethodData.java | Tominous/Pokedex | e91f44ad8625d3c3509c43d7c4b17bc8029a9034 | [
"Apache-2.0"
] | null | null | null | src/skaro/pokedex/data_processor/LearnMethodData.java | Tominous/Pokedex | e91f44ad8625d3c3509c43d7c4b17bc8029a9034 | [
"Apache-2.0"
] | 11 | 2018-12-01T02:03:06.000Z | 2022-02-21T12:33:13.000Z | 29.58 | 90 | 0.761325 | 9,834 | package skaro.pokedex.data_processor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import skaro.pokedex.core.ICachedData;
import skaro.pokedex.services.PokeFlexService;
import skaro.pokeflex.api.Endpoint;
import skaro.pokeflex.api.PokeFlexRequest;
import skaro.pokeflex.api.Request;
import skaro.pokeflex.objects.move_learn_method.MoveLearnMethod;
public class LearnMethodData implements ICachedData
{
private final Map<String, MoveLearnMethod> methodMap;
public LearnMethodData(PokeFlexService factory)
{
methodMap = new HashMap<String, MoveLearnMethod>();
initialize(factory);
}
@Override
public MoveLearnMethod getByName(String name)
{
return methodMap.get(name);
}
private void initialize(PokeFlexService factory)
{
List<PokeFlexRequest> concurrentRequests = new ArrayList<>();
System.out.println("[LearnMethodData] Getting Method data from external API...");
for(int i = 1; i < 11; i++)
concurrentRequests.add(new Request(Endpoint.MOVE_LEARN_METHOD, Integer.toString(i)));
factory.createFlexObjects(concurrentRequests, factory.getScheduler())
.ofType(MoveLearnMethod.class)
.doOnNext(learnMethod -> methodMap.put(learnMethod.getName(), learnMethod))
.subscribe(value -> System.out.println("[LearnMethodData] Cached data"),
error -> {
System.out.println("[LearnMethodData] Unable to get all Methods from external API");
System.exit(1);
});
}
}
|
3e17170dcda0a0e15e1de80661028cfd9c7555ae | 5,121 | java | Java | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/cache/SharedProcessor.java | anurag-rajawat/kubernetes-client | 45aab32b12e131c709b21813f5b4b04f51b8cd2d | [
"Apache-2.0"
] | null | null | null | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/cache/SharedProcessor.java | anurag-rajawat/kubernetes-client | 45aab32b12e131c709b21813f5b4b04f51b8cd2d | [
"Apache-2.0"
] | 62 | 2021-11-23T10:17:03.000Z | 2022-03-31T17:11:37.000Z | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/impl/cache/SharedProcessor.java | anurag-rajawat/kubernetes-client | 45aab32b12e131c709b21813f5b4b04f51b8cd2d | [
"Apache-2.0"
] | null | null | null | 29.947368 | 132 | 0.683656 | 9,835 | /**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.informers.impl.cache;
import io.fabric8.kubernetes.client.informers.ResourceEventHandler;
import io.fabric8.kubernetes.client.utils.internal.SerialExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* SharedProcessor class manages all the registered ProcessListener and distributes
* notifications.
*
* This has been taken from official-client:
* https://github.com/kubernetes-client/java/blob/master/util/src/main/java/io/kubernetes/client/informer/cache/SharedProcessor.java
*
* <br>
* Modified to simplify threading
*/
public class SharedProcessor<T> {
private static final Logger log = LoggerFactory.getLogger(SharedProcessor.class);
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final List<ProcessorListener<T>> listeners = new ArrayList<>();
private final List<ProcessorListener<T>> syncingListeners = new ArrayList<>();
private final SerialExecutor executor;
public SharedProcessor() {
this(Runnable::run);
}
public SharedProcessor(Executor executor) {
this.executor = new SerialExecutor(executor);
}
/**
* Adds the specific processorListener
*
* @param processorListener specific processor listener
*/
public void addListener(final ProcessorListener<T> processorListener) {
lock.writeLock().lock();
try {
this.listeners.add(processorListener);
if (processorListener.isReSync()) {
this.syncingListeners.add(processorListener);
}
} finally {
lock.writeLock().unlock();
}
}
/**
* Distribute the object amount listeners.
*
* @param obj specific obj
* @param isSync whether in sync or not
*/
public void distribute(ProcessorListener.Notification<T> obj, boolean isSync) {
distribute(l -> l.add(obj), isSync);
}
/**
* Distribute the operation to the respective listeners
*/
public void distribute(Consumer<ProcessorListener<T>> operation, boolean isSync) {
// obtain the list to call outside before submitting
lock.readLock().lock();
List<ProcessorListener<T>> toCall;
try {
if (isSync) {
toCall = new ArrayList<>(syncingListeners);
} else {
toCall = new ArrayList<>(listeners);
}
} finally {
lock.readLock().unlock();
}
try {
executor.execute(() -> {
for (ProcessorListener<T> listener : toCall) {
try {
operation.accept(listener);
} catch (Exception ex) {
log.error("Failed invoking {} event handler: {}", listener.getHandler(), ex.getMessage(), ex);
}
}
});
} catch (RejectedExecutionException e) {
// do nothing
}
}
public boolean shouldResync() {
lock.writeLock().lock();
boolean resyncNeeded = false;
try {
this.syncingListeners.clear();
ZonedDateTime now = ZonedDateTime.now();
for (ProcessorListener<T> listener : this.listeners) {
if (listener.shouldResync(now)) {
resyncNeeded = true;
this.syncingListeners.add(listener);
listener.determineNextResync(now);
}
}
} finally {
lock.writeLock().unlock();
}
return resyncNeeded;
}
public void stop() {
executor.shutdownNow();
lock.writeLock().lock();
try {
syncingListeners.clear();
listeners.clear();
} finally {
lock.writeLock().unlock();
}
}
/**
* Adds a new listener. When running this will pause event distribution until
* the new listener has received an initial set of add events
*/
public ProcessorListener<T> addProcessorListener(ResourceEventHandler<? super T> handler, long resyncPeriodMillis,
Supplier<Collection<T>> initialItems) {
lock.writeLock().lock();
try {
ProcessorListener<T> listener = new ProcessorListener<>(handler, resyncPeriodMillis);
for (T item : initialItems.get()) {
listener.add(new ProcessorListener.AddNotification<>(item));
}
addListener(listener);
return listener;
} finally {
lock.writeLock().unlock();
}
}
}
|
3e171743765956f38c29541cd5097391ca486c37 | 1,370 | java | Java | app/src/main/java/com/aerolitec/SMXL/tools/RoundedTransformation.java | clvacher/SMXL | 09f017b3fd9c89abd2e2eda8d66c1cf790b48923 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aerolitec/SMXL/tools/RoundedTransformation.java | clvacher/SMXL | 09f017b3fd9c89abd2e2eda8d66c1cf790b48923 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aerolitec/SMXL/tools/RoundedTransformation.java | clvacher/SMXL | 09f017b3fd9c89abd2e2eda8d66c1cf790b48923 | [
"Apache-2.0"
] | null | null | null | 29.782609 | 134 | 0.721898 | 9,836 | package com.aerolitec.SMXL.tools;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import com.squareup.picasso.Transformation;
public class RoundedTransformation
implements Transformation
{
public String key()
{
return "circle";
}
public Bitmap transform(Bitmap paramBitmap)
{
int i = Math.min(paramBitmap.getWidth(), paramBitmap.getHeight());
Bitmap localBitmap1 = Bitmap.createBitmap(paramBitmap, (paramBitmap.getWidth() - i) / 2, (paramBitmap.getHeight() - i) / 2, i, i);
if (localBitmap1 != paramBitmap) {
paramBitmap.recycle();
}
Bitmap localBitmap2 = Bitmap.createBitmap(i, i, paramBitmap.getConfig());
Canvas localCanvas = new Canvas(localBitmap2);
Paint localPaint = new Paint();
localPaint.setShader(new BitmapShader(localBitmap1, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
localPaint.setAntiAlias(true);
float f = i / 2.0F;
localCanvas.drawCircle(f, f, f, localPaint);
localBitmap1.recycle();
return localBitmap2;
}
}
/* Location: C:\Users\HPCorp\Desktop\SMXL\dex2jar-0.0.9.15\classes-dex2jar.jar
* Qualified Name: com.aerolitec.smxl.tools.RoundedTransformation
* JD-Core Version: 0.7.0.1
*/ |
3e17177a503a7881a9fba2b98a36044fbfb3b9b1 | 16,239 | java | Java | src/dspace-api/src/globus/java/org/dspace/handle/HandleServerIdentifierProvider.java | globus/globus-publish-dspace | ed3cc2e6b522ecb60fb6a16ab6bf365690dce04e | [
"Apache-2.0"
] | null | null | null | src/dspace-api/src/globus/java/org/dspace/handle/HandleServerIdentifierProvider.java | globus/globus-publish-dspace | ed3cc2e6b522ecb60fb6a16ab6bf365690dce04e | [
"Apache-2.0"
] | 8 | 2016-12-12T17:58:50.000Z | 2019-02-13T22:38:16.000Z | src/dspace-api/src/globus/java/org/dspace/handle/HandleServerIdentifierProvider.java | globus/globus-publish-dspace | ed3cc2e6b522ecb60fb6a16ab6bf365690dce04e | [
"Apache-2.0"
] | 3 | 2016-11-23T21:27:29.000Z | 2018-01-24T01:30:27.000Z | 31.841176 | 142 | 0.613461 | 9,837 | /**
* This file is a modified version of a DSpace file.
* All modifications are subject to the following copyright and license.
*
* Copyright 2016 University of Chicago. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dspace.handle;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.globus.Globus;
import org.dspace.globus.GlobusHandleClient;
import org.dspace.globus.configuration.BaseConfigurable;
import org.dspace.globus.configuration.Configurable;
import org.dspace.globus.configuration.GlobusConfigurationManager;
import org.dspace.identifier.HandleIdentifierProvider;
import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.IdentifierNotFoundException;
import org.dspace.identifier.IdentifierNotResolvableException;
import org.dspace.identifier.IdentifierProvider;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
/**
*
*/
public class HandleServerIdentifierProvider extends HandleIdentifierProvider
implements Configurable
{
private static final Logger logger = Logger
.getLogger(HandleServerIdentifierProvider.class);
private static final String CFG_AUTH_INDEX = "handle.auth-index";
private static final String CFG_KEY_PASSCODE = "handle.key-passcode";
private static final String CFG_PRIVATE_KEY = "handle.private-key";
private static final String CFG_PREFIX = "handle.prefix";
private static final String CFG_NAMESPACE = "handle.namespace";
public static final String CFG_RESOLVER = "handle.resolver";
/**
* Make this globus so we can reference it in call to
* {@link GlobusConfigurationManager#getProperty(Context, DSpaceObject, org.dspace.globus.configuration.Configurable.ConfigurableProperty)
* } to handle the default value for us
*/
private static final ConfigurableProperty RESOLVER_PROPERTY = new ConfigurableProperty(
CFG_RESOLVER, "Resolver base URL ", "http://hdl.handle.net/",
DataType.STRING, "Base URL for resolving identifier", true);
private static final ConfigurableProperty[] props = new ConfigurableProperty[] {
IdentifierProvider.IdentifierConfigProp,
new ConfigurableProperty(CFG_PREFIX, "Prefix", "123456789",
DataType.STRING, "Handle Prefix", true),
new ConfigurableProperty(CFG_NAMESPACE, "Namespace", null, DataType.STRING, "Handle namespace", true),
new ConfigurableProperty(CFG_PRIVATE_KEY,
"Administration Private Key", null, DataType.BLOB, "Base64 encoded string of the admin. private key", true),
new ConfigurableProperty(CFG_KEY_PASSCODE, "Private Key Passcode",
null, DataType.PASSWORD, "Passcode for the private key", true),
new ConfigurableProperty(CFG_AUTH_INDEX, "Authorization Index",
300, DataType.INTEGER, "Auth. index for provided admin. key", true), RESOLVER_PROPERTY };
private Map<String, GlobusHandleClient> clientMap;
private BaseConfigurable config;
protected String[] supportedPrefixes = new String[]{"info:hdl", "hdl", "http://hdl", "https://hdl"};
/**
*
*/
public HandleServerIdentifierProvider()
{
config = new BaseConfigurable("Handle", props);
}
// modified to not match all http:// identifiers
public boolean supports(String identifier)
{
for(String prefix : supportedPrefixes){
if(identifier.startsWith(prefix))
{
return true;
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.dspace.globus.configuration.Configurable#getName()
*/
@Override
public String getName()
{
return config.getName();
}
/*
* (non-Javadoc)
*
* @see org.dspace.globus.configuration.Configurable#getPropIds()
*/
@Override
public Iterator<String> getPropIds()
{
return config.getPropIds();
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.globus.configuration.Configurable#getProperty(java.lang.String
* )
*/
@Override
public ConfigurableProperty getProperty(String id)
{
return config.getProperty(id);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#reserve(org.dspace.core
* .Context, org.dspace.content.DSpaceObject, java.lang.String)
*/
@Override
public void reserve(Context context, DSpaceObject dso, String identifier)
{
// TODO Auto-generated method stub
super.reserve(context, dso, identifier);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#resolve(org.dspace.core
* .Context, java.lang.String, java.lang.String[])
*/
@Override
public DSpaceObject resolve(Context context, String identifier,
String... attributes)
{
// TODO Auto-generated method stub
return super.resolve(context, identifier, attributes);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#lookup(org.dspace.core
* .Context, org.dspace.content.DSpaceObject)
*/
@Override
public String lookup(Context context, DSpaceObject dso)
throws IdentifierNotFoundException,
IdentifierNotResolvableException
{
// TODO Auto-generated method stub
return super.lookup(context, dso);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#delete(org.dspace.core
* .Context, org.dspace.content.DSpaceObject, java.lang.String)
*/
@Override
public void delete(Context context, DSpaceObject dso, String identifier)
throws IdentifierException
{
// TODO Auto-generated method stub
super.delete(context, dso, identifier);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#delete(org.dspace.core
* .Context, org.dspace.content.DSpaceObject)
*/
@Override
public void delete(Context context, DSpaceObject dso)
throws IdentifierException
{
// TODO Auto-generated method stub
super.delete(context, dso);
}
/**
* This method is copied from the parent class from dspace so we can
* override the call to populateHandleMetadata with the local context to get
* value from this instance's resolver.
*/
@Override
public String register(Context context, DSpaceObject dso)
{
try
{
String id = mint(context, dso);
// move canonical to point the latest version
if (dso instanceof Item)
{
Item item = (Item) dso;
populateHandleMetadata(context, item, id);
}
return id;
}
catch (Exception e)
{
logger.error(LogManager.getHeader(context,
"Error while attempting to create handle", "Item id: "
+ dso.getID()), e);
throw new RuntimeException(
"Error while attempting to create identifier for Item id: "
+ dso.getID(), e);
}
}
@Override
public String mint(Context context, DSpaceObject dso) {
String identifier = super.mint(context, dso);
if (dso instanceof Item)
{
Item item = (Item) dso;
identifier = getCanonicalForm(context, item, identifier);
}
return identifier;
}
/**
* This method is copied from the parent class from dspace so we can
* override the call to populateHandleMetadata with the local context to get
* value from this instance's resolver.
*/
@Override
public void register(Context context, DSpaceObject dso, String identifier)
{
try
{
createNewIdentifier(context, dso, identifier);
if (dso instanceof Item)
{
Item item = (Item) dso;
populateHandleMetadata(context, item, identifier);
}
}
catch (Exception e)
{
logger.error(LogManager.getHeader(context,
"Error while attempting to create handle", "Item id: "
+ dso.getID()), e);
throw new RuntimeException(
"Error while attempting to create identifier for Item id: "
+ dso.getID(), e);
}
}
private synchronized GlobusHandleClient getHandleClientForObject(
Context context, DSpaceObject dso)
{
String prefix = getPrefixForObject(context, dso);
if (clientMap == null)
{
clientMap = new HashMap<String, GlobusHandleClient>();
}
GlobusHandleClient ghc = clientMap.get(prefix);
if (ghc == null)
{
byte[] privKey = (byte[]) getConfigProperty(
context, dso, config.getProperty(CFG_PRIVATE_KEY));
String passcode = getKeyPasscodeForObject(context, dso);
/*
* String passcode = GlobusConfigurationManager.getProperty(context,
* CFG_KEY_PASSCODE, dso);
*/
String authIndexStr = getConfigProperty(
context, CFG_AUTH_INDEX, dso);
int authIndex = Integer.valueOf(authIndexStr);
try
{
ghc = new GlobusHandleClient(privKey, null, authIndex,
passcode, prefix);
clientMap.put(prefix, ghc);
}
catch (Exception e)
{
logger.error(
"Failed to get client handle for prefix " + prefix, e);
}
}
return ghc;
}
/**
* Different objects stored in different collections may use different
* prefixes. For now, we use the global value set in the config file.
*
* @param context
* @param dso
* @return
*/
private String getPrefixForObject(Context context, DSpaceObject dso)
{
String prefix = getConfigProperty(context,
CFG_PREFIX, dso);
return prefix;
}
private String getNamespaceForObject(Context context, DSpaceObject dso)
{
String namespace = getConfigProperty(context, CFG_NAMESPACE, dso);
return namespace;
}
/**
* @param context
* @param dso
* @return
*/
private String getKeyPasscodeForObject(Context context, DSpaceObject dso)
{
String passcode = getConfigProperty(context,
CFG_KEY_PASSCODE, dso);
return passcode;
}
/**
* @param context
* @param dso
* @return
*/
private String getKeyfileForObject(Context context, DSpaceObject dso)
{
String keyFile = Globus
.getGlobusConfigProperty("handle.private-keyfile");
return keyFile;
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.identifier.HandleIdentifierProvider#createNewIdentifier(org
* .dspace.core.Context, org.dspace.content.DSpaceObject, java.lang.String)
*/
@Override
protected String createNewIdentifier(Context context, DSpaceObject dso,
String handleId) throws SQLException
{
if (handleId == null)
{
handleId = createHandleId(context, dso);
}
TableRow handleRow = findHandleInternal(context, handleId);
// Create the new row in the handle table
if (handleRow == null)
{
handleRow = DatabaseManager.create(context, "Handle");
}
modifyHandleRecord(context, dso, handleRow, handleId);
GlobusHandleClient ghc = getHandleClientForObject(context, dso);
if (ghc != null)
{
String urlString = HandleManager.resolveToURL(context, handleId);
if (urlString != null)
{
URL url;
try
{
url = new URL(urlString);
ghc.createHandle(handleId, url);
}
catch (Exception e)
{
logger.error("Failed to create handle for object " + dso, e);
}
}
}
return handleId;
}
protected static String getCanonicalForm(Context context, Item item,
String handle)
{
// Let the admin define a new prefix, if not then we'll use the
// CNRI default. This allows the admin to use "hdl:" if they want to or
// use a locally branded prefix handle.myuni.edu.
String handlePrefix = (String) getConfigProperty(context, item, RESOLVER_PROPERTY);
/*
String handlePrefix = ConfigurationManager
.getProperty("handle.canonical.prefix");
*/
if (handlePrefix == null || handlePrefix.length() == 0)
{
handlePrefix = "http://hdl.handle.net/";
}
return handlePrefix + handle;
}
private final static long XorMask = 0x88888888L;
/**
* @param dso
* @return
*/
private String createHandleId(Context context, DSpaceObject dso)
{
int objId = dso.getID();
int objType = dso.getType();
int serverId = Globus.getServerId();
long idLong = serverId + (objType << 16) + (objId << 32);
String suffix = longToAlphaNumeric(idLong ^ XorMask);
String namespace = getNamespaceForObject(context, dso);
if (namespace != null && !"".equals(namespace)) {
suffix = namespace + "_" + suffix;
}
return getPrefixForObject(context, dso) + "/" + suffix;
}
private final static String charMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/**
* @param bitRep
* @return
*/
private static String longToAlphaNumeric(long bitRep)
{
StringBuffer buf = new StringBuffer();
int numChars = charMap.length();
while (bitRep > 0)
{
// System.out.println("BitRep: " + bitRep);
buf.append(charMap.charAt((int) (bitRep % numChars)));
bitRep = bitRep / numChars;
}
return buf.toString();
}
protected void populateHandleMetadata(Context context, Item item,
String handle) throws SQLException, IOException, AuthorizeException
{
String handleref = getCanonicalForm(context, item, handle);
// Add handle as identifier.uri DC value.
// First check that identifier doesn't already exist.
boolean identifierExists = false;
DCValue[] identifiers = item.getDC("identifier", "uri", Item.ANY);
for (DCValue identifier : identifiers)
{
if (handleref.equals(identifier.value))
{
identifierExists = true;
}
}
if (!identifierExists)
{
item.addDC("identifier", "uri", null, handleref);
}
}
}
|
3e1717b1f4d562c8de92b66ccd25b0d6d96de219 | 14,224 | java | Java | tools/java/src/intra/Intra2.java | istn2/daala | d10a875282e69c56fec3a3584bf06709e00edabe | [
"BSD-2-Clause"
] | 577 | 2015-01-01T16:26:42.000Z | 2022-03-12T22:38:24.000Z | tools/java/src/intra/Intra2.java | istn2/daala | d10a875282e69c56fec3a3584bf06709e00edabe | [
"BSD-2-Clause"
] | 214 | 2015-02-05T15:52:11.000Z | 2021-10-06T18:23:17.000Z | tools/java/src/intra/Intra2.java | istn2/daala | d10a875282e69c56fec3a3584bf06709e00edabe | [
"BSD-2-Clause"
] | 123 | 2015-01-11T18:59:45.000Z | 2022-01-26T15:44:16.000Z | 29.26749 | 170 | 0.670627 | 9,838 | /*Daala video codec
Copyright (c) 2012 Daala project contributors. 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.
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 intra;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import javax.imageio.ImageIO;
import org.ejml.alg.dense.linsol.LinearSolver;
import org.ejml.alg.dense.linsol.svd.SolvePseudoInverseSvd;
import org.ejml.data.DenseMatrix64F;
public class Intra2 {
public static final int MODES=10;
public static final int DISK_BLOCK_SIZE=4096;
public static final int STEPS=30;
public static final int BITS_PER_COEFF=6;
public static final double MAX_CG=BITS_PER_COEFF*-10*Math.log10(0.5);
public static final boolean USE_CG=true;
public static final boolean UPDATE_WEIGHT=false;
public static double DC_WEIGHT=66.07307086571254;
public static final int[] MODE_COLORS={
0xFF000000,
0xFFFFFFFF,
0xFFFF0000,
0xFFFFBF00,
0xFF80FF00,
0xFF00FF3F,
0xFF00FFFF,
0xFF0040FF,
0xFF7F00FF,
0xFFFF00C0,
};
protected final int B_SZ;
protected final String DATA_FOLDER;
protected final int[] INDEX;
class ModeData {
protected long numBlocks;
protected double weightTotal;
protected double[] mean=new double[2*B_SZ*2*B_SZ];
protected double[][] covariance=new double[2*B_SZ*2*B_SZ][2*B_SZ*2*B_SZ];
protected double[][] beta_1=new double[3*B_SZ*B_SZ][B_SZ*B_SZ];
protected double[] beta_0=new double[B_SZ*B_SZ];
protected double[] mse=new double[B_SZ*B_SZ];
protected void addBlock(double _weight,int[] _data) {
update(_weight,_data);
numBlocks++;
}
protected void removeBlock(double _weight,int[] _data) {
update(-_weight,_data);
numBlocks--;
}
private void update(double _weight,int[] _data) {
double[] delta=new double[2*B_SZ*2*B_SZ];
weightTotal+=_weight;
// online update of the mean
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
delta[i]=_data[INDEX[i]]-mean[i];
mean[i]+=delta[i]*_weight/weightTotal;
}
// online update of the covariance
for (int j=0;j<2*B_SZ*2*B_SZ;j++) {
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
covariance[j][i]+=delta[j]*delta[i]*_weight*(weightTotal-_weight)/weightTotal;
}
}
}
protected void computeBetas() {
DenseMatrix64F xtx=new DenseMatrix64F(3*B_SZ*B_SZ,3*B_SZ*B_SZ);
DenseMatrix64F xty=new DenseMatrix64F(3*B_SZ*B_SZ,B_SZ*B_SZ);
DenseMatrix64F b=new DenseMatrix64F(3*B_SZ*B_SZ,B_SZ*B_SZ);
// extract X^T*X and X^T*Y
for (int j=0;j<3*B_SZ*B_SZ;j++) {
for (int i=0;i<3*B_SZ*B_SZ;i++) {
xtx.set(j,i,covariance[j][i]/weightTotal);
}
for (int i=0;i<B_SZ*B_SZ;i++) {
xty.set(j,i,covariance[j][3*B_SZ*B_SZ+i]/weightTotal);
}
}
// compute b = (X^T*X)^-1 * X^T*Y
LinearSolver<DenseMatrix64F> solver=new SolvePseudoInverseSvd();
solver.setA(xtx);
solver.solve(xty,b);
// extract beta_1
// compute beta_0 = Y - X * beta_1
// compute MSE = Y^T*Y - Y^T*X * beta_1
for (int i=0;i<B_SZ*B_SZ;i++) {
beta_0[i]=mean[3*B_SZ*B_SZ+i];
mse[i]=covariance[3*B_SZ*B_SZ+i][3*B_SZ*B_SZ+i]/weightTotal;
for (int j=0;j<3*B_SZ*B_SZ;j++) {
beta_1[j][i]=b.get(j,i);
beta_0[i]-=beta_1[j][i]*mean[j];
mse[i]-=covariance[3*B_SZ*B_SZ+i][j]/weightTotal*beta_1[j][i];
}
}
}
protected double msePerCoeff(double[] _mse) {
double total_mse=0;
for (int j=0;j<B_SZ*B_SZ;j++) {
total_mse+=_mse[j];
}
return(total_mse/(B_SZ*B_SZ));
}
protected double cgPerCoeff(double[] _mse) {
double total_cg=0;
for (int j=0;j<B_SZ*B_SZ;j++) {
double cg=-10*Math.log10(_mse[j]/(covariance[3*B_SZ*B_SZ+j][3*B_SZ*B_SZ+j]/weightTotal));
/*if (cg>=MAX_CG) {
cg=MAX_CG;
}*/
total_cg+=cg;
}
return(total_cg/(B_SZ*B_SZ));
}
protected double predError(int[] _data,int _y) {
double pred=beta_0[_y];
for (int i=0;i<3*B_SZ*B_SZ;i++) {
pred+=_data[INDEX[i]]*beta_1[i][_y];
}
return(Math.abs(_data[INDEX[3*B_SZ*B_SZ+_y]]-pred));
}
protected void mseUpdateHelper(int[] _data,double _weight,double[] _mse) {
for (int j=0;j<B_SZ*B_SZ;j++) {
double e=predError(_data,j);
double se=e*e;
double wt=weightTotal+_weight;
double delta=se-mse[j];
_mse[j]=mse[j]+delta*_weight/wt;
}
}
protected void mseUpdate(int[] _data,double _weight) {
mseUpdateHelper(_data,_weight,mse);
}
protected double deltaBits(int[] _data,double _weight) {
double old_cg=cgPerCoeff(mse);
double[] tmp_mse=new double[B_SZ*B_SZ];
mseUpdateHelper(_data,_weight,tmp_mse);
update(_weight,_data);
double cg=cgPerCoeff(tmp_mse);
update(-_weight,_data);
return((weightTotal+_weight)*cg-weightTotal*old_cg);
}
};
public Intra2(int _blockSize,String _dataFolder) {
B_SZ=_blockSize;
DATA_FOLDER=_dataFolder;
INDEX=new int[4*B_SZ*B_SZ];
for (int i=0,j=0;j<B_SZ;j++) {
for (int k=0;k<B_SZ;k++) {
INDEX[i+0*B_SZ*B_SZ]=2*B_SZ*j+k;
INDEX[i+1*B_SZ*B_SZ]=2*B_SZ*j+(B_SZ+k);
INDEX[i+2*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+k;
INDEX[i+3*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+(B_SZ+k);
i++;
}
}
}
protected File[] getFiles() throws IOException {
File folder=new File(DATA_FOLDER);
File[] coeffFiles=folder.listFiles(new FilenameFilter() {
public boolean accept(File _file,String _filename) {
return(_filename.endsWith(".coeffs"));
}
});
if (coeffFiles==null) {
return(null);
}
Arrays.sort(coeffFiles);
File[] binFiles=new File[coeffFiles.length];
for (int i=0;i<coeffFiles.length;i++) {
binFiles[i]=new File(coeffFiles[i].getPath()+".bin");
if (!binFiles[i].exists()) {
System.out.println("Converting "+coeffFiles[i].getPath()+" to "+binFiles[i].getPath());
Scanner s=new Scanner(new BufferedInputStream(new FileInputStream(coeffFiles[i]),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(binFiles[i]),DISK_BLOCK_SIZE));
while (s.hasNextShort()) {
dos.writeShort(s.nextShort());
}
s.close();
dos.close();
}
}
return(binFiles);
}
protected ModeData[] loadData(File[] _files) throws IOException {
// initialize the modes
ModeData modeData[]=new ModeData[MODES];
for (int i=0;i<MODES;i++) {
modeData[i]=new ModeData();
}
double weight_sum=0;
long block_sum=0;
for (File file : _files) {
System.out.println("Loading "+file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step00.mode"),DISK_BLOCK_SIZE));
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
int mode=dis.readShort();
double weight=dis.readShort();
//System.out.println("mode="+mode+" weight="+weight);
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
if (weight>0) {
weight_sum+=weight;
block_sum++;
if (mode==0) {
weight=DC_WEIGHT;
}
modeData[mode].addBlock(weight,data);
}
dos.writeShort(mode);
dos.writeDouble(weight);
rgb[block]=MODE_COLORS[mode];
}
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step00.png"));
dos.close();
dis.close();
}
DC_WEIGHT=weight_sum/block_sum;
System.out.println("DC_WEIGHT="+DC_WEIGHT);
// correct the DC to use DC_WEIGHT
return(modeData);
}
protected void fitData(ModeData[] _modeData) {
// compute betas and MSE
for (int i=0;i<MODES;i++) {
System.out.println("mode "+i);
double[] old_mse=new double[B_SZ*B_SZ];
for (int j=0;j<B_SZ*B_SZ;j++) {
old_mse[j]=_modeData[i].mse[j];
}
_modeData[i].computeBetas();
for (int j=0;j<B_SZ*B_SZ;j++) {
System.out.println(" "+j+": "+old_mse[j]+"\t"+_modeData[i].mse[j]+"\t"+(_modeData[i].mse[j]-old_mse[j]));
}
}
}
protected static final int SPACE=4;
protected void printStats(ModeData[] _modeData) {
double mse_sum=0;
double cg_sum=0;
double weight=0;
for (int i=0;i<MODES;i++) {
double mse=_modeData[i].msePerCoeff(_modeData[i].mse);
double cg=_modeData[i].cgPerCoeff(_modeData[i].mse);
System.out.println(" "+i+": "+_modeData[i].numBlocks+"\t"+_modeData[i].weightTotal+"\t"+mse+"\t"+cg);
mse_sum+=_modeData[i].weightTotal*mse;
cg_sum+=_modeData[i].weightTotal*cg;
weight+=_modeData[i].weightTotal;
}
System.out.println("Total Weight "+weight);
System.out.println("Average MSE "+mse_sum/weight);
System.out.println("Average CG "+cg_sum/weight);
// make a "heat map" using the normalized beta_1
/*int w=SPACE+(2*B_SZ+SPACE)*B_SZ*B_SZ;
int h=SPACE+(2*B_SZ+SPACE)*MODES;
int[] rgb=new int[w*h];
for (int i=0;i<MODES;i++) {
int yoff=SPACE+i*(2*B_SZ+SPACE);
int xoff=SPACE;
for (int j=0;j<B_SZ*B_SZ;j++) {
rgb[w*(yoff+i)+xoff];
}
}*/
}
protected void processData(int step,ModeData[] _modeData,File[] _files) throws IOException {
for (File file : _files) {
System.out.println("Processing "+file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataInputStream dis2=new DataInputStream(new BufferedInputStream(new FileInputStream(file.getPath()+".step"+(step-1<10?"0"+(step-1):step-1)+".mode"),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step"+(step<10?"0"+step:step)+".mode"),DISK_BLOCK_SIZE));
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
if ((block&0x3fff)==0) {
System.out.println(block);
}
// load the data
int mode=dis.readShort();
double weight=dis.readShort();
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
int lastMode=dis2.readShort();
double lastWeight=dis2.readDouble();
if (weight>0) {
if (mode==0) {
weight=DC_WEIGHT;
lastWeight=DC_WEIGHT;
}
// compute error
double[] error=new double[MODES];
double[] cg=new double[MODES];
for (int i=0;i<MODES;i++) {
for (int j=0;j<B_SZ*B_SZ;j++) {
error[i]+=_modeData[i].predError(data,j);
}
if (USE_CG) {
cg[i]=_modeData[i].deltaBits(data,lastMode==i?-weight:weight);
}
}
double best=-Double.MAX_VALUE;
double nextBest=-Double.MAX_VALUE;
for (int j=0;j<MODES;j++) {
// lower SATD is better
double metric=error[lastMode]-error[j];
if (USE_CG) {
// greater CG is better
metric=lastMode==j?0:cg[lastMode]+cg[j];
}
if (metric>best) {
nextBest=best;
best=metric;
mode=j;
}
else {
if (metric>nextBest) {
nextBest=metric;
}
}
}
if (UPDATE_WEIGHT) {
weight=best-nextBest;
}
if (USE_CG) {
_modeData[lastMode].mseUpdate(data,-lastWeight);
_modeData[mode].mseUpdate(data,weight);
}
_modeData[lastMode].removeBlock(lastWeight,data);
_modeData[mode].addBlock(weight,data);
/*if (USE_CG) {
_modeData[lastMode].computeBetas();
_modeData[mode].computeBetas();
}*/
}
dos.writeShort(mode);
dos.writeDouble(weight);
rgb[block]=MODE_COLORS[mode];
}
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step"+(step<10?"0"+step:step)+".png"));
dis.close();
dis2.close();
dos.close();
}
}
public void run() throws Exception {
File[] files=getFiles();
if (files==null) {
System.out.println("No .coeffs files found in "+DATA_FOLDER+" folder. Enable the PRINT_BLOCKS ifdef and run:");
System.out.println(" for f in subset1-y4m/*.y4m; do ./init_intra_maps $f && ./init_intra_xform $f 2> $f.coeffs; done");
System.out.println("Move the *.coeffs files to "+DATA_FOLDER);
return;
}
// load the blocks
ModeData[] modeData=loadData(files);
long start=System.currentTimeMillis();
for (int k=1;k<=STEPS;k++) {
// update model
fitData(modeData);
printStats(modeData);
// reclassify blocks
processData(k,modeData,files);
long now=System.currentTimeMillis();
System.out.println("Step "+k+" took "+((now-start)/1000.0)+"s");
}
}
public static void main(String[] _args) throws Exception {
Intra2 intra=new Intra2(4,"data2");
intra.run();
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.