hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0c4e8ff729e444fb81b6e67ec2ce6673800102 | 216 | java | Java | src/main/java/edu/xihua/project/pms/model/vo/CardListVO.java | GuaSeed/property-manage-system | 9beae1b66d15568ae52af153e4811c6dde7c6bfa | [
"MIT"
] | null | null | null | src/main/java/edu/xihua/project/pms/model/vo/CardListVO.java | GuaSeed/property-manage-system | 9beae1b66d15568ae52af153e4811c6dde7c6bfa | [
"MIT"
] | null | null | null | src/main/java/edu/xihua/project/pms/model/vo/CardListVO.java | GuaSeed/property-manage-system | 9beae1b66d15568ae52af153e4811c6dde7c6bfa | [
"MIT"
] | 1 | 2022-01-03T07:45:19.000Z | 2022-01-03T07:45:19.000Z | 15.428571 | 43 | 0.666667 | 5,224 | package edu.xihua.project.pms.model.vo;
import lombok.Data;
/**
* @author intent <a>zzy.main@gmail.com</a>
* @date 2021/5/30 2:50 下午
* @since 1.0
*/
@Data
public class CardListVO {
private String openid;
}
|
3e0c4f4fe532931260f18d2348491cdc68f74748 | 735 | java | Java | src/test/java/com/capgemini/nobank/model/AccountUT.java | alanAraujoSousa/nobank-api | 3b9d47f090fa80b8f55331017a65df24dcf6b4c2 | [
"MIT"
] | null | null | null | src/test/java/com/capgemini/nobank/model/AccountUT.java | alanAraujoSousa/nobank-api | 3b9d47f090fa80b8f55331017a65df24dcf6b4c2 | [
"MIT"
] | null | null | null | src/test/java/com/capgemini/nobank/model/AccountUT.java | alanAraujoSousa/nobank-api | 3b9d47f090fa80b8f55331017a65df24dcf6b4c2 | [
"MIT"
] | null | null | null | 28.269231 | 73 | 0.760544 | 5,225 | package com.capgemini.nobank.model;
import com.capgemini.nobank.domain.dto.v1.CreateAccountV1DTO;
import com.capgemini.nobank.domain.persistence.Account;
import org.junit.jupiter.api.Test;
import org.modelmapper.ModelMapper;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AccountUT {
private static final ModelMapper modelMapper = new ModelMapper();
@Test
public void check_create_mapping() {
CreateAccountV1DTO creation = new CreateAccountV1DTO();
creation.setMoneyAmount(new BigDecimal(12));
Account entity = modelMapper.map(creation, Account.class);
assertEquals(creation.getMoneyAmount(), entity.getMoneyAmount());
}
}
|
3e0c4f56cf02fab5bf98b310ae515d8a4c02f763 | 762 | java | Java | eagle-oj-web/src/main/java/com/eagleoj/web/postman/task/SendProblemAuditingMessageTask.java | YeGuangjun/eagle-oj-api | b6f5e902df8a471f6e853cc0d521103e6f2e5b25 | [
"Apache-2.0"
] | null | null | null | eagle-oj-web/src/main/java/com/eagleoj/web/postman/task/SendProblemAuditingMessageTask.java | YeGuangjun/eagle-oj-api | b6f5e902df8a471f6e853cc0d521103e6f2e5b25 | [
"Apache-2.0"
] | null | null | null | eagle-oj-web/src/main/java/com/eagleoj/web/postman/task/SendProblemAuditingMessageTask.java | YeGuangjun/eagle-oj-api | b6f5e902df8a471f6e853cc0d521103e6f2e5b25 | [
"Apache-2.0"
] | null | null | null | 16.212766 | 65 | 0.587927 | 5,226 | package com.eagleoj.web.postman.task;
/**
* @author Smith
**/
public class SendProblemAuditingMessageTask implements BaseTask {
private String title;
private int pid;
private int uid;
private boolean isAccepted;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public boolean isAccepted() {
return isAccepted;
}
public void setAccepted(boolean accepted) {
isAccepted = accepted;
}
}
|
3e0c50807406877144363d35926d12e6f3157f8e | 11,848 | java | Java | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/rest/test/api/TemplateAdminService.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 339 | 2017-03-29T20:40:34.000Z | 2022-03-31T08:05:43.000Z | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/rest/test/api/TemplateAdminService.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 3,938 | 2017-01-23T12:28:02.000Z | 2022-03-28T14:20:20.000Z | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/rest/test/api/TemplateAdminService.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 345 | 2016-12-21T11:59:07.000Z | 2022-03-31T08:39:38.000Z | 47.967611 | 182 | 0.670662 | 5,227 | /*
*Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.esb.rest.test.api;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axis2.AxisFault;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.clients.template.EndpointTemplateAdminServiceClient;
import org.wso2.esb.integration.common.clients.template.SequenceTemplateAdminServiceClient;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
/**
* Test templateAdminService related operations
*/
public class TemplateAdminService extends ESBIntegrationTest {
private SequenceTemplateAdminServiceClient templateAdmin;
private EndpointTemplateAdminServiceClient endpointAdmin;
private static final String templateName = "TemplateAdminService";
private static final String dynamicName = "TemplateUserService";
private final String KEY = "conf:/template/dynamicAdminTemplate";
private static final String template1 =
"<template xmlns=\"http://ws.apache.org/ns/synapse\" name=\"TemplateAdminService\">\n" + "<parameter name=\"message\"/>\n" + " <sequence>\n" + "<log level=\"custom\">\n"
+ "<property name=\"TMPL_MSG \" value= \"in Template Service..\" />\n" + "</log>\n" + " </sequence>\n" + "</template>";
private static final String template2 =
"<template xmlns=\"http://ws.apache.org/ns/synapse\" name=\"TemplateAdminService\">\n" + "<parameter name=\"message\"/>\n" + " <sequence>\n" + "<log level=\"custom\">\n"
+ "<property name=\"TMPL_MSG \" value= \"in Template Service Updated..\" />\n" + "</log>\n" + " </sequence>\n" + "</template>";
private static final String template3 =
"<template xmlns=\"http://ws.apache.org/ns/synapse\" name=\"TemplateUserService\">\n" + "<parameter name=\"message\"/>\n" + " <sequence>\n" + "<log level=\"custom\">\n"
+ "<property name=\"TMPL_MSG \" value= \"in Template Service Updated..\" />\n" + "</log>\n" + " </sequence>\n" + "</template>";
private static final String endpointTmpl1 = "<template xmlns=\"http://ws.apache.org/ns/synapse\" name= \"SampleEndpointTemplate\">" +
"<axis2ns3:parameter xmlns:axis2ns3=\"http://ws.apache.org/ns/synapse\" name=\"name\" />" +
"<axis2ns4:parameter xmlns:axis2ns4=\"http://ws.apache.org/ns/synapse\" name=\"uri\" />" +
"<endpoint name=\"quoteEndpoint\">" +
"<address uri=\"https://localhost:9000/services/SimpleStockQuoteService\">" +
"</address>" +
"</endpoint>" +
"</template>";
private static final String endpointTmpl2 = "<template xmlns=\"http://ws.apache.org/ns/synapse\" name= \"SampleEndpointTemplate\">" +
"<endpoint name=\"updateEndpoint\">" +
"<address uri=\"https://localhost:9000/services/SimpleStockQuoteService\">" +
"</address>" +
"</endpoint>" +
"</template>";
private static final String endpointName = "SampleEndpointTemplate";
@BeforeClass(alwaysRun = true)
public void init() throws Exception {
super.init();
templateAdmin = new SequenceTemplateAdminServiceClient(contextUrls.getBackEndUrl(), getSessionCookie());
endpointAdmin = new EndpointTemplateAdminServiceClient(contextUrls.getBackEndUrl(), getSessionCookie());
}
@Test(groups = { "wso2.esb" },
description = "Test template creation service",
priority = 1)
public void testCreateTemplate() throws Exception {
int prevCount = templateAdmin.getTemplatesCount();
templateAdmin.addSequenceTemplate(AXIOMUtil.stringToOM(template1));
int latestCount = templateAdmin.getTemplatesCount();
Assert.assertTrue(prevCount < latestCount, "New template not added");
}
@Test(groups = { "wso2.esb" },
description = "Test template list service",
priority = 2)
public void testGetTemplate() throws Exception {
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertNotNull(elm, "Unable to get the template");
Assert.assertTrue(elm.toString().contains(templateName), "Requested template name is invalid");
}
@Test(groups = { "wso2.esb" },
description = "Test template save service",
priority = 3)
public void testUpdateTemplate() throws Exception {
templateAdmin.saveTemplate(AXIOMUtil.stringToOM(template2));
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertTrue(elm.toString().contains("in Template Service Updated"), "Template not updated");
}
@Test(groups = { "wso2.esb" },
description = "Test template enable statistics",
priority = 4)
public void testEnableStatisticsTemplate() throws Exception {
templateAdmin.enableStatistics(templateName);
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertTrue(elm.toString().contains("statistics=\"enable\""), "Stats not enabled for template");
}
@Test(groups = { "wso2.esb" },
description = "Test template disable statistics",
priority = 5)
public void testDisableStatisticsTemplate() throws Exception {
templateAdmin.disableStatistics(templateName);
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertFalse(elm.toString().contains("statistics=\"enable\""), "Stats not disabled for template");
}
@Test(groups = { "wso2.esb" },
description = "Test template enable tracing",
priority = 6)
public void testEnableTracingTemplate() throws Exception {
templateAdmin.enableTracing(templateName);
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertTrue(elm.toString().contains("trace=\"enable\""), "Tracing not enabled for template");
}
@Test(groups = { "wso2.esb" },
description = "Test template disable tracing",
priority = 7)
public void testDisableTracingTemplate() throws Exception {
templateAdmin.disableTracing(templateName);
OMElement elm = templateAdmin.getTemplate(templateName);
Assert.assertFalse(elm.toString().contains("trace=\"enable\""), "Tracing not disabled for template");
}
@Test(groups = { "wso2.esb" },
description = "Test template delete service",
priority = 8)
public void testDeleteTemplate() throws Exception {
int prevCount = templateAdmin.getTemplatesCount();
templateAdmin.deleteTemplate(templateName);
int latestCount = templateAdmin.getTemplatesCount();
Assert.assertTrue(prevCount > latestCount, "New template not removed");
}
@Test(groups = { "wso2.esb" },
description = "Test list invalid template",
priority = 9)
public void testGetInvalidTemplate() throws Exception {
try {
templateAdmin.getTemplate("invalid");
Assert.fail("Expected exception not thrown when listing invalid template");
} catch (AxisFault e) {
Assert.assertTrue(e.getMessage().contains("Couldn't get the Synapse Configuration to get the Template"),
"Expected exception not thrown for invalid template");
}
}
@Test(groups = { "wso2.esb" },
description = "Test dynamic template creation service",
priority = 10)
public void testCreateDynamicTemplate() throws Exception {
int prevCount = templateAdmin.getDynamicTemplateCount();
templateAdmin.addDynamicSequenceTemplate(KEY,AXIOMUtil.stringToOM(template1));
int latestCount = templateAdmin.getDynamicTemplateCount();
Assert.assertTrue(prevCount < latestCount, "Dynamic template not added");
}
@Test(groups = { "wso2.esb" },
description = "Test dynamic template list service",
priority = 11)
public void testGetDynamicTemplate() throws Exception {
OMElement elm = templateAdmin.getDynamicTemplate(KEY);
Assert.assertNotNull(elm, "Unable to get dynamic template");
Assert.assertTrue(elm.toString().contains(templateName), "Requested template name is invalid");
}
@Test(groups = { "wso2.esb" },
description = "Test dynamic template creation service",
priority = 12)
public void testUpdateDynamicTemplate() throws Exception {
templateAdmin.updateDynamicTemplate(KEY, AXIOMUtil.stringToOM(template3));
templateAdmin.saveDynamicTemplate(KEY, AXIOMUtil.stringToOM(template3));
OMElement elm = templateAdmin.getDynamicTemplate(KEY);
Assert.assertTrue(elm.toString().contains(dynamicName), "Dynamic template not updated");
}
@Test(groups = { "wso2.esb" },
description = "Test endpoint template creation service",
priority = 13)
public void testCreateEndpointTemplate() throws Exception {
int prevCount = endpointAdmin.getEndpointTemplatesCount();
endpointAdmin.addEndpointTemplate(AXIOMUtil.stringToOM(endpointTmpl1));
int latestCount = endpointAdmin.getEndpointTemplatesCount();
Assert.assertTrue(prevCount < latestCount, "New endpoint template not added");
}
@Test(groups = { "wso2.esb" },
description = "Test endpoint template list service",
priority = 14)
public void testListEndpointTemplate() throws Exception {
OMElement elm = endpointAdmin.getEndpointTemplate(endpointName);
Assert.assertNotNull(elm, "Unable to get requested endpoint template");
Assert.assertTrue(elm.toString().contains(endpointName), "New endpoint template not listed");
}
@Test(groups = { "wso2.esb" },
description = "Test endpoint template update service",
priority = 15)
public void testUpdateEndpointTemplate() throws Exception {
if (endpointAdmin.hasDuplicateEndpointTemplate(endpointTmpl1)) {
endpointAdmin.deleteEndpointTemplate(endpointTmpl1);
}
endpointAdmin.saveEndpointTemplate(endpointTmpl2);
OMElement elm = endpointAdmin.getEndpointTemplate(endpointName);
Assert.assertTrue(elm.toString().contains("updateEndpoint"), "Endpoint template not updated");
}
@Test(groups = { "wso2.esb" },
description = "Test listing invalid endpoint template",
priority = 14)
public void testListInvalidEndpointTemplate() throws Exception {
try {
endpointAdmin.getEndpointTemplate("invalidEP");
Assert.fail("Expected exception not thrown for invalid endpoint template");
} catch (AxisFault e) {
Assert.assertTrue(
e.getMessage().contains("Couldn't get the Synapse Configuration to get the Endpoint Template"),
"Expected exception message not available");
}
}
@AfterClass(alwaysRun = true)
public void close() throws Exception {
templateAdmin = null;
endpointAdmin = null;
super.cleanup();
}
}
|
3e0c51a5f1cb70b6c0fd262832e5441d5e8420b0 | 746 | java | Java | app/src/main/java/com/nakeyfishzh/coolweather14/model/County.java | nakeyfishzh/coolweather | 0c676108fd40594428f3cbdc8fde262b4b7180c6 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/nakeyfishzh/coolweather14/model/County.java | nakeyfishzh/coolweather | 0c676108fd40594428f3cbdc8fde262b4b7180c6 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/nakeyfishzh/coolweather14/model/County.java | nakeyfishzh/coolweather | 0c676108fd40594428f3cbdc8fde262b4b7180c6 | [
"Apache-2.0"
] | null | null | null | 14.075472 | 44 | 0.537534 | 5,228 | package com.nakeyfishzh.coolweather14.model;
/**
* Created by walker on 15/11/17.
*/
public class County
{
private int id;
private int cityId;
private String name;
private String code;
public int getId()
{
return id;
}
public int getCityId()
{
return cityId;
}
public String getName()
{
return name;
}
public String getCode()
{
return code;
}
public void setId(int id)
{
this.id = id;
}
public void setCityId(int cityId)
{
this.cityId = cityId;
}
public void setName(String name)
{
this.name = name;
}
public void setCode(String code)
{
this.code = code;
}
}
|
3e0c52204dd95aa8c43b5ee6e601ef681c51c9a2 | 1,220 | java | Java | it.ismb.pert.pwal.core/it.ismb.pert.pwal.core.api/src/main/java/it/ismb/pertlab/pwal/api/events/base/PWALBaseEvent.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | it.ismb.pert.pwal.core/it.ismb.pert.pwal.core.api/src/main/java/it/ismb/pertlab/pwal/api/events/base/PWALBaseEvent.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | it.ismb.pert.pwal.core/it.ismb.pert.pwal.core.api/src/main/java/it/ismb/pertlab/pwal/api/events/base/PWALBaseEvent.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | 20.333333 | 74 | 0.621311 | 5,229 | package it.ismb.pertlab.pwal.api.events.base;
import it.ismb.pertlab.pwal.api.devices.interfaces.Device;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public abstract class PWALBaseEvent // implements Event<PWALBaseEvent>
{
/**
* Event time stamp in UTC format
*/
private DateTime timeStamp;
/**
* Event sender identification
*/
private String senderId;
/**
* Device who generates the event
*/
private Device sender;
public PWALBaseEvent(String timeStamp, String senderId, Device sender)
{
this.timeStamp = new DateTime(timeStamp, DateTimeZone.UTC);
this.senderId = senderId;
this.sender = sender;
}
public DateTime getTimeStamp()
{
return timeStamp;
}
public void setTimeStamp(DateTime timeStamp)
{
this.timeStamp = timeStamp;
}
public String getSenderId()
{
return senderId;
}
public void setSenderId(String senderId)
{
this.senderId = senderId;
}
public Device getSender()
{
return sender;
}
public void setSender(Device sender)
{
this.sender = sender;
}
}
|
3e0c523b5d58deb2edf468d73be7cc45f749e824 | 1,435 | java | Java | wan_server/src/main/java/net/wancom/graph/Graph.java | manu2504/WANCom | 8acdffb947d36fa7d7c8c78cbe9c3b06864128a6 | [
"MIT"
] | null | null | null | wan_server/src/main/java/net/wancom/graph/Graph.java | manu2504/WANCom | 8acdffb947d36fa7d7c8c78cbe9c3b06864128a6 | [
"MIT"
] | null | null | null | wan_server/src/main/java/net/wancom/graph/Graph.java | manu2504/WANCom | 8acdffb947d36fa7d7c8c78cbe9c3b06864128a6 | [
"MIT"
] | null | null | null | 23.916667 | 122 | 0.625784 | 5,230 | package net.wancom.graph;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* We have a Graph that is a set of nodes.
*
* @see {@link Node}
*
* Inspired by the implentation available at:
* https://github.com/eugenp/tutorials/blob/master/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
* authored by https://github.com/yasin3061
*/
public class Graph {
private Set<Node> nodes;
public String message; // to return info with the graph (BetterGraph.addBestNewNode uses it)
private Graph() {
this.nodes = new HashSet<>();
}
public static Graph initGraph() {
return new Graph();
}
//add node to graph
public void addNode(Node node) {
nodes.add(node);
}
//remove node from graph
public void removeNode(Node node){
nodes.remove(node);
}
// getters and setters
public Set<Node> getNodes() {
return nodes;
}
public void setNodes(Set<Node> nodes) {
this.nodes = nodes;
}
public Node findNode(String nodeName) {
return this.nodes.stream().filter(n -> nodeName.equals(n.getNodeName())).findFirst().orElse(null);
}
public void addAllNodes(List<Node> nodes) {
this.nodes = new HashSet<>(nodes);
}
public void resetCosts( ) {
for (Node node : nodes) {
node.setCost(Integer.MAX_VALUE);
}
}
}
|
3e0c528cfefe35c3e8ce705d01ca363f43c21af5 | 444 | java | Java | common-swagger/src/main/java/io/eventuate/examples/tram/ordersandcustomers/commonswagger/CommonSwaggerConfiguration.java | dartartem/eventuate-tram-reactive-examples-customers-and-orders | 026f3b2880d2900169deb53a79c3f9ddf4adcc63 | [
"Apache-2.0"
] | 407 | 2018-03-22T22:53:19.000Z | 2022-03-25T14:34:30.000Z | common-swagger/src/main/java/io/eventuate/examples/tram/ordersandcustomers/commonswagger/CommonSwaggerConfiguration.java | dartartem/eventuate-tram-reactive-examples-customers-and-orders | 026f3b2880d2900169deb53a79c3f9ddf4adcc63 | [
"Apache-2.0"
] | 35 | 2018-06-04T16:19:50.000Z | 2022-02-12T18:01:25.000Z | common-swagger/src/main/java/io/eventuate/examples/tram/ordersandcustomers/commonswagger/CommonSwaggerConfiguration.java | dartartem/eventuate-tram-reactive-examples-customers-and-orders | 026f3b2880d2900169deb53a79c3f9ddf4adcc63 | [
"Apache-2.0"
] | 218 | 2018-03-20T07:34:09.000Z | 2022-03-31T17:12:57.000Z | 31.714286 | 68 | 0.826577 | 5,231 | package io.eventuate.examples.tram.ordersandcustomers.commonswagger;
import io.eventuate.util.spring.swagger.EventuateSwaggerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CommonSwaggerConfiguration {
@Bean
public EventuateSwaggerConfig eventuateSwaggerConfig() {
return () -> "io.eventuate.examples.tram.ordersandcustomers";
}
}
|
3e0c53277b8d245334337cfe0a3e7057efd5b99b | 8,088 | java | Java | encoders/firebase-encoders-processor/src/main/java/com/google/firebase/encoders/processor/getters/GetterFactory.java | dmeng/firebase-android-sdk | 7b72c8203f1b301bd69c0f6e058facaa6d808458 | [
"Apache-2.0"
] | 12 | 2021-10-21T12:08:42.000Z | 2022-03-23T06:15:22.000Z | encoders/firebase-encoders-processor/src/main/java/com/google/firebase/encoders/processor/getters/GetterFactory.java | dmeng/firebase-android-sdk | 7b72c8203f1b301bd69c0f6e058facaa6d808458 | [
"Apache-2.0"
] | 42 | 2020-06-28T04:26:13.000Z | 2021-12-28T07:01:34.000Z | encoders/firebase-encoders-processor/src/main/java/com/google/firebase/encoders/processor/getters/GetterFactory.java | dmeng/firebase-android-sdk | 7b72c8203f1b301bd69c0f6e058facaa6d808458 | [
"Apache-2.0"
] | 2 | 2021-02-24T19:59:18.000Z | 2021-06-08T09:41:05.000Z | 38.698565 | 110 | 0.692755 | 5,232 | // Copyright 2019 Google LLC
//
// 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.firebase.encoders.processor.getters;
import com.google.firebase.encoders.annotations.Encodable;
import com.google.firebase.encoders.annotations.ExtraProperty;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.processing.Messager;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
public final class GetterFactory {
private final Types types;
private final Elements elements;
private final Messager messager;
public GetterFactory(Types types, Elements elements, Messager messager) {
this.types = types;
this.elements = elements;
this.messager = messager;
}
/** Returns all getters of a given type. */
public Set<Getter> allGetters(DeclaredType type) {
if (types.isSameType(type, elements.getTypeElement("java.lang.Object").asType())) {
return Collections.emptySet();
}
Set<Getter> result = new LinkedHashSet<>();
TypeMirror superclass = ((TypeElement) types.asElement(type)).getSuperclass();
if (!superclass.getKind().equals(TypeKind.NONE)) {
result.addAll(allGetters((DeclaredType) superclass));
}
for (ExecutableElement method :
ElementFilter.methodsIn(types.asElement(type).getEnclosedElements())) {
create(type, method).ifPresent(result::add);
}
return result;
}
private Optional<Getter> create(DeclaredType ownerType, ExecutableElement element) {
if (element.getKind() != ElementKind.METHOD
|| element.getModifiers().contains(Modifier.STATIC)
|| !element.getModifiers().contains(Modifier.PUBLIC)) {
return Optional.empty();
}
ExecutableType method = (ExecutableType) element.asType();
if (!method.getParameterTypes().isEmpty()) {
return Optional.empty();
}
if (element.getAnnotation(Encodable.Ignore.class) != null) {
return Optional.empty();
}
Optional<String> fieldName = inferName(element);
if (!fieldName.isPresent()) {
return Optional.empty();
}
TypeMirror returnType = resolveTypeArguments(ownerType, element.getReturnType());
String getterExpression = element.toString();
// Fail to compile if Maps with non-string keys are used, if/when we add support for such maps
// we should delete this.
TypeMirror map = types.erasure(elements.getTypeElement("java.util.Map").asType());
if (types.isAssignable(returnType, map)) {
TypeMirror keyType = ((DeclaredType) returnType).getTypeArguments().get(0);
if (!types.isSameType(keyType, elements.getTypeElement("java.lang.String").asType())) {
messager.printMessage(
Diagnostic.Kind.ERROR,
"Cannot encode Maps with non-String keys.",
((DeclaredType) returnType).asElement());
}
}
if (types.isAssignable(
returnType, types.erasure(elements.getTypeElement("java.util.Optional").asType()))) {
returnType = ((DeclaredType) returnType).getTypeArguments().get(0);
getterExpression = getterExpression + ".orElse(null)";
}
Encodable.Field field = element.getAnnotation(Encodable.Field.class);
return Optional.of(
Getter.create(
fieldName.get(),
inferDescriptors(element),
getterExpression,
returnType,
field != null && field.inline()));
}
private Set<AnnotationDescriptor> inferDescriptors(ExecutableElement element) {
Set<AnnotationDescriptor> annotationDescriptors = new HashSet<>();
for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
ExtraProperty extraProperty =
annotationMirror.getAnnotationType().asElement().getAnnotation(ExtraProperty.class);
if (extraProperty == null) {
continue;
}
List<AnnotationProperty> annotationValues =
annotationMirror.getElementValues().entrySet().stream()
.map(
e ->
AnnotationProperty.create(
e.getKey().getSimpleName().toString(), e.getValue()))
.collect(Collectors.toList());
annotationDescriptors.add(AnnotationDescriptor.create(annotationMirror, annotationValues));
}
return annotationDescriptors;
}
private TypeMirror resolveTypeArguments(DeclaredType ownerType, TypeMirror genericType) {
if (genericType instanceof DeclaredType) {
DeclaredType dType = (DeclaredType) genericType;
if (dType.getTypeArguments().isEmpty()) {
return genericType;
}
TypeElement genericElement = (TypeElement) dType.asElement();
List<TypeMirror> result = new ArrayList<>();
for (TypeMirror typeArgument : dType.getTypeArguments()) {
result.add(resolveTypeArguments(ownerType, typeArgument));
}
return types.getDeclaredType(genericElement, result.toArray(new TypeMirror[0]));
} else if (genericType instanceof TypeVariable) {
TypeVariable tVar = (TypeVariable) genericType;
TypeElement ownerElement = (TypeElement) ownerType.asElement();
int index = ownerElement.getTypeParameters().indexOf(tVar.asElement());
if (index == -1) {
messager.printMessage(
Diagnostic.Kind.ERROR,
String.format(
"Could not infer type of %s in %s. Is it a non-static inner class in a generic class?",
genericType, ownerType));
return genericType;
}
if (ownerType.getTypeArguments().get(index) instanceof TypeVariable) {
messager.printMessage(
Diagnostic.Kind.WARNING,
String.format(
"%s is a generic type, make sure you register encoders for types of %s that you plan to use.",
ownerType, genericType));
return genericType;
}
return resolveTypeArguments(ownerType, ownerType.getTypeArguments().get(index));
}
return genericType;
}
private static Optional<String> inferName(ExecutableElement element) {
Encodable.Field annotation = element.getAnnotation(Encodable.Field.class);
if (annotation != null && !annotation.name().isEmpty()) {
return Optional.of(annotation.name());
}
String methodName = element.getSimpleName().toString();
ExecutableType method = (ExecutableType) element.asType();
if (methodName.startsWith("is")
&& methodName.length() != 2
&& method.getReturnType().getKind() == TypeKind.BOOLEAN) {
return Optional.of(Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3));
}
if (methodName.startsWith("get")
&& methodName.length() != 3
&& method.getReturnType().getKind() != TypeKind.VOID) {
return Optional.of(Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4));
}
return Optional.empty();
}
}
|
3e0c539d54a311887a3420ea3df971485a520a60 | 12,866 | java | Java | src/net/betterpvp/osFighter/managers/Paint.java | Tomhoogstra/osFighter | cc0fba24e3d7c4b85e2ea56b033e731493397ee0 | [
"MIT"
] | 1 | 2019-02-10T19:12:54.000Z | 2019-02-10T19:12:54.000Z | src/net/betterpvp/osFighter/managers/Paint.java | Tomhoogstra/osFighter | cc0fba24e3d7c4b85e2ea56b033e731493397ee0 | [
"MIT"
] | null | null | null | src/net/betterpvp/osFighter/managers/Paint.java | Tomhoogstra/osFighter | cc0fba24e3d7c4b85e2ea56b033e731493397ee0 | [
"MIT"
] | null | null | null | 35.153005 | 132 | 0.577957 | 5,233 | package net.betterpvp.osFighter.managers;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.image.BufferedImage;
import java.beans.SimpleBeanInfo;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.imageio.ImageIO;
import net.betterpvp.osFighter.data.SessionData;
import net.betterpvp.osFighter.utilities.UtilFile;
import net.betterpvp.osFighter.utilities.UtilTime;
import org.osbot.rs07.api.map.Position;
import org.osbot.rs07.api.ui.Message;
import org.osbot.rs07.api.ui.Skill;
import org.osbot.rs07.canvas.paint.Painter;
import org.osbot.rs07.input.mouse.BotMouseListener;
import org.osbot.rs07.listener.MessageListener;
import net.betterpvp.osFighter.Fighter;
import net.betterpvp.osFighter.managers.paint.PaintObject;
import net.betterpvp.osFighter.managers.paint.SkillExperience;
import net.betterpvp.osFighter.managers.paint.objects.Label;
import net.betterpvp.osFighter.managers.paint.objects.MousePathPoint;
import net.betterpvp.osFighter.managers.paint.objects.PaintImage;
import net.betterpvp.osFighter.managers.paint.objects.UpdatingLabel;
public class Paint extends BotMouseListener implements Painter, MessageListener {
private Fighter i;
public int mined = 0;
private Point pos;
private List<PaintObject> po = new ArrayList<>();
private List<PaintObject> statLabels = new ArrayList<>();
private int mX, mY;
private long angle;
private BasicStroke cursorStroke = new BasicStroke(2);
private Color cursorColor = Color.CYAN;
private AffineTransform oldTransform;
private LinkedList<MousePathPoint> mousePath = new LinkedList<>();
private String url = "http://mykindos.me/osFighter/";
private String dir;
private PaintImage activePaint;
public Paint(Fighter i) {
this.i = i;
dir = getInstance().getDirectoryData() + "osFighter/";
SessionData data = i.getSessionData();
i.getSkills().getExperienceTracker().start(Skill.HITPOINTS);
i.getSkills().getExperienceTracker().start(Skill.ATTACK);
i.getSkills().getExperienceTracker().start(Skill.STRENGTH);
i.getSkills().getExperienceTracker().start(Skill.DEFENCE);
i.getSkills().getExperienceTracker().start(Skill.RANGED);
i.getSkills().getExperienceTracker().start(Skill.MAGIC);
i.getSkills().getExperienceTracker().start(Skill.PRAYER);
try {
data.getExpTrack().add(new SkillExperience(i, Skill.HITPOINTS, UtilFile.loadImage(dir, url, "Hitpoints.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.ATTACK, UtilFile.loadImage(dir, url,"Attack.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.STRENGTH, UtilFile.loadImage(dir, url,"Strength.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.DEFENCE, UtilFile.loadImage(dir, url, "Defence.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.RANGED, UtilFile.loadImage(dir, url, "Ranged.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.MAGIC,UtilFile.loadImage(dir, url, "Magic.png")));
data.getExpTrack().add(new SkillExperience(i, Skill.PRAYER, UtilFile.loadImage(dir, url, "Prayer.png")));
BufferedImage paintImg = UtilFile.loadImage(dir, url, "paint.png");
activePaint = new PaintImage("Active Paint", 0, i.getDisplay().getScreenHeight() - 22 - paintImg.getHeight(), paintImg);
addPaintObject(activePaint);
//addPaintObject(new PaintImage("Active Paint", 0, 309, paintImg));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadCommonLabels();
}
@Override
public void onPaint(Graphics2D g) {
drawMouse(i, g);
update();
draw(g);
if (i.isDefiningArea() || (!i.hasStarted() && i.getSessionData().getCombatAreaPositions().size() > 0)) {
g.setColor(Color.RED);
for (Position p : i.getSessionData().getCombatArea().getPositions()) {
g.drawPolygon(p.getPolygon(i.getBot()));
}
g.setColor(Color.GREEN);
if (i.getSessionData().getCombatAreaPositions().size() <= 4) {
for (Position p : i.getSessionData().getCombatAreaPositions()) {
g.drawPolygon(p.getPolygon(i.getBot()));
}
}
//g.setColor(Color.GREEN);
//g.drawPolygon(i.getSessionData().getCombatArea().getPolygon());
}
}
public void draw(Graphics2D g) {
if (paintEnabled) {
for (PaintObject p : po) {
if (p.isEnabled()) {
p.draw(g);
}
}
if (i.getSessionData().getSafeSpot() != null) {
g.setColor(Color.YELLOW);
g.drawPolygon(i.getSessionData().getSafeSpot().getPolygon(i.getBot()));
}
if (i.getSessionData().getResetPosition() != null) {
g.setColor(Color.CYAN);
g.drawPolygon(i.getSessionData().getResetPosition().getPolygon(i.getBot()));
}
if (i.getSessionData().isAFKMode() && i.getSessionData().getResetPosition() == null) {
g.setColor(Color.RED);
Font f1 = new Font("Calibri", Font.BOLD, 20);
g.setFont(f1);
g.drawString("You have not set a reset tile!", 11, 365);
g.drawString("Press F4 to set the reset tile where you are standing", 11, 385);
return;
}
if (i.getSessionData().isSafeSpotting() && i.getSessionData().getSafeSpot() == null) {
g.setColor(Color.RED);
Font f1 = new Font("Calibri", Font.BOLD, 16);
g.setFont(f1);
g.drawString("You have not set a safe spot! Press F3 to set the safe spot where you are standing", 11, 365);
return;
}
i.getSessionData().getExpTrack().sort(new Comparator<SkillExperience>() {
@Override
public int compare(SkillExperience a, SkillExperience b) {
return b.getGainedExp() - a.getGainedExp();
}
});
int x = 9;
int y = activePaint.getY() + 35;
for (SkillExperience e : i.getSessionData().getExpTrack()) {
if (e.getGainedExp() <= 0) continue;
if (x >= 260) {
x = 9;
y += 42;
}
g.drawImage(e.getResource(), x, y, null);
Font f1 = new Font("Calibri", Font.BOLD, 12);
g.setFont(f1);
g.setColor(Color.black);
g.drawString("TTL: ", x + 42, y + 10);
g.drawString("EXP / H: ", x + 42, y + 24);
g.drawString("Total: ", x + 42, y + 38);
Font f2 = new Font("Calibri", Font.PLAIN, 12);
g.setFont(f2);
g.drawString(UtilTime.totalTime((int) i.getExperienceTracker().getTimeToLevel(e.getSkill())), x + 66, y + 10);
g.drawString(NumberFormat.getNumberInstance(Locale.US).format(
i.getExperienceTracker().getGainedXPPerHour(e.getSkill())), x + 87, y + 24);
g.drawString(NumberFormat.getNumberInstance(Locale.US).format(
e.getGainedExp()) + " (" + i.getExperienceTracker().getGainedLevels(e.getSkill()) + ")", x + 75, y + 38);
x += 250;
}
}
}
public void update() {
for (PaintObject p : po) {
if (p.isEnabled()) {
p.update(this);
}
}
activePaint.setY(i.getDisplay().getScreenHeight() - 22 - activePaint.getHeight());
}
public void addPaintObject(PaintObject p) {
po.add(p);
}
public void addCommonPaintObject(PaintObject p) {
po.add(p);
statLabels.add(p);
}
public PaintObject getPaintObject(String ID) {
for (PaintObject p : po) {
if (p.getID().equals(ID)) {
return p;
}
}
return null;
}
public Point getMousePosition() {
return this.pos;
}
public Fighter getInstance() {
return this.i;
}
public void loadCommonLabels() {
int paintY = getPaintObject("Active Paint").getY();
addPaintObject(new Label("Version", 5, 15, "v" + i.getVersion()));
addPaintObject(new Label("Hotkeys", 5, 27, "Hotkeys"));
addPaintObject(new Label("F1", 5, 39, "F1: Enable Area Selection"));
addPaintObject(new Label("F2", 5, 51, "F2: Disable Area Selection"));
addPaintObject(new Label("F3", 5, 63, "F3: Set Safe Spot"));
addPaintObject(new Label("F4", 5, 75, "F4: Set Reset Position"));
addPaintObject(new UpdatingLabel("TimeRunning", 335, paintY + 27) {
@Override
public void update(Paint p) {
setY(getPaintObject("Active Paint").getY() + 27);
setText("Time Ran: " + UtilTime.totalTime((int) i.getSkills().getExperienceTracker().getElapsed(Skill.HITPOINTS)));
}
});
addPaintObject(new UpdatingLabel("Edit Settings", 335, paintY + 15, 100, 18) {
@Override
public void update(Paint p) {
setY(getPaintObject("Active Paint").getY() + 15);
setText("Edit Settings");
}
});
}
private void drawMouse(Fighter instance, Graphics2D g) {
oldTransform = g.getTransform();
mX = instance.getMouse().getPosition().x;
mY = instance.getMouse().getPosition().y;
g.setColor(Color.CYAN);
g.drawRect(mX - 1, mY + 20, 1, 25);
g.drawRect(mX - 1, mY - 45, 1, 25);
g.drawRect(mX + 20, mY - 1, 25, 1);
g.drawRect(mX - 45, mY - 1, 25, 1);
g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
//MOUSE TRAIL
while (!mousePath.isEmpty() && mousePath.peek().isUp())
mousePath.remove();
Point clientCursor = instance.getMouse().getPosition();
MousePathPoint mpp = new MousePathPoint(clientCursor.x, clientCursor.y, 300);
if (mousePath.isEmpty() || !mousePath.getLast().equals(mpp))
mousePath.add(mpp);
MousePathPoint lastPoint = null;
for (MousePathPoint a : mousePath) {
if (lastPoint != null) {
g.setColor(new Color(255, 255, 255, a.getAlpha())); //trail color
g.drawLine(a.x, a.y, lastPoint.x, lastPoint.y);
}
lastPoint = a;
}
if (mX != -1) {
g.setStroke(cursorStroke);
g.setColor(cursorColor);
g.drawLine(mX - 3, mY - 3, mX + 2, mY + 2);
g.drawLine(mX - 3, mY + 2, mX + 2, mY - 3);
g.rotate(Math.toRadians(angle += 6), mX, mY);
g.draw(new Arc2D.Double(mX - 12, mY - 12, 24, 24, 330, 60, Arc2D.OPEN));
g.draw(new Arc2D.Double(mX - 12, mY - 12, 24, 24, 151, 60, Arc2D.OPEN));
g.setTransform(oldTransform);
}
}
private boolean paintEnabled = true;
@Override
public void checkMouseEvent(MouseEvent e) {
if (getPaintObject("Edit Settings").getRectangle().contains(e.getPoint())) {
if (i.getGUI() == null) return;
i.started = false;
i.getGUI().setVisible(true);
if (!i.getBot().getScriptExecutor().isPaused()) {
e.consume();
}
} else if (getPaintObject("Active Paint").getRectangle().contains(e.getPoint())) {
if (getPaintObject("Active Paint").isEnabled()) {
getPaintObject("Active Paint").setEnabled(false);
for (PaintObject p : statLabels) {
p.setEnabled(false);
}
paintEnabled = false;
} else {
getPaintObject("Active Paint").setEnabled(true);
for (PaintObject p : statLabels) {
p.setEnabled(true);
}
paintEnabled = true;
}
if (!i.getBot().getScriptExecutor().isPaused()) {
e.consume();
}
}
}
@Override
public void onMessage(Message arg0) throws InterruptedException {
}
}
|
3e0c542bdc3c33218c299a0f9853bf164cf84f35 | 1,929 | java | Java | security/src/main/java/org/xipki/security/pkcs11/emulator/PKCS11Exception.java | feiyangqyw/xipki | adf5dab9d2bf7311187dc77a70c739ed55778bc1 | [
"Apache-2.0"
] | 1 | 2019-03-12T03:13:21.000Z | 2019-03-12T03:13:21.000Z | security/src/main/java/org/xipki/security/pkcs11/emulator/PKCS11Exception.java | feiyangqyw/xipki | adf5dab9d2bf7311187dc77a70c739ed55778bc1 | [
"Apache-2.0"
] | null | null | null | security/src/main/java/org/xipki/security/pkcs11/emulator/PKCS11Exception.java | feiyangqyw/xipki | adf5dab9d2bf7311187dc77a70c739ed55778bc1 | [
"Apache-2.0"
] | null | null | null | 25.381579 | 75 | 0.689476 | 5,234 | /*
*
* Copyright (c) 2013 - 2019 Lijun Liao
*
* 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.xipki.security.pkcs11.emulator;
import iaik.pkcs.pkcs11.constants.Functions;
/**
* TODO.
* @author Lijun Liao
* @since 4.0.0
*/
// CHECKSTYLE:SKIP
public class PKCS11Exception extends Exception {
private static final long serialVersionUID = -5193259612747392211L;
/**
* The code of the error which was the reason for this exception.
*/
private long errorCode;
private String errorDescription;
/**
* Constructor taking the error code as defined for the CKR_* constants
* in PKCS#11.
*
* @param errorCode
* The PKCS#11 error code (return value).
*/
public PKCS11Exception(long errorCode) {
this.errorCode = errorCode;
this.errorDescription = Functions.errorCodeToString(errorCode);
}
/**
* This method gets the corresponding text error message from
* a property file. If this file is not available, it returns the error
* code as a hex-string.
*
* @return The message or the error code; e.g. "CKR_DEVICE_ERROR" or
* "0x00000030".
* @preconditions
* @postconditions (result <> null)
*/
public String getMessage() {
return errorDescription;
}
/**
* Returns the PKCS#11 error code.
*
* @return The error code; e.g. 0x00000030.
*/
public long getErrorCode() {
return errorCode;
}
}
|
3e0c553fc20b309af265b2a376f5d124785cf25a | 1,262 | java | Java | ddcat-modules/ddcat-system/src/main/java/com/ddcat/system/service/impl/SysDictServiceImpl.java | dd-cat/ddcat-cloud | 4d17cb4700a6648afc242ac774644e94f77236c8 | [
"AFL-3.0"
] | 2 | 2021-06-21T08:40:00.000Z | 2021-06-26T09:45:07.000Z | ddcat-modules/ddcat-system/src/main/java/com/ddcat/system/service/impl/SysDictServiceImpl.java | dd-cat/ddcat-cloud | 4d17cb4700a6648afc242ac774644e94f77236c8 | [
"AFL-3.0"
] | null | null | null | ddcat-modules/ddcat-system/src/main/java/com/ddcat/system/service/impl/SysDictServiceImpl.java | dd-cat/ddcat-cloud | 4d17cb4700a6648afc242ac774644e94f77236c8 | [
"AFL-3.0"
] | 1 | 2021-06-26T02:45:33.000Z | 2021-06-26T02:45:33.000Z | 32.358974 | 105 | 0.775753 | 5,235 | package com.ddcat.system.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddcat.api.entity.SysDict;
import com.ddcat.api.entity.SysDictItem;
import com.ddcat.core.constant.CacheConstants;
import com.ddcat.system.mapper.SysDictItemMapper;
import com.ddcat.system.mapper.SysDictMapper;
import com.ddcat.system.service.SysDictService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author dd-cat
*/
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {
private final SysDictItemMapper dictItemMapper;
/**
* 根据ID 删除字典
*
* @param id 字典ID
* @return /
*/
@Override
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
@Transactional(rollbackFor = Exception.class)
public int removeDict(Integer id) {
baseMapper.deleteById(id);
return dictItemMapper.delete(Wrappers.<SysDictItem>lambdaQuery().eq(SysDictItem::getDictId, id));
}
}
|
3e0c55e0d3f4c16ec359e59586697b0aacb22bad | 770 | java | Java | src/main/java/br/ufmg/dcc/nanocomp/ctl/CtlVector.java | henriquenicolas1/ctl-parser | 52dcf2d59c48fe1caa416316abf789b45f05caa7 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/ufmg/dcc/nanocomp/ctl/CtlVector.java | henriquenicolas1/ctl-parser | 52dcf2d59c48fe1caa416316abf789b45f05caa7 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/ufmg/dcc/nanocomp/ctl/CtlVector.java | henriquenicolas1/ctl-parser | 52dcf2d59c48fe1caa416316abf789b45f05caa7 | [
"Apache-2.0"
] | null | null | null | 20.810811 | 78 | 0.715584 | 5,236 | package br.ufmg.dcc.nanocomp.ctl;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public class CtlVector extends CtlObject implements Iterable<CtlVariable<?>> {
private static final long serialVersionUID = 1L;
private List<CtlVariable<?>> values;
public CtlVector(List<CtlVariable<?>> values) {
this.values = values;
}
public CtlVariable<?> get(int index) {
return this.values.get(index);
}
@Override
public Iterator<CtlVariable<?>> iterator() {
return this.values.iterator();
}
@Override
public void write(Appendable appendable) throws IOException {
appendable.append("(vector");
for(CtlVariable<?> value : values) {
appendable.append(" ");
value.write(appendable);
}
appendable.append(")");
}
}
|
3e0c564f47ce4a7931ab30f7e018987f7055a3f4 | 23,777 | java | Java | http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClient.java | sheeraz21/aws-sdk-java-v2 | 6411db36f1ef8240dcfeb71b7d9f10799631309f | [
"Apache-2.0"
] | 1 | 2020-10-16T15:36:06.000Z | 2020-10-16T15:36:06.000Z | http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClient.java | sheeraz21/aws-sdk-java-v2 | 6411db36f1ef8240dcfeb71b7d9f10799631309f | [
"Apache-2.0"
] | 41 | 2019-07-17T18:39:38.000Z | 2019-08-15T22:51:05.000Z | http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClient.java | hitesh0901/aws-sdk-java-v2 | c615fbfaf1733944fa6d8dcbc8350d70e894b979 | [
"Apache-2.0"
] | null | null | null | 45.117647 | 128 | 0.681541 | 5,237 | /*
* Copyright 2010-2019 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 software.amazon.awssdk.http.nio.netty;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_CONNECTIONS;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.READ_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.WRITE_TIMEOUT;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslProvider;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.internal.AwaitCloseChannelPoolMap;
import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration;
import software.amazon.awssdk.http.nio.netty.internal.NettyRequestExecutor;
import software.amazon.awssdk.http.nio.netty.internal.NonManagedEventLoopGroup;
import software.amazon.awssdk.http.nio.netty.internal.RequestContext;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelOptions;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPoolMap;
import software.amazon.awssdk.http.nio.netty.internal.SharedSdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Either;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkAsyncHttpClient} that uses a Netty non-blocking HTTP client to communicate with the service.
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class NettyNioAsyncHttpClient implements SdkAsyncHttpClient {
private static final String CLIENT_NAME = "NettyNio";
private static final Logger log = LoggerFactory.getLogger(NettyNioAsyncHttpClient.class);
private static final long MAX_STREAMS_ALLOWED = 4294967295L; // unsigned 32-bit, 2^32 -1
private final SdkEventLoopGroup sdkEventLoopGroup;
private final SdkChannelPoolMap<URI, ? extends ChannelPool> pools;
private final NettyConfiguration configuration;
private NettyNioAsyncHttpClient(DefaultBuilder builder, AttributeMap serviceDefaultsMap) {
this.configuration = new NettyConfiguration(serviceDefaultsMap);
Protocol protocol = serviceDefaultsMap.get(SdkHttpConfigurationOption.PROTOCOL);
long maxStreams = builder.maxHttp2Streams == null ? MAX_STREAMS_ALLOWED : builder.maxHttp2Streams;
this.sdkEventLoopGroup = eventLoopGroup(builder);
this.pools = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(builder.sdkChannelOptions)
.configuration(configuration)
.protocol(protocol)
.maxStreams(maxStreams)
.sdkEventLoopGroup(sdkEventLoopGroup)
.sslProvider(resolveSslProvider(builder))
.build();
}
@SdkTestInternalApi
NettyNioAsyncHttpClient(SdkEventLoopGroup sdkEventLoopGroup,
SdkChannelPoolMap<URI, ? extends ChannelPool> pools,
NettyConfiguration configuration) {
this.sdkEventLoopGroup = sdkEventLoopGroup;
this.pools = pools;
this.configuration = configuration;
}
@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest request) {
RequestContext ctx = createRequestContext(request);
return new NettyRequestExecutor(ctx).execute();
}
public static Builder builder() {
return new DefaultBuilder();
}
private RequestContext createRequestContext(AsyncExecuteRequest request) {
ChannelPool pool = pools.get(poolKey(request.request()));
return new RequestContext(pool, sdkEventLoopGroup.eventLoopGroup(), request, configuration);
}
private SdkEventLoopGroup eventLoopGroup(DefaultBuilder builder) {
Validate.isTrue(builder.eventLoopGroup == null || builder.eventLoopGroupBuilder == null,
"The eventLoopGroup and the eventLoopGroupFactory can't both be configured.");
return Either.fromNullable(builder.eventLoopGroup, builder.eventLoopGroupBuilder)
.map(e -> e.map(this::nonManagedEventLoopGroup, SdkEventLoopGroup.Builder::build))
.orElseGet(SharedSdkEventLoopGroup::get);
}
private static URI poolKey(SdkHttpRequest sdkRequest) {
return invokeSafely(() -> new URI(sdkRequest.protocol(), null, sdkRequest.host(),
sdkRequest.port(), null, null, null));
}
private SslProvider resolveSslProvider(DefaultBuilder builder) {
if (builder.sslProvider != null) {
return builder.sslProvider;
}
return SslContext.defaultClientProvider();
}
private SdkEventLoopGroup nonManagedEventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
return SdkEventLoopGroup.create(new NonManagedEventLoopGroup(eventLoopGroup.eventLoopGroup()),
eventLoopGroup.channelFactory());
}
@Override
public void close() {
runAndLogError(log, "Unable to close channel pools", pools::close);
runAndLogError(log, "Unable to shutdown event loop", () ->
closeEventLoopUninterruptibly(sdkEventLoopGroup.eventLoopGroup()));
}
private void closeEventLoopUninterruptibly(EventLoopGroup eventLoopGroup) throws ExecutionException {
try {
eventLoopGroup.shutdownGracefully(EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS,
EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS,
TimeUnit.SECONDS)
.get(EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (TimeoutException e) {
log.error(String.format("Shutting down Netty EventLoopGroup did not complete within %s seconds",
EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS));
}
}
@Override
public String clientName() {
return CLIENT_NAME;
}
/**
* Builder that allows configuration of the Netty NIO HTTP implementation. Use {@link #builder()} to configure and construct
* a Netty HTTP client.
*/
public interface Builder extends SdkAsyncHttpClient.Builder<NettyNioAsyncHttpClient.Builder> {
/**
* Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections. For HTTP/2
* the number of connections that will be used depends on the max streams allowed per connection.
*
* <p>
* If the maximum number of concurrent requests is exceeded they may be queued in the HTTP client (see
* {@link #maxPendingConnectionAcquires(Integer)}</p>) and can cause increased latencies. If the client is overloaded
* enough such that the pending connection queue fills up, subsequent requests may be rejected or time out
* (see {@link #connectionAcquisitionTimeout(Duration)}).
* </p>
*
* @param maxConcurrency New value for max concurrency.
* @return This builder for method chaining.
*/
Builder maxConcurrency(Integer maxConcurrency);
/**
* The maximum number of pending acquires allowed. Once this exceeds, acquire tries will be failed.
*
* @param maxPendingAcquires Max number of pending acquires
* @return This builder for method chaining.
*/
Builder maxPendingConnectionAcquires(Integer maxPendingAcquires);
/**
* The amount of time to wait for a read on a socket before an exception is thrown.
* Specify {@code Duration.ZERO} to disable.
*
* @param readTimeout timeout duration
* @return this builder for method chaining.
*/
Builder readTimeout(Duration readTimeout);
/**
* The amount of time to wait for a write on a socket before an exception is thrown.
* Specify {@code Duration.ZERO} to disable.
*
* @param writeTimeout timeout duration
* @return this builder for method chaining.
*/
Builder writeTimeout(Duration writeTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out.
*
* @param timeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionTimeout(Duration timeout);
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout);
/**
* The maximum amount of time that a connection should be allowed to remain open, regardless of usage frequency.
*
* Unlike {@link #readTimeout(Duration)} and {@link #writeTimeout(Duration)}, this will never close a connection that
* is currently in use, so long-lived connections may remain open longer than this time. In particular, an HTTP/2
* connection won't be closed as long as there is at least one stream active on the connection.
*/
Builder connectionTimeToLive(Duration connectionTimeToLive);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle. Currently has no
* effect if {@link #useIdleConnectionReaper(Boolean)} is false.
*
* Unlike {@link #readTimeout(Duration)} and {@link #writeTimeout(Duration)}, this will never close a connection that
* is currently in use, so long-lived connections may remain open longer than this time.
*/
Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout);
/**
* Configure whether the idle connections in the connection pool should be closed.
* <p>
* When enabled, connections left idling for longer than {@link #connectionMaxIdleTime(Duration)} will be
* closed. This will not close connections currently in use. By default, this is enabled.
*/
Builder useIdleConnectionReaper(Boolean useConnectionReaper);
/**
* Sets the {@link SdkEventLoopGroup} to use for the Netty HTTP client. This event loop group may be shared
* across multiple HTTP clients for better resource and thread utilization. The preferred way to create
* an {@link EventLoopGroup} is by using the {@link SdkEventLoopGroup#builder()} method which will choose the
* optimal implementation per the platform.
*
* <p>The {@link EventLoopGroup} <b>MUST</b> be closed by the caller when it is ready to
* be disposed. The SDK will not close the {@link EventLoopGroup} when the HTTP client is closed. See
* {@link EventLoopGroup#shutdownGracefully()} to properly close the event loop group.</p>
*
* <p>This configuration method is only recommended when you wish to share an {@link EventLoopGroup}
* with multiple clients. If you do not need to share the group it is recommended to use
* {@link #eventLoopGroupBuilder(SdkEventLoopGroup.Builder)} as the SDK will handle its cleanup when
* the HTTP client is closed.</p>
*
* @param eventLoopGroup Netty {@link SdkEventLoopGroup} to use.
* @return This builder for method chaining.
* @see SdkEventLoopGroup
*/
Builder eventLoopGroup(SdkEventLoopGroup eventLoopGroup);
/**
* Sets the {@link SdkEventLoopGroup.Builder} which will be used to create the {@link SdkEventLoopGroup} for the Netty
* HTTP client. This allows for custom configuration of the Netty {@link EventLoopGroup}.
*
* <p>The {@link EventLoopGroup} created by the builder is managed by the SDK and will be shutdown
* when the HTTP client is closed.</p>
*
* <p>This is the preferred configuration method when you just want to customize the {@link EventLoopGroup}
* but not share it across multiple HTTP clients. If you do wish to share an {@link EventLoopGroup}, see
* {@link #eventLoopGroup(SdkEventLoopGroup)}</p>
*
* @param eventLoopGroupBuilder {@link SdkEventLoopGroup.Builder} to use.
* @return This builder for method chaining.
* @see SdkEventLoopGroup.Builder
*/
Builder eventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder);
/**
* Sets the HTTP protocol to use (i.e. HTTP/1.1 or HTTP/2). Not all services support HTTP/2.
*
* @param protocol Protocol to use.
* @return This builder for method chaining.
*/
Builder protocol(Protocol protocol);
/**
* Configures additional {@link ChannelOption} which will be used to create Netty Http client. This allows custom
* configuration for Netty.
*
* <p>
* If a {@link ChannelOption} was previously configured, the old value is replaced.
*
* @param channelOption {@link ChannelOption} to set
* @param value See {@link ChannelOption} to find the type of value for each option
* @return This builder for method chaining.
*/
Builder putChannelOption(ChannelOption channelOption, Object value);
/**
* Sets the max number of concurrent streams for an HTTP/2 connection. This setting is only respected when the HTTP/2
* protocol is used.
*
* <p>Note that this cannot exceed the value of the MAX_CONCURRENT_STREAMS setting returned by the service. If it
* does the service setting is used instead.</p>
*
* @param maxHttp2Streams Max concurrent HTTP/2 streams per connection.
* @return This builder for method chaining.
*/
Builder maxHttp2Streams(Integer maxHttp2Streams);
/**
* Sets the {@link SslProvider} to be used in the Netty client.
*
* <p>If not configured, {@link SslContext#defaultClientProvider()} will be used to determine the SslProvider.
*
* <p>Note that you might need to add other dependencies if not using JDK's default Ssl Provider.
* See https://netty.io/wiki/requirements-for-4.x.html#transport-security-tls
*
* @param sslProvider the SslProvider
* @return the builder of the method chaining.
*/
Builder sslProvider(SslProvider sslProvider);
}
/**
* Factory that allows more advanced configuration of the Netty NIO HTTP implementation. Use {@link #builder()} to
* configure and construct an immutable instance of the factory.
*/
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private SdkChannelOptions sdkChannelOptions = new SdkChannelOptions();
private SdkEventLoopGroup eventLoopGroup;
private SdkEventLoopGroup.Builder eventLoopGroupBuilder;
private Integer maxHttp2Streams;
private SslProvider sslProvider;
private DefaultBuilder() {
}
@Override
public Builder maxConcurrency(Integer maxConcurrency) {
standardOptions.put(MAX_CONNECTIONS, maxConcurrency);
return this;
}
public void setMaxConcurrency(Integer maxConnectionsPerEndpoint) {
maxConcurrency(maxConnectionsPerEndpoint);
}
@Override
public Builder maxPendingConnectionAcquires(Integer maxPendingAcquires) {
standardOptions.put(MAX_PENDING_CONNECTION_ACQUIRES, maxPendingAcquires);
return this;
}
public void setMaxPendingConnectionAcquires(Integer maxPendingAcquires) {
maxPendingConnectionAcquires(maxPendingAcquires);
}
@Override
public Builder readTimeout(Duration readTimeout) {
Validate.isNotNegative(readTimeout, "readTimeout");
standardOptions.put(READ_TIMEOUT, readTimeout);
return this;
}
public void setReadTimeout(Duration readTimeout) {
readTimeout(readTimeout);
}
@Override
public Builder writeTimeout(Duration writeTimeout) {
Validate.isNotNegative(writeTimeout, "writeTimeout");
standardOptions.put(WRITE_TIMEOUT, writeTimeout);
return this;
}
public void setWriteTimeout(Duration writeTimeout) {
writeTimeout(writeTimeout);
}
@Override
public Builder connectionTimeout(Duration timeout) {
Validate.isPositive(timeout, "connectionTimeout");
standardOptions.put(CONNECTION_TIMEOUT, timeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
@Override
public Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
Validate.isPositive(connectionAcquisitionTimeout, "connectionAcquisitionTimeout");
standardOptions.put(CONNECTION_ACQUIRE_TIMEOUT, connectionAcquisitionTimeout);
return this;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
connectionAcquisitionTimeout(connectionAcquisitionTimeout);
}
@Override
public Builder connectionTimeToLive(Duration connectionTimeToLive) {
Validate.isPositive(connectionTimeToLive, "connectionTimeToLive");
standardOptions.put(CONNECTION_TIME_TO_LIVE, connectionTimeToLive);
return this;
}
public void setConnectionTimeToLive(Duration connectionTimeToLive) {
connectionTimeToLive(connectionTimeToLive);
}
@Override
public Builder connectionMaxIdleTime(Duration connectionMaxIdleTime) {
Validate.isPositive(connectionMaxIdleTime, "connectionMaxIdleTime");
standardOptions.put(CONNECTION_MAX_IDLE_TIMEOUT, connectionMaxIdleTime);
return this;
}
public void setConnectionMaxIdleTime(Duration connectionMaxIdleTime) {
connectionMaxIdleTime(connectionMaxIdleTime);
}
@Override
public Builder useIdleConnectionReaper(Boolean useIdleConnectionReaper) {
standardOptions.put(REAP_IDLE_CONNECTIONS, useIdleConnectionReaper);
return this;
}
public void setUseIdleConnectionReaper(Boolean useIdleConnectionReaper) {
useIdleConnectionReaper(useIdleConnectionReaper);
}
@Override
public Builder eventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
this.eventLoopGroup = eventLoopGroup;
return this;
}
public void setEventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
eventLoopGroup(eventLoopGroup);
}
@Override
public Builder eventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder) {
this.eventLoopGroupBuilder = eventLoopGroupBuilder;
return this;
}
public void setEventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder) {
eventLoopGroupBuilder(eventLoopGroupBuilder);
}
@Override
public Builder protocol(Protocol protocol) {
standardOptions.put(SdkHttpConfigurationOption.PROTOCOL, protocol);
return this;
}
public void setProtocol(Protocol protocol) {
protocol(protocol);
}
@Override
public Builder putChannelOption(ChannelOption channelOption, Object value) {
this.sdkChannelOptions.putOption(channelOption, value);
return this;
}
@Override
public Builder maxHttp2Streams(Integer maxHttp2Streams) {
this.maxHttp2Streams = maxHttp2Streams;
return this;
}
public void setMaxHttp2Streams(Integer maxHttp2Streams) {
maxHttp2Streams(maxHttp2Streams);
}
@Override
public Builder sslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider;
return this;
}
public void setSslProvider(SslProvider sslProvider) {
sslProvider(sslProvider);
}
@Override
public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
return new NettyNioAsyncHttpClient(this, standardOptions.build()
.merge(serviceDefaults)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
}
}
|
3e0c5712c39760a1694dfb7daa432e0f012c3c2c | 3,050 | java | Java | iis-wf/iis-wf-affmatching/src/test/java/eu/dnetlib/iis/wf/affmatching/bucket/projectorg/read/DocumentOrganizationFetcherTest.java | johnfouf/iis | c27398cfa71a60af4932b4d6a12f8d21429578a2 | [
"Apache-2.0"
] | 20 | 2015-09-19T21:17:23.000Z | 2022-03-01T10:37:59.000Z | iis-wf/iis-wf-affmatching/src/test/java/eu/dnetlib/iis/wf/affmatching/bucket/projectorg/read/DocumentOrganizationFetcherTest.java | johnfouf/iis | c27398cfa71a60af4932b4d6a12f8d21429578a2 | [
"Apache-2.0"
] | 1,054 | 2015-09-11T06:51:27.000Z | 2022-03-30T09:46:54.000Z | iis-wf/iis-wf-affmatching/src/test/java/eu/dnetlib/iis/wf/affmatching/bucket/projectorg/read/DocumentOrganizationFetcherTest.java | LSmyrnaios/iis | 9a6a5e0eeafb1df0067b725d95fd36b1dc8c2e11 | [
"Apache-2.0"
] | 80 | 2015-12-09T12:41:52.000Z | 2022-02-16T11:46:42.000Z | 33.516484 | 156 | 0.744262 | 5,238 | package eu.dnetlib.iis.wf.affmatching.bucket.projectorg.read;
import eu.dnetlib.iis.wf.affmatching.bucket.projectorg.model.AffMatchDocumentOrganization;
import eu.dnetlib.iis.wf.affmatching.bucket.projectorg.model.AffMatchDocumentProject;
import eu.dnetlib.iis.wf.affmatching.bucket.projectorg.model.AffMatchProjectOrganization;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author madryk
*/
@ExtendWith(MockitoExtension.class)
public class DocumentOrganizationFetcherTest {
@InjectMocks
private DocumentOrganizationFetcher documentOrganizationFetcher = new DocumentOrganizationFetcher();
@Mock
private ProjectOrganizationReader projectOrganizationReader;
@Mock
private DocumentProjectFetcher documentProjectFetcher;
@Mock
private DocumentOrganizationCombiner documentOrganizationCombiner;
private Float docProjConfidenceLevelThreshold = 0.8f;
@Mock
private JavaSparkContext sc;
private String projOrgPath = "/input/proj_org";
@Mock
private JavaRDD<AffMatchDocumentProject> documentProject;
@Mock
private JavaRDD<AffMatchProjectOrganization> projectOrganization;
@Mock
private JavaRDD<AffMatchDocumentOrganization> documentOrganizations;
@BeforeEach
public void setup() {
documentOrganizationFetcher.setDocProjConfidenceLevelThreshold(docProjConfidenceLevelThreshold);
documentOrganizationFetcher.setProjOrgPath(projOrgPath);
}
//------------------------ TESTS --------------------------
@Test
public void fetchDocumentOrganizations() {
// given
when(documentProjectFetcher.fetchDocumentProjects()).thenReturn(documentProject);
when(projectOrganizationReader.readProjectOrganizations(sc, projOrgPath)).thenReturn(projectOrganization);
when(documentOrganizationCombiner.combine(documentProject, projectOrganization, docProjConfidenceLevelThreshold)).thenReturn(documentOrganizations);
// execute
JavaRDD<AffMatchDocumentOrganization> retDocumentOrganizations = documentOrganizationFetcher.fetchDocumentOrganizations();
// assert
assertSame(retDocumentOrganizations, documentOrganizations);
verify(documentProjectFetcher).fetchDocumentProjects();
verify(projectOrganizationReader).readProjectOrganizations(sc, projOrgPath);
verify(documentOrganizationCombiner).combine(documentProject, projectOrganization, docProjConfidenceLevelThreshold);
}
}
|
3e0c571e089539467443b44dadd64b2d489b02a4 | 1,751 | java | Java | Skizzle/net/minecraft/client/renderer/GLAllocation.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 3 | 2022-02-28T17:34:51.000Z | 2022-03-06T21:55:16.000Z | Skizzle/net/minecraft/client/renderer/GLAllocation.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | Skizzle/net/minecraft/client/renderer/GLAllocation.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | null | null | null | 32.425926 | 146 | 0.680754 | 5,239 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* org.lwjgl.opengl.GL11
* org.lwjgl.util.glu.GLU
*/
package net.minecraft.client.renderer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
public class GLAllocation {
private static final String __OBFID = "CL_00000630";
public static synchronized int generateDisplayLists(int p_74526_0_) {
int var1 = GL11.glGenLists((int)p_74526_0_);
if (var1 == 0) {
int var2 = GL11.glGetError();
String var3 = "No error code reported";
if (var2 != 0) {
var3 = GLU.gluErrorString((int)var2);
}
throw new IllegalStateException("glGenLists returned an ID of 0 for a count of " + p_74526_0_ + ", GL error (" + var2 + "): " + var3);
}
return var1;
}
public static synchronized void func_178874_a(int p_178874_0_, int p_178874_1_) {
GL11.glDeleteLists((int)p_178874_0_, (int)p_178874_1_);
}
public static synchronized void deleteDisplayLists(int p_74523_0_) {
GL11.glDeleteLists((int)p_74523_0_, (int)1);
}
public static synchronized ByteBuffer createDirectByteBuffer(int p_74524_0_) {
return ByteBuffer.allocateDirect(p_74524_0_).order(ByteOrder.nativeOrder());
}
public static IntBuffer createDirectIntBuffer(int p_74527_0_) {
return GLAllocation.createDirectByteBuffer(p_74527_0_ << 2).asIntBuffer();
}
public static FloatBuffer createDirectFloatBuffer(int p_74529_0_) {
return GLAllocation.createDirectByteBuffer(p_74529_0_ << 2).asFloatBuffer();
}
}
|
3e0c575fec60f73b38ba4b2d3c247acc5d08729f | 82 | java | Java | terasoluna-batch/src/main/java/jp/terasoluna/fw/batch/executor/concurrent/package-info.java | syama0731/batch3 | a197da2865aa015f37bec5274e479c8d153b0ba6 | [
"Apache-2.0"
] | null | null | null | terasoluna-batch/src/main/java/jp/terasoluna/fw/batch/executor/concurrent/package-info.java | syama0731/batch3 | a197da2865aa015f37bec5274e479c8d153b0ba6 | [
"Apache-2.0"
] | null | null | null | terasoluna-batch/src/main/java/jp/terasoluna/fw/batch/executor/concurrent/package-info.java | syama0731/batch3 | a197da2865aa015f37bec5274e479c8d153b0ba6 | [
"Apache-2.0"
] | null | null | null | 20.5 | 51 | 0.719512 | 5,240 | /**
* エグゼキュータ関連 非同期処理用
*/
package jp.terasoluna.fw.batch.executor.concurrent; |
3e0c57f51984b7f61b84007fdf8f76749a60597b | 968 | java | Java | src/main/java/SymbolicRexNode/RexNodeBase.java | hiramahmood/spes | 79f77bd7500a3f361dd03eae36b61cdbdfd1edf4 | [
"Apache-2.0"
] | 13 | 2021-01-06T06:17:54.000Z | 2022-03-23T02:50:52.000Z | src/main/java/SymbolicRexNode/RexNodeBase.java | hiramahmood/spes | 79f77bd7500a3f361dd03eae36b61cdbdfd1edf4 | [
"Apache-2.0"
] | 1 | 2022-01-14T00:57:20.000Z | 2022-01-14T01:13:55.000Z | src/main/java/SymbolicRexNode/RexNodeBase.java | hiramahmood/spes | 79f77bd7500a3f361dd03eae36b61cdbdfd1edf4 | [
"Apache-2.0"
] | 7 | 2021-03-20T07:32:36.000Z | 2022-03-23T07:53:33.000Z | 27.657143 | 85 | 0.713843 | 5,241 | package SymbolicRexNode;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
import com.microsoft.z3.Expr;
import org.apache.calcite.rex.RexNode;
import java.util.ArrayList;
import java.util.List;
public abstract class RexNodeBase {
protected Context z3Context;
protected SymbolicColumn output;
protected List<SymbolicColumn> inputs;
protected List<BoolExpr> assignConstraints;
public RexNodeBase(List<SymbolicColumn> inputs, RexNode node, Context z3Context){
this.inputs = inputs;
this.z3Context = z3Context;
this.assignConstraints = new ArrayList<>();
}
public SymbolicColumn getOutput(){
return this.output;
}
public Expr getOutputValue(){
return this.output.getSymbolicValue();
}
public BoolExpr getOutputNull(){
return this.output.getSymbolicNull();
}
public List<BoolExpr> getAssignConstrains(){
return this.assignConstraints;
}
}
|
3e0c588241da03d09d659a71ee8217577d5466c5 | 1,523 | java | Java | Dubbo-in-action/Demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiConsumerMockResult.java | lmmarisej/dubbo-source-code-read | bb4e7c12fbddf21a76891d780fa2c7008fa912c0 | [
"Apache-2.0"
] | null | null | null | Dubbo-in-action/Demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiConsumerMockResult.java | lmmarisej/dubbo-source-code-read | bb4e7c12fbddf21a76891d780fa2c7008fa912c0 | [
"Apache-2.0"
] | null | null | null | Dubbo-in-action/Demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiConsumerMockResult.java | lmmarisej/dubbo-source-code-read | bb4e7c12fbddf21a76891d780fa2c7008fa912c0 | [
"Apache-2.0"
] | null | null | null | 50.766667 | 128 | 0.699934 | 5,242 | package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
public class APiConsumerMockResult {
public static void mockResult(String type) {
// (1)获取服务注册中心工厂
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
// (2)根据zk地址,获取具体的zk注册中心的客户端实例
Registry registry2 = registryFactory.getRegistry(URL.valueOf("zookeeper://127.0.0.1:2181"));
// directory.subscribe(subscribeUrl.addParameter(CATEGORY_KEY,
// PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY));
// (3)注册降级方案到zk
registry2.register(URL.valueOf("override://0.0.0.0/com.books.dubbo.demo.api.GreetingService?category=configurators&" +
"dynamic=false&application=first-dubbo-consumer&mock=" + type + ":return+null&group=dubbo&version=1.0.0"));
//(4)取消配置
registry2.unregister(URL.valueOf("override://0.0.0.0/com.books.dubbo.demo.api.GreetingService?category=configurators&" +
"dynamic=false&application=first-dubbo-consumer&mock=" + type + ":return+null&group=dubbo&version=1.0.0"));
}
public static void main(String[] args) throws InterruptedException {
// mock=force:result+null;
mockResult("force");
// mock=fail:result+null;
mockResult("fail");
}
} |
3e0c58ee7a37efb72d124571169baf5744975fe7 | 845 | java | Java | elza/elza-core/src/main/java/cz/tacr/elza/packageimport/xml/RelationTypes.java | elzasw/elza | 5c9751f8b7366e8090b709bbcea3d085848125b6 | [
"Apache-2.0"
] | null | null | null | elza/elza-core/src/main/java/cz/tacr/elza/packageimport/xml/RelationTypes.java | elzasw/elza | 5c9751f8b7366e8090b709bbcea3d085848125b6 | [
"Apache-2.0"
] | null | null | null | elza/elza-core/src/main/java/cz/tacr/elza/packageimport/xml/RelationTypes.java | elzasw/elza | 5c9751f8b7366e8090b709bbcea3d085848125b6 | [
"Apache-2.0"
] | 1 | 2022-01-09T12:21:31.000Z | 2022-01-09T12:21:31.000Z | 25.606061 | 74 | 0.745562 | 5,243 | package cz.tacr.elza.packageimport.xml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.util.List;
/**
* VO typ vztahu - seznam.
*
* @author Martin Šlapa
* @since 21.11.2016
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "relation-types")
@XmlType(name = "relation-types")
public class RelationTypes {
@XmlElement(name = "relation-type", required = true)
private List<RelationType> relationTypes;
public List<RelationType> getRelationTypes() {
return relationTypes;
}
public void setRelationTypes(final List<RelationType> relationTypes) {
this.relationTypes = relationTypes;
}
}
|
3e0c592d6f47fb00e7982b536c5e06eae9566303 | 814 | java | Java | src/main/java/it/polimi/ingsw/ps14/model/bonus/BonusMainAction.java | pietroferretti/counciloffour | 8f55dc3e80a1c45690fd506a29c39c901287c823 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/polimi/ingsw/ps14/model/bonus/BonusMainAction.java | pietroferretti/counciloffour | 8f55dc3e80a1c45690fd506a29c39c901287c823 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/polimi/ingsw/ps14/model/bonus/BonusMainAction.java | pietroferretti/counciloffour | 8f55dc3e80a1c45690fd506a29c39c901287c823 | [
"Apache-2.0"
] | null | null | null | 21.421053 | 77 | 0.690418 | 5,244 | package it.polimi.ingsw.ps14.model.bonus;
import it.polimi.ingsw.ps14.model.Model;
import it.polimi.ingsw.ps14.model.Player;
public class BonusMainAction implements Bonus {
/**
*
*/
private static final long serialVersionUID = 6259525072078835164L;
private final int quantity;
public BonusMainAction(int quantity) {
if (quantity < 1)
throw new IllegalArgumentException("Impossible quantity for this bonus");
this.quantity = quantity;
}
@Override
public void useBonus(Player player, Model model) {
for (int i = 0; i < quantity; i++) {
model.incrementAdditionalMainsToDo();
}
}
@Override
public BonusMainAction makeCopy() {
return new BonusMainAction(quantity);
}
@Override
public String toString() {
return "\n+1 main action!";
}
}
|
3e0c59e1a3dd12ff81b80176a3124cd16885dd99 | 2,115 | java | Java | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/controller/SkuFullReductionController.java | yrcao95/gulimall | 9689356d370f50228d2faacf77e16f7b5c028342 | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/controller/SkuFullReductionController.java | yrcao95/gulimall | 9689356d370f50228d2faacf77e16f7b5c028342 | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/controller/SkuFullReductionController.java | yrcao95/gulimall | 9689356d370f50228d2faacf77e16f7b5c028342 | [
"Apache-2.0"
] | null | null | null | 23.511111 | 80 | 0.691399 | 5,245 | package com.atguigu.gulimall.coupon.controller;
import java.util.Arrays;
import java.util.Map;
import com.atguigu.common.to.SkuReductionTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.atguigu.gulimall.coupon.entity.SkuFullReductionEntity;
import com.atguigu.gulimall.coupon.service.SkuFullReductionService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
/**
* 商品满减信息
*
* @author YiruiCao
* @email dycjh@example.com
* @date 2020-10-22 19:02:36
*/
@RestController
@RequestMapping("coupon/skufullreduction")
public class SkuFullReductionController {
@Autowired
private SkuFullReductionService skuFullReductionService;
@PostMapping("/saveinfo")
public R saveInfo(@RequestBody SkuReductionTo reductionTo) {
skuFullReductionService.saveSkuReduction(reductionTo);
return R.ok();
}
/**
* 列表
*/
@RequestMapping("/list")
// @RequiresPermissions("coupon:skufullreduction:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = skuFullReductionService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
SkuFullReductionEntity skuFullReduction = skuFullReductionService.getById(id);
return R.ok().put("skuFullReduction", skuFullReduction);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody SkuFullReductionEntity skuFullReduction){
skuFullReductionService.save(skuFullReduction);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody SkuFullReductionEntity skuFullReduction){
skuFullReductionService.updateById(skuFullReduction);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
skuFullReductionService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e0c5a2ef71406a8ad8684128901cd8b40d82fdc | 4,926 | java | Java | src/java/billiards/viewer/ColorPicker.java | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | src/java/billiards/viewer/ColorPicker.java | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | src/java/billiards/viewer/ColorPicker.java | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | 41.05 | 96 | 0.647787 | 5,246 | package billiards.viewer;
import java.util.Optional;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class ColorPicker {
private static final int ROWS = 12;
private static final int COLS = 12;
private static final int RECT_SIZE = 20; // rect size in pixels
private static final Color[][] color = {
// first row
{Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW, Color.MAGENTA, Color.CHOCOLATE,
Color.ORANGE, Color.PINK, Color.LIME, Color.GOLD, Color.PURPLE,
Color.TURQUOISE},
// second row
{Color.TRANSPARENT, Color.WHITE, Color.WHITESMOKE, Color.GAINSBORO, Color.LIGHTGRAY,
Color.SILVER, Color.DARKGRAY, Color.GRAY, Color.DIMGRAY, Color.BLACK,
Color.BLACK, Color.BLACK},
// rows 3 through 12
{
Color.LIGHTGREEN, Color.MEDIUMAQUAMARINE, Color.SEAGREEN, Color.CORAL,
Color.PERU, Color.SIENNA, Color.ORANGERED, Color.DARKORANGE,
Color.MEDIUMVIOLETRED, Color.VIOLET, Color.DARKVIOLET, Color.INDIGO,
},
{Color.HONEYDEW, Color.MINTCREAM, Color.LIGHTCYAN, Color.LIGHTSKYBLUE,
Color.PALETURQUOISE, Color.POWDERBLUE, Color.CORNFLOWERBLUE, Color.STEELBLUE,
Color.TEAL, Color.CADETBLUE, Color.DARKCYAN, Color.DARKSEAGREEN},
{Color.OLDLACE, Color.WHEAT, Color.PAPAYAWHIP, Color.PALEVIOLETRED, Color.PEACHPUFF,
Color.LINEN, Color.TAN, Color.LIGHTSALMON, Color.PINK, Color.FUCHSIA,
Color.ORCHID, Color.DARKORCHID},
{Color.LEMONCHIFFON, Color.LIGHTYELLOW, Color.LIGHTGOLDENRODYELLOW, Color.CORNSILK,
Color.BISQUE, Color.KHAKI, Color.PALEGOLDENROD, Color.YELLOW, Color.GOLD,
Color.GOLDENROD, Color.DARKGOLDENROD, Color.OLIVE},
{Color.LAVENDERBLUSH, Color.MISTYROSE, Color.DARKSALMON, Color.LIGHTCORAL, Color.SALMON,
Color.INDIANRED, Color.TOMATO, Color.CRIMSON, Color.RED, Color.FIREBRICK,
Color.MAROON, Color.DARKRED},
{Color.THISTLE, Color.LIGHTPINK, Color.PLUM, Color.HOTPINK, Color.MAGENTA,
Color.DEEPPINK, Color.MEDIUMORCHID, Color.MEDIUMSLATEBLUE, Color.MEDIUMPURPLE,
Color.SLATEBLUE, Color.BLUEVIOLET, Color.DARKMAGENTA},
{Color.AZURE, Color.ANTIQUEWHITE, Color.BEIGE, Color.BLANCHEDALMOND, Color.MOCCASIN,
Color.NAVAJOWHITE, Color.BURLYWOOD, Color.DARKKHAKI, Color.SANDYBROWN,
Color.ROSYBROWN, Color.BROWN, Color.SADDLEBROWN},
{Color.PALEGREEN, Color.GREENYELLOW, Color.YELLOWGREEN, Color.SPRINGGREEN,
Color.LIMEGREEN, Color.CHARTREUSE, Color.LAWNGREEN, Color.MEDIUMSEAGREEN,
Color.FORESTGREEN, Color.OLIVEDRAB, Color.DARKOLIVEGREEN, Color.DARKGREEN},
{Color.AQUA, Color.CYAN, Color.AQUAMARINE, Color.DARKTURQUOISE, Color.TURQUOISE,
Color.MEDIUMSPRINGGREEN, Color.MEDIUMTURQUOISE, Color.ROYALBLUE, Color.SKYBLUE,
Color.DODGERBLUE, Color.DEEPSKYBLUE, Color.BLUE},
{Color.LAVENDER, Color.LIGHTBLUE, Color.LIGHTSTEELBLUE, Color.LIGHTSLATEGRAY,
Color.SLATEGRAY, Color.DARKSLATEGRAY, Color.DARKSLATEBLUE, Color.MEDIUMBLUE,
Color.INDIGO, Color.DARKBLUE, Color.MIDNIGHTBLUE, Color.NAVY}
};
private final GridPane grid = new GridPane();
private final Stage stage = new Stage();
private Optional<Color> selectedColor = Optional.empty();
public ColorPicker(final int x, final int y) {
stage.setX(x);
stage.setY(y);
stage.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if (!isNowFocused) {
stage.hide();
}
});
stage.setScene(new Scene(grid));
stage.setTitle("SO COLORFUL");
grid.setPadding(new Insets(10));
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
final Color currentColor = color[row][col];
final Rectangle rect = new Rectangle(RECT_SIZE, RECT_SIZE, currentColor);
rect.setOnMouseClicked(event -> {
selectedColor = Optional.of(currentColor);
stage.close();
});
Tooltip.install(rect, new Tooltip(Colors.colorMap.get(currentColor).get()));
grid.add(rect, col, row);
}
}
}
public static Color next(final Color inColor) {
if (inColor.equals(Color.BLACK)) {
return Color.RED;
}
for (int i = 0; i < 12; i++) {
if (color[0][i].equals(inColor)) {
return color[0][(i + 1) % 12];
}
}
return Color.BLACK;
}
public Optional<Color> pickColor() {
stage.showAndWait();
return selectedColor;
}
}
|
3e0c5b160f5d976e7525f314d846b32da6c7d0d2 | 611 | java | Java | applications/dev-management/src/main/java/no/dcat/testadmin/MvcConfig.java | tereseskavhaug/fdk | 0d4cd65d161f6bef50982297288b1c36cca3275c | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2016-09-09T07:07:17.000Z | 2018-05-16T12:52:36.000Z | applications/dev-management/src/main/java/no/dcat/testadmin/MvcConfig.java | computas/fdk | 5cbc1d82c25c941756add75c235963cdeb573fef | [
"ECL-2.0",
"Apache-2.0"
] | 1,404 | 2018-06-12T07:42:34.000Z | 2020-10-01T19:13:27.000Z | applications/dev-management/src/main/java/no/dcat/testadmin/MvcConfig.java | computas/fdk | 5cbc1d82c25c941756add75c235963cdeb573fef | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2018-08-22T09:05:07.000Z | 2020-06-04T07:33:42.000Z | 35.941176 | 81 | 0.785597 | 5,247 | package no.dcat.testadmin;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("test");
registry.addViewController("/").setViewName("test");
registry.addViewController("/login").setViewName("login");
}
} |
3e0c5b882d3d46650489039d5c1fda5ac7cf6f1f | 1,066 | java | Java | src/main/java/edu/neu/coe/info6205/FinalProject/Sort/MultiThreadSorting.java | Negi97Mohit/INFO-6205-Final_Project | 7ed50efab6a98e91c560ad22996a7d6dc9766bde | [
"Apache-2.0"
] | 1 | 2021-12-07T17:59:19.000Z | 2021-12-07T17:59:19.000Z | src/main/java/edu/neu/coe/info6205/FinalProject/Sort/MultiThreadSorting.java | Negi97Mohit/INFO-6205-Final_Project | 7ed50efab6a98e91c560ad22996a7d6dc9766bde | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/neu/coe/info6205/FinalProject/Sort/MultiThreadSorting.java | Negi97Mohit/INFO-6205-Final_Project | 7ed50efab6a98e91c560ad22996a7d6dc9766bde | [
"Apache-2.0"
] | null | null | null | 41 | 86 | 0.659475 | 5,248 | package edu.neu.coe.info6205.FinalProject.Sort;
import edu.neu.coe.info6205.util.SortBenchmark;
import java.io.IOException;
import java.util.concurrent.ForkJoinPool;
import static edu.neu.coe.info6205.util.SortBenchmark.getNames;
public class MultiThreadSorting {
public static void main(String[] args) throws IOException {
int[] words1 = {250000,500000,999998};
int[] threadCount={4};
for(int thread:threadCount) {
SortBenchmark.threadCount=thread;
SortBenchmark.threadFJP=new ForkJoinPool(SortBenchmark.threadCount);
for (int word : words1) {
SortBenchmark.sortBenchmark(new RadixSortMSD(), getNames(), word, 10);
SortBenchmark.sortBenchmark(new RadixSortLSD(), getNames(), word, 10);
SortBenchmark.sortBenchmarkTim(new TimSort(), getNames(), word, 10);
SortBenchmark.sortBenchmark(new DualPivot(), getNames(), word, 10);
SortBenchmark.sortBenchmark(new Husky(), getNames(), word, 1);
}
}
}
} |
3e0c5c5009405717397f5f3e2f1edaf4dbd75dc8 | 721 | java | Java | extensions/np/api/src/main/java/org/pcsoft/framework/jremote/ext/np/api/annotation/RemoteKeepAliveService.java | KleinerHacker/jremote | 0ed0f254ddb98e300bf212f5ea5317f76c7016b6 | [
"Apache-2.0"
] | null | null | null | extensions/np/api/src/main/java/org/pcsoft/framework/jremote/ext/np/api/annotation/RemoteKeepAliveService.java | KleinerHacker/jremote | 0ed0f254ddb98e300bf212f5ea5317f76c7016b6 | [
"Apache-2.0"
] | null | null | null | extensions/np/api/src/main/java/org/pcsoft/framework/jremote/ext/np/api/annotation/RemoteKeepAliveService.java | KleinerHacker/jremote | 0ed0f254ddb98e300bf212f5ea5317f76c7016b6 | [
"Apache-2.0"
] | null | null | null | 32.772727 | 101 | 0.773925 | 5,249 | package org.pcsoft.framework.jremote.ext.np.api.annotation;
import org.pcsoft.framework.jremote.api.internal.RemoteService;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark an interface as remote keep alive service. Must have exactly one method: <br/>
* <ul>
* <li><code>boolean ping(String uuid)</code> annotated with <code>{@link KeepAlive}</code><br/>
* Method to ping server with client's UUID to get TRUE if client is registered, otherwise FALSE</li>
* </ul>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@RemoteService
public @interface RemoteKeepAliveService {
}
|
3e0c5cbb51e501a13a959c459cb3b0a29a657c08 | 922 | java | Java | amberle-core/src/main/java/amberle/Either.java | ReactivePlatform/amberle | e40b8885e5675b4995595874c7ab78d2ba6261cd | [
"Apache-2.0"
] | 5 | 2018-12-21T02:13:57.000Z | 2018-12-25T02:09:19.000Z | amberle-core/src/main/java/amberle/Either.java | ReactivePlatform/amberle | e40b8885e5675b4995595874c7ab78d2ba6261cd | [
"Apache-2.0"
] | 13 | 2018-12-21T03:50:24.000Z | 2019-01-08T18:40:52.000Z | amberle-core/src/main/java/amberle/Either.java | ReactivePlatform/amberle | e40b8885e5675b4995595874c7ab78d2ba6261cd | [
"Apache-2.0"
] | 1 | 2018-12-25T02:10:17.000Z | 2018-12-25T02:10:17.000Z | 31.793103 | 75 | 0.76898 | 5,250 | /*
* Copyright 2018 amberle-core
*
* 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 amberle;
import amberle.annotation.NonStandardMonadicOperation;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public abstract class Either<L, R> {}
|
3e0c5cbe3964c6607a4850829c3a0163bb406835 | 8,630 | java | Java | androidviewertools/src/main/java/com/example/evan/androidviewertools/utils/Utils.java | KateUnger/viewer-2018-android-1 | 501c62c5b5fb3ad756e97a43017db2e6250d6d85 | [
"MIT"
] | 1 | 2019-03-21T23:55:31.000Z | 2019-03-21T23:55:31.000Z | androidviewertools/src/main/java/com/example/evan/androidviewertools/utils/Utils.java | KateUnger/viewer-2018-android-1 | 501c62c5b5fb3ad756e97a43017db2e6250d6d85 | [
"MIT"
] | 4 | 2018-10-11T03:37:33.000Z | 2018-12-30T00:42:18.000Z | androidviewertools/src/main/java/com/example/evan/androidviewertools/utils/Utils.java | KateUnger/viewer-2018-android-1 | 501c62c5b5fb3ad756e97a43017db2e6250d6d85 | [
"MIT"
] | 3 | 2018-08-02T01:46:28.000Z | 2022-01-17T22:57:19.000Z | 42.303922 | 169 | 0.656083 | 5,251 | package com.example.evan.androidviewertools.utils;
import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import com.example.evan.androidviewertools.firebase_classes.Match;
import com.example.evan.androidviewertools.firebase_classes.TeamInMatchData;
import com.example.evan.androidviewertools.utils.firebase.FirebaseLists;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Utils {
public static Object getObjectField(Object object, String field) {
try {
List<String> fields = Arrays.asList(field.split("\\."));
if (fields.size() == 1) {
return getDirectField(object, field);
} else {
Object parent = getObjectField(object, field.substring(0, field.indexOf("." + fields.get(fields.size() - 1))));
return getDirectField(parent, fields.get(fields.size() - 1));
}
} catch (Exception e) {
return null;
}
}
private static Object getDirectField(Object object, String field) throws Exception {
if (object instanceof List) {return ((List)object).get(Integer.parseInt(field));}
return findFieldInInheritedFields(object.getClass(), field).get(object);
}
private static Field findFieldInInheritedFields(Class clazz, String field) throws Exception {
try {
Field value = clazz.getDeclaredField(field);
value.setAccessible(true);
return value;
} catch (NoSuchFieldException nsfe) {
return findFieldInInheritedFields(clazz.getSuperclass(), field);
}
}
public static boolean fieldIsNotNull(Object object, String fieldName) {
return getObjectField(object, fieldName) != null;
}
public static void sortListByFieldName(List<Object> os, String fieldName) {
sortListByFieldName(os, fieldName, true);
}
public static void sortListByFieldName(List<Object> os, String fieldName, boolean isReversed) {
Collections.sort(os, new ObjectFieldComparator(fieldName, isReversed));
}
public static Integer getRankOfObject(Object o, List<Object> os, String fieldName) {
return getRankOfObject(o, os, fieldName, true);
}
public static Integer getRankOfObject(Object o, List<Object> os, String fieldName, boolean isReversed) {
if (Utils.getObjectField(o, fieldName) == null) {
return null;
}
try {
sortListByFieldName(os, fieldName, isReversed);
return os.indexOf(o);
} catch (IllegalArgumentException iae) {
return null;
}
}
public static String dataPointToPercentage(Float dataPoint, int decimalPlaces) {
if (dataPoint != null) {
return roundDataPoint(dataPoint * 100, decimalPlaces, "??") + "%";
} else {
return "???";
}
}
public static String getMatchDisplayValue(Match match, String key) {
return roundDataPoint(getObjectField(match, key), 2, "???");
}
public static String getDisplayValue(Object object, String key) {
return roundDataPoint(getObjectField(object, key), 2, "???");
}
public static String roundDataPoint(Object dataPoint, int decimalPlaces, String unkownValue) {
if (dataPoint == null) {
return unkownValue;
}
int decimalPointIndex = dataPoint.toString().indexOf(".");
if (decimalPointIndex < 0) {
return dataPoint.toString();
}
int substringIndex = dataPoint.toString().indexOf(".") + 1 + decimalPlaces;
if (decimalPlaces < 1) {
substringIndex--;
}
return dataPoint.toString().substring(0, Math.min(substringIndex, dataPoint.toString().length()));
}
public static Integer getLastMatchPlayed() {
Integer lastMatch = 0;
for (Match match : FirebaseLists.matchesList.getValues()) {
Integer redScore = (Integer)(Utils.getObjectField(match,"redScore"));
Integer blueScore = (Integer)(Utils.getObjectField(match,"blueScore"));
if(redScore != null || blueScore != null) {
lastMatch = ((Integer)(Utils.getObjectField(match,"number")));
}
}
return lastMatch;
}
public static SpannableString highlightTextInString(String fullString, String toHighlight) {
SpannableString spannableString = new SpannableString(fullString);
int index = fullString.indexOf(toHighlight);
if (index == 0) {
spannableString.setSpan(new BackgroundColorSpan(Color.GREEN), fullString.indexOf(toHighlight), fullString.indexOf(toHighlight) + toHighlight.length(), 0);
}
return spannableString;
}
public static List<TeamInMatchData> getTeamInMatchDatasForTeamNumber(Integer teamNumber) {
List<TeamInMatchData> teamInMatchDatas = new ArrayList<>();
for (TeamInMatchData teamInMatchData : FirebaseLists.teamInMatchDataList.getValues()) {
Log.e("teamNumber", Integer.toString(teamNumber));
Integer number = (Integer) Utils.getObjectField(teamInMatchData,"teamNumber");
//Log.e("number", Integer.toString(number));
//DRINK BLEACH
try {
if (number.equals(teamNumber)) {
teamInMatchDatas.add(teamInMatchData);
}
}catch (NullPointerException NPE){
Log.e("team Number", "NULL");
}
}
Collections.sort(teamInMatchDatas, new ObjectFieldComparator("matchNumber", true));
return teamInMatchDatas;
}//DRINK BLEACH//DRINK BLEACH
public static List<Integer> getMatchNumbersForTeamNumber(Integer teamNumber) {
List<Integer> matchNumbers = new ArrayList<>();
for (TeamInMatchData teamInMatchData : getTeamInMatchDatasForTeamNumber(teamNumber)) {
Integer matchNumber = (Integer) Utils.getObjectField(teamInMatchData,"matchNumber");
matchNumbers.add(matchNumber);
}
return matchNumbers;
}
//gson is a literal god, tasteless
private static final Gson gson = new Gson();
public static String serializeClass(Object object) throws JsonParseException {return gson.toJson(object);}
public static Object deserializeClass(String serializedClass, Class<?> clazz) throws JsonParseException {
return gson.fromJson(serializedClass, clazz);
}
//do I use reflection too much? probably
//anyway this method is used to display data points that aren't on firebase. Basically it calls a getter method for the field on the utils class
public static Object getViewerObjectField(Object object, String fieldName, Intent args, Class<?> viewerDataPointsClass) {
try {
Log.e("object", object.getClass().toString());
Log.e("methodName", "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1));
Log.e("className", viewerDataPointsClass.getName());
Method method = viewerDataPointsClass.getMethod("getMatchesUntilNextMatchForTeam", object.getClass(), Intent.class);
return method.invoke(viewerDataPointsClass.newInstance(), object, args);
} catch (NoSuchMethodException NSME) {
Log.e("Method", "ERROR");
return null;
}catch (InstantiationException ISE){
Log.e("Instantiation", "ERROR");
return null;
}catch (IllegalAccessException IAE){
Log.e("Illegal Access", "EXCEPTION");
return null;
}catch (InvocationTargetException ITE){
Log.e("Invocation", "TARGET EXCEPTION");
return null;
}
}
public static String getViewerObjectFieldRank(String fieldName, Intent args, Class<?> viewerDataPointsClass) {
try {
Method method = viewerDataPointsClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1) + "RankingsValue", Intent.class);
return (String)method.invoke(viewerDataPointsClass.newInstance(), args);
} catch (Exception e) {
Log.e("Method error", "Requested viewer object that doesn't exist!2");
return null;
}
}
}
|
3e0c5cd57b445b55a683dc284ac4fe3135f315ee | 2,108 | java | Java | src/main/java/br/edu/les/realmofcard/dao/CartaDAO.java | LucasCascao/realmofcards-api | ffab64dd72bd2365dc17d64f1a882fb3784cb542 | [
"MIT"
] | null | null | null | src/main/java/br/edu/les/realmofcard/dao/CartaDAO.java | LucasCascao/realmofcards-api | ffab64dd72bd2365dc17d64f1a882fb3784cb542 | [
"MIT"
] | 11 | 2020-02-24T01:03:36.000Z | 2022-03-02T10:53:50.000Z | src/main/java/br/edu/les/realmofcard/dao/CartaDAO.java | LucasCascao/realmofcards-api | ffab64dd72bd2365dc17d64f1a882fb3784cb542 | [
"MIT"
] | null | null | null | 32.430769 | 102 | 0.638994 | 5,252 | package br.edu.les.realmofcard.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.edu.les.realmofcard.domain.Carta;
import br.edu.les.realmofcard.domain.EntidadeDominio;
import br.edu.les.realmofcard.repository.CartaRepository;
import br.edu.les.realmofcard.repository.StatusRepository;
import java.util.ArrayList;
import java.util.List;
@Service
public class CartaDAO implements IDAO {
@Autowired
CartaRepository cartaRepository;
@Autowired
StatusRepository statusRepository;
@Override
public EntidadeDominio salvar(EntidadeDominio entidade) {
if(entidade instanceof Carta) return cartaRepository.save((Carta) entidade);
else return null;
}
@Override
public void alterar(EntidadeDominio entidade) {
if(entidade instanceof Carta) entidade = cartaRepository.save((Carta) entidade);
else entidade = null;
}
@Override
public void excluir(EntidadeDominio entidade) {
if(entidade instanceof Carta) {
Carta carta = (Carta) entidade;
carta = cartaRepository.findById(carta.getId()).get();
carta.setStatus( statusRepository.findById(carta.getStatus().getId() == 1 ? 2 : 1).get());
cartaRepository.save(carta);
}
}
@Override
public List<EntidadeDominio> consultar(EntidadeDominio entidade) {
List<EntidadeDominio> cartas = new ArrayList<>();
if (entidade instanceof Carta){
Carta carta = (Carta) entidade;
if(carta.getStatus() != null){
if (carta.getStatus().getId() >= 1 && carta.getStatus().getId() <= 2){
cartaRepository.findByStatus_Id(carta.getStatus().getId())
.forEach( resultado -> cartas.add(resultado));
}
}
if (carta.getId() != null){
cartas.add(cartaRepository.findById(carta.getId()).get());
return cartas;
}
return cartas;
}
return null;
}
}
|
3e0c5d9d758e6e8f75f4bde17e14812bd39ccf76 | 10,112 | java | Java | platform-facet/src/main/java/net/kyori/adventure/platform/facet/FacetAudienceProvider.java | Silthus/adventure-platform | 72e9bbbec58c09a69a93bf0f4e4ca074ab6bfcb3 | [
"MIT"
] | 59 | 2020-06-11T06:47:13.000Z | 2022-03-03T14:29:58.000Z | platform-facet/src/main/java/net/kyori/adventure/platform/facet/FacetAudienceProvider.java | Silthus/adventure-platform | 72e9bbbec58c09a69a93bf0f4e4ca074ab6bfcb3 | [
"MIT"
] | 47 | 2020-06-25T16:14:26.000Z | 2022-03-07T10:51:16.000Z | platform-facet/src/main/java/net/kyori/adventure/platform/facet/FacetAudienceProvider.java | Silthus/adventure-platform | 72e9bbbec58c09a69a93bf0f4e4ca074ab6bfcb3 | [
"MIT"
] | 24 | 2020-06-24T20:11:59.000Z | 2022-01-16T21:30:46.000Z | 33.045752 | 166 | 0.680182 | 5,253 | /*
* This file is part of adventure-platform, licensed under the MIT License.
*
* Copyright (c) 2018-2020 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.facet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.permission.PermissionChecker;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.kyori.adventure.util.TriState;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* An audience provider implementation using facets.
*
* <p>This is not supported API. Subject to change at any time.</p>
*
* @param <V> the viewer type
* @param <A> the audience type
* @since 4.0.0
*/
@ApiStatus.Internal
public abstract class FacetAudienceProvider<V, A extends FacetAudience<V>>
implements AudienceProvider, ForwardingAudience {
protected static final Locale DEFAULT_LOCALE = Locale.US;
protected final ComponentRenderer<Pointered> componentRenderer;
private final Audience console;
private final Audience player;
protected final Map<V, A> viewers;
private final Map<UUID, A> players;
private final Set<A> consoles;
private final A empty;
private volatile boolean closed;
protected FacetAudienceProvider(final @NotNull ComponentRenderer<Pointered> componentRenderer) {
this.componentRenderer = requireNonNull(componentRenderer, "component renderer");
this.viewers = new ConcurrentHashMap<>();
this.players = new ConcurrentHashMap<>();
this.consoles = new CopyOnWriteArraySet<>();
this.console = new ForwardingAudience() {
@Override
public @NotNull Iterable<? extends Audience> audiences() {
return FacetAudienceProvider.this.consoles;
}
@Override
public @NotNull Pointers pointers() {
if (FacetAudienceProvider.this.consoles.size() == 1) {
return FacetAudienceProvider.this.consoles.iterator().next().pointers();
} else {
return Pointers.empty();
}
}
};
this.player = Audience.audience(this.players.values());
this.empty = this.createAudience(Collections.emptyList());
this.closed = false;
}
/**
* Adds a viewer.
*
* @param viewer a viewer
* @since 4.0.0
*/
public void addViewer(final @NotNull V viewer) {
if (this.closed) return;
final A audience = this.viewers.computeIfAbsent(
requireNonNull(viewer, "viewer"),
v -> this.createAudience(Collections.singletonList(v)));
final FacetPointers.Type type = audience.getOrDefault(FacetPointers.TYPE, FacetPointers.Type.OTHER);
if (type == FacetPointers.Type.PLAYER) {
final @Nullable UUID id = audience.getOrDefault(Identity.UUID, null);
if (id != null) this.players.putIfAbsent(id, audience);
} else if (type == FacetPointers.Type.CONSOLE) {
this.consoles.add(audience);
}
}
/**
* Removes a viewer.
*
* @param viewer a viewer
* @since 4.0.0
*/
public void removeViewer(final @NotNull V viewer) {
final A audience = this.viewers.remove(viewer);
if (audience == null) return;
final FacetPointers.Type type = audience.getOrDefault(FacetPointers.TYPE, FacetPointers.Type.OTHER);
if (type == FacetPointers.Type.PLAYER) {
final @Nullable UUID id = audience.getOrDefault(Identity.UUID, null);
if (id != null) this.players.remove(id);
} else if (type == FacetPointers.Type.CONSOLE) {
this.consoles.remove(audience);
}
audience.close();
}
/**
* Refreshes a viewer's metadata.
*
* <p>Should be called after a viewer changes their locale, world, server, etc.</p>
*
* @param viewer a viewer
* @since 4.0.0
*/
public void refreshViewer(final @NotNull V viewer) {
final A audience = this.viewers.get(viewer);
if (audience != null) {
audience.refresh();
}
}
/**
* Creates an audience for a collection of viewers.
*
* @param viewers a collection viewers
* @return an audience
*/
protected abstract @NotNull A createAudience(final @NotNull Collection<V> viewers);
@Override
public @NotNull Iterable<? extends Audience> audiences() {
return this.viewers.values();
}
@Override
public @NotNull Audience all() {
return this;
}
@Override
public @NotNull Audience console() {
return this.console;
}
@Override
public @NotNull Audience players() {
return this.player;
}
@Override
public @NotNull Audience player(final @NotNull UUID playerId) {
return this.players.getOrDefault(playerId, this.empty);
}
/**
* Creates an audience based on a viewer predicate.
*
* @param predicate a predicate
* @return an audience
* @since 4.0.0
*/
public @NotNull Audience filter(final @NotNull Predicate<V> predicate) {
return Audience.audience(
filter(
this.viewers.entrySet(), entry -> predicate.test(entry.getKey()), Map.Entry::getValue));
}
private @NotNull Audience filterPointers(final @NotNull Predicate<Pointered> predicate) {
return Audience.audience(
filter(
this.viewers.entrySet(),
entry -> predicate.test(entry.getValue()),
Map.Entry::getValue));
}
@Override
public @NotNull Audience permission(final @NotNull String permission) {
return this.filterPointers(pointers -> pointers.get(PermissionChecker.POINTER).orElse(PermissionChecker.always(TriState.FALSE)).test(permission));
}
@Override
public @NotNull Audience world(final @NotNull Key world) {
return this.filterPointers(pointers -> world.equals(pointers.getOrDefault(FacetPointers.WORLD, null)));
}
@Override
public @NotNull Audience server(final @NotNull String serverName) {
return this.filterPointers(pointers -> serverName.equals(pointers.getOrDefault(FacetPointers.SERVER, null)));
}
@Override
public void close() {
this.closed = true;
for (final V viewer : this.viewers.keySet()) {
this.removeViewer(viewer);
}
}
/**
* Return a live filtered view of the input {@link Iterable}.
*
* <p>Only elements that match {@code filter} will be returned by {@linkplain Iterator Iterators}
* provided.</p>
*
* <p>Because this is a <em>live</em> view, any changes to the state of the parent
* {@linkplain Iterable} will be reflected in iterations over the return value.</p>
*
* @param input The source iterator
* @param filter predicate to filter on
* @param transformer transformer to change the value
* @param <T> value type
* @param <V> another value type
* @return live filtered view
*/
private static <T, V> @NotNull Iterable<V> filter(final @NotNull Iterable<T> input, final @NotNull Predicate<T> filter, final @NotNull Function<T, V> transformer) {
return new Iterable<V>() {
// create a lazy iterator
// pre-fetches by one output value to determine whether or not we have another value
// one value will be fetched on iterator creation, and each next value will be
// fetched after returning the previous value.
@Override
public @NotNull Iterator<V> iterator() {
return new Iterator<V>() {
private final Iterator<T> parent = input.iterator();
private V next;
private void populate() {
this.next = null;
while (this.parent.hasNext()) {
final T next = this.parent.next();
if (filter.test(next)) {
this.next = transformer.apply(next);
return;
}
}
}
// initialize first value
{
this.populate();
}
@Override
public boolean hasNext() {
return this.next != null;
}
@Override
public V next() {
if (this.next == null) {
throw new NoSuchElementException();
}
final V next = this.next;
this.populate();
return next;
}
};
}
@Override
public void forEach(final Consumer<? super V> action) {
for (final T each : input) {
if (filter.test(each)) {
action.accept(transformer.apply(each));
}
}
}
};
}
}
|
3e0c5de1a452a3aa20ccf7ab2abd0b84e6dcec71 | 1,075 | java | Java | LeetCodeProgram/src/test/java/restoreipaddresses/MyTest.java | cnkmym/LeetCodeSolutions | 64d2407e76364d0b0b015ef4002e745461442888 | [
"Apache-2.0"
] | null | null | null | LeetCodeProgram/src/test/java/restoreipaddresses/MyTest.java | cnkmym/LeetCodeSolutions | 64d2407e76364d0b0b015ef4002e745461442888 | [
"Apache-2.0"
] | null | null | null | LeetCodeProgram/src/test/java/restoreipaddresses/MyTest.java | cnkmym/LeetCodeSolutions | 64d2407e76364d0b0b015ef4002e745461442888 | [
"Apache-2.0"
] | null | null | null | 21.36 | 109 | 0.661985 | 5,254 | package restoreipaddresses;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class MyTest {
Solution s;
@Before
public void init() {
s = new Solution();
}
private String print(List<String> ips) {
Collections.sort(ips);
return "[" + String.join(",", ips) + "]";
}
@Test
public void test1() {
assertEquals("[0.0.0.0]", print(s.restoreIpAddresses("0000")));
assertEquals("[8.8.8.8]", print(s.restoreIpAddresses("8888")));
}
@Test
public void test2() {
assertEquals("[255.255.11.135,255.255.111.35]", print(s.restoreIpAddresses("25525511135")));
}
@Test
public void test3() {
assertEquals("[5.28.96.41,192.168.127.12,52.89.6.41,52.89.64.1]", print(s.restoreIpAddresses("5289641")));
}
@Test
public void test4() {
assertEquals("[0.10.0.10,0.100.1.0]", print(s.restoreIpAddresses("010010")));
}
@Test
public void test5() {
assertEquals("[1.0.10.23,172.16.31.10,10.1.0.23,10.10.2.3,101.0.2.3]", print(s.restoreIpAddresses("101023")));
}
}
|
3e0c5f28823391e6e45c746e254f5612375d3b86 | 1,113 | java | Java | mochila_voraz/src/mochila_voraz/Objeto.java | louri91/ALG201516 | fa738c872b9cc4e484048bb11f012ee18b4ac1a7 | [
"MIT"
] | null | null | null | mochila_voraz/src/mochila_voraz/Objeto.java | louri91/ALG201516 | fa738c872b9cc4e484048bb11f012ee18b4ac1a7 | [
"MIT"
] | null | null | null | mochila_voraz/src/mochila_voraz/Objeto.java | louri91/ALG201516 | fa738c872b9cc4e484048bb11f012ee18b4ac1a7 | [
"MIT"
] | null | null | null | 18.245902 | 88 | 0.654987 | 5,255 | package mochila_voraz;
/**
*
* @author louri
* @date 1 Mayo 2016
*/
public class Objeto implements Comparable<Objeto>{
private String nombre;
private double peso;
private double beneficio;
public Objeto(String nombre, double peso, double beneficio) {
super();
this.nombre = nombre;
this.peso = peso;
this.beneficio = beneficio;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public double getPeso() {
return peso;
}
public void setPeso(double peso) {
this.peso = peso;
}
public double getBeneficio() {
return beneficio;
}
public void setBeneficio(double beneficio) {
this.beneficio = beneficio;
}
@Override
public String toString() {
return "Nombre: " + nombre + ", Peso: " + peso + ", Beneficio: " + beneficio;
}
@Override
public int compareTo(Objeto o) {
if(((o.getBeneficio())/(o.getPeso()))>((this.getBeneficio())/(this.getPeso()))){
return -1;
}else if(((o.getBeneficio())/(o.getPeso()))<((this.getBeneficio())/(this.getPeso()))){
return 1;
}else{
return 0;
}
}
}
|
3e0c60c8d2a2e1f9ded565c6f10f8090e96c089c | 1,063 | java | Java | app/src/main/java/com/example/coolweather/android/db/County.java | MarkITSpacer/coolweather | 25ed5af3a20166c193d776effa557bdacbb2e1ed | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/coolweather/android/db/County.java | MarkITSpacer/coolweather | 25ed5af3a20166c193d776effa557bdacbb2e1ed | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/coolweather/android/db/County.java | MarkITSpacer/coolweather | 25ed5af3a20166c193d776effa557bdacbb2e1ed | [
"Apache-2.0"
] | null | null | null | 16.873016 | 50 | 0.618062 | 5,256 | package com.example.coolweather.android.db;
import org.litepal.crud.DataSupport;
/**
* author:Mark
* date:2017/4/2
* time:10:14
*/
public class County extends DataSupport {
private int id;
private String countyName;
private String countyCode;
private int cityId;
private String weatherId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getCountyCode() {
return countyCode;
}
public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getWeatherId() {
return weatherId;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
}
|
3e0c61108b156bbb4aeb802af91897b6a2765277 | 2,101 | java | Java | src/main/java/xyz/kvantum/plotbot/commands/Material.java | Sauilitired/PlotBot | af7360aa72e1490088c1cdecc054007054c4c5ec | [
"MIT"
] | 2 | 2019-05-04T14:21:15.000Z | 2020-09-06T20:37:06.000Z | src/main/java/xyz/kvantum/plotbot/commands/Material.java | Sauilitired/PlotBot | af7360aa72e1490088c1cdecc054007054c4c5ec | [
"MIT"
] | 1 | 2020-09-25T19:07:10.000Z | 2020-09-25T19:07:10.000Z | src/main/java/xyz/kvantum/plotbot/commands/Material.java | Sauilitired/PlotBot | af7360aa72e1490088c1cdecc054007054c4c5ec | [
"MIT"
] | 3 | 2018-12-23T12:58:15.000Z | 2019-05-04T14:21:21.000Z | 46.688889 | 294 | 0.743931 | 5,257 | package xyz.kvantum.plotbot.commands;
import com.intellectualsites.commands.Command;
import com.intellectualsites.commands.CommandDeclaration;
import com.intellectualsites.commands.CommandInstance;
import com.intellectualsites.commands.parser.impl.StringParser;
import xyz.kvantum.plotbot.BukkitLegacyMappings;
import xyz.kvantum.plotbot.BukkitLegacyMappings.LegacyBlock;
import xyz.kvantum.plotbot.StringComparison;
@CommandDeclaration(command = "material", usage = "material <material>", description = "Finds the closets matching material", permission = "all")
public class Material extends Command {
private final BukkitLegacyMappings bukkitLegacyMappings = new BukkitLegacyMappings();
public Material() {
withArgument("material", new StringParser(), "material name to match");
}
@Override
public boolean onCommand(CommandInstance instance) {
final String material = instance.getString("material");
final org.bukkit.Material match;
final LegacyBlock legacyBlock;
if (material.contains(":") && !material.startsWith("minecraft")) {
// Probably numerical
final String [] parts = material.split(":");
legacyBlock = bukkitLegacyMappings.fromLegacyToString(Integer.parseInt(parts[0]), Integer.parseInt(parts[0]));
if (legacyBlock == null) {
instance.getCaller().message("Couldn't find a material matching that ID and data pair");
return true;
}
match = org.bukkit.Material.valueOf(legacyBlock.getNewName().toUpperCase());
} else {
final StringComparison<org.bukkit.Material> comparison = new StringComparison<>(material,
org.bukkit.Material.values());
match = comparison.getMatchObject();
legacyBlock = bukkitLegacyMappings.fromStringToLegacy(match.name());
}
instance.getCaller().message(String.format("Closest matching material name is %s having data type %s. Minecraft name is minecraft:%s and numerical ID is %d:%d", match.name(), match.data.getSimpleName(), match.name().toLowerCase(), legacyBlock.getNumericalId(), legacyBlock.getDataValue()));
return true;
}
}
|
3e0c613c08b6ffa0c21b8232fd71536bc2695d7b | 8,328 | java | Java | fwmf-module-category/fwmf-module-category-service/src/main/java/cn/faury/fwmf/module/service/category/generate/sqlProvider/CategoryInfoGenerateSqlProvider.java | fzyycp/fwmf-module | 36d39a312ad73b0f9a77e96acd614b0ff8cebe4f | [
"Apache-2.0"
] | null | null | null | fwmf-module-category/fwmf-module-category-service/src/main/java/cn/faury/fwmf/module/service/category/generate/sqlProvider/CategoryInfoGenerateSqlProvider.java | fzyycp/fwmf-module | 36d39a312ad73b0f9a77e96acd614b0ff8cebe4f | [
"Apache-2.0"
] | null | null | null | fwmf-module-category/fwmf-module-category-service/src/main/java/cn/faury/fwmf/module/service/category/generate/sqlProvider/CategoryInfoGenerateSqlProvider.java | fzyycp/fwmf-module | 36d39a312ad73b0f9a77e96acd614b0ff8cebe4f | [
"Apache-2.0"
] | null | null | null | 41.024631 | 149 | 0.56196 | 5,258 | /**
* This file was generator by Fwmf Generated
* !!!Do not modify this file!!
*
* @fwmf.generated 2018-12-12 08:48:52
*/
package cn.faury.fwmf.module.service.category.generate.sqlProvider;
import cn.faury.fdk.common.utils.StringUtil;
import cn.faury.fwmf.module.api.category.generate.bean.CategoryInfoGenerateBean;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
public class CategoryInfoGenerateSqlProvider {
/**
* This method was generated by Fwmf Generated.
* This method corresponds to the database table product_t_category_info
*
* @fwmf.generated 2018-12-12 08:48:52
*/
public String insertSelective(CategoryInfoGenerateBean record) {
SQL sql = new SQL();
sql.INSERT_INTO("product_t_category_info");
if (record.getProductCategoryId() != null) {
sql.VALUES("PRODUCT_CATEGORY_ID", "#{productCategoryId,jdbcType=BIGINT}");
}
if (record.getProductCategoryName() != null) {
sql.VALUES("PRODUCT_CATEGORY_NAME", "#{productCategoryName,jdbcType=VARCHAR}");
}
if (record.getDisplayOrder() != null) {
sql.VALUES("DISPLAY_ORDER", "#{displayOrder,jdbcType=INTEGER}");
}
if (record.getParentId() != null) {
sql.VALUES("PARENT_ID", "#{parentId,jdbcType=BIGINT}");
}
if (record.getIconPath() != null) {
sql.VALUES("ICON_PATH", "#{iconPath,jdbcType=VARCHAR}");
}
if (record.getUsageCode() != null) {
sql.VALUES("USAGE_CODE", "#{usageCode,jdbcType=INTEGER}");
}
if (record.getIsDelete() != null) {
sql.VALUES("IS_DELETE", "#{isDelete,jdbcType=CHAR}");
}
if (record.getXpath() != null) {
sql.VALUES("XPATH", "#{xpath,jdbcType=VARCHAR}");
}
return sql.toString();
}
/**
* This method was generated by Fwmf Generated.
* This method corresponds to the database table product_t_category_info
*
* @fwmf.generated 2018-12-12 08:48:52
*/
public String updateByPrimaryKeySelective(CategoryInfoGenerateBean record) {
SQL sql = new SQL();
sql.UPDATE("product_t_category_info");
if (record.getProductCategoryName() != null) {
sql.SET("PRODUCT_CATEGORY_NAME = #{productCategoryName,jdbcType=VARCHAR}");
}
if (record.getDisplayOrder() != null) {
sql.SET("DISPLAY_ORDER = #{displayOrder,jdbcType=INTEGER}");
}
if (record.getParentId() != null) {
sql.SET("PARENT_ID = #{parentId,jdbcType=BIGINT}");
}
if (record.getIconPath() != null) {
sql.SET("ICON_PATH = #{iconPath,jdbcType=VARCHAR}");
}
if (record.getUsageCode() != null) {
sql.SET("USAGE_CODE = #{usageCode,jdbcType=INTEGER}");
}
if (record.getIsDelete() != null) {
sql.SET("IS_DELETE = #{isDelete,jdbcType=CHAR}");
}
if (record.getXpath() != null) {
sql.SET("XPATH = #{xpath,jdbcType=VARCHAR}");
}
sql.WHERE("PRODUCT_CATEGORY_ID = #{productCategoryId,jdbcType=BIGINT}");
return sql.toString();
}
/**
* This method was generated by Fwmf Generated.
* This method corresponds to the database table product_t_category_info
*
* @fwmf.generated 2018-12-12 08:48:52
*/
public String search(Map<String, Object> params) {
SQL sql = new SQL();
sql.SELECT("PRODUCT_CATEGORY_ID, PRODUCT_CATEGORY_NAME, DISPLAY_ORDER, PARENT_ID, ICON_PATH");
sql.SELECT("USAGE_CODE, IS_DELETE, XPATH");
sql.FROM("product_t_category_info");
if (params.get("productCategoryId") != null){
if (!(params.get("productCategoryId") instanceof String) || StringUtil.isNotEmpty((String) params.get("productCategoryId"))){
sql.WHERE("PRODUCT_CATEGORY_ID=#{productCategoryId,jdbcType=BIGINT}");
}
}
if (params.get("ids") != null && params.get("ids") instanceof List) {
List list = (List) params.get("ids");
if (list != null && list.size() > 0) {
StringBuilder inClause = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
inClause.append("#{ids[").append(i).append("],jdbcType=BIGINT},");
}
inClause.setLength(inClause.length() - 1);
sql.WHERE("PRODUCT_CATEGORY_ID IN (" + inClause.toString() + ")");
}
}
if (params.get("productCategoryName") != null){
if (!(params.get("productCategoryName") instanceof String) || StringUtil.isNotEmpty((String) params.get("productCategoryName"))){
sql.WHERE("PRODUCT_CATEGORY_NAME=#{productCategoryName,jdbcType=VARCHAR}");
}
}
if (params.get("productCategoryNameLike")!=null){
if (!(params.get("productCategoryNameLike") instanceof String) || StringUtil.isNotEmpty((String) params.get("productCategoryNameLike"))){
sql.WHERE("PRODUCT_CATEGORY_NAME LIKE CONCAT('%',#{productCategoryNameLike,jdbcType=VARCHAR},'%')");
}
}
if (params.get("displayOrder") != null){
if (!(params.get("displayOrder") instanceof String) || StringUtil.isNotEmpty((String) params.get("displayOrder"))){
sql.WHERE("DISPLAY_ORDER=#{displayOrder,jdbcType=INTEGER}");
}
}
if (params.get("parentId") != null){
if (!(params.get("parentId") instanceof String) || StringUtil.isNotEmpty((String) params.get("parentId"))){
sql.WHERE("PARENT_ID=#{parentId,jdbcType=BIGINT}");
}
}
if (params.get("iconPath") != null){
if (!(params.get("iconPath") instanceof String) || StringUtil.isNotEmpty((String) params.get("iconPath"))){
sql.WHERE("ICON_PATH=#{iconPath,jdbcType=VARCHAR}");
}
}
if (params.get("iconPathLike")!=null){
if (!(params.get("iconPathLike") instanceof String) || StringUtil.isNotEmpty((String) params.get("iconPathLike"))){
sql.WHERE("ICON_PATH LIKE CONCAT('%',#{iconPathLike,jdbcType=VARCHAR},'%')");
}
}
if (params.get("usageCode") != null){
if (!(params.get("usageCode") instanceof String) || StringUtil.isNotEmpty((String) params.get("usageCode"))){
sql.WHERE("USAGE_CODE=#{usageCode,jdbcType=INTEGER}");
}
}
if (params.get("isDelete") != null){
if (!(params.get("isDelete") instanceof String) || StringUtil.isNotEmpty((String) params.get("isDelete"))){
sql.WHERE("IS_DELETE=#{isDelete,jdbcType=CHAR}");
}
}
if (params.get("isDeleteLike")!=null){
if (!(params.get("isDeleteLike") instanceof String) || StringUtil.isNotEmpty((String) params.get("isDeleteLike"))){
sql.WHERE("IS_DELETE LIKE CONCAT('%',#{isDeleteLike,jdbcType=CHAR},'%')");
}
}
if (params.get("xpath") != null){
if (!(params.get("xpath") instanceof String) || StringUtil.isNotEmpty((String) params.get("xpath"))){
sql.WHERE("XPATH=#{xpath,jdbcType=VARCHAR}");
}
}
if (params.get("xpathLike")!=null){
if (!(params.get("xpathLike") instanceof String) || StringUtil.isNotEmpty((String) params.get("xpathLike"))){
sql.WHERE("XPATH LIKE CONCAT('%',#{xpathLike,jdbcType=VARCHAR},'%')");
}
}
if (params.get("ORDER_BY") != null){
String orderBy = (String) params.get("ORDER_BY");
String[] columns = orderBy.split(",");
for (int i = 0; i < columns.length; i = i + 2) {
if (i+1<columns.length){
sql.ORDER_BY(String.format("%s %s",columns[i],columns[i+1]));
} else {
sql.ORDER_BY(columns[i]);
}
}
}
return sql.toString();
}
} |
3e0c6232d8fe2153704552cef7331714aed139fb | 10,819 | java | Java | src/generated/java/org/schema/HowToSupply.java | aweiland/jsonld-metadata | fe0b9e4acdd4a459558ba601181812e2e7f11146 | [
"Apache-2.0"
] | null | null | null | src/generated/java/org/schema/HowToSupply.java | aweiland/jsonld-metadata | fe0b9e4acdd4a459558ba601181812e2e7f11146 | [
"Apache-2.0"
] | null | null | null | src/generated/java/org/schema/HowToSupply.java | aweiland/jsonld-metadata | fe0b9e4acdd4a459558ba601181812e2e7f11146 | [
"Apache-2.0"
] | 1 | 2021-08-05T06:07:51.000Z | 2021-08-05T06:07:51.000Z | 37.178694 | 422 | 0.6801 | 5,259 | /*
* Copyright 2015-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This is auto-generated file. Do not edit.
*/
package org.schema;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.annotation.*;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* A supply consumed when performing the instructions for how to achieve a result.
*/
public class HowToSupply extends HowToItem implements Supply {
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@JsonIgnore public MonetaryAmount getEstimatedCostMonetaryAmount() {
return (MonetaryAmount) getValue("estimatedCost");
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@JsonIgnore public Collection<MonetaryAmount> getEstimatedCostMonetaryAmounts() {
final Object current = myData.get("estimatedCost");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<MonetaryAmount>) current;
}
return Arrays.asList((MonetaryAmount) current);
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@JsonIgnore public String getEstimatedCostString() {
return (String) getValue("estimatedCost");
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@JsonIgnore public Collection<String> getEstimatedCostStrings() {
final Object current = myData.get("estimatedCost");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
protected HowToSupply(java.util.Map<String,Object> data) {
super(data);
}
/**
* Builder for {@link HowToSupply}
*/
public static class Builder extends HowToItem.Builder {
public Builder(@NotNull HashMap<String,Object> data) {
super(data);
}
@NotNull public HowToSupply build() {
return new HowToSupply(myData);
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@NotNull public Builder estimatedCost(@NotNull MonetaryAmount monetaryAmount) {
putValue("estimatedCost", monetaryAmount);
return this;
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@NotNull public Builder estimatedCost(@NotNull MonetaryAmount.Builder monetaryAmount) {
putValue("estimatedCost", monetaryAmount.build());
return this;
}
/**
* The estimated cost of the supply or supplies consumed when performing instructions.
*/
@NotNull public Builder estimatedCost(@NotNull String estimatedCost) {
putValue("estimatedCost", estimatedCost);
return this;
}
/**
* The required quantity of the item(s).
*/
@NotNull public Builder requiredQuantity(@NotNull Number number) {
putValue("requiredQuantity", number);
return this;
}
/**
* The required quantity of the item(s).
*/
@NotNull public Builder requiredQuantity(@NotNull QuantitativeValue quantitativeValue) {
putValue("requiredQuantity", quantitativeValue);
return this;
}
/**
* The required quantity of the item(s).
*/
@NotNull public Builder requiredQuantity(@NotNull QuantitativeValue.Builder quantitativeValue) {
putValue("requiredQuantity", quantitativeValue.build());
return this;
}
/**
* The required quantity of the item(s).
*/
@NotNull public Builder requiredQuantity(@NotNull String requiredQuantity) {
putValue("requiredQuantity", requiredQuantity);
return this;
}
/**
* An entity represented by an entry in a list or data feed (e.g. an 'artist' in a list of 'artists')’.
*/
@NotNull public Builder item(@NotNull Thing thing) {
putValue("item", thing);
return this;
}
/**
* An entity represented by an entry in a list or data feed (e.g. an 'artist' in a list of 'artists')’.
*/
@NotNull public Builder item(@NotNull Thing.Builder thing) {
putValue("item", thing.build());
return this;
}
/**
* A link to the ListItem that preceeds the current one.
*/
@NotNull public Builder previousItem(@NotNull ListItem listItem) {
putValue("previousItem", listItem);
return this;
}
/**
* A link to the ListItem that preceeds the current one.
*/
@NotNull public Builder previousItem(@NotNull ListItem.Builder listItem) {
putValue("previousItem", listItem.build());
return this;
}
/**
* A link to the ListItem that follows the current one.
*/
@NotNull public Builder nextItem(@NotNull ListItem listItem) {
putValue("nextItem", listItem);
return this;
}
/**
* A link to the ListItem that follows the current one.
*/
@NotNull public Builder nextItem(@NotNull ListItem.Builder listItem) {
putValue("nextItem", listItem.build());
return this;
}
/**
* An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
*/
@NotNull public Builder additionalType(@NotNull String additionalType) {
putValue("additionalType", additionalType);
return this;
}
/**
* An alias for the item.
*/
@NotNull public Builder alternateName(@NotNull String alternateName) {
putValue("alternateName", alternateName);
return this;
}
/**
* A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
*/
@NotNull public Builder disambiguatingDescription(@NotNull String disambiguatingDescription) {
putValue("disambiguatingDescription", disambiguatingDescription);
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull CreativeWork creativeWork) {
putValue("mainEntityOfPage", creativeWork);
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull CreativeWork.Builder creativeWork) {
putValue("mainEntityOfPage", creativeWork.build());
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull String mainEntityOfPage) {
putValue("mainEntityOfPage", mainEntityOfPage);
return this;
}
/**
* The name of the item.
*/
@NotNull public Builder name(@NotNull String name) {
putValue("name", name);
return this;
}
/**
* URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
*/
@NotNull public Builder sameAs(@NotNull String sameAs) {
putValue("sameAs", sameAs);
return this;
}
/**
* URL of the item.
*/
@NotNull public Builder url(@NotNull String url) {
putValue("url", url);
return this;
}
/**
* Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
*/
@NotNull public Builder potentialAction(@NotNull Action action) {
putValue("potentialAction", action);
return this;
}
/**
* Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
*/
@NotNull public Builder potentialAction(@NotNull Action.Builder action) {
putValue("potentialAction", action.build());
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull CreativeWork creativeWork) {
putValue("subjectOf", creativeWork);
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull CreativeWork.Builder creativeWork) {
putValue("subjectOf", creativeWork.build());
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull Event event) {
putValue("subjectOf", event);
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull Event.Builder event) {
putValue("subjectOf", event.build());
return this;
}
@NotNull public Builder id(@NotNull String id) {
myData.put("id", id);
return this;
}
public Builder id(long id) {
return id(Long.toString(id));
}
@Override protected void fromMap(String key, Object value) {
if ("estimatedCost".equals(key) && value instanceof MonetaryAmount) { estimatedCost((MonetaryAmount)value); return; }
if ("estimatedCosts".equals(key) && value instanceof MonetaryAmount) { estimatedCost((MonetaryAmount)value); return; }
if ("estimatedCost".equals(key) && value instanceof String) { estimatedCost((String)value); return; }
if ("estimatedCosts".equals(key) && value instanceof String) { estimatedCost((String)value); return; }
super.fromMap(key, value);
}
}
}
|
3e0c62723f239e41db8cf053a54eb8d506927264 | 10,736 | java | Java | src/ucar/unidata/view/sounding/WetTrajectoryBean.java | oxelson/IDV | 06ea41150e6a303c5c59d5aa59b1907a5a6e488b | [
"CNRI-Jython"
] | 48 | 2015-02-22T05:05:01.000Z | 2022-03-14T14:23:41.000Z | src/ucar/unidata/view/sounding/WetTrajectoryBean.java | oxelson/IDV | 06ea41150e6a303c5c59d5aa59b1907a5a6e488b | [
"CNRI-Jython"
] | 40 | 2015-02-09T19:25:29.000Z | 2022-02-16T00:21:08.000Z | src/ucar/unidata/view/sounding/WetTrajectoryBean.java | oxelson/IDV | 06ea41150e6a303c5c59d5aa59b1907a5a6e488b | [
"CNRI-Jython"
] | 28 | 2015-04-03T05:43:00.000Z | 2022-01-31T23:41:20.000Z | 35.455446 | 125 | 0.570139 | 5,260 | /*
* $Id: WetTrajectoryBean.java,v 1.6 2005/05/13 18:33:40 jeffmc Exp $
*
* Copyright 1997-2022 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* upchh@example.com.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ucar.unidata.view.sounding;
import java.awt.event.ActionEvent;
import java.beans.*;
import java.rmi.RemoteException;
import ucar.visad.Util;
import ucar.visad.VisADMath;
import ucar.visad.display.*;
import ucar.visad.functiontypes.AirTemperatureProfile;
import ucar.visad.quantities.*;
import visad.*;
/**
* A Java Bean that computes the trajectory of a parcel of saturated air lifted
* pseudo-adiabatically from its saturation point.
*
* @author Steven R. Emmerson
* @version $Revision: 1.6 $ $Date: 2005/05/13 18:33:40 $
*/
public class WetTrajectoryBean extends ClockedBean {
/** LCL temperature value */
private Real lclTemp;
/** LCL pressure value */
private Real lclPres;
/** minimum pressure value */
private Real minPres;
/** moist adiabatic trajectory */
private FlatField wetTraj;
/** factory */
private TemperatureCalculatorFactory factory;
/** dirty flag */
private boolean dirty;
/** missing LCL temp value */
private static final Real missingLclTemp;
/** missing LCL pressure value */
private static final Real missingLclPres;
/** missing min pressure value */
private static final Real missingMinPres;
/** missing trajectory */
private static final FlatField missingWetTraj;
/** log of max pressure ratio */
private static final double logMaxPresRatio;
/** pressure ratio type */
private static final RealType pressureRatioType;
/** trajectory type */
private static final FunctionType trajectoryType;
static {
Real mspt = null;
Real mspp = null;
Real mmp = null;
FlatField f = null;
RealType prt = null;
FunctionType tt = null;
try {
mspt = (Real) AirTemperature.getRealType().missingData();
mspp = (Real) AirPressure.getRealType().missingData();
mmp = mspp;
tt = AirTemperatureProfile.instance();
f = (FlatField) tt.missingData();
prt = RealType.getRealType("TrajectoryPressureRatio",
CommonUnit.dimensionless, null);
} catch (Exception e) {
System.err.print("Couldn't initialize class: ");
e.printStackTrace();
System.exit(1);
}
missingLclTemp = mspt;
missingLclPres = mspp;
missingMinPres = mmp;
trajectoryType = tt;
missingWetTraj = f;
logMaxPresRatio = Math.log(0.95);
pressureRatioType = prt;
}
/**
* The name of the saturation-point pressure property.
*/
public static final String OUTPUT_PROPERTY_NAME = "wetTrajectory";
/**
* Constructs from the network in which this bean will be a component.
*
* @param network The bean network.
*/
public WetTrajectoryBean(BeanNetwork network) {
super(network);
lclTemp = missingLclTemp;
lclPres = missingLclPres;
minPres = missingMinPres;
wetTraj = missingWetTraj;
factory = DefaultWetTemperatureCalculatorFactory.instance();
dirty = false;
}
/**
* Sets the input saturation-point temperature. The data is not copied.
*
* @param lclTemp The saturation-point temperature.
* @throws NullPointerException if the argument is <code>null</code>.
* @throws TypeException if the temperature has the wrong type.
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
public synchronized void setSaturationPointTemperature(Real lclTemp)
throws TypeException, VisADException, RemoteException {
Util.vetType(ucar.visad.quantities.AirTemperature.getRealType(),
lclTemp);
this.lclTemp = lclTemp;
dirty = true;
}
/**
* Sets the input saturation-point pressure. The data is not copied.
*
* @param lclPres The LCL pressure.
* @throws NullPointerException if the argument is <code>null</code>.
* @throws TypeException if the pressure has the wrong type.
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
public synchronized void setSaturationPointPressure(Real lclPres)
throws TypeException, VisADException, RemoteException {
Util.vetType(ucar.visad.quantities.AirPressure.getRealType(),
lclPres);
this.lclPres = lclPres;
dirty = true;
}
/**
* Sets the input minimum pressure to which to lift the parcel. The data
* is not copied.
*
* @param minPres The minimum pressure pressure.
* @throws NullPointerException if the argument is <code>null</code>.
* @throws TypeException if the pressure has the wrong type.
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
public synchronized void setMinimumPressure(Real minPres)
throws TypeException, VisADException, RemoteException {
Util.vetType(ucar.visad.quantities.AirPressure.getRealType(),
minPres);
this.minPres = minPres;
dirty = true;
}
/**
* Computes the output, saturated, pseudo-adiabatic trajectory property from
* the input data. A {@link java.beans.PropertyChangeEvent} is fired
* for the output property if it differs from the previous value.
*
* @throws TypeException if a VisAD data object has the wrong type.
* @throws VisADException if a VisAD failure occurs.
* @throws RemoteException if a Java RMI failure occurs.
*/
void clock() throws TypeException, VisADException, RemoteException {
FlatField oldValue;
FlatField newValue;
synchronized (this) {
if ( !dirty) {
oldValue = wetTraj;
newValue = wetTraj;
} else {
Unit presUnit = AirPressure.getRealType().getDefaultUnit();
double endPres = minPres.getValue(presUnit);
double startPres = lclPres.getValue(presUnit);
if (endPres >= startPres) {
newValue = missingWetTraj;
} else {
double logPresExtent = Math.log(endPres / startPres);
double logPresRatio = logPresExtent
/ Math.ceil(logPresExtent
/ (logMaxPresRatio));
int count = 1 + (int) Math.round(logPresExtent
/ logPresRatio);
Real pressureRatio = new Real(pressureRatioType,
Math.exp(logPresRatio));
float[] pressures = new float[count];
float[] temperatures = new float[count];
Real pressure = lclPres;
Real temperature = lclTemp;
TemperatureCalculator calculator =
factory.newTemperatureCalculator(lclPres, lclTemp);
pressures[0] = (float) pressure.getValue(presUnit);
Unit tempUnit =
AirTemperature.getRealType().getDefaultUnit();
temperatures[0] = (float) temperature.getValue(tempUnit);
for (int i = 1; i < count; ++i) {
pressure = (Real) pressure.multiply(pressureRatio);
temperature = calculator.nextTemperature(pressure);
pressures[i] = (float) pressure.getValue(presUnit);
temperatures[i] =
(float) temperature.getValue(tempUnit);
}
newValue = new FlatField(trajectoryType,
(pressures.length == 1)
? (Set) new SingletonSet(AirPressure.getRealTupleType(),
new double[]{ pressures[0] },
(CoordinateSystem) null,
new Unit[]{ presUnit },
(ErrorEstimate[]) null)
: new Gridded1DSet(
AirPressure.getRealTupleType(),
new float[][] {
pressures
}, pressures.length, (CoordinateSystem) null, new Unit[]{ presUnit }, (ErrorEstimate[]) null), (CoordinateSystem[]) null,
(Set[]) null, new Unit[]{ tempUnit });
newValue.setSamples(new float[][] {
temperatures
});
}
oldValue = wetTraj;
wetTraj = newValue;
dirty = false;
}
}
firePropertyChange(OUTPUT_PROPERTY_NAME, oldValue, newValue);
}
/**
* Returns the value of the saturated, pseudo-adiabatic trajectory property.
* The data is not copied.
*
* @return The value of the saturated, pseudo-adiabatic
* trajectory property.
*/
public synchronized Data getWetTrajectory() {
return wetTraj;
}
}
|
3e0c64ecd6f859bf4cfaee43aa47b2dc3a50501d | 4,291 | java | Java | reservas-teatro-ecst/src/test/java/com/autentia/tutoriales/reservas/teatro/command/RepresentacionCommandServiceTest.java | dav-garcia/reservas-teatro | 7d127d2987d7fc30d35dc4c90821aad48767dc50 | [
"Apache-2.0"
] | 8 | 2021-01-16T20:37:26.000Z | 2021-10-09T04:07:25.000Z | reservas-teatro-ecst/src/test/java/com/autentia/tutoriales/reservas/teatro/command/RepresentacionCommandServiceTest.java | dav-garcia/reservas-teatro | 7d127d2987d7fc30d35dc4c90821aad48767dc50 | [
"Apache-2.0"
] | null | null | null | reservas-teatro-ecst/src/test/java/com/autentia/tutoriales/reservas/teatro/command/RepresentacionCommandServiceTest.java | dav-garcia/reservas-teatro | 7d127d2987d7fc30d35dc4c90821aad48767dc50 | [
"Apache-2.0"
] | 4 | 2020-12-20T19:38:59.000Z | 2022-03-30T17:08:03.000Z | 44.697917 | 102 | 0.74901 | 5,261 | package com.autentia.tutoriales.reservas.teatro.command;
import com.autentia.tutoriales.reservas.teatro.Butaca;
import com.autentia.tutoriales.reservas.teatro.Representacion;
import com.autentia.tutoriales.reservas.teatro.Reserva;
import com.autentia.tutoriales.reservas.teatro.Sala;
import com.autentia.tutoriales.reservas.teatro.configuration.EcstConfiguration;
import com.autentia.tutoriales.reservas.teatro.event.ReservaCreadaEvent;
import com.autentia.tutoriales.reservas.teatro.infra.event.EventConsumer;
import com.autentia.tutoriales.reservas.teatro.infra.event.inmemory.InMemoryEventPublisher;
import com.autentia.tutoriales.reservas.teatro.infra.repository.Repository;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = EcstConfiguration.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class RepresentacionCommandServiceTest {
private static final Butaca A1 = new Butaca("A", 1);
private static final Butaca A2 = new Butaca("A", 2);
private static final Butaca A3 = new Butaca("A", 3);
private static final Butaca B1 = new Butaca("B", 1);
private static final Butaca B2 = new Butaca("B", 2);
private static final Butaca B3 = new Butaca("B", 3);
private static final Sala SALA = new Sala("SALA", Set.of(A1, A2, A3, B1, B2, B3));
@Autowired
private Repository<Representacion, UUID> representacionRepository;
@Autowired
private Repository<Reserva, UUID> reservaRepository;
@Autowired
private InMemoryEventPublisher<UUID> reservaPublisher;
@Autowired
private RepresentacionCommandService sut;
@MockBean
private EventConsumer<UUID> reservaEventConsumer;
@Test
public void givenSeleccionarButacasThenReservaCreada() {
final var idRepresentacion = UUID.randomUUID();
final var idCliente = RandomStringUtils.randomAlphabetic(10) + "@email.com";
representacionRepository.save(Representacion.builder()
.id(idRepresentacion)
.version(1L)
.cuando(ZonedDateTime.now())
.donde(SALA)
.butacasLibres(new HashSet<>(SALA.getButacas()))
.build());
reservaPublisher.registerEventConsumer(reservaEventConsumer);
final var idReserva = sut.seleccionarButacas(idRepresentacion, Set.of(A1, A2, B3), idCliente);
final var eventoCaptor = ArgumentCaptor.forClass(ReservaCreadaEvent.class);
verify(reservaEventConsumer).consume(eq(1L), eventoCaptor.capture());
await().atMost(2, TimeUnit.SECONDS).until(() -> eventoCaptor.getValue() != null);
final var representacion = representacionRepository.load(idRepresentacion).orElseThrow();
assertThat(representacion.getVersion()).isEqualTo(2L);
assertThat(representacion.getButacasLibres()).containsExactlyInAnyOrder(A3, B1, B2);
final var reserva = reservaRepository.load(idReserva).orElseThrow();
assertThat(reserva.getVersion()).isEqualTo(1L);
assertThat(reserva.getRepresentacion()).isEqualTo(idRepresentacion);
assertThat(reserva.getButacas()).containsExactlyInAnyOrder(A1, A2, B3);
assertThat(reserva.getCliente()).isEqualTo(idCliente);
final var evento = eventoCaptor.getValue();
assertThat(evento.getAggregateRootId()).isEqualTo(idReserva);
assertThat(evento.getRepresentacion()).isEqualTo(idRepresentacion);
assertThat(evento.getButacas()).containsExactlyInAnyOrder(A1, A2, B3);
assertThat(evento.getCliente()).isEqualTo(idCliente);
}
}
|
3e0c652c895054317d957100aba31b6478f913d9 | 477 | java | Java | src/main/java/com/gearservice/model/cheque/samples/Models.java | lwluc/gear-service | 9f698e996bb85160e21284d67d00a6f860135b6e | [
"MIT"
] | null | null | null | src/main/java/com/gearservice/model/cheque/samples/Models.java | lwluc/gear-service | 9f698e996bb85160e21284d67d00a6f860135b6e | [
"MIT"
] | null | null | null | src/main/java/com/gearservice/model/cheque/samples/Models.java | lwluc/gear-service | 9f698e996bb85160e21284d67d00a6f860135b6e | [
"MIT"
] | null | null | null | 23.85 | 107 | 0.685535 | 5,262 | package com.gearservice.model.cheque.samples;
/**
* Enum Models contains samples of models
*
* @version 1.0
* @author Dmitry
* @since 04.09.2015
*/
public enum Models {
model1("Asus.T100TA-DK003H"),
model2("Apple.MacBook Pro MGXA2");
private final String model;
Models(String s) {model = s;}
public boolean equalsName(String otherModel) {return (otherModel != null) && model.equals(otherModel);}
public String toString() {return this.model;}
}
|
3e0c667aed74bd4d0af1c17151f610299808aca0 | 1,641 | java | Java | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/AggreJoinTotalThreadCountBo.java | richardy2012/pinpoint | c50696734a2f7fcc37f8fea879ed4c84946e58f8 | [
"Apache-2.0"
] | 1,473 | 2020-10-14T02:18:07.000Z | 2022-03-31T11:43:49.000Z | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/AggreJoinTotalThreadCountBo.java | richardy2012/pinpoint | c50696734a2f7fcc37f8fea879ed4c84946e58f8 | [
"Apache-2.0"
] | 995 | 2020-10-14T05:09:43.000Z | 2022-03-31T12:04:05.000Z | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/AggreJoinTotalThreadCountBo.java | richardy2012/pinpoint | c50696734a2f7fcc37f8fea879ed4c84946e58f8 | [
"Apache-2.0"
] | 446 | 2020-10-14T02:42:50.000Z | 2022-03-31T03:03:53.000Z | 40.02439 | 135 | 0.769653 | 5,263 | /*
* Copyright 2020 NAVER Corp.
*
* 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.navercorp.pinpoint.web.vo.stat;
import com.navercorp.pinpoint.common.server.bo.stat.join.JoinLongFieldBo;
import com.navercorp.pinpoint.common.server.bo.stat.join.JoinTotalThreadCountBo;
public class AggreJoinTotalThreadCountBo extends JoinTotalThreadCountBo implements AggregationStatData{
public AggreJoinTotalThreadCountBo() {
}
public AggreJoinTotalThreadCountBo(String id, long timestamp, long avg, long min, String minAgentId, long max, String maxAgentId) {
super(id, timestamp, avg, min, minAgentId, max, maxAgentId);
}
public AggreJoinTotalThreadCountBo(String id, long timestamp, JoinLongFieldBo totalThreadCountJoinValue) {
super(id, timestamp, totalThreadCountJoinValue);
}
public static AggreJoinTotalThreadCountBo createUncollectedObject(long timestamp) {
AggreJoinTotalThreadCountBo aggreJoinTotalThreadCountBo = new AggreJoinTotalThreadCountBo();
aggreJoinTotalThreadCountBo.setTimestamp(timestamp);
return aggreJoinTotalThreadCountBo;
}
}
|
3e0c673d6abd1b00caf2c1fa6bd1ff0a80d5973d | 1,949 | java | Java | online-education/course/business/src/main/java/com/course/business/controller/admin/CourseController.java | OSrcD/java-for-linux | 5424b1af0e74797d57d820425b91c991aa28fda9 | [
"Apache-2.0"
] | 8 | 2020-12-31T16:36:13.000Z | 2021-07-14T12:05:37.000Z | online-education/course/business/src/main/java/com/course/business/controller/admin/CourseController.java | OpenSrcDeveloper/java-architect-grow-through-train | 5424b1af0e74797d57d820425b91c991aa28fda9 | [
"Apache-2.0"
] | 6 | 2021-01-01T10:22:06.000Z | 2021-02-20T08:57:34.000Z | online-education/course/business/src/main/java/com/course/business/controller/admin/CourseController.java | OpenSrcDeveloper/java-architect-grow-through-train | 5424b1af0e74797d57d820425b91c991aa28fda9 | [
"Apache-2.0"
] | 3 | 2020-12-31T16:36:15.000Z | 2021-01-18T09:34:47.000Z | 24.987179 | 86 | 0.67881 | 5,264 | package com.course.business.controller.admin;
import com.course.server.domain.Course;
import com.course.server.dto.CourseDto;
import com.course.server.dto.PageDto;
import com.course.server.dto.ResponseDto;
import com.course.server.service.CourseService;
import com.course.server.util.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/admin/course")
public class CourseController {
private static final Logger LOG = LoggerFactory.getLogger(CourseController.class);
public static final String BUSINESS_NAME = "课程表";
@Resource
private CourseService courseService;
/**
* 列表查询
* @param pageDto
* @return
*/
@PostMapping("/list")
public ResponseDto list(@RequestBody PageDto pageDto){
ResponseDto responseDto = new ResponseDto();
this.courseService.list(pageDto);
responseDto.setContent(pageDto);
return responseDto;
}
/**
* 保存,id有值时更新,无值时新增
* @param courseDto
* @return
*/
@PostMapping("/save")
public ResponseDto save(@RequestBody CourseDto courseDto){
// 保存校验
ValidatorUtil.require(courseDto.getName(),"名称");
ValidatorUtil.length(courseDto.getName(),"名称",1,50);
ValidatorUtil.length(courseDto.getSummary(),"概述",1,2000);
ValidatorUtil.length(courseDto.getImage(),"封面",1,100);
ResponseDto responseDto = new ResponseDto();
courseService.save(courseDto);
responseDto.setContent(courseDto);
return responseDto;
}
/**
* 删除
* @param id
* @return
*/
@DeleteMapping("/delete/{id}")
public ResponseDto delete(@PathVariable String id){
ResponseDto responseDto = new ResponseDto();
courseService.delete(id);
return responseDto;
}
}
|
3e0c683f579f3a628fc0b71b29765d88f8eaf0fc | 1,109 | java | Java | src/com/comcast/cns/controller/CNSMonitorMBean.java | musicglue/cmb | 32d1bce23249d3caac263bd2ff90881a47d500f6 | [
"Apache-2.0"
] | 149 | 2015-01-03T13:25:40.000Z | 2020-10-19T07:49:25.000Z | src/com/comcast/cns/controller/CNSMonitorMBean.java | stopme/cmb | d93e9e24f98563ac843cd841e4b863ee1bc92ba4 | [
"Apache-2.0"
] | 24 | 2015-01-01T20:12:17.000Z | 2018-05-21T14:12:37.000Z | src/com/comcast/cns/controller/CNSMonitorMBean.java | stopme/cmb | d93e9e24f98563ac843cd841e4b863ee1bc92ba4 | [
"Apache-2.0"
] | 41 | 2015-01-18T23:14:01.000Z | 2021-11-11T18:22:14.000Z | 24.644444 | 76 | 0.646528 | 5,265 | /**
* Copyright 2012 Comcast Corporation
*
* 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.comcast.cns.controller;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* Interface for monitoring CNS
* @author aseem
*
*/
public interface CNSMonitorMBean {
/**
*
* @return
*/
public Map<String, AtomicLong> getCallStats();
/**
*
* @return
*/
public Map<String, AtomicLong> getCallFailureStats();
/**
*
*/
public void resetCallStats();
}
|
3e0c6844bdd35d22dab306dcd5a3ca2fa0b05c6f | 4,247 | java | Java | Gui/opensim/K12/src/org/opensim/k12/ResultDisplayPanel.java | adamkewley/opensim-gui | f1236964886da07b5e80f96e919ee525cf71f743 | [
"Apache-2.0"
] | 34 | 2017-10-26T15:21:30.000Z | 2022-01-09T15:56:09.000Z | Gui/opensim/K12/src/org/opensim/k12/ResultDisplayPanel.java | adamkewley/opensim-gui | f1236964886da07b5e80f96e919ee525cf71f743 | [
"Apache-2.0"
] | 769 | 2017-10-06T02:33:26.000Z | 2022-03-29T15:17:46.000Z | Gui/opensim/K12/src/org/opensim/k12/ResultDisplayPanel.java | adamkewley/opensim-gui | f1236964886da07b5e80f96e919ee525cf71f743 | [
"Apache-2.0"
] | 28 | 2017-10-26T10:32:36.000Z | 2021-11-28T09:33:37.000Z | 44.705263 | 180 | 0.581352 | 5,266 | /* -------------------------------------------------------------------------- *
* OpenSim: ResultDisplayPanel.java *
* -------------------------------------------------------------------------- *
* OpenSim is a toolkit for musculoskeletal modeling and simulation, *
* developed as an open source project by a worldwide community. Development *
* and support is coordinated from Stanford University, with funding from the *
* U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file *
* for more information including specific grant numbers. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* ResultDisplayPanel.java
*
* Created on August 17, 2010, 2:53 PM
*/
package org.opensim.k12;
/**
*
* @author ayman
*/
public class ResultDisplayPanel extends javax.swing.JPanel {
/** Creates new form ResultDisplayPanel */
public ResultDisplayPanel() {
initComponents();
}
public javax.swing.JLabel getResultLabel() {
return resultLabel;
}
public void setResultLabel(javax.swing.JLabel resultLabel) {
this.resultLabel = resultLabel;
}
public javax.swing.JTextField getResultTextField() {
return resultTextField;
}
public void setResultTextField(javax.swing.JTextField resultTextField) {
this.resultTextField = resultTextField;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
resultLabel = new javax.swing.JLabel();
resultTextField = new javax.swing.JTextField();
resultLabel.setText("jLabel1");
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(resultLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(resultTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(resultLabel)
.add(resultTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel resultLabel;
private javax.swing.JTextField resultTextField;
// End of variables declaration//GEN-END:variables
}
|
3e0c68540b0c619ff063529abb700b5b237f7c84 | 441 | java | Java | build-tools/src/main/java/uk/ac/ox/ndph/mts/json_schema_generator/model/SpringCloud.java | NDPH-ARTS/mts-services | e2d7d654f8784858e04a6ed75236f33f106fec74 | [
"MIT"
] | 3 | 2021-01-15T22:00:13.000Z | 2021-03-10T10:48:29.000Z | build-tools/src/main/java/uk/ac/ox/ndph/mts/json_schema_generator/model/SpringCloud.java | NDPH-ARTS/mts-services | e2d7d654f8784858e04a6ed75236f33f106fec74 | [
"MIT"
] | 248 | 2020-12-23T17:21:51.000Z | 2021-06-23T15:47:28.000Z | build-tools/src/main/java/uk/ac/ox/ndph/mts/json_schema_generator/model/SpringCloud.java | NDPH-ARTS/mts-services | e2d7d654f8784858e04a6ed75236f33f106fec74 | [
"MIT"
] | 4 | 2021-03-05T16:48:45.000Z | 2021-05-30T14:17:06.000Z | 29.4 | 63 | 0.761905 | 5,267 | package uk.ac.ox.ndph.mts.json_schema_generator.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SpringCloud {
@JsonProperty(value = "gateway_service", required = true)
private Service gatewayService;
@JsonProperty(value = "discovery_service", required = true)
private Service discoveryService;
@JsonProperty(value = "config_server", required = true)
private ConfigServer configServer;
}
|
3e0c6947f417f4baf242a7af14c383f8888a6c9d | 740 | java | Java | company-employee-storage-api/src/main/java/com/ebf/storage/api/model/Company.java | gokhan-ebf/company-employee-storage | ad01d2dd7abba90d0f1fdd2ad11deeec83bc16f2 | [
"Apache-2.0"
] | 1 | 2020-05-28T15:12:42.000Z | 2020-05-28T15:12:42.000Z | company-employee-storage-api/src/main/java/com/ebf/storage/api/model/Company.java | gokhan-ebf/company-employee-storage | ad01d2dd7abba90d0f1fdd2ad11deeec83bc16f2 | [
"Apache-2.0"
] | 1 | 2021-03-09T20:31:14.000Z | 2021-03-09T20:31:14.000Z | company-employee-storage-api/src/main/java/com/ebf/storage/api/model/Company.java | gokhan-ebf/company-employee-storage | ad01d2dd7abba90d0f1fdd2ad11deeec83bc16f2 | [
"Apache-2.0"
] | null | null | null | 17.619048 | 55 | 0.617568 | 5,268 | package com.ebf.storage.api.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Table(name = "companies")
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
public Company() {
super();
}
public Company(@NotNull String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
3e0c695ccaa46b0a09b7aa43810021586026ca61 | 1,337 | java | Java | optimuscode-ranking-api/src/main/java/com/optimuscode/ranking/api/Ability.java | sujaybhowmick/online-code-evaluator | 37a684b3eeb6235e2d49b7c374f58709a0e6c341 | [
"Apache-2.0"
] | null | null | null | optimuscode-ranking-api/src/main/java/com/optimuscode/ranking/api/Ability.java | sujaybhowmick/online-code-evaluator | 37a684b3eeb6235e2d49b7c374f58709a0e6c341 | [
"Apache-2.0"
] | null | null | null | optimuscode-ranking-api/src/main/java/com/optimuscode/ranking/api/Ability.java | sujaybhowmick/online-code-evaluator | 37a684b3eeb6235e2d49b7c374f58709a0e6c341 | [
"Apache-2.0"
] | null | null | null | 22.661017 | 81 | 0.587883 | 5,269 | package com.optimuscode.ranking.api;
/**
* Created with IntelliJ IDEA.
* User: sujay
* Date: 11/5/13
* Time: 11:32 AM
* To change this template use File | Settings | File Templates.
*/
public class Ability {
private double mean;
private double variance;
private Ability(final double mean,
final double variance){
this.mean = mean;
this.variance = mean;
}
public static Ability withVariance(final double mean, final double variance){
return new Ability(mean, variance);
}
public static Ability withStddev(final double mean,
final double stdDeviation){
return new Ability(mean, stdDeviation * stdDeviation);
}
public static Ability zero(){
return new Ability(0.0, 0.0);
}
/**
* 68–95–99.7 three sigma rule
* @return
*/
public double skill(){
return this.mean - 3 * stddev();
}
public Ability plus(final Ability other) {
return withVariance(
this.mean + other.mean,
this.variance + other.variance);
}
public double stddev() {
return Math.sqrt(this.variance);
}
public double getMean(){
return this.mean;
}
public double getVariance(){
return this.variance;
}
}
|
3e0c6a7edfbcd6b5c11cfef446e0b2d2615c3817 | 5,926 | java | Java | src/main/java/com/github/trustedworldofcorona/cedar/proxy/ProxyApplication.java | TrustedWorldOfCorona/cedar-sparql-proxy | 401d8747616eaa1f357c9c3d564c0e44610f09c6 | [
"MIT"
] | null | null | null | src/main/java/com/github/trustedworldofcorona/cedar/proxy/ProxyApplication.java | TrustedWorldOfCorona/cedar-sparql-proxy | 401d8747616eaa1f357c9c3d564c0e44610f09c6 | [
"MIT"
] | null | null | null | src/main/java/com/github/trustedworldofcorona/cedar/proxy/ProxyApplication.java | TrustedWorldOfCorona/cedar-sparql-proxy | 401d8747616eaa1f357c9c3d564c0e44610f09c6 | [
"MIT"
] | null | null | null | 40.312925 | 195 | 0.629598 | 5,270 | package com.github.trustedworldofcorona.cedar.proxy;
import com.fasterxml.jackson.annotation.JsonIncludeProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLResultsJSONWriterFactory;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.repository.util.Repositories;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ProxyApplication {
public static void main(String[] args) {
SpringApplication.run(ProxyApplication.class, args);
}
@RestController
static class WebController {
@Value("${cedar.base}")
String base;
@Value("${cedar.token}")
String token;
static final HttpClient client = HttpClient.newHttpClient();
static final ObjectMapper mapper = new ObjectMapper();
/*
curl http://localhost:8080/resource\?id=https://repo.metadatacenter.org/template-instances/2b5fbe93-5439-44af-9c20-b77c6336a1e5&q=SELECT%20\?s%20\?p%20\?o%20%7B%20%3Fs%20%3Fp%20%3Fo%20%7D
*/
@GetMapping("/resource")
String query(@RequestParam String id, @RequestParam String q) {
var repository = new SailRepository(new MemoryStore());
consumeResource(id, repository);
var factory = new SPARQLResultsJSONWriterFactory();
var out = new ByteArrayOutputStream();
var writer = factory.getWriter(out);
Repositories.tupleQueryNoTransaction(repository, q, writer);
return out.toString();
}
/*
folder with single instance:
curl http://localhost:8080/folder\?id=https://repo.metadatacenter.org/folders/b06136a8-d4fb-4ad6-b939-ed1b37ea829d&q=SELECT%20\?s%20\?p%20\?o%20%7B%20%3Fs%20%3Fp%20%3Fo%20%7D
parent folder with subfolders:
curl http://localhost:8080/folder\?id=https://repo.metadatacenter.org/folders/cc9fbb7e-d15f-48db-a123-d20635877a0f&q=SELECT%20\?s%20\?p%20\?o%20%7B%20%3Fs%20%3Fp%20%3Fo%20%7D
*/
@GetMapping("/folder")
String queryFolder(@RequestParam String id, @RequestParam String q) {
var repository = new SailRepository(new MemoryStore());
consumeFolder(id, repository);
var factory = new SPARQLResultsJSONWriterFactory();
var out = new ByteArrayOutputStream();
var writer = factory.getWriter(out);
Repositories.tupleQueryNoTransaction(repository, q, writer);
return out.toString();
}
void consumeFolder(String id, Repository repository) {
final InputStream body;
try {
var req = HttpRequest.newBuilder()
.header("Authorization", token)
.header("Accept", "application/json")
.uri(URI.create(base + "/folders/"+URLEncoder.encode(id, StandardCharsets.UTF_8)+"/contents?resource_types=folder,instance"))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofInputStream());
body = resp.body();
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
final FolderResponse response;
try {
response = mapper.readValue(body, FolderResponse.class);
} catch (IOException e) {
throw new IllegalStateException(e);
}
for (var res : response.resources) {
if ("folder".equals(res.resourceType)) {
consumeFolder(res.id, repository);
} else if ("instance".equals(res.resourceType)) {
consumeResource(res.id, repository);
}
}
}
void consumeResource(String id, Repository repository) {
final InputStream body;
try {
var req = HttpRequest.newBuilder()
.uri(URI.create(id))
.header("Authorization", token)
.header("Accept", "application/json")
.build();
var response = client.send(req, HttpResponse.BodyHandlers.ofInputStream());
body = response.body();
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
Repositories.consume(repository, conn -> {
try {
conn.add(body, RDFFormat.JSONLD);
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
}
}
@JsonIncludeProperties("resources")
static class FolderResponse {
@JsonProperty
ArrayList<FolderResource> resources;
}
@JsonIncludeProperties({ "resourceType", "@id" })
static class FolderResource {
@JsonProperty
String resourceType;
@JsonProperty("@id")
String id;
}
}
|
3e0c6af62381086f21434b05b908704689d33022 | 703 | java | Java | ClickEffect/app/src/main/java/com/mjj/clickeffect/StateListAnimActivity.java | haloxxg/Android | 922084bb792f8e73ce91f6edb0c4c681b6a905c7 | [
"MIT"
] | 465 | 2015-09-30T08:20:44.000Z | 2022-03-08T08:37:00.000Z | ClickEffect/app/src/main/java/com/mjj/clickeffect/StateListAnimActivity.java | haloxxg/Android | 922084bb792f8e73ce91f6edb0c4c681b6a905c7 | [
"MIT"
] | 4 | 2015-10-18T08:54:36.000Z | 2019-11-12T10:02:48.000Z | ClickEffect/app/src/main/java/com/mjj/clickeffect/StateListAnimActivity.java | haloxxg/Android | 922084bb792f8e73ce91f6edb0c4c681b6a905c7 | [
"MIT"
] | 343 | 2015-10-22T02:57:00.000Z | 2022-03-10T03:50:08.000Z | 24.241379 | 77 | 0.805121 | 5,271 | package com.mjj.clickeffect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.mjj.clickeffect.adapter.StateListAnimAdapter;
public class StateListAnimActivity extends ABSActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statelistanim);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new StateListAnimAdapter());
}
public void itemClick(View v){
}
}
|
3e0c6bbac2895f7511d87129167152b3914597eb | 923 | java | Java | lab1/lab1_solutionOfB.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | lab1/lab1_solutionOfB.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | lab1/lab1_solutionOfB.java | Uncle-Road/CS203_Dsaa | f6ffa4993ea5d1505d0b8d909b49b9161b576673 | [
"MIT"
] | null | null | null | 27.969697 | 51 | 0.462622 | 5,272 | package com.company;
import java.util.Scanner;
public class lab1_solutionOfB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int times = scanner.nextInt();
for (int i = 0; i < times; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int n = scanner.nextInt();
String a1 = Integer.toBinaryString(a);
String b1 = Integer.toBinaryString(b);
int a2 = Integer.valueOf(a1, 2);
int b2 = Integer.valueOf(b1, 2);
int yushu = n % 3;
if (yushu == 0) {
System.out.println(a);
} else if (yushu == 1) {
System.out.println(b);
} else if (yushu == 2) {
int num = a2 ^ b2;
System.out.println(num);
}
}
}
}
|
3e0c6c7cc55abf398d85de8194ed691742334bd8 | 1,598 | java | Java | kettle-plugins/mapreduce/src/main/java/org/pentaho/big/data/kettle/plugins/mapreduce/entry/UserDefinedItem.java | rusxakep/big-data-plugin | f8cca06dbe3856471917937ddbbca16e8ee19c9f | [
"Apache-2.0"
] | 158 | 2015-01-06T06:06:52.000Z | 2022-03-18T03:06:51.000Z | kettle-plugins/mapreduce/src/main/java/org/pentaho/big/data/kettle/plugins/mapreduce/entry/UserDefinedItem.java | rusxakep/big-data-plugin | f8cca06dbe3856471917937ddbbca16e8ee19c9f | [
"Apache-2.0"
] | 1,575 | 2015-01-08T03:42:57.000Z | 2022-03-31T20:39:19.000Z | kettle-plugins/mapreduce/src/main/java/org/pentaho/big/data/kettle/plugins/mapreduce/entry/UserDefinedItem.java | rusxakep/big-data-plugin | f8cca06dbe3856471917937ddbbca16e8ee19c9f | [
"Apache-2.0"
] | 285 | 2015-01-16T17:53:00.000Z | 2022-03-30T13:38:30.000Z | 27.084746 | 80 | 0.616395 | 5,273 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.kettle.plugins.mapreduce.entry;
import org.pentaho.ui.xul.XulEventSource;
import java.beans.PropertyChangeListener;
public class UserDefinedItem implements XulEventSource {
private String name;
private String value;
public UserDefinedItem() {
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue( String value ) {
this.value = value;
}
public void addPropertyChangeListener( PropertyChangeListener listener ) {
}
public void removePropertyChangeListener( PropertyChangeListener listener ) {
}
}
|
3e0c6cdf1341789281116239d8c90e2b4cd545cc | 1,069 | java | Java | springsecurityoauth2demo/src/main/java/fun/fibreyu/springsecurityoauth2demo/config/JwtTokenStoreConfig.java | fibreyu/SpringSecurity_Demo | 3502eadb72682cd49f0becc6a07caf32dfd98261 | [
"Apache-2.0"
] | null | null | null | springsecurityoauth2demo/src/main/java/fun/fibreyu/springsecurityoauth2demo/config/JwtTokenStoreConfig.java | fibreyu/SpringSecurity_Demo | 3502eadb72682cd49f0becc6a07caf32dfd98261 | [
"Apache-2.0"
] | null | null | null | springsecurityoauth2demo/src/main/java/fun/fibreyu/springsecurityoauth2demo/config/JwtTokenStoreConfig.java | fibreyu/SpringSecurity_Demo | 3502eadb72682cd49f0becc6a07caf32dfd98261 | [
"Apache-2.0"
] | null | null | null | 28.131579 | 88 | 0.745557 | 5,274 | package fun.fibreyu.springsecurityoauth2demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
/**
* @author fibreyu
* @since 1.0.0
*/
@Configuration
public class JwtTokenStoreConfig {
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 将oauth2生成的token转为jwt格式
* @return
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
// 设置密钥
jwtAccessTokenConverter.setSigningKey("test_key");
return jwtAccessTokenConverter;
}
@Bean
public JwtTokenEnhancer jwtTokenEnhancer() {
return new JwtTokenEnhancer();
}
}
|
3e0c6d3145e3479739fe9231064c5065761539a2 | 345 | java | Java | src/main/java/io/github/linuxforhealth/rules/fact/StringValueType.java | LinuxForHealth/dicom-rules-engine | aec3f7498cf747a4c1c449794b2a88b3709a5a65 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/linuxforhealth/rules/fact/StringValueType.java | LinuxForHealth/dicom-rules-engine | aec3f7498cf747a4c1c449794b2a88b3709a5a65 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/linuxforhealth/rules/fact/StringValueType.java | LinuxForHealth/dicom-rules-engine | aec3f7498cf747a4c1c449794b2a88b3709a5a65 | [
"Apache-2.0"
] | null | null | null | 13.269231 | 51 | 0.684058 | 5,275 | /*
* (C) Copyright IBM Corp. 2021
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.github.linuxforhealth.rules.fact;
public class StringValueType implements ValueType {
private String value;
public StringValueType(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
}
|
3e0c6dd4973e356db8f140999b56d5372722fbff | 2,130 | java | Java | hazelcast/src/test/java/com/hazelcast/query/impl/extractor/predicates/SingleValueDataStructure.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 4,283 | 2015-01-02T03:56:10.000Z | 2022-03-29T23:07:45.000Z | hazelcast/src/test/java/com/hazelcast/query/impl/extractor/predicates/SingleValueDataStructure.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 14,014 | 2015-01-01T04:29:38.000Z | 2022-03-31T21:47:55.000Z | hazelcast/src/test/java/com/hazelcast/query/impl/extractor/predicates/SingleValueDataStructure.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 1,608 | 2015-01-04T09:57:08.000Z | 2022-03-31T12:05:26.000Z | 26.962025 | 98 | 0.622066 | 5,276 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.query.impl.extractor.predicates;
import com.hazelcast.test.ObjectTestUtils;
import java.io.Serializable;
/**
* Data structure used in the tests of extraction in single-value attributes (not in collections).
*/
public final class SingleValueDataStructure {
private SingleValueDataStructure() {
}
public static class Person implements Serializable {
Brain brain;
@Override
public boolean equals(Object o) {
if (!(o instanceof Person)) {
return false;
}
Person other = (Person) o;
return ObjectTestUtils.equals(this.brain, other.brain);
}
@Override
public int hashCode() {
return ObjectTestUtils.hashCode(brain);
}
}
public static class Brain implements Serializable {
Integer iq;
String name;
@Override
public boolean equals(Object o) {
if (!(o instanceof Brain)) {
return false;
}
Brain other = (Brain) o;
return ObjectTestUtils.equals(this.iq, other.iq);
}
@Override
public int hashCode() {
return ObjectTestUtils.hashCode(iq);
}
}
public static Person person(Integer iq) {
Brain brain = new Brain();
brain.iq = iq;
brain.name = "brain" + iq;
Person person = new Person();
person.brain = brain;
return person;
}
}
|
3e0c6e481fd5a69b6925d17dc8fbd82e190aaeaf | 612 | java | Java | src/main/java/com/febs/common/authentication/ShiroSessionListener.java | liubaixing/febs-dev | b1b3b804d98e2618a50be5ecaec322ede738e367 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/febs/common/authentication/ShiroSessionListener.java | liubaixing/febs-dev | b1b3b804d98e2618a50be5ecaec322ede738e367 | [
"Apache-2.0"
] | 1 | 2022-02-09T22:26:07.000Z | 2022-02-09T22:26:07.000Z | src/main/java/com/febs/common/authentication/ShiroSessionListener.java | liubaixing/febs-dev | b1b3b804d98e2618a50be5ecaec322ede738e367 | [
"Apache-2.0"
] | null | null | null | 20.4 | 65 | 0.779412 | 5,277 | package com.febs.common.authentication;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author MrBird
*/
public class ShiroSessionListener implements SessionListener{
private final AtomicInteger sessionCount = new AtomicInteger(0);
@Override
public void onStart(Session session) {
sessionCount.incrementAndGet();
}
@Override
public void onStop(Session session) {
sessionCount.decrementAndGet();
}
@Override
public void onExpiration(Session session) {
sessionCount.decrementAndGet();
}
}
|
3e0c6e4bbe0f8f24c332a7420b009b453513bbed | 477 | java | Java | src/main/java/com/stanrnd/excel/Sheet.java | stanslab/excel-generator | 83c698f8fd1a30cced90d982d916ccd25ab769f4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/stanrnd/excel/Sheet.java | stanslab/excel-generator | 83c698f8fd1a30cced90d982d916ccd25ab769f4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/stanrnd/excel/Sheet.java | stanslab/excel-generator | 83c698f8fd1a30cced90d982d916ccd25ab769f4 | [
"Apache-2.0"
] | null | null | null | 12.552632 | 45 | 0.610063 | 5,278 | package com.stanrnd.excel;
import java.util.List;
/**
*
* @author Stalin
*
*/
public class Sheet {
private Class<?> clazz;
private List<?> data;
public Sheet(Class<?> clazz, List<?> data) {
this.clazz = clazz;
this.data = data;
}
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
public List<?> getData() {
return data;
}
public void setData(List<?> data) {
this.data = data;
}
}
|
3e0c6ecc07f8aa82c837d712873ce91311bf9498 | 1,390 | java | Java | basics/src/test/java/ca/wbac/callbags/basics/helpers/PushableSource.java | mr-rampage/java-callbags | 65217ee181022e20717b0b3ca553bfaf485a694b | [
"CC0-1.0"
] | 1 | 2019-05-30T08:52:24.000Z | 2019-05-30T08:52:24.000Z | basics/src/test/java/ca/wbac/callbags/basics/helpers/PushableSource.java | mr-rampage/java-callbags | 65217ee181022e20717b0b3ca553bfaf485a694b | [
"CC0-1.0"
] | null | null | null | basics/src/test/java/ca/wbac/callbags/basics/helpers/PushableSource.java | mr-rampage/java-callbags | 65217ee181022e20717b0b3ca553bfaf485a694b | [
"CC0-1.0"
] | null | null | null | 27.8 | 87 | 0.558273 | 5,279 | package ca.wbac.callbags.basics.helpers;
import ca.wbac.callbags.core.Sink;
import ca.wbac.callbags.core.Source;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CompletableFuture;
public final class PushableSource<T> implements Source<T> {
private final Timer timer = new Timer();
private final CompletableFuture<Integer> completableFuture;
private final List<T> list;
private Sink<T> sink;
private boolean started = false;
public PushableSource(List<T> list, CompletableFuture<Integer> completableFuture) {
this.completableFuture = completableFuture;
this.list = list;
}
@Override
public void greet(Sink<T> sink) {
this.sink = sink;
sink.greet(this);
}
@Override
public void request() {
if (!started) {
started = true;
timer.scheduleAtFixedRate(new TimerTask() {
private int sent = 0;
@Override
public void run() {
if (sent == list.size()) {
timer.cancel();
completableFuture.complete(sent);
sink.terminate();
} else {
sink.deliver(list.get(sent++));
}
}
}, 0, 1);
}
}
}
|
3e0c6ef3dcda7f9cc6e9525cb51bbf868d03cd89 | 2,452 | java | Java | proto-google-cloud-redis-v1beta1/src/main/java/com/google/cloud/redis/v1beta1/UpgradeInstanceRequestOrBuilder.java | pmakani/java-redis | e7c1a6114ad176f109fd1b8fbd10e90bc0c2d230 | [
"Apache-2.0"
] | 8 | 2020-09-19T12:38:13.000Z | 2022-02-12T07:48:31.000Z | proto-google-cloud-redis-v1beta1/src/main/java/com/google/cloud/redis/v1beta1/UpgradeInstanceRequestOrBuilder.java | pmakani/java-redis | e7c1a6114ad176f109fd1b8fbd10e90bc0c2d230 | [
"Apache-2.0"
] | 483 | 2019-10-25T21:43:19.000Z | 2022-03-30T09:33:03.000Z | proto-google-cloud-redis-v1beta1/src/main/java/com/google/cloud/redis/v1beta1/UpgradeInstanceRequestOrBuilder.java | pmakani/java-redis | e7c1a6114ad176f109fd1b8fbd10e90bc0c2d230 | [
"Apache-2.0"
] | 14 | 2019-10-25T21:05:41.000Z | 2021-08-24T16:54:32.000Z | 29.190476 | 105 | 0.668842 | 5,280 | /*
* Copyright 2020 Google LLC
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/redis/v1beta1/cloud_redis.proto
package com.google.cloud.redis.v1beta1;
public interface UpgradeInstanceRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.redis.v1beta1.UpgradeInstanceRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. Redis instance resource name using the form:
* `projects/{project_id}/locations/{location_id}/instances/{instance_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Required. Redis instance resource name using the form:
* `projects/{project_id}/locations/{location_id}/instances/{instance_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* Required. Specifies the target version of Redis software to upgrade to.
* </pre>
*
* <code>string redis_version = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The redisVersion.
*/
java.lang.String getRedisVersion();
/**
*
*
* <pre>
* Required. Specifies the target version of Redis software to upgrade to.
* </pre>
*
* <code>string redis_version = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for redisVersion.
*/
com.google.protobuf.ByteString getRedisVersionBytes();
}
|
3e0c7029b6a676fb6d57dd51e547f06d623fbff1 | 4,464 | java | Java | math/src/test/java/org/apache/mahout/math/stats/OnlineSummarizerTest.java | shihken/mahout-cloudera | 53b897fd02110000b399f418f0e5a9338686505e | [
"Apache-2.0"
] | 1 | 2019-02-23T00:49:13.000Z | 2019-02-23T00:49:13.000Z | math/src/test/java/org/apache/mahout/math/stats/OnlineSummarizerTest.java | shihken/mahout-cloudera | 53b897fd02110000b399f418f0e5a9338686505e | [
"Apache-2.0"
] | null | null | null | math/src/test/java/org/apache/mahout/math/stats/OnlineSummarizerTest.java | shihken/mahout-cloudera | 53b897fd02110000b399f418f0e5a9338686505e | [
"Apache-2.0"
] | null | null | null | 33.56391 | 102 | 0.605959 | 5,281 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.math.stats;
import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.math.MahoutTestCase;
import org.apache.mahout.math.jet.random.AbstractContinousDistribution;
import org.apache.mahout.math.jet.random.Gamma;
import org.junit.Test;
import java.util.Random;
public final class OnlineSummarizerTest extends MahoutTestCase {
@Test
public void testCount() {
OnlineSummarizer x = new OnlineSummarizer();
assertEquals(0, x.getCount());
x.add(1);
assertEquals(1, x.getCount());
for (int i = 2; i < 110; i++) {
x.add(i);
assertEquals(i, x.getCount());
}
}
@Test
public void testStats() {
// the reference limits here were derived using a numerical simulation where I took
// 10,000 samples from the distribution in question and computed the stats from that
// sample to get min, 25%-ile, median and so on. I did this 1000 times to get 5% and
// 95% confidence limits for those values.
// symmetrical, well behaved
System.out.printf("normal\n");
check(normal(10000),
-4.417246, -3.419809,
-0.6972919, -0.6519899,
-0.02056658, 0.02176474,
0.6503866, 0.6983311,
4.419809, 5.417246,
-0.01515753, 0.01592942,
0.988395, 1.011883);
// asymmetrical, well behaved. The range for the maximum was fudged slightly to all this to pass.
System.out.printf("exp\n");
check(exp(10000),
-3e-4, 3.278763e-04,
0.2783866, 0.298,
0.6765024, 0.7109463,
1.356929, 1.414761,
8, 20,
0.983805, 1.015920,
0.977162, 1.022093
);
// asymmetrical, wacko distribution where mean/median is about 200
System.out.printf("gamma\n");
check(gamma(10000, 0.1),
-5e-30, 5e-30, // minimum
3.8e-6, 8.6e-6, // 25th %-ile
0.004847959, 0.007234259, // median
0.3074556, 0.4049404, // 75th %-ile
45, 100, // maximum
0.9, 1.1, // mean
2.8, 3.5); // standard dev
}
private static void check(OnlineSummarizer x, double... values) {
for (int i = 0; i < 5; i++) {
checkRange("quartile " + i, x.getQuartile(i), values[2 * i], values[2 * i + 1]);
}
assertEquals(x.getQuartile(2), x.getMedian(), 0);
checkRange("mean", x.getMean(), values[10], values[11]);
checkRange("sd", x.getSD(), values[12], values[13]);
}
private static void checkRange(String msg, double v, double low, double high) {
if (v < low || v > high) {
fail("Wanted " + msg + " to be in range [" + low + ',' + high + "] but got " + v);
}
}
private static OnlineSummarizer normal(int n) {
OnlineSummarizer x = new OnlineSummarizer();
Random gen = RandomUtils.getRandom(1L);
for (int i = 0; i < n; i++) {
x.add(gen.nextGaussian());
}
return x;
}
private static OnlineSummarizer exp(int n) {
OnlineSummarizer x = new OnlineSummarizer();
Random gen = RandomUtils.getRandom(1L);
for (int i = 0; i < n; i++) {
x.add(-Math.log1p(-gen.nextDouble()));
}
return x;
}
private static OnlineSummarizer gamma(int n, double shape) {
OnlineSummarizer x = new OnlineSummarizer();
Random gen = RandomUtils.getRandom();
AbstractContinousDistribution gamma = new Gamma(shape, shape, gen);
for (int i = 0; i < n; i++) {
x.add(gamma.nextDouble());
}
return x;
}
}
|
3e0c70e4a731830ebaf687ea3dcf37a23f96e853 | 1,670 | java | Java | src/com/kylecorry/ml4k/ModelStatus.java | kylecorry31/ML4K-AI-Extension | 5065c87ce4ce37ff23753f36bbb8074ea2849140 | [
"MIT"
] | 18 | 2018-07-31T01:26:00.000Z | 2021-12-05T13:30:19.000Z | src/com/kylecorry/ml4k/ModelStatus.java | kylecorry31/ML4K-AI-Extension | 5065c87ce4ce37ff23753f36bbb8074ea2849140 | [
"MIT"
] | 35 | 2018-07-17T18:24:53.000Z | 2022-03-21T10:07:44.000Z | src/com/kylecorry/ml4k/ModelStatus.java | kylecorry31/ML4K-AI-Extension | 5065c87ce4ce37ff23753f36bbb8074ea2849140 | [
"MIT"
] | 15 | 2018-08-03T01:29:49.000Z | 2021-12-05T13:30:25.000Z | 26.935484 | 76 | 0.581437 | 5,282 | package com.kylecorry.ml4k;
class ModelStatus {
private int statusCode;
private String message;
private String projectType;
/**
* Default constructor
* @param statusCode the status code
* @param message the message
*/
private ModelStatus(int statusCode, String message, String projectType){
this.statusCode = statusCode;
this.message = message;
this.projectType = projectType;
}
/**
* Loads a model status from JSON
* @param json the JSON
* @return the model status
* @throws ML4KException if the JSON does not represent a model status
*/
public static ModelStatus fromJson(String json) throws ML4KException {
int code = JSONUtils.readIntProperty(json, "status");
String message = JSONUtils.readStringProperty(json, "msg");
String type = JSONUtils.readStringProperty(json, "type");
if (message == null || type == null){
throw new ML4KException("JSON is not valid: " + json);
}
return new ModelStatus(code, message, type);
}
/**
* @return the status code (0 = error, 1 = training, 2 = ready)
*/
public int getStatusCode(){
return statusCode;
}
/**
* @return the message
*/
public String getMessage(){
return message;
}
public String getProjectType(){
return projectType;
}
@Override
public String toString() {
return "ModelStatus{" +
"statusCode=" + statusCode +
", message='" + message + '\'' +
", type='" + projectType + '\'' +
'}';
}
}
|
3e0c710a4e4b49538e0dad5d1979df9566a38576 | 7,568 | java | Java | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java | master-starcloud/micrometer | faedc1cbc73a9ff0eb99e265a762b63ade83d7f7 | [
"Apache-2.0"
] | 3,292 | 2017-07-21T02:33:05.000Z | 2022-03-31T16:15:23.000Z | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java | master-starcloud/micrometer | faedc1cbc73a9ff0eb99e265a762b63ade83d7f7 | [
"Apache-2.0"
] | 2,355 | 2017-07-20T21:57:08.000Z | 2022-03-31T22:55:05.000Z | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/okhttp3/OkHttpConnectionPoolMetrics.java | master-starcloud/micrometer | faedc1cbc73a9ff0eb99e265a762b63ade83d7f7 | [
"Apache-2.0"
] | 892 | 2017-07-24T13:44:05.000Z | 2022-03-30T19:48:07.000Z | 41.582418 | 138 | 0.645745 | 5,283 | /**
* Copyright 2020 VMware, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.core.instrument.binder.okhttp3;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.binder.BaseUnits;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.lang.NonNull;
import okhttp3.ConnectionPool;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
/**
* MeterBinder for collecting metrics of a given OkHttp {@link ConnectionPool}.
* <p>
* Example usage:
* <pre>
* ConnectionPool connectionPool = new ConnectionPool(connectionPoolSize, connectionPoolKeepAliveMs, TimeUnit.MILLISECONDS);
* new OkHttpConnectionPoolMetrics(connectionPool).bindTo(registry);
* </pre>
*
* @author Ben Hubert
* @since 1.6.0
*/
public class OkHttpConnectionPoolMetrics implements MeterBinder {
private static final String DEFAULT_NAME_PREFIX = "okhttp.pool";
private static final String TAG_STATE = "state";
private final ConnectionPool connectionPool;
private final String namePrefix;
private final Iterable<Tag> tags;
private final Double maxIdleConnectionCount;
private final ThreadLocal<ConnectionPoolConnectionStats> connectionStats = new ThreadLocal<>();
/**
* Creates a meter binder for the given connection pool.
* Metrics will be exposed using {@value #DEFAULT_NAME_PREFIX} as name prefix.
*
* @param connectionPool The connection pool to monitor. Must not be null.
*/
public OkHttpConnectionPoolMetrics(ConnectionPool connectionPool) {
this(connectionPool, DEFAULT_NAME_PREFIX, Collections.emptyList(), null);
}
/**
* Creates a meter binder for the given connection pool.
* Metrics will be exposed using {@value #DEFAULT_NAME_PREFIX} as name prefix.
*
* @param connectionPool The connection pool to monitor. Must not be null.
* @param tags A list of tags which will be passed for all meters. Must not be null.
*/
public OkHttpConnectionPoolMetrics(ConnectionPool connectionPool, Iterable<Tag> tags) {
this(connectionPool, DEFAULT_NAME_PREFIX, tags, null);
}
/**
* Creates a meter binder for the given connection pool.
*
* @param connectionPool The connection pool to monitor. Must not be null.
* @param namePrefix The desired name prefix for the exposed metrics. Must not be null.
* @param tags A list of tags which will be passed for all meters. Must not be null.
*/
public OkHttpConnectionPoolMetrics(ConnectionPool connectionPool, String namePrefix, Iterable<Tag> tags) {
this(connectionPool, namePrefix, tags, null);
}
/**
* Creates a meter binder for the given connection pool.
*
* @param connectionPool The connection pool to monitor. Must not be null.
* @param namePrefix The desired name prefix for the exposed metrics. Must not be null.
* @param tags A list of tags which will be passed for all meters. Must not be null.
* @param maxIdleConnections The maximum number of idle connections this pool will hold. This
* value is passed to the {@link ConnectionPool} constructor but is
* not exposed by this instance. Therefore this binder allows to pass
* it, to be able to monitor it.
*/
public OkHttpConnectionPoolMetrics(ConnectionPool connectionPool, String namePrefix, Iterable<Tag> tags, Integer maxIdleConnections) {
if (connectionPool == null) {
throw new IllegalArgumentException("Given ConnectionPool must not be null.");
}
if (namePrefix == null) {
throw new IllegalArgumentException("Given name prefix must not be null.");
}
if (tags == null) {
throw new IllegalArgumentException("Given list of tags must not be null.");
}
this.connectionPool = connectionPool;
this.namePrefix = namePrefix;
this.tags = tags;
this.maxIdleConnectionCount = Optional.ofNullable(maxIdleConnections)
.map(Integer::doubleValue)
.orElse(null);
}
@Override
public void bindTo(@NonNull MeterRegistry registry) {
String connectionCountName = namePrefix + ".connection.count";
Gauge.builder(connectionCountName, connectionStats,
cs -> {
if (cs.get() == null) {
cs.set(new ConnectionPoolConnectionStats());
}
return cs.get().getActiveCount();
})
.baseUnit(BaseUnits.CONNECTIONS)
.description("The state of connections in the OkHttp connection pool")
.tags(Tags.of(tags).and(TAG_STATE, "active"))
.register(registry);
Gauge.builder(connectionCountName, connectionStats,
cs -> {
if (cs.get() == null) {
cs.set(new ConnectionPoolConnectionStats());
}
return cs.get().getIdleConnectionCount();
})
.baseUnit(BaseUnits.CONNECTIONS)
.description("The state of connections in the OkHttp connection pool")
.tags(Tags.of(tags).and(TAG_STATE, "idle"))
.register(registry);
if (this.maxIdleConnectionCount != null) {
Gauge.builder(namePrefix + ".connection.limit", () -> this.maxIdleConnectionCount)
.baseUnit(BaseUnits.CONNECTIONS)
.description("The maximum idle connection count in an OkHttp connection pool.")
.tags(Tags.concat(tags))
.register(registry);
}
}
/**
* Allow us to coordinate between active and idle, making sure they always sum to the total available connections.
* Since we're calculating active from total-idle, we want to synchronize on idle to make sure the sum is accurate.
*/
private final class ConnectionPoolConnectionStats {
private CountDownLatch uses = new CountDownLatch(0);
private int idle;
private int total;
public int getActiveCount() {
snapshotStatsIfNecessary();
uses.countDown();
return total - idle;
}
public int getIdleConnectionCount() {
snapshotStatsIfNecessary();
uses.countDown();
return idle;
}
private void snapshotStatsIfNecessary() {
if (uses.getCount() == 0) {
idle = connectionPool.idleConnectionCount();
total = connectionPool.connectionCount();
uses = new CountDownLatch(2);
}
}
}
}
|
3e0c716c506d39713cfa2d697a162b6371515615 | 7,854 | java | Java | languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/editor/HeadSetOperation_EditorBuilder_a.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/editor/HeadSetOperation_EditorBuilder_a.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/editor/HeadSetOperation_EditorBuilder_a.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 46.2 | 236 | 0.786351 | 5,284 | package jetbrains.mps.baseLanguage.collections.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.baseLanguage.collections.editor.Collections_Style_StyleSheet.OperationStyleClass;
import jetbrains.mps.nodeEditor.cellMenu.CompositeSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.BasicCellContext;
import jetbrains.mps.nodeEditor.cellMenu.SubstituteInfoPartExt;
import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfoPartEx;
import jetbrains.mps.lang.editor.generator.internal.AbstractCellMenuPart_ReplaceNode_CustomNodeConcept;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import jetbrains.mps.openapi.editor.menus.EditorMenuDescriptor;
import jetbrains.mps.nodeEditor.cellMenu.CellContext;
import jetbrains.mps.lang.editor.menus.EditorMenuDescriptorBase;
import jetbrains.mps.smodel.SNodePointer;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.baseLanguage.editor.BaseLanguageStyle_StyleSheet.LeftParenAfterNameStyleClass;
import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.openapi.editor.cells.CellActionType;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSmart;
import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SEmptyContainmentSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo;
import jetbrains.mps.openapi.editor.menus.transformation.SNodeLocation;
import jetbrains.mps.baseLanguage.editor.BaseLanguageStyle_StyleSheet.RightParenStyleClass;
import org.jetbrains.mps.openapi.language.SInterfaceConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
/*package*/ class HeadSetOperation_EditorBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public HeadSetOperation_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_0();
}
private EditorCell createCollection_0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_tt6i8z_a");
editorCell.setBig(true);
setCellContext(editorCell);
editorCell.addEditorCell(createComponent_0());
editorCell.addEditorCell(createConstant_0());
editorCell.addEditorCell(createRefNode_0());
editorCell.addEditorCell(createConstant_1());
return editorCell;
}
private EditorCell createComponent_0() {
EditorCell editorCell = getCellFactory().createEditorComponentCell(myNode, "jetbrains.mps.lang.core.editor.alias");
Style style = new StyleImpl();
new OperationStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new CompositeSubstituteInfo(getEditorContext(), new BasicCellContext(myNode), new SubstituteInfoPartExt[]{new ReplaceWith_IOperation_cellMenu_tt6i8z_a0a0(), new SChildSubstituteInfoPartEx(editorCell)}));
return editorCell;
}
public static class ReplaceWith_IOperation_cellMenu_tt6i8z_a0a0 extends AbstractCellMenuPart_ReplaceNode_CustomNodeConcept {
public ReplaceWith_IOperation_cellMenu_tt6i8z_a0a0() {
}
public SAbstractConcept getReplacementConcept() {
return CONCEPTS.IOperation$ga;
}
@Override
protected EditorMenuDescriptor createEditorMenuDescriptor(CellContext cellContext, EditorContext editorContext) {
return new EditorMenuDescriptorBase("replace node (custom node concept: " + "IOperation" + ")", new SNodePointer("r:00000000-0000-4000-0000-011c8959032a(jetbrains.mps.baseLanguage.collections.editor)", "2886182022232400093"));
}
}
private EditorCell createConstant_0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "(");
editorCell.setCellId("Constant_tt6i8z_b0");
Style style = new StyleImpl();
new LeftParenAfterNameStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_0() {
SingleRoleCellProvider provider = new toElementSingleRoleHandler_tt6i8z_c0(myNode, LINKS.toElement$K86l, getEditorContext());
return provider.createCell();
}
private static class toElementSingleRoleHandler_tt6i8z_c0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public toElementSingleRoleHandler_tt6i8z_c0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), LINKS.toElement$K86l, child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), LINKS.toElement$K86l, child));
installCellInfo(child, editorCell, false);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell, boolean isEmpty) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo((isEmpty ? new SEmptyContainmentSubstituteInfo(editorCell) : new SChildSubstituteInfo(editorCell)));
}
if (editorCell.getSRole() == null) {
editorCell.setSRole(LINKS.toElement$K86l);
}
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), LINKS.toElement$K86l));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_toElement");
installCellInfo(null, editorCell, true);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no toElement>";
}
}
private EditorCell createConstant_1() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ")");
editorCell.setCellId("Constant_tt6i8z_d0");
Style style = new StyleImpl();
new RightParenStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private static final class CONCEPTS {
/*package*/ static final SInterfaceConcept IOperation$ga = MetaAdapterFactory.getInterfaceConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x116b46ac030L, "jetbrains.mps.baseLanguage.structure.IOperation");
}
private static final class LINKS {
/*package*/ static final SContainmentLink toElement$K86l = MetaAdapterFactory.getContainmentLink(0x8388864671ce4f1cL, 0x9c53c54016f6ad4fL, 0x120c4bdd40dL, 0x120c4be03acL, "toElement");
}
}
|
3e0c71bc8afe18225e41fad963b10d4926c2b568 | 1,336 | java | Java | src/main/java/dailydiary/handlers/builtin/FallbackIntentHandler.java | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-DailyDiary | d65d1193e09fe6b9dcbcc3ad0290ccd1e7a0c65d | [
"Apache-2.0"
] | null | null | null | src/main/java/dailydiary/handlers/builtin/FallbackIntentHandler.java | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-DailyDiary | d65d1193e09fe6b9dcbcc3ad0290ccd1e7a0c65d | [
"Apache-2.0"
] | null | null | null | src/main/java/dailydiary/handlers/builtin/FallbackIntentHandler.java | MUAS-DTLab-WiSe19-20-Alexa-Demenz/WiSe19-20-Alexa-Demenz-DailyDiary | d65d1193e09fe6b9dcbcc3ad0290ccd1e7a0c65d | [
"Apache-2.0"
] | null | null | null | 35.157895 | 92 | 0.725299 | 5,285 | package dailydiary.handlers.builtin;
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Response;
import dailydiary.handlers.DailyDiaryRequestHandler;
import java.util.Optional;
import static com.amazon.ask.request.Predicates.intentName;
// 2018-July-09: AMAZON.FallackIntent is only currently available in en-US locale.
// This handler will not be triggered except in that locale, so it can be
// safely deployed for any locale.
/**
* RequestHanlder for fallback conversation
*/
public class FallbackIntentHandler implements RequestHandler {
public static final String TXT_RESPONSE = "Tut mir leid. Das habe ich nicht verstanden."
+ " Sage einfach Hilfe, wenn du Unterstützung brauchst.";
@Override
public boolean canHandle(HandlerInput input) {
return input.matches(intentName("AMAZON.FallbackIntent"));
}
@Override
public Optional<Response> handle(HandlerInput input) {
return input.getResponseBuilder()
.withSimpleCard(DailyDiaryRequestHandler.RESPONSE_CARD_TITLE, TXT_RESPONSE)
.withSpeech(TXT_RESPONSE)
.withReprompt(TXT_RESPONSE)
.withShouldEndSession(false).build();
}
}
|
3e0c71c447f5297236f84f2a869203ef9c8f48c6 | 7,645 | java | Java | src/common/com/pinhuba/common/util/WorkCalenderMonth.java | cgs1999/mybams | 2e40e9792c241971d7fab7d9cae4b54ba30dd382 | [
"Apache-2.0"
] | null | null | null | src/common/com/pinhuba/common/util/WorkCalenderMonth.java | cgs1999/mybams | 2e40e9792c241971d7fab7d9cae4b54ba30dd382 | [
"Apache-2.0"
] | null | null | null | src/common/com/pinhuba/common/util/WorkCalenderMonth.java | cgs1999/mybams | 2e40e9792c241971d7fab7d9cae4b54ba30dd382 | [
"Apache-2.0"
] | null | null | null | 39.005102 | 202 | 0.626684 | 5,286 | package com.pinhuba.common.util;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.pinhuba.core.pojo.OaCalender;
public class WorkCalenderMonth {
private Map<Integer, List<OaCalender>> map = new HashMap<Integer, List<OaCalender>>();// 存放查询出来的日程
private HttpServletRequest reqeust;
/**
* @return the map
*/
String[] months = { "一 月", "二 月", "三 月", "四 月", "五 月", "六 月", "七 月", "八 月", "九 月", "十 月", "十一月", "十二月" };
int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int displayMonth;
int displayYear;
int todayYear;
int todayMonth;
int todayDay;
public WorkCalenderMonth() {
Calendar cal = Calendar.getInstance();
this.displayYear = cal.get(1);
this.displayMonth = cal.get(2);
this.todayYear = this.displayYear;
this.todayMonth = this.displayMonth;
this.todayDay = cal.get(5);
}
public int getDays(int month, int year) {
if (1 == month) {
return ((((0 == year % 4) && (0 != year % 100)) || (0 == year % 400)) ? 29 : 28);
}
return this.daysInMonth[month];
}
public String newCalendar(int displayYear, int displayMonth,HttpServletRequest request) {
this.displayYear = displayYear;
this.displayMonth = displayMonth;
Calendar newCal = Calendar.getInstance();
newCal.set(displayYear, displayMonth, 1);
int day = -1;
int startDayOfWeek = newCal.get(7);
if ((this.todayYear == newCal.get(1)) && (this.todayMonth == newCal.get(2))) {
day = this.todayDay;
}
int intDaysInMonth = getDays(newCal.get(2), newCal.get(1));
String daysGrid = makeDaysGrid(startDayOfWeek, day, intDaysInMonth, newCal);
return daysGrid;
}
public String makeDaysGrid(int startDay, int day, int intDaysInMonth, Calendar newCal) {
Calendar currentCal = Calendar.getInstance();
int currentday = currentCal.get(Calendar.DAY_OF_MONTH);
int currentyear = currentCal.get(Calendar.YEAR);
int currentmonth = currentCal.get(Calendar.MONTH) + 1;
String currentDate = this.getYearAndMonthAndDay(currentyear, currentmonth, currentday);
int forwardmonth = this.displayMonth + 1;
StringBuffer daysgrid = new StringBuffer();
daysgrid.append("<table class='tablerowStyleColor' cellpadding='1' cellspacing='0' border='1' style='width:100%;height:100%'/>");
daysgrid.append("<tr style=\"font:12px '宋体';text-align:center;BACKGROUND-IMAGE: url('"+reqeust.getContextPath()+"/images/grid_images/wbg.gif');\" height=\"26px\">");
daysgrid.append("<td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td>");
daysgrid.append("</tr>");
int dayOfMonthOfFirstSunday = 7 - startDay + 2;
int count = 0;
int dayOfMonth = 0;
for (int intWeek = 0; intWeek < 6; ++intWeek) {
daysgrid.append("<tr height='80'>");
for (int intDay = 0; intDay < 7; ++intDay) {
dayOfMonth = intWeek * 7 + intDay + dayOfMonthOfFirstSunday - 7;
if (dayOfMonth <= 0) {
daysgrid.append("<td> </td>");
} else if (dayOfMonth <= intDaysInMonth) {
++count;
String color = "black";
String bgcolor = "#ffffff";
String mousecolor = "blue";
String titlecolor = "#EDF5FA";
String tmp = getYearAndMonthAndDay(this.displayYear, forwardmonth, dayOfMonth);
String titletmp = "";
if (tmp.equalsIgnoreCase(currentDate)) {
mousecolor = "red";
titlecolor = "#C2C9D1";
} else {
mousecolor = "blue";
titlecolor = "#EDF5FA";
}
String dayString = String.valueOf(dayOfMonth);
daysgrid.append("<td width='13%' title='" + titletmp + "' align='right' valign='top' id='" + tmp + "' value='"
+ "' ondblclick='addCalender(this.id);' readonly style=\"font:12px '宋体';background-color:" + bgcolor + ";color:" + color
+ ";\" onmouseover=\"changDateColorOver(this,'#d3dfee','" + mousecolor + "');\" onmouseout =\"changDateColorOut(this);\">");
daysgrid.append("<div style=\"font:13px '宋体';background-color:" + titlecolor + ";padding:3px;border-bottom:1px solid #dddddd\" title='" + tmp + "'>" + dayString
+ "</div><input type='hidden' id='ch" + dayOfMonth + "' value='" + dayOfMonth + "'/>");
daysgrid.append("<div style='padding:5px;border:0px solid #214079;text-align:left;line-height:15px;word-break:break-all'>");
// 内容显示
if (getMap() != null && getMap().size() > 0) {
if (map.containsKey(dayOfMonth)) {
List<OaCalender> tmplist = map.get(dayOfMonth);
for (OaCalender cal : tmplist) {
int level = cal.getOaCalenderLevel();
String img = "";
if (level == EnumUtil.OA_CALENDER_LEVEL.one.value) {
img = "<img title ='重要/紧急' src='" + getReqeust().getContextPath() + "/images/grid_images/zyjj.png' border='0'/>";
} else if (level == EnumUtil.OA_CALENDER_LEVEL.two.value) {
img = "<img title ='重要/不紧急' src='" + getReqeust().getContextPath() + "/images/grid_images/zybjj.png' border='0'/>";
} else if (level == EnumUtil.OA_CALENDER_LEVEL.three.value) {
img = "<img title ='不重要/紧急' src='" + getReqeust().getContextPath() + "/images/grid_images/bzyjj.png' border='0'/>";
} else {
img = "<img title ='不重要/不紧急' src='" + getReqeust().getContextPath() + "/images/grid_images/bzybjj.png' border='0'/>";
}
if (cal.getOaCalenderStatus() == EnumUtil.OA_CALENDER_STATUS.one.value) {
daysgrid.append(img + " <a class='cal' href='javascript:void(0)' onmouseover=\"changeStatus('" + cal.getOaCalenderStatus() + "');\" id='" + cal.getPrimaryKey() + "'><font color='#00BD00'>"
+ cal.getOaCalenderStart().substring(5, 16) + "--" + cal.getOaCalenderEnd().substring(5, 16) + "</font><br/><font color='#476074'>"
+ cal.getLibrary().getLibraryInfoName() + ":</font><br/><font color='#0E75B7'>" + cal.getOaCalenderContent()
+ "</font><font color='#00BD00'> (已完成)</font></a><br/><br/>");
} else {
daysgrid.append(img + " <a class='cal' href='javascript:void(0)' onmouseover=\"changeStatus('" + cal.getOaCalenderStatus() + "');\" id='" + cal.getPrimaryKey() + "'><font color='#EC6907'>"
+ cal.getOaCalenderStart().substring(5, 16) + "--" + cal.getOaCalenderEnd().substring(5, 16) + "</font><br/><font color='#476074'>"
+ cal.getLibrary().getLibraryInfoName() + ":</font><br/><font color='#0E75B7'>" + cal.getOaCalenderContent()
+ "</font><font color='#EC6907'> (未完成)</font></a><br/><br/>");
}
}
}
}
daysgrid.append("</div>");
daysgrid.append("</td>");
}
}
int dayspan = dayOfMonth - count;
if (dayOfMonth < intDaysInMonth) {
daysgrid.append("</tr>");
} else if ((dayspan < 7) && (dayspan > 0)) {
for (int k = 0; k < dayspan; ++k) {
daysgrid.append("<td> </td>");
}
daysgrid.append("</tr>");
}
}
daysgrid.append("</table>");
return daysgrid.toString();
}
private String getYearAndMonthAndDay(int year, int month, int day) {
String m = String.valueOf(month < 10 ? "0" + month : month);
String d = String.valueOf(day < 10 ? "0" + day : day);
String tmp = year + "-" + m + "-" + d;
return tmp;
}
public WorkCalenderMonth(Map<Integer, List<OaCalender>> map) {
super();
this.map = map;
}
/**
* @return the map
*/
public Map<Integer, List<OaCalender>> getMap() {
return map;
}
/**
* @param map
* the map to set
*/
public void setMap(Map<Integer, List<OaCalender>> map) {
this.map = map;
}
public void setReqeust(HttpServletRequest reqeust) {
this.reqeust = reqeust;
}
public HttpServletRequest getReqeust() {
return reqeust;
}
}
|
3e0c71e5b960e1e58b6bf3db5631be7d6223cfc7 | 234 | java | Java | src/main/java/net/aunacraft/chatlogger/repository/APIKeyRepository.java | AunaCraft/ChatLog | 497ed9fdb14f5036801453d5d04933ec079d1e7d | [
"MIT"
] | null | null | null | src/main/java/net/aunacraft/chatlogger/repository/APIKeyRepository.java | AunaCraft/ChatLog | 497ed9fdb14f5036801453d5d04933ec079d1e7d | [
"MIT"
] | 3 | 2022-03-15T09:04:42.000Z | 2022-03-15T09:09:19.000Z | src/main/java/net/aunacraft/chatlogger/repository/APIKeyRepository.java | AunaCraft/ChatLog | 497ed9fdb14f5036801453d5d04933ec079d1e7d | [
"MIT"
] | null | null | null | 29.25 | 73 | 0.846154 | 5,287 | package net.aunacraft.chatlogger.repository;
import net.aunacraft.chatlogger.entities.APIKey;
import org.springframework.data.jpa.repository.JpaRepository;
public interface APIKeyRepository extends JpaRepository<APIKey, String> {
}
|
3e0c72c5e9c4e9bc0ac77e35873225ed4da06172 | 2,172 | java | Java | src/com/netease/nim/uikit/common/util/log/sdk/wrapper/NimLog.java | ckchenkai/uikit | 5cf09ee955697c049f5d708a6e7f72f88a37953c | [
"MIT"
] | 623 | 2015-09-08T07:35:36.000Z | 2021-06-01T09:57:32.000Z | src/com/netease/nim/uikit/common/util/log/sdk/wrapper/NimLog.java | ckchenkai/uikit | 5cf09ee955697c049f5d708a6e7f72f88a37953c | [
"MIT"
] | 60 | 2016-09-09T04:54:01.000Z | 2021-04-14T00:54:11.000Z | src/com/netease/nim/uikit/common/util/log/sdk/wrapper/NimLog.java | ckchenkai/uikit | 5cf09ee955697c049f5d708a6e7f72f88a37953c | [
"MIT"
] | 116 | 2015-10-16T03:25:27.000Z | 2021-05-07T16:32:57.000Z | 43.44 | 192 | 0.708103 | 5,288 | package com.netease.nim.uikit.common.util.log.sdk.wrapper;
import com.netease.nim.uikit.common.util.log.sdk.LogBase;
import com.netease.nim.uikit.common.util.log.sdk.NDateLogImpl;
import com.netease.nim.uikit.common.util.log.sdk.NLogImpl;
/**
* 云信日志封装
* <p>
* Created by huangjun on 2017/9/20.
*/
public class NimLog extends AbsNimLog {
/**
* 初始化多进程日志系统,支持多个进程写入一个日志文件
* 适用场景:多进程,对性能没有特别高的要求
* 缺点:持续频繁打日志会造成CPU内核态占用升高
*
* @param processName 进程名,单进程可以填 null,每行日志tag为[process]tag
* @param logDir 日志所在的目录,一般是 SD 卡下的目录绝对路径
* @param logFileName 日志名称,例如 nim_sdk.log
* @param level 日志级别,大于等于此日志级别的日志才会被写入
* @param maxLength 日志最大的文件大小,日志初始化时(一般是进程启动后),判断日志如果超过此大小将进行裁剪,填0表示默认值8M
* @param baseLength 日志裁减后的大小,填0表示默认值4M
* @param shrink 日志初始化时是否进行裁减
* @param interceptor 日志拦截器,可以在执行写日志前判断本地权限、磁盘是否准备好,决定是否要日志
*/
public static void initNLog(String processName, String logDir, String logFileName, int level, int maxLength, int baseLength, boolean shrink, LogBase.LogInterceptor interceptor) {
init(new NLogImpl(), processName, logDir, logFileName, level, maxLength, baseLength, shrink, interceptor);
}
/**
* 初始化多进程按日期存储的日志系统,支持多个进程写入一个日志文件,每天产生一个日志文件。
* 适用场景:多进程,要求按天记录日志,对性能没有特别高的要求。
* 缺点:持续频繁打日志会造成CPU内核态占用升高
*
* @param processName 进程名,单进程可以填 null,每行日志tag为[process]tag
* @param logDir 日志所在的目录,一般是 SD 卡下的目录绝对路径
* @param logFileNamePrefix 日志名前缀,会自动根据日期生成日志,例如nim_20170911.log
* @param level 日志级别,大于等于此日志级别的日志才会被写入
* @param maxLength 日志最大的文件大小,日志初始化时(一般是进程启动后),判断日志如果超过此大小将进行裁剪,填0表示默认值8M
* @param baseLength 日志裁减后的大小,填0表示默认值4M
* @param shrink 日志初始化时是否进行裁减
* @param interceptor 日志拦截器,可以在执行写日志前判断本地权限、磁盘是否准备好,决定是否要日志
*/
public static void initDateNLog(String processName, String logDir, String logFileNamePrefix, int level, int maxLength, int baseLength, boolean shrink, LogBase.LogInterceptor interceptor) {
init(new NDateLogImpl(), processName, logDir, logFileNamePrefix, level, maxLength, baseLength, shrink, interceptor);
}
}
|
3e0c72cc766429c6eeffa9b9e58c113f8e472306 | 3,627 | java | Java | src/main/java/org/logicng/predicates/satisfiability/SATPredicate.java | tnstrssnr/LogicNG | 994294fbb283b7b96230da3937369bf8fc062b5f | [
"Apache-2.0"
] | 92 | 2016-01-22T08:46:39.000Z | 2022-03-15T20:18:54.000Z | src/main/java/org/logicng/predicates/satisfiability/SATPredicate.java | tnstrssnr/LogicNG | 994294fbb283b7b96230da3937369bf8fc062b5f | [
"Apache-2.0"
] | 29 | 2016-05-14T09:07:42.000Z | 2022-02-22T07:40:23.000Z | src/main/java/org/logicng/predicates/satisfiability/SATPredicate.java | tnstrssnr/LogicNG | 994294fbb283b7b96230da3937369bf8fc062b5f | [
"Apache-2.0"
] | 18 | 2016-01-13T20:50:40.000Z | 2022-01-26T18:04:44.000Z | 43.698795 | 88 | 0.438379 | 5,289 | ///////////////////////////////////////////////////////////////////////////
// __ _ _ ________ //
// / / ____ ____ _(_)____/ | / / ____/ //
// / / / __ \/ __ `/ / ___/ |/ / / __ //
// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //
// /_____/\____/\__, /_/\___/_/ |_/\____/ //
// /____/ //
// //
// The Next Generation Logic Library //
// //
///////////////////////////////////////////////////////////////////////////
// //
// Copyright 2015-20xx Christoph Zengler //
// //
// 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.logicng.predicates.satisfiability;
import static org.logicng.formulas.cache.PredicateCacheEntry.IS_SAT;
import org.logicng.datastructures.Tristate;
import org.logicng.formulas.FType;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFactory;
import org.logicng.formulas.FormulaPredicate;
import org.logicng.solvers.MiniSat;
import org.logicng.solvers.SATSolver;
/**
* A SAT solver based SAT predicate. Indicates whether a formula is satisfiable or not.
* @version 1.5.1
* @since 1.0
*/
public final class SATPredicate implements FormulaPredicate {
private final SATSolver solver;
/**
* Constructs a new SAT predicate with a given formula factory.
* @param f the formula factory
*/
public SATPredicate(final FormulaFactory f) {
this.solver = MiniSat.miniSat(f);
}
@Override
public boolean test(final Formula formula, final boolean cache) {
final Tristate cached = formula.predicateCacheEntry(IS_SAT);
if (cached != Tristate.UNDEF) {
return cached == Tristate.TRUE;
}
final boolean result;
if (formula.type() == FType.FALSE) {
result = false;
} else {
this.solver.add(formula);
result = this.solver.sat() == Tristate.TRUE;
this.solver.reset();
}
if (cache) {
formula.setPredicateCacheEntry(IS_SAT, result);
}
return result;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
|
3e0c72ff4460e0439806d5787bc7260d6a6ffc66 | 40,273 | java | Java | openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaSchemaGenerator.java | gigara/ballerina-openapi | 5b3ca760272be91ad1a0b6f08f16ddf830438f79 | [
"Apache-2.0"
] | null | null | null | openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaSchemaGenerator.java | gigara/ballerina-openapi | 5b3ca760272be91ad1a0b6f08f16ddf830438f79 | [
"Apache-2.0"
] | null | null | null | openapi-cli/src/main/java/io/ballerina/openapi/generators/schema/BallerinaSchemaGenerator.java | gigara/ballerina-openapi | 5b3ca760272be91ad1a0b6f08f16ddf830438f79 | [
"Apache-2.0"
] | null | null | null | 55.779778 | 120 | 0.655923 | 5,290 | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.openapi.generators.schema;
import io.ballerina.compiler.syntax.tree.AbstractNodeFactory;
import io.ballerina.compiler.syntax.tree.AnnotationNode;
import io.ballerina.compiler.syntax.tree.IdentifierToken;
import io.ballerina.compiler.syntax.tree.ImportDeclarationNode;
import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode;
import io.ballerina.compiler.syntax.tree.MetadataNode;
import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode;
import io.ballerina.compiler.syntax.tree.ModulePartNode;
import io.ballerina.compiler.syntax.tree.Node;
import io.ballerina.compiler.syntax.tree.NodeFactory;
import io.ballerina.compiler.syntax.tree.NodeList;
import io.ballerina.compiler.syntax.tree.RecordFieldNode;
import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode;
import io.ballerina.compiler.syntax.tree.SyntaxKind;
import io.ballerina.compiler.syntax.tree.SyntaxTree;
import io.ballerina.compiler.syntax.tree.Token;
import io.ballerina.compiler.syntax.tree.TypeDefinitionNode;
import io.ballerina.compiler.syntax.tree.TypeDescriptorNode;
import io.ballerina.compiler.syntax.tree.TypeReferenceNode;
import io.ballerina.openapi.exception.BallerinaOpenApiException;
import io.ballerina.openapi.generators.DocCommentsGenerator;
import io.ballerina.openapi.generators.GeneratorConstants;
import io.ballerina.openapi.generators.GeneratorUtils;
import io.ballerina.tools.text.TextDocument;
import io.ballerina.tools.text.TextDocuments;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList;
import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken;
import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList;
import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken;
import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode;
import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode;
import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode;
import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode;
import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeDefinitionNode;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.ANYDATA_KEYWORD;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.ASTERISK_TOKEN;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_KEYWORD;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN;
import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD;
import static io.ballerina.openapi.generators.GeneratorConstants.BOOLEAN;
import static io.ballerina.openapi.generators.GeneratorConstants.INTEGER;
import static io.ballerina.openapi.generators.GeneratorConstants.MAX_ARRAY_LENGTH;
import static io.ballerina.openapi.generators.GeneratorConstants.NILLABLE;
import static io.ballerina.openapi.generators.GeneratorConstants.NUMBER;
import static io.ballerina.openapi.generators.GeneratorConstants.STRING;
import static io.ballerina.openapi.generators.GeneratorUtils.SINGLE_WS_MINUTIAE;
import static io.ballerina.openapi.generators.GeneratorUtils.convertOpenAPITypeToBallerina;
import static io.ballerina.openapi.generators.GeneratorUtils.escapeIdentifier;
import static io.ballerina.openapi.generators.GeneratorUtils.extractReferenceType;
import static io.ballerina.openapi.generators.GeneratorUtils.getValidName;
import static io.ballerina.openapi.generators.GeneratorUtils.isValidSchemaName;
/**
*This class wraps the {@link Schema} from openapi models inorder to overcome complications
*while populating syntax tree.
*/
public class BallerinaSchemaGenerator {
private List<TypeDefinitionNode> typeDefinitionNodeList;
private final boolean isNullable;
private final OpenAPI openAPI;
/**
* This public constructor is used to generate record and other relevant data type when the nullable flag is
* enabled in the openapi command.
*
* @param openAPI OAS definition
* @param isNullable nullable value
*/
public BallerinaSchemaGenerator(OpenAPI openAPI, boolean isNullable) {
this.openAPI = openAPI;
this.isNullable = isNullable;
this.typeDefinitionNodeList = new LinkedList<>();
}
/**
* This public constructor is used to generate record and other relevant data type when the absent of the nullable
* flag in the openapi command.
*
* @param openAPI OAS definition
*/
public BallerinaSchemaGenerator(OpenAPI openAPI) {
this(openAPI, false);
}
/**
* Returns a list of type definition nodes.
*/
public List<TypeDefinitionNode> getTypeDefinitionNodeList() {
return typeDefinitionNodeList;
}
/**
* Set the typeDefinitionNodeList.
*/
public void setTypeDefinitionNodeList(List<TypeDefinitionNode> typeDefinitionNodeList) {
this.typeDefinitionNodeList = typeDefinitionNodeList;
}
/**
* Generate syntaxTree for component schema.
*/
public SyntaxTree generateSyntaxTree() throws BallerinaOpenApiException {
if (openAPI.getComponents() != null) {
// Refactor schema name with valid name
// Create typeDefinitionNode
Components components = openAPI.getComponents();
Map<String, Schema> componentsSchemas = components.getSchemas();
if (componentsSchemas != null) {
Map<String, Schema> refacSchema = new HashMap<>();
for (Map.Entry<String, Schema> schemaEntry: componentsSchemas.entrySet()) {
String name = getValidName(schemaEntry.getKey(), true);
refacSchema.put(name, schemaEntry.getValue());
}
openAPI.getComponents().setSchemas(refacSchema);
}
Map<String, Schema> schemas = components.getSchemas();
if (schemas != null) {
for (Map.Entry<String, Schema> schema: schemas.entrySet()) {
List<Node> schemaDoc = new ArrayList<>();
if (schema.getValue().getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(
schema.getValue().getDescription(), false));
}
List<String> required = schema.getValue().getRequired();
if (isValidSchemaName(schema.getKey().trim())) {
generateTypeDefinitionNode(typeDefinitionNodeList, schema.getValue(), schemaDoc, required,
schema.getKey().trim());
}
}
}
}
//Create imports
NodeList<ImportDeclarationNode> imports = AbstractNodeFactory.createEmptyNodeList();
// Create module member declaration
NodeList<ModuleMemberDeclarationNode> moduleMembers = AbstractNodeFactory.createNodeList(
typeDefinitionNodeList.toArray(new TypeDefinitionNode[typeDefinitionNodeList.size()]));
Token eofToken = AbstractNodeFactory.createIdentifierToken("");
ModulePartNode modulePartNode = NodeFactory.createModulePartNode(imports, moduleMembers, eofToken);
TextDocument textDocument = TextDocuments.from("");
SyntaxTree syntaxTree = SyntaxTree.from(textDocument);
return syntaxTree.modifyWith(modulePartNode);
}
/**
* Generated typeDefinitionNode for openAPI schema. This types includes in the types.bal file.
*/
private void generateTypeDefinitionNode(List<TypeDefinitionNode> typeDefinitionNodeList,
Schema<?> schemaValue, List<Node> schemaDoc, List<String> required,
String recordName) throws BallerinaOpenApiException {
IdentifierToken typeName = AbstractNodeFactory.createIdentifierToken(recordName);
String defineDatatypeName = getValidName(recordName, true);
List<AnnotationNode> typeAnnotations = new ArrayList<>();
if (schemaValue.getDeprecated() != null && schemaValue.getDeprecated()) {
DocCommentsGenerator.extractDeprecatedAnnotation(schemaValue.getExtensions(),
schemaDoc, typeAnnotations);
}
// record field list for given schema.
List<Node> recordFieldList = new ArrayList<>();
TypeDefinitionNode typeDefNode;
if (schemaValue instanceof ComposedSchema) {
ComposedSchema composedSchema = (ComposedSchema) schemaValue;
getTypeDefinitionNodeForComposedSchema(typeDefinitionNodeList, schemaDoc, required, typeName,
defineDatatypeName, typeAnnotations, recordFieldList, composedSchema);
} else if (schemaValue.getProperties() != null || schemaValue instanceof ObjectSchema) {
Map<String, Schema> fields = schemaValue.getProperties();
typeDefNode = getTypeDefinitionNodeForObjectSchema(required, typeName, recordFieldList, fields,
schemaDoc, createNodeList(typeAnnotations));
typeDefinitionNodeList.add(typeDefNode);
} else if (schemaValue.getType() != null) {
if (schemaValue instanceof ArraySchema) {
ArraySchema arraySchema = (ArraySchema) schemaValue;
typeDefNode = getArrayTypeDefinition(arraySchema, defineDatatypeName, schemaDoc, typeAnnotations);
typeDefinitionNodeList.add(typeDefNode);
} else {
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(
createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(typeAnnotations));
if (schemaValue.getType() != null) {
String typeDescriptorName = convertOpenAPITypeToBallerina(schemaValue.getType().trim());
typeDescriptorName = getNullableType(schemaValue, typeDescriptorName);
typeDefNode = getTypeDefinitionNode(createIdentifierToken(typeDescriptorName),
getValidName((defineDatatypeName), true),
metadataNode);
typeDefinitionNodeList.add(typeDefNode);
}
}
} else if (schemaValue.get$ref() != null) {
Token typeRef = AbstractNodeFactory.createIdentifierToken(getValidName(
extractReferenceType(schemaValue.get$ref()), true));
TypeReferenceNode recordField = NodeFactory.createTypeReferenceNode(createToken(ASTERISK_TOKEN), typeRef,
createToken(SEMICOLON_TOKEN));
recordFieldList.add(recordField);
NodeList<Node> fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList);
RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory.createRecordTypeDescriptorNode(
createToken(SyntaxKind.RECORD_KEYWORD), createToken(OPEN_BRACE_TOKEN),
fieldNodes, null, createToken(SyntaxKind.CLOSE_BRACE_TOKEN));
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(typeAnnotations));
typeDefNode = NodeFactory.createTypeDefinitionNode(metadataNode,
createToken(PUBLIC_KEYWORD),
createToken(TYPE_KEYWORD),
typeName, recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN));
typeDefinitionNodeList.add(typeDefNode);
} else if (schemaValue.getType() == null) {
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(typeAnnotations));
String anyData = getNullableType(schemaValue, GeneratorConstants.ANY_DATA);
typeDefNode = getTypeDefinitionNode(createIdentifierToken(anyData), getValidName((defineDatatypeName),
true), metadataNode);
typeDefinitionNodeList.add(typeDefNode);
} else {
throw new BallerinaOpenApiException("Unsupported OAS schema type.");
}
}
/**
* Generate {@code TypeDefinitionNode} for given composed schema.
*/
private void getTypeDefinitionNodeForComposedSchema(List<TypeDefinitionNode> typeDefinitionNodeList,
List<Node> schemaDoc, List<String> required,
IdentifierToken typeName, String defineDatatypeName,
List<AnnotationNode> typeAnnotations,
List<Node> recordFieldList, ComposedSchema composedSchema)
throws BallerinaOpenApiException {
TypeDefinitionNode typeDefNode;
if (composedSchema.getAllOf() != null) {
List<Schema> allOf = composedSchema.getAllOf();
typeDefNode = getAllOfTypeDefinitionNode(schemaDoc, required, typeName, recordFieldList, allOf);
typeDefinitionNodeList.add(typeDefNode);
} else if (composedSchema.getOneOf() != null) {
List<Schema> oneOf = composedSchema.getOneOf();
String unionTypeCont = GeneratorUtils.getOneOfUnionType(oneOf);
String type = escapeIdentifier(defineDatatypeName.trim());
MetadataNode metadataNode = createMetadataNode(
createMarkdownDocumentationNode(createNodeList(schemaDoc)), createNodeList(typeAnnotations));
typeDefNode = getTypeDefinitionNode(createIdentifierToken(unionTypeCont), type, metadataNode);
typeDefinitionNodeList.add(typeDefNode);
} else if (composedSchema.getAnyOf() != null) {
List<Schema> anyOf = composedSchema.getAnyOf();
String unionTypeCont = GeneratorUtils.getOneOfUnionType(anyOf);
String type = escapeIdentifier(defineDatatypeName.trim());
MetadataNode metadataNode = createMetadataNode(
createMarkdownDocumentationNode(createNodeList(schemaDoc)), createNodeList(typeAnnotations));
typeDefNode = getTypeDefinitionNode(createIdentifierToken(unionTypeCont), type, metadataNode);
typeDefinitionNodeList.add(typeDefNode);
}
}
/**
* Util function for generate typeDefinition node.
*/
private TypeDefinitionNode getTypeDefinitionNode(IdentifierToken nameReference, String type,
MetadataNode metadataNode) {
return createTypeDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD),
createIdentifierToken(type), createSimpleNameReferenceNode(nameReference),
createToken(SEMICOLON_TOKEN));
}
/**
* Generate Node for allOf data binding.
*
* @param schemaDoc - API docs list
* @param required - required fields
* @param typeName - main record name
* @param recordFieldList - generated previous record field list
* @param allOf - allOf schema values
* @return TypeDefinitionNode for allOf
* @throws BallerinaOpenApiException
*/
public TypeDefinitionNode getAllOfTypeDefinitionNode(List<Node> schemaDoc, List<String> required,
IdentifierToken typeName, List<Node> recordFieldList,
List<Schema> allOf)
throws BallerinaOpenApiException {
RecordTypeDescriptorNode recordTypeDescriptorNode = getAllOfRecordTypeDescriptorNode(schemaDoc, required,
recordFieldList, allOf);
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createEmptyNodeList());
return NodeFactory.createTypeDefinitionNode(metadataNode,
createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, recordTypeDescriptorNode,
AbstractNodeFactory.createToken(SEMICOLON_TOKEN));
}
/**
* Create {@code RecordTypeDescriptorNode} for OAS AllOf data model.
*/
private RecordTypeDescriptorNode getAllOfRecordTypeDescriptorNode(List<Node> schemaDoc,
List<String> required, List<Node> recordFieldList,
List<Schema> allOf)
throws BallerinaOpenApiException {
for (Schema<?> allOfSchema: allOf) {
if (allOfSchema.getType() == null && allOfSchema.get$ref() != null) {
//Generate typeReferenceNode
getAllOfRecordFieldForReference(schemaDoc, recordFieldList, allOfSchema);
} else if (allOfSchema.getProperties() != null) {
if (allOfSchema.getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(allOfSchema.getDescription(),
false));
}
Map<String, Schema> properties = allOfSchema.getProperties();
for (Map.Entry<String, Schema> field : properties.entrySet()) {
addRecordFields(required, recordFieldList, field);
}
} else if (allOfSchema instanceof ComposedSchema) {
ComposedSchema allOfNested = (ComposedSchema) allOfSchema;
if (allOfNested.getAllOf() != null) {
for (Schema schema: allOfNested.getAllOf()) {
if (schema instanceof ObjectSchema) {
ObjectSchema objectSchema = (ObjectSchema) schema;
List<String> requiredField = objectSchema.getRequired();
Map<String, Schema> properties = objectSchema.getProperties();
// TODO: add api documentation
for (Map.Entry<String, Schema> field : properties.entrySet()) {
addRecordFields(requiredField, recordFieldList, field);
}
}
}
}
// TODO handle OneOf, AnyOf
}
}
NodeList<Node> fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList);
return NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), createToken(OPEN_BRACE_TOKEN),
fieldNodes, null, createToken(CLOSE_BRACE_TOKEN));
}
private void getAllOfRecordFieldForReference(List<Node> schemaDoc, List<Node> recordFieldList, Schema allOfSchema)
throws BallerinaOpenApiException {
Token typeRef = AbstractNodeFactory.createIdentifierToken(getValidName(
extractReferenceType(allOfSchema.get$ref()), true));
TypeReferenceNode recordField = NodeFactory.createTypeReferenceNode(createToken(ASTERISK_TOKEN), typeRef,
createToken(SEMICOLON_TOKEN));
recordFieldList.add(recordField);
if (allOfSchema.getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(allOfSchema.getDescription(), false));
}
}
/**
* This function is used to create typeDefinitionNode for objectSchema.
*
* @param required - This string list include required fields in properties.
* @param typeName - Record Name
* @param recordFieldList - RecordFieldList
* @param fields - schema properties map
* @return This return record TypeDefinitionNode
*/
public TypeDefinitionNode getTypeDefinitionNodeForObjectSchema(List<String> required,
IdentifierToken typeName,
List<Node> recordFieldList,
Map<String, Schema> fields,
List<Node> schemaDoc,
NodeList<AnnotationNode> annotationNodes)
throws BallerinaOpenApiException {
TypeDefinitionNode typeDefinitionNode;
if (fields != null) {
for (Map.Entry<String, Schema> field : fields.entrySet()) {
addRecordFields(required, recordFieldList, field);
}
NodeList<Node> fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList);
RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory.createRecordTypeDescriptorNode(
createToken(SyntaxKind.RECORD_KEYWORD), createToken(OPEN_BRACE_TOKEN), fieldNodes,
null, createToken(SyntaxKind.CLOSE_BRACE_TOKEN));
MarkdownDocumentationNode documentationNode =
createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, annotationNodes);
typeDefinitionNode = NodeFactory.createTypeDefinitionNode(metadataNode,
createToken(PUBLIC_KEYWORD),
createToken(TYPE_KEYWORD), typeName, recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN));
} else {
RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory.createRecordTypeDescriptorNode(
createToken(SyntaxKind.RECORD_KEYWORD),
createToken(OPEN_BRACE_TOKEN), createEmptyNodeList(), null,
createToken(SyntaxKind.CLOSE_BRACE_TOKEN));
MarkdownDocumentationNode documentationNode =
createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, annotationNodes);
typeDefinitionNode = NodeFactory.createTypeDefinitionNode(metadataNode,
createToken(PUBLIC_KEYWORD),
createToken(TYPE_KEYWORD), typeName,
recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN));
}
return typeDefinitionNode;
}
/**
* This util for generating record field with given schema properties.
*/
private void addRecordFields(List<String> required, List<Node> recordFieldList, Map.Entry<String, Schema> field)
throws BallerinaOpenApiException {
// TODO: Handle allOf , oneOf, anyOf
RecordFieldNode recordFieldNode;
// API doc generations
List<Node> schemaDoc = new ArrayList<>();
String fieldN = escapeIdentifier(field.getKey().trim());
if (field.getValue().getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(
field.getValue().getDescription(), false));
} else if (field.getValue().get$ref() != null) {
String[] split = field.getValue().get$ref().trim().split("/");
String componentName = getValidName(split[split.length - 1], true);
if (openAPI.getComponents().getSchemas().get(componentName) != null) {
Schema<?> schema = openAPI.getComponents().getSchemas().get(componentName);
if (schema.getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(
schema.getDescription(), false));
}
}
}
IdentifierToken fieldName = AbstractNodeFactory.createIdentifierToken(fieldN);
TypeDescriptorNode fieldTypeName = extractOpenAPISchema(field.getValue());
Token questionMarkToken = AbstractNodeFactory.createIdentifierToken(NILLABLE);
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createEmptyNodeList());
if (required != null) {
if (!required.contains(field.getKey().trim())) {
recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null,
fieldTypeName, fieldName, questionMarkToken, createToken(SEMICOLON_TOKEN));
} else {
recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null,
fieldTypeName, fieldName, null, createToken(SEMICOLON_TOKEN));
}
} else {
recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null,
fieldTypeName, fieldName, questionMarkToken, createToken(SEMICOLON_TOKEN));
}
recordFieldList.add(recordFieldNode);
}
/**
* Common method to extract OpenApi Schema type objects in to Ballerina type compatible schema objects.
*
* @param schema - OpenApi Schema
*/
private TypeDescriptorNode extractOpenAPISchema(Schema<?> schema) throws BallerinaOpenApiException {
if (schema.getType() != null || schema.getProperties() != null) {
List<String> primitiveTypeList = new ArrayList<>(Arrays.asList(INTEGER, NUMBER, STRING, BOOLEAN));
boolean isOASPrimitive = primitiveTypeList.contains(schema.getType());
if (schema.getType() != null && (isOASPrimitive)) {
String type = convertOpenAPITypeToBallerina(schema.getType().trim());
if (schema.getType().equals(NUMBER)) {
if (schema.getFormat() != null) {
type = convertOpenAPITypeToBallerina(schema.getFormat().trim());
}
}
type = getNullableType(schema, type);
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
} else if (schema instanceof ArraySchema) {
final ArraySchema arraySchema = (ArraySchema) schema;
if (arraySchema.getItems() != null) {
// single array
return getArrayTypeDescriptorNode(arraySchema);
}
} else if ((schema.getType() != null && schema.getType().equals("object")) ||
(schema.getProperties() != null)) {
if (schema.getProperties() != null) {
Map<String, Schema> properties = schema.getProperties();
List<Node> recordFList = new ArrayList<>();
List<String> required = schema.getRequired();
for (Map.Entry<String, Schema> property: properties.entrySet()) {
addRecordFields(required, recordFList, property);
}
NodeList<Node> fieldNodes = AbstractNodeFactory.createNodeList(recordFList);
return NodeFactory.createRecordTypeDescriptorNode(
createToken(RECORD_KEYWORD, SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE),
createToken(OPEN_BRACE_TOKEN, SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE), fieldNodes,
null, createToken(CLOSE_BRACE_TOKEN,
SINGLE_WS_MINUTIAE, SINGLE_WS_MINUTIAE));
} else if (schema.get$ref() != null) {
String type = getValidName(extractReferenceType(schema.get$ref()), true);
Schema<?> refSchema = openAPI.getComponents().getSchemas().get(type);
type = getNullableType(refSchema, type);
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
} else {
Token typeName = AbstractNodeFactory.createIdentifierToken(
convertOpenAPITypeToBallerina(schema.getType().trim()));
return createBuiltinSimpleNameReferenceNode(null, typeName);
}
} else if (schema.getType() != null && schema.getType().equals("object")) {
String type = convertOpenAPITypeToBallerina(schema.getType().trim());
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
} else {
throw new BallerinaOpenApiException("Unsupported OAS data type `" + schema.getType() + "`.");
}
} else if (schema.get$ref() != null) {
String type = extractReferenceType(schema.get$ref());
type = getValidName(type, true);
Schema<?> refSchema = openAPI.getComponents().getSchemas().get(type);
type = getNullableType(refSchema, type);
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
} else if (schema instanceof ComposedSchema) {
//TODO: API doc generator
ComposedSchema composedSchema = (ComposedSchema) schema;
return getTypeDescriptorNodeForComposedSchema(composedSchema, new ArrayList<>(), false);
} else if (schema.getType() == null) {
//This contains a fallback to Ballerina common type `anydata` if the OpenApi specification type is not
// defined.
String type = GeneratorConstants.ANY_DATA;
type = getNullableType(schema, type);
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
} else {
//This contains the OpenApi specification type is not compatible with any of the current Ballerina types.
throw new BallerinaOpenApiException("Unsupported OAS data type.");
}
String type = GeneratorConstants.ANY_DATA;
type = getNullableType(schema, type);
Token typeName = AbstractNodeFactory.createIdentifierToken(type);
return createBuiltinSimpleNameReferenceNode(null, typeName);
}
/**
* Generate proper type name considering the nullable configurations.
* Scenario 1 : schema.getNullable() != null && schema.getNullable() == true && nullable == true -> string?
* Scenario 2 : schema.getNullable() != null && schema.getNullable() == true && nullable == false -> string?
* Scenario 3 : schema.getNullable() != null && schema.getNullable() == false && nullable == false -> string
* Scenario 4 : schema.getNullable() != null && schema.getNullable() == false && nullable == true -> string
* Scenario 5 : schema.getNullable() == null && nullable == true -> string?
* Scenario 6 : schema.getNullable() == null && nullable == false -> string
*
* @param schema Schema of the property
* @param type Type name
* @return Final type of the field
*/
private String getNullableType(Schema<?> schema, String type) {
if (schema.getNullable() != null) {
if (schema.getNullable()) {
type = type + NILLABLE;
}
} else if (isNullable) {
type = type + NILLABLE;
}
return type;
}
/**
* This function is used to handle the array schema under the OAS components.
*/
private TypeDefinitionNode getArrayTypeDefinition(ArraySchema arraySchema, String arrayName, List<Node> schemaDoc,
List<AnnotationNode> typeAnnotations)
throws BallerinaOpenApiException {
TypeDescriptorNode fieldTypeName;
if (arraySchema.getItems() != null) {
fieldTypeName = extractOpenAPISchema(arraySchema.getItems());
} else {
Token type = AbstractNodeFactory.createToken(ANYDATA_KEYWORD);
fieldTypeName = NodeFactory.createBuiltinSimpleNameReferenceNode(null, type);
}
if (arraySchema.getDescription() != null) {
schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(arraySchema.getDescription(),
false));
}
MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc));
MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(typeAnnotations));
String fieldTypeNameStr = fieldTypeName.toString().trim();
if (fieldTypeName.toString().endsWith(NILLABLE)) {
fieldTypeNameStr = fieldTypeNameStr.substring(0, fieldTypeNameStr.length() - 1);
}
String arrayBrackets = "[]";
if (arraySchema.getMaxItems() != null) {
if (arraySchema.getMaxItems() <= MAX_ARRAY_LENGTH) {
arrayBrackets = "[" + arraySchema.getMaxItems() + "]";
} else {
throw new BallerinaOpenApiException("Maximum item count defined in the definition exceeds the " +
"maximum ballerina array length.");
}
}
fieldTypeNameStr = getNullableType(arraySchema, fieldTypeNameStr + arrayBrackets);
return getTypeDefinitionNode(createIdentifierToken(fieldTypeNameStr), escapeIdentifier(arrayName),
metadataNode);
}
/**
* Generate {@code TypeDescriptorNode} for Array Schema.
*
* @param arraySchema - Array schema
* @throws BallerinaOpenApiException when failure happens while processing
*/
public TypeDescriptorNode getArrayTypeDescriptorNode(ArraySchema arraySchema) throws BallerinaOpenApiException {
String type;
Token typeName;
TypeDescriptorNode memberTypeDesc;
Token openSBracketToken = AbstractNodeFactory.createIdentifierToken("[");
Schema<?> schemaItem = arraySchema.getItems();
Token closeSBracketToken = AbstractNodeFactory.createIdentifierToken(getNullableType(arraySchema, "]"));
if (schemaItem.get$ref() != null) {
type = getValidName(extractReferenceType(arraySchema.getItems().get$ref()), true);
typeName = AbstractNodeFactory.createIdentifierToken(type);
memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, typeName);
} else if (schemaItem instanceof ArraySchema) {
memberTypeDesc = extractOpenAPISchema(arraySchema.getItems());
} else if (schemaItem instanceof ObjectSchema) {
// Array has inline record
ObjectSchema inlineSchema = (ObjectSchema) schemaItem;
memberTypeDesc = extractOpenAPISchema(inlineSchema);
return NodeFactory.createArrayTypeDescriptorNode(memberTypeDesc, openSBracketToken,
null, closeSBracketToken);
} else if (schemaItem instanceof ComposedSchema) {
// TODO: API Doc generator
ComposedSchema composedSchema = (ComposedSchema) schemaItem;
memberTypeDesc = getTypeDescriptorNodeForComposedSchema(composedSchema, new ArrayList<>(), true);
} else if (schemaItem.getType() != null) {
type = schemaItem.getType();
closeSBracketToken = AbstractNodeFactory.createIdentifierToken(getNullableType(arraySchema, "]"));
typeName = AbstractNodeFactory.createIdentifierToken(convertOpenAPITypeToBallerina(type));
memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, typeName);
} else {
closeSBracketToken = AbstractNodeFactory.createIdentifierToken(getNullableType(arraySchema, "]"));
typeName = AbstractNodeFactory.createToken(ANYDATA_KEYWORD);
memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, typeName);
}
if (arraySchema.getMaxItems() != null) {
if (arraySchema.getMaxItems() <= MAX_ARRAY_LENGTH) {
return NodeFactory.createArrayTypeDescriptorNode(memberTypeDesc, openSBracketToken,
createIdentifierToken(arraySchema.getMaxItems().toString()), closeSBracketToken);
} else {
throw new BallerinaOpenApiException("Maximum item count defined in the definition exceeds the maximum" +
" ballerina array length.");
}
}
return NodeFactory.createArrayTypeDescriptorNode(memberTypeDesc, openSBracketToken,
null, closeSBracketToken);
}
private TypeDescriptorNode getTypeDescriptorNodeForComposedSchema(ComposedSchema composedSchema,
List<Node> schemaDoc, boolean isArray)
throws BallerinaOpenApiException {
TypeDescriptorNode memberTypeDesc;
String typeName;
boolean nullableComposedSchema = false;
if (composedSchema.getNullable() != null) {
if (composedSchema.getNullable()) {
nullableComposedSchema = true;
}
} else if (isNullable) {
nullableComposedSchema = true;
}
if (composedSchema.getOneOf() != null) {
typeName = GeneratorUtils.getOneOfUnionType(composedSchema.getOneOf());
} else if (composedSchema.getAnyOf() != null) {
typeName = GeneratorUtils.getOneOfUnionType(composedSchema.getAnyOf());
} else if (composedSchema.getAllOf() != null) {
return getAllOfRecordTypeDescriptorNode(schemaDoc, composedSchema.getRequired(), new ArrayList<>(),
composedSchema.getAllOf());
} else if (composedSchema.getType() != null) {
typeName = convertOpenAPITypeToBallerina(composedSchema.getType().trim());
} else if (composedSchema.get$ref() != null) {
typeName = getValidName(extractReferenceType(composedSchema.get$ref().trim()), true);
} else {
throw new BallerinaOpenApiException("Unsupported OAS data type.");
}
if (nullableComposedSchema && !isArray) {
typeName = typeName + NILLABLE;
return createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(typeName));
} else {
memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken(typeName));
return memberTypeDesc;
}
}
}
|
3e0c733940b541b225afef2fbdb37520c0e8d020 | 1,522 | java | Java | backend/src/main/java/CS591/GradeManageSystem/Service/impl/UserServiceImpl.java | xhyzzZ/CS591-Group7 | 49e0db62c10c66cf3f5267b366d9c40b6ca53cf0 | [
"MIT"
] | 2 | 2019-05-06T21:05:47.000Z | 2019-11-16T21:57:57.000Z | backend/src/main/java/CS591/GradeManageSystem/Service/impl/UserServiceImpl.java | xhyzzZ/CS591-Group7 | 49e0db62c10c66cf3f5267b366d9c40b6ca53cf0 | [
"MIT"
] | null | null | null | backend/src/main/java/CS591/GradeManageSystem/Service/impl/UserServiceImpl.java | xhyzzZ/CS591-Group7 | 49e0db62c10c66cf3f5267b366d9c40b6ca53cf0 | [
"MIT"
] | null | null | null | 37.121951 | 91 | 0.722733 | 5,291 | package CS591.GradeManageSystem.Service.impl;
import CS591.GradeManageSystem.DAO.Impl.UserRepositoryImpl;
import CS591.GradeManageSystem.Service.UserService;
import CS591.GradeManageSystem.entity.User;
public class UserServiceImpl implements UserService {
private static final int SUCCESS = 0;
private static final int USERALREADYEXIST = 1;
private static final int PASSWORDNOTEQUAL = 2;
private UserRepositoryImpl userRepository = new UserRepositoryImpl();
private ModelServiceImpl modelService = new ModelServiceImpl();
// 0: success, 1: no such user, 2: password is wrong
@Override
public int checkLogin(String username, String password) {
if (userRepository.findByUsername(username) == null) return 1;
if (userRepository.findByUsernameAndPassword(username, password) == null) return 2;
return 0;
}
@Override
public User login(String username, String password) {
return userRepository.findByUsernameAndPassword(username, password);
}
// 0: success, 1: user already exists, 2: passwords not equal
@Override
public int register(String username, String password, String confirm) {
if (!password.equals(confirm)) return PASSWORDNOTEQUAL;
User user = userRepository.findByUsername(username);
if (user != null) return USERALREADYEXIST;
user = new User(username, password);
userRepository.save(user);
modelService.createDefault(user.getUserId());
return SUCCESS;
}
}
|
3e0c736be3644aa749e10a1b8d2458373625b225 | 2,757 | java | Java | src/main/java/com/avail/tools/options/DefaultOption.java | tdhsmith/Avail | d033c2e4ca9b6ac60e605a9d5c8ad3b47e3bdf52 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/avail/tools/options/DefaultOption.java | tdhsmith/Avail | d033c2e4ca9b6ac60e605a9d5c8ad3b47e3bdf52 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/avail/tools/options/DefaultOption.java | tdhsmith/Avail | d033c2e4ca9b6ac60e605a9d5c8ad3b47e3bdf52 | [
"BSD-3-Clause"
] | null | null | null | 39.385714 | 80 | 0.751542 | 5,292 | /*
* DefaultOption.java
* Copyright © 1993-2018, The Avail Foundation, LLC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.avail.tools.options;
import com.avail.utility.evaluation.Continuation2NotNull;
import static java.util.Collections.singletonList;
/**
* A {@code DefaultOption} is the {@linkplain Option option} that an {@linkplain
* OptionProcessor option processor} recognizes bare arguments as being
* implicitly associated with.
*
* @author Todd L Smith <todd@availlang.org>
* @author Leslie Schultz <leslie@availlang.org>
* @param <OptionKeyType> The type of the option.
*/
public final class DefaultOption<OptionKeyType extends Enum<OptionKeyType>>
extends GenericOption<OptionKeyType>
{
/**
* Construct a new instance.
*
* @param optionKey
* The option key.
* @param description
* A description of the {@code DefaultOption}.
* @param action
* The {@linkplain Continuation2NotNull action} that should be
* performed upon setting of this {@code DefaultOption}.
*/
public DefaultOption (
final OptionKeyType optionKey,
final String description,
final Continuation2NotNull<String, String> action)
{
super(optionKey, singletonList(""), description, action);
}
}
|
3e0c73f841067db1415d630cbabe298726015b27 | 1,056 | java | Java | InterfacesAndAbstractionsExercise/src/BorderControl/Main.java | Dochko0/OOP_Advanced_November_2017 | 21cd80755761b8de5570a9dd15c35b7a28854959 | [
"MIT"
] | null | null | null | InterfacesAndAbstractionsExercise/src/BorderControl/Main.java | Dochko0/OOP_Advanced_November_2017 | 21cd80755761b8de5570a9dd15c35b7a28854959 | [
"MIT"
] | null | null | null | InterfacesAndAbstractionsExercise/src/BorderControl/Main.java | Dochko0/OOP_Advanced_November_2017 | 21cd80755761b8de5570a9dd15c35b7a28854959 | [
"MIT"
] | null | null | null | 27.076923 | 81 | 0.563447 | 5,293 | package BorderControl;
import com.sun.xml.internal.bind.v2.model.core.ID;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
List<Identificable> citizens = new ArrayList<>();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String[] input = bf.readLine().split(" ");
if (input[0].equalsIgnoreCase("end")) {
break;
}
if (input.length == 3) {
citizens.add(new Person(input[2]));
}
if (input.length == 2) {
citizens.add(new Person(input[1]));
}
}
String target = bf.readLine();
for (Identificable citizen : citizens) {
if (citizen.getId().endsWith(target)){
System.out.println(citizen.getId());
}
}
}
}
|
3e0c7463d82efe9b4242cec1b46ea32a8aebcd6e | 12,641 | java | Java | java/calcite/src/main/java/com/mapd/parser/server/ExtensionFunction.java | smilemaxdev/omniscidb | 0517d99b467806f6af7b4c969e351368a667497d | [
"Apache-2.0"
] | 868 | 2019-05-14T22:11:17.000Z | 2022-02-28T09:15:23.000Z | java/calcite/src/main/java/com/mapd/parser/server/ExtensionFunction.java | smilemaxdev/omniscidb | 0517d99b467806f6af7b4c969e351368a667497d | [
"Apache-2.0"
] | 327 | 2019-05-16T18:07:57.000Z | 2022-02-26T09:34:04.000Z | java/calcite/src/main/java/com/mapd/parser/server/ExtensionFunction.java | smilemaxdev/omniscidb | 0517d99b467806f6af7b4c969e351368a667497d | [
"Apache-2.0"
] | 166 | 2019-05-22T11:17:10.000Z | 2022-02-26T06:58:45.000Z | 27.966814 | 90 | 0.638953 | 5,294 | /*
* Copyright 2017 MapD Technologies, 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.mapd.parser.server;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author alex
*/
public class ExtensionFunction {
final static Logger MAPDLOGGER = LoggerFactory.getLogger(ExtensionFunction.class);
public enum ExtArgumentType {
Int8,
Int16,
Int32,
Int64,
Float,
Double,
Void,
PInt8,
PInt16,
PInt32,
PInt64,
PFloat,
PDouble,
PBool,
Bool,
ArrayInt8,
ArrayInt16,
ArrayInt32,
ArrayInt64,
ArrayFloat,
ArrayDouble,
ArrayBool,
ColumnInt8,
ColumnInt16,
ColumnInt32,
ColumnInt64,
ColumnFloat,
ColumnDouble,
ColumnBool,
GeoPoint,
GeoLineString,
Cursor,
GeoPolygon,
GeoMultiPolygon,
TextEncodingNone,
TextEncodingDict,
ColumnListInt8,
ColumnListInt16,
ColumnListInt32,
ColumnListInt64,
ColumnListFloat,
ColumnListDouble,
ColumnListBool,
ColumnTextEncodingDict,
ColumnListTextEncodingDict,
}
;
ExtensionFunction(final List<ExtArgumentType> args, final ExtArgumentType ret) {
this.args = args;
this.ret = ret;
this.outs = null;
this.names = null;
this.isRowUdf = true;
this.options = null;
}
ExtensionFunction(final List<ExtArgumentType> args,
final List<ExtArgumentType> outs,
final List<String> names,
final Map<String, String> options) {
this.args = args;
this.ret = null;
this.outs = outs;
this.names = names;
this.isRowUdf = false;
this.options = options;
}
public List<ExtArgumentType> getArgs() {
return this.args;
}
public List<ExtArgumentType> getOuts() {
return this.outs;
}
public List<String> getArgNames() {
if (this.names != null) {
return this.names.subList(0, this.args.size());
}
return null;
}
public List<String> getOutNames() {
if (this.names != null) {
return this.names.subList(this.args.size(), this.names.size());
}
return null;
}
public ExtArgumentType getRet() {
return this.ret;
}
public SqlTypeName getSqlRet() {
assert this.isRowUdf();
return toSqlTypeName(this.ret);
}
public List<SqlTypeName> getSqlOuts() {
assert this.isTableUdf();
List<SqlTypeName> sql_outs = new ArrayList<SqlTypeName>();
for (final ExtArgumentType otype : this.getOuts()) {
sql_outs.add(toSqlTypeName(getValueType(otype)));
}
return sql_outs;
}
public Map<String, String> getOptions() {
if (this.options != null) {
return new HashMap<String, String>(this.options);
}
return null;
}
public boolean isRowUdf() {
return this.isRowUdf;
}
public boolean isTableUdf() {
return !this.isRowUdf();
}
public String toJson(final String name) {
MAPDLOGGER.debug("Extensionfunction::toJson: " + name);
StringBuilder json_cons = new StringBuilder();
json_cons.append("{");
json_cons.append("\"name\":").append(dq(name)).append(",");
if (isRowUdf) {
json_cons.append("\"ret\":").append(dq(typeName(ret))).append(",");
} else {
json_cons.append("\"outs\":");
json_cons.append("[");
List<String> param_list = new ArrayList<String>();
for (final ExtArgumentType out : outs) {
param_list.add(dq(typeName(out)));
}
json_cons.append(ExtensionFunctionSignatureParser.join(param_list, ","));
json_cons.append("],");
}
json_cons.append("\"args\":");
json_cons.append("[");
List<String> param_list = new ArrayList<String>();
for (final ExtArgumentType arg : args) {
param_list.add(dq(typeName(arg)));
}
json_cons.append(ExtensionFunctionSignatureParser.join(param_list, ","));
json_cons.append("]");
json_cons.append("}");
return json_cons.toString();
}
private static String typeName(final ExtArgumentType type) {
switch (type) {
case Bool:
return "i1";
case Int8:
return "i8";
case Int16:
return "i16";
case Int32:
return "i32";
case Int64:
return "i64";
case Float:
return "float";
case Double:
return "double";
case Void:
return "void";
case PInt8:
return "i8*";
case PInt16:
return "i16*";
case PInt32:
return "i32*";
case PInt64:
return "i64*";
case PFloat:
return "float*";
case PDouble:
return "double*";
case PBool:
return "i1*";
case ArrayInt8:
return "{i8*, i64, i8}*";
case ArrayInt16:
return "{i16*, i64, i8}*";
case ArrayInt32:
return "{i32*, i64, i8}*";
case ArrayInt64:
return "{i64*, i64, i8}*";
case ArrayFloat:
return "{float*, i64, i8}*";
case ArrayDouble:
return "{double*, i64, i8}*";
case ArrayBool:
return "{i1*, i64, i8}*";
case ColumnInt8:
return "column_int8";
case ColumnInt16:
return "column_int16";
case ColumnInt32:
return "column_int32";
case ColumnInt64:
return "column_int64";
case ColumnFloat:
return "column_float";
case ColumnDouble:
return "column_double";
case ColumnBool:
return "column_bool";
case ColumnTextEncodingDict:
return "column_text_encoding_dict";
case GeoPoint:
return "geo_point";
case Cursor:
return "cursor";
case GeoLineString:
return "geo_linestring";
case GeoPolygon:
return "geo_polygon";
case GeoMultiPolygon:
return "geo_multi_polygon";
case TextEncodingNone:
return "text_encoding_none";
case TextEncodingDict:
return "text_encoding_dict";
case ColumnListInt8:
return "column_list_int8";
case ColumnListInt16:
return "column_list_int16";
case ColumnListInt32:
return "column_list_int32";
case ColumnListInt64:
return "column_list_int64";
case ColumnListFloat:
return "column_list_float";
case ColumnListDouble:
return "column_list_double";
case ColumnListBool:
return "column_list_bool";
case ColumnListTextEncodingDict:
return "column_list_text_encoding_dict";
}
MAPDLOGGER.info("Extensionfunction::typeName: unknown type=`" + type + "`");
assert false;
return null;
}
private static String dq(final String str) {
return "\"" + str + "\"";
}
private final List<ExtArgumentType> args;
private final List<ExtArgumentType> outs; // only used by UDTFs
private final List<String> names;
private final ExtArgumentType ret; // only used by UDFs
private final boolean isRowUdf;
private final Map<String, String> options;
public final java.util.List<SqlTypeFamily> toSqlSignature() {
java.util.List<SqlTypeFamily> sql_sig = new java.util.ArrayList<SqlTypeFamily>();
boolean isRowUdf = this.isRowUdf();
for (int arg_idx = 0; arg_idx < this.getArgs().size(); ++arg_idx) {
final ExtArgumentType arg_type = this.getArgs().get(arg_idx);
if (isRowUdf) {
sql_sig.add(toSqlTypeName(arg_type).getFamily());
if (isPointerType(arg_type)) {
++arg_idx;
}
} else {
sql_sig.add(toSqlTypeName(arg_type).getFamily());
}
}
return sql_sig;
}
private static boolean isPointerType(final ExtArgumentType type) {
return type == ExtArgumentType.PInt8 || type == ExtArgumentType.PInt16
|| type == ExtArgumentType.PInt32 || type == ExtArgumentType.PInt64
|| type == ExtArgumentType.PFloat || type == ExtArgumentType.PDouble
|| type == ExtArgumentType.PBool;
}
private static boolean isColumnType(final ExtArgumentType type) {
return type == ExtArgumentType.ColumnInt8 || type == ExtArgumentType.ColumnInt16
|| type == ExtArgumentType.ColumnInt32 || type == ExtArgumentType.ColumnInt64
|| type == ExtArgumentType.ColumnFloat || type == ExtArgumentType.ColumnDouble
|| type == ExtArgumentType.ColumnBool
|| type == ExtArgumentType.ColumnTextEncodingDict;
}
private static boolean isColumnListType(final ExtArgumentType type) {
return type == ExtArgumentType.ColumnListInt8
|| type == ExtArgumentType.ColumnListInt16
|| type == ExtArgumentType.ColumnListInt32
|| type == ExtArgumentType.ColumnListInt64
|| type == ExtArgumentType.ColumnListFloat
|| type == ExtArgumentType.ColumnListDouble
|| type == ExtArgumentType.ColumnListBool
|| type == ExtArgumentType.ColumnListTextEncodingDict;
}
private static ExtArgumentType getValueType(final ExtArgumentType type) {
switch (type) {
case PInt8:
case ColumnInt8:
case ColumnListInt8:
case Int8:
return ExtArgumentType.Int8;
case PInt16:
case ColumnInt16:
case ColumnListInt16:
case Int16:
return ExtArgumentType.Int16;
case PInt32:
case ColumnInt32:
case ColumnListInt32:
case Int32:
return ExtArgumentType.Int32;
case PInt64:
case ColumnInt64:
case ColumnListInt64:
case Int64:
return ExtArgumentType.Int64;
case PFloat:
case ColumnFloat:
case ColumnListFloat:
case Float:
return ExtArgumentType.Float;
case PDouble:
case ColumnDouble:
case ColumnListDouble:
case Double:
return ExtArgumentType.Double;
case PBool:
case ColumnBool:
case ColumnListBool:
case Bool:
return ExtArgumentType.Bool;
case TextEncodingDict:
case ColumnTextEncodingDict:
case ColumnListTextEncodingDict:
return ExtArgumentType.TextEncodingDict;
}
MAPDLOGGER.error("getValueType: no value for type " + type);
assert false;
return null;
}
private static SqlTypeName toSqlTypeName(final ExtArgumentType type) {
switch (type) {
case Bool:
return SqlTypeName.BOOLEAN;
case Int8:
return SqlTypeName.TINYINT;
case Int16:
return SqlTypeName.SMALLINT;
case Int32:
return SqlTypeName.INTEGER;
case Int64:
return SqlTypeName.BIGINT;
case Float:
return SqlTypeName.FLOAT;
case Double:
return SqlTypeName.DOUBLE;
case PInt8:
case PInt16:
case PInt32:
case PInt64:
case PFloat:
case PDouble:
case PBool:
case ArrayInt8:
case ArrayInt16:
case ArrayInt32:
case ArrayInt64:
case ArrayFloat:
case ArrayDouble:
case ArrayBool:
return SqlTypeName.ARRAY;
case GeoPoint:
case GeoLineString:
case GeoPolygon:
case GeoMultiPolygon:
return SqlTypeName.GEOMETRY;
case Cursor:
return SqlTypeName.CURSOR;
case TextEncodingNone:
case TextEncodingDict:
return SqlTypeName.VARCHAR;
case ColumnListInt8:
case ColumnListInt16:
case ColumnListInt32:
case ColumnListInt64:
case ColumnListFloat:
case ColumnListDouble:
case ColumnListBool:
case ColumnListTextEncodingDict:
return SqlTypeName.COLUMN_LIST;
case Void:
// some extension functions return void. these functions should be defined in
// MapDSqlOperatorTable and never have their definition set from the AST file
return null;
}
Set<SqlTypeName> allSqlTypeNames = EnumSet.allOf(SqlTypeName.class);
MAPDLOGGER.error("toSqlTypeName: unknown type " + type + " to be mapped to {"
+ allSqlTypeNames + "}");
assert false;
return null;
}
}
|
3e0c74815bd68bb5a3c0dac03f516d8caebb5450 | 1,120 | java | Java | main/src/cgeo/geocaching/maps/routing/AbstractServiceConnection.java | paatonkana/cgeo | ff96a0fa95374c2254ad253bfba94f75ed74db53 | [
"Apache-2.0"
] | null | null | null | main/src/cgeo/geocaching/maps/routing/AbstractServiceConnection.java | paatonkana/cgeo | ff96a0fa95374c2254ad253bfba94f75ed74db53 | [
"Apache-2.0"
] | null | null | null | main/src/cgeo/geocaching/maps/routing/AbstractServiceConnection.java | paatonkana/cgeo | ff96a0fa95374c2254ad253bfba94f75ed74db53 | [
"Apache-2.0"
] | null | null | null | 27.317073 | 90 | 0.734821 | 5,295 | package cgeo.geocaching.maps.routing;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.annotation.Nullable;
class AbstractServiceConnection implements ServiceConnection {
protected android.os.IInterface routingService;
private Runnable onServiceConnectedCallback = null;
AbstractServiceConnection (final @Nullable Runnable onServiceConnectedCallback) {
this.onServiceConnectedCallback = onServiceConnectedCallback;
}
@Override
public void onServiceConnected(final ComponentName className, final IBinder service) {
if (null != onServiceConnectedCallback) {
onServiceConnectedCallback.run();
}
}
@Override
public void onServiceDisconnected(final ComponentName className) {
this.onServiceConnectedCallback = null;
routingService = null;
}
public boolean isConnected() {
return routingService != null;
}
@Nullable
public String getTrackFromParams(final Bundle params) {
return null;
}
}
|
3e0c749a429e349667feababda06ef982a92a337 | 2,708 | java | Java | redisson/src/main/java/org/redisson/api/RAtomicDouble.java | ZJRui/redisson | 00eeedc719fa8f58eeb7092ea76bee0480901795 | [
"Apache-2.0"
] | 1 | 2020-06-30T09:45:37.000Z | 2020-06-30T09:45:37.000Z | redisson/src/main/java/org/redisson/api/RAtomicDouble.java | klamo/redisson | acbff29eab675ddc6fcfac4e4ae5dbb0f7c3ae45 | [
"Apache-2.0"
] | 4 | 2020-08-24T12:34:08.000Z | 2020-08-24T12:58:50.000Z | redisson/src/main/java/org/redisson/api/RAtomicDouble.java | klamo/redisson | acbff29eab675ddc6fcfac4e4ae5dbb0f7c3ae45 | [
"Apache-2.0"
] | 1 | 2022-03-02T13:54:14.000Z | 2022-03-02T13:54:14.000Z | 24.396396 | 75 | 0.630355 | 5,296 | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.api;
/**
* Distributed implementation to the AtomicDouble
*
* @author Nikita Koksharov
*
*/
public interface RAtomicDouble extends RExpirable, RAtomicDoubleAsync {
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
double getAndDecrement();
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
double addAndGet(double delta);
/**
* Atomically sets the value to the given updated value
* only if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful; or false if the actual value
* was not equal to the expected value.
*/
boolean compareAndSet(double expect, double update);
/**
* Atomically decrements the current value by one.
*
* @return the updated value
*/
double decrementAndGet();
/**
* Returns current value.
*
* @return current value
*/
double get();
/**
* Returns and deletes object
*
* @return the current value
*/
double getAndDelete();
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the old value before the add
*/
double getAndAdd(double delta);
/**
* Atomically sets the given value and returns the old value.
*
* @param newValue the new value
* @return the old value
*/
double getAndSet(double newValue);
/**
* Atomically increments the current value by one.
*
* @return the updated value
*/
double incrementAndGet();
/**
* Atomically increments the current value by one.
*
* @return the old value
*/
double getAndIncrement();
/**
* Atomically sets the given value.
*
* @param newValue the new value
*/
void set(double newValue);
}
|
3e0c74d61107fb0c5738e410560b173547afaee9 | 220 | java | Java | samples/_opengl/ParticlesBasic/androidstudio/ParticlesBasic/app/src/main/java/org/libcinder/samples/particlesbasic/ParticlesBasicActivity.java | s3global/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | [
"BSD-2-Clause"
] | 3,494 | 2015-01-02T08:42:09.000Z | 2022-03-31T14:16:23.000Z | samples/_opengl/ParticlesBasic/androidstudio/ParticlesBasic/app/src/main/java/org/libcinder/samples/particlesbasic/ParticlesBasicActivity.java | edselmalasig/Cinder | 2284df43f77b6b99f8f05384c516e962d9336bc3 | [
"BSD-2-Clause"
] | 1,284 | 2015-01-02T07:31:47.000Z | 2022-03-30T02:06:43.000Z | samples/_opengl/ParticlesBasic/androidstudio/ParticlesBasic/app/src/main/java/org/libcinder/samples/particlesbasic/ParticlesBasicActivity.java | edselmalasig/Cinder | 2284df43f77b6b99f8f05384c516e962d9336bc3 | [
"BSD-2-Clause"
] | 780 | 2015-01-02T22:14:29.000Z | 2022-03-30T00:16:56.000Z | 27.5 | 66 | 0.831818 | 5,297 | package org.libcinder.samples.particlesbasic;
import org.libcinder.app.CinderNativeActivity;
public class ParticlesBasicActivity extends CinderNativeActivity {
static final String TAG = "ParticlesBasicActivity";
}
|
3e0c754ff362ec716614ad713b09304e7be20940 | 6,994 | java | Java | app/src/main/java/com/jlu/chengjie/zhihu/activity/EditorActivity.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | 3 | 2021-04-08T11:20:42.000Z | 2022-03-10T13:23:50.000Z | app/src/main/java/com/jlu/chengjie/zhihu/activity/EditorActivity.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/jlu/chengjie/zhihu/activity/EditorActivity.java | Easoncheng0405/ZhiHu | e7e1dc0702a3806b46c8d0c69238ecd30b43a18c | [
"Apache-2.0"
] | 4 | 2019-05-09T15:24:55.000Z | 2022-03-19T06:49:00.000Z | 38.218579 | 156 | 0.664713 | 5,298 | /*
* Copyright [2018] [chengjie.jlu@qq.com]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jlu.chengjie.zhihu.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.reflect.TypeToken;
import com.jlu.chengjie.zhihu.R;
import com.jlu.chengjie.zhihu.model.Question;
import com.jlu.chengjie.zhihu.model.Response;
import com.jlu.chengjie.zhihu.net.OkHttpHelper;
import com.jlu.chengjie.zhihu.net.RequestCode;
import com.jlu.chengjie.zhihu.net.ServerHelper;
import com.jlu.chengjie.zhihu.util.SPUtil;
import com.jlu.chengjie.zhihu.util.TaskRunner;
import com.jlu.chengjie.zhihu.util.ZLog;
import es.dmoral.toasty.Toasty;
import jp.wasabeef.richeditor.RichEditor;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class EditorActivity extends AppCompatActivity {
private final String TAG = "EditorActivity";
private RichEditor mEditor;
private EditText mTitle;
private View mToolBar;
private SPUtil spUtil;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
context = this;
spUtil = new SPUtil(context);
mEditor = findViewById(R.id.editor);
mTitle = findViewById(R.id.title);
mToolBar = findViewById(R.id.tool_bar);
mEditor.setEditorHeight(200);
mEditor.setEditorFontSize(22);
mEditor.setPadding(10, 10, 10, 10);
mEditor.setPlaceholder("输入问题内容");
mTitle.setOnFocusChangeListener((v, hasFocus) -> mToolBar.setVisibility(hasFocus ? View.INVISIBLE : View.VISIBLE));
findViewById(R.id.next).setOnClickListener(v -> editFinish());
findViewById(R.id.cancel).setOnClickListener(v -> onBackPressed());
findViewById(R.id.action_undo).setOnClickListener(v -> mEditor.undo());
findViewById(R.id.action_redo).setOnClickListener(v -> mEditor.redo());
findViewById(R.id.action_bold).setOnClickListener(v -> mEditor.setBold());
findViewById(R.id.action_italic).setOnClickListener(v -> mEditor.setItalic());
findViewById(R.id.action_subscript).setOnClickListener(v -> mEditor.setSubscript());
findViewById(R.id.action_superscript).setOnClickListener(v -> mEditor.setSuperscript());
findViewById(R.id.action_strikethrough).setOnClickListener(v -> mEditor.setStrikeThrough());
findViewById(R.id.action_underline).setOnClickListener(v -> mEditor.setUnderline());
findViewById(R.id.action_heading1).setOnClickListener(v -> mEditor.setHeading(1));
findViewById(R.id.action_heading2).setOnClickListener(v -> mEditor.setHeading(2));
findViewById(R.id.action_heading3).setOnClickListener(v -> mEditor.setHeading(3));
findViewById(R.id.action_heading4).setOnClickListener(v -> mEditor.setHeading(4));
findViewById(R.id.action_heading5).setOnClickListener(v -> mEditor.setHeading(5));
findViewById(R.id.action_heading6).setOnClickListener(v -> mEditor.setHeading(6));
findViewById(R.id.action_indent).setOnClickListener(v -> mEditor.setIndent());
findViewById(R.id.action_outdent).setOnClickListener(v -> mEditor.setOutdent());
findViewById(R.id.action_align_left).setOnClickListener(v -> mEditor.setAlignLeft());
findViewById(R.id.action_align_center).setOnClickListener(v -> mEditor.setAlignCenter());
findViewById(R.id.action_align_right).setOnClickListener(v -> mEditor.setAlignRight());
findViewById(R.id.action_blockquote).setOnClickListener(v -> mEditor.setBlockquote());
findViewById(R.id.action_insert_bullets).setOnClickListener(v -> mEditor.setBullets());
findViewById(R.id.action_insert_numbers).setOnClickListener(v -> mEditor.setNumbers());
findViewById(R.id.action_insert_image).setOnClickListener(v -> mEditor.insertImage("http://www.1honeywan.com/dachshund/image/7.21/7.21_3_thumb.JPG",
"dachshund"));
findViewById(R.id.action_insert_link).setOnClickListener(v -> mEditor.insertLink("https://github.com/wasabeef", "wasabeef"));
findViewById(R.id.action_insert_checkbox).setOnClickListener(v -> mEditor.insertTodo());
}
private void editFinish() {
String phone = spUtil.getString(spUtil.KEY_PHONE, "");
if (TextUtils.isEmpty(phone)) {
ZLog.w(TAG, "");
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
final String title = mTitle.getText().toString();
if (TextUtils.isEmpty(title) || title.length() < 5 || title.length() > 50) {
Toasty.error(this, "标题长度在5到50个字符之间").show();
return;
}
final String cotent = mEditor.getHtml();
if (cotent == null || cotent.length() < 10) {
Toasty.error(this, "问题内容不少于10个字符").show();
return;
}
if (cotent.length() > 1000) {
Toasty.error(this, "问题内容过长").show();
return;
}
final Map<String, String> params = new HashMap<String, String>() {
{
put("phone", phone);
put("title", title);
put("content", cotent);
}
};
ZLog.d(TAG, "start to submit a new question,phone: %s,title: %s,content: %s", phone, title, cotent);
TaskRunner.execute(() -> {
Type type = new TypeToken<Response<Question>>() {
}.getType();
final Response<Question> response = OkHttpHelper.post(ServerHelper.getUrlQuestion(), type, params);
runOnUiThread(() -> {
if (response == null) {
Toasty.error(context, "无法连接到服务器", Toast.LENGTH_LONG, true).show();
return;
}
if (response.getCode() == RequestCode.SUCCESS) {
Toasty.success(context, "成功发布问题", Toast.LENGTH_LONG, true).show();
finish();
} else {
Toasty.error(context, "发布问题失败, code: " + response.getCode(), Toast.LENGTH_LONG, true).show();
}
});
});
}
}
|
3e0c75bf59d1861c6e3fd81ecbabc315b9a6d224 | 5,372 | java | Java | sofa-dashboard-backend/sofa-dashboard-governance/src/main/java/com/alipay/sofa/dashboard/registry/ZookeeperAdminRegistry.java | liujjpp/sofa-dashboard | 8f6e601f439ba7a145ac10e4c4c6f1ad7fa2f2fb | [
"Apache-2.0"
] | 62 | 2019-05-12T12:31:20.000Z | 2022-02-08T02:08:02.000Z | sofa-dashboard-backend/sofa-dashboard-governance/src/main/java/com/alipay/sofa/dashboard/registry/ZookeeperAdminRegistry.java | liujjpp/sofa-dashboard | 8f6e601f439ba7a145ac10e4c4c6f1ad7fa2f2fb | [
"Apache-2.0"
] | 50 | 2019-05-12T07:25:32.000Z | 2022-02-09T08:50:32.000Z | sofa-dashboard-backend/sofa-dashboard-governance/src/main/java/com/alipay/sofa/dashboard/registry/ZookeeperAdminRegistry.java | liujjpp/sofa-dashboard | 8f6e601f439ba7a145ac10e4c4c6f1ad7fa2f2fb | [
"Apache-2.0"
] | 39 | 2019-05-12T04:58:44.000Z | 2022-03-29T07:24:04.000Z | 37.830986 | 98 | 0.680938 | 5,299 | /*
* 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.alipay.sofa.dashboard.registry;
import com.alipay.sofa.dashboard.constants.SofaDashboardConstants;
import com.alipay.sofa.dashboard.listener.RegistryDataChangeListener;
import com.alipay.sofa.dashboard.listener.zookeeper.RootNodeChangeListener;
import com.alipay.sofa.rpc.common.utils.StringUtils;
import com.alipay.sofa.rpc.config.RegistryConfig;
import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static com.alipay.sofa.rpc.common.utils.StringUtils.CONTEXT_SEP;
/**
* @author bystander
* @version $Id: ZookeeperAdminRegistry.java, v 0.1 2018年12月11日 17:35 bystander Exp $
*/
public class ZookeeperAdminRegistry implements AdminRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperAdminRegistry.class);
/**
* 注册中心服务配置
*/
protected RegistryConfig registryConfig;
/**
* Zookeeper zkClient
*/
private CuratorFramework zkClient;
/**
* Root path of registry data
*/
private String rootPath;
@Autowired
private RootNodeChangeListener rootNodeChangeListener;
@Override
public boolean start(RegistryConfig registryConfig) {
if (zkClient != null) {
return true;
}
this.registryConfig = registryConfig;
// xxx:2181,yyy:2181/path1/path2
String addressInput = registryConfig.getAddress();
if (StringUtils.isEmpty(addressInput)) {
throw new SofaRpcRuntimeException("Address of zookeeper registry is empty.");
}
int idx = addressInput.indexOf(CONTEXT_SEP);
String address; // IP地址
if (idx > 0) {
address = addressInput.substring(0, idx);
rootPath = addressInput.substring(idx);
if (!rootPath.endsWith(CONTEXT_SEP)) {
// 保证以"/"结尾
rootPath += CONTEXT_SEP;
}
} else {
address = addressInput;
rootPath = CONTEXT_SEP;
}
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
zkClient = CuratorFrameworkFactory.builder().connectString(address)
.sessionTimeoutMs(registryConfig.getConnectTimeout() * 3)
.connectionTimeoutMs(registryConfig.getConnectTimeout()).canBeReadOnly(false)
.retryPolicy(retryPolicy).defaultData(null).build();
zkClient.getConnectionStateListenable().addListener((client, newState) -> {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("reconnect to zookeeper,recover provider and consumer data");
}
if (newState == ConnectionState.RECONNECTED) {
recoverRegistryData();
}
});
if (zkClient == null) {
LOGGER.warn("Start zookeeper registry must be do init first!");
return false;
}
if (zkClient.getState() == CuratorFrameworkState.STARTED) {
return true;
}
try {
zkClient.start();
LOGGER.info("Zookeeper client start success,address is {}", address);
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to start zookeeper zkClient", e);
}
return zkClient.getState() == CuratorFrameworkState.STARTED;
}
private void recoverRegistryData() {
//TODO 碧远
}
@Override
public void subscribe(String group, RegistryDataChangeListener listener) {
// 注册Consumer节点
try {
PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient,
SofaDashboardConstants.SEPARATOR + group, true);
pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
pathChildrenCache.getListenable().addListener(rootNodeChangeListener);
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to register consumer to zookeeperRegistry!",
e);
}
}
} |
3e0c7610a6d67dc8646aadf14271e7332374a5fa | 968 | java | Java | p2/p2/logic/objects/Shockwave.java | Corrochano/TP1-2019 | aa8877e728bee8bc8cdbdc8cca5631b9f7f83daf | [
"MIT"
] | null | null | null | p2/p2/logic/objects/Shockwave.java | Corrochano/TP1-2019 | aa8877e728bee8bc8cdbdc8cca5631b9f7f83daf | [
"MIT"
] | null | null | null | p2/p2/logic/objects/Shockwave.java | Corrochano/TP1-2019 | aa8877e728bee8bc8cdbdc8cca5631b9f7f83daf | [
"MIT"
] | null | null | null | 15.612903 | 50 | 0.616736 | 5,300 | package tp.p2.p2.logic.objects;
import tp.p2.p2.logic.Game;
public class Shockwave extends Weapon {
private boolean enable;
public Shockwave(Game game) {
super(game, -1, -1, 1);
this.setEnable(true);
}
@Override
public void computerAction() {
// TODO Auto-generated method stub
}
@Override
public void onDelete() {
// TODO Auto-generated method stub
this.setEnable(true);
}
@Override
public void move() {
// TODO Auto-generated method stub
}
@Override
public String toString() {
return "";
}
@Override
public boolean performAttack(GameObject other) {
if(!this.isEnable()) {
return other.receiveShockWaveAttack(1);
}
else {
return false;
}
}
/**
* @return the enableS
*/
public boolean isEnable() {
return enable;
}
/**
* @param enable the enable to set
*/
public void setEnable(boolean enable) {
this.enable = enable;
}
}
|
3e0c76f588027429cf62b21c4c8d09ee078589a9 | 3,625 | java | Java | manager/manager-core/src/main/java/cn/vbill/middleware/porter/manager/service/MrJobTasksScheduleService.java | js20166098/sxfStandard | e3ed994cc7aafde49572698609f1ddf7db7be0d0 | [
"Apache-2.0"
] | 542 | 2018-08-01T10:24:39.000Z | 2022-03-17T02:51:03.000Z | manager/manager-core/src/main/java/cn/vbill/middleware/porter/manager/service/MrJobTasksScheduleService.java | js20166098/sxfStandard | e3ed994cc7aafde49572698609f1ddf7db7be0d0 | [
"Apache-2.0"
] | 21 | 2018-08-07T09:36:03.000Z | 2020-04-08T03:13:38.000Z | manager/manager-core/src/main/java/cn/vbill/middleware/porter/manager/service/MrJobTasksScheduleService.java | js20166098/sxfStandard | e3ed994cc7aafde49572698609f1ddf7db7be0d0 | [
"Apache-2.0"
] | 166 | 2018-08-01T10:24:50.000Z | 2022-03-17T09:29:17.000Z | 27.255639 | 131 | 0.625103 | 5,301 | /*
* Copyright ©2018 vbill.cn.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* </p>
*/
package cn.vbill.middleware.porter.manager.service;
import cn.vbill.middleware.porter.manager.core.entity.MrJobTasksSchedule;
import cn.vbill.middleware.porter.common.task.statistics.DTaskStat;
import cn.vbill.middleware.porter.common.task.config.TaskConfig;
import cn.vbill.middleware.porter.common.task.dic.TaskStatusType;
import cn.vbill.middleware.porter.manager.web.page.Page;
import java.util.List;
/**
* 任务泳道进度表 服务接口类
*
* @author: FairyHood
* @date: 2018-03-07 13:40:30
* @version: V1.0-auto
* @review: FairyHood/2018-03-07 13:40:30
*/
public interface MrJobTasksScheduleService {
/**
* 新增
*
* @date 2018/8/10 下午1:58
* @param: [mrJobTasksSchedule]
* @return: java.lang.Integer
*/
Integer insert(MrJobTasksSchedule mrJobTasksSchedule);
/**
* 更新
*
* @date 2018/8/10 下午1:58
* @param: [id,
* mrJobTasksSchedule]
* @return: java.lang.Integer
*/
Integer update(Long id, MrJobTasksSchedule mrJobTasksSchedule);
/**
* 删除
*
* @date 2018/8/10 下午1:59
* @param: [id]
* @return: java.lang.Integer
*/
Integer delete(Long id);
/**
* 根据id查询
*
* @date 2018/8/10 下午1:59
* @param: [id]
* @return: cn.vbill.middleware.porter.manager.core.event.MrJobTasksSchedule
*/
MrJobTasksSchedule selectById(Long id);
/**
* 变更任务状态
*
* @param id
* @param taskStatusType
* @return
*/
Integer updateState(Long id, TaskStatusType taskStatusType);
/**
* 分页
*
* @date 2018/8/10 下午1:59
* @param: [page]
* @return: cn.vbill.middleware.porter.manager.web.page.Page<cn.vbill.middleware.porter.manager.core.event.MrJobTasksSchedule>
*/
Page<MrJobTasksSchedule> page(Page<MrJobTasksSchedule> page);
/** 解析处理 任务进度状态汇总. */
void dealDTaskStat(DTaskStat stat);
/**
* 接收任务
*
* @param task
* @param taskConfigJson
*/
void dealJobJsonText(TaskConfig task, String taskConfigJson);
/**
* 根据JobId查询
*
* @date 2018/8/10 下午2:00
* @param: [jobId]
* @return: java.util.List<cn.vbill.middleware.porter.manager.core.event.MrJobTasksSchedule>
*/
List<MrJobTasksSchedule> selectSwimlaneByJobId(String jobId);
/**
* 列表
*
* @date 2018/8/10 下午2:01
* @param: [jobId,
* heartBeatBeginDate, heartBeatEndDate]
* @return: java.util.List<cn.vbill.middleware.porter.manager.core.event.MrJobTasksSchedule>
*/
List<MrJobTasksSchedule> list(String jobId, String heartBeatBeginDate, String heartBeatEndDate);
/**
* 列表
*
* @param jobId
* @param heartBeatBeginDate
* @param heartBeatEndDate
* @return
*/
List<MrJobTasksSchedule> listJobTasks(String jobId, String heartBeatBeginDate, String heartBeatEndDate);
}
|
3e0c76faf953f63e88b964355acf97032320e48a | 1,616 | java | Java | evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/time/chrono/MockJapaneseChronology.java | racoq/TESRAC | 75a33741bd7a0c27a5fcd183fb4418d7b7146e80 | [
"Apache-2.0"
] | null | null | null | evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/time/chrono/MockJapaneseChronology.java | racoq/TESRAC | 75a33741bd7a0c27a5fcd183fb4418d7b7146e80 | [
"Apache-2.0"
] | null | null | null | evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/time/chrono/MockJapaneseChronology.java | racoq/TESRAC | 75a33741bd7a0c27a5fcd183fb4418d7b7146e80 | [
"Apache-2.0"
] | null | null | null | 34.382979 | 83 | 0.729579 | 5,302 | /**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.runtime.mock.java.time.chrono;
import org.evosuite.runtime.mock.StaticReplacementMock;
import org.evosuite.runtime.mock.java.time.MockClock;
import java.time.ZoneId;
import java.time.chrono.JapaneseChronology;
import java.time.chrono.JapaneseDate;
/**
* Created by gordon on 24/01/2016.
*/
public class MockJapaneseChronology implements StaticReplacementMock {
@Override
public String getMockedClassName() {
return JapaneseChronology.class.getName();
}
public static JapaneseDate dateNow(JapaneseChronology instance) {
return instance.dateNow(MockClock.systemDefaultZone());
}
public static JapaneseDate dateNow(JapaneseChronology instance, ZoneId zone) {
return instance.dateNow(MockClock.system(zone));
}
}
|
3e0c774c68774ceb4cc30262fa08975cced2abbb | 168 | java | Java | orchestrator/src/main/java/hu/perit/orchestrator/rest/model/PlaceOrderResponse.java | nagypet/camundastudy | 3bd7f15197088fc0e6ad4f4f33336cc2fabcd3e4 | [
"Apache-2.0"
] | 1 | 2021-06-01T12:48:01.000Z | 2021-06-01T12:48:01.000Z | orchestrator/src/main/java/hu/perit/orchestrator/rest/model/PlaceOrderResponse.java | nagypet/camundastudy | 3bd7f15197088fc0e6ad4f4f33336cc2fabcd3e4 | [
"Apache-2.0"
] | null | null | null | orchestrator/src/main/java/hu/perit/orchestrator/rest/model/PlaceOrderResponse.java | nagypet/camundastudy | 3bd7f15197088fc0e6ad4f4f33336cc2fabcd3e4 | [
"Apache-2.0"
] | null | null | null | 14 | 41 | 0.791667 | 5,303 | package hu.perit.orchestrator.rest.model;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class PlaceOrderResponse
{
String processInstanceId;
}
|
3e0c795dc8d81ef1966f75eb1b0386c56f8ac9e6 | 1,644 | java | Java | src/main/java/net/soularcana/common/entity/FrostProjectileEntity.java | gabeernie/Soul-Arcana | 314e693992984b252b78a6712ca3fb1dfb4a636d | [
"CC0-1.0"
] | null | null | null | src/main/java/net/soularcana/common/entity/FrostProjectileEntity.java | gabeernie/Soul-Arcana | 314e693992984b252b78a6712ca3fb1dfb4a636d | [
"CC0-1.0"
] | null | null | null | src/main/java/net/soularcana/common/entity/FrostProjectileEntity.java | gabeernie/Soul-Arcana | 314e693992984b252b78a6712ca3fb1dfb4a636d | [
"CC0-1.0"
] | null | null | null | 26.095238 | 101 | 0.657543 | 5,304 | package net.soularcana.common.entity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.ProjectileDamageSource;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.World;
import net.voxelindustry.brokkcolor.Color;
public class FrostProjectileEntity extends GlobeProjectileEntity
{
private static final Color PRIMARY_COLOR = new Color(224 / 256F, 1, 1);
private static final Color SECONDARY_COLOR = new Color(120 / 256F, 214 / 256F, 214 / 256F);
private static final Color FADE_COLOR = new Color(96 / 256F, 224 / 256F, 224 / 256F);
public FrostProjectileEntity(EntityType<?> type, World world)
{
super(type, world);
}
@Override
protected void onImpact(HitResult hitResult, Entity target)
{
target.damage(
new ProjectileDamageSource("frost_globe", this, world.getPlayerByUuid(getCasterId()))
.setUsesMagic()
.setProjectile(),
2F);
if (target instanceof LivingEntity living)
living.setFrozenTicks(20);
onImpact(hitResult);
}
@Override
protected void onImpact(HitResult hitResult)
{
discard();
// TODO: Projectile OnImpact particle effects
}
@Override
public Color getPrimaryColor()
{
return PRIMARY_COLOR;
}
@Override
public Color getSecondaryColor()
{
return SECONDARY_COLOR;
}
@Override
public Color getFadeColor()
{
return FADE_COLOR;
}
}
|
3e0c79ea932b6657c76d3cf7fd42850ba0d4a511 | 2,843 | java | Java | src/main/java/com/sensiblemetrics/api/alpenidos/pattern/throttling/ThrottlingPatternLoader.java | AlexRogalskiy/java4you | 7657177bcc3acc4029e19a63f21fe4d65c714aac | [
"MIT"
] | null | null | null | src/main/java/com/sensiblemetrics/api/alpenidos/pattern/throttling/ThrottlingPatternLoader.java | AlexRogalskiy/java4you | 7657177bcc3acc4029e19a63f21fe4d65c714aac | [
"MIT"
] | 144 | 2021-01-21T00:11:18.000Z | 2022-03-31T21:35:01.000Z | src/main/java/com/sensiblemetrics/api/alpenidos/pattern/throttling/ThrottlingPatternLoader.java | AlexRogalskiy/java4you | 7657177bcc3acc4029e19a63f21fe4d65c714aac | [
"MIT"
] | null | null | null | 41.808824 | 114 | 0.699261 | 5,305 | package com.sensiblemetrics.api.alpenidos.pattern.throttling;
import com.sensiblemetrics.api.alpenidos.pattern.throttling.iface.Throttler;
import com.sensiblemetrics.api.alpenidos.pattern.throttling.impl.ThrottleTimerImpl;
import com.sensiblemetrics.api.alpenidos.pattern.throttling.model.CallsCount;
import com.sensiblemetrics.api.alpenidos.pattern.throttling.model.Tenant;
import com.sensiblemetrics.api.alpenidos.pattern.throttling.service.B2BService;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Throttling pattern is a design pattern to throttle or limit the use of resources or even a complete service by
* users or a particular tenant. This can allow systems to continue to function and meet service level agreements,
* even when an increase in demand places load on resources.
* <p>
* In this example we have ({@link ThrottlingPatternLoader}) as the initiating point of the service.
* This is a time based throttling, i.e. only a certain number of calls are allowed per second.
* </p>
* ({@link Tenant}) is the Tenant POJO class with which many tenants can be created
* ({@link B2BService}) is the service which is consumed by the tenants and is throttled.
*/
@Slf4j
public class ThrottlingPatternLoader {
/**
* Application entry point
*
* @param args main arguments
*/
public static void main(final String[] args) {
final CallsCount callsCount = new CallsCount();
final Tenant adidas = new Tenant("Adidas", 5, callsCount);
final Tenant nike = new Tenant("Nike", 6, callsCount);
final ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(() -> makeServiceCalls(adidas, callsCount));
executorService.execute(() -> makeServiceCalls(nike, callsCount));
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("Executor Service terminated: {}", e.getMessage());
}
}
/**
* Make calls to the B2BService dummy API
*/
private static void makeServiceCalls(final Tenant tenant, final CallsCount callsCount) {
final Throttler timer = new ThrottleTimerImpl(10, callsCount);
final B2BService service = new B2BService(timer, callsCount);
for (int i = 0; i < 20; i++) {
service.dummyCustomerApi(tenant);
// Sleep is introduced to keep the output in check and easy to view and analyze the results.
try {
Thread.sleep(1);
} catch (InterruptedException e) {
log.error("Thread interrupted: {}", e.getMessage());
}
}
}
}
|
3e0c7b39fb105ae0039c6ec510f93677995fc3f1 | 3,944 | java | Java | src/dynamicinvoke/impl/DynamicBeanAccessor.java | tomatsu/dynamicinvoke | 12b9f0a8a844a7cb50810d1abded8759261cf70c | [
"CC0-1.0"
] | null | null | null | src/dynamicinvoke/impl/DynamicBeanAccessor.java | tomatsu/dynamicinvoke | 12b9f0a8a844a7cb50810d1abded8759261cf70c | [
"CC0-1.0"
] | null | null | null | src/dynamicinvoke/impl/DynamicBeanAccessor.java | tomatsu/dynamicinvoke | 12b9f0a8a844a7cb50810d1abded8759261cf70c | [
"CC0-1.0"
] | 1 | 2019-04-23T03:32:28.000Z | 2019-04-23T03:32:28.000Z | 28.788321 | 71 | 0.699797 | 5,306 | /*
* This software is released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/.
*/
package dynamicinvoke.impl;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import dynamicinvoke.*;
public class DynamicBeanAccessor extends BeanAccessor {
static Object[] noarg = new Object[0];
private Map<String,ProxyCache> readMethodProxies;
private Map<String,ProxyCache> writeMethodProxies;
public DynamicBeanAccessor(Class<?> cls) {
super(cls);
}
protected void init(Class<?> cls) {
this.readMethodProxies = new HashMap<String,ProxyCache>();
this.writeMethodProxies = new HashMap<String,ProxyCache>();
super.init(cls);
}
protected void addReadMethod(String name, Method m) {
Method m0 = m;
if (!isPublic) {
String methodName = m.getName();
Class[] types = m.getParameterTypes();
m = DynamicRuntime.findCallableMethod(beanClass, methodName, types);
}
if (m != null) {
CodeLoader loader = new CodeLoader(m.getDeclaringClass()
.getClassLoader());
DynamicProxy px = DynamicProxyFactory.makeProxy(m, loader);
ProxyCache pc = new ProxyCache(m, beanClass);
pc.proxy = px;
readMethodProxies.put(name, pc);
} else {
DynamicProxy px = createReflectionProxy(beanClass, name);
ProxyCache pc = new ProxyCache(m0, beanClass);
pc.proxy = px;
readMethodProxies.put(name, pc);
writeMethodProxies.put(name, pc);
}
}
protected void addWriteMethod(String name, Method m) {
Method m0 = m;
if (!isPublic) {
String methodName = m.getName();
Class[] types = m.getParameterTypes();
m = DynamicRuntime.findCallableMethod(beanClass, methodName, types);
}
if (m != null) {
CodeLoader loader = new CodeLoader(m.getDeclaringClass()
.getClassLoader());
DynamicProxy px = DynamicProxyFactory.makeProxy(m, loader);
ProxyCache pc = new ProxyCache(m, beanClass);
pc.proxy = px;
writeMethodProxies.put(name, pc);
} else {
DynamicProxy px = createReflectionProxy(beanClass, name);
ProxyCache pc = new ProxyCache(m0, beanClass);
pc.proxy = px;
readMethodProxies.put(name, pc);
writeMethodProxies.put(name, pc);
}
}
public ProxyCache findReadMethodProxy(String name) {
return readMethodProxies.get(name);
}
public ProxyCache findWriteMethodProxy(String name) {
return writeMethodProxies.get(name);
}
static void createMethodMap(ObjectDesc d,
final Map<String,Method> readMethods,
final Map<String,Method> writeMethods)
{
d.handleProperties(new PropertyHandler() {
public void handle(String propertyName, Class<?> type,
Method readMethod, Method writeMethod) {
if (readMethod != null) {
readMethods.put(propertyName, readMethod);
}
if (writeMethod != null) {
writeMethods.put(propertyName, writeMethod);
}
}
});
}
static DynamicProxy createReflectionProxy(Class<?> cls, String name) {
ObjectDesc od = ObjectDescFactory.getDefault().create(cls);
Map<String,Method> rmap = new HashMap<String,Method>();
Map<String,Method> wmap = new HashMap<String,Method>();
createMethodMap(od, rmap, wmap);
Method w = rmap.get(name);
Method r = wmap.get(name);
if (r != null) {
r.setAccessible(true);
}
if (w != null) {
w.setAccessible(true);
}
final Method readMethod = r;
final Method writeMethod = w;
DynamicProxy px = new DynamicProxy() {
public Object invoke(Object target) {
try {
return readMethod.invoke(target, noarg);
} catch (IllegalAccessException iae) {
} catch (InvocationTargetException ite) {
}
return null;
}
public Object invoke(Object target, Object[] args) {
try {
writeMethod.invoke(target, args);
} catch (IllegalAccessException iae) {
} catch (InvocationTargetException ite) {
}
return null;
}
};
return px;
}
}
|
3e0c7b6da9a0decece6cfb3c61757685561b2c26 | 3,881 | java | Java | Common/data/src/test/java/adsbrecorder/common/test/user/TestRoleService.java | wangyeee/adsbrecorder | 3774c13d641865d5635be1e66b47754b1536077c | [
"BSD-3-Clause"
] | 2 | 2019-06-04T09:30:10.000Z | 2019-06-04T09:30:11.000Z | Common/data/src/test/java/adsbrecorder/common/test/user/TestRoleService.java | wangyeee/adsbrecorder | 3774c13d641865d5635be1e66b47754b1536077c | [
"BSD-3-Clause"
] | null | null | null | Common/data/src/test/java/adsbrecorder/common/test/user/TestRoleService.java | wangyeee/adsbrecorder | 3774c13d641865d5635be1e66b47754b1536077c | [
"BSD-3-Clause"
] | 1 | 2020-10-04T21:57:00.000Z | 2020-10-04T21:57:00.000Z | 41.287234 | 122 | 0.735635 | 5,307 | package adsbrecorder.common.test.user;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import adsbrecorder.common.test.conf.InMemoryDBTestConfiguration;
import adsbrecorder.user.entity.Role;
import adsbrecorder.user.service.RoleService;
@EnableJpaRepositories(basePackages = "adsbrecorder.user.repo")
@TestPropertySource(locations = "/test.properties")
@ContextConfiguration(classes = InMemoryDBTestConfiguration.class)
@ComponentScan(basePackages = {
"adsbrecorder.user",
"adsbrecorder.user.service"})
@EntityScan(basePackages = {
"adsbrecorder.user.entity"})
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class TestRoleService {
@Autowired
public RoleService roleService;
@Test
public void testFindOrSaveByRoleName() {
String roleName = "ROLE_TEST_FIND_OR_SAVE_BY_ROLE_NAME";
String displayName = "Test Role Display Name";
String description = "Test role description";
Role newRole = roleService.findOrSaveByRoleName(roleName, displayName, description);
assertNotNull(newRole);
Role updatedRole = roleService.findOrSaveByRoleName(roleName, displayName + " updated", description + " updated");
assertNotEquals(updatedRole, newRole);
}
@Test
public void testFindByRoleName() {
String roleName = "ROLE_TEST_FIND_BY_ROLE_NAME";
String displayName = "Test Role Display Name";
String description = "Test role description";
Role newRole = roleService.findOrSaveByRoleName(roleName, displayName, description);
assertNotNull(newRole);
Role findByName = roleService.findByRoleName(roleName);
assertEquals(newRole, findByName);
Role nonExists = roleService.findByRoleName("Some Role");
assertEquals(Long.valueOf(-1L), nonExists.getRoleId());
Role nullName = roleService.findByRoleName(null);
assertEquals(Long.valueOf(-1L), nullName.getRoleId());
}
@Test
public void testFindRoleById() {
String roleName = "ROLE_TEST_FIND_BY_ROLE_NAME";
String displayName = "Test Role Display Name";
String description = "Test role description";
Role newRole = roleService.findOrSaveByRoleName(roleName, displayName, description);
assertNotNull(newRole);
Role findById = roleService.findRoleById(newRole.getRoleId());
assertEquals(newRole, findById);
Role nonExists = roleService.findRoleById(-2L);
assertEquals(Long.valueOf(-1L), nonExists.getRoleId());
}
@Test
public void testSaveRole() {
String roleName = "ROLE_TEST_SAVE_ROLE";
String displayName = "Test Role Display Name";
String description = "Test role description";
Role newRole = new Role();
newRole.setDisplayName(displayName);
newRole.setRoleName(roleName);
newRole.setDescription(description);
Role savedRole = roleService.saveRole(newRole);
assertEquals(roleName, savedRole.getRoleName());
assertEquals(displayName, savedRole.getDisplayName());
assertEquals(description, savedRole.getDescription());
}
}
|
3e0c7c84c6fe26c99cf057a87726889f9cc42adb | 2,177 | java | Java | src/main/java/com/proyecto/AbeRol/UIUtils/AudioFilePlayer.java | Abepuoh/AbeRol | 5edf152c0c2df1000590409cb02f893f1d4a9f04 | [
"MIT"
] | null | null | null | src/main/java/com/proyecto/AbeRol/UIUtils/AudioFilePlayer.java | Abepuoh/AbeRol | 5edf152c0c2df1000590409cb02f893f1d4a9f04 | [
"MIT"
] | null | null | null | src/main/java/com/proyecto/AbeRol/UIUtils/AudioFilePlayer.java | Abepuoh/AbeRol | 5edf152c0c2df1000590409cb02f893f1d4a9f04 | [
"MIT"
] | null | null | null | 33.492308 | 113 | 0.642168 | 5,308 | package com.proyecto.AbeRol.UIUtils;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioFilePlayer extends Thread{
@Override
public void run() {
play("D:\\ESTUDIOS\\1DAM\\TERCER TRISMESTRE\\AbeRol\\src\\main\\resources\\com\\proyecto\\AbeRol\\tabern.wav");
}
public static void play(String inputStream) {
final File file = new File(inputStream);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private static AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private static void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
|
3e0c7cd06847314c6909be695f8dc652422e2f3c | 1,704 | java | Java | app/src/androidTest/java/com/github/devjn/githubsearch/Utils.java | devjn/GithubSearch | a61d3bd55db1c211759fecbe26bf27f2f931402e | [
"Apache-2.0"
] | 4 | 2017-05-04T07:37:44.000Z | 2019-02-15T05:18:13.000Z | app/src/androidTest/java/com/github/devjn/githubsearch/Utils.java | devjn/GithubSearch | a61d3bd55db1c211759fecbe26bf27f2f931402e | [
"Apache-2.0"
] | 1 | 2017-05-04T07:34:09.000Z | 2017-05-05T18:29:59.000Z | app/src/androidTest/java/com/github/devjn/githubsearch/Utils.java | devjn/GithubSearch | a61d3bd55db1c211759fecbe26bf27f2f931402e | [
"Apache-2.0"
] | null | null | null | 25.432836 | 110 | 0.609155 | 5,309 | package com.github.devjn.githubsearch;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by @author Jahongir on 11-Jul-18
* lyhxr@example.com
* Utils
*/
public class Utils {
public static Executor immediateExecutor() {
return command -> command.run();
}
public static ExecutorService immediateExecutorService() {
return new AbstractExecutorService() {
@Override public void shutdown() {
}
@Override public List<Runnable> shutdownNow() {
return null;
}
@Override public boolean isShutdown() {
return false;
}
@Override public boolean isTerminated() {
return false;
}
@Override public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException {
return false;
}
@Override public void execute(Runnable runnable) {
runnable.run();
}
};
}
public static class TestExecutor implements Executor {
private ConcurrentLinkedQueue<Runnable> commands = new ConcurrentLinkedQueue<>();
@Override public void execute(@NotNull Runnable command) {
commands.add(command);
}
public void triggerActions() {
for (Runnable command : commands) {
command.run();
}
}
}
}
|
3e0c7d53de02c99ce89de0ac2224478f7062a874 | 655 | java | Java | src/main/java/com/spring/auth/role/infrastructure/dtos/output/CreateRoleOutputDto.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | src/main/java/com/spring/auth/role/infrastructure/dtos/output/CreateRoleOutputDto.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | src/main/java/com/spring/auth/role/infrastructure/dtos/output/CreateRoleOutputDto.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | 23.392857 | 56 | 0.761832 | 5,310 | package com.spring.auth.role.infrastructure.dtos.output;
import com.spring.auth.role.domain.Role;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/** @author diegotobalina created on 24/06/2020 */
@Getter
@Setter
@ToString
@NoArgsConstructor
public class CreateRoleOutputDto {
private String id;
private String name;
private String description;
private String value;
public CreateRoleOutputDto(Role createdRole) {
this.id = createdRole.getId();
this.name = createdRole.getName();
this.description = createdRole.getDescription();
this.value = createdRole.getValue();
}
}
|
3e0c7edae40260f459d1600d6a992a2f1733b56b | 191 | java | Java | src/main/java/ltd/kafka/soonelu/plugins/ui/gen/base/Item.java | soonelu/idea-plugin | 552f6619a4b31523c01e602a0047345a68e81c7c | [
"MIT"
] | null | null | null | src/main/java/ltd/kafka/soonelu/plugins/ui/gen/base/Item.java | soonelu/idea-plugin | 552f6619a4b31523c01e602a0047345a68e81c7c | [
"MIT"
] | null | null | null | src/main/java/ltd/kafka/soonelu/plugins/ui/gen/base/Item.java | soonelu/idea-plugin | 552f6619a4b31523c01e602a0047345a68e81c7c | [
"MIT"
] | null | null | null | 11.9375 | 46 | 0.539267 | 5,311 | package ltd.kafka.soonelu.plugins.ui.gen.base;
/**
* 元素接口
*
* @author soonelu
*/
public interface Item {
/**
* 获取元素名称
*
* @return 元素名称
*/
String getName();
}
|
3e0c7f4144819c2672545b0aba7c0c1d3361ed66 | 1,060 | java | Java | mllib/target/java/org/apache/spark/ml/tree/ContinuousSplit.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mllib/target/java/org/apache/spark/ml/tree/ContinuousSplit.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mllib/target/java/org/apache/spark/ml/tree/ContinuousSplit.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | 55.789474 | 120 | 0.714151 | 5,312 | package org.apache.spark.ml.tree;
/**
* Split which tests a continuous feature.
* param: featureIndex Index of the feature to test
* param: threshold If the feature value is less than or equal to this threshold, then the
* split goes left. Otherwise, it goes right.
*/
public class ContinuousSplit implements org.apache.spark.ml.tree.Split {
// not preceding
ContinuousSplit (int featureIndex, double threshold) { throw new RuntimeException(); }
public boolean equals (Object o) { throw new RuntimeException(); }
public int featureIndex () { throw new RuntimeException(); }
public int hashCode () { throw new RuntimeException(); }
boolean shouldGoLeft (org.apache.spark.ml.linalg.Vector features) { throw new RuntimeException(); }
boolean shouldGoLeft (int binnedFeature, org.apache.spark.ml.tree.Split[] splits) { throw new RuntimeException(); }
public double threshold () { throw new RuntimeException(); }
org.apache.spark.mllib.tree.model.Split toOld () { throw new RuntimeException(); }
}
|
3e0c7f798c0c9d04a775d4dfafc56d57043b5e23 | 251 | java | Java | src/ClientPeer/Peer.java | ltdagabriel/projeto-sd | acd9556b9aa9d842d4142ed263cdbef2233e8eaf | [
"Unlicense"
] | null | null | null | src/ClientPeer/Peer.java | ltdagabriel/projeto-sd | acd9556b9aa9d842d4142ed263cdbef2233e8eaf | [
"Unlicense"
] | null | null | null | src/ClientPeer/Peer.java | ltdagabriel/projeto-sd | acd9556b9aa9d842d4142ed263cdbef2233e8eaf | [
"Unlicense"
] | null | null | null | 17.928571 | 43 | 0.661355 | 5,313 | package ClientPeer;
import java.io.Serializable;
import java.net.InetAddress;
public class Peer implements Serializable {
InetAddress ip;
int port;
Peer(InetAddress ip, int port) {
this.ip = ip;
this.port = port;
}
} |
3e0c7fcfaa2e7cafe6a47961ebaf5fbcbba86d56 | 8,471 | java | Java | src/main/java/org/cloudfoundry/promregator/cfaccessor/ReactiveCFPaginatedRequestFetcher.java | mcsammac/promregator | c79bff7029573ca9f57e32a6b56b976fed4fa8fe | [
"Apache-2.0"
] | null | null | null | src/main/java/org/cloudfoundry/promregator/cfaccessor/ReactiveCFPaginatedRequestFetcher.java | mcsammac/promregator | c79bff7029573ca9f57e32a6b56b976fed4fa8fe | [
"Apache-2.0"
] | null | null | null | src/main/java/org/cloudfoundry/promregator/cfaccessor/ReactiveCFPaginatedRequestFetcher.java | mcsammac/promregator | c79bff7029573ca9f57e32a6b56b976fed4fa8fe | [
"Apache-2.0"
] | null | null | null | 42.782828 | 124 | 0.711132 | 5,314 | package org.cloudfoundry.promregator.cfaccessor;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.logging.Level;
import org.cloudfoundry.client.v2.OrderDirection;
import org.cloudfoundry.client.v2.PaginatedRequest;
import org.cloudfoundry.client.v2.PaginatedResponse;
import org.cloudfoundry.promregator.ExitCodes;
import org.cloudfoundry.promregator.internalmetrics.InternalMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
class ReactiveCFPaginatedRequestFetcher {
private static final Logger log = LoggerFactory.getLogger(ReactiveCFPaginatedRequestFetcher.class);
private static final int MAX_SUPPORTED_RESULTS_PER_PAGE = 100;
private static final int RESULTS_PER_PAGE = MAX_SUPPORTED_RESULTS_PER_PAGE;
private InternalMetrics internalMetrics;
public ReactiveCFPaginatedRequestFetcher(InternalMetrics internalMetrics) {
super();
this.internalMetrics = internalMetrics;
}
/**
* performs standard (raw) retrieval from the CF Cloud Controller of a single
* page
*
* @param retrievalTypeName
* the name of type of the request which is being made; used for
* identification in internalMetrics
* @param logName
* the name of the logger category, which shall be used for logging
* this Reactor operation
* @param key
* the key for which the request is being made (e.g. orgId,
* orgId|spaceName, ...)
* @param requestData
* an object which is being used as input parameter for the request
* @param requestFunction
* a function which calls the CF API operation, which is being made,
* <code>requestData</code> is used as input parameter for this
* function.
* @param timeoutInMS
* the timeout value in milliseconds for a single data request to the
* CF Cloud Controller
* @return a Mono on the response provided by the CF Cloud Controller
*/
@SuppressWarnings("lgtm[java/sync-on-boxed-types]")
/*
* Reasoning: The string used as foundation for the lock is made very unique.
* The risk of another thread using exactly the very same value of the string for a different purpose
* is considered acceptable.
* Moreover, the performance impact of the lock being engaged improperly is considered small,
* as the duration of this method is assumed to be within milliseconds.
* The effort of implementing a key to lock-object mapping (as alternative) is expected to be rather high
* and would imply the risk of memory leaks.
*/
public <P, R> Mono<P> performGenericRetrieval(String retrievalTypeName, String logName, String key, R requestData,
Function<R, Mono<P>> requestFunction, int timeoutInMS) {
final String lock = (this.getClass().getCanonicalName()+"|"+retrievalTypeName+"|"+key).intern();
synchronized (lock) {
Mono<P> result = null;
ReactiveTimer reactiveTimer = new ReactiveTimer(this.internalMetrics, retrievalTypeName);
result = Mono.just(requestData)
// start the timer
.zipWith(Mono.just(reactiveTimer)).map(tuple -> {
tuple.getT2().start();
return tuple.getT1();
}).flatMap(requestFunction).timeout(Duration.ofMillis(timeoutInMS)).retry(2)
.doOnError(throwable -> {
Throwable unwrappedThrowable = Exceptions.unwrap(throwable);
if (unwrappedThrowable instanceof TimeoutException) {
log.error(String.format(
"Async retrieval of %s with key %s caused a timeout after %dms even though we tried three times",
logName, key, timeoutInMS));
} else if (unwrappedThrowable instanceof OutOfMemoryError){
// This may be an direct memory or a heap error!
// Using String.format and/or log.error here is a bad idea - it takes memory!
if (System.getenv("VCAP_APPLICATION") != null) {
// we assume that we are running on a Cloud Foundry container
this.triggerOutOfMemoryRestart();
}
} else {
log.error(String.format("Async retrieval of %s with key %s raised a reactor error", logName,
key), unwrappedThrowable);
}
})
// stop the timer
.zipWith(Mono.just(reactiveTimer)).map(tuple -> {
tuple.getT2().stop();
return tuple.getT1();
}).log(log.getName() + "." + logName, Level.FINE).cache();
return result;
}
}
@SuppressFBWarnings(value = "DM_EXIT", justification="Restart of JVM is done intentionally here!")
private void triggerOutOfMemoryRestart() {
System.err.println("Out of Memory situation detected on talking to the Cloud Foundry Controller; restarting application");
System.exit(ExitCodes.CF_ACCESSOR_OUT_OF_MEMORY);
}
/**
* performs a retrieval from the CF Cloud Controller fetching all pages
* available.
*
* @param retrievalTypeName
* the name of type of the request which is being made; used for
* identification in internalMetrics
* @param logName
* the name of the logger category, which shall be used for logging
* this Reactor operation
* @param key
* the key for which the request is being made (e.g. orgId,
* orgId|spaceName, ...)
* @param requestGenerator
* a request generator function, which permits creating request
* objects instance for a given set of page parameters (e.g. for
* which page, using which page size, ...)
* @param requestFunction
* a function which calls the CF API operation, which is being made.
* @param timeoutInMS
* the timeout value in milliseconds for a single data request to the
* CF Cloud Controller
* @param responseGenerator
* a response generator function, which permits creating a response
* object, which contains the collected resources of all pages
* retrieved.
* @return a Mono on the response provided by the CF Cloud Controller
*/
public <S, P extends PaginatedResponse<?>, R extends PaginatedRequest> Mono<P> performGenericPagedRetrieval(
String retrievalTypeName, String logName, String key, PaginatedRequestGeneratorFunction<R> requestGenerator,
Function<R, Mono<P>> requestFunction, int timeoutInMS,
PaginatedResponseGeneratorFunction<S, P> responseGenerator) {
final String pageRetrievalType = retrievalTypeName + "_singlePage";
ReactiveTimer reactiveTimer = new ReactiveTimer(this.internalMetrics, retrievalTypeName);
Mono<P> firstPage = Mono.just(reactiveTimer).doOnNext(ReactiveTimer::start).flatMap(dummy ->
this.performGenericRetrieval(pageRetrievalType, logName, key, requestGenerator.
apply(OrderDirection.ASCENDING, RESULTS_PER_PAGE, 1), requestFunction, timeoutInMS));
Flux<R> requestFlux = firstPage.map(page -> page.getTotalPages() - 1)
.flatMapMany(pagesCount -> Flux.range(2, pagesCount))
.map(pageNumber -> requestGenerator.apply(OrderDirection.ASCENDING, RESULTS_PER_PAGE, pageNumber));
Mono<List<P>> subsequentPagesList = requestFlux.flatMap(req ->
this.performGenericRetrieval(pageRetrievalType, logName, key, req, requestFunction, timeoutInMS)).collectList();
/*
* Word on error handling: We can't judge here what will be the consequence, if
* the first page could be retrieved properly, but retrieving some some later
* page fails. The implication would depend on the consumer (whether incomplete
* data was ok or not). So the safe answer here is to raise an error for the
* entire request. That, however, is already in place with the error handling in
* performGenericRetrieval: the stream is already in state "error" and thus will
* not emit any item.
*/
return Mono.zip(firstPage, subsequentPagesList, Mono.just(reactiveTimer)).map(tuple -> {
P first = tuple.getT1();
List<P> subsequent = tuple.getT2();
List<S> ret = new LinkedList<>();
ret.addAll((List<? extends S>) first.getResources());
for (P listResponse : subsequent) {
ret.addAll((List<? extends S>) listResponse.getResources());
}
P retObject = responseGenerator.apply(ret, subsequent.size() + 1);
tuple.getT3().stop();
return retObject;
});
}
}
|
3e0c8028424393e0e880ed7dc93b4cf3d1e39002 | 3,668 | java | Java | oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimsSetTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | 6,992 | 2015-01-02T15:38:39.000Z | 2022-03-31T05:57:56.000Z | oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimsSetTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | 7,823 | 2015-01-05T15:04:20.000Z | 2022-03-31T21:38:32.000Z | oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimsSetTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | 5,393 | 2015-01-04T14:29:19.000Z | 2022-03-31T02:16:35.000Z | 40.307692 | 108 | 0.778353 | 5,315 | /*
* Copyright 2002-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.springframework.security.oauth2.jwt;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link JwtClaimsSet}.
*
* @author Joe Grandja
*/
public class JwtClaimsSetTests {
@Test
public void buildWhenClaimsEmptyThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwtClaimsSet.builder().build())
.withMessage("claims cannot be empty");
}
@Test
public void buildWhenAllClaimsProvidedThenAllClaimsAreSet() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
// @formatter:off
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
.issuer(expectedJwtClaimsSet.getIssuer().toExternalForm())
.subject(expectedJwtClaimsSet.getSubject())
.audience(expectedJwtClaimsSet.getAudience())
.issuedAt(expectedJwtClaimsSet.getIssuedAt())
.notBefore(expectedJwtClaimsSet.getNotBefore())
.expiresAt(expectedJwtClaimsSet.getExpiresAt())
.id(expectedJwtClaimsSet.getId())
.claims((claims) -> claims.put("custom-claim-name", "custom-claim-value"))
.build();
// @formatter:on
assertThat(jwtClaimsSet.getIssuer()).isEqualTo(expectedJwtClaimsSet.getIssuer());
assertThat(jwtClaimsSet.getSubject()).isEqualTo(expectedJwtClaimsSet.getSubject());
assertThat(jwtClaimsSet.getAudience()).isEqualTo(expectedJwtClaimsSet.getAudience());
assertThat(jwtClaimsSet.getIssuedAt()).isEqualTo(expectedJwtClaimsSet.getIssuedAt());
assertThat(jwtClaimsSet.getNotBefore()).isEqualTo(expectedJwtClaimsSet.getNotBefore());
assertThat(jwtClaimsSet.getExpiresAt()).isEqualTo(expectedJwtClaimsSet.getExpiresAt());
assertThat(jwtClaimsSet.getId()).isEqualTo(expectedJwtClaimsSet.getId());
assertThat(jwtClaimsSet.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void fromWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwtClaimsSet.from(null))
.withMessage("claims cannot be null");
}
@Test
public void fromWhenClaimsProvidedThenCopied() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.from(expectedJwtClaimsSet).build();
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void claimWhenNameNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwtClaimsSet.builder().claim(null, "value")).withMessage("name cannot be empty");
}
@Test
public void claimWhenValueNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwtClaimsSet.builder().claim("name", null)).withMessage("value cannot be null");
}
}
|
3e0c807805e5fa3e760073bc6340b03bc308e40d | 18,113 | java | Java | src/Challenges.java | informramiz/hacker-rank-coding-challenges | 16ff326817b85dd07539d782994ff42a1c1f5486 | [
"Apache-2.0"
] | null | null | null | src/Challenges.java | informramiz/hacker-rank-coding-challenges | 16ff326817b85dd07539d782994ff42a1c1f5486 | [
"Apache-2.0"
] | null | null | null | src/Challenges.java | informramiz/hacker-rank-coding-challenges | 16ff326817b85dd07539d782994ff42a1c1f5486 | [
"Apache-2.0"
] | null | null | null | 28.796502 | 103 | 0.484514 | 5,316 | import java.util.*;
/**
* Created by ramiz on 11/9/17.
*/
public class Challenges {
public static void main(String args[]) {
testKnapSackSumChallenge();
// testKnapsack();
// testTextQueries();
// countNumbers();
// testStringTokens();
// testDFSConnectedRegionChallenge();
// testBinarySearch();
// testMergeSort();
// testQuickSort();
// testBubbleSort();
// testUniqueElementChallenge();
// testRunningMedian();
// testQueueOfStacksChallenge();
// testBalancedBrackets();
// testRansomNoteChallenge();
// testStringAnagrams();
// testArrayLeftRotation();
}
public static void testKnapSackSumChallenge() {
// int sum = 12;
// int[] a = {1, 6, 9};
int sum = 9;
int[] a = {3, 4, 4, 4, 8};
int possibleSum = knapSackSum(a, sum, a.length - 1);
System.out.println(possibleSum);
}
public static int knapSackSum (int[] a, int remainingSum, int n) {
if (n < 0 || remainingSum <= 0) {
return 0;
}
//check if current element (nth element) can be selected
if (a[n] > remainingSum) {
//nth element can't be selected, try n-1 element
return knapSackSum(a, remainingSum, n-1);
} else {
//current element can be selected so select it and continue
//selecting elements (including current one)
//until remaining sum is 0 or there is no element left
//to choose from
int sumWithThisElementSelected = a[n] + knapSackSum(a, remainingSum - a[n], n);
//now what if not selecting current element but the rest gives
//better results? So try that as well
int sumWithThisElementNotSelected = knapSackSum(a, remainingSum, n-1);
//return the maxium out of these two sums
return Math.max(sumWithThisElementSelected, sumWithThisElementNotSelected);
}
}
public static void testKnapsack() {
int money = 50;
int[] bundles = {19, 20};
int[] costs = {20, 24};
// int money = 4;
// int[] bundles = {10};
// int[] costs = {2};
int n = bundles.length - 1;
int count = findMaxBundles(money, costs, bundles, n);
System.out.println(count);
}
// Returns the maximum value that can be put in a knapsack of capacity W
static int findMaxBundles(int money, int costs[], int bundles[], int n) {
// Base Case
if (n < 0 || money <= 0)
return 0;
if (costs[n] > money) {
return findMaxBundles(money, costs, bundles, n - 1);
} else {
return Math.max( bundles[n] + findMaxBundles(money - costs[n], costs, bundles, n),
findMaxBundles(money, costs, bundles, n-1)
);
}
}
public static boolean isPresent(HashMap<String, Integer> map, String words[]) {
for (String w : words) {
if (!map.containsKey(w)) {
return false;
}
}
return true;
}
public static void testTextQueries() {
String[] sentences = {"jim likes marry", "kate likes tom", "tom does not like jim"};
String[] queries = {"jim tom", "likes"};
textQueries(sentences, queries);
}
public static void textQueries(String[] sentences, String[] queries) {
//for each query, print indices of sentences in which all words of that query are present
ArrayList<HashMap<String, Integer>> sList = new ArrayList<HashMap<String, Integer>>();
for (String s : sentences) {
String[] words = s.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>(words.length);
for (String w : words) {
map.put(w, 1);
}
sList.add(map);
}
for (String query : queries) {
String[] words = query.split(" ");
ArrayList<Integer> indices = new ArrayList<>();
for (int i = 0; i < sList.size(); i++) {
HashMap<String, Integer> map = sList.get(i);
if (isPresent(map, words)) {
indices.add(i);
}
}
if (indices.isEmpty()) {
System.out.println("-1");
} else {
for (int index : indices) {
System.out.print(index + " ");
}
System.out.println();
}
}
}
public static void countNumbers() {
int N = 15;
// constraint on values of L gives us the
// time Complexity as O(N^0.5)
int count = 0;
for (int L = 1; L * (L + 1) < 2 * N; L++) {
float a = (float) ((1.0 * N - (L * (L + 1)) / 2) / (L + 1));
if (a - (int) a == 0.0)
count++;
}
System.out.println(countNumbersToSum(N));
}
public static long getValue(long i) {
return i * (i + 1);
}
public static boolean shouldCount(long num, long i) {
float value = (float) ((1.0 * num - (i * (i + 1)) / 2) / (i + 1));
int intValue = (int) value;
return (value - intValue == 0.0);
}
public static long countNumbersToSum(long num) {
long totalCount = 0;
for (long i = 1; getValue(i) < 2 * num; i++) {
if (shouldCount(num, i)) {
totalCount++;
}
}
return totalCount;
}
public static void testStringTokens() {
String str = "He is a very very good boy, isn't he?";
String[] tokens = str.split("[^a-zA-z]");
for (String token : tokens) {
if (!token.isEmpty()) {
System.out.println(token);
}
}
}
/***********************
* Max connected region
*/
public static void testDFSConnectedRegionChallenge() {
int[][] matrix = {
{1, 1, 0, 0},
{0, 1, 1, 0},
{0, 0, 1, 0},
{1, 0, 0, 0}
};
int largestConnectedRegionCellsCount = Graph.getBiggestRegion(matrix);
System.out.println("Largest region cell count: " + largestConnectedRegionCellsCount);
}
/**************************
* Binary search algorithm
*/
public static void testBinarySearch() {
int[] a = {1, 2, 3, 4, 5};
int key = 3;
int keyIndex = SearchAlgorithms.binarySearch(a, key);
System.out.println("Key index: " + keyIndex);
}
/**
* Merge sort algorithm: A highly efficient algorithm
*/
public static void testMergeSort() {
// int[] a = {2, 9, 11, 7, 10, 0, 15};
// int[] a = {2, 4, 1};
int[] a = {2, 1, 3, 1, 2};
// int[] a = {1, 1, 1, 2, 2};
long swaps = SortingAlgorithms.mergeSort(a);
System.out.println("Swaps count: " + swaps);
for (int v : a) {
System.out.print(v + " ");
}
}
/*********************
* Quick sort algorithm
*/
public static void testQuickSort() {
int[] a = {2, 9, 11, 7, 10, 0, 15};
SortingAlgorithms.quickSort(a);
for (int v : a) {
System.out.print(v + " ");
}
}
/*********************
* optimized Bubble sort algorithm
*/
public static void testBubbleSort() {
int[] a = {1, 3, 1, 6};
SortingAlgorithms.bubbleSort(a);
for (int v : a) {
System.out.print(v + " ");
}
}
/********
* A list of numbers has every number in pair except one number.
* So one and only one number is unique and all other are in pairs
* Find that number
*/
public static void testUniqueElementChallenge() {
int a[] = {1, 1, 2, 2, 7, 3, 3};
int result = 0;
for (int v : a) {
result = result ^ v;
}
System.out.println(result);
}
/**************************
* Find a running median from a list of unsorted numbers comming online
*/
public static void testRunningMedian() {
Integer[] values1 = {12, 4, 5, 3, 8, 7};
Integer[] values2 = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
PriorityQueue<Integer> minQueue = new PriorityQueue<>();
PriorityQueue<Integer> maxQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
return y - x;
}
});
for (Integer v : values2) {
if (minQueue.isEmpty() && maxQueue.isEmpty()) {
maxQueue.add(v);
} else {
if (v < maxQueue.peek()) {
maxQueue.add(v);
} else {
minQueue.add(v);
}
balanceHeaps(minQueue, maxQueue);
}
double median;
if (maxQueue.size() == minQueue.size()) {
median = (minQueue.peek() + maxQueue.peek()) / 2.0;
} else if (minQueue.size() > maxQueue.size()) {
median = minQueue.peek();
} else {
median = maxQueue.peek();
}
System.out.println(String.format("Median: %.1f", median));
}
}
public static void balanceHeaps(PriorityQueue<Integer> minHeap, PriorityQueue<Integer> maxHeap) {
if (minHeap.size() - maxHeap.size() > 1) {
maxHeap.add(minHeap.poll());
} else if (maxHeap.size() - minHeap.size() > 1) {
minHeap.add(maxHeap.poll());
}
}
public static double getMedian1(PriorityQueue<Integer> queue) {
Stack<Integer> stack = new Stack<>();
int size = queue.size();
boolean isEven = queue.size() % 2 == 0;
int medianIndex = size / 2;
medianIndex = isEven ? (medianIndex - 1) : medianIndex;
//extract elements before median
for (int i = 0; i < medianIndex; i++) {
stack.push(queue.poll());
}
double median;
if (isEven) {
int m1 = queue.peek();
stack.push(queue.poll());
int m2 = queue.peek();
median = (m1 + m2) / 2.0;
} else {
median = queue.peek();
}
queue.addAll(stack);
return median;
}
public static double getMedian(PriorityQueue<Integer> queue) {
PriorityQueue<Integer> newQueue = new PriorityQueue<>();
int size = queue.size();
boolean isEven = queue.size() % 2 == 0;
int medianIndex = size / 2;
medianIndex = isEven ? (medianIndex - 1) : medianIndex;
//extract elements before median
for (int i = 0; i < medianIndex; i++) {
newQueue.add(queue.poll());
}
double median;
if (isEven) {
int m1 = queue.peek();
newQueue.add(queue.poll());
int m2 = queue.peek();
newQueue.add(queue.poll());
median = (m1 + m2) / 2.0;
} else {
median = queue.peek();
}
while (!queue.isEmpty()) {
newQueue.add(queue.poll());
}
queue.addAll(newQueue);
return median;
}
public static Integer getElement(Integer[] array, int n) {
int index = 0;
for (int i = 0; i < n; i++) {
index = index * 2 + 1;
}
return array[index];
}
/***********************************************
*
* Queue of 2 Stacks: Implement a queue with 2 stacks
*/
public static void testQueueOfStacksChallenge() {
//should print following output:
//14
//14
Queue<Integer> queue = new Queue<>();
queue.enqueue(42);
queue.dequeue();
queue.enqueue(14);
System.out.println(queue.peek());
queue.enqueue(28);
System.out.println(queue.peek());
queue.enqueue(60);
queue.enqueue(78);
queue.dequeue();
queue.dequeue();
}
/***********************************************
*
* Balanced Brackets problem: Identify if sequence of brackets
* is balanced or not
*/
public static void testBalancedBrackets() {
String[] strings = {"{[()]}", "{[(])}", "{{[[(())]]}}"};
for (String string : strings) {
System.out.println((isBalanced(string)) ? "YES" : "NO");
}
}
public static boolean isOpeningBracket(char ch) {
return (ch == '(' || ch == '{' || ch == '[');
}
public static boolean isClosingBracket(char ch) {
return (ch == ')' || ch == '}' || ch == ']');
}
public static boolean areSameBrackets(char opening, char closing) {
if (opening == '(' && closing == ')') {
return true;
} else if (opening == '{' && closing == '}') {
return true;
} else if (opening == '[' && closing == ']') {
return true;
}
return false;
}
public static boolean isBalanced(String expression) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < expression.length(); ++i) {
char ch = expression.charAt(i);
if (isOpeningBracket(ch)) {
stack.push(ch);
continue;
}
if (isClosingBracket(ch)) {
if (stack.empty() || !areSameBrackets(stack.pop(), ch)) {
return false;
}
}
}
return stack.isEmpty();
}
/* ****************************************************************
* Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.
*
* A Node is defined as:
* class Node {
* int data;
* Node next;
* }
********************************************************************/
class Node {
int data;
Node next;
}
boolean hasCycle(Node head) {
if (head == null) {
return false;
}
Map<Node, Integer> map = new HashMap<Node, Integer>();
map.put(head, 1);
while (head.next != null) {
head = head.next;
if (map.containsKey(head)) {
return true;
}
map.put(head, 1);
}
return false;
}
/**************************
* Ransom Note Challenge solution: Identify if note string can be made of
* words from magazine string
*/
public static void testRansomNoteChallenge() {
String magazine = "give me one grand today night";
String note = "give one grand today";
//should print true
System.out.println(solveRansomNote(magazine, note));
}
public static boolean solveRansomNote(String magazine, String note) {
HashMap<String, Integer> magazineMap = new HashMap<>();
HashMap<String, Integer> noteMap = new HashMap<>();
String magazineWords[] = magazine.split(" ");
String[] noteWords = note.split(" ");
initializeMap(magazineMap, magazineWords);
initializeMap(noteMap, noteWords);
Set set = noteMap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
String key = (String) entry.getKey();
Integer value = (Integer) entry.getValue();
if (!magazineMap.containsKey(key) || magazineMap.get(key) < value) {
return false;
}
}
return true;
}
public static void initializeMap(Map<String, Integer> map, String[] words) {
for (int i = 0; i < words.length; ++i) {
String word = words[i];
int prevCount = 0;
if (map.containsKey(word)) {
prevCount = map.get(word);
}
map.put(word, ++prevCount);
}
}
/* * *************************************
* Identify characters needed to be deleted to make two string Anagrams
*/
public static void testStringAnagrams() {
String first = "cde";
String second = "abc";
//shout be 4
int number = numberNeededForMakingStringAnagram(first, second);
System.out.println(number);
}
public static int numberNeededForMakingStringAnagram(String first, String second) {
int firstCount[] = new int[26];
int secondCount[] = new int[26];
for (int i = 0; i < first.length(); ++i) {
int index = first.charAt(i) - 'a';
firstCount[index]++;
}
for (int i = 0; i < second.length(); ++i) {
int index = second.charAt(i) - 'a';
secondCount[index]++;
}
int diff = 0;
for (int i = 0; i < 26; ++i) {
diff += Math.abs(firstCount[i] - secondCount[i]);
}
return diff;
}
/******************************************
* Shift rotate array left `k` times
*/
private static void testArrayLeftRotation() {
int a[] = {1, 2, 3, 4, 5};
int k = 4;
int n = 5;
int[] output = new int[n];
output = arrayLeftRotation1(a, n, 9);
//shout print = 5 1 2 3 4
for (int i = 0; i < n; i++)
System.out.print(output[i] + " ");
System.out.println();
}
public static int[] arrayLeftRotation1(int[] a, int n, int k) {
int output[] = new int[n];
int currentIndex = k % n;
for (int i = 0; i < a.length; ++i) {
output[i] = a[currentIndex];
currentIndex = (currentIndex + 1) % n;
}
return output;
}
}
|
3e0c80ca808ac2f44dcc0bf71ea47a13ecbf0576 | 4,569 | java | Java | web/src/main/java/de/cotto/lndmanagej/controller/ChannelController.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | 6 | 2022-03-09T23:32:29.000Z | 2022-03-21T23:04:29.000Z | web/src/main/java/de/cotto/lndmanagej/controller/ChannelController.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | 12 | 2022-03-09T22:47:51.000Z | 2022-03-27T16:34:37.000Z | web/src/main/java/de/cotto/lndmanagej/controller/ChannelController.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | null | null | null | 42.305556 | 112 | 0.764062 | 5,317 | package de.cotto.lndmanagej.controller;
import com.codahale.metrics.annotation.Timed;
import de.cotto.lndmanagej.controller.dto.BalanceInformationDto;
import de.cotto.lndmanagej.controller.dto.ChannelDetailsDto;
import de.cotto.lndmanagej.controller.dto.ChannelDto;
import de.cotto.lndmanagej.controller.dto.ClosedChannelDetailsDto;
import de.cotto.lndmanagej.controller.dto.FeeReportDto;
import de.cotto.lndmanagej.controller.dto.ObjectMapperConfiguration;
import de.cotto.lndmanagej.controller.dto.PoliciesDto;
import de.cotto.lndmanagej.model.BalanceInformation;
import de.cotto.lndmanagej.model.ChannelId;
import de.cotto.lndmanagej.model.ClosedChannel;
import de.cotto.lndmanagej.model.LocalChannel;
import de.cotto.lndmanagej.model.OpenCloseStatus;
import de.cotto.lndmanagej.model.PoliciesForLocalChannel;
import de.cotto.lndmanagej.service.BalanceService;
import de.cotto.lndmanagej.service.ChannelDetailsService;
import de.cotto.lndmanagej.service.ChannelService;
import de.cotto.lndmanagej.service.FeeService;
import de.cotto.lndmanagej.service.PolicyService;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Import(ObjectMapperConfiguration.class)
@SuppressWarnings("PMD.ExcessiveImports")
@RequestMapping("/api/channel/{channelId}")
public class ChannelController {
private final ChannelService channelService;
private final BalanceService balanceService;
private final PolicyService policyService;
private final FeeService feeService;
private final ChannelDetailsService channelDetailsService;
public ChannelController(
ChannelService channelService,
BalanceService balanceService,
PolicyService policyService,
FeeService feeService,
ChannelDetailsService channelDetailsService
) {
this.channelService = channelService;
this.balanceService = balanceService;
this.policyService = policyService;
this.feeService = feeService;
this.channelDetailsService = channelDetailsService;
}
@Timed
@GetMapping("/")
public ChannelDto getBasicInformation(@PathVariable ChannelId channelId) throws NotFoundException {
LocalChannel localChannel = channelService.getLocalChannel(channelId).orElse(null);
if (localChannel == null) {
throw new NotFoundException();
}
return new ChannelDto(localChannel);
}
@Timed
@GetMapping("/details")
public ChannelDetailsDto getDetails(@PathVariable ChannelId channelId) throws NotFoundException {
LocalChannel localChannel = channelService.getLocalChannel(channelId).orElse(null);
if (localChannel == null) {
throw new NotFoundException();
}
return ChannelDetailsDto.createFromModel(channelDetailsService.getDetails(localChannel));
}
@Timed
@GetMapping("/balance")
public BalanceInformationDto getBalance(@PathVariable ChannelId channelId) {
BalanceInformation balanceInformation = balanceService.getBalanceInformation(channelId)
.orElse(BalanceInformation.EMPTY);
return BalanceInformationDto.createFromModel(balanceInformation);
}
@Timed
@GetMapping("/policies")
public PoliciesDto getPolicies(@PathVariable ChannelId channelId) {
LocalChannel localChannel = channelService.getLocalChannel(channelId).orElse(null);
if (localChannel == null || localChannel.getStatus().openCloseStatus() != OpenCloseStatus.OPEN) {
return PoliciesDto.createFromModel(PoliciesForLocalChannel.UNKNOWN);
}
return PoliciesDto.createFromModel(policyService.getPolicies(localChannel));
}
@Timed
@GetMapping("/close-details")
public ClosedChannelDetailsDto getCloseDetails(@PathVariable ChannelId channelId) throws NotFoundException {
ClosedChannel closedChannel = channelService.getClosedChannel(channelId).orElse(null);
if (closedChannel == null) {
throw new NotFoundException();
}
return ClosedChannelDetailsDto.createFromModel(closedChannel);
}
@Timed
@GetMapping("/fee-report")
public FeeReportDto getFeeReport(@PathVariable ChannelId channelId) {
return FeeReportDto.createFromModel(feeService.getFeeReportForChannel(channelId));
}
}
|
3e0c81d9441eea9dbf7b9af2a8d0750e43f9d9ca | 51,908 | java | Java | server/src/test/java/org/apache/iotdb/db/engine/compaction/inner/InnerSeqCompactionTest.java | SzyWilliam/iotdb | 13c732b43a307fe2ecbf6cd990cc537f8c73eceb | [
"Apache-2.0"
] | 945 | 2018-12-13T00:39:04.000Z | 2020-10-01T04:17:02.000Z | server/src/test/java/org/apache/iotdb/db/engine/compaction/inner/InnerSeqCompactionTest.java | SzyWilliam/iotdb | 13c732b43a307fe2ecbf6cd990cc537f8c73eceb | [
"Apache-2.0"
] | 923 | 2019-01-18T01:12:04.000Z | 2020-10-01T02:17:11.000Z | server/src/test/java/org/apache/iotdb/db/engine/compaction/inner/InnerSeqCompactionTest.java | leety1228/iotdb | ffdcc0a5381596a74bb807a8f89fe6de3749125a | [
"Apache-2.0"
] | 375 | 2018-12-23T06:40:33.000Z | 2020-10-01T02:49:20.000Z | 54.070833 | 100 | 0.554963 | 5,318 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.engine.compaction.inner;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.exception.MetadataException;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.engine.cache.ChunkCache;
import org.apache.iotdb.db.engine.cache.TimeSeriesMetadataCache;
import org.apache.iotdb.db.engine.compaction.CompactionUtils;
import org.apache.iotdb.db.engine.compaction.performer.impl.ReadChunkCompactionPerformer;
import org.apache.iotdb.db.engine.compaction.utils.CompactionCheckerUtils;
import org.apache.iotdb.db.engine.compaction.utils.CompactionClearUtils;
import org.apache.iotdb.db.engine.compaction.utils.CompactionConfigRestorer;
import org.apache.iotdb.db.engine.compaction.utils.CompactionFileGeneratorUtils;
import org.apache.iotdb.db.engine.compaction.utils.CompactionTimeseriesType;
import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
import org.apache.iotdb.db.exception.StorageEngineException;
import org.apache.iotdb.db.service.IoTDB;
import org.apache.iotdb.db.utils.EnvironmentUtils;
import org.apache.iotdb.tsfile.common.conf.TSFileDescriptor;
import org.apache.iotdb.tsfile.exception.write.WriteProcessException;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.apache.iotdb.tsfile.read.TimeValuePair;
import org.apache.iotdb.tsfile.utils.Pair;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.iotdb.db.engine.compaction.utils.CompactionCheckerUtils.putChunk;
import static org.apache.iotdb.db.engine.compaction.utils.CompactionCheckerUtils.putOnePageChunk;
import static org.apache.iotdb.db.engine.compaction.utils.CompactionCheckerUtils.putOnePageChunks;
public class InnerSeqCompactionTest {
static final String COMPACTION_TEST_SG = "root.compactionTest";
static final String[] fullPaths =
new String[] {
COMPACTION_TEST_SG + ".device0.sensor0",
COMPACTION_TEST_SG + ".device1.sensor0",
COMPACTION_TEST_SG + ".device2.sensor0",
COMPACTION_TEST_SG + ".device3.sensor0",
COMPACTION_TEST_SG + ".device4.sensor0",
COMPACTION_TEST_SG + ".device5.sensor0",
COMPACTION_TEST_SG + ".device6.sensor0",
COMPACTION_TEST_SG + ".device7.sensor0",
COMPACTION_TEST_SG + ".device8.sensor0",
};
static final int[] toMergeFileNums = new int[] {2, 3};
static final CompactionTimeseriesType[] compactionTimeseriesTypes =
new CompactionTimeseriesType[] {
CompactionTimeseriesType.ALL_SAME,
CompactionTimeseriesType.PART_SAME,
CompactionTimeseriesType.NO_SAME
};
static final boolean[] compactionBeforeHasMods = new boolean[] {true, false};
static final boolean[] compactionHasMods = new boolean[] {true, false};
private static int prevMaxDegreeOfIndexNode;
@Before
public void setUp() throws MetadataException {
prevMaxDegreeOfIndexNode = TSFileDescriptor.getInstance().getConfig().getMaxDegreeOfIndexNode();
TSFileDescriptor.getInstance().getConfig().setMaxDegreeOfIndexNode(2);
IoTDB.configManager.init();
IoTDB.schemaProcessor.setStorageGroup(new PartialPath(COMPACTION_TEST_SG));
for (String fullPath : fullPaths) {
PartialPath path = new PartialPath(fullPath);
IoTDB.schemaProcessor.createTimeseries(
path,
TSDataType.INT64,
TSEncoding.valueOf(TSFileDescriptor.getInstance().getConfig().getValueEncoder()),
TSFileDescriptor.getInstance().getConfig().getCompressor(),
Collections.emptyMap());
}
}
@After
public void tearDown() throws IOException, StorageEngineException {
new CompactionConfigRestorer().restoreCompactionConfig();
CompactionClearUtils.clearAllCompactionFiles();
ChunkCache.getInstance().clear();
TimeSeriesMetadataCache.getInstance().clear();
IoTDB.configManager.clear();
EnvironmentUtils.cleanAllDir();
TSFileDescriptor.getInstance().getConfig().setMaxDegreeOfIndexNode(prevMaxDegreeOfIndexNode);
}
@Test
public void testDeserializePage() throws MetadataException, IOException, WriteProcessException {
long chunkSizeLowerBoundInCompaction =
IoTDBDescriptor.getInstance().getConfig().getChunkSizeLowerBoundInCompaction();
IoTDBDescriptor.getInstance().getConfig().setChunkSizeLowerBoundInCompaction(10240);
long chunkPointNumLowerBoundInCompaction =
IoTDBDescriptor.getInstance().getConfig().getChunkPointNumLowerBoundInCompaction();
IoTDBDescriptor.getInstance().getConfig().setChunkPointNumLowerBoundInCompaction(1000);
try {
for (int toMergeFileNum : toMergeFileNums) {
for (CompactionTimeseriesType compactionTimeseriesType : compactionTimeseriesTypes) {
for (boolean compactionBeforeHasMod : compactionBeforeHasMods) {
for (boolean compactionHasMod : compactionHasMods) {
List<TsFileResource> sourceResources = new ArrayList<>();
// generate source file
for (int i = 0; i < toMergeFileNum; i++) {
Set<String> fullPath = new HashSet<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
} else {
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
}
} else {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
fullPath.add(fullPaths[5]);
} else {
fullPath.add(fullPaths[6]);
fullPath.add(fullPaths[7]);
fullPath.add(fullPaths[8]);
}
}
List<List<Long>> chunkPagePointsNum = new ArrayList<>();
List<Long> pagePointsNum = new ArrayList<>();
pagePointsNum.add(100L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(200L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(300L);
chunkPagePointsNum.add(pagePointsNum);
TsFileResource tsFileResource =
CompactionFileGeneratorUtils.generateTsFileResource(true, i + 1);
CompactionFileGeneratorUtils.writeTsFile(
fullPath, chunkPagePointsNum, i * 600L, tsFileResource);
sourceResources.add(tsFileResource);
// has mods files before compaction
if (compactionBeforeHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
toDeleteTimeseriesAndTime.put(
fullPaths[i], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[0], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[3], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[4], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
} else {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[2], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[5], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[8], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
}
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, tsFileResource, false);
}
}
TsFileResource targetTsFileResource =
CompactionFileGeneratorUtils.getTargetTsFileResourceFromSourceResource(
sourceResources.get(0));
Map<String, List<TimeValuePair>> sourceData =
CompactionCheckerUtils.readFiles(sourceResources);
if (compactionHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
toDeleteTimeseriesAndTime.put(fullPaths[1], new Pair<>(250L, 300L));
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, sourceResources.get(0), true);
// remove data in source data list
List<TimeValuePair> timeValuePairs = sourceData.get(fullPaths[1]);
timeValuePairs.removeIf(
timeValuePair ->
timeValuePair.getTimestamp() >= 250L
&& timeValuePair.getTimestamp() <= 300L);
}
new ReadChunkCompactionPerformer(sourceResources, targetTsFileResource).perform();
CompactionUtils.moveTargetFile(
Collections.singletonList(targetTsFileResource), true, COMPACTION_TEST_SG);
CompactionUtils.combineModsInInnerCompaction(sourceResources, targetTsFileResource);
List<TsFileResource> targetTsFileResources = new ArrayList<>();
targetTsFileResources.add(targetTsFileResource);
// check data
CompactionCheckerUtils.checkDataAndResource(sourceData, targetTsFileResources);
Map<String, List<List<Long>>> chunkPagePointsNumMerged = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1149L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1149L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1200L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1200L);
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1749L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1749L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1749L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1800L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1800L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1800L);
}
}
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 549L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 549L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 600L);
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 549L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1800L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 1149L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 549L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1800L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 1200L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 600L);
}
}
} else {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 549L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 549L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 600L);
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 549L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 549L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[6], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[7], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[8], 549L);
} else {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[6], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[7], 600L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[8], 600L);
}
}
}
CompactionCheckerUtils.checkChunkAndPage(
chunkPagePointsNumMerged, targetTsFileResource);
CompactionClearUtils.clearAllCompactionFiles();
}
}
}
}
} catch (InterruptedException | StorageEngineException e) {
e.printStackTrace();
} finally {
IoTDBDescriptor.getInstance()
.getConfig()
.setChunkPointNumLowerBoundInCompaction(chunkPointNumLowerBoundInCompaction);
IoTDBDescriptor.getInstance()
.getConfig()
.setChunkSizeLowerBoundInCompaction(chunkSizeLowerBoundInCompaction);
}
}
@Test
public void testAppendPage()
throws IOException, MetadataException, InterruptedException, StorageEngineException,
WriteProcessException {
for (int toMergeFileNum : toMergeFileNums) {
for (CompactionTimeseriesType compactionTimeseriesType : compactionTimeseriesTypes) {
for (boolean compactionBeforeHasMod : compactionBeforeHasMods) {
for (boolean compactionHasMod : compactionHasMods) {
List<TsFileResource> toMergeResources = new ArrayList<>();
for (int i = 0; i < toMergeFileNum; i++) {
Set<String> fullPath = new HashSet<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
} else {
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
}
} else {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
fullPath.add(fullPaths[5]);
} else {
fullPath.add(fullPaths[6]);
fullPath.add(fullPaths[7]);
fullPath.add(fullPaths[8]);
}
}
List<List<Long>> chunkPagePointsNum = new ArrayList<>();
List<Long> pagePointsNum = new ArrayList<>();
pagePointsNum.add(100L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(200L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(300L);
chunkPagePointsNum.add(pagePointsNum);
TsFileResource tsFileResource =
CompactionFileGeneratorUtils.generateTsFileResource(true, i + 1);
CompactionFileGeneratorUtils.writeTsFile(
fullPath, chunkPagePointsNum, i * 600L, tsFileResource);
toMergeResources.add(tsFileResource);
// has mods files before compaction
if (compactionBeforeHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
toDeleteTimeseriesAndTime.put(
fullPaths[i], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[0], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[3], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[4], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
} else {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[2], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[5], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[8], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
}
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, tsFileResource, false);
}
}
TsFileResource targetTsFileResource =
CompactionFileGeneratorUtils.getTargetTsFileResourceFromSourceResource(
toMergeResources.get(0));
Map<String, List<TimeValuePair>> sourceData =
CompactionCheckerUtils.readFiles(toMergeResources);
if (compactionHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
toDeleteTimeseriesAndTime.put(fullPaths[1], new Pair<>(250L, 300L));
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, toMergeResources.get(0), true);
// remove data in source data list
List<TimeValuePair> timeValuePairs = sourceData.get(fullPaths[1]);
timeValuePairs.removeIf(
timeValuePair ->
timeValuePair.getTimestamp() >= 250L && timeValuePair.getTimestamp() <= 300L);
}
new ReadChunkCompactionPerformer(toMergeResources, targetTsFileResource).perform();
CompactionUtils.moveTargetFile(
Collections.singletonList(targetTsFileResource), true, COMPACTION_TEST_SG);
CompactionUtils.combineModsInInnerCompaction(toMergeResources, targetTsFileResource);
List<TsFileResource> targetTsFileResources = new ArrayList<>();
targetTsFileResources.add(targetTsFileResource);
CompactionCheckerUtils.checkDataAndResource(sourceData, targetTsFileResources);
Map<String, List<List<Long>>> chunkPagePointsNumMerged = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1149L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1149L);
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
} else {
putChunk(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 1749L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[1], 1749L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 1749L);
} else {
putChunk(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
}
}
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 549L);
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 549L);
} else {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[0], 549L);
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[3], 1149L);
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[4], 549L);
} else {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putChunk(
chunkPagePointsNumMerged,
fullPaths[3],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
}
}
} else {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 549L);
putChunk(chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 549L);
} else {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[2], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[5], new long[] {100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[2], 549L);
putChunk(chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[5], 549L);
putChunk(chunkPagePointsNumMerged, fullPaths[6], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[7], new long[] {100L, 200L, 300L});
putOnePageChunk(chunkPagePointsNumMerged, fullPaths[8], 549L);
} else {
putChunk(chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[2], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[5], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[6], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[7], new long[] {100L, 200L, 300L});
putChunk(chunkPagePointsNumMerged, fullPaths[8], new long[] {100L, 200L, 300L});
}
}
}
CompactionCheckerUtils.checkChunkAndPage(
chunkPagePointsNumMerged, targetTsFileResource);
CompactionClearUtils.clearAllCompactionFiles();
}
}
}
}
}
@Test
public void testAppendChunk()
throws IOException, IllegalPathException, MetadataException, StorageEngineException,
WriteProcessException {
long prevChunkPointNumLowerBoundInCompaction =
IoTDBDescriptor.getInstance().getConfig().getChunkPointNumLowerBoundInCompaction();
IoTDBDescriptor.getInstance().getConfig().setChunkPointNumLowerBoundInCompaction(1);
long prevChunkSizeLowerBoundInCompaction =
IoTDBDescriptor.getInstance().getConfig().getChunkSizeLowerBoundInCompaction();
IoTDBDescriptor.getInstance().getConfig().setChunkSizeLowerBoundInCompaction(1);
long prevTargetChunkPointNum =
IoTDBDescriptor.getInstance().getConfig().getTargetChunkPointNum();
long prevTargetChunkSize = IoTDBDescriptor.getInstance().getConfig().getTargetChunkSize();
IoTDBDescriptor.getInstance().getConfig().setTargetChunkSize(1);
IoTDBDescriptor.getInstance().getConfig().setTargetChunkPointNum(1);
try {
for (int toMergeFileNum : toMergeFileNums) {
for (CompactionTimeseriesType compactionTimeseriesType : compactionTimeseriesTypes) {
for (boolean compactionBeforeHasMod : compactionBeforeHasMods) {
for (boolean compactionHasMod : compactionHasMods) {
List<TsFileResource> toMergeResources = new ArrayList<>();
for (int i = 0; i < toMergeFileNum; i++) {
Set<String> fullPath = new HashSet<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
} else {
fullPath.add(fullPaths[2]);
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
}
} else {
if (i == 0) {
fullPath.add(fullPaths[0]);
fullPath.add(fullPaths[1]);
fullPath.add(fullPaths[2]);
} else if (i == 1) {
fullPath.add(fullPaths[3]);
fullPath.add(fullPaths[4]);
fullPath.add(fullPaths[5]);
} else {
fullPath.add(fullPaths[6]);
fullPath.add(fullPaths[7]);
fullPath.add(fullPaths[8]);
}
}
List<List<Long>> chunkPagePointsNum = new ArrayList<>();
List<Long> pagePointsNum = new ArrayList<>();
pagePointsNum.add(100L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(200L);
chunkPagePointsNum.add(pagePointsNum);
pagePointsNum = new ArrayList<>();
pagePointsNum.add(300L);
chunkPagePointsNum.add(pagePointsNum);
TsFileResource tsFileResource =
CompactionFileGeneratorUtils.generateTsFileResource(true, i + 1);
CompactionFileGeneratorUtils.writeTsFile(
fullPath, chunkPagePointsNum, i * 600L, tsFileResource);
toMergeResources.add(tsFileResource);
// has mods files before compaction
if (compactionBeforeHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
toDeleteTimeseriesAndTime.put(
fullPaths[i], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[0], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[3], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[4], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
} else {
if (i == 0) {
toDeleteTimeseriesAndTime.put(fullPaths[2], new Pair<>(250L, 300L));
} else if (i == 1) {
toDeleteTimeseriesAndTime.put(
fullPaths[5], new Pair<>(i * 600L + 250L, i * 600L + 300L));
} else {
toDeleteTimeseriesAndTime.put(
fullPaths[8], new Pair<>(i * 600L + 250L, i * 600L + 300L));
}
}
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, tsFileResource, false);
}
}
TsFileResource targetTsFileResource =
CompactionFileGeneratorUtils.getTargetTsFileResourceFromSourceResource(
toMergeResources.get(0));
Map<String, List<TimeValuePair>> sourceData =
CompactionCheckerUtils.readFiles(toMergeResources);
if (compactionHasMod) {
Map<String, Pair<Long, Long>> toDeleteTimeseriesAndTime = new HashMap<>();
toDeleteTimeseriesAndTime.put(fullPaths[1], new Pair<>(250L, 300L));
CompactionFileGeneratorUtils.generateMods(
toDeleteTimeseriesAndTime, toMergeResources.get(0), true);
// remove data in source data list
List<TimeValuePair> timeValuePairs = sourceData.get(fullPaths[1]);
timeValuePairs.removeIf(
timeValuePair ->
timeValuePair.getTimestamp() >= 250L
&& timeValuePair.getTimestamp() <= 300L);
}
new ReadChunkCompactionPerformer(toMergeResources, targetTsFileResource).perform();
CompactionUtils.moveTargetFile(
Collections.singletonList(targetTsFileResource), true, COMPACTION_TEST_SG);
CompactionUtils.combineModsInInnerCompaction(toMergeResources, targetTsFileResource);
List<TsFileResource> targetTsFileResources = new ArrayList<>();
targetTsFileResources.add(targetTsFileResource);
CompactionCheckerUtils.checkDataAndResource(sourceData, targetTsFileResources);
Map<String, List<List<Long>>> chunkPagePointsNumMerged = new HashMap<>();
if (compactionTimeseriesType == CompactionTimeseriesType.ALL_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100, 150, 299, 100, 200, 300});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100, 200, 300, 100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
} else {
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100, 150, 299, 100, 200, 300, 100, 200, 300});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100, 200, 300, 100, 150, 299, 100, 200, 300});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100, 200, 300, 100, 200, 300, 100, 150, 299});
} else {
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[0],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
}
}
} else if (compactionTimeseriesType == CompactionTimeseriesType.PART_SAME) {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100, 150, 299});
} else {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[3],
new long[] {100, 150, 299, 100, 200, 300});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100, 150, 299});
} else {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[1],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[2],
new long[] {100L, 200L, 300L, 100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged,
fullPaths[3],
new long[] {100L, 200L, 300L, 100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
}
}
} else {
if (toMergeFileNum == 2) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[2], new long[] {100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[5], new long[] {100, 150, 299});
} else {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[2], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[5], new long[] {100L, 200L, 300L});
}
} else if (toMergeFileNum == 3) {
if (compactionBeforeHasMod) {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[2], new long[] {100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[5], new long[] {100, 150, 299});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[6], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[7], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[8], new long[] {100, 150, 299});
} else {
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[0], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[1], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[2], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[3], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[4], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[5], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[6], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[7], new long[] {100L, 200L, 300L});
putOnePageChunks(
chunkPagePointsNumMerged, fullPaths[8], new long[] {100L, 200L, 300L});
}
}
}
CompactionCheckerUtils.checkChunkAndPage(
chunkPagePointsNumMerged, targetTsFileResource);
CompactionClearUtils.clearAllCompactionFiles();
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
IoTDBDescriptor.getInstance()
.getConfig()
.setChunkSizeLowerBoundInCompaction(prevChunkSizeLowerBoundInCompaction);
IoTDBDescriptor.getInstance()
.getConfig()
.setChunkPointNumLowerBoundInCompaction(prevChunkPointNumLowerBoundInCompaction);
IoTDBDescriptor.getInstance().getConfig().setTargetChunkPointNum(prevTargetChunkPointNum);
IoTDBDescriptor.getInstance().getConfig().setTargetChunkSize(prevTargetChunkSize);
}
}
}
|
3e0c83803eb647e5e89349e4730a0c9f3895ed06 | 286 | java | Java | role_game/src/main/java/ru/job4j/observers/HeroCreatedObserver.java | zCRUSADERz/AlexanderYakovlev | 9b098fb876b5a60d5e5fdc8274b3b47e994d88ba | [
"Apache-2.0"
] | 2 | 2019-03-03T16:26:31.000Z | 2019-03-13T08:35:34.000Z | role_game/src/main/java/ru/job4j/observers/HeroCreatedObserver.java | zCRUSADERz/AlexanderYakovlev | 9b098fb876b5a60d5e5fdc8274b3b47e994d88ba | [
"Apache-2.0"
] | 1 | 2022-02-16T00:55:29.000Z | 2022-02-16T00:55:29.000Z | role_game/src/main/java/ru/job4j/observers/HeroCreatedObserver.java | zCRUSADERz/AlexanderYakovlev | 9b098fb876b5a60d5e5fdc8274b3b47e994d88ba | [
"Apache-2.0"
] | null | null | null | 20.428571 | 61 | 0.734266 | 5,319 | package ru.job4j.observers;
import ru.job4j.heroes.Hero;
import java.util.function.BiConsumer;
public interface HeroCreatedObserver {
BiConsumer<Hero, HeroCreatedObserver> CREATED
= (hero, observer) -> observer.heroCreated(hero);
void heroCreated(Hero hero);
}
|
3e0c84ab8dddfe533dbfdfd86ad44ea8382952c2 | 842 | java | Java | api/src/test/java/chezz/users/UserTokenGeneratorTests.java | niamster/chezz | 8daa5d6fb19e7ae0576fccab230bb93a680adea1 | [
"MIT"
] | null | null | null | api/src/test/java/chezz/users/UserTokenGeneratorTests.java | niamster/chezz | 8daa5d6fb19e7ae0576fccab230bb93a680adea1 | [
"MIT"
] | 6 | 2021-03-10T00:42:16.000Z | 2022-02-26T20:53:15.000Z | api/src/test/java/chezz/users/UserTokenGeneratorTests.java | niamster/chezz | 8daa5d6fb19e7ae0576fccab230bb93a680adea1 | [
"MIT"
] | null | null | null | 32.384615 | 76 | 0.76247 | 5,320 | package chezz.users;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class UserTokenGeneratorTests {
@Test
public void testUnknownUserTokenGenerator() {
assertTrue(new UserTokenGeneratorSelector().getByName("???").isEmpty());
}
@DisplayName("User Token Generator tests")
@ParameterizedTest(name = "run #{index} with [{arguments}]")
@ValueSource(strings = {"simple"})
public void testKeyWhitener(String name) {
var gen = new UserTokenGeneratorSelector().getByName(name).get();
assertNotEquals(gen.generateToken("a"), gen.generateToken("b"));
}
}
|
3e0c85648990077026532367d0e3a9010dc60939 | 1,748 | java | Java | src/main/java/io/slingr/endpoints/ftp/components/CustomSftpComponent.java | NicoGitHub98/ftp-endpoint | ba65407d777009d3ac374af66fc8b50cdaabedb0 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/slingr/endpoints/ftp/components/CustomSftpComponent.java | NicoGitHub98/ftp-endpoint | ba65407d777009d3ac374af66fc8b50cdaabedb0 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/slingr/endpoints/ftp/components/CustomSftpComponent.java | NicoGitHub98/ftp-endpoint | ba65407d777009d3ac374af66fc8b50cdaabedb0 | [
"Apache-2.0"
] | 1 | 2021-11-12T18:38:19.000Z | 2021-11-12T18:38:19.000Z | 36.416667 | 153 | 0.720252 | 5,321 | package io.slingr.endpoints.ftp.components;
import com.jcraft.jsch.ChannelSftp;
import org.apache.camel.CamelContext;
import org.apache.camel.component.file.GenericFileEndpoint;
import org.apache.camel.component.file.remote.FtpUtils;
import org.apache.camel.component.file.remote.SftpComponent;
import org.apache.camel.component.file.remote.SftpConfiguration;
import java.net.URI;
import java.util.Map;
/**
* Same functionality of Secure FTP Component but rewrite the /root/.ssh/known_hosts file
*
* Created by lefunes on 15/05/17.
*/
public class CustomSftpComponent extends SftpComponent {
public CustomSftpComponent() {
setEndpointClass(CustomSftpEndpoint.class);
}
public CustomSftpComponent(CamelContext context) {
super(context);
setEndpointClass(CustomSftpEndpoint.class);
}
@Override
protected GenericFileEndpoint<ChannelSftp.LsEntry> buildFileEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// get the base uri part before the options as they can be non URI valid such as the expression using $ chars
// and the URI constructor will regard $ as an illegal character and we dont want to enforce end users to
// to escape the $ for the expression (file language)
String baseUri = uri;
if (uri.indexOf("?") != -1) {
baseUri = uri.substring(0, uri.indexOf("?"));
}
// lets make sure we create a new configuration as each endpoint can
// customize its own version
SftpConfiguration config = new SftpConfiguration(new URI(baseUri));
FtpUtils.ensureRelativeFtpDirectory(this, config);
return new CustomSftpEndpoint(uri, this, config);
}
}
|
3e0c8586f47c7cbf54291acf21c8de916bc02212 | 40,141 | java | Java | src/main/java/org/broadinstitute/hellbender/tools/genomicsdb/GenomicsDBImport.java | falcon-computing/gatk4 | eff34c69e0ee1557396c5ad7f94128a08c0ab2f3 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/org/broadinstitute/hellbender/tools/genomicsdb/GenomicsDBImport.java | falcon-computing/gatk4 | eff34c69e0ee1557396c5ad7f94128a08c0ab2f3 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/org/broadinstitute/hellbender/tools/genomicsdb/GenomicsDBImport.java | falcon-computing/gatk4 | eff34c69e0ee1557396c5ad7f94128a08c0ab2f3 | [
"BSD-3-Clause"
] | null | null | null | 50.811392 | 324 | 0.683516 | 5,322 | package org.broadinstitute.hellbender.tools.genomicsdb;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intel.genomicsdb.importer.GenomicsDBImporter;
import com.intel.genomicsdb.importer.model.ChromosomeInterval;
import com.intel.genomicsdb.model.Coordinates;
import com.intel.genomicsdb.model.GenomicsDBCallsetsMapProto;
import com.intel.genomicsdb.model.GenomicsDBImportConfiguration;
import com.intel.genomicsdb.model.ImportConfig;
import com.intel.genomicsdb.model.BatchCompletionCallbackFunctionArgument;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.util.Locatable;
import htsjdk.tribble.AbstractFeatureReader;
import htsjdk.tribble.CloseableTribbleIterator;
import htsjdk.tribble.FeatureReader;
import htsjdk.tribble.TribbleException;
import htsjdk.tribble.readers.LineIterator;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFCodec;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import htsjdk.variant.vcf.VCFUtils;
import org.broadinstitute.barclay.argparser.Advanced;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.CommandLineException;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.ShortVariantDiscoveryProgramGroup;
import org.broadinstitute.hellbender.engine.GATKTool;
import org.broadinstitute.hellbender.exceptions.GATKException;
import org.broadinstitute.hellbender.exceptions.UserException;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.io.IOUtils;
import org.broadinstitute.hellbender.utils.nio.SeekableByteChannelPrefetcher;
import java.io.File;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Import single-sample GVCFs into GenomicsDB before joint genotyping.
*
* <p>The GATK4 Best Practice Workflow for SNP and Indel calling uses GenomicsDBImport to merge GVCFs from multiple samples.
* GenomicsDBImport offers the same functionality as CombineGVCFs and comes from the <i>Intel-Broad Center for Genomics</i>.
* The datastore transposes sample-centric variant information across genomic loci to make data more accessible to tools.
* </p>
*
* <p>To query the contents of the GenomicsDB datastore, use
* <a href='https://software.broadinstitute.org/gatk/documentation/tooldocs/current/org_broadinstitute_gatk_tools_walkers_variantutils_SelectVariants.php'>SelectVariants</a>.
* See <a href='https://software.broadinstitute.org/gatk/documentation/article?id=10061'>Tutorial#10061</a> to get started. </p>
*
* <p>Details on GenomicsDB are at
* <a href='https://github.com/Intel-HLS/GenomicsDB/wiki'>https://github.com/Intel-HLS/GenomicsDB/wiki</a>.
* In brief, GenomicsDB is a utility built on top of TileDB. TileDB is a format for efficiently representing sparse data.
* Genomics data is typically sparse in that each sample has few variants with respect to the entire reference genome.
* GenomicsDB contains code to specialize TileDB for genomics applications, such as VCF parsing and INFO field annotation
* calculation.
* </p>
*
* <h3>Input</h3>
* <p>
* One or more GVCFs produced by in HaplotypeCaller with the `-ERC GVCF` or `-ERC BP_RESOLUTION` settings, containing
* the samples to joint-genotype.
* </p>
*
* <h3>Output</h3>
* <p>
* A GenomicsDB workspace
* </p>
*
* <h3>Usage examples</h3>
*
* Provide each sample GVCF separately.
* <pre>
* gatk --java-options "-Xmx4g -Xms4g" GenomicsDBImport \
* -V data/gvcfs/mother.g.vcf.gz \
* -V data/gvcfs/father.g.vcf.gz \
* -V data/gvcfs/son.g.vcf.gz \
* --genomicsdb-workspace-path my_database \
* -L 20
* </pre>
*
* Provide sample GVCFs in a map file.
*
* <pre>
* gatk --java-options "-Xmx4g -Xms4g" \
* GenomicsDBImport \
* --genomicsdb-workspace-path my_database \
* --batch-size 50 \
* -L chr1:1000-10000 \
* --sample-name-map cohort.sample_map \
* --reader-threads 5
* </pre>
*
* The sample map is a tab-delimited text file with sample_name--tab--path_to_sample_vcf per line. Using a sample map
* saves the tool from having to download the GVCF headers in order to determine the sample names. Sample names in
* the sample name map file may have non-tab whitespace, but may not begin or end with whitespace.
*
* <pre>
* sample1 sample1.vcf.gz
* sample2 sample2.vcf.gz
* sample3 sample3.vcf.gz
* </pre>
*
* <h3>Caveats</h3>
* <ul>
* <li>IMPORTANT: The -Xmx value the tool is run with should be less than the total amount of physical memory available by at least a few GB, as the native TileDB library requires additional memory on top of the Java memory. Failure to leave enough memory for the native code can result in confusing error messages!</li>
* <li>At least one interval must be provided</li>
* <li>Input GVCFs cannot contain multiple entries for a single genomic position</li>
* <li>The --genomicsdb-workspace-path must point to a non-existent or empty directory.</li>
* </ul>
*
* <h3>Developer Note</h3>
* To read data from GenomicsDB, use the query interface {@link com.intel.genomicsdb.reader.GenomicsDBFeatureReader}
*/
@DocumentedFeature
@CommandLineProgramProperties(
summary = "Import VCFs to GenomicsDB",
oneLineSummary = "Import VCFs to GenomicsDB",
programGroup = ShortVariantDiscoveryProgramGroup.class
)
public final class GenomicsDBImport extends GATKTool {
private static final long DEFAULT_VCF_BUFFER_SIZE_PER_SAMPLE = 16*1024L;
private static final long DEFAULT_SEGMENT_SIZE = 1048576L;
private static final int DEFAULT_ZERO_BATCH_SIZE = 0;
public static final String WORKSPACE_ARG_LONG_NAME = "genomicsdb-workspace-path";
public static final String SEGMENT_SIZE_ARG_LONG_NAME = "genomicsdb-segment-size";
public static final String OVERWRITE_WORKSPACE_LONG_NAME = "overwrite-existing-genomicsdb-workspace";
public static final String VCF_BUFFER_SIZE_ARG_NAME = "genomicsdb-vcf-buffer-size";
public static final String BATCHSIZE_ARG_LONG_NAME = "batch-size";
public static final String CONSOLIDATE_ARG_NAME = "consolidate";
public static final String SAMPLE_NAME_MAP_LONG_NAME = "sample-name-map";
public static final String VALIDATE_SAMPLE_MAP_LONG_NAME = "validate-sample-name-map";
public static final String VCF_INITIALIZER_THREADS_LONG_NAME = "reader-threads";
public static final String MAX_NUM_INTERVALS_TO_IMPORT_IN_PARALLEL = "max-num-intervals-to-import-in-parallel";
@Argument(fullName = WORKSPACE_ARG_LONG_NAME,
doc = "Workspace for GenomicsDB. Must be a POSIX file system path, but can be a relative path." +
" Must be an empty or non-existent directory.")
private String workspace;
@Argument(fullName = SEGMENT_SIZE_ARG_LONG_NAME,
doc = "Buffer size in bytes allocated for GenomicsDB attributes during " +
"import. Should be large enough to hold data from one site. " +
" Defaults to " + DEFAULT_SEGMENT_SIZE,
optional = true)
private long segmentSize = DEFAULT_SEGMENT_SIZE;
@Argument(fullName = StandardArgumentDefinitions.VARIANT_LONG_NAME,
shortName = StandardArgumentDefinitions.VARIANT_SHORT_NAME,
doc = "GVCF files to be imported to GenomicsDB. Each file must contain" +
"data for only a single sample. Either this or " + SAMPLE_NAME_MAP_LONG_NAME +
" must be specified.",
optional = true,
mutex = {SAMPLE_NAME_MAP_LONG_NAME})
private List<String> variantPaths;
@Argument(fullName = VCF_BUFFER_SIZE_ARG_NAME,
shortName = VCF_BUFFER_SIZE_ARG_NAME,
doc = "Buffer size in bytes to store variant contexts." +
" Larger values are better as smaller values cause frequent disk writes." +
" Defaults to " + DEFAULT_VCF_BUFFER_SIZE_PER_SAMPLE + " which was empirically determined to work" +
" well for many inputs.",
optional = true,
minValue = 1024L,
minRecommendedValue = 10 * 1024)
private long vcfBufferSizePerSample = DEFAULT_VCF_BUFFER_SIZE_PER_SAMPLE;
@Argument(fullName = OVERWRITE_WORKSPACE_LONG_NAME,
doc = "Will overwrite given workspace if it exists. " +
"Otherwise a new workspace is created. " +
"Defaults to false",
optional = true)
private Boolean overwriteExistingWorkspace = false;
@Argument(fullName = BATCHSIZE_ARG_LONG_NAME,
doc = "Batch size controls the number of samples for which readers are open at once " +
"and therefore provides a way to minimize memory consumption. However, it can take longer to complete. " +
"Use the consolidate flag if more than a hundred batches were used. This will improve feature read time. " +
"batchSize=0 means no batching (i.e. readers for all samples will be opened at once) " +
"Defaults to " + DEFAULT_ZERO_BATCH_SIZE,
optional = true)
private int batchSize = DEFAULT_ZERO_BATCH_SIZE;
@Argument(fullName = CONSOLIDATE_ARG_NAME,
shortName = CONSOLIDATE_ARG_NAME,
doc = "Boolean flag to enable consolidation. If importing data in batches, a new fragment is created for " +
"each batch. In case thousands of fragments are created, GenomicsDB feature readers will try " +
"to open ~20x as many files. Also, internally GenomicsDB would consume more memory to maintain " +
"bookkeeping data from all fragments. Use this flag to merge all fragments into one. " +
"Merging can potentially improve read performance, however overall benefit might not be noticeable " +
"as the top Java layers have significantly higher overheads. This flag has no effect if only one " +
"batch is used. Defaults to false",
optional = true)
private Boolean doConsolidation = false;
@Advanced
@Argument(fullName = SAMPLE_NAME_MAP_LONG_NAME,
doc = "Path to file containing a mapping of sample name to file uri in tab delimited format. If this is " +
"specified then the header from the first sample will be treated as the merged header rather than " +
"merging the headers, and the sample names will be taken from this file. This may be used to rename " +
"input samples. This is a performance optimization that relaxes the normal checks for consistent " +
"headers. Using vcfs with incompatible headers may result in silent data corruption.",
optional = true,
mutex = {StandardArgumentDefinitions.VARIANT_LONG_NAME})
private String sampleNameMapFile;
@Argument(fullName = VALIDATE_SAMPLE_MAP_LONG_NAME,
shortName = VALIDATE_SAMPLE_MAP_LONG_NAME,
doc = "Boolean flag to enable checks on the sampleNameMap file. If true, tool checks whether" +
"feature readers are valid and shows a warning if sample names do not match with the headers. " +
"Defaults to false",
optional = true)
private Boolean validateSampleToReaderMap = false;
@Advanced
@Argument(fullName = VCF_INITIALIZER_THREADS_LONG_NAME,
shortName = VCF_INITIALIZER_THREADS_LONG_NAME,
doc = "How many simultaneous threads to use when opening VCFs in batches; higher values may improve performance " +
"when network latency is an issue",
optional = true,
minValue = 1)
private int vcfInitializerThreads = 1;
@Advanced
@Argument(fullName = MAX_NUM_INTERVALS_TO_IMPORT_IN_PARALLEL,
shortName = MAX_NUM_INTERVALS_TO_IMPORT_IN_PARALLEL,
doc = "Max number of intervals to import in parallel; higher values may improve performance, but require more" +
" memory and a higher number of file descriptors open at the same time",
optional = true,
minValue = 1)
private int maxNumIntervalsToImportInParallel = 1;
//executor service used when vcfInitializerThreads > 1
private ExecutorService inputPreloadExecutorService;
@Override
public boolean requiresIntervals() { return true; }
@Override
public int getDefaultCloudPrefetchBufferSize() {
// Empirical testing has shown that this tool performs best at scale with cloud buffering
// disabled. With cloud buffering on and thousands of concurrent GenomicsDBImport tasks,
// we do too many simultaneous GCS accesses (since the prefetcher spawns a new thread for each
// reader upon a query) and start seeing intermittent failures, even with aggressive retries.
return 0;
}
@Override
public int getDefaultCloudIndexPrefetchBufferSize() {
// Empirical testing has shown that this tool performs best at scale with cloud buffering
// disabled. With cloud buffering on and thousands of concurrent GenomicsDBImport tasks,
// we do too many simultaneous GCS accesses (since the prefetcher spawns a new thread for each
// reader upon a query) and start seeing intermittent failures, even with aggressive retries.
return 0;
}
@Override
public String getProgressMeterRecordLabel() { return "batches"; }
// Intervals from command line (singleton for now)
private List<ChromosomeInterval> intervals;
// Sorted mapping between sample names and corresponding GVCF file name
//
// IMPORTANT: This must be sorted or it will result in sample name swaps in the output database.
// This happens because the callset json is generated independently from the import process
// each imported batch is then sorted, so if we have an unsorted list we'll end up with different global vs batch
// sorting.
// We preemptively sort here so we will have consistent sorting.
private SortedMap<String, Path> sampleNameToVcfPath = new TreeMap<>();
// Needed as smartMergeHeaders() returns a set of VCF header lines
private Set<VCFHeaderLine> mergedHeaderLines = null;
// sequence dictionary created from the merged header
private SAMSequenceDictionary mergedHeaderSequenceDictionary;
// Path to vidmap file to be written by GenomicsDBImporter
private File vidMapJSONFile;
// Path to callsetmap file to be written by GenomicsDBImporter
private File callsetMapJSONFile;
// Path to combined VCF header file to be written by GenomicsDBImporter
private File vcfHeaderFile;
// GenomicsDB callset map protobuf structure containing all callset names
// used to write the callset json file on traversal success
private GenomicsDBCallsetsMapProto.CallsetMappingPB callsetMappingPB;
//in-progress batchCount
private int batchCount = 1;
/**
* Before traversal starts, create the feature readers
* for all the input GVCFs, create the merged header and
* initialize the interval
*/
@Override
public void onStartup() {
assertVariantPathsOrSampleNameFileWasSpecified();
initializeHeaderAndSampleMappings();
initializeIntervals();
super.onStartup();
}
private void assertVariantPathsOrSampleNameFileWasSpecified(){
if ( (variantPaths == null || variantPaths.isEmpty()) && sampleNameMapFile == null) {
throw new CommandLineException.MissingArgument(StandardArgumentDefinitions.VARIANT_LONG_NAME,
"One of --" + StandardArgumentDefinitions.VARIANT_LONG_NAME + " or --" + SAMPLE_NAME_MAP_LONG_NAME + " must be specified" );
}
}
/**
* sets the values of mergedHeaderLines, mergedHeaderSequenceDictionary, and sampleNameToVcfPath
*/
private void initializeHeaderAndSampleMappings() {
// Only one of -V and --sampleNameMapFile may be specified
if (sampleNameMapFile == null) {
// -V was specified
final List<VCFHeader> headers = new ArrayList<>(variantPaths.size());
for (final String variantPathString : variantPaths) {
final Path variantPath = IOUtils.getPath(variantPathString);
final VCFHeader header = getHeaderFromPath(variantPath);
Utils.validate(header != null, "Null header was found in " + variantPath + ".");
assertGVCFHasOnlyOneSample(variantPathString, header);
headers.add(header);
final String sampleName = header.getGenotypeSamples().get(0);
final Path previousPath = sampleNameToVcfPath.put(sampleName, variantPath);
if (previousPath != null) {
throw new UserException("Duplicate sample: " + sampleName + ". Sample was found in both "
+ variantPath.toUri() + " and " + previousPath.toUri() + ".");
}
}
mergedHeaderLines = VCFUtils.smartMergeHeaders(headers, true);
mergedHeaderSequenceDictionary = new VCFHeader(mergedHeaderLines).getSequenceDictionary();
} else {
// --sampleNameMap was specified
//it's VERY IMPORTANT that this map is Sorted according to String's natural ordering, if it is not
//the resulting database will have incorrect sample names
//see https://github.com/broadinstitute/gatk/issues/3682 for more information
sampleNameToVcfPath = loadSampleNameMapFileInSortedOrder(IOUtils.getPath(sampleNameMapFile));
final Path firstHeaderPath = sampleNameToVcfPath.entrySet().iterator().next().getValue();
final VCFHeader header = getHeaderFromPath(firstHeaderPath);
//getMetaDataInInputOrder() returns an ImmutableSet - LinkedHashSet is mutable and preserves ordering
mergedHeaderLines = new LinkedHashSet<VCFHeaderLine>(header.getMetaDataInInputOrder());
mergedHeaderSequenceDictionary = header.getSequenceDictionary();
}
mergedHeaderLines.addAll(getDefaultToolVCFHeaderLines());
if ( mergedHeaderSequenceDictionary == null) {
throw new UserException("The merged vcf header has no sequence dictionary. Please provide a header that contains a sequence dictionary.");
}
}
private VCFHeader getHeaderFromPath(final Path variantPath) {
try(final AbstractFeatureReader<VariantContext, LineIterator> reader = getReaderFromPath(variantPath)) {
return (VCFHeader) reader.getHeader();
} catch (final IOException e) {
throw new UserException("Error while reading vcf header from " + variantPath.toUri(), e);
}
}
private static void assertGVCFHasOnlyOneSample(final String variantPath, final VCFHeader header) {
// A GVCF file must contain only one sample, throw an exception otherwise
final int numberOfSamples = header.getNGenotypeSamples();
if (numberOfSamples != 1) {
throw new UserException("Input GVCF: " + variantPath + " was expected to contain a single sample but actually contained " + numberOfSamples + " samples.");
}
}
/**
* load a tab delimited new line separated file of sample name to URI mapping:
* this maintains the keys in the same order that they appeared in the file
*
* this tool should only call {@link #loadSampleNameMapFileInSortedOrder(Path)},
* this version is exposed for the benefit of {@link org.broadinstitute.hellbender.tools.FixCallSetSampleOrdering}
*
* ex:
*
* Sample1\tpathToSample1.vcf\n
* Sample2\tpathTosample2.vcf\n
* ...
*
* The sample names must be unique.
* @param sampleToFileMapPath path to the mapping file
* @return map of sample name to corresponding file, the map will be ordered according to the order in the input file
*/
public static LinkedHashMap<String, Path> loadSampleNameMapFile(final Path sampleToFileMapPath) {
try {
final List<String> lines = Files.readAllLines(sampleToFileMapPath);
if (lines.isEmpty()) {
throw new UserException.BadInput( "At least 1 sample is required but none were found in the sample mapping file");
}
final LinkedHashMap<String, Path> sampleToFilename = new LinkedHashMap<>();
for ( final String line : lines) {
final String[] split = line.split("\\t",-1);
if (split.length != 2) {
throw new UserException.BadInput("Expected a file with 2 fields per line in the format\nSample\tFile\n but found line: \""
+ line +"\" with "+split.length+" fields");
}
if ( !split[0].trim().equals(split[0]) || split[0].trim().isEmpty()
|| split[1].trim().isEmpty()) {
throw new UserException.BadInput("Expected a file of format\nSample\tFile\n but found line: '" + line + "'\nValid sample names must be non-empty strings that cannot begin or end with whitespace and valid file names must be non-empty and not all whitespace");
}
final String sample = split[0];
final String path = split[1].trim();
final Path oldPath = sampleToFilename.put(sample, IOUtils.getPath(path));
if (oldPath != null){
throw new UserException.BadInput("Found two mappings for the same sample: " + sample + "\n" + path + "\n" + oldPath.toUri() );
}
}
return sampleToFilename;
} catch (final IOException e) {
throw new UserException.CouldNotReadInputFile(sampleToFileMapPath, "exception while reading sample->filename mapping file", e);
}
}
/**
* load a tab delimited new line separated file of sample name to URI mapping:
*
* ex:
* Sample1\tpathToSample1.vcf\n
* Sample2\tpathTosample2.vcf\n
* ...
*
* The sample names must be unique.
* @param sampleToFileMapPath path to the mapping file
* @return map of sample name to corresponding file, sorted by sample name
*/
public static SortedMap<String, Path> loadSampleNameMapFileInSortedOrder(final Path sampleToFileMapPath){
return new TreeMap<>(loadSampleNameMapFile(sampleToFileMapPath));
}
/**
* Before traversal, fix configuration parameters and initialize
* GenomicsDB. Hard-coded to handle only VCF files and headers
*/
@Override
public void onTraversalStart() {
final File workspaceDir = overwriteOrCreateWorkspace();
vidMapJSONFile = new File(workspaceDir + "/" + GenomicsDBConstants.DEFAULT_VIDMAP_FILE_NAME);
callsetMapJSONFile = new File(workspaceDir + "/" + GenomicsDBConstants.DEFAULT_CALLSETMAP_FILE_NAME);
vcfHeaderFile = new File(workspaceDir + "/" + GenomicsDBConstants.DEFAULT_VCFHEADER_FILE_NAME);
logger.info("Vid Map JSON file will be written to " + vidMapJSONFile);
logger.info("Callset Map JSON file will be written to " + callsetMapJSONFile);
logger.info("Complete VCF Header will be written to " + vcfHeaderFile);
logger.info("Importing to array - " + workspace + "/" + GenomicsDBConstants.DEFAULT_ARRAY_NAME);
initializeInputPreloadExecutorService();
}
private void initializeInputPreloadExecutorService() {
if( vcfInitializerThreads > 1) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("readerInitializer-thread-%d")
.setDaemon(true)
.build();
this.inputPreloadExecutorService = Executors.newFixedThreadPool(vcfInitializerThreads, threadFactory);
} else {
inputPreloadExecutorService = null;
}
}
private Map<String, FeatureReader<VariantContext>> createSampleToReaderMap(
final Map<String, Path> sampleNameToVcfPath, final int batchSize, final int index) {
// TODO: fix casting since it's really ugly
return inputPreloadExecutorService != null ?
getFeatureReadersInParallel((SortedMap<String, Path>) sampleNameToVcfPath, batchSize, index)
: getFeatureReadersSerially(sampleNameToVcfPath, batchSize, index);
}
private Void logMessageOnBatchCompletion(final BatchCompletionCallbackFunctionArgument arg) {
progressMeter.update(intervals.get(0));
logger.info("Done importing batch " + arg.batchCount + "/" + arg.totalBatchCount);
this.batchCount = arg.batchCount + 1;
return null;
}
private List<GenomicsDBImportConfiguration.Partition> generatePartitionListFromIntervals(List<ChromosomeInterval> chromosomeIntervals) {
return chromosomeIntervals.stream().map(interval -> {
GenomicsDBImportConfiguration.Partition.Builder partitionBuilder = GenomicsDBImportConfiguration.Partition.newBuilder();
Coordinates.ContigPosition.Builder contigPositionBuilder = Coordinates.ContigPosition.newBuilder();
Coordinates.GenomicsDBColumn.Builder columnBuilder = Coordinates.GenomicsDBColumn.newBuilder();
//begin
contigPositionBuilder.setContig(interval.getContig()).setPosition(interval.getStart());
columnBuilder.setContigPosition(contigPositionBuilder.build());
partitionBuilder.setBegin(columnBuilder.build());
//end
contigPositionBuilder.setPosition(interval.getEnd());
columnBuilder.setContigPosition(contigPositionBuilder.build());
partitionBuilder.setEnd(columnBuilder.build());
partitionBuilder.setWorkspace(workspace);
partitionBuilder.setGenerateArrayNameFromPartitionBounds(true);
return partitionBuilder.build();
}).collect(Collectors.toList());
}
private ImportConfig createImportConfig(final int batchSize) {
final List<GenomicsDBImportConfiguration.Partition> partitions = generatePartitionListFromIntervals(intervals);
GenomicsDBImportConfiguration.ImportConfiguration.Builder importConfigurationBuilder =
GenomicsDBImportConfiguration.ImportConfiguration.newBuilder();
importConfigurationBuilder.addAllColumnPartitions(partitions);
importConfigurationBuilder.setSizePerColumnPartition(vcfBufferSizePerSample);
importConfigurationBuilder.setFailIfUpdating(true);
importConfigurationBuilder.setSegmentSize(segmentSize);
importConfigurationBuilder.setConsolidateTiledbArrayAfterLoad(doConsolidation);
ImportConfig importConfig = new ImportConfig(importConfigurationBuilder.build(), validateSampleToReaderMap, true,
batchSize, mergedHeaderLines, sampleNameToVcfPath, this::createSampleToReaderMap);
importConfig.setOutputCallsetmapJsonFile(callsetMapJSONFile.getAbsolutePath());
importConfig.setOutputVidmapJsonFile(vidMapJSONFile.getAbsolutePath());
importConfig.setOutputVcfHeaderFile(vcfHeaderFile.getAbsolutePath());
importConfig.setUseSamplesInOrder(true);
importConfig.setFunctionToCallOnBatchCompletion(this::logMessageOnBatchCompletion);
return importConfig;
}
/**
* A complete traversal from start to finish. This method will import all samples
* specified in the input GVCF files.
*/
@Override
public void traverse() {
// Force the progress meter to update after every batch
progressMeter.setRecordsBetweenTimeChecks(1L);
final int sampleCount = sampleNameToVcfPath.size();
final int updatedBatchSize = (batchSize == DEFAULT_ZERO_BATCH_SIZE) ? sampleCount : batchSize;
final ImportConfig importConfig = createImportConfig(updatedBatchSize);
GenomicsDBImporter importer;
try {
importer = new GenomicsDBImporter(importConfig);
importer.executeImport(maxNumIntervalsToImportInParallel);
} catch (final IOException e) {
throw new UserException("Error initializing GenomicsDBImporter", e);
} catch (final IllegalArgumentException iae) {
throw new GATKException("Null feature reader found in sampleNameMap file: " + sampleNameMapFile, iae);
}
}
@Override
public Object onTraversalSuccess() {
if (batchSize == DEFAULT_ZERO_BATCH_SIZE) {
logger.info("Import completed!");
} else {
logger.info("Import of all batches to GenomicsDB completed!");
}
return true;
}
/**
* Method to create feature readers for input files or GCS URLs
* in the current batch
*
* @param sampleNametoPath Sample name to file name mapping
* @param batchSize Current batch size
* @param lowerSampleIndex 0-based Lower bound of sample index -- inclusive
* @return Feature readers to be imported in the current batch, sorted by sample name
*/
private SortedMap<String, FeatureReader<VariantContext>> getFeatureReadersInParallel(
final SortedMap<String, Path> sampleNametoPath, final int batchSize, final int lowerSampleIndex) {
final SortedMap<String, FeatureReader<VariantContext>> sampleToReaderMap = new TreeMap<>();
logger.info("Starting batch input file preload");
final Map<String, Future<FeatureReader<VariantContext>>> futures = new LinkedHashMap<>();
final List<String> sampleNames = new ArrayList<>(sampleNametoPath.keySet());
for(int i = lowerSampleIndex; i < sampleNametoPath.size() && i < lowerSampleIndex+batchSize; ++i) {
final String sampleName = sampleNames.get(i);
futures.put(sampleName, inputPreloadExecutorService.submit(() -> {
final Path variantPath = sampleNametoPath.get(sampleName);
try {
return new InitializedQueryWrapper(getReaderFromPath(variantPath), intervals.get(0));
} catch (final IOException e) {
throw new UserException.CouldNotReadInputFile("Couldn't read file: " + variantPath.toUri(), e);
}
}));
}
futures.forEach((sampleName, future) -> {
try {
final FeatureReader<VariantContext> reader = future.get();
sampleToReaderMap.put(sampleName, reader);
} catch (InterruptedException | ExecutionException e) {
throw new UserException.CouldNotReadInputFile("Failure while waiting for FeatureReader to initialize ",
e);
}
});
logger.info("Finished batch preload");
logger.info("Importing batch " + this.batchCount + " with " + sampleToReaderMap.size() + " samples");
return sampleToReaderMap;
}
private SortedMap<String, FeatureReader<VariantContext>> getFeatureReadersSerially(final Map<String, Path> sampleNameToPath,
final int batchSize, final int lowerSampleIndex){
final SortedMap<String, FeatureReader<VariantContext>> sampleToReaderMap = new TreeMap<>();
final List<String> sampleNames = new ArrayList<>(sampleNameToPath.keySet());
for(int i = lowerSampleIndex; i < sampleNameToPath.size() && i < lowerSampleIndex+batchSize; ++i) {
final String sampleName = sampleNames.get(i);
final AbstractFeatureReader<VariantContext, LineIterator> reader = getReaderFromPath(sampleNameToPath.get(sampleName));
sampleToReaderMap.put(sampleName, reader);
}
logger.info("Importing batch " + this.batchCount + " with " + sampleToReaderMap.size() + " samples");
return sampleToReaderMap;
}
/**
* Creates a feature reader object from a given VCF URI (can also be
* a local file path) and returns it
* @return Feature reader
* @param variantPath
*/
private AbstractFeatureReader<VariantContext, LineIterator> getReaderFromPath(final Path variantPath) {
final String variantURI = variantPath.toAbsolutePath().toUri().toString();
final Function<SeekableByteChannel, SeekableByteChannel> cloudWrapper = (cloudPrefetchBuffer > 0 ? is -> SeekableByteChannelPrefetcher.addPrefetcher(cloudPrefetchBuffer, is) : Function.identity());
final Function<SeekableByteChannel, SeekableByteChannel> cloudIndexWrapper = (cloudIndexPrefetchBuffer > 0 ? is -> SeekableByteChannelPrefetcher.addPrefetcher(cloudIndexPrefetchBuffer, is) : Function.identity());
try {
return AbstractFeatureReader.getFeatureReader(variantURI, null, new VCFCodec(), true, cloudWrapper, cloudIndexWrapper);
} catch (final TribbleException e){
throw new UserException("Failed to create reader from " + variantURI, e);
}
}
/**
* Input argument "overwriteExistingWorkspace" defaults to false.
* The tool creates a new workspace if it doesn't exist. Deletes
* an existing workspace if argument is true
*
* @return The workspace directory
*/
private File overwriteOrCreateWorkspace() {
final File workspaceDir = new File(workspace);
if (overwriteExistingWorkspace) {
IOUtils.tryDelete(workspaceDir);
}
if (!workspaceDir.exists()) {
final int ret = GenomicsDBImporter.createTileDBWorkspace(workspaceDir.getAbsolutePath());
if (ret > 0) {
checkIfValidWorkspace(workspaceDir);
logger.info("Importing data to GenomicsDB workspace: " + workspaceDir);
} else if (ret < 0) {
throw new UnableToCreateGenomicsDBWorkspace("Error creating GenomicsDB workspace: " + workspaceDir);
}
return workspaceDir;
} else {
throw new UnableToCreateGenomicsDBWorkspace("The workspace you're trying to create already exists. ( " + workspaceDir.getAbsolutePath() + " ) " +
"Writing into an existing workspace can cause data corruption. " +
"Please choose an output path that doesn't already exist. ");
}
}
static class UnableToCreateGenomicsDBWorkspace extends UserException {
private static final long serialVersionUID = 1L;
UnableToCreateGenomicsDBWorkspace(final String message){
super(message);
}
}
private static void checkIfValidWorkspace(final File workspaceDir) {
final File tempFile = new File(workspaceDir.getAbsolutePath() + "/__tiledb_workspace.tdb");
if (!tempFile.exists()) {
throw new UserException(workspaceDir.getAbsolutePath() + " is not a valid GenomicsDB workspace");
}
}
/**
* Loads our intervals using the best available sequence
* dictionary (as returned by {@link #getBestAvailableSequenceDictionary})
* to parse/verify them. Does nothing if no intervals were specified.
*/
private void initializeIntervals() {
if (intervalArgumentCollection.intervalsSpecified()) {
final SAMSequenceDictionary intervalDictionary = getBestAvailableSequenceDictionary();
if (intervalDictionary == null) {
throw new UserException("We require at least one input source that " +
"has a sequence dictionary (reference or reads) when intervals are specified");
}
intervals = new ArrayList<>();
final List<SimpleInterval> simpleIntervalList = intervalArgumentCollection.getIntervals(intervalDictionary);
simpleIntervalList.forEach(interval -> intervals.add(new ChromosomeInterval(interval.getContig(),
interval.getStart(), interval.getEnd())));
} else {
throw new UserException("No intervals specified");
}
}
@Override
public void onShutdown(){
if(inputPreloadExecutorService != null) {
inputPreloadExecutorService.shutdownNow();
}
}
/**
* Overriding getBestAvailableSequenceDictionary() to prefer the mergedVCFHeader's
* sequence directory, if present, over any other dictionaries
*
* @return Sequence directory from merged header, or super.getBestAvailableSequenceDictionary()
* if none
*/
@Override
public SAMSequenceDictionary getBestAvailableSequenceDictionary() {
final SAMSequenceDictionary sequenceDictionary = mergedHeaderSequenceDictionary;
if (sequenceDictionary == null) {
return super.getBestAvailableSequenceDictionary();
} else {
return sequenceDictionary;
}
}
/**
* This class is a hack to force parallel loading of the headers and indexes of remote gvcf files.
* It initializes a feature reader and starts a query. This causes the header and index to be read, and also causes any
* pre-fetching to begin if enabled. It is very narrowly crafted and should not be used for other purposes.
*/
private static final class InitializedQueryWrapper implements FeatureReader<VariantContext> {
private final FeatureReader<VariantContext> reader;
private final SimpleInterval interval;
private CloseableTribbleIterator<VariantContext> query;
private InitializedQueryWrapper(final FeatureReader<VariantContext> reader, final Locatable interval) throws IOException {
this.reader = reader;
this.interval = new SimpleInterval(interval);
this.query = reader.query(interval.getContig(), interval.getStart(), interval.getEnd());
}
@Override
public CloseableTribbleIterator<VariantContext> query(final String chr, final int start, final int end) {
final SimpleInterval queryInterval = new SimpleInterval(chr, start, end);
if( !interval.equals(queryInterval)){
throw new GATKException("Cannot call query with different interval, expected:" + this.interval + " queried with: " + queryInterval);
}
if( query != null ){
final CloseableTribbleIterator<VariantContext> tmp = query;
query = null;
return tmp;
} else {
throw new GATKException("Cannot call query twice on this wrapper.");
}
}
@Override
public CloseableTribbleIterator<VariantContext> iterator() {
throw new UnsupportedOperationException("iterator() not supported, this should not have been called and indicates an issue with GenomicsDB integration");
}
@Override
public void close() throws IOException {
reader.close();
}
@Override
public List<String> getSequenceNames() {
throw new UnsupportedOperationException("getSequenceNames() not supported, this should not have been called and indicates an issue with GenomicsDB integration");
}
@Override
public Object getHeader() {
return reader.getHeader();
}
}
}
|
3e0c8589bac8b58335b2431f94128a7dc4ec08a6 | 8,395 | java | Java | FHICT-Companion/app/src/main/java/s/pahlplatz/fhict_companion/controllers/PeopleController.java | StefanPahlplatz/fontys-companion-app | 6bcf305e9e2a1f2f9c05ce95e8c2bddf95d6a6b2 | [
"MIT"
] | null | null | null | FHICT-Companion/app/src/main/java/s/pahlplatz/fhict_companion/controllers/PeopleController.java | StefanPahlplatz/fontys-companion-app | 6bcf305e9e2a1f2f9c05ce95e8c2bddf95d6a6b2 | [
"MIT"
] | 2 | 2017-04-30T14:47:38.000Z | 2018-04-03T14:25:02.000Z | FHICT-Companion/app/src/main/java/s/pahlplatz/fhict_companion/controllers/PeopleController.java | StefanPahlplatz/fontys-companion-app | 6bcf305e9e2a1f2f9c05ce95e8c2bddf95d6a6b2 | [
"MIT"
] | null | null | null | 34.547325 | 118 | 0.56081 | 5,323 | package s.pahlplatz.fhict_companion.controllers;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import s.pahlplatz.fhict_companion.models.Person;
import s.pahlplatz.fhict_companion.utils.FontysAPI;
import s.pahlplatz.fhict_companion.utils.PreferenceHelper;
/**
* Created by Stefan on 25-2-2017.
* <p>
* Controller for the people fragment.
*/
public class PeopleController {
private static final String TAG = PeopleController.class.getSimpleName();
private final Context ctx;
private final PeopleListener listener; // Reference to the view hosting the search.
private ArrayList<Person> personList;
private OnFragmentInteractionListener activityListener; // Reference to the activity hosting the search.
/**
* Constructor.
*
* @param ctx context that implements OnPeopleSearchListener.
* @param caller calling view that implements ProgressbarListener.
*/
public PeopleController(final Context ctx, final PeopleListener caller) {
this.ctx = ctx;
this.listener = caller;
// Assign the listener.
if (ctx instanceof OnFragmentInteractionListener) {
activityListener = (OnFragmentInteractionListener) ctx;
} else {
throw new RuntimeException(ctx.toString() + " must implement OnPeopleSearchListener");
}
}
/**
* Starts a search for the specified query.
*
* @param query search parameter.
*/
public void search(final String query) {
if (!query.equals("")) {
new LoadResults().execute(query);
} else {
Toast.makeText(ctx, "Search can't be empty", Toast.LENGTH_SHORT).show();
}
}
private ArrayAdapter getAdapter(final ArrayList<Person> persons) {
@SuppressWarnings("unchecked")
ArrayAdapter adapter =
new ArrayAdapter(ctx, android.R.layout.simple_list_item_2, android.R.id.text1, persons) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(persons.get(position).getName());
text2.setText(persons.get(position).getTitle());
return view;
}
};
return adapter;
}
/**
* Creates and sets the adapter to show the persons from the search results.
*
* @param persons list of retrieved persons.
*/
public void createList(final ArrayList<Person> persons) {
personList = persons;
listener.setAdapter(getAdapter(persons));
}
/**
* Getter for personList.
*/
public ArrayList<Person> getPersonList() {
return personList;
}
/**
* Switch fragments to display the information of the selected person.
*
* @param i index in the listview/list.
*/
public void onItemSelected(final int i) {
activityListener.onFragmentInteraction(personList.get(i));
}
/**
* Interface implemented by the host to control the visibility of the progressbar.
*/
public interface PeopleListener {
/**
* Hides and un-hides the progressbar.
*
* @param visible or not.
*/
void progressbarVisibility(boolean visible);
/**
* Assign the adapter to the listview.
*
* @param adapter to be assigned.
*/
void setAdapter(ArrayAdapter adapter);
}
/**
* Interface implemented by the hosting activity to switch to the details fragment.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Person person);
}
/**
* Load the results from the fontys API.
*/
private class LoadResults extends AsyncTask<String, Void, Void> {
private JSONArray jArrayPeopleSearch = null;
private JSONArray jArrayClassMembers = null;
private String token;
private String classId;
private String className;
private String query;
@Override
protected void onPreExecute() {
token = PreferenceHelper.getString(ctx, PreferenceHelper.TOKEN);
classId = PreferenceHelper.getString(ctx, PreferenceHelper.CLASS_ID);
className = PreferenceHelper.getString(ctx, PreferenceHelper.CLASS_NAME);
listener.progressbarVisibility(true);
}
@Override
protected Void doInBackground(final String... params) {
query = params[0];
// // Get data from the people search.
try {
jArrayPeopleSearch = new JSONArray(FontysAPI.getStream(
"https://api.fhict.nl/people/search/" + query, token));
} catch (Exception ex) {
Log.e(TAG, "doInBackground: Couldn't get data", ex);
}
// Get data from the class search.
if (!classId.equals("")) {
try {
JSONObject jObj = new JSONObject(FontysAPI.getStream(
"https://api.fhict.nl/groups/" + classId + "?includeMembers=true", token));
jArrayClassMembers = jObj.getJSONArray("members");
} catch (Exception ex) {
Log.e(TAG, "doInBackground: Couldn't get data from class search.", ex);
}
}
return null;
}
@Override
protected void onPostExecute(final Void v) {
personList = new ArrayList<>();
if (jArrayPeopleSearch != null) {
// One result.
if (jArrayPeopleSearch.length() == 1) {
try {
personList.add(new Person(jArrayPeopleSearch.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
// More results.
} else {
try {
for (int i = 0; i < jArrayPeopleSearch.length(); i++) {
JSONObject p = jArrayPeopleSearch.getJSONObject(i);
personList.add(new Person(p));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Log.e(TAG, "onPostExecute: People search is null");
}
if (jArrayClassMembers != null) {
for (int i = 0; i < jArrayClassMembers.length(); i++) {
JSONObject p = null;
try {
p = jArrayClassMembers.getJSONObject(i);
} catch (JSONException e) {
// Do nothing.
}
Person person = new Person(p, className);
if (person.contains(query)) {
personList.add(person);
}
}
} else {
Log.e(TAG, "onPostExecute: jArrayClassMembers = null. "
+ "This means that the search for people in your class was unsuccessful");
}
if (personList.size() == 0) {
Toast.makeText(ctx, "No results found", Toast.LENGTH_SHORT).show();
} else if (personList.size() == 1) {
activityListener.onFragmentInteraction(personList.get(0));
} else {
createList(personList);
}
// Hide the pbar.
listener.progressbarVisibility(false);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.