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
sequence | 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
sequence | 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
sequence | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9245ab89722c74e2341e9feee69a8b66f5754cd3 | 200 | java | Java | Algorithm/src/test/java/com/leetcode/Solution_27Test.java | huangbin082/Bin | 34dc50a1684b23199cfa6517284a6f698c6f910d | [
"Apache-2.0"
] | null | null | null | Algorithm/src/test/java/com/leetcode/Solution_27Test.java | huangbin082/Bin | 34dc50a1684b23199cfa6517284a6f698c6f910d | [
"Apache-2.0"
] | 5 | 2021-05-26T15:03:42.000Z | 2022-01-04T14:30:13.000Z | Algorithm/src/test/java/com/leetcode/Solution_27Test.java | huangbinme/Bin | 6741afde67878cd1e853395817cb9c63e1900e9c | [
"Apache-2.0"
] | null | null | null | 18.181818 | 52 | 0.705 | 1,003,480 | package com.leetcode;
import org.testng.annotations.Test;
public class Solution_27Test {
@Test
public void testRemoveElement() {
Solution_27 solution_27 = new Solution_27();
}
} |
9245acf94dac55779f3716554a700f01963d60f4 | 5,152 | java | Java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/ParameterMetadataMarshaller.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-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/ParameterMetadataMarshaller.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-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/ParameterMetadataMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 59.218391 | 158 | 0.767275 | 1,003,481 | /*
* 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.simplesystemsmanagement.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ParameterMetadataMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ParameterMetadataMarshaller {
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Name").build();
private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Type").build();
private static final MarshallingInfo<String> KEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("KeyId").build();
private static final MarshallingInfo<java.util.Date> LASTMODIFIEDDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastModifiedDate").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<String> LASTMODIFIEDUSER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastModifiedUser").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
private static final MarshallingInfo<String> ALLOWEDPATTERN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AllowedPattern").build();
private static final MarshallingInfo<Long> VERSION_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Version").build();
private static final MarshallingInfo<String> TIER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Tier").build();
private static final MarshallingInfo<List> POLICIES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Policies").build();
private static final MarshallingInfo<String> DATATYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("DataType").build();
private static final ParameterMetadataMarshaller instance = new ParameterMetadataMarshaller();
public static ParameterMetadataMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ParameterMetadata parameterMetadata, ProtocolMarshaller protocolMarshaller) {
if (parameterMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterMetadata.getName(), NAME_BINDING);
protocolMarshaller.marshall(parameterMetadata.getType(), TYPE_BINDING);
protocolMarshaller.marshall(parameterMetadata.getKeyId(), KEYID_BINDING);
protocolMarshaller.marshall(parameterMetadata.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING);
protocolMarshaller.marshall(parameterMetadata.getLastModifiedUser(), LASTMODIFIEDUSER_BINDING);
protocolMarshaller.marshall(parameterMetadata.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(parameterMetadata.getAllowedPattern(), ALLOWEDPATTERN_BINDING);
protocolMarshaller.marshall(parameterMetadata.getVersion(), VERSION_BINDING);
protocolMarshaller.marshall(parameterMetadata.getTier(), TIER_BINDING);
protocolMarshaller.marshall(parameterMetadata.getPolicies(), POLICIES_BINDING);
protocolMarshaller.marshall(parameterMetadata.getDataType(), DATATYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
9245ae415eb06341dd39a0afbc0d68db7ebfed0c | 1,421 | java | Java | ol4gwt-main/src/main/java/org/openlayers/ol/events/RasterSourceEvent.java | iSergio/ol4gwt | 194b91c50fdb9e24d77e239dcb28e758a20b2d06 | [
"Apache-2.0"
] | 1 | 2018-04-26T01:44:52.000Z | 2018-04-26T01:44:52.000Z | ol4gwt-main/src/main/java/org/openlayers/ol/events/RasterSourceEvent.java | iSergio/gwt-ol | 194b91c50fdb9e24d77e239dcb28e758a20b2d06 | [
"Apache-2.0"
] | null | null | null | ol4gwt-main/src/main/java/org/openlayers/ol/events/RasterSourceEvent.java | iSergio/gwt-ol | 194b91c50fdb9e24d77e239dcb28e758a20b2d06 | [
"Apache-2.0"
] | null | null | null | 29.040816 | 86 | 0.705552 | 1,003,482 | /*
* Copyright 2017 iserge.
*
* 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.openlayers.ol.events;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import org.openlayers.ol.Extent;
/**
* @author Serge Silaev aka iSergio <[email protected]>
*/
@JsType(isNative = true, namespace = "ol.source.Raster", name = "Event")
public class RasterSourceEvent extends Event {
/**
* An object made available to all operations. This can be used by operations as a
* storage object (e.g. for calculating statistics).
*/
@JsProperty
public Object data;
/**
* The raster extent.
*/
@JsProperty
public Extent extent;
/**
* The pixel resolution (map units per pixel).
*/
@JsProperty
public double resolution;
@JsConstructor
private RasterSourceEvent() {}
}
|
9245ae67fa70084ef7957479ef169c28280a12f3 | 2,380 | java | Java | common/src/main/java/dev/hophamducnguyen/auto/web/common/pageobject/webadmin/LoginPage.java | hophamducnguyen/web-auto-junit-selenium | 7acc8523a4b6563a885ff2f665fe707020bcb5e5 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/dev/hophamducnguyen/auto/web/common/pageobject/webadmin/LoginPage.java | hophamducnguyen/web-auto-junit-selenium | 7acc8523a4b6563a885ff2f665fe707020bcb5e5 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/dev/hophamducnguyen/auto/web/common/pageobject/webadmin/LoginPage.java | hophamducnguyen/web-auto-junit-selenium | 7acc8523a4b6563a885ff2f665fe707020bcb5e5 | [
"Apache-2.0"
] | null | null | null | 34 | 95 | 0.678992 | 1,003,483 | package dev.hophamducnguyen.auto.web.common.pageobject.webadmin;
import dev.hophamducnguyen.auto.web.common.core.BasePage;
import dev.hophamducnguyen.auto.web.common.core.TestSettings;
import dev.hophamducnguyen.auto.web.common.core.webelement.NWebElement;
import dev.hophamducnguyen.auto.web.common.core.webelement.support.CustomElementFieldDecorator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage extends BasePage {
public LoginPage(WebDriver driver) {
super(driver);
PageFactory.initElements(new CustomElementFieldDecorator(driver), this);
}
public LoginPage(WebDriver driver, TestSettings settings) {
super(driver, settings);
PageFactory.initElements(new CustomElementFieldDecorator(driver), this);
}
@FindBy(css = "body > div > form > button")
private NWebElement btnSignInWithGoogle;
@FindBy(id = "identifierId")
private NWebElement txtGoogleEmail;
@FindBy(name = "password")
private NWebElement txtPassword;
@FindBy(id = "totpPin")
private NWebElement txtTotPin;
@FindBy(xpath = "//*[contains(@id,'Next')]")
private NWebElement btnNext;
@FindBy(name = "email_address")
private NWebElement txtEdgeUserName;
@FindBy(xpath = "//input[@value='Sign In']")
private NWebElement btnEdgeSignIn;
public HomePage logInAsSuperTwoFactor() {
String url = settings.getWebAdminUrl() + "/login.php";
String userName = settings.getAdminUserName();
String password = settings.getAdminPassword();
try {
driver.get(url);
btnSignInWithGoogle.click();
txtGoogleEmail.setText(userName);
btnNext.click();
txtPassword.setText(password);
btnNext.click();
txtTotPin.setText(getTwoFactorCode());
btnNext.click();
txtEdgeUserName.setText(userName);
txtPassword.setText(password);
btnEdgeSignIn.click();
} catch (Exception e) {
logger.info("OTP may have timed out, trying again... {}", e.getMessage());
logInAsSuperTwoFactor();
}
HomePage homePage = new HomePage(driver, settings);
homePage.divSearchImage.waitForVisible();
return homePage;
}
} |
9245aead4ab552590a39b721668cecb7a11d3fc3 | 1,639 | java | Java | sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicesImpl.java | odidev/azure-sdk-for-java | 46f02c1407a92fed7f11bcdb223f998bd9f3e4ce | [
"MIT"
] | 1 | 2021-09-15T16:36:28.000Z | 2021-09-15T16:36:28.000Z | sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicesImpl.java | odidev/azure-sdk-for-java | 46f02c1407a92fed7f11bcdb223f998bd9f3e4ce | [
"MIT"
] | 306 | 2019-09-27T06:41:56.000Z | 2019-10-14T08:19:57.000Z | sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/BlobServicesImpl.java | odidev/azure-sdk-for-java | 46f02c1407a92fed7f11bcdb223f998bd9f3e4ce | [
"MIT"
] | 1 | 2020-08-12T02:32:01.000Z | 2020-08-12T02:32:01.000Z | 37.25 | 112 | 0.779744 | 1,003,484 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.storage.implementation;
import com.azure.resourcemanager.resources.fluentcore.model.implementation.WrapperImpl;
import com.azure.resourcemanager.storage.StorageManager;
import com.azure.resourcemanager.storage.fluent.BlobServicesClient;
import com.azure.resourcemanager.storage.models.BlobServiceProperties;
import com.azure.resourcemanager.storage.models.BlobServices;
import com.azure.resourcemanager.storage.fluent.inner.BlobServicePropertiesInner;
import reactor.core.publisher.Mono;
public class BlobServicesImpl extends WrapperImpl<BlobServicesClient> implements BlobServices {
private final StorageManager manager;
public BlobServicesImpl(StorageManager manager) {
super(manager.inner().getBlobServices());
this.manager = manager;
}
public StorageManager getManager() {
return this.manager;
}
@Override
public BlobServicePropertiesImpl define(String name) {
return wrapModel(name);
}
private BlobServicePropertiesImpl wrapModel(BlobServicePropertiesInner inner) {
return new BlobServicePropertiesImpl(inner, getManager());
}
private BlobServicePropertiesImpl wrapModel(String name) {
return new BlobServicePropertiesImpl(name, this.getManager());
}
@Override
public Mono<BlobServiceProperties> getServicePropertiesAsync(String resourceGroupName, String accountName) {
return inner().getServicePropertiesAsync(resourceGroupName, accountName).map(inner -> wrapModel(inner));
}
}
|
9245af8eb85284bbf5438b8a2276fcb2e28e996d | 2,070 | java | Java | shetland/core/src/main/java/org/n52/shetland/ogc/wps/description/ProcessInputDescriptionContainer.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 19 | 2017-01-13T13:30:32.000Z | 2021-11-27T16:21:42.000Z | shetland/core/src/main/java/org/n52/shetland/ogc/wps/description/ProcessInputDescriptionContainer.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 81 | 2017-12-19T15:47:04.000Z | 2022-03-30T04:00:52.000Z | shetland/core/src/main/java/org/n52/shetland/ogc/wps/description/ProcessInputDescriptionContainer.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 32 | 2017-12-21T14:32:29.000Z | 2022-03-02T15:04:52.000Z | 30.895522 | 86 | 0.7 | 1,003,485 | /*
* Copyright (C) 2015-2021 52°North Spatial Information Research 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.n52.shetland.ogc.wps.description;
import org.n52.janmayen.stream.Streams;
import org.n52.shetland.ogc.ows.OwsCode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author Christian Autermann
*/
public interface ProcessInputDescriptionContainer extends Description {
ProcessInputDescription getInput(OwsCode id);
default ProcessInputDescription getInput(String id) {
return getInput(new OwsCode(id));
}
Collection<? extends ProcessInputDescription> getInputDescriptions();
Set<OwsCode> getInputs();
interface Builder<T extends ProcessInputDescriptionContainer,
B extends ProcessInputDescriptionContainer.Builder<T, B>>
extends Description.Builder<T, B> {
B withInput(ProcessInputDescription input);
default B withInput(ProcessInputDescription.Builder<?, ?> input) {
return withInput(input.build());
}
default B withInput(Stream<? extends ProcessInputDescription> input) {
input.forEach(this::withInput);
return self();
}
default B withInput(Iterable<ProcessInputDescription> inputs) {
return withInput(Streams.stream(inputs));
}
default B withInput(ProcessInputDescription... inputs) {
return withInput(Arrays.asList(inputs));
}
}
}
|
9245b0579417262289e6fc8359db6fbd46b7388c | 2,186 | java | Java | src/main/java/ru/prevent/service/UserService.java | NicolayGolovnev/Prevent-WebApp | a642e619264ed5df1ef8a82ed484934e363ffc47 | [
"MIT"
] | null | null | null | src/main/java/ru/prevent/service/UserService.java | NicolayGolovnev/Prevent-WebApp | a642e619264ed5df1ef8a82ed484934e363ffc47 | [
"MIT"
] | null | null | null | src/main/java/ru/prevent/service/UserService.java | NicolayGolovnev/Prevent-WebApp | a642e619264ed5df1ef8a82ed484934e363ffc47 | [
"MIT"
] | null | null | null | 32.147059 | 118 | 0.655993 | 1,003,486 | package ru.prevent.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.prevent.entity.QuizEntity;
import ru.prevent.entity.UserAndQuizzesEntity;
import ru.prevent.entity.UserEntity;
import ru.prevent.exception.UserNotFoundException;
import ru.prevent.repository.QuizRepository;
import ru.prevent.repository.UserRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
UserRepository repository;
@Autowired
QuizService quizService;
public List<UserEntity> findAll() {
return repository.findAll();
}
public UserEntity findByFIO(String fio) {
String[] names = fio.split(" ");
Optional<UserEntity> optionalUser = Optional.empty();
if (names.length == 2)
optionalUser = repository.findByFirstNameAndLastName(names[0], names[1]);
else if (names.length == 3)
optionalUser = repository.findByFirstNameAndLastNameAndThirdName(names[0], names[1], names[2]);
if (optionalUser.isPresent())
return optionalUser.get();
else
throw new UserNotFoundException("User[firstName=" + names[0] + ", lastName=" + names[1] + "] not found!");
}
public UserEntity findById(Long id) {
Optional<UserEntity> optionalUser = repository.findById(id);
if (optionalUser.isPresent())
return optionalUser.get();
else
throw new RuntimeException("User with id=" + id + " not found!");
}
public void save(UserEntity user) {
List<QuizEntity> openQuizzes = quizService.findAllByAccessIsTrue();
List<UserAndQuizzesEntity> userQuizzes = new ArrayList<>();
for (QuizEntity quiz : openQuizzes)
userQuizzes.add(UserAndQuizzesEntity.builder()
.status("открытый")
.user(user)
.quiz(quiz)
.build());
user.setQuizzes(userQuizzes);
repository.save(user);
}
public void deleteById(Long id) {
repository.deleteById(id);
}
}
|
9245b215d1478fc0b6b7a46a33868fc9a092bc0c | 11,268 | java | Java | MOHEFT/src/MOHEFT.java | theuerse/sccTasksched18 | cf74795426cde85ad836ea22f9fce0798e856858 | [
"MIT"
] | null | null | null | MOHEFT/src/MOHEFT.java | theuerse/sccTasksched18 | cf74795426cde85ad836ea22f9fce0798e856858 | [
"MIT"
] | null | null | null | MOHEFT/src/MOHEFT.java | theuerse/sccTasksched18 | cf74795426cde85ad836ea22f9fce0798e856858 | [
"MIT"
] | null | null | null | 35.771429 | 127 | 0.582712 | 1,003,487 | import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
public class MOHEFT {
int N, K, MAX_INSTANCES_PER_TYPE;
String[] instanceTypes = null;
HashMap<String, Double> makeSpanMap = new HashMap<String, Double>();
HashMap<String, Double> costMap = new HashMap<String, Double>();
ArrayList<String> R = new ArrayList<>();
ArrayList<WorkflowSchedule> S = new ArrayList<>();
String[] dag;
String[] bRankedTasks;
String OUTPUT_FILE;
public MOHEFT(String configFilePath){
initFromConfigFile(configFilePath);
}
private void initFromConfigFile(String configFilePath){
Properties props = new Properties();
try {
props.load(new FileInputStream(configFilePath));
}catch(IOException e){
System.out.println(e.getMessage());
System.exit(-1);
}
N = Integer.parseInt(props.getProperty("N","20"));
K = Integer.parseInt(props.getProperty("K","6"));
MAX_INSTANCES_PER_TYPE = Integer.parseInt(props.getProperty("MAX_INSTANCES_PER_TYPE","5"));
OUTPUT_FILE = props.getProperty("MOHEFT_OUTPUT_FILE");
makeSpanMap = readMatrixFile(props.getProperty("MAKESPAN_FILE"));
costMap = readMatrixFile(props.getProperty("COST_FILE"));
// read dag from file (adjacency list)
try {
List<String> list = Files.readAllLines(new File(props.getProperty("DAG_FILE")).toPath(), Charset.defaultCharset());
list.remove(0); // dump header
dag = list.toArray(new String[0]);
}catch(IOException e){
System.out.println(e.getMessage());
System.exit(-1);
}
bRankedTasks = getBRankedTasks();
System.out.println("B-ranked task order: " + Arrays.toString(bRankedTasks));
// init ressources
for(String instanceType : instanceTypes){
for(int i=0; i < MAX_INSTANCES_PER_TYPE; i++){
R.add(instanceType+"_"+Integer.toString(i));
}
}
System.out.println("Ressources: " + R);
// start calculation of schedules
scheduleTasks(bRankedTasks);
}
private void scheduleTasks(String[] bRankedTasks){
WorkflowSchedule w;
String key;
// set up initial set of workflow schedules
for(int i = 0; i < K; i++){
S.add(new WorkflowSchedule(N));
}
// Iterate over the ranked tasks
for(int i = 0; i < bRankedTasks.length; i++){
ArrayList<WorkflowSchedule> S_tmp = new ArrayList<>();
// Iterate over all ressources
for(int j = 0; j < R.size(); j++){
// Iterate over all tradeoff schedules
for(int k = 0; k < Math.min(S.size(),K); k++){
// Extend all intermediate schedules
w = new WorkflowSchedule(S.get(k));
key = bRankedTasks[i] + "@" + R.get(j).split("_")[0];
w.schedule(R.get(j),bRankedTasks[i],costMap.get(key),makeSpanMap.get(key));
S_tmp.add(w);
}
}
// limit schedules to paretoFront
S_tmp = getParetoFront(S_tmp);
// sort S_tmp according to crowding distance
S_tmp = sortByCrowdingDistance(S_tmp);
// choose K schedules with highest crowding distance (first K schedules in sorted list)
S_tmp.subList(Math.min(S_tmp.size(),K),S_tmp.size()).clear();
S = S_tmp;
}
// finished!
System.out.println("\n\nFound tradeoff schedules: ");
for(WorkflowSchedule s : S){
System.out.println(s);
}
writeResultsToFile(S);
}
private ArrayList<WorkflowSchedule> getParetoFront(ArrayList<WorkflowSchedule> schedules){
ArrayList<WorkflowSchedule> paretoFront = new ArrayList<>();
ArrayList<WorkflowSchedule> dominatedSolutions = new ArrayList<>();
paretoFront.add(schedules.get(0));
int dom=0;
for(WorkflowSchedule s : schedules.subList(1,schedules.size())){
dominatedSolutions.clear();
for(WorkflowSchedule frontSched : paretoFront){
if(frontSched.equals(s)) {
dom = -1; break;
}
dom = frontSched.checkDomination(s); // , 0 if non-dominant, 1 if frontSched is dominated by s
if(dom == -1){
// -1 if frontSched dominates s -> forget about s
break;
}else if(dom == 1){
dominatedSolutions.add(frontSched);
}
}
// -1 ... dominated is the only case in which s is not added
if(dom != -1){
paretoFront.add(s);
paretoFront.removeAll(dominatedSolutions);
}
}
return paretoFront;
}
private void writeResultsToFile(ArrayList<WorkflowSchedule> schedules){
StringBuilder sb = new StringBuilder();
sb.append("totalCost,totalTime\n");
for(WorkflowSchedule ws : schedules){
sb.append(ws.totalCost+","+ws.totalTime+"\n");
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(OUTPUT_FILE), "utf-8"))) {
writer.write(sb.toString());
}catch (IOException e){
System.err.println(e.getMessage());
}
}
private ArrayList<WorkflowSchedule> sortByCrowdingDistance(ArrayList<WorkflowSchedule> schedules){
double crowdingDist = 0;
// sort by first objective domain (time)
schedules.sort((o1, o2) -> o1.getTotalTime().compareTo(o2.getTotalTime()));
// first and last elem are assigned crowding distance "infinity"
schedules.get(0).setCrowdingDistance(Double.MAX_VALUE);
schedules.get(schedules.size()-1).setCrowdingDistance(Double.MAX_VALUE);
// for all others, crowding dist. is calculated as the difference of the objective value of the two closest neighbours
for(int i=1; i<schedules.size()-1;i++){
crowdingDist = schedules.get(i+1).getTotalTime() - schedules.get(i-1).getTotalTime();
schedules.get(i).setCrowdingDistance(Math.max(schedules.get(i).getCrowdingDistance(), crowdingDist));
}
// sort by second objective domain (cost)
schedules.sort((o1, o2) -> o1.getTotalCost().compareTo(o2.getTotalCost()));
// first and last elem are assigned crowding distance "infinity"
schedules.get(0).setCrowdingDistance(Double.MAX_VALUE);
schedules.get(schedules.size()-1).setCrowdingDistance(Double.MAX_VALUE);
// for all others, crowding dist. is calculated as the difference of the objective value of the two closest neighbours
// add up indiv. crowding distances? -> Manhattan distance
for(int i=1; i<schedules.size()-1;i++){
crowdingDist = schedules.get(i+1).getTotalTime() - schedules.get(i-1).getTotalTime();
schedules.get(i).setCrowdingDistance(Math.max(schedules.get(i).getCrowdingDistance(), crowdingDist));
}
// finally sort by crowding distance
schedules.sort((o1, o2) -> o1.getCrowdingDistance().compareTo(o2.getCrowdingDistance()));
Collections.reverse(schedules); // descending order of crowding distance
return schedules;
}
private HashMap<String,Double> readMatrixFile(String path){
HashMap<String,Double> resultMap = new HashMap<>();
try {
List<String> list = Files.readAllLines(new File(path).toPath(), Charset.defaultCharset());
String line = list.get(0); // read header
String[] parts = line.replace("task,","").split(",");
String[] iTypes = parts;
// integrity-check
if(instanceTypes == null){
instanceTypes = iTypes;
}else{
if(! Arrays.equals(instanceTypes, iTypes)){
throw new IllegalArgumentException("instanceTypes from configFiles do not match");
}
}
String task = "";
for(int i = 1; i < list.size(); i++){
line = list.get(i);
parts = line.split(",");
task = parts[0];
for(int j = 1; j < parts.length; j++){
resultMap.put(task+"@"+iTypes[j-1],Double.parseDouble(parts[j]));
}
}
}catch(IOException e){
System.out.println(e.getMessage());
System.exit(-1);
}
return resultMap;
}
private String[] getBRankedTasks(){
ArrayList<String> predecessors;
ArrayList<String> resultList = new ArrayList<>();
// find node to begin with
predecessors = getPredecessors("end");
if(predecessors.size() != 1){
throw new IllegalArgumentException("DAG has to have one and only one end-node!");
}
HashMap<String,Double> timeOffSetMap = getTime(predecessors.get(0), new HashMap<String,Double>());
ValueComparator bvc = new ValueComparator(timeOffSetMap);
TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
sorted_map.putAll(timeOffSetMap);
return sorted_map.keySet().toArray(new String[0]);
}
private HashMap<String,Double> getTime(String node, HashMap<String,Double> map){
double ownTime = getTaskLength(node);
double maxPredecessorTime = 0;
for(String predecessor : getPredecessors(node)){
map = getTime(predecessor, map);
maxPredecessorTime = Math.max(maxPredecessorTime, map.get(predecessor));
}
map.put(node, ownTime + maxPredecessorTime);
return map;
}
// avg of makespans as a concession to our data-model (actual measurements)
private double getTaskLength(String task){
double makespanSum=0, count=0;
for(String instance : instanceTypes){
makespanSum+=makeSpanMap.get(task + "@" + instance);
count++;
}
return makespanSum/count;
}
private ArrayList<String> getPredecessors(String vertice){
ArrayList<String> predecessors = new ArrayList<>();
String[] parts;
String nd;
for(String adjacency : dag){
parts = adjacency.split(":");
nd = parts[0];
parts = parts[1].split(",");
for(String successor : parts) {
if (successor.equals(vertice)) {
predecessors.add(nd);
break;
}
}
}
return predecessors;
}
// Program argument example: /home/theuers/sccTasksched18/MOHEFT/data/config.txt
public static void main (String[] args){
if(args.length != 1){
System.out.println("locaction of config-File needs to be given!");
System.exit(-1);
}else {
System.out.println("using config-file from: " + args[0]);
MOHEFT m = new MOHEFT(args[0]);
}
}
}
|
9245b38eb8182afaab5942ca66e0141f1c9e925d | 1,431 | java | Java | src/main/java/com/dolinskm/rej006/views/OnlineViewController.java | micdol/REJ006JFX | 965d26a8b55859b8a88f6bcdb54e3197bd568a38 | [
"MIT"
] | null | null | null | src/main/java/com/dolinskm/rej006/views/OnlineViewController.java | micdol/REJ006JFX | 965d26a8b55859b8a88f6bcdb54e3197bd568a38 | [
"MIT"
] | 23 | 2020-03-09T15:15:05.000Z | 2020-03-22T21:07:38.000Z | src/main/java/com/dolinskm/rej006/views/OnlineViewController.java | micdol/REJ006JFX | 965d26a8b55859b8a88f6bcdb54e3197bd568a38 | [
"MIT"
] | null | null | null | 24.672414 | 98 | 0.752621 | 1,003,488 | package com.dolinskm.rej006.views;
import com.dolinskm.rej006.controls.BackPaneController;
import com.dolinskm.rej006.controls.SettingsGridController;
import com.dolinskm.rej006.managers.ViewManager;
import com.dolinskm.rej006.models.device.Mode;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import net.rgielen.fxweaver.core.FxmlView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
@FxmlView("online-view.fxml")
public class OnlineViewController {
@Autowired
private ViewManager viewManager;
// region FXML Controls
@FXML
private Button btnZeroing;
@FXML
private Button btnStartRegistration;
@FXML
private SettingsGridController settingsGridController;
@FXML
private BackPaneController backPaneController;
// endregion
// region FXML Action Handlers
@FXML
void onStartRegistrationClicked(ActionEvent event) {
viewManager.show(View.Plot);
}
@FXML
void onZeroingClicked(ActionEvent event) {
}
// endregion
@FXML
void initialize() {
settingsGridController.getSettings().setMode(Mode.Online);
btnStartRegistration.disableProperty().bind(settingsGridController.validProperty().not());
btnZeroing.disableProperty().bind(settingsGridController.validProperty().not());
}
}
|
9245b4235beb16b223f305aa46b391ff1c073354 | 3,184 | java | Java | src/main/java/io/supertokens/javalin/core/accessToken/AccessToken.java | jscyo/supertokens-javalin | f12783db27abe154d3c11b82dcc4dd737952ee46 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/supertokens/javalin/core/accessToken/AccessToken.java | jscyo/supertokens-javalin | f12783db27abe154d3c11b82dcc4dd737952ee46 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/supertokens/javalin/core/accessToken/AccessToken.java | jscyo/supertokens-javalin | f12783db27abe154d3c11b82dcc4dd737952ee46 | [
"Apache-2.0"
] | null | null | null | 44.222222 | 123 | 0.690327 | 1,003,489 | /*
* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* 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.supertokens.javalin.core.accessToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.supertokens.javalin.core.exception.TryRefreshTokenException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class AccessToken {
public static AccessTokenInfo getInfoFromAccessToken(String token, String jwtSigningPublicKey, boolean doAntiCsrfCheck)
throws TryRefreshTokenException {
try {
JsonObject payload = JWT.verifyJWTAndGetPayload(token, jwtSigningPublicKey);
AccessTokenInfo tokenInfo = new Gson().fromJson(payload, AccessTokenInfo.class);
if (tokenInfo.sessionHandle == null || tokenInfo.userId == null || tokenInfo.refreshTokenHash1 == null
|| tokenInfo.userData == null || (doAntiCsrfCheck && tokenInfo.antiCsrfToken == null)) {
throw new TryRefreshTokenException(
"Access token does not contain all the information. Maybe the structure has changed?");
}
if (tokenInfo.expiryTime < System.currentTimeMillis()) {
throw new TryRefreshTokenException("Access token expired");
}
return tokenInfo;
} catch (InvalidKeyException | NoSuchAlgorithmException | JWT.JWTException e) {
throw new TryRefreshTokenException("Error while verifying JWT");
}
}
public static class AccessTokenInfo {
public final String sessionHandle;
public final String userId;
public final String refreshTokenHash1;
public final String parentRefreshTokenHash1;
public final JsonObject userData;
public final String antiCsrfToken;
public final long expiryTime;
final long timeCreated;
AccessTokenInfo(String sessionHandle, String userId, String refreshTokenHash1,
long expiryTime, String parentRefreshTokenHash1, JsonObject userData,
String antiCsrfToken, long timeCreated, boolean isPaid) {
this.sessionHandle = sessionHandle;
this.userId = userId;
this.refreshTokenHash1 = refreshTokenHash1;
this.expiryTime = expiryTime;
this.parentRefreshTokenHash1 = parentRefreshTokenHash1;
this.userData = userData;
this.antiCsrfToken = antiCsrfToken;
this.timeCreated = timeCreated;
}
}
}
|
9245b485a98c6032e58e38d68db8c9226e8aed76 | 4,557 | java | Java | src/main/java/org/ggp/base/util/http/HttpReader.java | elishayer/sewards-folly | d9e9f7c8e031d6db7b67557f565860d93876b83e | [
"BSD-3-Clause"
] | 79 | 2015-01-29T03:11:44.000Z | 2022-03-17T17:24:11.000Z | src/main/java/org/ggp/base/util/http/HttpReader.java | elishayer/sewards-folly | d9e9f7c8e031d6db7b67557f565860d93876b83e | [
"BSD-3-Clause"
] | 37 | 2015-01-01T14:54:27.000Z | 2020-04-03T17:42:28.000Z | src/main/java/org/ggp/base/util/http/HttpReader.java | elishayer/sewards-folly | d9e9f7c8e031d6db7b67557f565860d93876b83e | [
"BSD-3-Clause"
] | 98 | 2015-01-25T02:53:11.000Z | 2021-12-28T17:56:09.000Z | 43.4 | 114 | 0.604126 | 1,003,490 | package org.ggp.base.util.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
public final class HttpReader
{
// Wrapper methods to support socket timeouts for reading requests/responses.
public static String readAsClient(Socket socket, int timeout) throws IOException, SocketTimeoutException
{
socket.setSoTimeout(timeout);
return readAsClient(socket);
}
public static String readAsServer(Socket socket, int timeout) throws IOException, SocketTimeoutException
{
socket.setSoTimeout(timeout);
return readAsServer(socket);
}
// Implementations of reading HTTP responses (readAsClient) and
// HTTP requests (readAsServer) for the purpose of communicating
// with other general game playing systems.
public static String readAsClient(Socket socket) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return readContentFromPOST(br);
}
public static String readAsServer(Socket socket) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// The first line of the HTTP request is the request line.
String requestLine = br.readLine();
if (requestLine == null) {
throw new IOException("The HTTP request was empty.");
}
String message;
if(requestLine.toUpperCase().startsWith("GET ")) {
message = requestLine.substring(5, requestLine.lastIndexOf(' '));
message = URLDecoder.decode(message, "UTF-8");
message = message.replace((char)13, ' ');
} else if (requestLine.toUpperCase().startsWith("POST ")) {
message = readContentFromPOST(br);
} else if (requestLine.toUpperCase().startsWith("OPTIONS ")) {
// Web browsers can send an OPTIONS request in advance of sending
// real XHR requests, to discover whether they should have permission
// to send those XHR requests. We want to handle this at the network
// layer rather than sending it up to the actual player, so we write
// a blank response (which will include the headers that the browser
// is interested in) and throw an exception so the player ignores the
// rest of this request.
HttpWriter.writeAsServer(socket, "", null);
throw new IOException("Drop this message at the network layer.");
} else {
HttpWriter.writeAsServer(socket, "", null);
throw new IOException("Unexpected request type: " + requestLine);
}
return message;
}
private static String readContentFromPOST(BufferedReader br) throws IOException {
String line;
int theContentLength = -1;
StringBuilder theContent = new StringBuilder();
while ((line = br.readLine()) != null) {
if (line.toLowerCase().startsWith("content-length:")) {
try {
theContentLength = Integer.parseInt(line.toLowerCase().replace("content-length:", "").trim());
} catch (NumberFormatException e) {
throw new IOException("Content-Length header can't be parsed: \"" + line + "\"");
}
} else if (line.length() == 0) {
// We want to ignore the headers in the request, so we'll just
// ignore every line up until the first blank line. The content
// of the request appears after that.
if (theContentLength != -1) {
// When the content-length header is available, we only read exactly
// that much content, once we reach the content.
for (int i = 0; i < theContentLength; i++) {
theContent.append((char)br.read());
}
} else {
// If there is no content-length header, read from the stream until
// it is closed.
String t;
while ((t = br.readLine()) != null) {
theContent.append(t);
}
}
return theContent.toString().trim();
}
}
throw new IOException("Could not find content in POST request.");
}
} |
9245b4e2552997ea9310b15b1bf2de1c4f53df59 | 1,072 | java | Java | presto-cache/src/main/java/com/facebook/presto/cache/NoOpCacheManager.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 9,782 | 2016-03-18T15:16:19.000Z | 2022-03-31T07:49:41.000Z | presto-cache/src/main/java/com/facebook/presto/cache/NoOpCacheManager.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 10,310 | 2016-03-18T01:03:00.000Z | 2022-03-31T23:54:08.000Z | presto-cache/src/main/java/com/facebook/presto/cache/NoOpCacheManager.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 3,803 | 2016-03-18T22:54:24.000Z | 2022-03-31T07:49:46.000Z | 29.777778 | 101 | 0.727612 | 1,003,491 | /*
* 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.facebook.presto.cache;
import com.facebook.presto.hive.CacheQuota;
import io.airlift.slice.Slice;
import static com.facebook.presto.cache.CacheResult.MISS;
public class NoOpCacheManager
implements CacheManager
{
@Override
public CacheResult get(FileReadRequest request, byte[] buffer, int offset, CacheQuota cacheQuota)
{
return MISS;
}
@Override
public void put(FileReadRequest request, Slice data, CacheQuota cacheQuota)
{
// no op
}
}
|
9245b508a7d32c8092bf75af090e2c1b64dd0d90 | 1,060 | java | Java | backend/burning-okr/burning-okr-app/src/main/java/org/burningokr/controller/configuration/OAuthFrontendDetailsController.java | LSchultebraucks/BurningOKR | 7e748bccd172599fd573f7cfd42cec8865d19884 | [
"Apache-2.0"
] | null | null | null | backend/burning-okr/burning-okr-app/src/main/java/org/burningokr/controller/configuration/OAuthFrontendDetailsController.java | LSchultebraucks/BurningOKR | 7e748bccd172599fd573f7cfd42cec8865d19884 | [
"Apache-2.0"
] | null | null | null | backend/burning-okr/burning-okr-app/src/main/java/org/burningokr/controller/configuration/OAuthFrontendDetailsController.java | LSchultebraucks/BurningOKR | 7e748bccd172599fd573f7cfd42cec8865d19884 | [
"Apache-2.0"
] | null | null | null | 44.166667 | 100 | 0.865094 | 1,003,492 | package org.burningokr.controller.configuration;
import lombok.RequiredArgsConstructor;
import org.burningokr.annotation.RestApiController;
import org.burningokr.dto.configuration.OAuthFrontendDetailsDto;
import org.burningokr.mapper.interfaces.DataMapper;
import org.burningokr.model.configuration.OAuthFrontendDetails;
import org.burningokr.service.configuration.OAuthFrontendDetailsService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@RestApiController
@RequiredArgsConstructor
public class OAuthFrontendDetailsController {
private final OAuthFrontendDetailsService oauthFrontendDetailsService;
private final DataMapper<OAuthFrontendDetails, OAuthFrontendDetailsDto> dataMapper;
@GetMapping("/oAuthFrontendDetails")
public ResponseEntity<OAuthFrontendDetailsDto> getOAuthFrontendDetails() {
OAuthFrontendDetails oauthClientDetails = oauthFrontendDetailsService.getOAuthFrontendDetails();
return ResponseEntity.ok().body(dataMapper.mapEntityToDto(oauthClientDetails));
}
}
|
9245b517931b1de2f53241c443eeaeac4e8262fe | 1,450 | java | Java | ProjetoYouTube/src/projetoyoutube/Visualizacao.java | GabrielProdi/JAVA_POO_CursoEmVideo | 54c4b481410203e9fde694b6e192c215a6623e56 | [
"MIT"
] | null | null | null | ProjetoYouTube/src/projetoyoutube/Visualizacao.java | GabrielProdi/JAVA_POO_CursoEmVideo | 54c4b481410203e9fde694b6e192c215a6623e56 | [
"MIT"
] | null | null | null | ProjetoYouTube/src/projetoyoutube/Visualizacao.java | GabrielProdi/JAVA_POO_CursoEmVideo | 54c4b481410203e9fde694b6e192c215a6623e56 | [
"MIT"
] | null | null | null | 20.714286 | 91 | 0.545517 | 1,003,493 | package projetoyoutube;
/**
*
* @author Gabriel Ferreira Prodi
* Curso POO Java #014b e #15b
* 16/07/2020
*
*/
public class Visualizacao {
private Gafanhoto espectador ;
private Video video;
public Visualizacao(Gafanhoto espectador, Video video) {
this.espectador = espectador;
this.video = video;
this.espectador.setTotAssistido(this.espectador.getTotAssistido() + 1);
this.video.setViews(this.video.getViews() + 1);
}
public Gafanhoto getEspectador() {
return espectador;
}
public void setEspectador(Gafanhoto espectador) {
this.espectador = espectador;
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
@Override
public String toString() {
return "Visualizacao{" + "espectador=" + espectador + ", \nvideo=" + video + "}\n";
}
public void avaliar(){
this.video.setAvaliacao(5);
}
public void avaliar(int nota){
this.video.setAvaliacao(nota);
}
public void avaliar (double porcent){
int tot = 0;
if (porcent <= 20) {
tot = 2;
} else if (porcent <= 50) {
tot = 5;
} else if (porcent <= 90){
tot = 8;
} else {
tot = 10;
}
this.video.setAvaliacao(tot);
}
}
|
9245b54557889d5f1462208eeb25ee57721fe99f | 148 | java | Java | mechanics/src/main/java/com/pipai/wf/unit/ability/component/LevelledAbilityComponent.java | applepi07/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | 3 | 2016-03-05T21:54:08.000Z | 2016-09-02T13:48:57.000Z | mechanics/src/main/java/com/pipai/wf/unit/ability/component/LevelledAbilityComponent.java | applepi07/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | 2 | 2015-09-18T05:26:35.000Z | 2015-10-02T07:29:27.000Z | mechanics/src/main/java/com/pipai/wf/unit/ability/component/LevelledAbilityComponent.java | cypai/wf | 6906895037c29af3ec7df7c54ffea227c56560ff | [
"Apache-2.0"
] | null | null | null | 14.8 | 45 | 0.722973 | 1,003,494 | package com.pipai.wf.unit.ability.component;
public interface LevelledAbilityComponent {
int getLevel();
void setLevel(int level);
}
|
9245b64b09ee10e27acdcf904ad0c3aa64009b48 | 1,325 | java | Java | config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | 42.741935 | 128 | 0.669434 | 1,003,495 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.schema.parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
/**
* @author arnej
*/
public class ParsedDocumentTestCase {
@Test
public void fields_can_be_added_once() throws Exception {
var doc = new ParsedDocument("foo");
var stringType = ParsedType.fromName("string");
doc.addField(new ParsedField("bar1", stringType));
doc.addField(new ParsedField("zap", stringType));
doc.addField(new ParsedField("bar2", stringType));
doc.addField(new ParsedField("bar3", stringType));
var e = assertThrows(IllegalArgumentException.class, () ->
doc.addField(new ParsedField("zap", stringType)));
System.err.println("As expected: "+e);
assertEquals("document 'foo' error: Duplicate (case insensitively) field 'zap' in document type 'foo'", e.getMessage());
e = assertThrows(IllegalArgumentException.class, () ->
doc.addField(new ParsedField("ZAP", stringType)));
assertEquals("document 'foo' error: Duplicate (case insensitively) field 'ZAP' in document type 'foo'", e.getMessage());
}
}
|
9245b79c26a8f21260566c3b59b41fdfe602e462 | 857 | java | Java | src/main/java/com/senac/petshop/rnval/AgendaRNVal.java | lossurdo/PetShop4j-Senac | 2a6b6b94ed82777b514fa4d1d2857a84b479dd1e | [
"MIT"
] | 1 | 2019-06-08T20:25:14.000Z | 2019-06-08T20:25:14.000Z | src/main/java/com/senac/petshop/rnval/AgendaRNVal.java | lossurdo/PetShop4j-Senac | 2a6b6b94ed82777b514fa4d1d2857a84b479dd1e | [
"MIT"
] | null | null | null | src/main/java/com/senac/petshop/rnval/AgendaRNVal.java | lossurdo/PetShop4j-Senac | 2a6b6b94ed82777b514fa4d1d2857a84b479dd1e | [
"MIT"
] | null | null | null | 20.902439 | 76 | 0.626604 | 1,003,496 | package com.senac.petshop.rnval;
import com.senac.petshop.bean.Agenda;
import com.senac.petshop.infra.ValidacaoRN;
/**
*
* @author lossurdo
*/
public class AgendaRNVal implements ValidacaoRN<Agenda> {
@Override
public void validarSalvar(Agenda bean) {
if (bean.getData() == null) {
throw new RuntimeException("Campo Data não informado");
}
if (bean.getAnimais() == null) {
throw new RuntimeException("Campo Animais não informado");
}
if (bean.getProcedimentos() == null) {
throw new RuntimeException("Campo Procedimentos não informado");
}
}
@Override
public void validarExcluir(Agenda bean) {
}
@Override
public void validarConsultar(Agenda bean) {
}
@Override
public void validarAlterar(Agenda bean) {
}
}
|
9245b807199d067c9962492733132737d7222585 | 6,156 | java | Java | app/src/main/java/com/lin/dlivkfragment/adapter/RoadInfoexpandableListAdapter.java | xinlyun/DivTwo | 54d2a32f010dd509a95a3024ac6ddb1fface9fd3 | [
"Apache-2.0"
] | 1 | 2016-01-22T02:56:31.000Z | 2016-01-22T02:56:31.000Z | app/src/main/java/com/lin/dlivkfragment/adapter/RoadInfoexpandableListAdapter.java | xinlyun/DivTwo | 54d2a32f010dd509a95a3024ac6ddb1fface9fd3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lin/dlivkfragment/adapter/RoadInfoexpandableListAdapter.java | xinlyun/DivTwo | 54d2a32f010dd509a95a3024ac6ddb1fface9fd3 | [
"Apache-2.0"
] | null | null | null | 31.569231 | 125 | 0.620858 | 1,003,497 | package com.lin.dlivkfragment.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.amap.api.navi.model.AMapNaviGuide;
import com.lin.dlivkfragment.R;
import com.lin.dlivkfragment.util.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xinlyun on 15-10-16.
*/
public class RoadInfoexpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private LayoutInflater inflater;
private List<AMapNaviGuide> aMapNaviGuides;
private List<Data> datas;
public RoadInfoexpandableListAdapter(Context context, List<AMapNaviGuide> aMapNaviGuides){
this.context = context;
inflater = LayoutInflater.from(context);
this.aMapNaviGuides = aMapNaviGuides;
initData();
}
private void initData(){
datas = new ArrayList<>();
String name = "";
List<String> strings = null;
for(AMapNaviGuide aMapNaviGuide:aMapNaviGuides){
if((!name.equals(aMapNaviGuide.getName()) && !aMapNaviGuide.getName().equals(""))|| datas.size()==0){
name = new String(aMapNaviGuide.getName());
strings = new ArrayList<>();
Data d = new Data(name);
d.setStrs(strings);
strings.add("行驶 " + aMapNaviGuide.getLength() + "米 " + Utils.rePid(aMapNaviGuide.getIconType()));
datas.add(d);
}else if(name.equals(aMapNaviGuide.getName()) || aMapNaviGuide.getName().equals("")){
strings.add("行驶 "+aMapNaviGuide.getLength()+"米 "+ Utils.rePid(aMapNaviGuide.getIconType()));
}
}
}
@Override
public int getGroupCount() {
return datas.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return datas.get(groupPosition).size();
}
@Override
public Object getGroup(int groupPosition) {
return datas.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return datas.get(groupPosition).getStrs().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
View view1;
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupHolder groupHolder = null;
if (convertView == null) {
groupHolder = new GroupHolder();
convertView = inflater.inflate(R.layout.group1, null);
groupHolder.textView = (TextView) convertView
.findViewById(R.id.group1);
groupHolder.imageView = (ImageView) convertView
.findViewById(R.id.image1);
convertView.setTag(groupHolder);
} else {
groupHolder = (GroupHolder) convertView.getTag();
}
this.view1 = convertView;
datas.get(groupPosition).setView(view1);
groupHolder.textView.setText(datas.get(groupPosition).getName());
if (isExpanded)// ture is Expanded or false is not isExpanded
groupHolder.imageView.setImageResource(R.drawable.expanded);
else
groupHolder.imageView.setImageResource(R.drawable.collapse);
return convertView;
// View view = inflater.inflate(R.layout.group1,null);
// TextView textView = (TextView) view.findViewById(R.id.group1);
// ImageView imageView = (ImageView) view.findViewById(R.id.image1);
// textView.setText(datas.get(groupPosition).getName());
// return view;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder childHolder = null;
if (convertView == null) {
childHolder = new ChildHolder();
convertView = inflater.inflate(R.layout.child1, null);
childHolder.textName = (TextView) convertView
.findViewById(R.id.name2);
childHolder.imageView = (ImageView) convertView
.findViewById(R.id.image2);
convertView.setTag(childHolder);
} else {
childHolder = (ChildHolder) convertView.getTag();
}
childHolder.textName.setText(datas.get(groupPosition).getStrs().get(childPosition));
return convertView;
// View view = inflater.inflate(R.layout.child1,null);
// TextView textView = (TextView) view.findViewById(R.id.name2);
// ImageView imageView = (ImageView) view.findViewById(R.id.image2);
// Button button = (Button) view.findViewById(R.id.button2);
// textView.setText(datas.get(groupPosition).getStrs().get(childPosition));
// return view;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public class Data{
String name="";
List<String> s;
View headView;
Data(String name){
this.name = ""+name;
}
private void setView(View view){
this.headView = view;
}
public View getHeadView(){
return headView;
}
private void setStrs(List<String> s){
this.s = s;
}
public String getName() {
if(name==null)return "";
return name;
}
private List<String> getStrs() {
return s;
}
private int size(){
return s.size();
}
}
public class GroupHolder {
TextView textView;
ImageView imageView;
}
public class ChildHolder {
TextView textName;
ImageView imageView;
}
}
|
9245b83dbacac5d5eb523ea4b8d377067c0d3d31 | 5,156 | java | Java | AirballDataProxy/src/org/schmivits/airball/dataproxy/data/ActualDataSourceStream.java | ihab/airball-for-android | 83c2d90c628aad34e749a7cc3437dc473b99ea8a | [
"MIT"
] | 3 | 2015-02-12T17:57:41.000Z | 2021-07-16T01:16:41.000Z | AirballDataProxy/src/org/schmivits/airball/dataproxy/data/ActualDataSourceStream.java | ihab/airball-for-android | 83c2d90c628aad34e749a7cc3437dc473b99ea8a | [
"MIT"
] | null | null | null | AirballDataProxy/src/org/schmivits/airball/dataproxy/data/ActualDataSourceStream.java | ihab/airball-for-android | 83c2d90c628aad34e749a7cc3437dc473b99ea8a | [
"MIT"
] | 1 | 2021-07-16T01:16:46.000Z | 2021-07-16T01:16:46.000Z | 28.644444 | 96 | 0.657874 | 1,003,498 | package org.schmivits.airball.dataproxy.data;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import tw.com.prolific.driver.pl2303.PL2303Driver;
import tw.com.prolific.driver.pl2303.PL2303Driver.BaudRate;
import tw.com.prolific.driver.pl2303.PL2303Driver.DataBits;
import tw.com.prolific.driver.pl2303.PL2303Driver.FlowControl;
import tw.com.prolific.driver.pl2303.PL2303Driver.Parity;
import tw.com.prolific.driver.pl2303.PL2303Driver.StopBits;
import android.content.Context;
import android.hardware.usb.UsbManager;
public class ActualDataSourceStream extends ConcurrentProcess implements DataSourceStream {
private static final String USB_PERMISSION = "org.schmivits.airball.dataproxy.USB_PERMISSION";
private static final int READ_BUFFER_SIZE = 2048;
private static final long ENUMERATE_PAUSE = 1000L;
private static final long SETUP_PAUSE = 500L;
private static final long READ_PAUSE = 10L;
public static class SerialParameters {
public final BaudRate mBaudRate;
public final DataBits mDataBits;
public final StopBits mStopBits;
public final Parity mParity;
public final FlowControl mFlowControl;
public SerialParameters(
BaudRate baudRate,
DataBits dataBits,
StopBits stopBits,
Parity parity,
FlowControl flowControl) {
mBaudRate = baudRate;
mDataBits = dataBits;
mStopBits = stopBits;
mParity = parity;
mFlowControl = flowControl;
}
}
private final List<Listener> mListeners = new ArrayList<Listener>();
private SerialParameters mSerialParameters = new SerialParameters(
BaudRate.B115200,
DataBits.D8,
StopBits.S1,
Parity.NONE,
FlowControl.OFF);
private PL2303Driver mDriver;
private final byte[] mReadBuffer = new byte[READ_BUFFER_SIZE];
private final StringBuilder mLineBuilder = new StringBuilder();
private boolean mSerialChanged = false;
public ActualDataSourceStream(Context context, ProcessNode parent, String title) {
super(context, parent, title);
}
@Override protected void doRun() throws InterruptedException {
mDriver = new PL2303Driver(
(UsbManager) getContext().getSystemService(Context.USB_SERVICE),
getContext(),
USB_PERMISSION);
boolean doneSetup = false;
while (isRunning()) {
if (mSerialChanged) {
synchronized (this) {
if (mSerialChanged) {
doneSetup = false;
mSerialChanged = false;
}
}
}
if (!mDriver.isConnected()) {
doneSetup = false;
enumerateDriver();
} else if (mDriver.isConnected() && !doneSetup) {
doneSetup = setupDriver();
} else {
readFromDriver();
}
}
}
private void enumerateDriver() throws InterruptedException {
setStatus("Attempting enumerate ...");
if (mDriver.enumerate()) {
setStatus("Enumerate successful");
} else {
setStatus("Enumerate failed, sleeping ...");
Thread.sleep(ENUMERATE_PAUSE);
}
}
private boolean setupDriver() throws InterruptedException {
setStatus("Setting up driver ...");
boolean success;
try {
int setup = mDriver.setup(
mSerialParameters.mBaudRate,
mSerialParameters.mDataBits,
mSerialParameters.mStopBits,
mSerialParameters.mParity,
mSerialParameters.mFlowControl);
boolean initByBaudRate = mDriver.InitByBaudRate(
mSerialParameters.mBaudRate);
success = setup == 0 && initByBaudRate;
} catch (IOException e) {
success = false;
setStatus(e.toString());
}
if (success) {
setStatus("Setup succeeded");
return true;
} else {
setStatus("Setup failed, sleeping ...");
Thread.sleep(SETUP_PAUSE);
return false;
}
}
private void readFromDriver() throws InterruptedException {
for (int n; (n = mDriver.read(mReadBuffer)) > 0; ) {
receivedData(n);
}
Thread.sleep(READ_PAUSE);
}
private boolean isLineSeparator(char c) {
return c == '\r' || c == '\n';
}
private void receivedData(int n) {
for (int i = 0; i < n; i++) {
char c = (char) mReadBuffer[i];
if (isLineSeparator(c)) {
if (mLineBuilder.length() > 0) {
notifyListeners(mLineBuilder.toString());
setStatus(mLineBuilder.toString());
mLineBuilder.setLength(0);
}
} else {
mLineBuilder.append(c);
}
}
}
private void notifyListeners(String line) {
for (Listener l : mListeners) {
l.data(line);
}
}
@Override
public void addListener(Listener l) {
synchronized (mListeners) {
mListeners.add(l);
}
}
@Override
public void removeListener(Listener l) {
synchronized (mListeners) {
mListeners.remove(l);
}
}
public void setSerialParameters(SerialParameters p) {
synchronized (this) {
mSerialParameters = p;
mSerialChanged = true;
}
}
public SerialParameters getSerialParameters() {
return mSerialParameters;
}
}
|
9245b8d9f7838e2937e1973fa8ea404fd46c7ad1 | 142 | java | Java | api/src/main/java/com/tb/interfaces/ITest.java | bjvolcano/encryptClass | 774216a2094c157675f0204467d7c5233741eea6 | [
"Apache-2.0"
] | 2 | 2021-05-13T11:33:43.000Z | 2022-02-17T15:09:21.000Z | api/src/main/java/com/tb/interfaces/ITest.java | bjvolcano/encryptClass | 774216a2094c157675f0204467d7c5233741eea6 | [
"Apache-2.0"
] | 1 | 2021-12-27T09:00:35.000Z | 2021-12-31T07:33:12.000Z | api/src/main/java/com/tb/interfaces/ITest.java | bjvolcano/encryptClass | 774216a2094c157675f0204467d7c5233741eea6 | [
"Apache-2.0"
] | null | null | null | 14.2 | 26 | 0.626761 | 1,003,499 | package com.tb.interfaces;
/**
* @Author bjvolcano
* @Date 2021/5/7 6:55 下午
* @Version 1.0
*/
public interface ITest {
void test();
}
|
9245b99e34702ba362ad55c90383364553b1be76 | 4,004 | java | Java | vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/ViewportWithCorrectionPastingDecorator.java | draker94/vividus | 46545b6555c29f21b5d9b29a70ef8679ce42e119 | [
"Apache-2.0"
] | 335 | 2019-06-24T06:43:45.000Z | 2022-03-26T08:26:23.000Z | vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/ViewportWithCorrectionPastingDecorator.java | draker94/vividus | 46545b6555c29f21b5d9b29a70ef8679ce42e119 | [
"Apache-2.0"
] | 2,414 | 2019-08-15T15:24:31.000Z | 2022-03-31T14:38:26.000Z | vividus-plugin-web-app/src/main/java/org/vividus/selenium/screenshot/strategies/ViewportWithCorrectionPastingDecorator.java | Yauhenda/vividus | 583df23b34dfc48d3911ed1b300a273c2fd1777c | [
"Apache-2.0"
] | 64 | 2019-08-16T11:32:48.000Z | 2022-03-12T06:15:18.000Z | 37.074074 | 107 | 0.713287 | 1,003,500 | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.selenium.screenshot.strategies;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.vividus.util.Sleeper;
import ru.yandex.qatools.ashot.coordinates.Coords;
import ru.yandex.qatools.ashot.shooting.ShootingStrategy;
import ru.yandex.qatools.ashot.shooting.ViewportPastingDecorator;
/**
* Modified copy of ru.yandex.qatools.ashot.shooting.ViewportPastingDecorator
*/
public class ViewportWithCorrectionPastingDecorator extends ViewportPastingDecorator
{
private static final long serialVersionUID = 1294938703067038698L;
private static final float ACCURACY = 1.03f;
private int correctedHeight;
private int correctedWidth;
public ViewportWithCorrectionPastingDecorator(ShootingStrategy strategy)
{
super(strategy);
}
public ViewportWithCorrectionPastingDecorator withCorrectedHeight(int correctedHeight)
{
this.correctedHeight = correctedHeight;
return this;
}
public ViewportWithCorrectionPastingDecorator withCorrectedWidth(int correctedWidth)
{
this.correctedWidth = correctedWidth;
return this;
}
@Override
public BufferedImage getScreenshot(WebDriver wd, Set<Coords> coordsSet)
{
JavascriptExecutor js = (JavascriptExecutor) wd;
int pageHeight = getFullHeight(wd);
int pageWidth = getFullWidth(wd);
int viewportHeight = getWindowHeight(wd);
Coords shootingArea = getShootingCoords(coordsSet, pageWidth, pageHeight, viewportHeight);
double heightRation = (double) correctedHeight / viewportHeight;
double widthRation = (double) correctedWidth / pageWidth;
BufferedImage finalImage = new BufferedImage(Math.toIntExact(Math.round(pageWidth * widthRation)),
Math.toIntExact(Math.round(shootingArea.height * heightRation * ACCURACY)), BufferedImage
.TYPE_3BYTE_BGR);
Graphics2D graphics = finalImage.createGraphics();
int scrollTimes = (int) Math.ceil(shootingArea.getHeight() / viewportHeight);
for (int n = 0; n < scrollTimes; n++)
{
scrollVertically(js, shootingArea.y + viewportHeight * n);
Sleeper.sleep(Duration.ofMillis(scrollTimeout));
BufferedImage part = getShootingStrategy().getScreenshot(wd);
graphics.drawImage(part, 0, Math.toIntExact(Math.round((getCurrentScrollY(js) - shootingArea.y)
* heightRation)), null);
}
graphics.dispose();
return finalImage;
}
private Coords getShootingCoords(Set<Coords> coords, int pageWidth, int pageHeight, int viewPortHeight)
{
if (coords == null || coords.isEmpty())
{
return new Coords(0, 0, pageWidth, pageHeight);
}
return extendShootingArea(Coords.unity(coords), viewPortHeight, pageHeight);
}
private Coords extendShootingArea(Coords shootingCoords, int viewportHeight, int pageHeight)
{
int halfViewport = viewportHeight / 2;
shootingCoords.y = Math.max(shootingCoords.y - halfViewport / 2, 0);
shootingCoords.height = Math.min(shootingCoords.height + halfViewport, pageHeight);
return shootingCoords;
}
}
|
9245b9a08c58c084f60454e763de3597af3cd8a6 | 689 | java | Java | gluecodium/src/test/resources/smoke/field_constructors/output/android/com/example/smoke/FieldConstructorsPartialDefaults.java | heremaps/gluecodium | 2d69e3e00cae511efe852556c8019eb378a45136 | [
"Apache-2.0"
] | 138 | 2019-12-11T13:16:52.000Z | 2022-03-28T01:24:21.000Z | gluecodium/src/test/resources/smoke/field_constructors/output/android/com/example/smoke/FieldConstructorsPartialDefaults.java | heremaps/gluecodium | 2d69e3e00cae511efe852556c8019eb378a45136 | [
"Apache-2.0"
] | 310 | 2020-01-14T11:46:26.000Z | 2022-03-31T15:05:40.000Z | gluecodium/src/test/resources/smoke/field_constructors/output/android/com/example/smoke/FieldConstructorsPartialDefaults.java | heremaps/gluecodium | 2d69e3e00cae511efe852556c8019eb378a45136 | [
"Apache-2.0"
] | 10 | 2019-12-11T11:46:16.000Z | 2021-11-02T10:41:59.000Z | 31.318182 | 125 | 0.716981 | 1,003,501 | /*
*
*/
package com.example.smoke;
import android.support.annotation.NonNull;
public final class FieldConstructorsPartialDefaults {
@NonNull
public String stringField;
public int intField;
public boolean boolField;
public FieldConstructorsPartialDefaults(final int intField, @NonNull final String stringField) {
this.intField = intField;
this.stringField = stringField;
this.boolField = true;
}
public FieldConstructorsPartialDefaults(final boolean boolField, final int intField, @NonNull final String stringField) {
this.boolField = boolField;
this.intField = intField;
this.stringField = stringField;
}
}
|
9245ba58c8e18773be87a259696f6a283ccab0f2 | 1,034 | java | Java | rxrpc-apt-java/src/test/resources/output/SampleMetaSampleMetaEndpointInputEndpoint_RxClient.java | dicbrus/rxrpc | c8c822f9e4ee6c27ab3e0615fcc31142c07bb708 | [
"Apache-2.0"
] | null | null | null | rxrpc-apt-java/src/test/resources/output/SampleMetaSampleMetaEndpointInputEndpoint_RxClient.java | dicbrus/rxrpc | c8c822f9e4ee6c27ab3e0615fcc31142c07bb708 | [
"Apache-2.0"
] | null | null | null | rxrpc-apt-java/src/test/resources/output/SampleMetaSampleMetaEndpointInputEndpoint_RxClient.java | dicbrus/rxrpc | c8c822f9e4ee6c27ab3e0615fcc31142c07bb708 | [
"Apache-2.0"
] | null | null | null | 34.466667 | 141 | 0.767892 | 1,003,502 | package com.slimgears.rxrpc.sample;
import com.slimgears.rxrpc.client.AbstractClient;
import com.slimgears.rxrpc.client.RxClient.Session;
import com.slimgears.util.reflect.TypeToken;
import io.reactivex.Observable;
import java.lang.String;
import java.util.List;
import javax.annotation.Generated;
/**
* Generated from com.slimgears.rxrpc.sample.SampleMetaSampleMetaEndpointInputEndpoint
*/
@Generated("com.slimgears.rxrpc.apt.RxRpcEndpointAnnotationProcessor")
public class SampleMetaSampleMetaEndpointInputEndpoint_RxClient extends AbstractClient implements SampleMetaSampleMetaEndpointInputEndpoint {
public SampleMetaSampleMetaEndpointInputEndpoint_RxClient(Session session) {
super(session);
}
@Override
public Observable<List<SampleMetaEndpointInput>> data(String data) {
return invokeObservable(
new TypeToken<List<SampleMetaEndpointInput>>(){},
"sampleMetaSampleMetaEndpointInputEndpoint/data",
arguments()
.put("data", data));
}
}
|
9245bb64c54e1cd643bb8ba2dabe44572cab2558 | 1,288 | java | Java | testability-explorer/src/main/java/com/google/test/metric/javasrc/TypeBuilder.java | dipooyekanmi/testability-explorer | 9c309d65d67b0213eb26e0429a9b4ebf04c0b19a | [
"Apache-2.0"
] | 1 | 2019-09-18T19:29:44.000Z | 2019-09-18T19:29:44.000Z | testability-explorer/src/main/java/com/google/test/metric/javasrc/TypeBuilder.java | dipooyekanmi/testability-explorer | 9c309d65d67b0213eb26e0429a9b4ebf04c0b19a | [
"Apache-2.0"
] | null | null | null | testability-explorer/src/main/java/com/google/test/metric/javasrc/TypeBuilder.java | dipooyekanmi/testability-explorer | 9c309d65d67b0213eb26e0429a9b4ebf04c0b19a | [
"Apache-2.0"
] | null | null | null | 28.622222 | 80 | 0.732143 | 1,003,503 | /*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.test.metric.javasrc;
import com.google.test.metric.ClassInfo;
import com.google.test.metric.FieldInfo;
import com.google.test.metric.Type;
import com.google.test.metric.Visibility;
public class TypeBuilder {
private final ClassInfo info;
public TypeBuilder(ClassInfo info) {
this.info = info;
}
public void addField(String name, Type type, Visibility visibility,
boolean isGlobal, boolean isFinal) {
boolean isPrivate = Visibility.PRIVATE == visibility;
FieldInfo fieldInfo = new FieldInfo(info, name, type, isFinal, isGlobal,
isPrivate);
info.addField(fieldInfo);
}
public String getName() {
return info.getName();
}
}
|
9245bc409baa28a5bb9850909621f2fb00a8f975 | 2,152 | java | Java | src/com/lchau/gwt/twitter/client/view/ApplicationView.java | lamchau/gwt-twitter | ea6f6618f9647fc31dfdf8df4218ff84b038e41e | [
"Apache-2.0"
] | null | null | null | src/com/lchau/gwt/twitter/client/view/ApplicationView.java | lamchau/gwt-twitter | ea6f6618f9647fc31dfdf8df4218ff84b038e41e | [
"Apache-2.0"
] | null | null | null | src/com/lchau/gwt/twitter/client/view/ApplicationView.java | lamchau/gwt-twitter | ea6f6618f9647fc31dfdf8df4218ff84b038e41e | [
"Apache-2.0"
] | null | null | null | 25.023256 | 94 | 0.749071 | 1,003,504 | package com.lchau.gwt.twitter.client.view;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.lchau.gwt.twitter.client.presenter.TweetPresenter;
public class ApplicationView extends Composite implements TweetPresenter.Display {
interface ApplicationViewUiBinder extends UiBinder<Widget, ApplicationView> {
}
private static ApplicationViewUiBinder uiBinder = GWT.create(ApplicationViewUiBinder.class);
@UiField
InlineLabel characterCount;
@UiField(provided = true)
Label errorMessage;
@UiField
HasValue<String> message;
@UiField
HasClickHandlers generateTweetsButton;
@UiField
HasClickHandlers resetButton;
@UiField
HasClickHandlers sendTweet;
@UiField
FlowPanel twitterFeed;
public ApplicationView() {
// auto-hiding error message
errorMessage = new Label() {
@Override
public void setText(String text) {
setVisible(text != null && text.length() > 0);
super.setText(text);
}
};
initWidget(uiBinder.createAndBindUi(this));
}
@Override
public HasText getCharacterCount() {
return characterCount;
}
@Override
public HasText getErrorMessage() {
return errorMessage;
}
@Override
public HasValue<String> getMessage() {
return message;
}
@Override
public HasClickHandlers getResetButton() {
return resetButton;
}
@Override
public HasClickHandlers getSendTweetButton() {
return sendTweet;
}
@Override
public HasWidgets getTwitterFeedContainer() {
return twitterFeed;
}
@Override
public HasClickHandlers generateRandomTweets() {
return generateTweetsButton;
}
}
|
9245bc49fa5e35ab7696ff7ac3a50d05a31de03f | 712 | java | Java | sapjco-api/src/main/java/cn/gitlab/virtualcry/sapjco/util/key/KeyGenerator.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | 3 | 2019-07-06T06:29:02.000Z | 2021-08-30T06:44:06.000Z | sapjco-api/src/main/java/cn/gitlab/virtualcry/sapjco/util/key/KeyGenerator.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | null | null | null | sapjco-api/src/main/java/cn/gitlab/virtualcry/sapjco/util/key/KeyGenerator.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | 4 | 2019-07-06T06:29:52.000Z | 2021-04-11T23:45:07.000Z | 22.967742 | 105 | 0.639045 | 1,003,505 | package cn.gitlab.virtualcry.sapjco.util.key;
import java.util.UUID;
/**
* JCo settings key generator.
*
* @author VirtualCry
*/
public class KeyGenerator {
/**
* Generate client key.
* @return client key.
*/
public static String generateClientKey() {
return UUID.randomUUID().toString();
}
/**
* Generate server key.
* @param gatewayHost gateway host
* @param gatewayService gateway service
* @param programId program id
* @return server key.
*/
public static String generateServerKey(String gatewayHost, String gatewayService, String programId) {
return gatewayHost + " | " + gatewayService + " | " + programId;
}
}
|
9245bdb4a167cf4ebd0ee71846855ba609700dc1 | 226 | java | Java | gradle-hello/src/main/java/ninja/bryansills/HelloPlugin.java | bryansills/roboto-plugin | 14a20d5193871b28c9362d2b1c05c37942aa2228 | [
"Apache-2.0"
] | null | null | null | gradle-hello/src/main/java/ninja/bryansills/HelloPlugin.java | bryansills/roboto-plugin | 14a20d5193871b28c9362d2b1c05c37942aa2228 | [
"Apache-2.0"
] | null | null | null | gradle-hello/src/main/java/ninja/bryansills/HelloPlugin.java | bryansills/roboto-plugin | 14a20d5193871b28c9362d2b1c05c37942aa2228 | [
"Apache-2.0"
] | null | null | null | 22.6 | 53 | 0.730088 | 1,003,506 | package ninja.bryansills;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public class HelloPlugin implements Plugin<Project> {
public void apply(Project project) {
project.task("helloTask");
}
} |
9245bf4ff296e0c337677968191b57ccfff278ca | 12,828 | java | Java | src/com/HotelRoom/controller/HotelRoomServlet.java | Codachen/EA101G3 | d8e3a6a568d5541b8890cbe99b96d67c0e5fa754 | [
"Apache-2.0"
] | null | null | null | src/com/HotelRoom/controller/HotelRoomServlet.java | Codachen/EA101G3 | d8e3a6a568d5541b8890cbe99b96d67c0e5fa754 | [
"Apache-2.0"
] | null | null | null | src/com/HotelRoom/controller/HotelRoomServlet.java | Codachen/EA101G3 | d8e3a6a568d5541b8890cbe99b96d67c0e5fa754 | [
"Apache-2.0"
] | null | null | null | 40.0875 | 122 | 0.613112 | 1,003,507 | package com.HotelRoom.controller;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.HotelRoom.model.HotelRoomService;
import com.HotelRoom.model.HotelRoomVO;
public class HotelRoomServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String action = req.getParameter("action");
if ("getOne_For_Display".equals(action)) {
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 - 輸入格式的錯誤處理 **********************/
Integer roomNo = null;
try {
roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
} catch (NumberFormatException e) {
errorMsgs.add("房間編號請填數字.");
}
/*************************** 2.開始查詢資料 *****************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
HotelRoomVO hotelRoomVO = hotelRoomSvc.getOneHotelRoom(roomNo);
if (hotelRoomVO == null) {
errorMsgs.add("查無資料");
}
// Send the use back to the form, if there were errors
if (!errorMsgs.isEmpty()) {
RequestDispatcher failureView = req
.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
return;// 程式中斷
}
/*************************** 3.查詢完成,準備轉交(Send the Success view) *************/
req.setAttribute("hotelRoomVO", hotelRoomVO);// 資料庫取出的hotelRoomVO物件,存入req
String url = "/back-end/Hotel/HotelRoom/listOneHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add("無法取得資料:" + e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("getOne_For_Update".equals(action)) { // 來自listAllHotelRoom.jsp的請求
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 ****************************************/
Integer roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
/*************************** 2.開始查詢資料 ****************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
HotelRoomVO hotelRoomVO = hotelRoomSvc.getOneHotelRoom(roomNo);
/*************************** 3.查詢完成,準備轉交(Send the Success view) ************/
req.setAttribute("hotelRoomVO", hotelRoomVO);// 資料庫取出的hotelRoomVO物件,存入req
String url = "/back-end/Hotel/HotelRoom/update_HotelRoom_input.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);// 成功轉交 update_HotelRoom_input.jsp
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add("無法取得要修改的資料:" + e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("update".equals(action)) { // 來自update_HotelRoom_input.jsp的請求
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 - 輸入格式的錯誤處理 **********************/
Integer roomNo = null;
try {
roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
} catch (NumberFormatException e) {
errorMsgs.add("房間編號請勿空白");
}
String roomTypeNo = req.getParameter("roomTypeNo");
System.out.println(roomTypeNo);
if (roomTypeNo == null || (roomTypeNo.trim()).length() == 0) {
errorMsgs.add("房型編號請勿空白");
}
String petNo = req.getParameter("petNo"); // 寵物編號可以為空值
System.out.println(petNo);
Integer roomStatus = null;
try {
roomStatus = new Integer(req.getParameter("roomStatus"));
System.out.println(roomStatus);
} catch (NumberFormatException e) {
roomStatus = 0;
errorMsgs.add("房型狀態請勿空白");
}
HotelRoomVO hotelRoomVO = new HotelRoomVO();
hotelRoomVO.setRoomNo(roomNo);
hotelRoomVO.setRoomTypeNo(roomTypeNo);
hotelRoomVO.setPetNo(petNo);
hotelRoomVO.setRoomStatus(roomStatus);
if (!errorMsgs.isEmpty()) {
req.setAttribute("hotelRoomVO", hotelRoomVO); // 含有輸入格式錯誤的hotelRoomVO物件,也存入req
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/update_HotelRoomType_input.jsp");
failureView.forward(req, res);
return; // 程式中斷
}
/*************************** 2.開始修改資料 *****************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
hotelRoomVO = hotelRoomSvc.updateHotelRoom(roomNo, roomTypeNo, petNo, roomStatus);
/*************************** 3.修改完成,準備轉交(Send the Success view) *************/
req.setAttribute("hotelRoomVO", hotelRoomVO);
String url = "/back-end/Hotel/HotelRoom/listOneHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);
req.setAttribute("updateOk", "更新成功");
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add(e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/update_HotelRoom_input.jsp");
failureView.forward(req, res);
}
}
if ("insert".equals(action)) { // 來自addHotelRoom.jsp的請求
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*********************** 1.接收請求參數 - 輸入格式的錯誤處理 *************************/
Integer roomNo = null;
try {
roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
} catch (NumberFormatException e) {
errorMsgs.add("房間編號請勿空白");
}
String roomTypeNo = req.getParameter("roomTypeNo");
System.out.println(roomTypeNo);
if (roomTypeNo == null || (roomTypeNo.trim()).length() == 0) {
errorMsgs.add("房型編號請勿空白");
}
String petNo = req.getParameter("petNo"); // 寵物編號可以為空值
System.out.println(petNo);
Integer roomStatus = null;
try {
roomStatus = new Integer(req.getParameter("roomStatus"));
System.out.println(roomStatus);
} catch (NumberFormatException e) {
roomStatus = 0;
errorMsgs.add("房型狀態:請勿空白");
}
HotelRoomVO hotelRoomVO = new HotelRoomVO();
hotelRoomVO.setRoomNo(roomNo);
hotelRoomVO.setRoomTypeNo(roomTypeNo);
hotelRoomVO.setPetNo(petNo);
hotelRoomVO.setRoomStatus(roomStatus);
// Send the use back to the form, if there were errors
if (!errorMsgs.isEmpty()) {
req.setAttribute("hotelRoomVO", hotelRoomVO); // 含有輸入格式錯誤的hotelRoomVO物件,也存入req
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/addHotelRoom.jsp");
failureView.forward(req, res);
return;
}
/*************************** 2.開始新增資料 ***************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
hotelRoomVO = hotelRoomSvc.addHotelRoom(roomNo, roomTypeNo, petNo, roomStatus);
/*************************** 3.新增完成,準備轉交(Send the Success view) ***********/
String url = "/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);// 新增成功後轉交listAllHotelRoom.jsp
req.setAttribute("success", "success");
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add(e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/addHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("delete".equals(action)) { // 來自listAllHotelRoomType.jsp
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 ***************************************/
Integer roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
/*************************** 2.開始刪除資料 ***************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
hotelRoomSvc.deleteHotelRoom(roomNo);
/*************************** 3.刪除完成,準備轉交(Send the Success view) ***********/
String url = "/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);
req.setAttribute("fail", "刪除成功");
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add("刪除資料失敗:" + e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("delete".equals(action)) { // 來自listAllHotelRoom.jsp
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 ***************************************/
Integer roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
/*************************** 2.開始刪除資料 ***************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
hotelRoomSvc.deleteHotelRoom(roomNo);
/*************************** 3.刪除完成,準備轉交(Send the Success view) ***********/
String url = "/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);
req.setAttribute("fail", "刪除成功");
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add("刪除資料失敗:" + e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("delete".equals(action)) { // 來自listAllHotelRoom.jsp
List<String> errorMsgs = new LinkedList<String>();
// Store this set in the request scope, in case we need to
// send the ErrorPage view.
req.setAttribute("errorMsgs", errorMsgs);
try {
/*************************** 1.接收請求參數 ***************************************/
Integer roomNo = new Integer(req.getParameter("roomNo"));
System.out.println(roomNo);
/*************************** 2.開始刪除資料 ***************************************/
HotelRoomService hotelRoomSvc = new HotelRoomService();
hotelRoomSvc.deleteHotelRoom(roomNo);
/*************************** 3.刪除完成,準備轉交(Send the Success view) ***********/
String url = "/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp";
RequestDispatcher successView = req.getRequestDispatcher(url);
req.setAttribute("fail", "刪除成功");
successView.forward(req, res);
/*************************** 其他可能的錯誤處理 **********************************/
} catch (Exception e) {
errorMsgs.add("刪除資料失敗:" + e.getMessage());
RequestDispatcher failureView = req.getRequestDispatcher("/back-end/Hotel/HotelRoom/listAllHotelRoom.jsp");
failureView.forward(req, res);
}
}
if ("getemptyroom".equals(action)) {
String roomTypeNo = req.getParameter("roomTypeNo");
HotelRoomService svc = new HotelRoomService();
List list = svc.getEmptyRoom(roomTypeNo);
req.setAttribute("emptyRoom", list);
RequestDispatcher failureView = req.getRequestDispatcher("/front-end/emptyroom.jsp");
failureView.forward(req, res);
}
}
}
|
9245bf61e1159e6bc7ad2ca15f172214921b236b | 847 | java | Java | app/src/main/java/coid/moonlay/pickupondemand/jet/model/map/Step.java | jetexpress/coid.moonlay.pickupondemand.jet | f438d30d946fcab479de017e1bbf6644c9d11565 | [
"MIT"
] | null | null | null | app/src/main/java/coid/moonlay/pickupondemand/jet/model/map/Step.java | jetexpress/coid.moonlay.pickupondemand.jet | f438d30d946fcab479de017e1bbf6644c9d11565 | [
"MIT"
] | null | null | null | app/src/main/java/coid/moonlay/pickupondemand/jet/model/map/Step.java | jetexpress/coid.moonlay.pickupondemand.jet | f438d30d946fcab479de017e1bbf6644c9d11565 | [
"MIT"
] | 2 | 2018-01-31T08:48:27.000Z | 2018-02-07T03:26:47.000Z | 19.697674 | 56 | 0.671783 | 1,003,508 | package coid.moonlay.pickupondemand.jet.model.map;
import com.google.gson.annotations.SerializedName;
public class Step
{
@SerializedName("end_location")
private Location endLocation;
@SerializedName("start_location")
private Location startLocation;
private Polyline polyline;
public Location getEndLocation()
{
return endLocation;
}
public void setEndLocation(Location endLocation)
{
this.endLocation = endLocation;
}
public Location getStartLocation()
{
return startLocation;
}
public void setStartLocation(Location startLocation)
{
this.startLocation = startLocation;
}
public Polyline getPolyline()
{
return polyline;
}
public void setPolyline(Polyline polyline)
{
this.polyline = polyline;
}
}
|
9245bfa7c573d12190f5bc20ef0267c8238ef983 | 397 | java | Java | src/main/java/net/soti/go/plugin/notification/email/model/gocd/plugin/configuration/PackageConfig.java | soti/GoCdEmailNotificationPlugin | df4a24d38257a0cfe1911f37056ded01da713f76 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/soti/go/plugin/notification/email/model/gocd/plugin/configuration/PackageConfig.java | soti/GoCdEmailNotificationPlugin | df4a24d38257a0cfe1911f37056ded01da713f76 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/soti/go/plugin/notification/email/model/gocd/plugin/configuration/PackageConfig.java | soti/GoCdEmailNotificationPlugin | df4a24d38257a0cfe1911f37056ded01da713f76 | [
"Apache-2.0"
] | null | null | null | 20.894737 | 78 | 0.732997 | 1,003,509 | package net.soti.go.plugin.notification.email.model.gocd.plugin.configuration;
import com.google.gson.annotations.SerializedName;
/**
* User: wsim
* Date: 2018-04-03
*/
public class PackageConfig {
@SerializedName("REPO_ID")
private String repoId;
@SerializedName("PACKAGE_PATH")
private String packagePath;
@SerializedName("PACKAGE_ID")
private String packageId;
}
|
9245c037290ee16cbda95de8c76efc2df82f8a79 | 777 | java | Java | dspace-api/src/main/java/org/dspace/content/service/SiteService.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 541 | 2015-01-08T17:28:08.000Z | 2022-03-28T07:16:48.000Z | dspace-api/src/main/java/org/dspace/content/service/SiteService.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 2,364 | 2015-01-02T16:39:38.000Z | 2022-03-31T21:04:54.000Z | dspace-api/src/main/java/org/dspace/content/service/SiteService.java | clairtonluz/DSpace | 1db8e382d574234d0444ab90b4a02d34917ec12f | [
"BSD-3-Clause"
] | 973 | 2015-01-09T15:12:13.000Z | 2022-03-29T23:41:13.000Z | 27.75 | 116 | 0.763192 | 1,003,510 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.content.service;
import java.sql.SQLException;
import org.dspace.content.Site;
import org.dspace.core.Context;
/**
* Service interface class for the Site object.
* The implementation of this class is responsible for all business logic calls for the Site object and is autowired
* by spring
*
* @author kevinvandevelde at atmire.com
*/
public interface SiteService extends DSpaceObjectService<Site> {
public Site createSite(Context context) throws SQLException;
public Site findSite(Context context) throws SQLException;
}
|
9245c18aa20606bf1845338cbe69393d98d940d9 | 540 | java | Java | src/main/java/com/qingchi/server/model/SetUserFilterVO.java | g2863784098/qingchi-web | 904e347ea403f130ff51f16f07503dd6295495b3 | [
"MIT"
] | 4 | 2021-03-31T07:41:39.000Z | 2022-02-25T16:05:35.000Z | src/main/java/com/qingchi/server/model/SetUserFilterVO.java | g2863784098/qingchi-web | 904e347ea403f130ff51f16f07503dd6295495b3 | [
"MIT"
] | null | null | null | src/main/java/com/qingchi/server/model/SetUserFilterVO.java | g2863784098/qingchi-web | 904e347ea403f130ff51f16f07503dd6295495b3 | [
"MIT"
] | 6 | 2021-01-09T08:04:50.000Z | 2021-02-27T04:00:37.000Z | 22.5 | 49 | 0.712963 | 1,003,511 | package com.qingchi.server.model;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @author qinkaiyuan 查询结果可以没有set和空构造,前台传值可以没有get
* @date 2019-08-13 23:34
*/
@Data
public class SetUserFilterVO {
@NotBlank
private String gender;
@NotNull
@Range(min = 0, max = 40, message = "参数异常")
private Integer minAge;
@NotNull
@Range(min = 0, max = 40, message = "参数异常")
private Integer maxAge;
}
|
9245c1b597fc2c26a80c4cd7fbb488d3956dafed | 6,097 | java | Java | src/main/java/hu/lordoftheflies/hydra/ui/BackendCookieCsrfTokenRepository.java | lordoftheflies/hydra-ui | f3a3069074c3cc06796682b39db51830b22cc107 | [
"Apache-2.0"
] | null | null | null | src/main/java/hu/lordoftheflies/hydra/ui/BackendCookieCsrfTokenRepository.java | lordoftheflies/hydra-ui | f3a3069074c3cc06796682b39db51830b22cc107 | [
"Apache-2.0"
] | null | null | null | src/main/java/hu/lordoftheflies/hydra/ui/BackendCookieCsrfTokenRepository.java | lordoftheflies/hydra-ui | f3a3069074c3cc06796682b39db51830b22cc107 | [
"Apache-2.0"
] | null | null | null | 36.291667 | 215 | 0.689191 | 1,003,512 | /*
* 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.
*/
package hu.lordoftheflies.hydra.ui;
import java.lang.reflect.Method;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
*
* @author lordoftheflies
*/
public final class BackendCookieCsrfTokenRepository implements CsrfTokenRepository {
static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN";
static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN";
private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;
private String headerName = DEFAULT_CSRF_HEADER_NAME;
private String cookieName = DEFAULT_CSRF_COOKIE_NAME;
private final Method setHttpOnlyMethod;
private boolean cookieHttpOnly;
public BackendCookieCsrfTokenRepository() {
this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
if (this.setHttpOnlyMethod != null) {
this.cookieHttpOnly = true;
}
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return new DefaultCsrfToken(this.headerName, this.parameterName,
createNewToken());
}
@Override
public void saveToken(CsrfToken token, HttpServletRequest request,
HttpServletResponse response) {
String tokenValue = token == null ? "" : token.getToken();
Cookie cookie = new Cookie(this.cookieName, tokenValue);
cookie.setSecure(request.isSecure());
cookie.setPath(getCookiePath(request));
if (token == null) {
cookie.setMaxAge(0);
} else {
cookie.setMaxAge(-1);
}
if (cookieHttpOnly && setHttpOnlyMethod != null) {
ReflectionUtils.invokeMethod(setHttpOnlyMethod, cookie, Boolean.TRUE);
}
response.addCookie(cookie);
}
@Override
public CsrfToken loadToken(HttpServletRequest request) {
Cookie cookie = WebUtils.getCookie(request, this.cookieName);
if (cookie == null) {
return null;
}
String token = cookie.getValue();
if (!StringUtils.hasLength(token)) {
return null;
}
return new DefaultCsrfToken(this.headerName, this.parameterName, token);
}
/**
* Sets the name of the HTTP request parameter that should be used to
* provide a token.
*
* @param parameterName the name of the HTTP request parameter that should
* be used to provide a token
*/
public void setParameterName(String parameterName) {
Assert.notNull(parameterName, "parameterName is not null");
this.parameterName = parameterName;
}
/**
* Sets the name of the HTTP header that should be used to provide the
* token.
*
* @param headerName the name of the HTTP header that should be used to
* provide the token
*/
public void setHeaderName(String headerName) {
Assert.notNull(headerName, "headerName is not null");
this.headerName = headerName;
}
/**
* Sets the name of the cookie that the expected CSRF token is saved to and
* read from.
*
* @param cookieName the name of the cookie that the expected CSRF token is
* saved to and read from
*/
public void setCookieName(String cookieName) {
Assert.notNull(cookieName, "cookieName is not null");
this.cookieName = cookieName;
}
/**
* Sets the HttpOnly attribute on the cookie containing the CSRF token. The
* cookie will only be marked as HttpOnly if both
* <code>cookieHttpOnly</code> is <code>true</code> and the underlying
* version of Servlet is 3.0 or greater. Defaults to <code>true</code> if
* the underlying version of Servlet is 3.0 or greater. NOTE: The
* {@link Cookie#setHttpOnly(boolean)} was introduced in Servlet 3.0.
*
* @param cookieHttpOnly <code>true</code> sets the HttpOnly attribute,
* <code>false</code> does not set it (depending on Servlet version)
* @throws IllegalArgumentException if <code>cookieHttpOnly</code> is
* <code>true</code> and the underlying version of Servlet is less than 3.0
*/
public void setCookieHttpOnly(boolean cookieHttpOnly) {
if (cookieHttpOnly && setHttpOnlyMethod == null) {
throw new IllegalArgumentException("Cookie will not be marked as HttpOnly because you are using a version of Servlet less than 3.0. NOTE: The Cookie#setHttpOnly(boolean) was introduced in Servlet 3.0.");
}
this.cookieHttpOnly = cookieHttpOnly;
}
private String getCookiePath(HttpServletRequest request) {
// String contextPath = request.getContextPath();
// return contextPath.length() > 0 ? contextPath : "/";
return "/";
}
/**
* Factory method to conveniently create an instance that has
* {@link #setCookieHttpOnly(boolean)} set to false.
*
* @return and instance of CookieCsrfTokenRepository with
* {@link #setCookieHttpOnly(boolean)} set to false
*/
public static BackendCookieCsrfTokenRepository withHttpOnlyFalse() {
BackendCookieCsrfTokenRepository result = new BackendCookieCsrfTokenRepository();
result.setCookieHttpOnly(false);
return result;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
}
|
9245c1b6aac5572145fa16d9647761571aad2396 | 19,940 | java | Java | src/main/java/com/github/sohalsdr/mdMathTool/mdMathTool.java | sohalsdr/mdMathTool | 937f9068e9f086d474386c2c2b836d31be37177c | [
"MIT"
] | 3 | 2020-10-01T19:15:23.000Z | 2020-11-01T07:21:26.000Z | src/main/java/com/github/sohalsdr/mdMathTool/mdMathTool.java | sohalsdr/mdMathTool | 937f9068e9f086d474386c2c2b836d31be37177c | [
"MIT"
] | 1 | 2020-10-30T13:40:38.000Z | 2020-11-08T13:13:49.000Z | src/main/java/com/github/sohalsdr/mdMathTool/mdMathTool.java | sohalsdr/mdMathTool | 937f9068e9f086d474386c2c2b836d31be37177c | [
"MIT"
] | null | null | null | 55.388889 | 420 | 0.489318 | 1,003,513 | package com.github.sohalsdr.mdMathTool;
import org.apache.commons.text.StringEscapeUtils;
import javax.script.ScriptException;
import java.io.*;
import java.util.Scanner;
import static com.github.sohalsdr.mdMathTool.changeDelims.replaceDelims;
import static com.github.sohalsdr.mdMathTool.convertGitHub.convertToGitHub;
import static com.github.sohalsdr.mdMathTool.convertGitHub.githubify;
import static com.github.sohalsdr.mdMathTool.printToTerminal.printOut;
public class mdMathTool {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//MAKE SURE TO CHANGE VERSION BEFORE RELEASE!!!
String version = "1.2.0";
try {
if ((args[0].equals("-a")) || (args[0].equals("-s")) || (args[0].equals("-b")) || (args[0].equals("-q"))) {
String mode = args[0];
if (mode.equals("-a")) {
try {
if ((args[1].substring(args[1].lastIndexOf(".")).equals(".md")) && (args[2].substring(args[2].lastIndexOf(".")).equals(".md"))) {
advancedMode(args[1], args[2], StringEscapeUtils.escapeJava(args[3]), args[4]);
} else{
System.out.println("Either your source or destination file are not .md files.");
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
} else if (mode.equals("-s")) {
simpleMode();
} else if (mode.equals("-b")) {
batchMode(args[1], args[2], StringEscapeUtils.escapeJava(args[3]), args[4]);
} else if (mode.equals("-q")) {
if (args.length == 1) {
System.out.println("Please enter the equation you want to quick-convert. ");
System.out.print("Equation: ");
String equation = in.nextLine();
System.out.println(githubify(equation));
} else if (args.length == 2) {
String equation = args[1];
System.out.println("Processing equation " + equation+"...");
System.out.println(githubify(equation));
} else {
System.out.println("Not a valid equation. Please wrap any equations with spaces inside in quotations.");
}
}
} else if(args[0].equals("version")) {
System.out.println("mdMathTool release "+version);
}else if(args[0].equals("help")) {
// File modeHelp = new File("./modeHelp.txt");
// printOut(modeHelp);
System.out.print("----mdMathTool------------------------------------------------\n" +
"Various utilities to make working with math in markdown easier\n" +
"https://github.com/sohalsdr/mdMathTool\n" +
"\n" +
"MODES\n" +
" SIMPLE: Prompts user through individual arguments\n" +
" ADVANCED: Accepts all arguments at command start\n" +
" BATCH: Same as Advanced, but converts a whole folder\n" +
" QUICK: You put in an equation, and it spits out a GitHub embed, as simple as that\n" +
"\n" +
"USAGE\n" +
" SIMPLE: mdmathtool -s\n" +
" ADVANCED: mdmathtool -a <Source File> <Destination File> <Source Delimiter> <Destination Delimiter>\n" +
" BATCH: mdmathtool -b <Source Folder> <Append To File Name> <Source Delimiter> <Destination Delimiter>\n" +
" QUICK: mdmathtool -q\n" +
" or\n" +
" mdmathtool -q <equation>\n" +
"\n" +
"FORMATS\n" +
" Common math delimiters are $ and $$, although the program will accept any delimiter put in. In Advanced Mode, delimiters must be surrounded with ' '\n" +
"(e.g. '$'). Simple mode does not require the ' ' (for whatever reason).\n" +
" If \"github\" is chosen as the destination delimiter, the program will render all detected equations into images for use with GitHub.\n" +
" For Batch mode, the <Append To File Name> flag is a string that will be appended to the end of the filename, before the extension. For example, if a folder you passed through batchmode had \"test.md\" and \"anothertest.md\", and you put \"bananas\" as appendToFileName, the output files would be \"testbananas.md\" and \"anothertestbananas.md\". appendToFileName cannot have any spaces.\n" +
" In quick mode, if feeding the equation in as a commandline argument, it must be wrapped in quotations (e.g \"x^2 = 10\").\n" +
"--------------------------------------------------------------");
System.exit(0);
} else {
System.out.println("Invalid Mode argument, please run with a mode argument");
System.out.println("Run with argument \"help\" for more info");
}
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("No Mode argument found, please run with a mode argument");
System.out.println("Run with argument \"help\" for more info");
} catch (IOException | NoSuchMethodException | ScriptException ex) {
ex.printStackTrace();
}
}
public static void advancedMode(String sourceDir, String destDir, String sourceDelim, String destDelim) throws IOException {
if (destDir.equals(sourceDir)) {
System.err.println("You have chosen the same file for both sources. Please choose a different destination file.");
System.exit(0);
}
sourceDir = sourceDir.replace('~', '.');
destDir = destDir.replace('~', '.');
if (destDelim.toLowerCase().equals("github")) {
File sourceFile = new File (sourceDir);
File destFile = new File (destDir);
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists())
destFile.createNewFile();
if (destFile.createNewFile()) {
System.out.println("File " + destDir + " Created");
}
convertToGitHub(sourceFile, destFile, sourceDelim);
} else {
String sourceDelimL = sourceDelim;
String sourceDelimR = sourceDelim;
if (sourceDelim.toLowerCase().equals("latex\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
String destDelimL = destDelim;
String destDelimR = destDelim;
if (destDelim.toLowerCase().equals("latex\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
File sourceFile = new File (sourceDir);
File destFile = new File (destDir);
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists())
destFile.createNewFile();
if (destFile.createNewFile()) {
System.out.println("File " + destDir + " Created");
}
replaceDelims(sourceFile, destFile, sourceDelimL, sourceDelimR, destDelimL, destDelimR);
}
}
public static void simpleMode() throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to mdMathTool Simple Mode.");
System.out.print("Please enter the path to your source file. Note that it should either be an absolute path from root (e. g. /Users/sohalsdr/Desktop/example.md), or a relative path from home if on a UNIX-based system (~/Desktop/example.md).\n Source File: ");
String sourceDir = in.nextLine().replace(" ", "");
System.out.print("Please enter the path to your destination file. Note that it should either be an absolute path from root (e. g. /Users/sohalsdr/Desktop/exampleOutput.md), or a relative path from home if on a UNIX-based system (~/Desktop/exampleOutput.md).\n Destination File: ");
String destDir = in.nextLine().replace(" ", "");
sourceDir = sourceDir.replace('~', '.');
destDir = destDir.replace('~', '.');
if (destDir.equals(sourceDir)) {
System.err.println("You have chosen the same file for both sources. Please choose a different destination file.");
System.exit(0);
}
if (!(sourceDir.substring(sourceDir.lastIndexOf(".")).equals(".md")) || !(destDir.substring(destDir.lastIndexOf(".")).equals(".md")) ){
System.out.println("Either your source or destination file was not a .md file. Please try again");
System.exit(0);
}
System.out.print("Please enter your source delimiter.\nSource Delimiter: ");
String sourceDelim = in.nextLine().replace(" ", "").replace("\'", "");
System.out.print("Please enter your destination delimiter.\nDestination Delimiter: ");
String destDelim = in.nextLine().replace(" ", "").replace("\'", "");
System.out.println(sourceDelim);
System.out.println(destDelim);
if (destDelim.toLowerCase().equals("github")) {
File sourceFile = new File (sourceDir);
File destFile = new File (destDir);
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists())
destFile.createNewFile();
if (destFile.createNewFile()) {
System.out.println("File " + destDir + " Created");
}
convertToGitHub(sourceFile, destFile, sourceDelim);
} else {
String sourceDelimL = sourceDelim;
String sourceDelimR = sourceDelim;
if (sourceDelim.toLowerCase().equals("latex\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
String destDelimL = destDelim;
String destDelimR = destDelim;
if (destDelim.toLowerCase().equals("latex\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
File sourceFile = new File (sourceDir);
File destFile = new File (destDir);
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists())
destFile.createNewFile();
if (destFile.createNewFile()) {
System.out.println("File " + destDir + " Created");
}
replaceDelims(sourceFile, destFile, sourceDelimL, sourceDelimR, destDelimL, destDelimR);
}
}
public static void batchMode(String sourceDirString, String appendToFilename, String sourceDelim, String destDelim) throws IOException {
sourceDirString = sourceDirString.replace('~', '.');
File sourceDir = new File(sourceDirString);
if(sourceDir.isDirectory()) {
for(File sourceFile : sourceDir.listFiles()) {
String sourceFileString = sourceFile.toString();
int lastIndex = sourceFileString.lastIndexOf(".");
if(lastIndex != -1) {
if (sourceFileString.substring(sourceFileString.lastIndexOf(".")).equals(".md")) {
System.out.println(sourceFileString);
int lastDotIndex = sourceFileString.lastIndexOf(".");
String destFileString = sourceFileString.substring(0, lastDotIndex) + appendToFilename + sourceFileString.substring(lastDotIndex);
File destFile = new File(destFileString);
if (destFile.createNewFile()) {
System.out.println("File " + destFileString + " Created");
}
if (destDelim.toLowerCase().equals("github")) {
convertToGitHub(sourceFile, destFile, sourceDelim);
} else {
String sourceDelimL = sourceDelim;
String sourceDelimR = sourceDelim;
if (sourceDelim.toLowerCase().equals("latex\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\[")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (sourceDelim.toLowerCase().equals("latex\\\\(")) {
// sourceDelimL = "\\[";
// sourceDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
String destDelimL = destDelim;
String destDelimR = destDelim;
if (destDelim.toLowerCase().equals("latex\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\[")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
if (destDelim.toLowerCase().equals("latex\\\\(")) {
// destDelimL = "\\[";
// destDelimR = "\\]";
System.err.println("This delimiter option is not supported yet");
System.exit(0);
}
replaceDelims(sourceFile, destFile, sourceDelimL, sourceDelimR, destDelimL, destDelimR);
}
}
}
}
}else {
System.out.println(sourceDirString + " is not a valid folder. Either select a folder, or run with the -a argument to process a single file.");
System.exit(0);
}
}
}
|
9245c392f91c9d191d5cc9743e82dd997bc9a06c | 579 | java | Java | gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrAttrgroupRelationDao.java | fhx210114/gulimall | 97d282f3f5273ce67949090eeea5a4a09002b796 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrAttrgroupRelationDao.java | fhx210114/gulimall | 97d282f3f5273ce67949090eeea5a4a09002b796 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:12:29.000Z | 2021-09-20T21:02:37.000Z | gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrAttrgroupRelationDao.java | fhx210114/gulimall | 97d282f3f5273ce67949090eeea5a4a09002b796 | [
"Apache-2.0"
] | null | null | null | 26.409091 | 92 | 0.795181 | 1,003,514 | package com.atguigu.gulimall.product.dao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 属性&属性分组关联
*
* @author kite
* @email [email protected]
* @date 2020-09-24 19:30:42
*/
@Mapper
public interface AttrAttrgroupRelationDao extends BaseMapper<AttrAttrgroupRelationEntity> {
void deleteBatChRelation(@Param("entities") List<AttrAttrgroupRelationEntity> entities);
}
|
9245c44e3581b559e8b6919990e470b4e84b755f | 1,478 | java | Java | src/main/java/com/socion/session/dto/Member.java | arghyam/PDA-SESSION | 041a1c2264c16dbb3c08f5436986150c2d3dd42a | [
"MIT"
] | null | null | null | src/main/java/com/socion/session/dto/Member.java | arghyam/PDA-SESSION | 041a1c2264c16dbb3c08f5436986150c2d3dd42a | [
"MIT"
] | null | null | null | src/main/java/com/socion/session/dto/Member.java | arghyam/PDA-SESSION | 041a1c2264c16dbb3c08f5436986150c2d3dd42a | [
"MIT"
] | 1 | 2022-02-02T04:59:25.000Z | 2022-02-02T04:59:25.000Z | 19.972973 | 76 | 0.634641 | 1,003,515 | package com.socion.session.dto;
import java.util.List;
public class Member {
private String userId;
private List<String> roles;
private String optionalRoleDescription;
private List<String> resourceList;
private Long sessionId;
private String name;
private String photo;
public Member() {
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getOptionalRoleDescription() {
return optionalRoleDescription;
}
public void setOptionalRoleDescription(String optionalRoleDescription) {
this.optionalRoleDescription = optionalRoleDescription;
}
public List<String> getResourceList() {
return resourceList;
}
public void setResourceList(List<String> resourceList) {
this.resourceList = resourceList;
}
public Long getSessionId() {
return sessionId;
}
public void setSessionId(Long sessionId) {
this.sessionId = sessionId;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
9245c4e3f0a4e8a5f8e122f58fdff1a14bd6fb2c | 1,203 | java | Java | src/main/java/mezz/modnametooltip/ModNameTooltipClient.java | Greg-21/ModNameTooltip-fork | 5a69fb35827d728c53e84f110cfc9b8879a68f54 | [
"MIT"
] | 8 | 2015-12-11T16:32:36.000Z | 2022-03-25T14:28:04.000Z | src/main/java/mezz/modnametooltip/ModNameTooltipClient.java | Greg-21/ModNameTooltip-fork | 5a69fb35827d728c53e84f110cfc9b8879a68f54 | [
"MIT"
] | 20 | 2016-06-05T17:28:36.000Z | 2022-01-18T23:21:01.000Z | src/main/java/mezz/modnametooltip/ModNameTooltipClient.java | Greg-21/ModNameTooltip-fork | 5a69fb35827d728c53e84f110cfc9b8879a68f54 | [
"MIT"
] | 12 | 2015-12-14T08:26:01.000Z | 2021-12-03T12:17:40.000Z | 41.482759 | 138 | 0.822111 | 1,003,516 | package mezz.modnametooltip;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import java.util.function.Consumer;
public class ModNameTooltipClient {
public static void run() {
Config config = new Config();
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, config.getConfigSpec());
TooltipEventHandler tooltipEventHandler = new TooltipEventHandler(config);
IEventBus eventBus = MinecraftForge.EVENT_BUS;
addListener(eventBus, ModConfigEvent.class, EventPriority.NORMAL, config::onConfigChanged);
addListener(eventBus, ItemTooltipEvent.class, EventPriority.LOW, tooltipEventHandler::onToolTip);
}
private static <T extends Event> void addListener(IEventBus eventBus, Class<T> eventType, EventPriority priority, Consumer<T> listener) {
eventBus.addListener(priority, false, eventType, listener);
}
}
|
9245c4f5246f2b1f06e9bc810f1f942c6b1c0506 | 620 | java | Java | src/main/java/tanks/modapi/menus/FixedMenu.java | pythoncoder1234/Tanks-Multiplayer-Modding-API | c105d21f95bacfd5c8af12146896847cda8cfa20 | [
"MIT"
] | null | null | null | src/main/java/tanks/modapi/menus/FixedMenu.java | pythoncoder1234/Tanks-Multiplayer-Modding-API | c105d21f95bacfd5c8af12146896847cda8cfa20 | [
"MIT"
] | null | null | null | src/main/java/tanks/modapi/menus/FixedMenu.java | pythoncoder1234/Tanks-Multiplayer-Modding-API | c105d21f95bacfd5c8af12146896847cda8cfa20 | [
"MIT"
] | null | null | null | 22.142857 | 56 | 0.669355 | 1,003,517 | package tanks.modapi.menus;
import tanks.IDrawable;
import tanks.modapi.ModAPI;
public abstract class FixedMenu implements IDrawable
{
public double id = Math.random() * Double.MAX_VALUE;
public double posX = 0;
public double posY = 0;
public double posZ = 0;
public double sizeX = 300;
public double sizeY = 300;
public double sizeZ = 1;
public int duration = 0;
public boolean afterGameStarted = false;
public int drawLevel = 3;
public FixedMenu()
{
ModAPI.ids.put(this.id, this);
}
public abstract void draw();
public abstract void update();
}
|
9245c511eb9d4891173fb4995ccd290f5fa8d21b | 910 | java | Java | src/main/java/it/polimi/ingsw/server/messages/clienttoserver/ServerMessage.java | pablogiaccaglia/ing-sw-2021-laconca-lodari-giaccaglia | 16eb658e74a3ea580b64c30fc870aba402404475 | [
"MIT"
] | 1 | 2022-03-18T09:59:21.000Z | 2022-03-18T09:59:21.000Z | src/main/java/it/polimi/ingsw/server/messages/clienttoserver/ServerMessage.java | pablogiaccaglia/ing-sw-2021-laconca-lodari-giaccaglia | 16eb658e74a3ea580b64c30fc870aba402404475 | [
"MIT"
] | null | null | null | src/main/java/it/polimi/ingsw/server/messages/clienttoserver/ServerMessage.java | pablogiaccaglia/ing-sw-2021-laconca-lodari-giaccaglia | 16eb658e74a3ea580b64c30fc870aba402404475 | [
"MIT"
] | 2 | 2021-09-08T12:07:43.000Z | 2022-02-24T10:13:18.000Z | 32.5 | 82 | 0.757143 | 1,003,518 | package it.polimi.ingsw.server.messages.clienttoserver;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import it.polimi.ingsw.server.ClientHandler;
import it.polimi.ingsw.server.utils.GsonAdapters;
import static it.polimi.ingsw.network.jsonutils.JsonUtility.deserializeFromString;
/**
* All the messages from the client to the server implement this interface.
* It contains methods that can only be used in the server.
*/
public interface ServerMessage {
void processMessage(ClientHandler clientHandler);
static ServerMessage deserialize(String jsonString){
Gson gson1 = new GsonBuilder()
.registerTypeAdapterFactory(GsonAdapters.gsonServerMessageAdapter)
.registerTypeAdapterFactory(GsonAdapters.gsonEventMessageAdapter)
.create();
return deserializeFromString(jsonString, ServerMessage.class,gson1);
}
}
|
9245c5813b179523b4736139cdd75da20006b907 | 1,407 | java | Java | PracticalTest01Var02/src/ro/pub/cs/systems/eim/practicaltest01var02/ProcessingThread.java | georgianaIzabela/PracticalTest01Var02 | 891e42408835e70d70de2696621377d339995284 | [
"Apache-2.0"
] | null | null | null | PracticalTest01Var02/src/ro/pub/cs/systems/eim/practicaltest01var02/ProcessingThread.java | georgianaIzabela/PracticalTest01Var02 | 891e42408835e70d70de2696621377d339995284 | [
"Apache-2.0"
] | null | null | null | PracticalTest01Var02/src/ro/pub/cs/systems/eim/practicaltest01var02/ProcessingThread.java | georgianaIzabela/PracticalTest01Var02 | 891e42408835e70d70de2696621377d339995284 | [
"Apache-2.0"
] | null | null | null | 29.93617 | 114 | 0.668088 | 1,003,519 | package ro.pub.cs.systems.eim.practicaltest01var02;
import java.util.Date;
import java.util.Random;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ProcessingThread extends Thread{
private Context context = null;
private int firstNr, secondNr;
private double artmean, geomean;
private boolean isRunning = true;
private Random random = new Random();
public ProcessingThread (Context context, int firstNr, int secondNr) {
this.context = context;
this.firstNr = firstNr;
this.secondNr = secondNr;
artmean = (firstNr + secondNr) / 2;
geomean = Math.sqrt(firstNr * secondNr);
}
@Override
public void run () {
Log.d("[ProcessingThread]", "Thread has started!");
while (isRunning) {
Intent intent = new Intent();
//intent.setAction(Constants.actions[random.nextInt(Constants.actions.length)]);
intent.putExtra("message", new Date(System.currentTimeMillis()) + " " + this.artmean + " " + this.geomean);
context.sendBroadcast(intent);
sleep();
}
Log.d("[ProcessingThread]", "Thread has stopped!");
}
private void sleep() {
try {
Thread.sleep(10000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}
public void stopThread() {
isRunning = false;
}
}
|
9245c5d09bad81b49e37d72cb4743585e1f7586d | 4,881 | java | Java | app/src/main/java/com/nethergrim/combogymdiary/activities/StatisticsActivity.java | nethergrim/Training-Log | cabea47a9dd6e4988e8a5031d90cdf7f3f64d89b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/nethergrim/combogymdiary/activities/StatisticsActivity.java | nethergrim/Training-Log | cabea47a9dd6e4988e8a5031d90cdf7f3f64d89b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/nethergrim/combogymdiary/activities/StatisticsActivity.java | nethergrim/Training-Log | cabea47a9dd6e4988e8a5031d90cdf7f3f64d89b | [
"Apache-2.0"
] | null | null | null | 34.132867 | 86 | 0.627535 | 1,003,520 | package com.nethergrim.combogymdiary.activities;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.nethergrim.combogymdiary.R;
import com.nethergrim.combogymdiary.fragments.StatisticsMeasuringsFragment;
import com.nethergrim.combogymdiary.fragments.StatisticsWeightsFragment;
import java.util.Locale;
public class StatisticsActivity extends AnalyticsActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics_new);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle(R.string.statistics);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return false;
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new StatisticsWeightsFragment();
} else if (position == 1) {
fragment = new StatisticsMeasuringsFragment();
}
return fragment;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.weight_reps).toUpperCase(l);
case 1:
return getString(R.string.measures).toUpperCase(l);
case 2:
return getString(R.string.total_weight).toUpperCase(l);
}
return null;
}
}
}
|
9245c6adf8a6c9faf4e26ca7d2abc0a9a6532d68 | 1,893 | java | Java | service/interactivespaces-service-image-vision/src/main/java/interactivespaces/service/image/video/VideoLoop.java | EndPointCorp/interactivespaces | 74b052e5a184f1273010df5d02dc693a64b098e7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | service/interactivespaces-service-image-vision/src/main/java/interactivespaces/service/image/video/VideoLoop.java | EndPointCorp/interactivespaces | 74b052e5a184f1273010df5d02dc693a64b098e7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | service/interactivespaces-service-image-vision/src/main/java/interactivespaces/service/image/video/VideoLoop.java | EndPointCorp/interactivespaces | 74b052e5a184f1273010df5d02dc693a64b098e7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 25.24 | 90 | 0.686741 | 1,003,521 | /*
* Copyright (C) 2013 Google 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 interactivespaces.service.image.video;
import interactivespaces.util.concurrency.CancellableLoop;
import com.google.common.collect.Lists;
import java.util.List;
/**
* A loop for capturing video.
*
* @param <T>
* the type of video frame
*
* @author Keith M. Hughes
*/
public abstract class VideoLoop<T> extends CancellableLoop {
/**
* A set of processors for the video frames.
*/
private final List<VideoFrameProcessor<T>> processors = Lists.newCopyOnWriteArrayList();
/**
* Add a new frame processor to the loop.
*
* @param processor
* the new processor
*/
public void addProcessor(VideoFrameProcessor<T> processor) {
processors.add(processor);
}
/**
* Remove a frame processor from the loop.
*
* <p>
* Does nothing if the processor was never added.
*
* @param processor
* the processor to remove
*/
public void removeProcessor(VideoFrameProcessor<T> processor) {
processors.remove(processor);
}
/**
* Notify all processors about a new video frame.
*
* @param frame
* the new frame
*/
protected void notifyListenersNewVideoFrame(T frame) {
for (VideoFrameProcessor<T> processor : processors) {
processor.onNewVideoFrame(frame);
}
}
}
|
9245c73dc7c832ae417ce7b1026cca27d016691d | 2,448 | java | Java | simm-model/src/test/java/com/acadiasoft/simm/model/util/BigDecimalUtilsTest.java | mymbrooks/simm-lib | d093ae12d275c0b0e9d8f569fae108bbac0a2d08 | [
"MIT"
] | 1 | 2018-09-05T07:51:07.000Z | 2018-09-05T07:51:07.000Z | simm-model/src/test/java/com/acadiasoft/simm/model/util/BigDecimalUtilsTest.java | mymbrooks/simm-lib | d093ae12d275c0b0e9d8f569fae108bbac0a2d08 | [
"MIT"
] | null | null | null | simm-model/src/test/java/com/acadiasoft/simm/model/util/BigDecimalUtilsTest.java | mymbrooks/simm-lib | d093ae12d275c0b0e9d8f569fae108bbac0a2d08 | [
"MIT"
] | null | null | null | 42.206897 | 154 | 0.742239 | 1,003,522 | /*
* Copyright (c) 2017 AcadiaSoft, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.acadiasoft.simm.model.util;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class BigDecimalUtilsTest {
@Test
public void sqrt() {
Assert.assertEquals(new BigDecimal("2"), BigDecimalUtils.sqrt(new BigDecimal("4")));
Assert.assertEquals(new BigDecimal("3"), BigDecimalUtils.sqrt(new BigDecimal("9")));
Assert.assertEquals(new BigDecimal("4"), BigDecimalUtils.sqrt(new BigDecimal("16")));
Assert.assertEquals(new BigDecimal("5"), BigDecimalUtils.sqrt(new BigDecimal("25")));
}
@Test
public void square() {
Assert.assertEquals(new BigDecimal("4"), BigDecimalUtils.square(new BigDecimal("2")));
Assert.assertEquals(new BigDecimal("9"), BigDecimalUtils.square(new BigDecimal("3")));
Assert.assertEquals(new BigDecimal("16"), BigDecimalUtils.square(new BigDecimal("4")));
Assert.assertEquals(new BigDecimal("25"), BigDecimalUtils.square(new BigDecimal("5")));
}
@Test
public void squareInStream() {
List<BigDecimal> list = Arrays.asList(new BigDecimal("2"), new BigDecimal("3"));
Assert.assertEquals(Arrays.asList(new BigDecimal("4"), new BigDecimal("9")), list.stream().map(BigDecimalUtils::square).collect(Collectors.toList()));
}
}
|
9245c79dca065634be34f69498f0907ff8321f72 | 21,724 | java | Java | flow-server/src/main/java/com/vaadin/flow/server/frontend/NodeUpdater.java | vaadin/flow | 290feac84a2234b343402e5a604f46fc8908a94f | [
"Apache-2.0"
] | 402 | 2017-10-02T09:00:34.000Z | 2022-03-30T06:09:40.000Z | flow-server/src/main/java/com/vaadin/flow/server/frontend/NodeUpdater.java | vaadin/flow | 290feac84a2234b343402e5a604f46fc8908a94f | [
"Apache-2.0"
] | 9,144 | 2017-10-02T07:12:23.000Z | 2022-03-31T19:16:56.000Z | flow-server/src/main/java/com/vaadin/flow/server/frontend/NodeUpdater.java | vaadin/flow | 290feac84a2234b343402e5a604f46fc8908a94f | [
"Apache-2.0"
] | 167 | 2017-10-11T13:07:29.000Z | 2022-03-22T09:02:42.000Z | 38.045534 | 110 | 0.613607 | 1,003,523 | /*
* Copyright 2000-2021 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.server.frontend;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.experimental.FeatureFlags;
import com.vaadin.flow.server.Constants;
import com.vaadin.flow.server.frontend.scanner.ClassFinder;
import com.vaadin.flow.server.frontend.scanner.FrontendDependencies;
import com.vaadin.flow.server.frontend.scanner.FrontendDependenciesScanner;
import elemental.json.Json;
import elemental.json.JsonException;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
import static com.vaadin.flow.server.Constants.COMPATIBILITY_RESOURCES_FRONTEND_DEFAULT;
import static com.vaadin.flow.server.Constants.PACKAGE_JSON;
import static com.vaadin.flow.server.Constants.RESOURCES_FRONTEND_DEFAULT;
import static com.vaadin.flow.server.frontend.FrontendUtils.FLOW_NPM_PACKAGE_NAME;
import static com.vaadin.flow.server.frontend.FrontendUtils.NODE_MODULES;
import static elemental.json.impl.JsonUtil.stringify;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Base abstract class for frontend updaters that needs to be run when in
* dev-mode or from the flow maven plugin.
* <p>
* For internal use only. May be renamed or removed in a future release.
*
* @since 2.0
*/
public abstract class NodeUpdater implements FallibleCommand {
private static final String VAADIN_FORM_PKG_LEGACY_VERSION = "flow-frontend/form";
private static final String VAADIN_FORM_PKG = "@vaadin/form";
/**
* Relative paths of generated should be prefixed with this value, so they
* can be correctly separated from {projectDir}/frontend files.
*/
public static final String GENERATED_PREFIX = "GENERATED/";
static final String DEPENDENCIES = "dependencies";
static final String VAADIN_DEP_KEY = "vaadin";
static final String HASH_KEY = "hash";
static final String DEV_DEPENDENCIES = "devDependencies";
private static final String DEP_LICENSE_KEY = "license";
private static final String DEP_LICENSE_DEFAULT = "UNLICENSED";
private static final String DEP_NAME_KEY = "name";
private static final String DEP_NAME_DEFAULT = "no-name";
private static final String DEP_MAIN_KEY = "main";
protected static final String DEP_NAME_FLOW_DEPS = "@vaadin/flow-deps";
protected static final String DEP_NAME_FLOW_JARS = "@vaadin/flow-frontend";
private static final String DEP_MAIN_VALUE = "index";
private static final String DEP_VERSION_KEY = "version";
private static final String DEP_VERSION_DEFAULT = "1.0.0";
private static final String ROUTER_VERSION = "1.7.4";
protected static final String POLYMER_VERSION = "3.2.0";
/**
* Base directory for {@link Constants#PACKAGE_JSON},
* {@link FrontendUtils#WEBPACK_CONFIG}, {@link FrontendUtils#NODE_MODULES}.
*/
protected final File npmFolder;
/**
* The path to the {@link FrontendUtils#NODE_MODULES} directory.
*/
protected final File nodeModulesFolder;
/**
* Base directory for flow generated files.
*/
protected final File generatedFolder;
/**
* Base directory for flow dependencies coming from jars.
*/
protected final File flowResourcesFolder;
/**
* The {@link FrontendDependencies} object representing the application
* dependencies.
*/
protected final FrontendDependenciesScanner frontDeps;
protected String buildDir;
final ClassFinder finder;
boolean modified;
FeatureFlags featureFlags;
/**
* Constructor.
*
* @param finder
* a reusable class finder
* @param frontendDependencies
* a reusable frontend dependencies
* @param npmFolder
* folder with the `package.json` file
* @param generatedPath
* folder where flow generated files will be placed.
* @param flowResourcesPath
* folder where flow dependencies will be copied to.
* @param buildDir
* the used build directory
* @param featureFlags
* FeatureFlags for this build
*/
protected NodeUpdater(ClassFinder finder,
FrontendDependenciesScanner frontendDependencies, File npmFolder,
File generatedPath, File flowResourcesPath, String buildDir,
FeatureFlags featureFlags) {
this.frontDeps = frontendDependencies;
this.finder = finder;
this.npmFolder = npmFolder;
this.nodeModulesFolder = new File(npmFolder, NODE_MODULES);
this.generatedFolder = generatedPath;
this.flowResourcesFolder = flowResourcesPath;
this.buildDir = buildDir;
this.featureFlags = featureFlags;
}
private File getPackageJsonFile() {
return new File(npmFolder, PACKAGE_JSON);
}
/**
* Gets the platform pinned versions that are not overridden by the user in
* package.json.
*
* @return json object with the dependencies or {@code null}
* @throws IOException
* when versions file could not be read
*/
JsonObject getPlatformPinnedDependencies() throws IOException {
URL resource = finder.getResource(Constants.VAADIN_VERSIONS_JSON);
if (resource == null) {
log().info("Couldn't find {} file to pin dependency versions."
+ " Transitive dependencies won't be pinned for pnpm.",
Constants.VAADIN_VERSIONS_JSON);
}
JsonObject versionsJson = null;
try (InputStream content = resource == null ? null
: resource.openStream()) {
if (content != null) {
VersionsJsonConverter convert = new VersionsJsonConverter(
Json.parse(IOUtils.toString(content,
StandardCharsets.UTF_8)));
versionsJson = convert.getConvertedJson();
versionsJson = new VersionsJsonFilter(getPackageJson(),
DEPENDENCIES).getFilteredVersions(versionsJson);
}
}
return versionsJson;
}
static Set<String> getGeneratedModules(File directory,
Set<String> excludes) {
if (!directory.exists()) {
return Collections.emptySet();
}
final Function<String, String> unixPath = str -> str.replace("\\", "/");
final URI baseDir = directory.toURI();
return FileUtils.listFiles(directory, new String[] { "js" }, true)
.stream().filter(file -> {
String path = unixPath.apply(file.getPath());
if (path.contains("/node_modules/")) {
return false;
}
return excludes.stream().noneMatch(
postfix -> path.endsWith(unixPath.apply(postfix)));
})
.map(file -> GENERATED_PREFIX + unixPath
.apply(baseDir.relativize(file.toURI()).getPath()))
.collect(Collectors.toSet());
}
String resolveResource(String importPath) {
String resolved = importPath;
if (!importPath.startsWith("@")) {
// We only should check here those paths starting with './' when all
// flow components
// have the './' prefix
String resource = resolved.replaceFirst("^\\./+", "");
if (hasMetaInfResource(resource)) {
if (!resolved.startsWith("./")) {
log().warn(
"Use the './' prefix for files in JAR files: '{}', please update your component.",
importPath);
}
resolved = FLOW_NPM_PACKAGE_NAME + resource;
}
}
return resolved;
}
private boolean hasMetaInfResource(String resource) {
return finder.getResource(
RESOURCES_FRONTEND_DEFAULT + "/" + resource) != null
|| finder.getResource(COMPATIBILITY_RESOURCES_FRONTEND_DEFAULT
+ "/" + resource) != null;
}
JsonObject getPackageJson() throws IOException {
JsonObject packageJson = getJsonFileContent(getPackageJsonFile());
if (packageJson == null) {
packageJson = Json.createObject();
packageJson.put(DEP_NAME_KEY, DEP_NAME_DEFAULT);
packageJson.put(DEP_LICENSE_KEY, DEP_LICENSE_DEFAULT);
}
addDefaultObjects(packageJson);
addVaadinDefaultsToJson(packageJson);
addWebpackPlugins(packageJson);
return packageJson;
}
private void addDefaultObjects(JsonObject json) {
computeIfAbsent(json, DEPENDENCIES, Json::createObject);
computeIfAbsent(json, DEV_DEPENDENCIES, Json::createObject);
}
private void addWebpackPlugins(JsonObject packageJson) {
final List<String> plugins = WebpackPluginsUtil.getPlugins();
Path targetFolder = Paths.get(npmFolder.toString(), buildDir,
WebpackPluginsUtil.PLUGIN_TARGET);
JsonObject devDependencies;
if (packageJson.hasKey(DEV_DEPENDENCIES)) {
devDependencies = packageJson.getObject(DEV_DEPENDENCIES);
} else {
devDependencies = Json.createObject();
packageJson.put(DEV_DEPENDENCIES, devDependencies);
}
String atVaadinPrefix = "@vaadin/";
String pluginTargetPrefix = "./"
+ (npmFolder.toPath().relativize(targetFolder) + "/")
.replace('\\', '/');
plugins.stream().filter(plugin -> targetFolder.toFile().exists())
.forEach(plugin -> {
String pluginTarget = pluginTargetPrefix + plugin;
devDependencies.put(atVaadinPrefix + plugin, pluginTarget);
});
// Remove plugins previously installed but no longer needed
for (String depKey : devDependencies.keys()) {
String depVersion = devDependencies.getString(depKey);
if (depKey.startsWith(atVaadinPrefix)
&& depVersion.startsWith(pluginTargetPrefix)) {
final String pluginName = depKey
.substring(atVaadinPrefix.length());
if (!plugins.contains(pluginName)) {
devDependencies.remove(depKey);
}
}
}
}
JsonObject getResourcesPackageJson() throws IOException {
JsonObject packageJson = getJsonFileContent(
new File(flowResourcesFolder, PACKAGE_JSON));
if (packageJson == null) {
packageJson = Json.createObject();
packageJson.put(DEP_NAME_KEY, DEP_NAME_FLOW_JARS);
packageJson.put(DEP_LICENSE_KEY, DEP_LICENSE_DEFAULT);
packageJson.put(DEP_MAIN_KEY, DEP_MAIN_VALUE);
packageJson.put(DEP_VERSION_KEY, DEP_VERSION_DEFAULT);
}
return packageJson;
}
static JsonObject getJsonFileContent(File packageFile) throws IOException {
JsonObject jsonContent = null;
if (packageFile.exists()) {
String fileContent = FileUtils.readFileToString(packageFile,
UTF_8.name());
try {
jsonContent = Json.parse(fileContent);
} catch (JsonException e) { // NOSONAR
throw new JsonException(String
.format("Cannot parse package file '%s'", packageFile));
}
}
return jsonContent;
}
void addVaadinDefaultsToJson(JsonObject json) {
JsonObject vaadinPackages = computeIfAbsent(json, VAADIN_DEP_KEY,
Json::createObject);
computeIfAbsent(vaadinPackages, DEPENDENCIES, () -> {
final JsonObject dependencies = Json.createObject();
getDefaultDependencies().forEach(dependencies::put);
return dependencies;
});
computeIfAbsent(vaadinPackages, DEV_DEPENDENCIES, () -> {
final JsonObject devDependencies = Json.createObject();
getDefaultDevDependencies().forEach(devDependencies::put);
return devDependencies;
});
computeIfAbsent(vaadinPackages, HASH_KEY, () -> Json.create(""));
}
private static <T extends JsonValue> T computeIfAbsent(
JsonObject jsonObject, String key, Supplier<T> valueSupplier) {
T result = jsonObject.get(key);
if (result == null) {
result = valueSupplier.get();
jsonObject.put(key, result);
}
return result;
}
Map<String, String> getDefaultDependencies() {
Map<String, String> defaults = new HashMap<>();
defaults.put("@vaadin/router", ROUTER_VERSION);
defaults.put("@polymer/polymer", POLYMER_VERSION);
defaults.put("lit", "2.0.0");
// Constructable style sheets is only implemented for chrome,
// polyfill needed for FireFox et.al. at the moment
defaults.put("construct-style-sheets-polyfill", "3.0.4");
defaults.put("@vaadin/common-frontend", "0.0.17");
return defaults;
}
Map<String, String> getDefaultDevDependencies() {
Map<String, String> defaults = new HashMap<>();
defaults.put("typescript", "4.5.3");
final String WORKBOX_VERSION = "6.4.2";
if (featureFlags.isEnabled(FeatureFlags.VITE)) {
defaults.put("vite", "v2.7.4");
defaults.put("rollup-plugin-brotli", "3.1.0");
defaults.put("vite-plugin-checker", "0.3.4");
defaults.put("mkdirp", "1.0.4"); // for application-theme-plugin
defaults.put("workbox-build", "6.4.1");
} else {
// Webpack plugins and helpers
defaults.put("esbuild-loader", "2.15.1");
defaults.put("html-webpack-plugin", "4.5.1");
defaults.put("fork-ts-checker-webpack-plugin", "6.2.1");
defaults.put("webpack", "4.46.0");
defaults.put("webpack-cli", "4.9.0");
defaults.put("webpack-dev-server", "4.1.1");
defaults.put("compression-webpack-plugin", "4.0.1");
defaults.put("extra-watch-webpack-plugin", "1.0.3");
defaults.put("webpack-merge", "4.2.2");
defaults.put("css-loader", "4.2.1");
defaults.put("extract-loader", "5.1.0");
defaults.put("lit-css-loader", "0.1.0");
defaults.put("file-loader", "6.2.0");
defaults.put("loader-utils", "2.0.0");
defaults.put("workbox-webpack-plugin", WORKBOX_VERSION);
// Forcing chokidar version for now until new babel version is
// available
// check out https://github.com/babel/babel/issues/11488
defaults.put("chokidar", "^3.5.0");
}
defaults.put("workbox-core", WORKBOX_VERSION);
defaults.put("workbox-precaching", WORKBOX_VERSION);
defaults.put("glob", "7.1.6");
return defaults;
}
/**
* Updates default dependencies and development dependencies to
* package.json.
*
* @param packageJson
* package.json json object to update with dependencies
* @return true if items were added or removed from the {@code packageJson}
*/
boolean updateDefaultDependencies(JsonObject packageJson) {
int added = 0;
for (Map.Entry<String, String> entry : getDefaultDependencies()
.entrySet()) {
added += addDependency(packageJson, DEPENDENCIES, entry.getKey(),
entry.getValue());
}
for (Map.Entry<String, String> entry : getDefaultDevDependencies()
.entrySet()) {
added += addDependency(packageJson, DEV_DEPENDENCIES,
entry.getKey(), entry.getValue());
}
if (added > 0) {
log().info("Added {} default dependencies to main package.json",
added);
}
return added > 0;
}
int addDependency(JsonObject json, String key, String pkg, String version) {
Objects.requireNonNull(json, "Json object need to be given");
Objects.requireNonNull(key, "Json sub object needs to be give.");
Objects.requireNonNull(pkg, "dependency package needs to be defined");
JsonObject vaadinDeps = json.getObject(VAADIN_DEP_KEY);
if (!json.hasKey(key)) {
json.put(key, Json.createObject());
}
json = json.get(key);
vaadinDeps = vaadinDeps.getObject(key);
if (vaadinDeps.hasKey(pkg)) {
if (version == null) {
version = vaadinDeps.getString(pkg);
}
return handleExistingVaadinDep(json, pkg, version, vaadinDeps);
} else {
vaadinDeps.put(pkg, version);
if (!json.hasKey(pkg) || isNewerVersion(json, pkg, version)) {
json.put(pkg, version);
log().debug("Added \"{}\": \"{}\" line.", pkg, version);
return 1;
}
}
return 0;
}
private boolean isNewerVersion(JsonObject json, String pkg,
String version) {
try {
FrontendVersion newVersion = new FrontendVersion(version);
FrontendVersion existingVersion = toVersion(json, pkg);
return newVersion.isNewerThan(existingVersion);
} catch (NumberFormatException e) {
if (VAADIN_FORM_PKG.equals(pkg) && json.getString(pkg)
.contains(VAADIN_FORM_PKG_LEGACY_VERSION)) {
return true;
} else {
throw e;
}
}
}
private int handleExistingVaadinDep(JsonObject json, String pkg,
String version, JsonObject vaadinDeps) {
boolean added = false;
FrontendVersion vaadinVersion = toVersion(vaadinDeps, pkg);
if (json.hasKey(pkg)) {
try {
FrontendVersion packageVersion = toVersion(json, pkg);
FrontendVersion newVersion = new FrontendVersion(version);
// Vaadin and package.json versions are the same, but dependency
// updates (can be up or down)
if (vaadinVersion.isEqualTo(packageVersion)
&& !vaadinVersion.isEqualTo(newVersion)) {
json.put(pkg, version);
added = true;
// if vaadin and package not the same, but new version is
// newer
// update package version.
} else if (newVersion.isNewerThan(packageVersion)) {
json.put(pkg, version);
added = true;
}
} catch (NumberFormatException e) { // NOSONAR
/*
* If the current version is not parseable, it can refer to a
* file and we should leave it alone
*/
}
} else {
json.put(pkg, version);
added = true;
}
// always update vaadin version to the latest set version
vaadinDeps.put(pkg, version);
if (added) {
log().debug("Added \"{}\": \"{}\" line.", pkg, version);
} else {
// we made a change to the package json vaadin defaults
// even if we didn't add to the dependencies.
added = !vaadinVersion.isEqualTo(new FrontendVersion(version));
}
return added ? 1 : 0;
}
private static FrontendVersion toVersion(JsonObject json, String key) {
return new FrontendVersion(json.getString(key));
}
String writePackageFile(JsonObject packageJson) throws IOException {
return writePackageFile(packageJson, new File(npmFolder, PACKAGE_JSON));
}
String writeResourcesPackageFile(JsonObject packageJson)
throws IOException {
return writePackageFile(packageJson,
new File(flowResourcesFolder, PACKAGE_JSON));
}
String writePackageFile(JsonObject json, File packageFile)
throws IOException {
log().debug("writing file {}.", packageFile.getAbsolutePath());
FileUtils.forceMkdirParent(packageFile);
String content = stringify(json, 2) + "\n";
FileUtils.writeStringToFile(packageFile, content, UTF_8.name());
return content;
}
Logger log() {
return LoggerFactory.getLogger(this.getClass());
}
}
|
9245c81bc2df7224bd86e62101d49e96211db9c1 | 2,141 | java | Java | android/src/org/colinw/asteroids/AsteroidsBullet.java | colinw7/CQAsteroids | ae008edcb7592db2480c96e0bdeb326c49acec95 | [
"MIT"
] | 1 | 2021-12-23T02:22:39.000Z | 2021-12-23T02:22:39.000Z | android/src/org/colinw/asteroids/AsteroidsBullet.java | colinw7/CQAsteroids | ae008edcb7592db2480c96e0bdeb326c49acec95 | [
"MIT"
] | null | null | null | android/src/org/colinw/asteroids/AsteroidsBullet.java | colinw7/CQAsteroids | ae008edcb7592db2480c96e0bdeb326c49acec95 | [
"MIT"
] | null | null | null | 19.824074 | 116 | 0.599253 | 1,003,524 | package org.colinw.asteroids;
import java.util.LinkedList;
import java.util.ListIterator;
public class AsteroidsBullet extends AsteroidsObject {
static Point draw_coords_[] = {
new Point(-0.1, -0.1),
new Point( 0.1, -0.1),
new Point(-0.1, 0.1),
new Point( 0.1, 0.1),
};
static int num_draw_coords_ = 4;
static Point collision_coords_[] = {
new Point(-0.1, -0.1),
new Point( 0.1, -0.1),
new Point(-0.1, 0.1),
new Point( 0.1, 0.1),
};
static int num_collision_coords_ = 4;
private double speed_;
private double life_;
private double d_;
public AsteroidsBullet(AsteroidsView view, double x, double y, double a, double size, double speed, double life) {
super(view, x, y, a, 0.0, 0.0, 0.0, size, 0, true);
speed_ = speed;
life_ = life;
matrix_.setRotation(2*Math.PI*a_);
Point p = matrix_.multiplyPoint(speed_, 0);
dx_ = p.x();
dy_ = p.y();
d_ = 0.0;
setDrawCoords(draw_coords_, num_draw_coords_);
setCollisionCoords(collision_coords_, num_collision_coords_);
}
@Override
public void move() {
d_ += speed_;
if (d_ > life_)
setRemove();
super.move();
}
@Override
public void intersect() {
intersectRocks();
intersectSaucers();
}
public void intersectRocks() {
LinkedList<AsteroidsRock> rocks = view_.getRockMgr().getRocks();
ListIterator<AsteroidsRock> itr = rocks.listIterator();
while (itr.hasNext()) {
AsteroidsRock rock = itr.next();
if (rock.pointInside(x_, y_)) {
rock.hit();
setRemove();
break;
}
}
}
public void intersectSaucers() {
AsteroidsSaucerMgr saucer_mgr = view_.getSaucerMgr();
LinkedList<AsteroidsSaucer> saucers = saucer_mgr.getSaucers();
ListIterator<AsteroidsSaucer> itr = saucers.listIterator();
while (itr.hasNext()) {
AsteroidsSaucer saucer = itr.next();
if (saucer.pointInside(x_, y_)) {
saucer.hit();
setRemove();
break;
}
}
}
public void destroy() {
hit();
}
} |
9245c84380c1e169c5636cfec62137a2030f81ca | 547 | java | Java | app/src/main/java/ru/art2000/calculator/view_model/calculator/HistoryViewModel.java | ARTI1208/Calculator7 | ba48bc653d2011af446f81b1ad4bc78fb53b876e | [
"MIT"
] | null | null | null | app/src/main/java/ru/art2000/calculator/view_model/calculator/HistoryViewModel.java | ARTI1208/Calculator7 | ba48bc653d2011af446f81b1ad4bc78fb53b876e | [
"MIT"
] | 57 | 2020-12-17T07:03:54.000Z | 2022-03-01T07:02:52.000Z | app/src/main/java/ru/art2000/calculator/view_model/calculator/HistoryViewModel.java | ARTI1208/Calculator | 124e366fa93510f6d6d76820f4d3cd72ad20832c | [
"MIT"
] | null | null | null | 20.259259 | 75 | 0.753199 | 1,003,525 | package ru.art2000.calculator.view_model.calculator;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import java.util.List;
import ru.art2000.calculator.model.calculator.HistoryItem;
public interface HistoryViewModel {
int COPY_ALL = 100;
int COPY_EXPR = 101;
int COPY_RES = 102;
int DELETE = 200;
LiveData<List<HistoryItem>> getHistoryItems();
String copyHistoryItemToClipboard(@NonNull HistoryItem item, int type);
void removeHistoryItem(int id);
void clearHistoryDatabase();
}
|
9245c85ddf680f2a80833f55b0caa4fb2dad419c | 13,728 | java | Java | jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/format/IntlTestDecimalFormatAPI.java | gaybro8777/j2objc | 9234ca9bed5d16a2f9914d55001ce1ec2e84dc9d | [
"Apache-2.0"
] | 4,901 | 2015-01-02T09:29:18.000Z | 2022-03-29T06:51:04.000Z | jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/format/IntlTestDecimalFormatAPI.java | 1Crazymoney/j2objc | 444f387445b3f22fd807b7c72eca484ea8823c8e | [
"Apache-2.0"
] | 853 | 2015-01-03T08:13:19.000Z | 2022-03-22T18:51:24.000Z | jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/format/IntlTestDecimalFormatAPI.java | 1Crazymoney/j2objc | 444f387445b3f22fd807b7c72eca484ea8823c8e | [
"Apache-2.0"
] | 964 | 2015-01-08T08:52:00.000Z | 2022-03-23T16:36:47.000Z | 34.149254 | 105 | 0.562427 | 1,003,526 | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*****************************************************************************************
*
* Copyright (C) 1996-2012, International Business Machines
* Corporation and others. All Rights Reserved.
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatAPI
* Source File: java/text/format/IntlTestDecimalFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format API
*/
package android.icu.dev.test.format;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
import org.junit.Test;
import android.icu.math.BigDecimal;
import android.icu.math.MathContext;
import android.icu.text.DecimalFormat;
import android.icu.text.DecimalFormatSymbols;
import android.icu.text.NumberFormat;
public class IntlTestDecimalFormatAPI extends android.icu.dev.test.TestFmwk
{
/**
* Problem 1: simply running
* decF4.setRoundingMode(java.math.BigDecimal.ROUND_HALF_UP) does not work
* as decF4.setRoundingIncrement(.0001) must also be run.
* Problem 2: decF4.format(8.88885) does not return 8.8889 as expected.
* You must run decF4.format(new BigDecimal(Double.valueOf(8.88885))) in
* order for this to work as expected.
* Problem 3: There seems to be no way to set half up to be the default
* rounding mode.
* We solved the problem with the code at the bottom of this page however
* this is not quite general purpose enough to include in icu4j. A static
* setDefaultRoundingMode function would solve the problem nicely. Also
* decimal places past 20 are not handled properly. A small ammount of work
* would make bring this up to snuff.
*/
@Test
public void testJB1871()
{
// problem 2
double number = 8.88885;
String expected = "8.8889";
String pat = ",##0.0000";
DecimalFormat dec = new DecimalFormat(pat);
dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
double roundinginc = 0.0001;
dec.setRoundingIncrement(roundinginc);
String str = dec.format(number);
if (!str.equals(expected)) {
errln("Fail: " + number + " x \"" + pat + "\" = \"" +
str + "\", expected \"" + expected + "\"");
}
pat = ",##0.0001";
dec = new DecimalFormat(pat);
dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
str = dec.format(number);
if (!str.equals(expected)) {
errln("Fail: " + number + " x \"" + pat + "\" = \"" +
str + "\", expected \"" + expected + "\"");
}
// testing 20 decimal places
pat = ",##0.00000000000000000001";
dec = new DecimalFormat(pat);
BigDecimal bignumber = new BigDecimal("8.888888888888888888885");
expected = "8.88888888888888888889";
dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
str = dec.format(bignumber);
if (!str.equals(expected)) {
errln("Fail: " + bignumber + " x \"" + pat + "\" = \"" +
str + "\", expected \"" + expected + "\"");
}
}
/**
* This test checks various generic API methods in DecimalFormat to achieve
* 100% API coverage.
*/
@Test
public void TestAPI()
{
logln("DecimalFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
}
catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if( ! def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + d + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + d + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + d + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if( ! pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if(posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if(negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if(posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if(negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if(multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if(groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if(tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if( ! s2.equals(p1) ) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if( ! s3.equals(p2) ) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
}
@Test
public void testJB6134()
{
DecimalFormat decfmt = new DecimalFormat();
StringBuffer buf = new StringBuffer();
FieldPosition fposByInt = new FieldPosition(NumberFormat.INTEGER_FIELD);
decfmt.format(123, buf, fposByInt);
buf.setLength(0);
FieldPosition fposByField = new FieldPosition(NumberFormat.Field.INTEGER);
decfmt.format(123, buf, fposByField);
if (fposByInt.getEndIndex() != fposByField.getEndIndex())
{
errln("ERROR: End index for integer field - fposByInt:" + fposByInt.getEndIndex() +
" / fposByField: " + fposByField.getEndIndex());
}
}
@Test
public void testJB4971()
{
DecimalFormat decfmt = new DecimalFormat();
MathContext resultICU;
MathContext comp1 = new MathContext(0, MathContext.PLAIN);
resultICU = decfmt.getMathContextICU();
if ((comp1.getDigits() != resultICU.getDigits()) ||
(comp1.getForm() != resultICU.getForm()) ||
(comp1.getLostDigits() != resultICU.getLostDigits()) ||
(comp1.getRoundingMode() != resultICU.getRoundingMode()))
{
errln("ERROR: Math context 1 not equal - result: " + resultICU.toString() +
" / expected: " + comp1.toString());
}
MathContext comp2 = new MathContext(5, MathContext.ENGINEERING);
decfmt.setMathContextICU(comp2);
resultICU = decfmt.getMathContextICU();
if ((comp2.getDigits() != resultICU.getDigits()) ||
(comp2.getForm() != resultICU.getForm()) ||
(comp2.getLostDigits() != resultICU.getLostDigits()) ||
(comp2.getRoundingMode() != resultICU.getRoundingMode()))
{
errln("ERROR: Math context 2 not equal - result: " + resultICU.toString() +
" / expected: " + comp2.toString());
}
java.math.MathContext result;
java.math.MathContext comp3 = new java.math.MathContext(3, java.math.RoundingMode.DOWN);
decfmt.setMathContext(comp3);
result = decfmt.getMathContext();
if ((comp3.getPrecision() != result.getPrecision()) ||
(comp3.getRoundingMode() != result.getRoundingMode()))
{
errln("ERROR: Math context 3 not equal - result: " + result.toString() +
" / expected: " + comp3.toString());
}
}
@Test
public void testJB6354()
{
DecimalFormat pat = new DecimalFormat("#,##0.00");
java.math.BigDecimal r1, r2;
// get default rounding increment
r1 = pat.getRoundingIncrement();
// set rounding mode with zero increment. Rounding
// increment should be set by this operation
pat.setRoundingMode(BigDecimal.ROUND_UP);
r2 = pat.getRoundingIncrement();
// check for different values
if ((r1 != null) && (r2 != null))
{
if (r1.compareTo(r2) == 0)
{
errln("ERROR: Rounding increment did not change");
}
}
}
@Test
public void testJB6648()
{
DecimalFormat df = new DecimalFormat();
df.setParseStrict(true);
String numstr = new String();
String[] patterns = {
"0",
"00",
"000",
"0,000",
"0.0",
"#000.0"
};
for(int i=0; i < patterns.length; i++) {
df.applyPattern(patterns[i]);
numstr = df.format(5);
try {
Number n = df.parse(numstr);
logln("INFO: Parsed " + numstr + " -> " + n);
} catch (ParseException pe) {
errln("ERROR: Failed round trip with strict parsing.");
}
}
df.applyPattern(patterns[1]);
numstr = "005";
try {
Number n = df.parse(numstr);
logln("INFO: Successful parse for " + numstr + " with strict parse enabled. Number is " + n);
} catch (ParseException pe) {
errln("ERROR: Parse Exception encountered in strict mode: numstr -> " + numstr);
}
}
}
|
9245c87ba4fc8500e6429084ec32d625c384836c | 765 | java | Java | java_backup/my java/bhasa/lucky_number.java | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 16 | 2018-11-26T08:39:42.000Z | 2019-05-08T10:09:52.000Z | java_backup/my java/bhasa/lucky_number.java | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 8 | 2020-05-04T06:29:26.000Z | 2022-02-12T05:33:16.000Z | java_backup/my java/bhasa/lucky_number.java | SayanGhoshBDA/code-backup | 8b6135facc0e598e9686b2e8eb2d69dd68198b80 | [
"MIT"
] | 5 | 2020-02-11T16:02:21.000Z | 2021-02-05T07:48:30.000Z | 17.790698 | 72 | 0.601307 | 1,003,527 | import java.io.*;
class lucky_number
{
public static void main(String args[])throws IOException
{
int n,i,t,d,t1,limit;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER LIMIT");
n=Integer.parseInt(br.readLine());
t=0;d=2;t1=n;limit=n;
int a[]=new int[n];
int b[]=new int[n];
for(i=0;i<n;i++)
{
System.out.println("enter element for element no."+(i+1));
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("ORIGINAL SERIES :-");
for(i=0;i<n;i++)
{
System.out.print(a[i]+",");
}
while(d<t1)
{
for(i=0;i<limit;i=i+d)
{
b[t]=a[i];
t++;
}
for(i=0;i<t;i++)
{
a[i]=b[i];
}
System.out.println("");
for(i=0;i<t;i++)
{
System.out.print(a[i]+",");
}
limit=t;t1=t;t=0;d++;
}
}
}
|
9245c9307fe9a4fccbfaa46e698db3e5f5c91afa | 188 | java | Java | card-game/src/main/java/com/s4game/server/bus/init/command/InitCommands.java | zuesgooogle/HappyCard | 20356b4f1f3dcf8fe26a7cf53be3b14e87b7c95d | [
"Apache-2.0"
] | null | null | null | card-game/src/main/java/com/s4game/server/bus/init/command/InitCommands.java | zuesgooogle/HappyCard | 20356b4f1f3dcf8fe26a7cf53be3b14e87b7c95d | [
"Apache-2.0"
] | null | null | null | card-game/src/main/java/com/s4game/server/bus/init/command/InitCommands.java | zuesgooogle/HappyCard | 20356b4f1f3dcf8fe26a7cf53be3b14e87b7c95d | [
"Apache-2.0"
] | null | null | null | 18.8 | 49 | 0.670213 | 1,003,528 | package com.s4game.server.bus.init.command;
public class InitCommands {
public static final String ROLE_IN = "000";
public static final String ROLE_OUT = "-001";
}
|
9245cd631b8337822e1422aeeb7f1b8c38eb33a5 | 974 | java | Java | x-netdisk-web/src/main/java/group/xuxiake/web/util/PasswordEncoder.java | xuxiake2017/x-netdisk | 3b1f5b22737e4b8dd3d7a3107b84fdf6c2ed2b22 | [
"MIT"
] | 6 | 2020-03-27T09:25:24.000Z | 2021-11-25T04:47:30.000Z | x-netdisk-web/src/main/java/group/xuxiake/web/util/PasswordEncoder.java | xuxiake2017/x-netdisk | 3b1f5b22737e4b8dd3d7a3107b84fdf6c2ed2b22 | [
"MIT"
] | 1 | 2022-03-11T05:55:26.000Z | 2022-03-14T01:27:28.000Z | x-netdisk-web/src/main/java/group/xuxiake/web/util/PasswordEncoder.java | xuxiake2017/x-netdisk | 3b1f5b22737e4b8dd3d7a3107b84fdf6c2ed2b22 | [
"MIT"
] | 3 | 2021-02-24T07:17:04.000Z | 2022-03-11T05:55:22.000Z | 20.723404 | 90 | 0.694045 | 1,003,529 | package group.xuxiake.web.util;
import org.apache.shiro.crypto.hash.SimpleHash;
/**
* 密码加密及验证密码
*/
public class PasswordEncoder {
/**
* 密码加密
* @param password 原始密码
* @param username 用户名
* @return 加密后的密码
*/
public static String encode(String password, String username) {
//加密方式
String algorithmName = "MD5";
//加密次数
int hashIterations = 1024;
//盐值
String salt = username;
//加密后的密码
SimpleHash simpleHash = new SimpleHash(algorithmName, password, salt, hashIterations );
return simpleHash.toString();
}
/**
* 验证用户输入密码是否正确
* @param pwdInput 输入的原始密码
* @param pwdTrue 加密后的正确密码
* @param username 用户名
* @return 用户输入密码是否正确
*/
public static boolean isPasswordValid(String pwdInput, String pwdTrue, String username) {
if (pwdTrue.equals(encode(pwdInput, username))) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
System.out.println(PasswordEncoder.encode("123456", "xuxiake"));
}
}
|
9245d02b42ec701f7abf6210d874946ca644d76e | 1,054 | java | Java | examples/full-api-edge-cases/src/main/java/com/webcohesion/enunciate/examples/jaxwsrijersey/genealogy/data/EventDescriptionContainer.java | octetnest/enunciate | e571c6a7aa50a18c60a529be28d14619342940eb | [
"Apache-2.0"
] | 431 | 2015-01-05T06:27:54.000Z | 2022-03-29T22:01:03.000Z | examples/full-api-edge-cases/src/main/java/com/webcohesion/enunciate/examples/jaxwsrijersey/genealogy/data/EventDescriptionContainer.java | octetnest/enunciate | e571c6a7aa50a18c60a529be28d14619342940eb | [
"Apache-2.0"
] | 1,020 | 2015-01-17T17:44:54.000Z | 2022-03-30T14:11:06.000Z | examples/full-api-edge-cases/src/main/java/com/webcohesion/enunciate/examples/jaxwsrijersey/genealogy/data/EventDescriptionContainer.java | octetnest/enunciate | e571c6a7aa50a18c60a529be28d14619342940eb | [
"Apache-2.0"
] | 180 | 2015-02-02T17:12:44.000Z | 2022-03-05T10:51:47.000Z | 30.2 | 75 | 0.752129 | 1,003,530 | /**
* Copyright © 2006-2016 Web Cohesion ([email protected])
*
* 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.webcohesion.enunciate.examples.jaxwsrijersey.genealogy.data;
import java.util.List;
/**
* @author Ryan Heaton
*/
public class EventDescriptionContainer {
private List<Event> typesToDescriptions;
public List<Event> getTypesToDescriptions() {
return typesToDescriptions;
}
public void setTypesToDescriptions(List<Event> typesToDescriptions) {
this.typesToDescriptions = typesToDescriptions;
}
}
|
9245d03d26a9cf182d4a3f02f4c476b7912de7cf | 658 | java | Java | customcamera/src/main/java/com/birfincankafein/customcamera/FlashState.java | birfincankafein/customcamera | ec59943b7282354e32e31d64d760f2f057d26423 | [
"Apache-2.0"
] | 2 | 2018-04-19T07:07:26.000Z | 2020-05-09T08:38:27.000Z | customcamera/src/main/java/com/birfincankafein/customcamera/FlashState.java | birfincankafein/customcamera | ec59943b7282354e32e31d64d760f2f057d26423 | [
"Apache-2.0"
] | null | null | null | customcamera/src/main/java/com/birfincankafein/customcamera/FlashState.java | birfincankafein/customcamera | ec59943b7282354e32e31d64d760f2f057d26423 | [
"Apache-2.0"
] | null | null | null | 21.225806 | 93 | 0.572948 | 1,003,531 | package com.birfincankafein.customcamera;
/**
* Created by metehantoksoy on 9.04.2018.
*/
public enum FlashState {
ON(R.drawable.ic_flash_on), AUTO(R.drawable.ic_flash_auto), OFF(R.drawable.ic_flash_off);
private final int resourceId;
FlashState(int resourceId) {
this.resourceId = resourceId;
}
public int getResourceId(){
return resourceId;
}
public static FlashState next(FlashState state){
switch (state){
case AUTO:
return ON;
case OFF:
return AUTO;
case ON:
default:
return OFF;
}
}
}
|
9245d0c68efc5d34cf60a0b64a246d62812d7b9c | 468 | java | Java | vertx-client/src/main/java/com/github/viniciusfcf/vertxclient/OlaHandler2.java | viniciusferraz/quarkus | d4fff47744f3dca3c41f977d4a86f883798556f7 | [
"Apache-2.0"
] | 30 | 2020-04-30T18:08:12.000Z | 2022-03-05T20:53:58.000Z | vertx-client/src/main/java/com/github/viniciusfcf/vertxclient/OlaHandler2.java | viniciusferraz/quarkus | d4fff47744f3dca3c41f977d4a86f883798556f7 | [
"Apache-2.0"
] | null | null | null | vertx-client/src/main/java/com/github/viniciusfcf/vertxclient/OlaHandler2.java | viniciusferraz/quarkus | d4fff47744f3dca3c41f977d4a86f883798556f7 | [
"Apache-2.0"
] | 17 | 2020-06-16T13:48:34.000Z | 2022-03-10T20:31:24.000Z | 23.4 | 50 | 0.784188 | 1,003,532 | package com.github.viniciusfcf.vertxclient;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import io.quarkus.vertx.ConsumeEvent;
@ApplicationScoped
public class OlaHandler2 {
@ConsumeEvent(value="olaRequest", local=false)
public String consume(String name) {
return name.toUpperCase()+" Quarkus 2!!";
}
} |
9245d13806142dd1eccb3c2c8ceae178e20ba4ad | 950 | java | Java | build/tmp/expandedArchives/forge-1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1-sources.jar_c582e790131b6dd3325b282fce9d2d3d/net/minecraft/util/datafix/versions/V1801.java | TheDarkRob/Sgeorsge | 307a675cd3af5905504e34717e4f853b2943ba7b | [
"Apache-2.0"
] | 2 | 2020-07-09T09:56:49.000Z | 2020-07-21T00:08:17.000Z | build/tmp/expandedArchives/forge-1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1-sources.jar_c582e790131b6dd3325b282fce9d2d3d/net/minecraft/util/datafix/versions/V1801.java | TheDarkRob/Sgeorsge | 307a675cd3af5905504e34717e4f853b2943ba7b | [
"Apache-2.0"
] | null | null | null | build/tmp/expandedArchives/forge-1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1-sources.jar_c582e790131b6dd3325b282fce9d2d3d/net/minecraft/util/datafix/versions/V1801.java | TheDarkRob/Sgeorsge | 307a675cd3af5905504e34717e4f853b2943ba7b | [
"Apache-2.0"
] | null | null | null | 38 | 129 | 0.763158 | 1,003,533 | package net.minecraft.util.datafix.versions;
import com.mojang.datafixers.schemas.Schema;
import com.mojang.datafixers.types.templates.TypeTemplate;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.util.datafix.NamespacedSchema;
public class V1801 extends NamespacedSchema {
public V1801(int p_i50418_1_, Schema p_i50418_2_) {
super(p_i50418_1_, p_i50418_2_);
}
protected static void func_219878_a(Schema p_219878_0_, Map<String, Supplier<TypeTemplate>> p_219878_1_, String p_219878_2_) {
p_219878_0_.register(p_219878_1_, p_219878_2_, () -> {
return V0100.equipment(p_219878_0_);
});
}
public Map<String, Supplier<TypeTemplate>> registerEntities(Schema p_registerEntities_1_) {
Map<String, Supplier<TypeTemplate>> map = super.registerEntities(p_registerEntities_1_);
func_219878_a(p_registerEntities_1_, map, "minecraft:illager_beast");
return map;
}
} |
9245d2d82d710265622f451de62a143e42e0def4 | 33,583 | java | Java | byte-buddy-dep/src/test/java/net/bytebuddy/description/annotation/AbstractAnnotationDescriptionTest.java | mar-kolya/byte-buddy | 8e2045e91856dbe004219f2a3b29e792cc7ce799 | [
"Apache-2.0"
] | 1 | 2018-12-03T06:19:15.000Z | 2018-12-03T06:19:15.000Z | byte-buddy-dep/src/test/java/net/bytebuddy/description/annotation/AbstractAnnotationDescriptionTest.java | mar-kolya/byte-buddy | 8e2045e91856dbe004219f2a3b29e792cc7ce799 | [
"Apache-2.0"
] | null | null | null | byte-buddy-dep/src/test/java/net/bytebuddy/description/annotation/AbstractAnnotationDescriptionTest.java | mar-kolya/byte-buddy | 8e2045e91856dbe004219f2a3b29e792cc7ce799 | [
"Apache-2.0"
] | null | null | null | 45.138441 | 176 | 0.693148 | 1,003,534 | package net.bytebuddy.description.annotation;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.enumeration.EnumerationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeVariableToken;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.OpenedClassReader;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractAnnotationDescriptionTest {
private static final boolean BOOLEAN = true;
private static final boolean[] BOOLEAN_ARRAY = new boolean[]{BOOLEAN};
private static final byte BYTE = 42;
private static final byte[] BYTE_ARRAY = new byte[]{BYTE};
private static final short SHORT = 42;
private static final short[] SHORT_ARRAY = new short[]{SHORT};
private static final char CHARACTER = 42;
private static final char[] CHARACTER_ARRAY = new char[]{CHARACTER};
private static final int INTEGER = 42;
private static final int[] INTEGER_ARRAY = new int[]{INTEGER};
private static final long LONG = 42L;
private static final long[] LONG_ARRAY = new long[]{LONG};
private static final float FLOAT = 42f;
private static final float[] FLOAT_ARRAY = new float[]{FLOAT};
private static final double DOUBLE = 42d;
private static final double[] DOUBLE_ARRAY = new double[]{DOUBLE};
private static final String FOO = "foo", BAR = "bar";
private static final String[] STRING_ARRAY = new String[]{FOO};
private static final SampleEnumeration ENUMERATION = SampleEnumeration.VALUE;
private static final SampleEnumeration[] ENUMERATION_ARRAY = new SampleEnumeration[]{ENUMERATION};
private static final Class<?> CLASS = Void.class;
private static final Class<?>[] CLASS_ARRAY = new Class<?>[]{CLASS};
private static final Class<?> ARRAY_CLASS = Void[].class;
private static final Other ANNOTATION = EnumerationCarrier.class.getAnnotation(Other.class);
private static final Other[] ANNOTATION_ARRAY = new Other[]{ANNOTATION};
private static final boolean OTHER_BOOLEAN = false;
private static final boolean[] OTHER_BOOLEAN_ARRAY = new boolean[]{OTHER_BOOLEAN};
private static final byte OTHER_BYTE = 42 * 2;
private static final byte[] OTHER_BYTE_ARRAY = new byte[]{OTHER_BYTE};
private static final short OTHER_SHORT = 42 * 2;
private static final short[] OTHER_SHORT_ARRAY = new short[]{OTHER_SHORT};
private static final char OTHER_CHARACTER = 42 * 2;
private static final char[] OTHER_CHARACTER_ARRAY = new char[]{OTHER_CHARACTER};
private static final int OTHER_INTEGER = 42 * 2;
private static final int[] OTHER_INTEGER_ARRAY = new int[]{OTHER_INTEGER};
private static final long OTHER_LONG = 42L * 2;
private static final long[] OTHER_LONG_ARRAY = new long[]{OTHER_LONG};
private static final float OTHER_FLOAT = 42f * 2;
private static final float[] OTHER_FLOAT_ARRAY = new float[]{OTHER_FLOAT};
private static final double OTHER_DOUBLE = 42d * 2;
private static final double[] OTHER_DOUBLE_ARRAY = new double[]{OTHER_DOUBLE};
private static final SampleEnumeration OTHER_ENUMERATION = SampleEnumeration.OTHER;
private static final SampleEnumeration[] OTHER_ENUMERATION_ARRAY = new SampleEnumeration[]{OTHER_ENUMERATION};
private static final Class<?> OTHER_CLASS = Object.class;
private static final Class<?>[] OTHER_CLASS_ARRAY = new Class<?>[]{OTHER_CLASS};
private static final Class<?> OTHER_ARRAY_CLASS = Object[].class;
private static final Other OTHER_ANNOTATION = OtherEnumerationCarrier.class.getAnnotation(Other.class);
private static final Other[] OTHER_ANNOTATION_ARRAY = new Other[]{OTHER_ANNOTATION};
private static final String[] OTHER_STRING_ARRAY = new String[]{BAR};
private Annotation first, second, defaultFirst, defaultSecond, explicitTarget, broken;
private Class<?> brokenCarrier;
protected abstract AnnotationDescription describe(Annotation annotation, Class<?> declaringType);
private AnnotationDescription describe(Annotation annotation) {
Class<?> carrier;
if (annotation == first) {
carrier = FooSample.class;
} else if (annotation == second) {
carrier = BarSample.class;
} else if (annotation == defaultFirst) {
carrier = DefaultSample.class;
} else if (annotation == defaultSecond) {
carrier = NonDefaultSample.class;
} else if (annotation == explicitTarget) {
carrier = ExplicitTarget.Carrier.class;
} else if (annotation == broken) {
carrier = brokenCarrier;
} else {
throw new AssertionError();
}
return describe(annotation, carrier);
}
@Before
public void setUp() throws Exception {
first = FooSample.class.getAnnotation(Sample.class);
second = BarSample.class.getAnnotation(Sample.class);
defaultFirst = DefaultSample.class.getAnnotation(SampleDefault.class);
defaultSecond = NonDefaultSample.class.getAnnotation(SampleDefault.class);
explicitTarget = ExplicitTarget.Carrier.class.getAnnotation(ExplicitTarget.class);
brokenCarrier = new ByteBuddy()
.subclass(Object.class)
.visit(new AnnotationValueBreaker())
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT)
.getLoaded();
broken = brokenCarrier.getAnnotations()[0];
}
@Test
public void testPrecondition() throws Exception {
assertThat(describe(first), is(describe(first)));
assertThat(describe(second), is(describe(second)));
assertThat(describe(first), not(describe(second)));
assertThat(describe(first).getAnnotationType(), is(describe(second).getAnnotationType()));
assertThat(describe(first).getAnnotationType(), not((TypeDescription) TypeDescription.ForLoadedType.of(Other.class)));
assertThat(describe(second).getAnnotationType(), not((TypeDescription) TypeDescription.ForLoadedType.of(Other.class)));
assertThat(describe(first).getAnnotationType().represents(first.annotationType()), is(true));
assertThat(describe(second).getAnnotationType().represents(second.annotationType()), is(true));
}
@Test
public void assertToString() throws Exception {
assertToString(describe(first).toString(), first);
assertToString(describe(second).toString(), second);
}
private void assertToString(String actual, Annotation loaded) throws Exception {
assertThat(actual, startsWith("@" + loaded.annotationType().getName()));
String loadedString = loaded.toString();
if (loadedString.length() - loadedString.replace(",", "").length() != loaded.annotationType().getDeclaredMethods().length - 1) {
throw new AssertionError("Unexpected amount of commas for " + loaded); // Expect tested annotations not to contain commas in values.
}
for (Method method : loaded.annotationType().getDeclaredMethods()) {
assertThat(loadedString.split(method.getName() + "=", -1).length - 1, is(1)); // Expect property delimiter not to exist as value.
int start = loadedString.indexOf(method.getName() + "="), end = loadedString.indexOf(',', start);
assertThat(actual, containsString(loadedString.substring(start, end == -1 ? loadedString.length() - 1 : end)));
}
}
@Test
public void testHashCode() throws Exception {
assertThat(describe(first).hashCode(), is(describe(first).hashCode()));
assertThat(describe(second).hashCode(), is(describe(second).hashCode()));
assertThat(describe(first).hashCode(), not(describe(second).hashCode()));
}
@Test
@SuppressWarnings("unchecked")
public void testEquals() throws Exception {
AnnotationDescription identical = describe(first);
assertThat(identical, is(identical));
AnnotationDescription equalFirst = mock(AnnotationDescription.class);
when(equalFirst.getAnnotationType()).thenReturn(TypeDescription.ForLoadedType.of(first.annotationType()));
when(equalFirst.getValue(Mockito.any(MethodDescription.InDefinedShape.class))).then(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MethodDescription.InDefinedShape method = (MethodDescription.InDefinedShape) invocation.getArguments()[0];
return AnnotationDescription.ForLoadedAnnotation.of(first).getValue(method);
}
});
assertThat(describe(first), is(equalFirst));
AnnotationDescription equalSecond = mock(AnnotationDescription.class);
when(equalSecond.getAnnotationType()).thenReturn(TypeDescription.ForLoadedType.of(first.annotationType()));
when(equalSecond.getValue(Mockito.any(MethodDescription.InDefinedShape.class))).then(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MethodDescription.InDefinedShape method = (MethodDescription.InDefinedShape) invocation.getArguments()[0];
return AnnotationDescription.ForLoadedAnnotation.of(second).getValue(method);
}
});
assertThat(describe(second), is(equalSecond));
AnnotationDescription equalFirstTypeOnly = mock(AnnotationDescription.class);
when(equalFirstTypeOnly.getAnnotationType()).thenReturn(TypeDescription.ForLoadedType.of(Other.class));
when(equalFirstTypeOnly.getValue(Mockito.any(MethodDescription.InDefinedShape.class))).then(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
MethodDescription.InDefinedShape method = (MethodDescription.InDefinedShape) invocation.getArguments()[0];
return AnnotationDescription.ForLoadedAnnotation.of(first).getValue(method);
}
});
assertThat(describe(first), not(equalFirstTypeOnly));
AnnotationDescription equalFirstNameOnly = mock(AnnotationDescription.class);
when(equalFirstNameOnly.getAnnotationType()).thenReturn(TypeDescription.ForLoadedType.of(first.annotationType()));
AnnotationValue<?, ?> annotationValue = mock(AnnotationValue.class);
when(annotationValue.resolve()).thenReturn(null);
when(equalFirstNameOnly.getValue(Mockito.any(MethodDescription.InDefinedShape.class))).thenReturn((AnnotationValue) annotationValue);
assertThat(describe(first), not(equalFirstNameOnly));
assertThat(describe(first), not(equalSecond));
assertThat(describe(first), not(new Object()));
assertThat(describe(first), not(equalTo(null)));
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalMethod() throws Exception {
describe(first).getValue(new MethodDescription.ForLoadedMethod(Object.class.getMethod("toString")));
}
@Test
public void testLoadedEquals() throws Exception {
assertThat(describe(first).prepare(Sample.class).load(), is(first));
assertThat(describe(first).prepare(Sample.class).load(), is(describe(first).prepare(Sample.class).load()));
assertThat(describe(first).prepare(Sample.class).load(), not(describe(second).prepare(Sample.class).load()));
assertThat(describe(second).prepare(Sample.class).load(), is(second));
assertThat(describe(first).prepare(Sample.class).load(), not(second));
}
@Test
public void testLoadedHashCode() throws Exception {
assertThat(describe(first).prepare(Sample.class).load().hashCode(), is(first.hashCode()));
assertThat(describe(second).prepare(Sample.class).load().hashCode(), is(second.hashCode()));
assertThat(describe(first).prepare(Sample.class).load().hashCode(), not(second.hashCode()));
}
@Test
public void testLoadedToString() throws Exception {
assertToString(describe(first).prepare(Sample.class).load().toString(), first);
assertToString(describe(second).prepare(Sample.class).load().toString(), second);
}
@Test
public void testToString() throws Exception {
assertToString(describe(first).prepare(Sample.class).toString(), first);
assertToString(describe(second).prepare(Sample.class).toString(), second);
}
@Test
@Ignore("Add better handling for annotations with inconsistent values")
public void testBrokenAnnotation() throws Exception {
describe(broken);
}
@Test
public void testLoadedAnnotationType() throws Exception {
assertThat(describe(first).prepare(Sample.class).load().annotationType(), CoreMatchers.<Class<?>>is(Sample.class));
assertThat(describe(second).prepare(Sample.class).load().annotationType(), CoreMatchers.<Class<?>>is(Sample.class));
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalPreparation() throws Exception {
describe(first).prepare(Other.class);
}
@Test
public void testValues() throws Exception {
assertValue(first, "booleanValue", BOOLEAN, BOOLEAN);
assertValue(second, "booleanValue", BOOLEAN, BOOLEAN);
assertValue(first, "byteValue", BYTE, BYTE);
assertValue(second, "byteValue", BYTE, BYTE);
assertValue(first, "shortValue", SHORT, SHORT);
assertValue(second, "shortValue", SHORT, SHORT);
assertValue(first, "charValue", CHARACTER, CHARACTER);
assertValue(second, "charValue", CHARACTER, CHARACTER);
assertValue(first, "intValue", INTEGER, INTEGER);
assertValue(second, "intValue", INTEGER, INTEGER);
assertValue(first, "longValue", LONG, LONG);
assertValue(second, "longValue", LONG, LONG);
assertValue(first, "floatValue", FLOAT, FLOAT);
assertValue(second, "floatValue", FLOAT, FLOAT);
assertValue(first, "doubleValue", DOUBLE, DOUBLE);
assertValue(second, "doubleValue", DOUBLE, DOUBLE);
assertValue(first, "stringValue", FOO, FOO);
assertValue(second, "stringValue", BAR, BAR);
assertValue(first, "classValue", TypeDescription.ForLoadedType.of(CLASS), CLASS);
assertValue(second, "classValue", TypeDescription.ForLoadedType.of(CLASS), CLASS);
assertValue(first, "arrayClassValue", TypeDescription.ForLoadedType.of(ARRAY_CLASS), ARRAY_CLASS);
assertValue(second, "arrayClassValue", TypeDescription.ForLoadedType.of(ARRAY_CLASS), ARRAY_CLASS);
assertValue(first, "enumValue", new EnumerationDescription.ForLoadedEnumeration(ENUMERATION), ENUMERATION);
assertValue(second, "enumValue", new EnumerationDescription.ForLoadedEnumeration(ENUMERATION), ENUMERATION);
assertValue(first, "annotationValue", AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION), ANNOTATION);
assertValue(second, "annotationValue", AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION), ANNOTATION);
assertValue(first, "booleanArrayValue", BOOLEAN_ARRAY, BOOLEAN_ARRAY);
assertValue(second, "booleanArrayValue", BOOLEAN_ARRAY, BOOLEAN_ARRAY);
assertValue(first, "byteArrayValue", BYTE_ARRAY, BYTE_ARRAY);
assertValue(second, "byteArrayValue", BYTE_ARRAY, BYTE_ARRAY);
assertValue(first, "shortArrayValue", SHORT_ARRAY, SHORT_ARRAY);
assertValue(second, "shortArrayValue", SHORT_ARRAY, SHORT_ARRAY);
assertValue(first, "charArrayValue", CHARACTER_ARRAY, CHARACTER_ARRAY);
assertValue(second, "charArrayValue", CHARACTER_ARRAY, CHARACTER_ARRAY);
assertValue(first, "intArrayValue", INTEGER_ARRAY, INTEGER_ARRAY);
assertValue(second, "intArrayValue", INTEGER_ARRAY, INTEGER_ARRAY);
assertValue(first, "longArrayValue", LONG_ARRAY, LONG_ARRAY);
assertValue(second, "longArrayValue", LONG_ARRAY, LONG_ARRAY);
assertValue(first, "floatArrayValue", FLOAT_ARRAY, FLOAT_ARRAY);
assertValue(second, "floatArrayValue", FLOAT_ARRAY, FLOAT_ARRAY);
assertValue(first, "doubleArrayValue", DOUBLE_ARRAY, DOUBLE_ARRAY);
assertValue(second, "doubleArrayValue", DOUBLE_ARRAY, DOUBLE_ARRAY);
assertValue(first, "stringArrayValue", STRING_ARRAY, STRING_ARRAY);
assertValue(second, "stringArrayValue", STRING_ARRAY, STRING_ARRAY);
assertValue(first, "classArrayValue", new TypeDescription[]{TypeDescription.ForLoadedType.of(CLASS)}, CLASS_ARRAY);
assertValue(second, "classArrayValue", new TypeDescription[]{TypeDescription.ForLoadedType.of(CLASS)}, CLASS_ARRAY);
assertValue(first, "enumArrayValue", new EnumerationDescription[]{new EnumerationDescription.ForLoadedEnumeration(ENUMERATION)}, ENUMERATION_ARRAY);
assertValue(second, "enumArrayValue", new EnumerationDescription[]{new EnumerationDescription.ForLoadedEnumeration(ENUMERATION)}, ENUMERATION_ARRAY);
assertValue(first, "annotationArrayValue", new AnnotationDescription[]{AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION)}, ANNOTATION_ARRAY);
assertValue(second, "annotationArrayValue", new AnnotationDescription[]{AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION)}, ANNOTATION_ARRAY);
}
@Test
public void testValuesDefaults() throws Exception {
assertValue(defaultFirst, "booleanValue", BOOLEAN, BOOLEAN);
assertValue(defaultSecond, "booleanValue", OTHER_BOOLEAN, OTHER_BOOLEAN);
assertValue(defaultFirst, "byteValue", BYTE, BYTE);
assertValue(defaultSecond, "byteValue", OTHER_BYTE, OTHER_BYTE);
assertValue(defaultFirst, "shortValue", SHORT, SHORT);
assertValue(defaultSecond, "shortValue", OTHER_SHORT, OTHER_SHORT);
assertValue(defaultFirst, "charValue", CHARACTER, CHARACTER);
assertValue(defaultSecond, "charValue", OTHER_CHARACTER, OTHER_CHARACTER);
assertValue(defaultFirst, "intValue", INTEGER, INTEGER);
assertValue(defaultSecond, "intValue", OTHER_INTEGER, OTHER_INTEGER);
assertValue(defaultFirst, "longValue", LONG, LONG);
assertValue(defaultSecond, "longValue", OTHER_LONG, OTHER_LONG);
assertValue(defaultFirst, "floatValue", FLOAT, FLOAT);
assertValue(defaultSecond, "floatValue", OTHER_FLOAT, OTHER_FLOAT);
assertValue(defaultFirst, "doubleValue", DOUBLE, DOUBLE);
assertValue(defaultSecond, "doubleValue", OTHER_DOUBLE, OTHER_DOUBLE);
assertValue(defaultFirst, "stringValue", FOO, FOO);
assertValue(defaultSecond, "stringValue", BAR, BAR);
assertValue(defaultFirst, "classValue", TypeDescription.ForLoadedType.of(CLASS), CLASS);
assertValue(defaultSecond, "classValue", TypeDescription.ForLoadedType.of(OTHER_CLASS), OTHER_CLASS);
assertValue(defaultFirst, "arrayClassValue", TypeDescription.ForLoadedType.of(ARRAY_CLASS), ARRAY_CLASS);
assertValue(defaultSecond, "arrayClassValue", TypeDescription.ForLoadedType.of(OTHER_ARRAY_CLASS), OTHER_ARRAY_CLASS);
assertValue(defaultFirst, "enumValue", new EnumerationDescription.ForLoadedEnumeration(ENUMERATION), ENUMERATION);
assertValue(defaultSecond, "enumValue", new EnumerationDescription.ForLoadedEnumeration(OTHER_ENUMERATION), OTHER_ENUMERATION);
assertValue(defaultFirst, "annotationValue", AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION), ANNOTATION);
assertValue(defaultSecond, "annotationValue", AnnotationDescription.ForLoadedAnnotation.of(OTHER_ANNOTATION), OTHER_ANNOTATION);
assertValue(defaultFirst, "booleanArrayValue", BOOLEAN_ARRAY, BOOLEAN_ARRAY);
assertValue(defaultSecond, "booleanArrayValue", OTHER_BOOLEAN_ARRAY, OTHER_BOOLEAN_ARRAY);
assertValue(defaultFirst, "byteArrayValue", BYTE_ARRAY, BYTE_ARRAY);
assertValue(defaultSecond, "byteArrayValue", OTHER_BYTE_ARRAY, OTHER_BYTE_ARRAY);
assertValue(defaultFirst, "shortArrayValue", SHORT_ARRAY, SHORT_ARRAY);
assertValue(defaultSecond, "shortArrayValue", OTHER_SHORT_ARRAY, OTHER_SHORT_ARRAY);
assertValue(defaultFirst, "charArrayValue", CHARACTER_ARRAY, CHARACTER_ARRAY);
assertValue(defaultSecond, "charArrayValue", OTHER_CHARACTER_ARRAY, OTHER_CHARACTER_ARRAY);
assertValue(defaultFirst, "intArrayValue", INTEGER_ARRAY, INTEGER_ARRAY);
assertValue(defaultSecond, "intArrayValue", OTHER_INTEGER_ARRAY, OTHER_INTEGER_ARRAY);
assertValue(defaultFirst, "longArrayValue", LONG_ARRAY, LONG_ARRAY);
assertValue(defaultSecond, "longArrayValue", OTHER_LONG_ARRAY, OTHER_LONG_ARRAY);
assertValue(defaultFirst, "floatArrayValue", FLOAT_ARRAY, FLOAT_ARRAY);
assertValue(defaultSecond, "floatArrayValue", OTHER_FLOAT_ARRAY, OTHER_FLOAT_ARRAY);
assertValue(defaultFirst, "doubleArrayValue", DOUBLE_ARRAY, DOUBLE_ARRAY);
assertValue(defaultSecond, "doubleArrayValue", OTHER_DOUBLE_ARRAY, OTHER_DOUBLE_ARRAY);
assertValue(defaultFirst, "stringArrayValue", STRING_ARRAY, STRING_ARRAY);
assertValue(defaultSecond, "stringArrayValue", OTHER_STRING_ARRAY, OTHER_STRING_ARRAY);
assertValue(defaultFirst, "classArrayValue", new TypeDescription[]{TypeDescription.ForLoadedType.of(CLASS)}, CLASS_ARRAY);
assertValue(defaultSecond, "classArrayValue", new TypeDescription[]{TypeDescription.ForLoadedType.of(OTHER_CLASS)}, OTHER_CLASS_ARRAY);
assertValue(defaultFirst, "enumArrayValue", new EnumerationDescription[]{new EnumerationDescription.ForLoadedEnumeration(ENUMERATION)}, ENUMERATION_ARRAY);
assertValue(defaultSecond, "enumArrayValue", new EnumerationDescription[]{new EnumerationDescription.ForLoadedEnumeration(OTHER_ENUMERATION)}, OTHER_ENUMERATION_ARRAY);
assertValue(defaultFirst, "annotationArrayValue", new AnnotationDescription[]{AnnotationDescription.ForLoadedAnnotation.of(ANNOTATION)}, ANNOTATION_ARRAY);
assertValue(defaultSecond, "annotationArrayValue", new AnnotationDescription[]{AnnotationDescription.ForLoadedAnnotation.of(OTHER_ANNOTATION)}, OTHER_ANNOTATION_ARRAY);
}
@Test
public void testRetention() throws Exception {
assertThat(describe(first).getRetention(), is(RetentionPolicy.RUNTIME));
}
@Test
public void testAnnotationTarget() throws Exception {
assertThat(describe(first).getElementTypes(), is((Set<ElementType>) new HashSet<ElementType>(Arrays.asList(ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD,
ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE))));
assertThat(describe(explicitTarget).getElementTypes(), is(Collections.singleton(ElementType.TYPE)));
}
@Test
public void testInheritance() throws Exception {
assertThat(describe(first).isInherited(), is(false));
assertThat(describe(defaultFirst).isInherited(), is(true));
}
@Test
public void testDocumented() throws Exception {
assertThat(describe(first).isDocumented(), is(false));
assertThat(describe(defaultFirst).isDocumented(), is(true));
}
private void assertValue(Annotation annotation, String methodName, Object unloadedValue, Object loadedValue) throws Exception {
assertThat(describe(annotation).getValue(new MethodDescription.ForLoadedMethod(annotation.annotationType().getDeclaredMethod(methodName))).resolve(),
is(unloadedValue));
assertThat(describe(annotation).getValue(new MethodDescription.Latent(TypeDescription.ForLoadedType.of(annotation.annotationType()),
methodName,
Opcodes.ACC_PUBLIC,
Collections.<TypeVariableToken>emptyList(),
TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(annotation.annotationType().getDeclaredMethod(methodName).getReturnType()),
Collections.<ParameterDescription.Token>emptyList(),
Collections.<TypeDescription.Generic>emptyList(),
Collections.<AnnotationDescription>emptyList(),
AnnotationValue.UNDEFINED,
TypeDescription.Generic.UNDEFINED)).resolve(), is(unloadedValue));
assertThat(annotation.annotationType().getDeclaredMethod(methodName).invoke(describe(annotation).prepare(annotation.annotationType()).load()),
is(loadedValue));
}
public enum SampleEnumeration {
VALUE,
OTHER
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Sample2 {
Class<?> foo();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Sample {
boolean booleanValue();
byte byteValue();
short shortValue();
char charValue();
int intValue();
long longValue();
float floatValue();
double doubleValue();
String stringValue();
Class<?> classValue();
Class<?> arrayClassValue();
SampleEnumeration enumValue();
Other annotationValue();
boolean[] booleanArrayValue();
byte[] byteArrayValue();
short[] shortArrayValue();
char[] charArrayValue();
int[] intArrayValue();
long[] longArrayValue();
float[] floatArrayValue();
double[] doubleArrayValue();
String[] stringArrayValue();
Class<?>[] classArrayValue();
SampleEnumeration[] enumArrayValue();
Other[] annotationArrayValue();
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface SampleDefault {
boolean booleanValue() default BOOLEAN;
byte byteValue() default BYTE;
short shortValue() default SHORT;
char charValue() default CHARACTER;
int intValue() default INTEGER;
long longValue() default LONG;
float floatValue() default FLOAT;
double doubleValue() default DOUBLE;
String stringValue() default FOO;
Class<?> classValue() default Void.class;
Class<?> arrayClassValue() default Void[].class;
SampleEnumeration enumValue() default SampleEnumeration.VALUE;
Other annotationValue() default @Other;
boolean[] booleanArrayValue() default BOOLEAN;
byte[] byteArrayValue() default BYTE;
short[] shortArrayValue() default SHORT;
char[] charArrayValue() default CHARACTER;
int[] intArrayValue() default INTEGER;
long[] longArrayValue() default LONG;
float[] floatArrayValue() default FLOAT;
double[] doubleArrayValue() default DOUBLE;
String[] stringArrayValue() default FOO;
Class<?>[] classArrayValue() default Void.class;
SampleEnumeration[] enumArrayValue() default SampleEnumeration.VALUE;
Other[] annotationArrayValue() default @Other;
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Other {
String value() default FOO;
}
@Sample(booleanValue = BOOLEAN,
byteValue = BYTE,
charValue = CHARACTER,
shortValue = SHORT,
intValue = INTEGER,
longValue = LONG,
floatValue = FLOAT,
doubleValue = DOUBLE,
stringValue = FOO,
classValue = Void.class,
arrayClassValue = Void[].class,
enumValue = SampleEnumeration.VALUE,
annotationValue = @Other,
booleanArrayValue = BOOLEAN,
byteArrayValue = BYTE,
shortArrayValue = SHORT,
charArrayValue = CHARACTER,
intArrayValue = INTEGER,
longArrayValue = LONG,
floatArrayValue = FLOAT,
doubleArrayValue = DOUBLE,
stringArrayValue = FOO,
classArrayValue = Void.class,
enumArrayValue = SampleEnumeration.VALUE,
annotationArrayValue = @Other)
private static class FooSample {
/* empty */
}
@Sample(booleanValue = BOOLEAN,
byteValue = BYTE,
charValue = CHARACTER,
shortValue = SHORT,
intValue = INTEGER,
longValue = LONG,
floatValue = FLOAT,
doubleValue = DOUBLE,
stringValue = BAR,
classValue = Void.class,
arrayClassValue = Void[].class,
enumValue = SampleEnumeration.VALUE,
annotationValue = @Other,
booleanArrayValue = BOOLEAN,
byteArrayValue = BYTE,
shortArrayValue = SHORT,
charArrayValue = CHARACTER,
intArrayValue = INTEGER,
longArrayValue = LONG,
floatArrayValue = FLOAT,
doubleArrayValue = DOUBLE,
stringArrayValue = FOO,
classArrayValue = Void.class,
enumArrayValue = SampleEnumeration.VALUE,
annotationArrayValue = @Other)
private static class BarSample {
/* empty */
}
@SampleDefault
private static class DefaultSample {
/* empty */
}
@SampleDefault(booleanValue = !BOOLEAN,
byteValue = BYTE * 2,
charValue = CHARACTER * 2,
shortValue = SHORT * 2,
intValue = INTEGER * 2,
longValue = LONG * 2,
floatValue = FLOAT * 2,
doubleValue = DOUBLE * 2,
stringValue = BAR,
classValue = Object.class,
arrayClassValue = Object[].class,
enumValue = SampleEnumeration.OTHER,
annotationValue = @Other(BAR),
booleanArrayValue = !BOOLEAN,
byteArrayValue = OTHER_BYTE,
shortArrayValue = OTHER_SHORT,
charArrayValue = OTHER_CHARACTER,
intArrayValue = OTHER_INTEGER,
longArrayValue = OTHER_LONG,
floatArrayValue = OTHER_FLOAT,
doubleArrayValue = OTHER_DOUBLE,
stringArrayValue = BAR,
classArrayValue = Object.class,
enumArrayValue = SampleEnumeration.OTHER,
annotationArrayValue = @Other(BAR))
private static class NonDefaultSample {
/* empty */
}
@Other
private static class EnumerationCarrier {
/* empty */
}
@Other(BAR)
private static class OtherEnumerationCarrier {
/* empty */
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
protected @interface ExplicitTarget {
@ExplicitTarget
class Carrier {
/* empty */
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface BrokenAnnotation {
String stringValue();
SampleEnumeration enumValue();
Class<?> classValue();
}
private static class AnnotationValueBreaker extends AsmVisitorWrapper.AbstractBase {
public ClassVisitor wrap(TypeDescription instrumentedType,
ClassVisitor classVisitor,
Implementation.Context implementationContext,
TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields,
MethodList<?> methods,
int writerFlags,
int readerFlags) {
return new BreakingClassVisitor(classVisitor);
}
private static class BreakingClassVisitor extends ClassVisitor {
public BreakingClassVisitor(ClassVisitor classVisitor) {
super(OpenedClassReader.ASM_API, classVisitor);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
AnnotationVisitor annotationVisitor = visitAnnotation(Type.getDescriptor(BrokenAnnotation.class), true);
annotationVisitor.visit("stringValue", INTEGER);
annotationVisitor.visitEnum("enumValue", Type.getDescriptor(SampleEnumeration.class), FOO);
annotationVisitor.visit("classValue", Type.getType("Lnet/bytebuddy/inexistant/Foo;"));
annotationVisitor.visitEnd();
}
}
}
}
|
9245d4c78fee9609e514b3fd1dcdc75bde05608f | 1,843 | java | Java | mall-spring-boot/src/main/java/edu/nju/mall/config/HttpMessageConvertersConfig.java | Rogues-in-NJU/MALL | 6dc99d682621e6166cd4ce4a30c87edc15f7fdf3 | [
"Apache-2.0"
] | null | null | null | mall-spring-boot/src/main/java/edu/nju/mall/config/HttpMessageConvertersConfig.java | Rogues-in-NJU/MALL | 6dc99d682621e6166cd4ce4a30c87edc15f7fdf3 | [
"Apache-2.0"
] | 14 | 2020-01-30T05:00:42.000Z | 2022-03-02T07:09:44.000Z | mall-spring-boot/src/main/java/edu/nju/mall/config/HttpMessageConvertersConfig.java | Rogues-in-NJU/MALL | 6dc99d682621e6166cd4ce4a30c87edc15f7fdf3 | [
"Apache-2.0"
] | 1 | 2020-01-30T04:31:55.000Z | 2020-01-30T04:31:55.000Z | 44.95122 | 88 | 0.784048 | 1,003,535 | package edu.nju.mall.config;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class HttpMessageConvertersConfig {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
// supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
// supportedMediaTypes.add(MediaType.TEXT_XML);
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
fastConverter.setSupportedMediaTypes(supportedMediaTypes);
return new HttpMessageConverters(fastConverter);
}
}
|
9245d5785b00e53867d4eeaf360aa4d5f9e792d5 | 2,213 | java | Java | src/main/java/net/codestory/http/templating/helpers/WebjarHelperSource.java | AutoscanForJava/net.code-story-http | 5aba37bbd00d1e1278a95678a42fc46a5fefd61f | [
"Apache-2.0"
] | 182 | 2015-01-08T17:27:23.000Z | 2021-07-06T05:46:42.000Z | src/main/java/net/codestory/http/templating/helpers/WebjarHelperSource.java | AutoscanForJava/net.code-story-http | 5aba37bbd00d1e1278a95678a42fc46a5fefd61f | [
"Apache-2.0"
] | 71 | 2015-01-10T18:25:58.000Z | 2020-11-03T14:41:51.000Z | src/main/java/net/codestory/http/templating/helpers/WebjarHelperSource.java | AutoscanForJava/net.code-story-http | 5aba37bbd00d1e1278a95678a42fc46a5fefd61f | [
"Apache-2.0"
] | 38 | 2015-01-09T14:27:22.000Z | 2022-02-21T19:36:53.000Z | 32.558824 | 94 | 0.720867 | 1,003,536 | /**
* Copyright (C) 2013-2015 [email protected]
*
* 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.codestory.http.templating.helpers;
import com.github.jknack.handlebars.Options;
import net.codestory.http.misc.Cache;
import net.codestory.http.misc.WebJarUrlFinder;
import java.net.URL;
import java.util.function.Function;
import static net.codestory.http.io.Strings.substringAfter;
public class WebjarHelperSource {
private final WebJarUrlFinder webJarUrlFinder;
private final Function<String, String> fullPathForUri;
public WebjarHelperSource(boolean prodMode) {
this.webJarUrlFinder = new WebJarUrlFinder(prodMode);
this.fullPathForUri = prodMode ? new Cache<>(this::fullPathForUri) : this::fullPathForUri;
}
// Handler entry point
public CharSequence webjar(Object context, Options options) {
String attributes = HelperTools.hashAsString(options);
return HelperTools.toString(context, value -> singleWebjar(value, attributes));
}
// Internal
private String singleWebjar(Object value, String attributes) {
String fullPath = fullPathForUri.apply(value.toString());
return tag(fullPath, attributes);
}
private String fullPathForUri(String uri) {
URL classpathUrl = webJarUrlFinder.url(uri);
if (classpathUrl == null) {
return uri; // Not found
}
return substringAfter(classpathUrl.toString(), "/META-INF/resources");
}
private String tag(String fullPath, String attributes) {
if (fullPath.endsWith(".css")) {
return "<link rel=\"stylesheet\" href=\"" + fullPath + "\"" + attributes + ">";
} else {
return "<script src=\"" + fullPath + "\"" + attributes + "></script>";
}
}
}
|
9245d6000508871733fe9e0db25e2c40f39dd611 | 800 | java | Java | tacomall-api/api/ma/src/main/java/store/tacomall/apima/service/impl/OrderFormGoodsItemsServiceImpl.java | jadesun/tacomall | d00d24d7d218742d12a03fd92562fb076a3ee913 | [
"Apache-2.0"
] | 1 | 2021-12-13T02:22:51.000Z | 2021-12-13T02:22:51.000Z | tacomall-api/api/ma/src/main/java/store/tacomall/apima/service/impl/OrderFormGoodsItemsServiceImpl.java | jadesun/tacomall | d00d24d7d218742d12a03fd92562fb076a3ee913 | [
"Apache-2.0"
] | null | null | null | tacomall-api/api/ma/src/main/java/store/tacomall/apima/service/impl/OrderFormGoodsItemsServiceImpl.java | jadesun/tacomall | d00d24d7d218742d12a03fd92562fb076a3ee913 | [
"Apache-2.0"
] | null | null | null | 35.217391 | 118 | 0.809877 | 1,003,537 | /***
* @Author: [email protected]
* @Date: 2021-11-02 15:54:27
* @LastEditTime: 2021-11-02 15:55:36
* @LastEditors: 码上talk|RC
* @Description:
* @FilePath: /tacomall-api/api/ma/src/main/java/store/tacomall/apima/service/impl/OrderFormGoodsItemsServiceImpl.java
*/
package store.tacomall.apima.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import store.tacomall.apima.service.OrderFormGoodsItemsService;
import store.tacomall.common.entity.order.OrderFormGoodsItems;
import store.tacomall.common.mapper.order.OrderFormGoodsItemsMapper;
@Service
public class OrderFormGoodsItemsServiceImpl extends ServiceImpl<OrderFormGoodsItemsMapper, OrderFormGoodsItems>
implements OrderFormGoodsItemsService {
} |
9245d6b4a49cca09ca61087d715bdc6dc7264931 | 3,213 | java | Java | smile/src/test/java/com/fasterxml/jackson/dataformat/smile/parse/UnicodeHandlingTest.java | gaybro8777/jackson-dataformats-binary | 61a7d7510a6c9846e49b85faf11d697b30c797c0 | [
"Apache-2.0"
] | null | null | null | smile/src/test/java/com/fasterxml/jackson/dataformat/smile/parse/UnicodeHandlingTest.java | gaybro8777/jackson-dataformats-binary | 61a7d7510a6c9846e49b85faf11d697b30c797c0 | [
"Apache-2.0"
] | null | null | null | smile/src/test/java/com/fasterxml/jackson/dataformat/smile/parse/UnicodeHandlingTest.java | gaybro8777/jackson-dataformats-binary | 61a7d7510a6c9846e49b85faf11d697b30c797c0 | [
"Apache-2.0"
] | 1 | 2021-02-09T07:44:00.000Z | 2021-02-09T07:44:00.000Z | 34.548387 | 91 | 0.652039 | 1,003,538 | package com.fasterxml.jackson.dataformat.smile.parse;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.smile.BaseTestForSmile;
import com.fasterxml.jackson.dataformat.smile.testutil.ThrottledInputStream;
public class UnicodeHandlingTest extends BaseTestForSmile
{
public void testShortUnicodeWithSurrogates() throws IOException
{
_testLongUnicodeWithSurrogates(28, false);
_testLongUnicodeWithSurrogates(28, true);
_testLongUnicodeWithSurrogates(53, false);
_testLongUnicodeWithSurrogates(230, false);
}
public void testLongUnicodeWithSurrogates() throws IOException
{
_testLongUnicodeWithSurrogates(700, false);
_testLongUnicodeWithSurrogates(900, true);
_testLongUnicodeWithSurrogates(9600, false);
_testLongUnicodeWithSurrogates(9600, true);
}
private void _testLongUnicodeWithSurrogates(int length,
boolean throttling) throws IOException
{
final String SURROGATE_CHARS = "\ud834\udd1e";
StringBuilder sb = new StringBuilder(length+200);
while (sb.length() < length) {
sb.append(SURROGATE_CHARS);
sb.append(sb.length());
if ((sb.length() & 1) == 1) {
sb.append("\u00A3");
} else {
sb.append("\u3800");
}
}
final String TEXT = sb.toString();
final String quoted = quote(TEXT);
byte[] data = _smileDoc(quoted);
JsonParser p = _parser(data, throttling);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertEquals(TEXT, p.getText());
assertNull(p.nextToken());
p.close();
// Then same but skipping
p = _parser(data, throttling);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertNull(p.nextToken());
p.close();
// Also, verify that it works as field name
data = _smileDoc("{"+quoted+":true}");
p = _parser(data, throttling);
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.FIELD_NAME, p.nextToken());
assertEquals(TEXT, p.currentName());
assertToken(JsonToken.VALUE_TRUE, p.nextToken());
assertToken(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
// and skipping
p = _parser(data, throttling);
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.FIELD_NAME, p.nextToken());
assertToken(JsonToken.VALUE_TRUE, p.nextToken());
assertToken(JsonToken.END_OBJECT, p.nextToken());
p.close();
}
private final ObjectMapper MAPPER = new ObjectMapper(smileFactory(false, true, false));
@SuppressWarnings("resource")
private JsonParser _parser(byte[] data, boolean throttling) throws IOException
{
if (throttling) {
return MAPPER.createParser(new ThrottledInputStream(data, 3));
}
return MAPPER.createParser(data);
}
}
|
9245d7686578d8188eb30c4b7cf9d917324a4e46 | 1,912 | java | Java | src/main/java/de/hpi/julianweise/query/join/ADBJoinQuery.java | julianweise/actor-based-database | 69438a6f11dad1065f516d17e318a2b7fa1204db | [
"MIT"
] | 1 | 2020-11-26T08:02:01.000Z | 2020-11-26T08:02:01.000Z | src/main/java/de/hpi/julianweise/query/join/ADBJoinQuery.java | julianweise/actor-based-database | 69438a6f11dad1065f516d17e318a2b7fa1204db | [
"MIT"
] | 2 | 2021-12-18T18:25:34.000Z | 2022-01-04T16:41:59.000Z | src/main/java/de/hpi/julianweise/query/join/ADBJoinQuery.java | julianweise/actor-based-database | 69438a6f11dad1065f516d17e318a2b7fa1204db | [
"MIT"
] | 2 | 2020-03-27T13:17:31.000Z | 2021-07-23T11:32:21.000Z | 31.866667 | 107 | 0.641736 | 1,003,539 | package de.hpi.julianweise.query.join;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.hpi.julianweise.query.ADBQuery;
import de.hpi.julianweise.utility.list.ObjectArrayListCollector;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ADBJoinQuery implements ADBQuery {
protected List<ADBJoinQueryPredicate> predicates = new ArrayList<>();
protected boolean shouldBeMaterialized;
public ADBJoinQuery(List<ADBJoinQueryPredicate> predicates) {
this.predicates = predicates;
}
public void addPredicate(ADBJoinQueryPredicate predicate) {
this.getPredicates().add(predicate);
}
public String[] getAllLeftHandSideFields() {
return this.getPredicates().stream()
.map(ADBJoinQueryPredicate::getLeftHandSideAttribute)
.distinct()
.toArray(String[]::new);
}
public String[] getAllRightHandSideFields() {
return this.getPredicates().stream()
.map(ADBJoinQueryPredicate::getRightHandSideAttribute)
.distinct()
.toArray(String[]::new);
}
@Override
public String toString() {
return "[JoinQuery] " + this.getPredicates().stream()
.map(ADBJoinQueryPredicate::toString)
.reduce((predicate, acc) -> acc + " & " + predicate).orElse("");
}
@JsonIgnore
public ADBJoinQuery getReverse() {
return new ADBJoinQuery(this.getPredicates().stream()
.map(ADBJoinQueryPredicate::getReverse)
.collect(new ObjectArrayListCollector<>()), this.shouldBeMaterialized);
}
}
|
9245d7ccc126d0d9f1b6283b23cd31449832b1b3 | 11,004 | java | Java | src/main/java/org/ggp/base/util/statemachine/abstractsm/ExplicitStateMachine.java | Lucsparidans/GGP-Project | e3533815ba3269da2e9949485515abe62aa22d86 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/org/ggp/base/util/statemachine/abstractsm/ExplicitStateMachine.java | Lucsparidans/GGP-Project | e3533815ba3269da2e9949485515abe62aa22d86 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/org/ggp/base/util/statemachine/abstractsm/ExplicitStateMachine.java | Lucsparidans/GGP-Project | e3533815ba3269da2e9949485515abe62aa22d86 | [
"BSD-3-Clause"
] | null | null | null | 38.746479 | 221 | 0.766358 | 1,003,540 | package org.ggp.base.util.statemachine.abstractsm;
import java.util.ArrayList;
import java.util.List;
import org.ggp.base.util.gdl.grammar.Gdl;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
import org.ggp.base.util.statemachine.exceptions.StateMachineException;
import org.ggp.base.util.statemachine.exceptions.StateMachineInitializationException;
import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException;
import org.ggp.base.util.statemachine.structure.MachineState;
import org.ggp.base.util.statemachine.structure.Move;
import org.ggp.base.util.statemachine.structure.Role;
import org.ggp.base.util.statemachine.structure.explicit.ExplicitMachineState;
import org.ggp.base.util.statemachine.structure.explicit.ExplicitMove;
import org.ggp.base.util.statemachine.structure.explicit.ExplicitRole;
import csironi.ggp.course.utils.MyPair;
/**
* TODO: using instanceof is not elegant. Find a better way to deal with state machines using different types of moves, states and roles.
*/
public class ExplicitStateMachine extends AbstractStateMachine {
private ExplicitStateMachineInterface theMachine;
public ExplicitStateMachine(ExplicitStateMachineInterface theMachine) {
this.theMachine = theMachine;
}
@Override
public void initialize(List<Gdl> description, long timeout) throws StateMachineInitializationException {
super.initialize(description, timeout);
this.theMachine.initialize(description, timeout);
}
@Override
public List<Double> getAllGoalsForOneRole(MachineState state, Role role) throws StateMachineException {
if(state instanceof ExplicitMachineState && role instanceof ExplicitRole){
return this.theMachine.getAllGoalsForOneRole((ExplicitMachineState)state, (ExplicitRole)role);
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-getAllGoalsForOneRole(): detected wrong type for machine state and/or role: [" + state.getClass().getSimpleName() + ", " + role.getClass().getSimpleName() + "].");
}
}
@Override
public boolean isTerminal(MachineState state) throws StateMachineException {
if(state instanceof ExplicitMachineState){
return this.theMachine.isTerminal((ExplicitMachineState)state);
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-isTerminal(): detected wrong type for machine state : [" + state.getClass().getSimpleName() + "].");
}
}
@Override
public MachineState getInitialState() {
return this.theMachine.getExplicitInitialState();
}
@Override
public List<Move> getLegalMoves(MachineState state, Role role) throws MoveDefinitionException, StateMachineException{
if(state instanceof ExplicitMachineState && role instanceof ExplicitRole){
return new ArrayList<Move>(this.theMachine.getExplicitLegalMoves((ExplicitMachineState)state, (ExplicitRole)role));
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-getLegalMoves(): detected wrong type for machine state and/or role: [" + state.getClass().getSimpleName() + ", " + role.getClass().getSimpleName() + "].");
}
}
@Override
public MachineState getNextState(MachineState state, List<Move> moves) throws TransitionDefinitionException, StateMachineException {
if(state instanceof ExplicitMachineState){
return this.theMachine.getExplicitNextState((ExplicitMachineState)state, this.convertListOfMoves(moves));
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-getNextState(): detected wrong type for machine state: [" + state.getClass().getSimpleName() + "].");
}
}
@Override
public ExplicitMachineState convertToExplicitMachineState(MachineState state) {
if(state instanceof ExplicitMachineState){
return (ExplicitMachineState)state;
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-convertToExplicitMachineState(): detected wrong type for machine state: [" + state.getClass().getSimpleName() + "].");
}
}
@Override
public ExplicitMove convertToExplicitMove(Move move) {
if(move instanceof ExplicitMove){
return (ExplicitMove)move;
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-convertToExplicitMove(): detected wrong type for move: [" + move.getClass().getSimpleName() + "].");
}
}
@Override
public ExplicitRole convertToExplicitRole(Role role) {
if(role instanceof ExplicitRole){
return (ExplicitRole)role;
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-convertToExplicitRole(): detected wrong type for role: [" + role.getClass().getSimpleName() + "].");
}
}
@Override
public void shutdown() {
this.theMachine.shutdown();
}
@Override
protected List<Role> computeRoles() {
return new ArrayList<Role>(this.theMachine.getExplicitRoles());
}
private List<ExplicitMove> convertListOfMoves(List<Move> moves){
List<ExplicitMove> explicitMoves = new ArrayList<ExplicitMove>();
for(Move m : moves){
if(m instanceof ExplicitMove){
explicitMoves.add((ExplicitMove)m);
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-checkListOfMoves(): detected wrong type for move: [" + m.getClass().getSimpleName() + "].");
}
}
return explicitMoves;
}
@Override
public String getName() {
return this.getClass().getSimpleName() + "(" + this.theMachine.getName() + ")";
}
@Override
public MyPair<double[], Double> fastPlayouts(MachineState state, int numSimulationsPerPlayout, int maxDepth) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException, StateMachineException {
if(state instanceof ExplicitMachineState){
return this.theMachine.fastPlayouts((ExplicitMachineState)state, numSimulationsPerPlayout, maxDepth);
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-fastPlayouts(): detected wrong type for machine state: [" + state.getClass().getSimpleName() + "].");
}
}
/*
@Override
public List<Move> getJointMove(List<List<Move>> legalMovesPerRole, MachineState state) throws MoveDefinitionException, StateMachineException {
if(state instanceof ExplicitMachineState){
List<List<ExplicitMove>> explicitLegalMovesPerRole = new ArrayList<List<ExplicitMove>>();
for(List<Move> legalMoves: legalMovesPerRole) {
List<ExplicitMove> explicitLegalMoves = new ArrayList<ExplicitMove>();
for(Move move: legalMoves) {
if(move instanceof ExplicitMove) {
explicitLegalMoves.add((ExplicitMove)move);
}else {
throw new RuntimeException("ExplicitStateMachine-getJointMove(): detected wrong type for move: [" + move.getClass().getSimpleName() + "].");
}
}
explicitLegalMovesPerRole.add(explicitLegalMoves);
}
return new ArrayList<Move>(this.theMachine.getJointMove(explicitLegalMovesPerRole, (ExplicitMachineState)state));
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-getJointMove(): detected wrong type for machine state: [" + state.getClass().getSimpleName() + "].");
}
}
*/
@Override
public Move getMoveForRole(List<Move> legalMoves, MachineState state, Role role) throws StateMachineException, MoveDefinitionException {
if(state instanceof ExplicitMachineState){
if(role instanceof ExplicitRole) {
List<ExplicitMove> explicitLegalMoves;
if(legalMoves != null) {
explicitLegalMoves = new ArrayList<ExplicitMove>();
for(Move move: legalMoves) {
if(move instanceof ExplicitMove) {
explicitLegalMoves.add((ExplicitMove)move);
}else {
throw new RuntimeException("ExplicitStateMachine-getMoveForRole(): detected wrong type for move: [" + move.getClass().getSimpleName() + "].");
}
}
}else {
explicitLegalMoves = null;
}
return this.theMachine.getMoveForRole(explicitLegalMoves, (ExplicitMachineState)state, (ExplicitRole)role);
}else {
throw new RuntimeException("ExplicitStateMachine-getMoveForRole(): detected wrong type for role: [" + role.getClass().getSimpleName() + "].");
}
}else{
// Not throwing StateMachineException because failure here is not the fault of the state machine but
// the fault of some programming error that caused the wrong state and role formats to end up here.
throw new RuntimeException("ExplicitStateMachine-getMoveForRole(): detected wrong type for machine state: [" + state.getClass().getSimpleName() + "].");
}
}
@Override
public MachineState convertToInternalMachineState(ExplicitMachineState explicitState) {
return explicitState;
}
@Override
public Move convertToInternalMove(ExplicitMove explicitMove, ExplicitRole explicitRole) {
return explicitMove;
}
@Override
public Role convertToInternalRole(ExplicitRole explicitRole) {
return explicitRole;
}
@Override
public void doPerMoveWork() {
this.theMachine.doPerMoveWork();
}
@Override
public StateMachine getActualStateMachine() {
return this.theMachine.getActualStateMachine();
}
}
|
9245d7d67115915a4265ef089239bbe0e86b930e | 728 | java | Java | server/rest/src/main/java/org/infinispan/rest/ServerRestBlockHoundIntegration.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 713 | 2015-01-06T02:14:17.000Z | 2022-03-29T10:22:07.000Z | server/rest/src/main/java/org/infinispan/rest/ServerRestBlockHoundIntegration.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 5,732 | 2015-01-01T19:13:35.000Z | 2022-03-31T16:31:11.000Z | server/rest/src/main/java/org/infinispan/rest/ServerRestBlockHoundIntegration.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 402 | 2015-01-05T23:23:42.000Z | 2022-03-25T08:14:32.000Z | 38.315789 | 108 | 0.785714 | 1,003,541 | package org.infinispan.rest;
import org.kohsuke.MetaInfServices;
import reactor.blockhound.BlockHound;
import reactor.blockhound.integration.BlockHoundIntegration;
@MetaInfServices
public class ServerRestBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(BlockHound.Builder builder) {
// ChunkedFile read is blocking - This can be fixed in
// https://issues.redhat.com/browse/ISPN-11834
builder.allowBlockingCallsInside(ResponseWriter.CHUNKED_FILE.getClass().getName(), "writeResponse");
// ChunkedInputStream read is blocking, see ISPN-13131
builder.allowBlockingCallsInside(ResponseWriter.CHUNKED_STREAM.getClass().getName(), "writeResponse");
}
}
|
9245d9073d39558e1e8b13c7068a28d6ce85b513 | 6,351 | java | Java | net.sourceforge.texlipse/source/net/sourceforge/texlipse/tableview/views/TexCellListener.java | alaplums/TeXlipse | 44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61 | [
"MIT"
] | null | null | null | net.sourceforge.texlipse/source/net/sourceforge/texlipse/tableview/views/TexCellListener.java | alaplums/TeXlipse | 44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61 | [
"MIT"
] | null | null | null | net.sourceforge.texlipse/source/net/sourceforge/texlipse/tableview/views/TexCellListener.java | alaplums/TeXlipse | 44b755c3a7bdb7bcd9ba6b2be45d7aa7b977cd61 | [
"MIT"
] | 1 | 2020-05-17T14:20:07.000Z | 2020-05-17T14:20:07.000Z | 38.72561 | 83 | 0.590301 | 1,003,542 | /*
* $Id$
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package net.sourceforge.texlipse.tableview.views;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
/**
* @author Esa Seuranen
*
* A key listener class for individual cells in the table viewer.
*
* The main purpose for this class is to enable better (more usable) controls
* when editing table entries in the table viewer (TableViewer), which, as the
* name suggest, is not originally designed to be a table editor. However, this
* class enables fast moving around between neighboring cells by using
* CTRL+ArrowKeys.
*/
public class TexCellListener implements KeyListener {
/** Table Viewer to which listener belongs */
private TableViewer viewer;
/** Column, which the listener listens
* This is here, because there seems to be no way
* to extract the "current column" information from the viewer...
*/
private int column;
/** The underlying datastructure, TexRowList, of the whole table */
private TexRowList texRowList;
/**
* Constructor
*
* DO NOT USE THIS, use the other constructor(s) instead
*/
private TexCellListener() {
}
/**
* Constructor for the cell listener.
*
* Column information is necessary, so that moving around neighboring cell
* listener (i.e. activating the editing controls) can be done.
*
* @param viewer
* to which the cell listener belongs to
* @param texRowList
* the underlying datastructure for the whole table
* @param column
* which the cell listener listens to
*/
public TexCellListener(TableViewer viewer, TexRowList texRowList, int column) {
this.viewer = viewer;
this.texRowList = texRowList;
this.column = column;
}
/**
* KeyListener method from KeyListener Interface
*
* Determines the actions to be taken, when a key is pressed. That means
* either moving the editing controls to neigboring cell, if a)
* CTRL+ArrowKey was pressed b) neighboring cell in that direction exists or
* calculating a sum of cells in given direction (and copying it to
* clipboard) c) CTRL+KEYPAD_8,_2,_4 or _6 (up, down, left, right) is
* pressed
*
* @param e key event that occured
*/
public void keyPressed(KeyEvent e) {
if ((e.stateMask & (SWT.CTRL | SWT.ALT | SWT.SHIFT)) != SWT.CTRL)
return;
int row = viewer.getTable().getSelectionIndex();
int columns = viewer.getTable().getColumnCount();
int rows = viewer.getTable().getItemCount();
// FIXME redundant test
if ((e.stateMask & (SWT.CTRL | SWT.ALT | SWT.SHIFT)) == SWT.CTRL) {
//TexRow texRow = (TexRow) texRowList.getRows().get(row);
double sum = 0.0;
switch (e.keyCode) {
case SWT.ARROW_UP:
if (row > 0)
viewer.editElement(viewer.getElementAt(row - 1), column);
break;
case SWT.ARROW_DOWN:
/*
if (row < rows - 1) // TODO else { add one row to the model }
viewer.editElement(viewer.getElementAt(row + 1), column);
*/
if (row >= rows - 1)
texRowList.addRow();
viewer.editElement(viewer.getElementAt(row + 1), column);
break;
case SWT.ARROW_LEFT:
if (column > 0)
viewer.editElement(viewer.getElementAt(row), column - 1);
break;
case SWT.ARROW_RIGHT:
if (column < columns - 1)
viewer.editElement(viewer.getElementAt(row), column + 1);
break;
case SWT.KEYPAD_8:
sum = texRowList.sum(column, row, TexRowList.SUM_UP);
if(row>0) {
viewer.editElement(viewer.getElementAt(row - 1), column);
((TexRow)texRowList.getRows().get(row)).setCol(column,
((int)sum==sum)?Integer.toString((int)sum):Double.toString(sum));
viewer.editElement(viewer.getElementAt(row), column);
}
break;
case SWT.KEYPAD_2:
sum = texRowList.sum(column, row, TexRowList.SUM_DOWN);
if(row<texRowList.getRows().size()-1) {
viewer.editElement(viewer.getElementAt(row + 1), column);
((TexRow)texRowList.getRows().get(row)).setCol(column,
((int)sum==sum)?Integer.toString((int)sum):Double.toString(sum));
viewer.editElement(viewer.getElementAt(row), column);
}
break;
case SWT.KEYPAD_4:
sum = texRowList.sum(column, row, TexRowList.SUM_LEFT);
if(column>0) {
viewer.editElement(viewer.getElementAt(row), column-1);
((TexRow)texRowList.getRows().get(row)).setCol(column,
((int)sum==sum)?Integer.toString((int)sum):Double.toString(sum));
viewer.editElement(viewer.getElementAt(row), column);
}
break;
case SWT.KEYPAD_6:
sum = texRowList.sum(column, row, TexRowList.SUM_RIGHT);
if(column<TexRow.COLUMNS-1) {
viewer.editElement(viewer.getElementAt(row), column+1);
((TexRow)texRowList.getRows().get(row)).setCol(column,
((int)sum==sum)?Integer.toString((int)sum):Double.toString(sum));
viewer.editElement(viewer.getElementAt(row), column);
}
break;
}
}
}
/**
* KeyListener method from KeyListener Interface
*
* Determines the actions to be taken, when a key is released
* (which is absolutely nothing).
*
* @param e key event, that occurred
*/
public void keyReleased(KeyEvent e) {
}
} |
9245da5db3b4614f546b6c13e83d3e68ad4f3e4b | 5,619 | java | Java | small-spring-step-19/src/main/java/cn/bugstack/springframework/util/ClassUtils.java | zh-d-d/small-spring | 0e24960bd6d06bc35b2ad256353b949108f6151d | [
"Apache-2.0"
] | 1 | 2022-03-14T01:45:34.000Z | 2022-03-14T01:45:34.000Z | small-spring-step-19/src/main/java/cn/bugstack/springframework/util/ClassUtils.java | zh-d-d/small-spring | 0e24960bd6d06bc35b2ad256353b949108f6151d | [
"Apache-2.0"
] | null | null | null | small-spring-step-19/src/main/java/cn/bugstack/springframework/util/ClassUtils.java | zh-d-d/small-spring | 0e24960bd6d06bc35b2ad256353b949108f6151d | [
"Apache-2.0"
] | null | null | null | 35.339623 | 104 | 0.621997 | 1,003,543 | package cn.bugstack.springframework.util;
import cn.hutool.core.lang.Assert;
import java.io.Closeable;
import java.io.Externalizable;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
public class ClassUtils {
private static final Set<Class<?>> javaLanguageInterfaces;
private static final Map<String, Class<?>> commonClassCache = new HashMap<>(64);
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(8);
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap<>(8);
static {
Class<?>[] javaLanguageInterfaceArray = {Serializable.class, Externalizable.class,
Closeable.class, AutoCloseable.class, Cloneable.class, Comparable.class};
registerCommonClasses(javaLanguageInterfaceArray);
javaLanguageInterfaces = new HashSet<>(Arrays.asList(javaLanguageInterfaceArray));
}
private static void registerCommonClasses(Class<?>... commonClasses) {
for (Class<?> clazz : commonClasses) {
commonClassCache.put(clazz.getName(), clazz);
}
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtils.class.getClassLoader();
}
return cl;
}
/**
* Check whether the specified class is a CGLIB-generated class.
* @param clazz the class to check
*/
public static boolean isCglibProxyClass(Class<?> clazz) {
return (clazz != null && isCglibProxyClassName(clazz.getName()));
}
/**
* Check whether the specified class name is a CGLIB-generated class.
* @param className the class name to check
*/
public static boolean isCglibProxyClassName(String className) {
return (className != null && className.contains("$$"));
}
public static String getQualifiedMethodName(Method method, Class<?> clazz) {
Assert.notNull(method, "Method must not be null");
return (clazz != null ? clazz : method.getDeclaringClass()).getName() + "." + method.getName();
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, null);
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
return toClassArray(getAllInterfacesForClassAsSet(clazz, classLoader));
}
public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface() && isVisible(clazz, classLoader)) {
return Collections.singleton(clazz);
}
Set<Class<?>> interfaces = new LinkedHashSet<>();
Class<?> current = clazz;
while (current != null) {
Class<?>[] ifcs = current.getInterfaces();
for (Class<?> ifc : ifcs) {
if (isVisible(ifc, classLoader)) {
interfaces.add(ifc);
}
}
current = current.getSuperclass();
}
return interfaces;
}
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
if (clazz.getClassLoader() == classLoader) {
return true;
}
} catch (SecurityException ex) {
// Fall through to loadable check below
}
// Visible if same Class can be loaded from given ClassLoader
return isLoadable(clazz, classLoader);
}
private static boolean isLoadable(Class<?> clazz, ClassLoader classLoader) {
try {
return (clazz == classLoader.loadClass(clazz.getName()));
// Else: different class with same name found
} catch (ClassNotFoundException ex) {
// No corresponding class found at all
return false;
}
}
public static Class<?>[] toClassArray(Collection<Class<?>> collection) {
return collection.toArray(new Class<?>[0]);
}
public static boolean isJavaLanguageInterface(Class<?> ifc) {
return javaLanguageInterfaces.contains(ifc);
}
public static boolean isInnerClass(Class<?> clazz) {
return (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()));
}
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Assert.notNull(lhsType, "Left-hand side type must not be null");
Assert.notNull(rhsType, "Right-hand side type must not be null");
if (lhsType.isAssignableFrom(rhsType)) {
return true;
}
if (lhsType.isPrimitive()) {
Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);
if (lhsType == resolvedPrimitive) {
return true;
}
} else {
Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) {
return true;
}
}
return false;
}
}
|
9245db5dc1a9505f779ee8a00e3903158fa56ed7 | 3,453 | java | Java | app/src/main/java/com/xw/project/gracefulmovies/ui/activity/BoxOfficeActivity.java | kapw001/GracefulMovies | cb8d4b68e0d864772325575c05c989f145fd797b | [
"Apache-2.0"
] | 973 | 2017-02-27T03:36:01.000Z | 2022-03-19T15:07:29.000Z | app/src/main/java/com/xw/project/gracefulmovies/ui/activity/BoxOfficeActivity.java | kapw001/GracefulMovies | cb8d4b68e0d864772325575c05c989f145fd797b | [
"Apache-2.0"
] | 14 | 2017-02-27T07:51:21.000Z | 2021-01-23T04:07:07.000Z | app/src/main/java/com/xw/project/gracefulmovies/ui/activity/BoxOfficeActivity.java | kapw001/GracefulMovies | cb8d4b68e0d864772325575c05c989f145fd797b | [
"Apache-2.0"
] | 218 | 2017-02-27T04:17:15.000Z | 2022-03-19T15:07:30.000Z | 33.524272 | 127 | 0.695048 | 1,003,544 | package com.xw.project.gracefulmovies.ui.activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.res.Resources;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import com.xw.project.gracefulmovies.GMApplication;
import com.xw.project.gracefulmovies.R;
import com.xw.project.gracefulmovies.data.DataResource;
import com.xw.project.gracefulmovies.databinding.ActivityBoxOfficeBinding;
import com.xw.project.gracefulmovies.ui.activity.base.BaseActivity;
import com.xw.project.gracefulmovies.ui.adapter.BoxOfficeAdapter;
import com.xw.project.gracefulmovies.viewmodel.BoxOfficeViewModel;
/**
* 票房
* <p>
* Created by xoxingxiao on 2018-08-17.
*/
public class BoxOfficeActivity extends BaseActivity<ActivityBoxOfficeBinding> implements SwipeRefreshLayout.OnRefreshListener {
private BoxOfficeAdapter mAdapter;
private BoxOfficeViewModel mViewModel;
@Override
protected int contentLayoutRes() {
return R.layout.activity_box_office;
}
@Override
protected void afterSetContentView() {
initializeToolbar();
mBinding.fab.setOnClickListener(view -> {
if (mAdapter.getData() != null && !mAdapter.getData().isEmpty())
mBinding.recyclerView.smoothScrollToPosition(0);
});
mBinding.swipeRefreshLayout.setColorSchemeColors(
ContextCompat.getColor(this, R.color.colorAccent),
ContextCompat.getColor(this, R.color.colorPrimary)
);
mBinding.swipeRefreshLayout.setProgressViewEndTarget(false, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 80, Resources.getSystem().getDisplayMetrics()));
mBinding.swipeRefreshLayout.setOnRefreshListener(this);
mAdapter = new BoxOfficeAdapter();
mBinding.recyclerView.setAdapter(mAdapter);
GMApplication.getInstance().getDatabase().boxOfficeDao().loadBoxOfficeList()
.observe(this, list -> mAdapter.setData(list));
mViewModel = ViewModelProviders.of(this).get(BoxOfficeViewModel.class);
mViewModel.getBoxOffices().observe(this, resource -> {
assert resource != null;
processStatusView(resource);
if (resource.getStatus() != DataResource.Status.LOADING) {
mBinding.swipeRefreshLayout.setRefreshing(false);
}
});
mBinding.swipeRefreshLayout.setRefreshing(true);
mViewModel.load();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.box_office, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_attention) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setView(R.layout.layout_box_office_attention_dialog);
builder.setPositiveButton("好的", null);
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onReload() {
mViewModel.load();
}
@Override
public void onRefresh() {
mViewModel.load();
}
}
|
9245dc2f57902fcc6fb7bdd7039b4ac8ddc48d45 | 9,500 | java | Java | services/common/src/main/java/com/epam/dlab/process/ProcessInfoBuilder.java | yarki/DLab | 8df55ca341722ebfb1cf8a857d997f7b82701f34 | [
"Apache-2.0"
] | 1 | 2021-05-13T05:35:53.000Z | 2021-05-13T05:35:53.000Z | services/common/src/main/java/com/epam/dlab/process/ProcessInfoBuilder.java | yarki/DLab | 8df55ca341722ebfb1cf8a857d997f7b82701f34 | [
"Apache-2.0"
] | null | null | null | services/common/src/main/java/com/epam/dlab/process/ProcessInfoBuilder.java | yarki/DLab | 8df55ca341722ebfb1cf8a857d997f7b82701f34 | [
"Apache-2.0"
] | null | null | null | 34.671533 | 113 | 0.545053 | 1,003,545 | /*
Copyright 2016 EPAM Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.epam.dlab.process;
import com.aegisql.conveyor.Expireable;
import com.aegisql.conveyor.Testing;
import com.aegisql.conveyor.TimeoutAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
import static com.epam.dlab.process.ProcessStatus.*;
public class ProcessInfoBuilder implements Supplier<ProcessInfo>, Testing, TimeoutAction, Expireable {
private final static Logger LOG = LoggerFactory.getLogger(ProcessInfoBuilder.class);
private final ProcessId processId;
private final long startTimeStamp = System.currentTimeMillis();
private ProcessStatus status = CREATED;
private final StringBuilder stdOut = new StringBuilder();
private final StringBuilder stdErr = new StringBuilder();
private int exitCode = -1;
private String[] command = new String[]{"N/A"};
private Collection<ProcessInfo> rejected = null;
private int pid = -1;
private boolean finished = false;
private boolean stdOutClosed = false;
private boolean stdErrClosed = false;
private Process p = null;
private CompletableFuture<ProcessInfo> future;
private long expirationTime;
public ProcessInfoBuilder(ProcessId processId, long ttl) {
this.processId = processId;
this.expirationTime = System.currentTimeMillis() + ttl;
}
public static void schedule(ProcessInfoBuilder b, String[] command) {
b.status = SCHEDULED;
b.command = command;
}
public static void start(ProcessInfoBuilder b, String[] command) {
if( b.status == CREATED ) {
b.status = LAUNCHING;
b.command = command;
b.launch();
} else {
if(b.rejected == null) {
b.rejected = new LinkedList<>();
}
long timeStamp = System.currentTimeMillis();
b.rejected.add(new ProcessInfo(
b.processId,
REJECTED,
command,
"",
"rejected duplicated command",
REJECTED.ordinal(),
timeStamp,
timeStamp,null, b.pid));
}
}
public static void failed(ProcessInfoBuilder b, Object dummy) {
b.status = FAILED;
b.setReady();
}
public static void stop(ProcessInfoBuilder b, Object dummy) {
if(b.p != null) {
b.p.destroy();
}
if(b.status != LAUNCHING && b.status != RUNNING) {
b.setReady();
}
b.status = STOPPED;
}
public static void kill(ProcessInfoBuilder b, Object dummy) {
if(b.p != null) {
b.p.destroyForcibly();
}
if(b.status != LAUNCHING && b.status != RUNNING) {
b.setReady();
}
b.status = KILLED;
}
public static void finish(ProcessInfoBuilder b, Integer exitCode) {
if(b.status != STOPPED && b.status != KILLED && b.status != TIMEOUT ) {
b.status = FINISHED;
}
b.exitCode = exitCode;
b.finished = true;
}
public static void stdOut(ProcessInfoBuilder b, Object msg) {
if (msg == null) {
b.stdOutClosed = true;
} else {
b.stdOut.append(msg).append("\n");
}
}
public static void stdErr(ProcessInfoBuilder b, Object msg) {
if (msg == null) {
b.stdErrClosed = true;
} else {
b.stdErr.append(msg).append("\n");
}
}
private void launch() {
DlabProcess.getInstance().getUsersExecutorService(processId.getUser()).submit(()->{
status = SCHEDULED;
DlabProcess.getInstance().getExecutorService().execute(()->{
try {
p = new ProcessBuilder(command).start();
pid = getPid(p);
InputStream stdOutStream = p.getInputStream();
DlabProcess.getInstance().getExecutorService().execute(()->{
BufferedReader reader = new BufferedReader(new InputStreamReader(stdOutStream));
String line;
try {
while ((line = reader.readLine()) != null) {
DlabProcess.getInstance().toStdOut(processId,line);
}
DlabProcess.getInstance().toStdOut(processId,null);
} catch (IOException e) {
DlabProcess.getInstance().toStdErr(processId,"Failed process STDOUT reader",e);
DlabProcess.getInstance().failed(processId);
}
});
InputStream stdErrStream = p.getErrorStream();
DlabProcess.getInstance().getExecutorService().execute(()->{
BufferedReader reader = new BufferedReader(new InputStreamReader(stdErrStream));
String line;
try {
while ((line = reader.readLine()) != null) {
DlabProcess.getInstance().toStdErr(processId,line);
}
DlabProcess.getInstance().toStdErr(processId,null);
} catch (IOException e) {
DlabProcess.getInstance().toStdErr(processId,"Failed process STDERR reader",e);
DlabProcess.getInstance().failed(processId);
}
});
status = RUNNING;
int exit = p.waitFor();
DlabProcess.getInstance().finish(processId,exit);
} catch (IOException e) {
DlabProcess.getInstance().toStdErr(processId,"Command launch failed. "+get().getCommand(),e);
DlabProcess.getInstance().failed(processId);
} catch (InterruptedException e) {
DlabProcess.getInstance().toStdErr(processId,"Command interrupted. "+get().getCommand(),e);
DlabProcess.getInstance().failed(processId);
}
});
try {
future.get();
} catch (Exception e) {
}
});
}
@Override
public ProcessInfo get() {
return new ProcessInfo(
processId,
status,
command,
stdOut.toString(),
stdErr.toString(),
exitCode,
startTimeStamp, System.currentTimeMillis(),rejected, pid);
}
@Override
public boolean test() {
return finished && stdOutClosed && stdErrClosed;
}
private void setReady() {
finished = true;
stdOutClosed = true;
stdErrClosed = true;
}
public static void future(ProcessInfoBuilder b, CompletableFuture<ProcessInfo> future) {
if(b.future == null) {
b.future = future;
} else {
future.cancel(true);
}
}
@Override
public void onTimeout() {
if(status != TIMEOUT) {
LOG.debug("Stopping on timeout ...");
stop(this, "STOP");
status = TIMEOUT;
expirationTime += 60_000;
} else {
LOG.debug("Killing on timeout ...");
kill(this, "KILL");
status = TIMEOUT;
setReady();
}
}
@Override
public long getExpirationTime() {
return expirationTime;
}
private static Function<Process,Integer> pidSupplier = null;
public static int getPid(Process process) {
try {
if(pidSupplier == null) {
Class<?> cProcessImpl = process.getClass();
final Field fPid = cProcessImpl.getDeclaredField("pid");
LOG.debug("PID field found");
if (!fPid.isAccessible()) {
fPid.setAccessible(true);
}
pidSupplier = (p) -> {
try {
return fPid.getInt(p);
} catch (IllegalAccessException e) {
LOG.error("Unable to access PID. {}",e.getMessage());
return -1;
}
};
}
return pidSupplier.apply(process);
} catch (NoSuchFieldException e) {
LOG.debug("PID field not found");
pidSupplier = (p) -> -1;
return -1;
}
}
}
|
9245dca785c141e043b345bb0e81f6fe8c501cb8 | 703 | java | Java | bundles/org.eclipse.passage.lic.registry/src/org/eclipse/passage/lic/registry/UserDescriptor.java | arsysop/passage-licensing-runtime | b86f42d329eda031dbc2c5101444cb7fbb1b3a91 | [
"Apache-2.0"
] | 2 | 2018-11-28T07:06:47.000Z | 2019-09-26T08:21:59.000Z | bundles/org.eclipse.passage.lic.registry/src/org/eclipse/passage/lic/registry/UserDescriptor.java | arsysop/passage-lic | b86f42d329eda031dbc2c5101444cb7fbb1b3a91 | [
"Apache-2.0"
] | 9 | 2018-11-17T15:35:33.000Z | 2018-12-16T20:37:25.000Z | bundles/org.eclipse.passage.lic.registry/src/org/eclipse/passage/lic/registry/UserDescriptor.java | arsysop/passage-licensing-runtime | b86f42d329eda031dbc2c5101444cb7fbb1b3a91 | [
"Apache-2.0"
] | 1 | 2018-12-01T10:18:07.000Z | 2018-12-01T10:18:07.000Z | 27.038462 | 81 | 0.570413 | 1,003,546 | /*******************************************************************************
* Copyright (c) 2018-2019 ArSysOp
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* ArSysOp - initial API and implementation
*******************************************************************************/
package org.eclipse.passage.lic.registry;
public interface UserDescriptor extends Identified {
String getEmail();
String getFullName();
String getDescription();
UserOriginDescriptor getUserOrigin();
}
|
9245dd2d099a8b5b3fdea792d3d8dcaab1c9f4db | 941 | java | Java | Game/src/main/java/com/github/jolice/game/listener/dropout/TeamDropOutListener.java | TrashToggled/MinecraftNetwork | 3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7 | [
"MIT"
] | 41 | 2020-06-13T19:25:06.000Z | 2022-03-08T00:03:09.000Z | Game/src/main/java/com/github/jolice/game/listener/dropout/TeamDropOutListener.java | TrashToggled/MinecraftNetwork | 3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7 | [
"MIT"
] | 1 | 2020-12-23T14:47:50.000Z | 2020-12-23T14:47:50.000Z | Game/src/main/java/com/github/jolice/game/listener/dropout/TeamDropOutListener.java | TrashToggled/MinecraftNetwork | 3e2dd390e3fbcf72b908afb03fc144dfaee3a5a7 | [
"MIT"
] | 5 | 2020-06-30T10:03:07.000Z | 2022-03-06T19:54:06.000Z | 32.448276 | 77 | 0.738576 | 1,003,547 | package com.github.jolice.game.listener.dropout;
import com.github.jolice.game.team.repository.Teams;
import com.github.jolice.game.core.Game;
import com.github.jolice.game.player.repository.GamePlayerStorage;
import com.github.jolice.game.player.team.TeamPlayer;
import lombok.RequiredArgsConstructor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.github.jolice.game.event.PlayerDropOutEvent;
@RequiredArgsConstructor
public class TeamDropOutListener implements Listener {
private final Game game;
private final Teams teams;
private final GamePlayerStorage<TeamPlayer> teamPlayerStorage;
@EventHandler
public void onDropOut(PlayerDropOutEvent event) {
TeamPlayer player = teamPlayerStorage.getPlayer(event.getPlayerId());
if (!player.getTeam().isAlive()) {
if (teams.getAliveTeams() == 1) {
game.end();
}
}
}
}
|
9245dde26d246314adbe4c01edc86536622a3348 | 3,996 | java | Java | quickstart-eureka/src/main/java/org/quickstart/netflix/eureka/sample/SampleEurekaService.java | youngzil/quickstart-netflix | 437af76cf8b904697666eab53a1c25307704cda8 | [
"Apache-2.0"
] | null | null | null | quickstart-eureka/src/main/java/org/quickstart/netflix/eureka/sample/SampleEurekaService.java | youngzil/quickstart-netflix | 437af76cf8b904697666eab53a1c25307704cda8 | [
"Apache-2.0"
] | 7 | 2020-06-30T23:24:00.000Z | 2022-02-01T01:00:20.000Z | quickstart-eureka/src/main/java/org/quickstart/netflix/eureka/sample/SampleEurekaService.java | youngzil/quickstart-netflix | 437af76cf8b904697666eab53a1c25307704cda8 | [
"Apache-2.0"
] | null | null | null | 33.630252 | 128 | 0.645177 | 1,003,548 | /**
* 项目名称:quickstart-netflix-eureka
* 文件名:SampleEurekaService.java
* 版本信息:
* 日期:2018年5月19日
* Copyright yangzl Corporation 2018
* 版权所有 *
*/
package org.quickstart.netflix.eureka.sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryManager;
/**
* SampleEurekaService
*
* @[email protected]
* @2018年5月19日 下午4:10:14
* @since 1.0
*/
public class SampleEurekaService {
private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance();
private static final Logger logger = LoggerFactory.getLogger(SampleEurekaService.class);
@SuppressWarnings("deprecation")
public void registerWithEureka() {
// Register with Eureka
DiscoveryManager.getInstance().initComponent(new MyDataCenterInstanceConfig(), new DefaultEurekaClientConfig());
ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP);
String vipAddress = configInstance.getStringProperty("eureka.vipAddress", "sampleservice.mydomain.net").get();
InstanceInfo nextServerInfo = null;
while (nextServerInfo == null) {
try {
nextServerInfo = DiscoveryManager.getInstance().getDiscoveryClient().getNextServerFromEureka(vipAddress, false);
} catch (Throwable e) {
System.out.println("Waiting for service to register with eureka..");
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
System.out.println("Service started and ready to process requests..");
try {
ServerSocket serverSocket = new ServerSocket(configInstance.getIntProperty("eureka.port", 8010).get());
final Socket s = serverSocket.accept();
System.out.println("Client got connected..Processing request from the client");
processRequest(s);
} catch (IOException e) {
e.printStackTrace();
}
this.unRegisterWithEureka();
System.out.println("Shutting down server.Demo over.");
}
public void unRegisterWithEureka() {
// Un register from eureka.
DiscoveryManager.getInstance().shutdownComponent();
}
private void processRequest(final Socket s) {
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = rd.readLine();
if (line != null) {
System.out.println("Received the request from the client.");
}
PrintStream out = new PrintStream(s.getOutputStream());
System.out.println("Sending the response to the client...");
out.println("Reponse at " + new Date());
} catch (Throwable e) {
System.err.println("Error processing requests");
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
SampleEurekaService sampleEurekaService = new SampleEurekaService();
sampleEurekaService.registerWithEureka();
}
}
|
9245de0b8166154bdfeee36ba6cde8c73495c03c | 2,811 | java | Java | dcwlt-modules/dcwlt-pay-batch/src/main/java/com/dcits/dcwlt/pay/batch/service/impl/CheckResultServiceImpl.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | null | null | null | dcwlt-modules/dcwlt-pay-batch/src/main/java/com/dcits/dcwlt/pay/batch/service/impl/CheckResultServiceImpl.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | null | null | null | dcwlt-modules/dcwlt-pay-batch/src/main/java/com/dcits/dcwlt/pay/batch/service/impl/CheckResultServiceImpl.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | 1 | 2022-03-01T08:24:59.000Z | 2022-03-01T08:24:59.000Z | 28.11 | 149 | 0.693348 | 1,003,549 | package com.dcits.dcwlt.pay.batch.service.impl;
import com.dcits.dcwlt.pay.api.domain.dcep.check.CheckWrongQueryResDTO;
import com.dcits.dcwlt.pay.api.model.CheckResultDO;
import com.dcits.dcwlt.pay.batch.mapper.SettleCheckResultMapper;
import com.dcits.dcwlt.pay.batch.service.ICheckResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CheckResultServiceImpl implements ICheckResultService {
@Autowired
private SettleCheckResultMapper settleCheckResultMapper;
/**
* 插入数据
* @return
*/
@Override
public int insert(CheckResultDO checkResultDO) {
return settleCheckResultMapper.insert( checkResultDO);
}
/**
* 批量插入数据
* @param list
* @return
*/
@Override
public int insertByBatch(List<CheckResultDO> list) {
return settleCheckResultMapper.insertByBatch( list);
}
/**
* 查询数据
* @param payDate
* @param paySerno
* @return
*/
@Override
public CheckResultDO select(String payDate, String paySerno) {
return settleCheckResultMapper.selectCheckResult(payDate, paySerno);
}
/**
* 查询需要处理的对账结果表
* @param batchId
* @return
*/
@Override
public List<CheckResultDO> selectCheckResultByStatus(String payDate, String batchId) {
return settleCheckResultMapper.selectCheckResultByStatus(payDate,batchId);
}
/**
* 对账不平记录查询
* @param payDate --平台日期, 必输
* @param batchId --交易批次号, 可选
* @param msgType --报文编号, 可选
* @param checkStatus --对账标识, 可选
* @param procStatus --差错处理状态, 可选
* @param msgId --报文标识号, 可选 翻页时必填
* @param count --查询条数, 必输
* @param queryPageFlag --上下翻页操作, 必输, 0首页; 1上翻; 2下翻 只按升序排序
* @return
*/
@Override
public List<CheckWrongQueryResDTO> selectWrongMatchCheckResult(String payDate, String batchId, String msgType,
String checkStatus, String procStatus, String msgId, int count, int queryPageFlag, String queryPageKey) {
// Map<String, Object> map = new HashMap<>();
// map.put("payDate( payDate);
// map.put("batchId( batchId);
// map.put("msgType( msgType);
// map.put("checkStatus( checkStatus);
// map.put("procStatus( procStatus);
// map.put("msgId( msgId);
// map.put("count( count);
// map.put("queryPageFlag( queryPageFlag);
// map.put("queryPageKey( queryPageKey);
return settleCheckResultMapper.selectWrongMatchCheckResult(payDate,batchId,msgType,checkStatus,procStatus,msgId,count,queryPageFlag,queryPageKey
);
}
/**
* 对账状态更新
* @param checkResultDO
* @return
*/
@Override
public int update(CheckResultDO checkResultDO) {
return settleCheckResultMapper.updateCheckResult(checkResultDO);
}
}
|
9245de9017d28fa50372577eb7a90f630a1268ac | 2,023 | java | Java | src/self/learning/interview/coding/RobotMovement.java | rajkumardubey/MyInterviewChecklist | b721d2ee4e6915aaf8c9afd73fd68cfa5230acac | [
"Unlicense"
] | 2 | 2021-06-16T20:38:04.000Z | 2022-02-17T21:21:47.000Z | src/self/learning/interview/coding/RobotMovement.java | rajkumardubey/MyInterviewChecklist | b721d2ee4e6915aaf8c9afd73fd68cfa5230acac | [
"Unlicense"
] | null | null | null | src/self/learning/interview/coding/RobotMovement.java | rajkumardubey/MyInterviewChecklist | b721d2ee4e6915aaf8c9afd73fd68cfa5230acac | [
"Unlicense"
] | 2 | 2021-05-13T12:52:14.000Z | 2022-02-17T21:21:32.000Z | 24.670732 | 83 | 0.44439 | 1,003,550 | package self.learning.interview.coding;
import java.util.Arrays;
public class RobotMovement {
// your code
private static Integer[] walk(String path) {
int r = 0, c = 0;
for (Character ch : path.toUpperCase().toCharArray()) {
switch (ch) {
case 'U':
c++;
break;
case 'D':
c--;
break;
case 'L':
r--;
break;
case 'R':
r++;
break;
}
// System.out.println(String.format("ch: %s, r: %s, c: %s", ch, r, c));
}
return new Integer[]{r, c};
}
public static boolean isEqual(Integer[] a, Integer[] b) {
return Arrays.equals(a, b);
}
public static boolean pass() {
boolean res = true;
{
String test = "UUU";
Integer[] result = walk(test);
System.out.println(Arrays.toString(result));
res &= isEqual(result, new Integer[]{0, 3});
}
{
String test = "ULDR";
Integer[] result = walk(test);
System.out.println(Arrays.toString(result));
res &= isEqual(result, new Integer[]{0, 0});
}
{
String test = "ULLLDUDUUR";
Integer[] result = walk(test);
System.out.println(Arrays.toString(result));
res &= isEqual(result, new Integer[]{-2, 2});
}
{
String test = "UP LEFT 2xDOWN DOWN RIGHT RIGHT UP UP";
Integer[] result = walk(test);
System.out.println(Arrays.toString(result));
res &= isEqual(result, new Integer[]{1, 1});
}
return res;
}
public static void main(String[] args) {
if (pass()) {
System.out.println("{Pass");
} else {
System.out.println("Test failures");
}
}
}
|
9245e14d8955545d097bf853a6c056db384bdc6d | 4,329 | java | Java | datax-core/src/main/java/com/wugui/datatx/core/util/JSONUtils.java | luwu1991/datax-web | 76013358a4a90b5bb53adc7a2e18ae0577694a82 | [
"MIT"
] | null | null | null | datax-core/src/main/java/com/wugui/datatx/core/util/JSONUtils.java | luwu1991/datax-web | 76013358a4a90b5bb53adc7a2e18ae0577694a82 | [
"MIT"
] | 1 | 2020-03-10T08:47:07.000Z | 2020-03-10T08:47:07.000Z | datax-core/src/main/java/com/wugui/datatx/core/util/JSONUtils.java | waterWang/datax-web | 035d7d249340a5e45a7940ec982696ba1655f923 | [
"MIT"
] | null | null | null | 26.396341 | 102 | 0.57958 | 1,003,551 | package com.wugui.datatx.core.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* json utils
*/
public class JSONUtils {
private static final Logger logger = LoggerFactory.getLogger(JSONUtils.class);
/**
* json representation of object
* @param object object
* @return object to json string
*/
public static String toJson(Object object) {
try{
return JSON.toJSONString(object,false);
} catch (Exception e) {
logger.error("object to json exception!",e);
}
return null;
}
/**
*
* This method deserializes the specified Json into an object of the specified class. It is not
* suitable to use if the specified class is a generic type since it will not have the generic
* type information because of the Type Erasure feature of Java. Therefore, this method should not
* be used if the desired type is a generic type. Note that this method works fine if the any of
* the fields of the specified object are generics, just the object itself should not be a
* generic type.
*
* @param json the string from which the object is to be deserialized
* @param clazz the class of T
* @param <T> T
* @return an object of type T from the string
* classOfT
*/
public static <T> T parseObject(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json, clazz);
} catch (Exception e) {
logger.error("parse object exception!",e);
}
return null;
}
/**
* json to list
*
* @param json json string
* @param clazz class
* @param <T> T
* @return list
*/
public static <T> List<T> toList(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return new ArrayList<>();
}
try {
return JSONArray.parseArray(json, clazz);
} catch (Exception e) {
logger.error("JSONArray.parseArray exception!",e);
}
return new ArrayList<>();
}
/**
* json to map
*
* {@link #toMap(String, Class, Class)}
*
* @param json json
* @return json to map
*/
public static Map<String, String> toMap(String json) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json, new TypeReference<HashMap<String, String>>(){});
} catch (Exception e) {
logger.error("json to map exception!",e);
}
return null;
}
/**
*
* json to map
*
* @param json json
* @param classK classK
* @param classV classV
* @param <K> K
* @param <V> V
* @return to map
*/
public static <K, V> Map<K, V> toMap(String json, Class<K> classK, Class<V> classV) {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return JSON.parseObject(json, new TypeReference<HashMap<K, V>>() {});
} catch (Exception e) {
logger.error("json to map exception!",e);
}
return null;
}
/**
* object to json string
* @param object object
* @return json string
*/
public static String toJsonString(Object object) {
try{
return JSON.toJSONString(object,false);
} catch (Exception e) {
throw new RuntimeException("Object json deserialization exception.", e);
}
}
public static JSONObject parseObject(String text) {
try{
return JSON.parseObject(text);
} catch (Exception e) {
throw new RuntimeException("String json deserialization exception.", e);
}
}
public static JSONArray parseArray(String text) {
try{
return JSON.parseArray(text);
} catch (Exception e) {
throw new RuntimeException("Json deserialization exception.", e);
}
}
}
|
9245e253f92336fa795a659c484ca31deabac9c1 | 2,624 | java | Java | src/main/java/pl/touk/chat/bot/janusz/commands/cmdfucommand/CMDFuCommand.java | TouK/janusz | 4ebd72df7e5e5f27103fcef903ed68eeec140cb2 | [
"Apache-2.0"
] | 10 | 2015-01-30T09:40:08.000Z | 2016-04-08T13:28:35.000Z | src/main/java/pl/touk/chat/bot/janusz/commands/cmdfucommand/CMDFuCommand.java | TouK/janusz | 4ebd72df7e5e5f27103fcef903ed68eeec140cb2 | [
"Apache-2.0"
] | null | null | null | src/main/java/pl/touk/chat/bot/janusz/commands/cmdfucommand/CMDFuCommand.java | TouK/janusz | 4ebd72df7e5e5f27103fcef903ed68eeec140cb2 | [
"Apache-2.0"
] | 2 | 2015-02-06T09:07:23.000Z | 2016-01-29T15:05:05.000Z | 33.21519 | 135 | 0.655869 | 1,003,552 | package pl.touk.chat.bot.janusz.commands.cmdfucommand;
import com.google.common.base.Joiner;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.touk.chat.bot.janusz.commands.JanuszCommand;
import java.util.Base64;
import java.util.List;
public class CMDFuCommand implements JanuszCommand {
public static final String CMDFU_API_PATH = "http://www.commandlinefu.com/commands";
public static final String HELP_MESSAGE = "Zagnij devopsa komendą";
public static final String ERROR_MESSAGE = "Przepraszam, zachowałem się jak gówniarz";
Logger log = LoggerFactory.getLogger(CMDFuCommand.class);
@Override
public String invoke(String sender, List<String> words) {
String question = buildCommand(words);
if (isCommandEmpty(question)) {
return HELP_MESSAGE;
}
try {
return askCMDFu(question);
} catch (Exception e) {
log.error(e.getMessage());
}
return ERROR_MESSAGE;
}
private boolean isCommandEmpty(String question) {
return question == null || "".equals(question);
}
private String buildCommand(List<String> params) {
return Joiner.on(",").join(params);
}
private String askCMDFu(String question) throws UnirestException {
try {
return retriveFromCMDFu(question);
} catch (UnirestException e) {
log.error("Przepraszam, zachowałem się jak gówniarz {}", e.getMessage());
e.printStackTrace();
throw e;
}
}
private String retriveFromCMDFu(String question) throws UnirestException {
HttpResponse<JsonNode> cmdfuResponse = Unirest.get(CMDFU_API_PATH + "//matching/{search}/{b64_search}/bys=/sort-by-votes/json")
.routeParam("search", question)
.routeParam("b64_search", new String(Base64.getEncoder().encode(question.getBytes())))
.asJson();
System.out.println("cmdfuResponse = " + cmdfuResponse);
log.info("Command for {}", question);
log.info("CMDFu response: {}", cmdfuResponse.getBody().toString());
String response = "";
for (int i = 0; i < 3; i++) {
response += cmdfuResponse.getBody().getArray().getJSONObject(i).get("command").toString()+"\n";
}
log.info("Got commands {}", response);
return response;
}
}
|
9245e29df4d1a21d50948d42d92531496a4b7ab4 | 1,907 | java | Java | frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/service/account/impl/FrostmourneSpiAccountService.java | xyzj91/frostmourne-1 | d66da4e0a6c17b7e0eee910c2c3950a0ef0c6b79 | [
"MIT"
] | 1 | 2020-07-17T08:31:25.000Z | 2020-07-17T08:31:25.000Z | frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/service/account/impl/FrostmourneSpiAccountService.java | xyzj91/frostmourne-1 | d66da4e0a6c17b7e0eee910c2c3950a0ef0c6b79 | [
"MIT"
] | null | null | null | frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/service/account/impl/FrostmourneSpiAccountService.java | xyzj91/frostmourne-1 | d66da4e0a6c17b7e0eee910c2c3950a0ef0c6b79 | [
"MIT"
] | null | null | null | 36.673077 | 118 | 0.738857 | 1,003,553 | package com.autohome.frostmourne.monitor.service.account.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import com.autohome.frostmourne.core.contract.Protocol;
import com.autohome.frostmourne.core.jackson.JacksonUtil;
import com.autohome.frostmourne.monitor.contract.Consts;
import com.autohome.frostmourne.monitor.service.account.IAccountService;
import com.autohome.frostmourne.spi.starter.api.IFrostmourneSpiApi;
import com.autohome.frostmourne.spi.starter.model.AccountInfo;
import com.autohome.frostmourne.spi.starter.model.Team;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class FrostmourneSpiAccountService implements IAccountService {
private final static Logger LOGGER = LoggerFactory.getLogger(FrostmourneSpiAccountService.class);
@Resource
private IFrostmourneSpiApi frostmourneSpiApi;
@Override
public AccountInfo findByAccount(String account) {
return frostmourneSpiApi.findByAccount(Consts.APP_ID, account).getResult();
}
@Override
public List<Team> teams(String department) {
Protocol<List<Team>> protocol = frostmourneSpiApi.teams(Consts.APP_ID, department);
if (protocol.getReturncode() != 0) {
LOGGER.error("error when spi teams, response: {}", JacksonUtil.serialize(protocol));
return new ArrayList<>();
}
return protocol.getResult();
}
@Override
public List<AccountInfo> search(String keyword) {
Protocol<List<AccountInfo>> protocol = frostmourneSpiApi.search(Consts.APP_ID, keyword);
if (protocol.getReturncode() != 0) {
LOGGER.error("error when spi search keyword: {}, response: {}", keyword, JacksonUtil.serialize(protocol));
return new ArrayList<>();
}
return protocol.getResult();
}
}
|
9245e2c8aaf3312f839c984154e1a6a2d7195432 | 473 | java | Java | src/test/java/com/sid/leetcode/problem/array/JumpGameIITest.java | rencht/LeetCode | b791c39858784273a9f66a0b0326f8e721ba4c1d | [
"MIT"
] | null | null | null | src/test/java/com/sid/leetcode/problem/array/JumpGameIITest.java | rencht/LeetCode | b791c39858784273a9f66a0b0326f8e721ba4c1d | [
"MIT"
] | null | null | null | src/test/java/com/sid/leetcode/problem/array/JumpGameIITest.java | rencht/LeetCode | b791c39858784273a9f66a0b0326f8e721ba4c1d | [
"MIT"
] | null | null | null | 18.92 | 62 | 0.693446 | 1,003,554 | package com.sid.leetcode.problem.array;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.sid.leetcode.problem.array.JumpGameII;
public class JumpGameIITest {
private JumpGameII problem;
@Before
public void setUp() throws Exception {
problem = new JumpGameII();
}
@Test
public void testJump() throws Exception {
assertEquals(2, problem.jump(new int[] { 2, 3, 1, 1, 4 }));
}
}
|
9245e2ea3a8a5924a849404d909a4cc8a00565d8 | 1,956 | java | Java | src/main/java/net/wissel/vertx/proxy/filters/TextSubFilter.java | Stwissel/SampleProxy | 2ad190b4b776bda19ab4a2715a26a3ef26b339be | [
"Apache-2.0"
] | 1 | 2022-03-17T02:03:59.000Z | 2022-03-17T02:03:59.000Z | src/main/java/net/wissel/vertx/proxy/filters/TextSubFilter.java | Stwissel/SampleProxy | 2ad190b4b776bda19ab4a2715a26a3ef26b339be | [
"Apache-2.0"
] | 1 | 2018-12-11T15:59:13.000Z | 2018-12-11T15:59:27.000Z | src/main/java/net/wissel/vertx/proxy/filters/TextSubFilter.java | Stwissel/SampleProxy | 2ad190b4b776bda19ab4a2715a26a3ef26b339be | [
"Apache-2.0"
] | null | null | null | 46.690476 | 79 | 0.390107 | 1,003,555 | /** ========================================================================= *
* Copyright (C) 2017, 2018 Salesforce Inc ( http://www.salesforce.com/ *
* All rights reserved. *
* *
* @author Stephan H. Wissel (stw) <[email protected]> *
* @notessensei *
* @version 1.0 *
* ========================================================================== *
* *
* 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.wissel.vertx.proxy.filters;
/**
* Interface for filters that operate on HTML documents
*
* @author swissel
*
*/
public interface TextSubFilter {
/**
* Manipulates a text String
*
* @param text
* the String to fix
* @return the altered String
*/
public String apply(final String text);
}
|
9245e3e2eb2bc6171fcace026a7906d811971490 | 1,957 | java | Java | sdk/android/api/org/webrtc/MediaSource.java | jackz314/knock-webrtc | f1a9d40f3d2c26d6c587e52d07007f37503c45ad | [
"BSD-3-Clause"
] | 344 | 2016-07-03T11:45:20.000Z | 2022-03-19T16:54:10.000Z | sdk/android/api/org/webrtc/MediaSource.java | jackz314/knock-webrtc | f1a9d40f3d2c26d6c587e52d07007f37503c45ad | [
"BSD-3-Clause"
] | 59 | 2020-08-24T09:17:42.000Z | 2022-02-27T23:33:37.000Z | sdk/android/api/org/webrtc/MediaSource.java | jackz314/knock-webrtc | f1a9d40f3d2c26d6c587e52d07007f37503c45ad | [
"BSD-3-Clause"
] | 278 | 2016-04-26T07:37:12.000Z | 2022-01-24T10:09:44.000Z | 26.093333 | 93 | 0.692897 | 1,003,556 | /*
* Copyright 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
/** Java wrapper for a C++ MediaSourceInterface. */
public class MediaSource {
/** Tracks MediaSourceInterface.SourceState */
public enum State {
INITIALIZING,
LIVE,
ENDED,
MUTED;
@CalledByNative("State")
static State fromNativeIndex(int nativeIndex) {
return values()[nativeIndex];
}
}
private final RefCountDelegate refCountDelegate;
private long nativeSource;
public MediaSource(long nativeSource) {
refCountDelegate = new RefCountDelegate(() -> JniCommon.nativeReleaseRef(nativeSource));
this.nativeSource = nativeSource;
}
public State state() {
checkMediaSourceExists();
return nativeGetState(nativeSource);
}
public void dispose() {
checkMediaSourceExists();
refCountDelegate.release();
nativeSource = 0;
}
/** Returns a pointer to webrtc::MediaSourceInterface. */
protected long getNativeMediaSource() {
checkMediaSourceExists();
return nativeSource;
}
/**
* Runs code in {@code runnable} holding a reference to the media source. If the object has
* already been released, does nothing.
*/
void runWithReference(Runnable runnable) {
if (refCountDelegate.safeRetain()) {
try {
runnable.run();
} finally {
refCountDelegate.release();
}
}
}
private void checkMediaSourceExists() {
if (nativeSource == 0) {
throw new IllegalStateException("MediaSource has been disposed.");
}
}
private static native State nativeGetState(long pointer);
}
|
9245e3eea0b9b07ad5f7bec5437b6e1c8d1e5a26 | 259 | java | Java | mall-product/src/main/java/com/lyd/mall/product/vo/AttrValueWithSkuIdVo.java | SexyJava/mall | 14b8c7f2d2df6224fb210d21b769cf2de39cc826 | [
"Apache-2.0"
] | 1 | 2021-01-26T15:48:02.000Z | 2021-01-26T15:48:02.000Z | mall-product/src/main/java/com/lyd/mall/product/vo/AttrValueWithSkuIdVo.java | SexyJava/mall | 14b8c7f2d2df6224fb210d21b769cf2de39cc826 | [
"Apache-2.0"
] | null | null | null | mall-product/src/main/java/com/lyd/mall/product/vo/AttrValueWithSkuIdVo.java | SexyJava/mall | 14b8c7f2d2df6224fb210d21b769cf2de39cc826 | [
"Apache-2.0"
] | null | null | null | 16.1875 | 35 | 0.702703 | 1,003,557 | package com.lyd.mall.product.vo;
import lombok.Data;
/**
* @Author Liuyunda
* @Date 2021/5/12 20:59
* @Email [email protected]
* @Description: TODO
*/
@Data
public class AttrValueWithSkuIdVo {
private String attrValue;
private String skuIds;
}
|
9245e4da4459aa56f1b3a940fb822a3ee33fd102 | 1,763 | java | Java | src/test/java/pl/gov/coi/pomocua/ads/materialaid/MaterialAidTestDataGenerator.java | sfc-gh-pnescior/pomocua-ogloszenia | 60d00ebf6489f036e8b86a3d63288a0652a9e894 | [
"MIT"
] | 17 | 2022-03-03T15:22:47.000Z | 2022-03-21T22:41:06.000Z | src/test/java/pl/gov/coi/pomocua/ads/materialaid/MaterialAidTestDataGenerator.java | sfc-gh-pnescior/pomocua-ogloszenia | 60d00ebf6489f036e8b86a3d63288a0652a9e894 | [
"MIT"
] | 16 | 2022-03-04T07:21:13.000Z | 2022-03-31T09:27:36.000Z | src/test/java/pl/gov/coi/pomocua/ads/materialaid/MaterialAidTestDataGenerator.java | sfc-gh-pnescior/pomocua-ogloszenia | 60d00ebf6489f036e8b86a3d63288a0652a9e894 | [
"MIT"
] | 24 | 2022-03-03T11:29:17.000Z | 2022-03-24T08:48:18.000Z | 39.177778 | 103 | 0.675553 | 1,003,558 | package pl.gov.coi.pomocua.ads.materialaid;
import lombok.Builder;
import pl.gov.coi.pomocua.ads.Location;
import java.util.Optional;
public class MaterialAidTestDataGenerator {
public static MaterialAidOfferBuilder aMaterialAidOffer() {
return MaterialAidTestDataGenerator.builder()
.title("sample work")
.category(MaterialAidCategory.CLOTHING)
.location(new Location("Mazowieckie", "Warszawa"))
.description("description")
.phoneNumber("+48123456789");
}
public static MaterialAidOfferDefinitionDTO sampleUpdateJson() {
var updateJson = new MaterialAidOfferDefinitionDTO();
updateJson.title = "new title";
updateJson.description = "new description";
updateJson.location = new Location("Pomorskie", "Gdańsk");
updateJson.category = MaterialAidCategory.FOR_CHILDREN;
updateJson.phoneNumber = "+48123456780";
return updateJson;
}
@Builder
private static MaterialAidOffer materialAidOfferBuilder(
String title,
String description,
MaterialAidCategory category,
Location location,
String phoneNumber
) {
MaterialAidOffer offer = new MaterialAidOffer();
offer.title = Optional.ofNullable(title).orElse("some title");
offer.description = Optional.ofNullable(description).orElse("some description");
offer.category = Optional.ofNullable(category).orElse(MaterialAidCategory.FOOD);
offer.location = Optional.ofNullable(location).orElse(new Location("mazowieckie", "warszawa"));
offer.phoneNumber = Optional.ofNullable(phoneNumber).orElse("+48123456789");
return offer;
}
}
|
9245e588b97bf00970b37d04465d9effee1353fe | 4,044 | java | Java | services/src/main/java/org/keycloak/protocol/oidc/representations/OIDCConfigurationRepresentation.java | matzew/keycloak | 0095968a739e51aea1b298e79fbf9805642be197 | [
"Apache-2.0"
] | null | null | null | services/src/main/java/org/keycloak/protocol/oidc/representations/OIDCConfigurationRepresentation.java | matzew/keycloak | 0095968a739e51aea1b298e79fbf9805642be197 | [
"Apache-2.0"
] | null | null | null | services/src/main/java/org/keycloak/protocol/oidc/representations/OIDCConfigurationRepresentation.java | matzew/keycloak | 0095968a739e51aea1b298e79fbf9805642be197 | [
"Apache-2.0"
] | null | null | null | 26.618421 | 100 | 0.724913 | 1,003,559 | package org.keycloak.protocol.oidc.representations;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Stian Thorgersen</a>
*/
public class OIDCConfigurationRepresentation {
@JsonProperty("issuer")
private String issuer;
@JsonProperty("authorization_endpoint")
private String authorizationEndpoint;
@JsonProperty("token_endpoint")
private String tokenEndpoint;
@JsonProperty("userinfo_endpoint")
private String userinfoEndpoint;
@JsonProperty("end_session_endpoint")
private String logoutEndpoint;
@JsonProperty("jwks_uri")
private String jwksUri;
@JsonProperty("grant_types_supported")
private List<String> grantTypesSupported;
@JsonProperty("response_types_supported")
private List<String> responseTypesSupported;
@JsonProperty("subject_types_supported")
private List<String> subjectTypesSupported;
@JsonProperty("id_token_signing_alg_values_supported")
private List<String> idTokenSigningAlgValuesSupported;
@JsonProperty("response_modes_supported")
private List<String> responseModesSupported;
protected Map<String, Object> otherClaims = new HashMap<String, Object>();
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public String getAuthorizationEndpoint() {
return authorizationEndpoint;
}
public void setAuthorizationEndpoint(String authorizationEndpoint) {
this.authorizationEndpoint = authorizationEndpoint;
}
public String getTokenEndpoint() {
return tokenEndpoint;
}
public void setTokenEndpoint(String tokenEndpoint) {
this.tokenEndpoint = tokenEndpoint;
}
public String getUserinfoEndpoint() {
return userinfoEndpoint;
}
public void setUserinfoEndpoint(String userinfoEndpoint) {
this.userinfoEndpoint = userinfoEndpoint;
}
public String getJwksUri() {
return jwksUri;
}
public void setJwksUri(String jwksUri) {
this.jwksUri = jwksUri;
}
public String getLogoutEndpoint() {
return logoutEndpoint;
}
public void setLogoutEndpoint(String logoutEndpoint) {
this.logoutEndpoint = logoutEndpoint;
}
public List<String> getGrantTypesSupported() {
return grantTypesSupported;
}
public void setGrantTypesSupported(List<String> grantTypesSupported) {
this.grantTypesSupported = grantTypesSupported;
}
public List<String> getResponseTypesSupported() {
return responseTypesSupported;
}
public void setResponseTypesSupported(List<String> responseTypesSupported) {
this.responseTypesSupported = responseTypesSupported;
}
public List<String> getSubjectTypesSupported() {
return subjectTypesSupported;
}
public void setSubjectTypesSupported(List<String> subjectTypesSupported) {
this.subjectTypesSupported = subjectTypesSupported;
}
public List<String> getIdTokenSigningAlgValuesSupported() {
return idTokenSigningAlgValuesSupported;
}
public void setIdTokenSigningAlgValuesSupported(List<String> idTokenSigningAlgValuesSupported) {
this.idTokenSigningAlgValuesSupported = idTokenSigningAlgValuesSupported;
}
public List<String> getResponseModesSupported() {
return responseModesSupported;
}
public void setResponseModesSupported(List<String> responseModesSupported) {
this.responseModesSupported = responseModesSupported;
}
@JsonAnyGetter
public Map<String, Object> getOtherClaims() {
return otherClaims;
}
@JsonAnySetter
public void setOtherClaims(String name, Object value) {
otherClaims.put(name, value);
}
}
|
9245e64133428514a9e1fecb678627383c619f88 | 9,872 | java | Java | src/rapaio/graphics/opt/NamedColors.java | padreati/rapaio | 9fe8f53c4821bdb106875b7c875a2ff2e0d747ff | [
"Apache-2.0"
] | 82 | 2015-01-07T15:01:27.000Z | 2022-03-22T16:40:22.000Z | src/rapaio/graphics/opt/NamedColors.java | padreati/rapaio | 9fe8f53c4821bdb106875b7c875a2ff2e0d747ff | [
"Apache-2.0"
] | 198 | 2015-02-13T08:05:55.000Z | 2022-03-24T04:57:19.000Z | src/rapaio/graphics/opt/NamedColors.java | padreati/rapaio | 9fe8f53c4821bdb106875b7c875a2ff2e0d747ff | [
"Apache-2.0"
] | 26 | 2015-01-20T14:31:01.000Z | 2022-03-21T23:40:32.000Z | 43.113537 | 83 | 0.609744 | 1,003,560 | /*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright 2013 - 2021 Aurelian Tutuianu
*
* 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 rapaio.graphics.opt;
import java.awt.Color;
import java.util.HashMap;
/**
* Created by <a href="mailto:[email protected]">Aurelian Tutuianu</a> on 6/27/21.
*/
public class NamedColors {
private static NamedColors instance;
public static NamedColors getInstance() {
if (instance == null) {
instance = new NamedColors();
}
return instance;
}
private final HashMap<String, Color> map = new HashMap<>();
private NamedColors() {
// base colors
map.put("b", new Color(0f, 0f, 1f));
map.put("g", new Color(0f, 0.5f, 0f));
map.put("r", new Color(1f, 0f, 0f));
map.put("c", new Color(0f, 0.75f, 0.75f));
map.put("m", new Color(0.75f, 0f, 0.75f));
map.put("y", new Color(0.75f, 0.75f, 0f));
map.put("k", new Color(0f, 0f, 0f));
map.put("w", new Color(1f, 1f, 1f));
// tableau colors
map.put("tab:blue", new Color(0x1f77b4));
map.put("tab:orange", new Color(0xff7f0e));
map.put("tab:green", new Color(0x2ca02c));
map.put("tab:red", new Color(0xd62728));
map.put("tab:purple", new Color(0x9467bd));
map.put("tab:brown", new Color(0x8c564b));
map.put("tab:pink", new Color(0xe377c2));
map.put("tab:gray", new Color(0x7f7f7f));
map.put("tab:olive", new Color(0xbcbd22));
map.put("tab:cyan", new Color(0x17becf));
// CSS4 COLOURS
map.put("aliceblue", new Color(0xF0F8FF));
map.put("antiquewhite", new Color(0xFAEBD7));
map.put("aqua", new Color(0x00FFFF));
map.put("aquamarine", new Color(0x7FFFD4));
map.put("azure", new Color(0xF0FFFF));
map.put("beige", new Color(0xF5F5DC));
map.put("bisque", new Color(0xFFE4C4));
map.put("black", new Color(0x000000));
map.put("blanchedalmond", new Color(0xFFEBCD));
map.put("blue", new Color(0x0000FF));
map.put("blueviolet", new Color(0x8A2BE2));
map.put("brown", new Color(0xA52A2A));
map.put("burlywood", new Color(0xDEB887));
map.put("cadetblue", new Color(0x5F9EA0));
map.put("chartreuse", new Color(0x7FFF00));
map.put("chocolate", new Color(0xD2691E));
map.put("coral", new Color(0xFF7F50));
map.put("cornflowerblue", new Color(0x6495ED));
map.put("cornsilk", new Color(0xFFF8DC));
map.put("crimson", new Color(0xDC143C));
map.put("cyan", new Color(0x00FFFF));
map.put("darkblue", new Color(0x00008B));
map.put("darkcyan", new Color(0x008B8B));
map.put("darkgoldenrod", new Color(0xB8860B));
map.put("darkgray", new Color(0xA9A9A9));
map.put("darkgreen", new Color(0x006400));
map.put("darkgrey", new Color(0xA9A9A9));
map.put("darkkhaki", new Color(0xBDB76B));
map.put("darkmagenta", new Color(0x8B008B));
map.put("darkolivegreen", new Color(0x556B2F));
map.put("darkorange", new Color(0xFF8C00));
map.put("darkorchid", new Color(0x9932CC));
map.put("darkred", new Color(0x8B0000));
map.put("darksalmon", new Color(0xE9967A));
map.put("darkseagreen", new Color(0x8FBC8F));
map.put("darkslateblue", new Color(0x483D8B));
map.put("darkslategray", new Color(0x2F4F4F));
map.put("darkslategrey", new Color(0x2F4F4F));
map.put("darkturquoise", new Color(0x00CED1));
map.put("darkviolet", new Color(0x9400D3));
map.put("deeppink", new Color(0xFF1493));
map.put("deepskyblue", new Color(0x00BFFF));
map.put("dimgray", new Color(0x696969));
map.put("dimgrey", new Color(0x696969));
map.put("dodgerblue", new Color(0x1E90FF));
map.put("firebrick", new Color(0xB22222));
map.put("floralwhite", new Color(0xFFFAF0));
map.put("forestgreen", new Color(0x228B22));
map.put("fuchsia", new Color(0xFF00FF));
map.put("gainsboro", new Color(0xDCDCDC));
map.put("ghostwhite", new Color(0xF8F8FF));
map.put("gold", new Color(0xFFD700));
map.put("goldenrod", new Color(0xDAA520));
map.put("gray", new Color(0x808080));
map.put("green", new Color(0x008000));
map.put("greenyellow", new Color(0xADFF2F));
map.put("grey", new Color(0x808080));
map.put("honeydew", new Color(0xF0FFF0));
map.put("hotpink", new Color(0xFF69B4));
map.put("indianred", new Color(0xCD5C5C));
map.put("indigo", new Color(0x4B0082));
map.put("ivory", new Color(0xFFFFF0));
map.put("khaki", new Color(0xF0E68C));
map.put("lavender", new Color(0xE6E6FA));
map.put("lavenderblush", new Color(0xFFF0F5));
map.put("lawngreen", new Color(0x7CFC00));
map.put("lemonchiffon", new Color(0xFFFACD));
map.put("lightblue", new Color(0xADD8E6));
map.put("lightcoral", new Color(0xF08080));
map.put("lightcyan", new Color(0xE0FFFF));
map.put("lightgoldenrodyellow", new Color(0xFAFAD2));
map.put("lightgray", new Color(0xD3D3D3));
map.put("lightgreen", new Color(0x90EE90));
map.put("lightgrey", new Color(0xD3D3D3));
map.put("lightpink", new Color(0xFFB6C1));
map.put("lightsalmon", new Color(0xFFA07A));
map.put("lightseagreen", new Color(0x20B2AA));
map.put("lightskyblue", new Color(0x87CEFA));
map.put("lightslategray", new Color(0x778899));
map.put("lightslategrey", new Color(0x778899));
map.put("lightsteelblue", new Color(0xB0C4DE));
map.put("lightyellow", new Color(0xFFFFE0));
map.put("lime", new Color(0x00FF00));
map.put("limegreen", new Color(0x32CD32));
map.put("linen", new Color(0xFAF0E6));
map.put("magenta", new Color(0xFF00FF));
map.put("maroon", new Color(0x800000));
map.put("mediumaquamarine", new Color(0x66CDAA));
map.put("mediumblue", new Color(0x0000CD));
map.put("mediumorchid", new Color(0xBA55D3));
map.put("mediumpurple", new Color(0x9370DB));
map.put("mediumseagreen", new Color(0x3CB371));
map.put("mediumslateblue", new Color(0x7B68EE));
map.put("mediumspringgreen", new Color(0x00FA9A));
map.put("mediumturquoise", new Color(0x48D1CC));
map.put("mediumvioletred", new Color(0xC71585));
map.put("midnightblue", new Color(0x191970));
map.put("mintcream", new Color(0xF5FFFA));
map.put("mistyrose", new Color(0xFFE4E1));
map.put("moccasin", new Color(0xFFE4B5));
map.put("navajowhite", new Color(0xFFDEAD));
map.put("navy", new Color(0x000080));
map.put("oldlace", new Color(0xFDF5E6));
map.put("olive", new Color(0x808000));
map.put("olivedrab", new Color(0x6B8E23));
map.put("orange", new Color(0xFFA500));
map.put("orangered", new Color(0xFF4500));
map.put("orchid", new Color(0xDA70D6));
map.put("palegoldenrod", new Color(0xEEE8AA));
map.put("palegreen", new Color(0x98FB98));
map.put("paleturquoise", new Color(0xAFEEEE));
map.put("palevioletred", new Color(0xDB7093));
map.put("papayawhip", new Color(0xFFEFD5));
map.put("peachpuff", new Color(0xFFDAB9));
map.put("peru", new Color(0xCD853F));
map.put("pink", new Color(0xFFC0CB));
map.put("plum", new Color(0xDDA0DD));
map.put("powderblue", new Color(0xB0E0E6));
map.put("purple", new Color(0x800080));
map.put("rebeccapurple", new Color(0x663399));
map.put("red", new Color(0xFF0000));
map.put("rosybrown", new Color(0xBC8F8F));
map.put("royalblue", new Color(0x4169E1));
map.put("saddlebrown", new Color(0x8B4513));
map.put("salmon", new Color(0xFA8072));
map.put("sandybrown", new Color(0xF4A460));
map.put("seagreen", new Color(0x2E8B57));
map.put("seashell", new Color(0xFFF5EE));
map.put("sienna", new Color(0xA0522D));
map.put("silver", new Color(0xC0C0C0));
map.put("skyblue", new Color(0x87CEEB));
map.put("slateblue", new Color(0x6A5ACD));
map.put("slategray", new Color(0x708090));
map.put("slategrey", new Color(0x708090));
map.put("snow", new Color(0xFFFAFA));
map.put("springgreen", new Color(0x00FF7F));
map.put("steelblue", new Color(0x4682B4));
map.put("tan", new Color(0xD2B48C));
map.put("teal", new Color(0x008080));
map.put("thistle", new Color(0xD8BFD8));
map.put("tomato", new Color(0xFF6347));
map.put("turquoise", new Color(0x40E0D0));
map.put("violet", new Color(0xEE82EE));
map.put("wheat", new Color(0xF5DEB3));
map.put("white", new Color(0xFFFFFF));
map.put("whitesmoke", new Color(0xF5F5F5));
map.put("yellow", new Color(0xFFFF00));
map.put("yellowgreen", new Color(0x9ACD32));
}
public Color getColor(char name) {
return getColor(String.valueOf(name));
}
public Color getColor(String name) {
return map.get(name);
}
}
|
9245e7038b2812f52a32b63031ed1042b6f34ed1 | 2,234 | java | Java | src/test/java/org/mafagafogigante/dungeon/util/DungeonMathTest.java | ImmutableBox/dungeon | 59b3f3326d57dab6d1b87c7359cd4acf888c3efe | [
"BSD-3-Clause"
] | 79 | 2018-04-03T06:35:34.000Z | 2022-03-11T21:30:40.000Z | src/test/java/org/mafagafogigante/dungeon/util/DungeonMathTest.java | ImmutableBox/dungeon | 59b3f3326d57dab6d1b87c7359cd4acf888c3efe | [
"BSD-3-Clause"
] | 336 | 2015-01-13T12:05:01.000Z | 2017-12-25T11:46:14.000Z | src/test/java/org/mafagafogigante/dungeon/util/DungeonMathTest.java | ImmutableBox/dungeon | 59b3f3326d57dab6d1b87c7359cd4acf888c3efe | [
"BSD-3-Clause"
] | 45 | 2015-05-01T21:46:01.000Z | 2018-02-07T20:31:05.000Z | 50.772727 | 108 | 0.759176 | 1,003,561 | package org.mafagafogigante.dungeon.util;
import org.junit.Assert;
import org.junit.Test;
public class DungeonMathTest {
@Test
public void weightedAverageShouldWorkAsExpected() throws Exception {
Assert.assertEquals(0, Double.compare(0.0, DungeonMath.weightedAverage(0.0, 1.0, new Percentage(0.0))));
Assert.assertEquals(0, Double.compare(1.0, DungeonMath.weightedAverage(1.0, 0.0, new Percentage(0.0))));
Assert.assertEquals(0, Double.compare(1.0, DungeonMath.weightedAverage(0.0, 1.0, new Percentage(1.0))));
Assert.assertEquals(0, Double.compare(0.0, DungeonMath.weightedAverage(1.0, 0.0, new Percentage(1.0))));
Assert.assertEquals(0, Double.compare(0.0, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(0.0))));
Assert.assertEquals(0, Double.compare(0.1, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(0.2))));
Assert.assertEquals(0, Double.compare(0.2, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(0.4))));
Assert.assertEquals(0, Double.compare(0.3, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(0.6))));
Assert.assertEquals(0, Double.compare(0.4, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(0.8))));
Assert.assertEquals(0, Double.compare(0.5, DungeonMath.weightedAverage(0.0, 0.5, new Percentage(1.0))));
}
@Test
public void safeCastLongToIntegerShouldNotChangeValue() throws Exception {
Assert.assertEquals(-1, DungeonMath.safeCastLongToInteger(-1L));
Assert.assertEquals(0, DungeonMath.safeCastLongToInteger(0L));
Assert.assertEquals(1, DungeonMath.safeCastLongToInteger(1L));
Assert.assertEquals(Integer.MIN_VALUE, DungeonMath.safeCastLongToInteger((long) Integer.MIN_VALUE));
Assert.assertEquals(Integer.MAX_VALUE, DungeonMath.safeCastLongToInteger((long) Integer.MAX_VALUE));
}
@Test(expected = IllegalArgumentException.class)
public void safeCastLongToIntegerShouldThrowExceptionOnUnderflow() throws Exception {
DungeonMath.safeCastLongToInteger(((long) Integer.MIN_VALUE) - 1);
}
@Test(expected = IllegalArgumentException.class)
public void safeCastLongToIntegerShouldThrowExceptionOnOverflow() throws Exception {
DungeonMath.safeCastLongToInteger(((long) Integer.MAX_VALUE) + 1);
}
}
|
9245e77a19bda527a47711daf92589f674c3aee9 | 969 | java | Java | agp-7.1.0-alpha01/tools/base/bazel/src/com/android/tools/bazel/parser/ast/Expression.java | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | 1 | 2020-10-04T19:30:22.000Z | 2020-10-04T19:30:22.000Z | agp-7.1.0-alpha01/tools/base/bazel/src/com/android/tools/bazel/parser/ast/Expression.java | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | agp-7.1.0-alpha01/tools/base/bazel/src/com/android/tools/bazel/parser/ast/Expression.java | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | 2 | 2020-10-04T19:30:24.000Z | 2020-11-04T05:58:17.000Z | 30.28125 | 75 | 0.718266 | 1,003,562 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.tools.bazel.parser.ast;
import java.io.PrintWriter;
public abstract class Expression extends Node {
public Expression(Token start, Token end) {
super(start, end);
}
public abstract void write(String indent, PrintWriter writer);
public String getLiteral() {
return getStart().value();
}
}
|
9245e8e69d87a6889f5cd6c991865286add08b5e | 148 | java | Java | OrientacaoObjetos/src/exemplo9/classe_abstrata/TestaVeiculo.java | danilogprojetos/cursoJava | fe6a961631f6901607ed113cf841e701e491c8cc | [
"Apache-2.0"
] | null | null | null | OrientacaoObjetos/src/exemplo9/classe_abstrata/TestaVeiculo.java | danilogprojetos/cursoJava | fe6a961631f6901607ed113cf841e701e491c8cc | [
"Apache-2.0"
] | null | null | null | OrientacaoObjetos/src/exemplo9/classe_abstrata/TestaVeiculo.java | danilogprojetos/cursoJava | fe6a961631f6901607ed113cf841e701e491c8cc | [
"Apache-2.0"
] | null | null | null | 13.454545 | 41 | 0.702703 | 1,003,563 | package exemplo9.classe_abstrata;
public class TestaVeiculo {
public static void main(String[] args) {
Veiculo v = new Carro ("Fusca");
}
}
|
9245ea2ee941d20bdd0b0bc314b4d65bfe2e8d50 | 707 | java | Java | bus-testing/src/test/java/org/aoju/bus/health/software/NetworkParamsTest.java | aoju/forest | c99eb5213365eed846496acdc84f528410434ba4 | [
"MIT"
] | null | null | null | bus-testing/src/test/java/org/aoju/bus/health/software/NetworkParamsTest.java | aoju/forest | c99eb5213365eed846496acdc84f528410434ba4 | [
"MIT"
] | null | null | null | bus-testing/src/test/java/org/aoju/bus/health/software/NetworkParamsTest.java | aoju/forest | c99eb5213365eed846496acdc84f528410434ba4 | [
"MIT"
] | 1 | 2020-11-24T02:10:54.000Z | 2020-11-24T02:10:54.000Z | 26.185185 | 66 | 0.707214 | 1,003,564 | package org.aoju.bus.health.software;
import org.aoju.bus.health.Builder;
import org.aoju.bus.health.builtin.software.NetworkParams;
import org.junit.Assert;
import org.junit.Test;
/**
* Test network parameters
*/
public class NetworkParamsTest {
/**
* Test network parameters
*/
@Test
public void testNetworkParams() {
NetworkParams params = Builder.getOs().getNetworkParams();
Assert.assertNotNull(params.getHostName());
Assert.assertNotNull(params.getDomainName());
Assert.assertNotNull(params.getDnsServers());
Assert.assertNotNull(params.getIpv4DefaultGateway());
Assert.assertNotNull(params.getIpv6DefaultGateway());
}
}
|
9245ea463ac7fcab0238c37b37b10fb8f7a6303a | 1,390 | java | Java | Leetcode-cn/Counting Elements.java | joey66666/Codeyard | 08fc599baf1d99e39f878386124af854006a3602 | [
"MIT"
] | 1 | 2020-05-03T22:03:33.000Z | 2020-05-03T22:03:33.000Z | Leetcode-cn/Counting Elements.java | joey66666/Algorithms | 72f72ffa5401ecdd8f77957cf2afb64f40f29cd2 | [
"MIT"
] | 4 | 2020-03-25T14:49:19.000Z | 2020-07-04T03:30:25.000Z | Leetcode-cn/Counting Elements.java | joey66666/Codeyard | 08fc599baf1d99e39f878386124af854006a3602 | [
"MIT"
] | null | null | null | 25.740741 | 78 | 0.511511 | 1,003,565 | // Given an integer array arr, count element x such that x + 1 is also in arr.
// If there're duplicates in arr, count them seperately.
// Example 1:
// Input: arr = [1,2,3]
// Output: 2
// Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
// Example 2:
// Input: arr = [1,1,3,3,5,5,7,7]
// Output: 0
// Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
// Example 3:
// Input: arr = [1,3,2,3,5,0]
// Output: 3
// Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
// Example 4:
// Input: arr = [1,1,2,2]
// Output: 2
// Explanation: Two 1s are counted cause 2 is in arr.
//Constraints:
// 1 <= arr.length <= 1000
// 0 <= arr[i] <= 1000
class Solution {
public int countElements(int[] arr) {
//Hash存all valid nums(本身)
HashMap<Integer, Integer> hm = new HashMap<>();
int c = 1;
for (int i = 0; i < arr.length; i++) {
int valNum = arr[i];
if (!hm.containsKey(valNum)) {
hm.put(valNum, c);
} else {
hm.get(valNum);
hm.put(valNum, c + 1);
}
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (hm.containsKey(arr[i]) && hm.containsKey(arr[i] + 1)) {
count += 1;
}
}
return count;
}
}
// @lc code=end |
9245ea52e9593b81c2a2f775d2126cd920b419f5 | 447 | java | Java | src/main/java/com/qinwei/deathnote/context/annotation/Value.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qinwei/deathnote/context/annotation/Value.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | 3 | 2021-12-10T01:15:26.000Z | 2021-12-14T21:19:48.000Z | src/main/java/com/qinwei/deathnote/context/annotation/Value.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | null | null | null | 22.35 | 51 | 0.785235 | 1,003,566 | package com.qinwei.deathnote.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author qinwei
* @date 2019-06-20
*/
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
|
9245eb7e891dca7642103d15fa015fd1173f9538 | 3,634 | java | Java | ProgettoDellaPenna/src/java/courseweb/controller/Docenti.java | PetPis/ProgettoDellaPenna | fd6b7bd1f77608aebbba09cfb19a43e283bc751b | [
"MIT"
] | 2 | 2018-08-06T14:02:33.000Z | 2018-08-07T10:15:44.000Z | ProgettoDellaPenna/src/java/courseweb/controller/Docenti.java | PetPis/ProgettoDellaPenna | fd6b7bd1f77608aebbba09cfb19a43e283bc751b | [
"MIT"
] | null | null | null | ProgettoDellaPenna/src/java/courseweb/controller/Docenti.java | PetPis/ProgettoDellaPenna | fd6b7bd1f77608aebbba09cfb19a43e283bc751b | [
"MIT"
] | null | null | null | 40.377778 | 170 | 0.607595 | 1,003,567 | package courseweb.controller;
import courseweb.controller.data.DataLayerException;
import courseweb.model.interfacce.IgwDataLayer;
import courseweb.view.FailureResult;
import courseweb.view.TemplateManagerException;
import courseweb.view.TemplateResult;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Docenti extends BaseController {
private void action_error(HttpServletRequest request, HttpServletResponse response) {
if (request.getAttribute("exception") != null) {
(new FailureResult(getServletContext())).activate((Exception) request.getAttribute("exception"), request, response);
} else {
(new FailureResult(getServletContext())).activate((String) request.getAttribute("message"), request, response);
}
}
private void action_default(HttpServletRequest request, HttpServletResponse response, String lingua) throws IOException, ServletException, TemplateManagerException {
try {
TemplateResult res = new TemplateResult(getServletContext());
request.setAttribute("docenti", ((IgwDataLayer) request.getAttribute("datalayer")).getDocente());
request.setAttribute("servlet", "Docenti?");
request.setAttribute("change", "y");
HttpSession session = request.getSession(false);
if (session != null && request.isRequestedSessionIdValid()) {
String a = (String) session.getAttribute("username");
request.setAttribute("nome", a);
boolean doc = (boolean) session.getAttribute("docente");
if (doc == true) {
int id = (int) session.getAttribute("docenteid");
request.setAttribute("docente", id);
}
}
if (lingua.equals("it") || lingua.equals("")) {
request.setAttribute("lingua", "it");
request.setAttribute("page_title", "Lista Docenti");
res.activate("docenti.ftl.html", request, response);
} else {
request.setAttribute("lingua", "en");
request.setAttribute("page_title", "Teachers List");
res.activate("docenti_en.ftl.html", request, response);
}
} catch (DataLayerException ex) {
request.setAttribute("message", "Data access exception: " + ex.getMessage());
action_error(request, response);
}
}
@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
String lin;
try {
if (request.getParameter("lin") == null) {
lin = "it";
} else {
lin = request.getParameter("lin");
}
action_default(request, response, lin);
} catch (IOException ex) {
request.setAttribute("exception", ex);
action_error(request, response);
} catch (TemplateManagerException ex) {
request.setAttribute("exception", ex);
action_error(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Main Corso servlet";
}// </editor-fold>
}
|
9245ec02b76ad54c7f1cfa7b0efd1f2cabc85dc6 | 670 | java | Java | L06-reflection/src/main/java/ru/otus/reflection/DemoClass.java | serghalak/otus_java_2020_03 | abde01553db857843ca0018b6ca4386f41db694f | [
"MIT"
] | 4 | 2020-03-30T17:27:16.000Z | 2021-02-20T11:40:10.000Z | L06-reflection/src/main/java/ru/otus/reflection/DemoClass.java | serghalak/otus_java_2020_03 | abde01553db857843ca0018b6ca4386f41db694f | [
"MIT"
] | null | null | null | L06-reflection/src/main/java/ru/otus/reflection/DemoClass.java | serghalak/otus_java_2020_03 | abde01553db857843ca0018b6ca4386f41db694f | [
"MIT"
] | 15 | 2020-03-29T10:21:32.000Z | 2021-04-01T18:48:35.000Z | 18.611111 | 60 | 0.562687 | 1,003,568 | package ru.otus.reflection;
public class DemoClass {
public int publicFieldForDemo;
private String value = "initValue";
public DemoClass(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
private void privateMethod() {
System.out.println("privateMethod executed");
}
@Override
@SimpleAnnotation
public String toString() {
return "DemoClass{" +
"publicFieldForDemo=" + publicFieldForDemo +
", value='" + value + '\'' +
'}';
}
}
|
9245eca2810bffd01e72dea4baf4be3edd615905 | 2,031 | java | Java | src/com/sendev/databasemanager/seeder/Commerce.java | Senither/Database-Manager | 2c61d7f5454a33418fe21bde0a987dbece4c8bbf | [
"MIT"
] | null | null | null | src/com/sendev/databasemanager/seeder/Commerce.java | Senither/Database-Manager | 2c61d7f5454a33418fe21bde0a987dbece4c8bbf | [
"MIT"
] | null | null | null | src/com/sendev/databasemanager/seeder/Commerce.java | Senither/Database-Manager | 2c61d7f5454a33418fe21bde0a987dbece4c8bbf | [
"MIT"
] | null | null | null | 27.821918 | 104 | 0.658789 | 1,003,569 | package com.sendev.databasemanager.seeder;
import java.text.DecimalFormat;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import com.sendev.databasemanager.seeder.contracts.FakeValuesServiceContract;
import com.sendev.databasemanager.seeder.contracts.Generator;
import com.sendev.databasemanager.seeder.contracts.ResolverContract;
public class Commerce extends Generator
{
public Commerce(ResolverContract resolver, FakeValuesServiceContract fakeValueService)
{
super(resolver, fakeValueService);
}
public String color()
{
return service().fetchString("color.name");
}
public String department()
{
int numberOfDepartments = Math.max(random().nextInt(4), 1);
SortedSet<String> departments = new TreeSet<String>();
while (departments.size() < numberOfDepartments) {
departments.add(service().fetchString("commerce.department"));
}
if (departments.size() > 1) {
String lastDepartment = departments.last();
return StringUtils.join(departments.headSet(lastDepartment), ", ") + " & " + lastDepartment;
}
return departments.first();
}
public String productName()
{
return StringUtils.join(new String[]{service().fetchString("commerce.product_name.adjective"),
service().fetchString("commerce.product_name.material"),
service().fetchString("commerce.product_name.product")}, " ");
}
public String material()
{
return service().fetchString("commerce.product_name.material");
}
/**
* Generate a random price between 0.00 and 100.00
*
* @return a random price between 0.00 and 100.00.
*/
public String price()
{
return price(0, 100);
}
public String price(double min, double max)
{
double price = min + (random().nextDouble() * (max - min));
return new DecimalFormat("#0.00").format(price);
}
}
|
9245ee161b3b37c5b939840da12910db24e9e1f7 | 1,623 | java | Java | src/main/java/com/gianlu/pyxreloaded/handlers/PlayCardHandler.java | themysteriousdeveloper/PYX-Reloaded | 5cc7d80faf792f9e4cf7ea64ab4876b6739ba6d3 | [
"Apache-2.0"
] | 25 | 2018-01-03T23:21:38.000Z | 2020-12-21T13:17:59.000Z | src/main/java/com/gianlu/pyxreloaded/handlers/PlayCardHandler.java | themysteriousdeveloper/PYX-Reloaded | 5cc7d80faf792f9e4cf7ea64ab4876b6739ba6d3 | [
"Apache-2.0"
] | 94 | 2018-01-02T21:12:14.000Z | 2018-12-11T06:11:48.000Z | src/main/java/com/gianlu/pyxreloaded/handlers/PlayCardHandler.java | themysteriousdeveloper/PYX-Reloaded | 5cc7d80faf792f9e4cf7ea64ab4876b6739ba6d3 | [
"Apache-2.0"
] | 16 | 2018-01-27T05:49:19.000Z | 2021-12-06T01:24:37.000Z | 39.585366 | 150 | 0.75724 | 1,003,570 | package com.gianlu.pyxreloaded.handlers;
import com.gianlu.pyxreloaded.Consts;
import com.gianlu.pyxreloaded.data.JsonWrapper;
import com.gianlu.pyxreloaded.data.User;
import com.gianlu.pyxreloaded.game.Game;
import com.gianlu.pyxreloaded.server.Annotations;
import com.gianlu.pyxreloaded.server.BaseCahHandler;
import com.gianlu.pyxreloaded.server.Parameters;
import com.gianlu.pyxreloaded.singletons.GamesManager;
import io.undertow.server.HttpServerExchange;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jetbrains.annotations.NotNull;
public class PlayCardHandler extends GameWithPlayerHandler {
public static final String OP = Consts.Operation.PLAY_CARD.toString();
public PlayCardHandler(@Annotations.GameManager GamesManager gamesManager) {
super(gamesManager);
}
@NotNull
@Override
public JsonWrapper handleWithUserInGame(User user, Game game, Parameters params, HttpServerExchange exchange) throws BaseCahHandler.CahException {
String cardIdStr = params.getStringNotNull(Consts.GeneralKeys.CARD_ID);
if (cardIdStr.isEmpty()) throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);
int cardId;
try {
cardId = Integer.parseInt(cardIdStr);
} catch (NumberFormatException ex) {
throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_CARD, ex);
}
String text = params.getString(Consts.GeneralKeys.WRITE_IN_TEXT);
if (text != null && text.contains("<")) text = StringEscapeUtils.escapeXml11(text);
return game.playCard(user, cardId, text);
}
}
|
9245ee1f2082b5ccf6d5366ba34ef14d534c4160 | 1,043 | java | Java | engine/src/main/java/com/arcadedb/database/async/NewEdgeCallback.java | elegoff/arcadedb | 7de1f4b1088ff4ea0680148126da6d2594bf57d0 | [
"Apache-2.0"
] | null | null | null | engine/src/main/java/com/arcadedb/database/async/NewEdgeCallback.java | elegoff/arcadedb | 7de1f4b1088ff4ea0680148126da6d2594bf57d0 | [
"Apache-2.0"
] | 31 | 2021-11-29T04:18:59.000Z | 2022-03-28T05:14:55.000Z | engine/src/main/java/com/arcadedb/database/async/NewEdgeCallback.java | elegoff/arcadedb | 7de1f4b1088ff4ea0680148126da6d2594bf57d0 | [
"Apache-2.0"
] | null | null | null | 37.25 | 89 | 0.763183 | 1,003,571 | /*
* Copyright 2021 Arcade Data Ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.arcadedb.database.async;
import com.arcadedb.graph.Edge;
public interface NewEdgeCallback {
void call(Edge newEdge, boolean createdSourceVertex, boolean createdDestinationVertex);
}
|
9245ee6721708b6444003f6a187381fc7bbcab03 | 587 | java | Java | dcwlt-common/dcwlt-common-pay/src/main/java/com/dcits/dcwlt/pay/api/domain/dcep/login/LoginInnerRspDTO.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | null | null | null | dcwlt-common/dcwlt-common-pay/src/main/java/com/dcits/dcwlt/pay/api/domain/dcep/login/LoginInnerRspDTO.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | null | null | null | dcwlt-common/dcwlt-common-pay/src/main/java/com/dcits/dcwlt/pay/api/domain/dcep/login/LoginInnerRspDTO.java | shuwenjin/dcwlt | 97f677cf596b7bcb23ce8867b5a286cce4a82339 | [
"MIT"
] | 1 | 2022-03-01T08:24:59.000Z | 2022-03-01T08:24:59.000Z | 20.241379 | 55 | 0.611584 | 1,003,572 | package com.dcits.dcwlt.pay.api.domain.dcep.login;
import com.dcits.dcwlt.pay.api.domain.ecny.ECNYRspBody;
/**
* 行内登录退出响应报文
*
* @author
* @date 2021/1/4
*/
public class LoginInnerRspDTO extends ECNYRspBody {
private String procResult; //处理结果
public String getProcResult() {
return procResult;
}
public void setProcResult(String procResult) {
this.procResult = procResult;
}
@Override
public String toString() {
return "LoginInnerRspDTO{" +
"procResult='" + procResult + '\'' +
'}';
}
}
|
9245ee8d8588bcc6e1bacd82c8031057937ae672 | 2,161 | java | Java | src/main/java/com/dumbdogdiner/stickyapi/common/configuration/InvalidConfigurationException.java | DumbDogDiner/StickyAPIOld | dbcd72ec7d1af0e95dcf6849c759b67fbb8b54a4 | [
"MIT"
] | null | null | null | src/main/java/com/dumbdogdiner/stickyapi/common/configuration/InvalidConfigurationException.java | DumbDogDiner/StickyAPIOld | dbcd72ec7d1af0e95dcf6849c759b67fbb8b54a4 | [
"MIT"
] | 1 | 2020-10-28T20:30:53.000Z | 2021-02-20T20:32:42.000Z | src/main/java/com/dumbdogdiner/stickyapi/common/configuration/InvalidConfigurationException.java | DumbDogDiner/StickyAPIOld | dbcd72ec7d1af0e95dcf6849c759b67fbb8b54a4 | [
"MIT"
] | null | null | null | 32.939394 | 76 | 0.697792 | 1,003,573 | /*
* Koffee - A simple collection of utilities I commonly use
* Copyright (C) 2019-2020 Justin Crawford <[email protected]>
* Copyright (C) 2019-2020 Zachery Coleman <[email protected]>
* Copyright (C) 2019-2020 Skye Elliot <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dumbdogdiner.stickyapi.common.configuration;
/**
* Exception thrown when attempting to load an invalid {@link Configuration}
*/
@SuppressWarnings("serial")
public class InvalidConfigurationException extends Exception {
/**
* Creates a new instance of InvalidConfigurationException without a
* message or cause.
*/
public InvalidConfigurationException() {}
/**
* Constructs an instance of InvalidConfigurationException with the
* specified message.
*
* @param msg The details of the exception.
*/
public InvalidConfigurationException(String msg) {
super(msg);
}
/**
* Constructs an instance of InvalidConfigurationException with the
* specified cause.
*
* @param cause The cause of the exception.
*/
public InvalidConfigurationException(Throwable cause) {
super(cause);
}
/**
* Constructs an instance of InvalidConfigurationException with the
* specified message and cause.
*
* @param cause The cause of the exception.
* @param msg The details of the exception.
*/
public InvalidConfigurationException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
9245eef5b81020de2bd46e4a009ef4d1446e87e2 | 6,400 | java | Java | to_refactor/main/osm/algorithm/SeClust.java | lukehb/TrajSuite | 020ddb1b8377da18a7a61f5b14fbe51604b2c0e7 | [
"MIT"
] | 16 | 2018-05-22T18:38:55.000Z | 2021-01-27T16:03:00.000Z | to_refactor/main/osm/algorithm/SeClust.java | kwnam4u/TrajSuite | 020ddb1b8377da18a7a61f5b14fbe51604b2c0e7 | [
"MIT"
] | 1 | 2021-07-22T08:52:04.000Z | 2021-07-22T08:52:04.000Z | to_refactor/main/osm/algorithm/SeClust.java | kwnam4u/TrajSuite | 020ddb1b8377da18a7a61f5b14fbe51604b2c0e7 | [
"MIT"
] | 3 | 2018-06-06T05:27:50.000Z | 2018-08-20T15:13:04.000Z | 41.558442 | 124 | 0.568906 | 1,003,575 | package onethreeseven.trajsuite.osm.algorithm;
import onethreeseven.common.model.TimeCategory;
import onethreeseven.common.model.TimeCategoryPool;
import onethreeseven.common.util.Maths;
import onethreeseven.common.util.NDUtil;
import onethreeseven.datastructures.model.STStopPt;
import onethreeseven.datastructures.model.STStopTrajectory;
import onethreeseven.datastructures.model.SpatioCompositeTrajectory;
import onethreeseven.trajsuite.osm.model.StopEpisode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
/**
* Converts some raw spatio-temporal traces into stop episodes.
* @author Luke Bermingham
*/
public class SeClust {
/**
* Converts a trajectory within individually annotated stops and moves into a trajectory
* of stop episodes.
* @param traj The stop/move annotated trajectory to convert.
* @param minMoveDurationMillis If move episode is less than this it becomes a stop also.
* @param minEpisodeMillis The minimum amount of time for a stop episode to be considered an episode.
* @param timeCategoryPool The time category pool used to discretise the time dimension into a category.
* @return A trajectory made of distinct stop episodes.
*/
public SpatioCompositeTrajectory<StopEpisode> run(STStopTrajectory traj,
long minMoveDurationMillis,
long minEpisodeMillis,
TimeCategoryPool timeCategoryPool){
cleanupStops(traj, minMoveDurationMillis);
return toStopEpisodes(traj, minEpisodeMillis, timeCategoryPool);
}
/**
* Merges contiguous stops with a small enough temporal gap into one bigger set of stops.
* @param traj The stop traj.
* @param nearbyStopMillis How small the move gap has to be.
*/
private void cleanupStops(STStopTrajectory traj, long nearbyStopMillis){
//algo works by going from one stop end to another stop beginning
for (int i = 0; i < traj.size(); i++) {
STStopPt entry = traj.get(i);
boolean inAStop = entry.isStopped();
//found the start of a stop
if(inAStop){
//traverse through the stop
int moveStartIdx = i;
for (; i < traj.size() && inAStop; i++) {
entry = traj.get(i);
moveStartIdx = i;
inAStop = entry.isStopped();
}
//now we are in a move, traverse through it
int moveEndIdx = moveStartIdx;
for (; i < traj.size() && !inAStop; i++) {
entry = traj.get(i);
moveEndIdx = i;
inAStop = entry.isStopped();
}
//we have ended up in a new stop
if(inAStop){
long moveDurationMillis = ChronoUnit.MILLIS.between(
traj.getTime(moveStartIdx),
traj.getTime(moveEndIdx));
//make the in-between moves all into stops because they are between two nearby stops
if(moveDurationMillis <= nearbyStopMillis){
for (int j = moveStartIdx; j < moveEndIdx; j++) {
traj.get(j).setIsStopped(true);
}
}
}
}
}
}
private SpatioCompositeTrajectory<StopEpisode> toStopEpisodes(STStopTrajectory traj,
long minEpisodeMillis,
TimeCategoryPool timeCategoryPool){
ArrayList<double[]> coords = new ArrayList<>();
LocalDateTime startEpisode = null;
LocalDateTime endEpisode = null;
boolean isInStop = false;
//make sure we are in cartesian coordinates
if(!traj.isInCartesianMode()){
traj.toCartesian();
}
SpatioCompositeTrajectory<StopEpisode> output =
new SpatioCompositeTrajectory<StopEpisode>(true, traj.getProjection()) {};
for (int i = 0; i < traj.size(); i++) {
STStopPt entry = traj.get(i);
boolean curStopped = entry.isStopped();
//case: this is the first stop
if(!isInStop && curStopped){
isInStop = true;
coords.add(entry.getCoords());
startEpisode = entry.getExtra();
endEpisode = entry.getExtra();
}
//case: this is not the first stop
else if(isInStop && curStopped){
coords.add(entry.getCoords());
endEpisode = entry.getExtra();
}
//case: in a stop, but we processed a move (or ran out of entries), so make a stop episode
if(isInStop && !curStopped || isInStop && i == traj.size() - 1){
isInStop = false;
long durationMillis = ChronoUnit.MILLIS.between(startEpisode, endEpisode);
//only permit stop episode of minimum duration or larger
if(durationMillis >= minEpisodeMillis){
output.add(makeStopEpisode(coords, startEpisode, timeCategoryPool));
}
coords.clear();
startEpisode = null;
endEpisode = null;
}
}
return output;
}
private StopEpisode makeStopEpisode(ArrayList<double[]> coords, LocalDateTime start, TimeCategoryPool timeCategoryPool){
double[][] pts = new double[coords.size()][coords.iterator().next().length];
for (int i = 0; i < coords.size(); i++) {
pts[i] = coords.get(i);
}
double[] centerPt = NDUtil.averagePt(pts);
//measure distance from center point to find our radius
double maxRadius = 0;
for (double[] otherPt : pts) {
double curRadius = Maths.dist(centerPt, otherPt);
if(curRadius > maxRadius){
maxRadius = curRadius;
}
}
TimeCategory timeCategory = timeCategoryPool.resolve(start);
return new StopEpisode(centerPt, maxRadius, start, timeCategory);
}
}
|
9245f085bf923e5eb7416b6027b054e509987dee | 2,060 | java | Java | src/main/java/net/kemuri9/invoke/UnreflectToMethodHandle.java | kemuri-9/invoke | 84b0db58c8c3a4d53ae94d19ab445846b2449112 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/kemuri9/invoke/UnreflectToMethodHandle.java | kemuri-9/invoke | 84b0db58c8c3a4d53ae94d19ab445846b2449112 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/kemuri9/invoke/UnreflectToMethodHandle.java | kemuri-9/invoke | 84b0db58c8c3a4d53ae94d19ab445846b2449112 | [
"Apache-2.0"
] | null | null | null | 42.916667 | 119 | 0.730583 | 1,003,576 | /**
* Copyright 2021,2022 Steven Walters
*
* 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.kemuri9.invoke;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/**
* Specialization of {@link Unreflector} for returning {@link MethodHandle}s
*
* @param <E> Type of {@link Member} to lookup
*/
public interface UnreflectToMethodHandle<E extends Member> extends Unreflector<E, MethodHandle> {
/** {@link UnreflectToMethodHandle} to invoke a {@link Constructor} */
public static final UnreflectToMethodHandle<Constructor<?>> CONSTRUCTOR = (l, c)-> l.unreflectConstructor(c);
/** {@link UnreflectToMethodHandle} to invoke a {@link Executable} */
public static final UnreflectToMethodHandle<Executable> EXECUTABLE =
(l, e)-> (e instanceof Constructor) ? l.unreflectConstructor((Constructor<?>) e) : l.unreflect((Method) e);
/** {@link UnreflectToMethodHandle} to get the value of a {@link Field} */
public static final UnreflectToMethodHandle<Field> FIELD_GETTER = (l, f)-> l.unreflectGetter(f);
/** {@link UnreflectToMethodHandle} to set the value of a {@link Field} */
public static final UnreflectToMethodHandle<Field> FIELD_SETTER = (l, f)-> l.unreflectSetter(f);
/** {@link UnreflectToMethodHandle} to invoke a {@link Method} */
public static final UnreflectToMethodHandle<Method> METHOD = (l, m)-> l.unreflect(m);
}
|
9245f0c90c7468baff406ab3bbaf020eac13964d | 454 | java | Java | src/main/java/seedu/address/model/person/predicates/ReturnTruePredicate.java | IceBear789/tp | 887a2d8e5b9e839982cffcaa2e16da30cf6eff60 | [
"MIT"
] | null | null | null | src/main/java/seedu/address/model/person/predicates/ReturnTruePredicate.java | IceBear789/tp | 887a2d8e5b9e839982cffcaa2e16da30cf6eff60 | [
"MIT"
] | 129 | 2021-02-21T09:32:01.000Z | 2021-04-12T09:55:15.000Z | src/main/java/seedu/address/model/person/predicates/ReturnTruePredicate.java | IceBear789/tp | 887a2d8e5b9e839982cffcaa2e16da30cf6eff60 | [
"MIT"
] | 5 | 2021-02-15T06:52:42.000Z | 2021-02-27T11:40:07.000Z | 21.619048 | 63 | 0.718062 | 1,003,577 | package seedu.address.model.person.predicates;
import java.util.function.Predicate;
import seedu.address.model.person.Person;
/**
* A dummy predicate that returns true all the time.
*/
public class ReturnTruePredicate implements Predicate<Person> {
@Override
public boolean test(Person person) {
return true;
}
@Override
public boolean equals(Object other) {
return other instanceof ReturnTruePredicate;
}
}
|
9245f0cff702f55ba95891e72f8c42084936241e | 2,487 | java | Java | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/aaa/LogoutSessionCommand.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/aaa/LogoutSessionCommand.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/aaa/LogoutSessionCommand.java | UranusBlockStack/ovirt-engine | fe3c90ed3e74e6af9497c826c82e653382946ae1 | [
"Apache-2.0"
] | null | null | null | 35.528571 | 128 | 0.675915 | 1,003,578 | package org.ovirt.engine.core.bll.aaa;
import java.util.Collections;
import java.util.List;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.aaa.Authn;
import org.ovirt.engine.core.aaa.AuthenticationProfile;
import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
/**
* Tries to log out a user identified by its session id
*/
public class LogoutSessionCommand<T extends VdcActionParametersBase> extends CommandBase<T> {
public LogoutSessionCommand(T parameters) {
this(parameters, null);
}
public LogoutSessionCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
}
@Override
public AuditLogType getAuditLogTypeValue() {
return getSucceeded() ? AuditLogType.USER_VDC_LOGOUT : AuditLogType.USER_VDC_LOGOUT_FAILED;
}
@Override
protected boolean canDoAction() {
return SessionDataContainer.getInstance().isSessionExists(getParameters().getSessionId());
}
@Override
protected void executeCommand() {
AuthenticationProfile profile = SessionDataContainer.getInstance().getProfile(getParameters().getSessionId());
if (profile == null) {
setSucceeded(false);
} else {
if ((profile.getAuthn().getContext().<Long> get(Authn.ContextKeys.CAPABILITIES) & Authn.Capabilities.LOGOUT) != 0) {
profile.getAuthn().invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authn.InvokeCommands.LOGOUT
).mput(
Authn.InvokeKeys.PRINCIPAL,
SessionDataContainer.getInstance().getPrincipalName(getParameters().getSessionId())
));
}
SessionDataContainer.getInstance().removeSessionOnLogout(getParameters().getSessionId());
setSucceeded(true);
}
}
@Override
protected boolean isUserAuthorizedToRunAction() {
return true;
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
// Not needed for admin operations.
return Collections.emptyList();
}
}
|
9245f2c0b0258f379daa4ca7a3abcd8b421f4bd2 | 155 | java | Java | BlueDBOnDisk/src/main/java/org/bluedb/disk/file/ComparableAndSerializable.java | BlueDB/bluedb | dbad0a8fbe80a277bd88e0834f060030a4024e49 | [
"Apache-2.0"
] | null | null | null | BlueDBOnDisk/src/main/java/org/bluedb/disk/file/ComparableAndSerializable.java | BlueDB/bluedb | dbad0a8fbe80a277bd88e0834f060030a4024e49 | [
"Apache-2.0"
] | null | null | null | BlueDBOnDisk/src/main/java/org/bluedb/disk/file/ComparableAndSerializable.java | BlueDB/bluedb | dbad0a8fbe80a277bd88e0834f060030a4024e49 | [
"Apache-2.0"
] | null | null | null | 19.375 | 84 | 0.767742 | 1,003,579 | package org.bluedb.disk.file;
import java.io.Serializable;
public interface ComparableAndSerializable<T> extends Comparable<T>, Serializable {
}
|
9245f3fce01a6b2ec02169db484b2859c1447e97 | 542 | java | Java | cucumber-tests/src/main/java/ru/iteco/cucumber/model/AuthRequest.java | fmh-charity/fmh-backend | e3f3433f65d6cad306b195d960ea39f9b39e69bb | [
"Apache-2.0"
] | 3 | 2021-09-27T15:55:02.000Z | 2022-02-02T19:57:05.000Z | cucumber-tests/src/main/java/ru/iteco/cucumber/model/AuthRequest.java | fmh-charity/fmh-backend | e3f3433f65d6cad306b195d960ea39f9b39e69bb | [
"Apache-2.0"
] | 2 | 2021-12-03T20:02:15.000Z | 2021-12-10T14:19:39.000Z | cucumber-tests/src/main/java/ru/iteco/cucumber/model/AuthRequest.java | fmh-charity/fmh-backend | e3f3433f65d6cad306b195d960ea39f9b39e69bb | [
"Apache-2.0"
] | null | null | null | 21.68 | 53 | 0.773063 | 1,003,580 | package ru.iteco.cucumber.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@JsonFormat
public class AuthRequest {
@JsonProperty("clientId")
private String clientId;
@JsonProperty("clientSecret")
private String clientSecret;
@JsonProperty("audience")
private String audience;
@JsonProperty("grantType")
private String grantType;
}
|
Subsets and Splits