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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
924275278b104895651fc74aeeed14bef16347c7
| 1,334 |
java
|
Java
|
modules/server-endpoints/language-server/src/main/java/org/wso2/carbon/identity/developer/lsp/debug/runtime/builders/SAMLEntryVariablePlan.java
|
madurangasiriwardena/identity-developer-tools
|
52102e0ee72f0f05cbb6fb610116bc59034b8143
|
[
"Apache-2.0"
] | 3 |
2020-04-09T09:10:48.000Z
|
2020-10-31T16:37:39.000Z
|
modules/server-endpoints/language-server/src/main/java/org/wso2/carbon/identity/developer/lsp/debug/runtime/builders/SAMLEntryVariablePlan.java
|
madurangasiriwardena/identity-developer-tools
|
52102e0ee72f0f05cbb6fb610116bc59034b8143
|
[
"Apache-2.0"
] | 20 |
2020-01-16T11:50:24.000Z
|
2021-11-02T04:27:24.000Z
|
modules/server-endpoints/language-server/src/main/java/org/wso2/carbon/identity/developer/lsp/debug/runtime/builders/SAMLEntryVariablePlan.java
|
madurangasiriwardena/identity-developer-tools
|
52102e0ee72f0f05cbb6fb610116bc59034b8143
|
[
"Apache-2.0"
] | 12 |
2019-10-15T09:38:50.000Z
|
2021-07-27T15:57:23.000Z
| 33.35 | 97 | 0.72039 | 1,002,275 |
/*
* Copyright (c) 2020, 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.identity.developer.lsp.debug.runtime.builders;
/**
* Interface to help build the SAMLEntryVariable.
*/
public interface SAMLEntryVariablePlan {
/**
* This method is add httpServletRequest to variables list After the argument is proceeded.
*
* @param httpServletRequest The HttpServletRequest object, known as "request" in a JSP page.
*/
void setHttpServletRequest(Object httpServletRequest);
/**
* This method is add SAML Request to variables list After the argument is proceeded.
*
* @param samlRequest The SAML Request string.
*/
void setSAMLRequest(Object samlRequest);
}
|
92427558251a6e23b4a5d6b21b1bba67535e12d5
| 2,918 |
java
|
Java
|
src/main/java/fi/laverca/jaxb/xmldsigcore/SPKIData.java
|
Hemuu/laverca
|
cd5ac94eccaa6c64ee511cdc431f17c8c7936648
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/fi/laverca/jaxb/xmldsigcore/SPKIData.java
|
Hemuu/laverca
|
cd5ac94eccaa6c64ee511cdc431f17c8c7936648
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/fi/laverca/jaxb/xmldsigcore/SPKIData.java
|
Hemuu/laverca
|
cd5ac94eccaa6c64ee511cdc431f17c8c7936648
|
[
"Apache-2.0"
] | null | null | null | 31.042553 | 113 | 0.672721 | 1,002,276 |
package fi.laverca.jaxb.xmldsigcore;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import com.sun.xml.bind.Locatable;
import com.sun.xml.bind.annotation.XmlLocation;
import org.w3c.dom.Element;
import org.xml.sax.Locator;
/**
* <p>Java class for SPKIDataType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SPKIDataType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence maxOccurs="unbounded">
* <element name="SPKISexp" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/>
* <any processContents='lax' namespace='##other' minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SPKIDataType", namespace = "http://www.w3.org/2000/09/xmldsig#", propOrder = {
"spkiSexpsAndAnies"
})
@XmlRootElement(name = "SPKIData", namespace = "http://www.w3.org/2000/09/xmldsig#")
public class SPKIData implements Locatable
{
@XmlElementRef(name = "SPKISexp", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class)
@XmlAnyElement
protected List<java.lang.Object> spkiSexpsAndAnies;
@XmlLocation
@XmlTransient
protected Locator locator;
/**
* Gets the value of the spkiSexpsAndAnies property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the spkiSexpsAndAnies property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSPKISexpsAndAnies().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link byte[]}{@code >}
* {@link Element }
*
*
*/
public List<java.lang.Object> getSPKISexpsAndAnies() {
if (spkiSexpsAndAnies == null) {
spkiSexpsAndAnies = new ArrayList<java.lang.Object>();
}
return this.spkiSexpsAndAnies;
}
public Locator sourceLocation() {
return locator;
}
public void setSourceLocation(Locator newLocator) {
locator = newLocator;
}
}
|
924275714ef460fc232bb971640611796ff5ea70
| 1,693 |
java
|
Java
|
org/sonatype/aether/util/layout/MavenDefaultLayout.java
|
CoOwner/VisualPvP
|
c92d1dcf40a812787e32e8a21d6462b57e755b99
|
[
"MIT"
] | null | null | null |
org/sonatype/aether/util/layout/MavenDefaultLayout.java
|
CoOwner/VisualPvP
|
c92d1dcf40a812787e32e8a21d6462b57e755b99
|
[
"MIT"
] | null | null | null |
org/sonatype/aether/util/layout/MavenDefaultLayout.java
|
CoOwner/VisualPvP
|
c92d1dcf40a812787e32e8a21d6462b57e755b99
|
[
"MIT"
] | null | null | null | 19.022472 | 84 | 0.608978 | 1,002,277 |
package org.sonatype.aether.util.layout;
import java.net.URI;
import java.net.URISyntaxException;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.metadata.Metadata;
public class MavenDefaultLayout
implements RepositoryLayout
{
public MavenDefaultLayout() {}
private URI toUri(String path)
{
try
{
return new URI(null, null, path, null);
}
catch (URISyntaxException e)
{
throw new IllegalStateException(e);
}
}
public URI getPath(Artifact artifact)
{
StringBuilder path = new StringBuilder(128);
path.append(artifact.getGroupId().replace('.', '/')).append('/');
path.append(artifact.getArtifactId()).append('/');
path.append(artifact.getBaseVersion()).append('/');
path.append(artifact.getArtifactId()).append('-').append(artifact.getVersion());
if (artifact.getClassifier().length() > 0)
{
path.append('-').append(artifact.getClassifier());
}
path.append('.').append(artifact.getExtension());
return toUri(path.toString());
}
public URI getPath(Metadata metadata)
{
StringBuilder path = new StringBuilder(128);
if (metadata.getGroupId().length() > 0)
{
path.append(metadata.getGroupId().replace('.', '/')).append('/');
if (metadata.getArtifactId().length() > 0)
{
path.append(metadata.getArtifactId()).append('/');
if (metadata.getVersion().length() > 0)
{
path.append(metadata.getVersion()).append('/');
}
}
}
path.append(metadata.getType());
return toUri(path.toString());
}
}
|
9242757a64db81252f474158fbbb4a7ad81551c7
| 3,706 |
java
|
Java
|
src/main/java/com/soprasteria/initiatives/service/TokenService.java
|
cegiraud/test-spring
|
d7f6383ff4791d93f367a5534a40b669cd84cffb
|
[
"MIT"
] | null | null | null |
src/main/java/com/soprasteria/initiatives/service/TokenService.java
|
cegiraud/test-spring
|
d7f6383ff4791d93f367a5534a40b669cd84cffb
|
[
"MIT"
] | null | null | null |
src/main/java/com/soprasteria/initiatives/service/TokenService.java
|
cegiraud/test-spring
|
d7f6383ff4791d93f367a5534a40b669cd84cffb
|
[
"MIT"
] | null | null | null | 42.113636 | 120 | 0.750944 | 1,002,278 |
package com.soprasteria.initiatives.service;
import com.soprasteria.initiatives.utils.SSOProvider;
import com.soprasteria.initiatives.utils.UrlUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.StringJoiner;
/**
* Business service to obtain OAuth2 token
*
* @author jntakpe
* @author cegiraud
*/
@Service
public class TokenService {
private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);
private static final String BASIC_PREFIX = "Basic ";
private static final String BLANK_WORD = "";
private static final String OAUTH2_TOKEN_URL = "/oauth/token";
private final OAuth2ClientProperties oAuth2ClientProperties;
public TokenService(OAuth2ClientProperties oAuth2ClientProperties) {
this.oAuth2ClientProperties = oAuth2ClientProperties;
}
public ResponseEntity<OAuth2AccessToken> authorize(String accessToken, SSOProvider ssoProvider, String requestUrl) {
try {
String url = url(accessToken, ssoProvider, requestUrl);
return new RestTemplate().postForEntity(url, new HttpEntity(initializeHeaders()), OAuth2AccessToken.class);
} catch (Exception e) {
LOGGER.warn("Unable to obtain token {}", e);
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
private String url(String accessToken, SSOProvider ssoProvider, String requestUrl) {
String serverAddress = UrlUtils.getServerAdressFromRequest(requestUrl);
return UriComponentsBuilder.fromHttpUrl(serverAddress + OAUTH2_TOKEN_URL)
.queryParams(requestParams(accessToken, ssoProvider)).toUriString();
}
private MultiValueMap<String, String> requestParams(String authorization, SSOProvider ssoProvider) {
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add("username", authorization);
requestParams.add("password", BLANK_WORD);
requestParams.add(OAuth2Utils.GRANT_TYPE, "password");
requestParams.add(OAuth2Utils.SCOPE, "openid");
requestParams.add(OAuth2Utils.CLIENT_ID, oAuth2ClientProperties.getClientId());
requestParams.add("secret", oAuth2ClientProperties.getClientSecret());
requestParams.add("ssoProvider", ssoProvider.toString());
return requestParams;
}
private MultiValueMap<String, String> initializeHeaders() {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add(HttpHeaders.AUTHORIZATION, BASIC_PREFIX + base64ClientIdSecret());
headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
return headers;
}
private String base64ClientIdSecret() {
String clientIdSecret = new StringJoiner(":")
.add(oAuth2ClientProperties.getClientId())
.add(oAuth2ClientProperties.getClientSecret()).toString();
return Base64.encodeBase64String(clientIdSecret.getBytes());
}
}
|
924275a06f0930520d695748d08f8921a7e85243
| 1,592 |
java
|
Java
|
references/bcb_chosen_clones/selected#2301312#52#79.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 23 |
2018-10-03T15:02:53.000Z
|
2021-09-16T11:07:36.000Z
|
references/bcb_chosen_clones/selected#2301312#52#79.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 18 |
2019-02-10T04:52:54.000Z
|
2022-01-25T02:14:40.000Z
|
references/bcb_chosen_clones/selected#2301312#52#79.java
|
cragkhit/Siamese
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 19 |
2018-11-16T13:39:05.000Z
|
2021-09-05T23:59:30.000Z
| 54.896552 | 156 | 0.582915 | 1,002,279 |
private Map<String, com.sun.jdi.connect.Connector.Argument> parseConnectorArgs(Connector connector, String argString) {
Map<String, com.sun.jdi.connect.Connector.Argument> arguments = connector.defaultArguments();
String regexPattern = "(quote=[^,]+,)|" + "(\\w+=)" + "(((\"[^\"]*\")|" + "('[^']*')|" + "([^,'\"]+))+,)";
Pattern p = Pattern.compile(regexPattern);
Matcher m = p.matcher(argString);
while (m.find()) {
int startPosition = m.start();
int endPosition = m.end();
if (startPosition > 0) {
throw new IllegalArgumentException(MessageOutput.format("Illegal connector argument", argString));
}
String token = argString.substring(startPosition, endPosition);
int index = token.indexOf('=');
String name = token.substring(0, index);
String value = token.substring(index + 1, token.length() - 1);
Connector.Argument argument = arguments.get(name);
if (argument == null) {
throw new IllegalArgumentException(MessageOutput.format("Argument is not defined for connector:", new Object[] { name, connector.name() }));
}
argument.setValue(value);
argString = argString.substring(endPosition);
m = p.matcher(argString);
}
if ((!argString.equals(",")) && (argString.length() > 0)) {
throw new IllegalArgumentException(MessageOutput.format("Illegal connector argument", argString));
}
return arguments;
}
|
9242761decae1885f37f00c8496ebfe70edbf4f2
| 166 |
java
|
Java
|
afterburner-java/src/main/java/nl/stokpop/afterburner/domain/BurnerMessage.java
|
mhuijgens/afterburner
|
d5d5fe102df15dd3e57d9f348fa7ef6bf5e790cb
|
[
"MIT"
] | 2 |
2021-01-20T14:17:26.000Z
|
2021-04-13T18:50:20.000Z
|
afterburner-java/src/main/java/nl/stokpop/afterburner/domain/BurnerMessage.java
|
mhuijgens/afterburner
|
d5d5fe102df15dd3e57d9f348fa7ef6bf5e790cb
|
[
"MIT"
] | 65 |
2020-04-07T05:12:06.000Z
|
2022-01-19T09:53:27.000Z
|
afterburner-java/src/main/java/nl/stokpop/afterburner/domain/BurnerMessage.java
|
mhuijgens/afterburner
|
d5d5fe102df15dd3e57d9f348fa7ef6bf5e790cb
|
[
"MIT"
] | 2 |
2021-01-20T08:31:33.000Z
|
2022-03-14T14:08:07.000Z
| 12.769231 | 38 | 0.73494 | 1,002,280 |
package nl.stokpop.afterburner.domain;
import lombok.Value;
@Value
public class BurnerMessage {
String message;
String name;
long durationInMillis;
}
|
924276e0568849a033ba68e79f36ab840830d373
| 1,726 |
java
|
Java
|
app/src/main/java/com/clover_studio/spikachatmodule/robospice/api/MessagesApi.java
|
cloverstudio/SpikaAndroid2
|
cc4aa395a5bd6d384ec0b364eb5c4531676d7a62
|
[
"MIT"
] | 41 |
2015-01-10T16:51:32.000Z
|
2018-12-12T13:11:46.000Z
|
app/src/main/java/com/clover_studio/spikachatmodule/robospice/api/MessagesApi.java
|
cloverstudio/SpikaAndroid2
|
cc4aa395a5bd6d384ec0b364eb5c4531676d7a62
|
[
"MIT"
] | 11 |
2015-01-01T16:56:16.000Z
|
2015-05-11T03:44:31.000Z
|
app/src/main/java/com/clover_studio/spikachatmodule/robospice/api/MessagesApi.java
|
cloverstudio/SpikaAndroid2
|
cc4aa395a5bd6d384ec0b364eb5c4531676d7a62
|
[
"MIT"
] | 79 |
2015-01-02T14:01:49.000Z
|
2018-05-15T20:35:44.000Z
| 30.280702 | 124 | 0.661066 | 1,002,281 |
package com.clover_studio.spikachatmodule.robospice.api;
import com.clover_studio.spikachatmodule.base.SpikaApp;
import com.clover_studio.spikachatmodule.models.GetMessagesModel;
import com.clover_studio.spikachatmodule.robospice.spice.CustomSpiceRequest;
import com.clover_studio.spikachatmodule.utils.Const;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import java.net.URI;
/**
* Created by ubuntu_ivo on 22.07.15..
*/
public class MessagesApi {
public static class GetMessages extends CustomSpiceRequest<GetMessagesModel> {
String roomId;
String lastMessageId;
public GetMessages(String roomId, String lastMessageId) {
super(GetMessagesModel.class);
this.roomId = roomId;
this.lastMessageId = lastMessageId;
}
@Override
public GetMessagesModel loadDataFromNetwork() throws Exception {
String url = SpikaApp.getConfig().apiBaseUrl + Const.Api.MESSAGES + "/" + roomId;
if(lastMessageId != null) {
url = url + "/" + lastMessageId;
}else{
url = url + "/0";
}
URI uri = new URI(url);
// LogCS.d("LOG", "req: " + url);
HttpEntity<?> entity = new HttpEntity<>(null, getHeaders());
ResponseEntity responseEntity = getRestTemplate().exchange(uri, HttpMethod.GET, entity, GetMessagesModel.class);
GetMessagesModel response = (GetMessagesModel) responseEntity.getBody();
// LogCS.responseE(uri, getRestTemplate(), HttpMethod.GET, entity);
return response;
}
}
}
|
924276fbc33bf1c72d8b30bc42c1a12d89776f13
| 1,328 |
java
|
Java
|
src/org/usfirst/frc190/CurrentRobotProject/commands/PivotRaise.java
|
Team-190/2k14-robot-code
|
8162a0892c6e35da332ad3d9b343d79951f58a59
|
[
"BSD-3-Clause"
] | null | null | null |
src/org/usfirst/frc190/CurrentRobotProject/commands/PivotRaise.java
|
Team-190/2k14-robot-code
|
8162a0892c6e35da332ad3d9b343d79951f58a59
|
[
"BSD-3-Clause"
] | null | null | null |
src/org/usfirst/frc190/CurrentRobotProject/commands/PivotRaise.java
|
Team-190/2k14-robot-code
|
8162a0892c6e35da332ad3d9b343d79951f58a59
|
[
"BSD-3-Clause"
] | null | null | null | 31.619048 | 73 | 0.649096 | 1,002,282 |
//This command raises the pivot until the button is released or it hits
//the upper limit switch
package org.usfirst.frc190.CurrentRobotProject.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc190.CurrentRobotProject.Robot;
import org.usfirst.frc190.CurrentRobotProject.ArduinoMessages;
public class PivotRaise extends Command {
public boolean isManual;
double motorSpeed = 0.8;
public PivotRaise() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
isManual = false;
}
public PivotRaise(boolean run) {
isManual = true;
}
protected void initialize() {
if(Robot.oi.manualSwitch.get()||!isManual){
Robot.I2CComm.sendMessage(ArduinoMessages.RAISING_PIVOT);
Robot.pivot.disable();
Robot.collector.setRollerSpeed(0);
}
}
protected void execute() {
if(Robot.oi.manualSwitch.get()||!isManual){
Robot.pivot.setMotor(motorSpeed);
}
}
protected boolean isFinished() {
return Robot.pivot.topLimitSwitchPressed();
}
protected void end() {
Robot.pivot.setMotor(0);
}
protected void interrupted() {
end();
}
}
|
924277d3a340b45f8d69666731936764fdf449f1
| 3,519 |
java
|
Java
|
krati-main/src/main/java/krati/store/DataStoreHandler.java
|
JLLeitschuh/krati
|
1ca0f994a7b0c8215b827eac9aaf95789ec08d21
|
[
"Apache-2.0"
] | 37 |
2015-01-27T16:21:31.000Z
|
2022-01-25T21:28:14.000Z
|
krati-main/src/main/java/krati/store/DataStoreHandler.java
|
JLLeitschuh/krati
|
1ca0f994a7b0c8215b827eac9aaf95789ec08d21
|
[
"Apache-2.0"
] | 1 |
2019-07-02T17:21:54.000Z
|
2019-07-02T17:21:54.000Z
|
krati-main/src/main/java/krati/store/DataStoreHandler.java
|
JLLeitschuh/krati
|
1ca0f994a7b0c8215b827eac9aaf95789ec08d21
|
[
"Apache-2.0"
] | 14 |
2015-07-20T15:42:20.000Z
|
2021-03-08T01:45:06.000Z
| 31.419643 | 115 | 0.622052 | 1,002,283 |
/*
* Copyright (c) 2010-2012 LinkedIn, 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 krati.store;
import java.util.List;
import java.util.Map.Entry;
/**
* DataStoreHandler
*
* @author jwu
*
* <p>
* 06/13, 2012 - Added javadoc <br/>
*/
public interface DataStoreHandler extends DataHandler {
/**
* Assembles the specified <code>key</code> and <code>value</code> into a byte array.
*
* @param key - the key
* @param value - the value
* @return the resulting byte array
*/
public byte[] assemble(byte[] key, byte[] value);
/**
* Assembles the specified <code>key</code> and <code>value</code> into a byte array
* which is then combined with the specified <code>data</code> into the resulting byte array.
*
* @param key - the key
* @param value - the value
* @param data - the assembled data
* @return the resulting byte array
*/
public byte[] assemble(byte[] key, byte[] value, byte[] data);
/**
* Counts the number of collisions of the specified <code>key</code> in the <code>data</code>.
*
* @param key - the key
* @param data - the assembled data
* @return the number of keys found in the specified <code>data</code> if the specified <code>key</code>
* is found. Otherwise, the negative number of keys found in the <code>data</code>.
*/
public int countCollisions(byte[] key, byte[] data);
/**
* Extracts the value mapped to the specified <code>key</code>.
*
* @param key - the key
* @param data - the assembled data
* @return the value
*/
public byte[] extractByKey(byte[] key, byte[] data);
/**
* Removes the specified <code>key</code> and its value from the specified <code>data</code>.
*
* @param key - the key
* @param data - the assembled data
* @return the number of bytes left in the <code>data</code> after removing the <code>key</code> and its value.
*/
public int removeByKey(byte[] key, byte[] data);
/**
* Extracts the keys from the specified <code>data</code>.
*
* @param data - the assembled data
* @return a list of keys.
*/
public List<byte[]> extractKeys(byte[] data);
/**
* Extracts the values from the specified <code>data</code>.
*
* @param data - the assembled data
* @return a list of values.
*/
public List<byte[]> extractValues(byte[] data);
/**
* Extracts the mappings from the specified <code>data</code>.
*
* @param data - the assembled data
* @return a list of Map.Entry values.
*/
public List<Entry<byte[], byte[]>> extractEntries(byte[] data);
/**
* Assembles a list of mappings into a byte array.
*
* @param entries - the list of mappings
* @return the resulting byte array
*/
public byte[] assembleEntries(List<Entry<byte[], byte[]>> entries);
}
|
924277dcfc5d5f8c8698b5f03c3e3a5148769070
| 585 |
java
|
Java
|
archive/librmi-java/src/id/web/edom/rmi/ProtocolException.java
|
edom/work
|
df55868caa436efc631e145a43e833220b8da1d0
|
[
"Apache-2.0",
"CC0-1.0"
] | null | null | null |
archive/librmi-java/src/id/web/edom/rmi/ProtocolException.java
|
edom/work
|
df55868caa436efc631e145a43e833220b8da1d0
|
[
"Apache-2.0",
"CC0-1.0"
] | 4 |
2020-12-02T18:37:37.000Z
|
2022-02-16T00:55:32.000Z
|
archive/librmi-java/src/id/web/edom/rmi/ProtocolException.java
|
edom/work
|
df55868caa436efc631e145a43e833220b8da1d0
|
[
"Apache-2.0",
"CC0-1.0"
] | 1 |
2018-10-02T15:20:22.000Z
|
2018-10-02T15:20:22.000Z
| 17.727273 | 62 | 0.635897 | 1,002,284 |
package id.web.edom.rmi;
/**
* <p>Thrown when the receiver detects
* a violation of the protocol specification.</p>
*
* @author erik
*/
public class ProtocolException extends RmiException
{
private static final long serialVersionUID = 1L;
public ProtocolException ()
{
super();
}
public ProtocolException (String message, Throwable cause)
{
super(message, cause);
}
public ProtocolException (String message)
{
super(message);
}
public ProtocolException (Throwable cause)
{
super(cause);
}
}
|
9242788c5e022da0b942e41eda99f90deb9e9185
| 51,971 |
java
|
Java
|
jsonlib-to-easyjson/src/main/java/net/sf/json/JSONArray.java
|
jxt4995038/easyjson
|
c73583f498bd54dabf7c5c406329166e27c215d5
|
[
"Apache-2.0"
] | 86 |
2019-06-11T05:43:55.000Z
|
2022-03-31T05:12:50.000Z
|
jsonlib-to-easyjson/src/main/java/net/sf/json/JSONArray.java
|
jxt4995038/easyjson
|
c73583f498bd54dabf7c5c406329166e27c215d5
|
[
"Apache-2.0"
] | 46 |
2019-06-24T22:54:21.000Z
|
2022-03-31T21:39:24.000Z
|
jsonlib-to-easyjson/src/main/java/net/sf/json/JSONArray.java
|
jxt4995038/easyjson
|
c73583f498bd54dabf7c5c406329166e27c215d5
|
[
"Apache-2.0"
] | 15 |
2019-11-28T06:27:14.000Z
|
2021-11-05T05:42:04.000Z
| 32.583699 | 137 | 0.588097 | 1,002,285 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache, 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.gnu.org/licenses/lgpl-3.0.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.json;
import com.jn.easyjson.core.JSONBuilderProvider;
import com.jn.langx.util.reflect.type.Primitives;
import net.sf.json.easyjson.JsonMapper;
import net.sf.json.util.JSONUtils;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>element</code> methods
* for adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONNull object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws
* an exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and
* type coersion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there is
* <code>,</code> <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a
* quote or single quote, and if they do not contain leading or trailing spaces,
* and if they do not contain any of these characters:
* <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers and
* if they are not the reserved words <code>true</code>, <code>false</code>,
* or <code>null</code>.</li>
* <li>Values can be separated by <code>;</code> <small>(semicolon)</small>
* as well as by <code>,</code> <small>(comma)</small>.</li>
* <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
* <code>0x-</code> <small>(hex)</small> prefix.</li>
* <li>Comments written in the slashshlash, slashstar, and hash conventions
* will be ignored.</li>
* </ul>
*
* @author JSON.org
*/
public final class JSONArray extends AbstractJSON implements JSON, List, Comparable {
/**
* Creates a JSONArray.<br>
* Inspects the object type to call the correct JSONArray factory method.
* Accepts JSON formatted strings, arrays, Collections and Enums.
*
* @param object
* @throws JSONException if the object can not be converted to a proper
* JSONArray.
*/
public static JSONArray fromObject(Object object) {
return fromObject(object, new JsonConfig());
}
/**
* Creates a JSONArray.<br>
* Inspects the object type to call the correct JSONArray factory method.
* Accepts JSON formatted strings, arrays, Collections and Enums.
*
* @param object
* @throws JSONException if the object can not be converted to a proper
* JSONArray.
*/
public static JSONArray fromObject(Object object, JsonConfig jsonConfig) {
Object jsonobj = JsonMapper.fromJavaObject(object, jsonConfig);
JSONArray jsonArray = new JSONArray();
if (jsonobj != JSONNull.getInstance()) {
if (Primitives.isPrimitive(jsonobj.getClass())) {
jsonArray.element(jsonobj);
}
if (jsonobj instanceof JSONArray) {
return (JSONArray) jsonobj;
}
if (jsonobj instanceof JSONObject) {
jsonArray.element(jsonobj);
}
}
return jsonArray;
}
/**
* Get the collection type from a getter or setter, or null if no type was
* found.<br/>
* Contributed by [Matt Small @ WaveMaker].
*/
public static Class[] getCollectionType(PropertyDescriptor pd, boolean useGetter)
throws JSONException {
Type type;
if (useGetter) {
Method m = pd.getReadMethod();
type = m.getGenericReturnType();
} else {
Method m = pd.getWriteMethod();
Type[] gpts = m.getGenericParameterTypes();
if (1 != gpts.length) {
throw new JSONException("method " + m + " is not a standard setter");
}
type = gpts[0];
}
if (!(type instanceof ParameterizedType)) {
return null;
// throw new JSONException("type not instanceof ParameterizedType:
// "+type.getClass());
}
ParameterizedType pType = (ParameterizedType) type;
Type[] actualTypes = pType.getActualTypeArguments();
Class[] ret = new Class[actualTypes.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = (Class) actualTypes[i];
}
return ret;
}
/**
* Returns the number of dimensions suited for a java array.
*/
public static int[] getDimensions(JSONArray jsonArray) {
// short circuit for empty arrays
if (jsonArray == null || jsonArray.isEmpty()) {
return new int[]{0};
}
List dims = new ArrayList();
processArrayDimensions(jsonArray, dims, 0);
int[] dimensions = new int[dims.size()];
int j = 0;
for (Iterator i = dims.iterator(); i.hasNext(); ) {
dimensions[j++] = ((Integer) i.next()).intValue();
}
return dimensions;
}
/**
* Creates a java array from a JSONArray.
*/
public static Object toArray(JSONArray jsonArray) {
return toArray(jsonArray, new JsonConfig());
}
/**
* Creates a java array from a JSONArray.
*/
public static Object toArray(JSONArray jsonArray, Class objectClass) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(objectClass);
return toArray(jsonArray, jsonConfig);
}
/**
* Creates a java array from a JSONArray.<br>
* Any attribute is a JSONObject and matches a key in the classMap, it will
* be converted to that target class.<br>
* The classMap has the following conventions:
* <ul>
* <li>Every key must be an String.</li>
* <li>Every value must be a Class.</li>
* <li>A key may be a regular expression.</li>
* </ul>
*/
public static Object toArray(JSONArray jsonArray, Class objectClass, Map classMap) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(objectClass);
jsonConfig.setClassMap(classMap);
return toArray(jsonArray, jsonConfig);
}
/**
* Creates a java array from a JSONArray.<br>
*/
public static Object toArray(JSONArray jsonArray, JsonConfig jsonConfig) {
List list = toList(jsonArray, jsonConfig);
return list.toArray(new Object[list.size()]);
}
/**
* Creates a java array from a JSONArray.<br>
*/
public static Object toArray(JSONArray jsonArray, Object root, JsonConfig jsonConfig) {
Class clazz = jsonConfig.getRootClass();
if (root != null && root.getClass() != clazz) {
jsonConfig.setRootClass(root.getClass());
}
return toArray(jsonArray, jsonConfig);
}
/**
* Returns a List or a Set taking generics into account.<br/>
*/
public static Collection toCollection(JSONArray jsonArray) {
return toCollection(jsonArray, new JsonConfig());
}
/**
* Returns a List or a Set taking generics into account.<br/>
*/
public static Collection toCollection(JSONArray jsonArray, Class objectClass) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(objectClass);
return toCollection(jsonArray, jsonConfig);
}
/**
* Returns a List or a Set taking generics into account.<br/>
* Contributed by [Matt Small @ WaveMaker].
*/
public static Collection toCollection(JSONArray jsonArray, JsonConfig jsonConfig) {
com.jn.easyjson.core.JSON json = JsonMapper.buildJSON(jsonConfig);
if (jsonConfig.getRootClass() != null) {
return json.fromJsonTreeNode(JsonMapper.toJsonTreeNode(jsonArray), jsonConfig.getRootClass());
} else {
return (Collection) JsonMapper.toJavaObject(jsonArray, jsonConfig);
}
}
public static Collection toCollection(JSONArray jsonArray, Object root, JsonConfig jsonConfig) {
Class clazz = jsonConfig.getRootClass();
if (root != null && root.getClass() != clazz) {
jsonConfig.setRootClass(root.getClass());
}
return toCollection(jsonArray, jsonConfig);
}
/**
* Creates a List from a JSONArray.<br>
*
* @see #toCollection(JSONArray)
* @deprecated replaced by toCollection
*/
public static List toList(JSONArray jsonArray) {
return toList(jsonArray, new JsonConfig());
}
/**
* Creates a List from a JSONArray.
*
* @see #toCollection(JSONArray, Class)
* @deprecated replaced by toCollection
*/
public static List toList(JSONArray jsonArray, Class objectClass) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(objectClass);
return toList(jsonArray, jsonConfig);
}
/**
* Creates a List from a JSONArray.<br>
* Any attribute is a JSONObject and matches a key in the classMap, it will
* be converted to that target class.<br>
* The classMap has the following conventions:
* <ul>
* <li>Every key must be an String.</li>
* <li>Every value must be a Class.</li>
* <li>A key may be a regular expression.</li>
* </ul>
*
* @deprecated replaced by toCollection
*/
public static List toList(JSONArray jsonArray, Class objectClass, Map classMap) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(objectClass);
jsonConfig.setClassMap(classMap);
return toList(jsonArray, jsonConfig);
}
/**
* Creates a List from a JSONArray.<br>
*
* @see #toCollection(JSONArray, JsonConfig)
* @deprecated replaced by toCollection
*/
public static List toList(JSONArray jsonArray, JsonConfig jsonConfig) {
Collection collection = toCollection(jsonArray, jsonConfig);
if (collection != null) {
if (collection instanceof List) {
return (List) collection;
} else {
return new ArrayList(collection);
}
} else {
return Collections.emptyList();
}
}
/**
* Creates a List from a JSONArray.<br>
*/
public static List toList(JSONArray jsonArray, Object root, JsonConfig jsonConfig) {
Class clazz = jsonConfig.getRootClass();
if (root != null && root.getClass() != clazz) {
jsonConfig.setRootClass(root.getClass());
}
return toList(jsonArray, jsonConfig);
}
private static void processArrayDimensions(JSONArray jsonArray, List dims, int index) {
if (dims.size() <= index) {
dims.add(new Integer(jsonArray.size()));
} else {
int i = ((Integer) dims.get(index)).intValue();
if (jsonArray.size() > i) {
dims.set(index, new Integer(jsonArray.size()));
}
}
for (Iterator i = jsonArray.iterator(); i.hasNext(); ) {
Object item = i.next();
if (item instanceof JSONArray) {
processArrayDimensions((JSONArray) item, dims, index + 1);
}
}
}
// ------------------------------------------------------
/**
* The List where the JSONArray's properties are kept.
*/
private List elements;
/**
* A flag for XML processing.
*/
private boolean expandElements;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.elements = new ArrayList();
}
@Override
public void add(int index, Object value) {
add(index, value, new JsonConfig());
}
public void add(int index, Object value, JsonConfig jsonConfig) {
this.elements.add(index, processValue(value, jsonConfig));
}
@Override
public boolean add(Object value) {
return add(value, new JsonConfig());
}
public boolean add(Object value, JsonConfig jsonConfig) {
element(value, jsonConfig);
return true;
}
@Override
public boolean addAll(Collection collection) {
return addAll(collection, new JsonConfig());
}
public boolean addAll(Collection collection, JsonConfig jsonConfig) {
if (collection == null || collection.size() == 0) {
return false;
}
for (Iterator i = collection.iterator(); i.hasNext(); ) {
element(i.next(), jsonConfig);
}
return true;
}
@Override
public boolean addAll(int index, Collection collection) {
return addAll(index, collection, new JsonConfig());
}
public boolean addAll(int index, Collection collection, JsonConfig jsonConfig) {
if (collection == null || collection.size() == 0) {
return false;
}
int offset = 0;
for (Iterator i = collection.iterator(); i.hasNext(); ) {
this.elements.add(index + (offset++), processValue(i.next(), jsonConfig));
}
return true;
}
@Override
public void clear() {
elements.clear();
}
@Override
public int compareTo(Object obj) {
if (obj != null && (obj instanceof JSONArray)) {
JSONArray other = (JSONArray) obj;
int size1 = size();
int size2 = other.size();
if (size1 < size2) {
return -1;
} else if (size1 > size2) {
return 1;
} else if (this.equals(other)) {
return 0;
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return contains(o, new JsonConfig());
}
public boolean contains(Object o, JsonConfig jsonConfig) {
return elements.contains(processValue(o, jsonConfig));
}
@Override
public boolean containsAll(Collection collection) {
return containsAll(collection, new JsonConfig());
}
public boolean containsAll(Collection collection, JsonConfig jsonConfig) {
return elements.containsAll(fromObject(collection, jsonConfig));
}
/**
* Remove an element, if present.
*
* @param index the index of the element.
* @return this.
*/
public JSONArray discard(int index) {
elements.remove(index);
return this;
}
/**
* Remove an element, if present.
*
* @return this.
*/
public JSONArray discard(Object o) {
elements.remove(o);
return this;
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value A boolean value.
* @return this.
*/
public JSONArray element(boolean value) {
return element(value ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Append a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value A Collection value.
* @return this.
*/
public JSONArray element(Collection value) {
return element(value, new JsonConfig());
}
/**
* Append a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value A Collection value.
* @return this.
*/
public JSONArray element(Collection value, JsonConfig jsonConfig) {
if (value instanceof JSONArray) {
elements.add(value);
return this;
} else {
return element(JsonMapper.fromJavaObject(value));
}
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value A double value.
* @return this.
* @throws JSONException if the value is not finite.
*/
public JSONArray element(double value) {
Double d = new Double(value);
JSONUtils.testValidity(d);
return element(d);
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value An int value.
* @return this.
*/
public JSONArray element(int value) {
return element(new Integer(value));
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index The subscript.
* @param value A boolean value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray element(int index, boolean value) {
return element(index, value ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is
* produced from a Collection.
*
* @param index The subscript.
* @param value A Collection value.
* @return this.
* @throws JSONException If the index is negative or if the value is not
* finite.
*/
public JSONArray element(int index, Collection value) {
return element(index, value, new JsonConfig());
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is
* produced from a Collection.
*
* @param index The subscript.
* @param value A Collection value.
* @return this.
* @throws JSONException If the index is negative or if the value is not
* finite.
*/
public JSONArray element(int index, Collection value, JsonConfig jsonConfig) {
if (value instanceof JSONArray) {
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < size()) {
elements.set(index, value);
} else {
while (index != size()) {
element(JSONNull.getInstance());
}
element(value, jsonConfig);
}
return this;
} else {
return element(index, JsonMapper.fromJavaObject(value, jsonConfig));
}
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index The subscript.
* @param value A double value.
* @return this.
* @throws JSONException If the index is negative or if the value is not
* finite.
*/
public JSONArray element(int index, double value) {
return element(index, new Double(value));
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index The subscript.
* @param value An int value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray element(int index, int value) {
return element(index, new Integer(value));
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index The subscript.
* @param value A long value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray element(int index, long value) {
return element(index, new Long(value));
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param index The subscript.
* @param value The Map value.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, Map value) {
return element(index, value, new JsonConfig());
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param index The subscript.
* @param value The Map value.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, Map value, JsonConfig jsonConfig) {
if (value instanceof JSONObject) {
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < size()) {
elements.set(index, value);
} else {
while (index != size()) {
element(JSONNull.getInstance());
}
element(value, jsonConfig);
}
return this;
} else {
return element(index, JSONObject.fromObject(value, jsonConfig));
}
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index The subscript.
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, Object value) {
return element(index, value, new JsonConfig());
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index The subscript.
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, Object value, JsonConfig jsonConfig) {
JSONUtils.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < size()) {
this.elements.set(index, processValue(value, jsonConfig));
} else {
while (index != size()) {
element(JSONNull.getInstance());
}
element(value, jsonConfig);
}
return this;
}
/**
* Put or replace a String value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.<br>
* The string may be a valid JSON formatted string, in tha case, it will be
* transformed to a JSONArray, JSONObject or JSONNull.
*
* @param index The subscript.
* @param value A String value.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, String value) {
return element(index, value, new JsonConfig());
}
/**
* Put or replace a String value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.<br>
* The string may be a valid JSON formatted string, in tha case, it will be
* transformed to a JSONArray, JSONObject or JSONNull.
*
* @param index The subscript.
* @param value A String value.
* @return this.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray element(int index, String value, JsonConfig jsonConfig) {
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < size()) {
if (value == null) {
this.elements.set(index, "");
} else if (JSONUtils.mayBeJSON(value)) {
try {
this.elements.set(index, JSONSerializer.toJSON(value, jsonConfig));
} catch (JSONException jsone) {
this.elements.set(index, JSONUtils.stripQuotes(value));
}
} else {
this.elements.set(index, JSONUtils.stripQuotes(value));
}
} else {
while (index != size()) {
element(JSONNull.getInstance());
}
element(value, jsonConfig);
}
return this;
}
/**
* Append an JSON value. This increases the array's length by one.
*
* @param value An JSON value.
* @return this.
*/
public JSONArray element(JSONNull value) {
this.elements.add(value);
return this;
}
/**
* Append an JSON value. This increases the array's length by one.
*
* @param value An JSON value.
* @return this.
*/
public JSONArray element(JSONObject value) {
this.elements.add(value);
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value A long value.
* @return this.
*/
public JSONArray element(long value) {
return element(JSONUtils.transformNumber(new Long(value)));
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value A Map value.
* @return this.
*/
public JSONArray element(Map value) {
return element(value, new JsonConfig());
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value A Map value.
* @return this.
*/
public JSONArray element(Map value, JsonConfig jsonConfig) {
if (value instanceof JSONObject) {
elements.add(value);
return this;
} else {
return element(JSONObject.fromObject(value, jsonConfig));
}
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
*/
public JSONArray element(Object value) {
return element(value, new JsonConfig());
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
*/
public JSONArray element(Object value, JsonConfig jsonConfig) {
return addValue(value, jsonConfig);
}
/**
* Append a String value. This increases the array's length by one.<br>
* The string may be a valid JSON formatted string, in tha case, it will be
* transformed to a JSONArray, JSONObject or JSONNull.
*
* @param value A String value.
* @return this.
*/
public JSONArray element(String value) {
return element(value, new JsonConfig());
}
/**
* Append a String value. This increases the array's length by one.<br>
* The string may be a valid JSON formatted string, in tha case, it will be
* transformed to a JSONArray, JSONObject or JSONNull.
*
* @param value A String value.
* @return this.
*/
public JSONArray element(String value, JsonConfig jsonConfig) {
if (value == null) {
this.elements.add("");
} else if (JSONUtils.hasQuotes(value)) {
this.elements.add(value);
} else if (JSONNull.getInstance().equals(value)) {
this.elements.add(JSONNull.getInstance());
} else if (JSONUtils.isJsonKeyword(value, jsonConfig)) {
if (jsonConfig.isJavascriptCompliant() && "undefined".equals(value)) {
this.elements.add(JSONNull.getInstance());
} else {
this.elements.add(value);
}
} else if (JSONUtils.mayBeJSON(value)) {
try {
this.elements.add(JSONSerializer.toJSON(value, jsonConfig));
} catch (JSONException jsone) {
this.elements.add(value);
}
} else {
this.elements.add(value);
}
return this;
}
@Override
public boolean equals(Object obj) {
return true;
}
/**
* Get the object value associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return An object value.
*/
@Override
public Object get(int index) {
/*
* Object o = opt( index ); if( o == null ){ throw new JSONException(
* "JSONArray[" + index + "] not found." ); } return o;
*/
return this.elements.get(index);
}
/**
* Get the boolean value associated with an index. The string values "true"
* and "false" are converted to boolean.
*
* @param index The index must be between 0 and size() - 1.
* @return The truth.
* @throws JSONException If there is no value for the index or if the value
* is not convertable to boolean.
*/
public boolean getBoolean(int index) {
Object o = get(index);
if (o != null) {
if (o.equals(Boolean.FALSE)
|| (o instanceof String && ((String) o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE)
|| (o instanceof String && ((String) o).equalsIgnoreCase("true"))) {
return true;
}
}
throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot be
* converted to a number.
*/
public double getDouble(int index) {
Object o = get(index);
if (o != null) {
try {
return o instanceof Number ? ((Number) o).doubleValue()
: Double.parseDouble((String) o);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
/**
* Get the int value associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot be
* converted to a number. if the value cannot be converted to a
* number.
*/
public int getInt(int index) {
Object o = get(index);
if (o != null) {
return o instanceof Number ? ((Number) o).intValue() : (int) getDouble(index);
}
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
/**
* Get the JSONArray associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return A JSONArray value.
* @throws JSONException If there is no value for the index. or if the value
* is not a JSONArray
*/
public JSONArray getJSONArray(int index) {
Object o = get(index);
if (o != null && o instanceof JSONArray) {
return (JSONArray) o;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
*
* @param index subscript
* @return A JSONObject value.
* @throws JSONException If there is no value for the index or if the value
* is not a JSONObject
*/
public JSONObject getJSONObject(int index) {
Object o = get(index);
if (JSONNull.getInstance()
.equals(o)) {
return new JSONObject(true);
} else if (o instanceof JSONObject) {
return (JSONObject) o;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot be
* converted to a number.
*/
public long getLong(int index) {
Object o = get(index);
if (o != null) {
return o instanceof Number ? ((Number) o).longValue() : (long) getDouble(index);
}
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
/**
* Get the string associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return A string value.
* @throws JSONException If there is no value for the index.
*/
public String getString(int index) {
Object o = get(index);
if (o != null) {
return o.toString();
}
throw new JSONException("JSONArray[" + index + "] not found.");
}
@Override
public int hashCode() {
int hashcode = 29;
for (Iterator e = elements.iterator(); e.hasNext(); ) {
Object element = e.next();
hashcode += JSONUtils.hashCode(element);
}
return hashcode;
}
@Override
public int indexOf(Object o) {
return elements.indexOf(o);
}
@Override
public boolean isArray() {
return true;
}
@Override
public boolean isEmpty() {
return this.elements.isEmpty();
}
public boolean isExpandElements() {
return expandElements;
}
/**
* Returns an Iterator for this JSONArray
*/
@Override
public Iterator iterator() {
return new JSONArrayListIterator();
}
@Override
public int lastIndexOf(Object o) {
return elements.lastIndexOf(o);
}
@Override
public ListIterator listIterator() {
return listIterator(0);
}
@Override
public ListIterator listIterator(int index) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException("Index: " + index);
}
return new JSONArrayListIterator(index);
}
/**
* Get the optional object value associated with an index.
*
* @param index The index must be between 0 and size() - 1.
* @return An object value, or null if there is no object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= size()) ? null : this.elements.get(index);
}
/**
* Get the optional boolean value associated with an index. It returns false
* if there is no value at that index, or if the value is not Boolean.TRUE or
* the String "true".
*
* @param index The index must be between 0 and size() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index. It returns the
* defaultValue if there is no value at that index or if it is not a Boolean
* or the String "true" or "false" (case insensitive).
*
* @param index The index must be between 0 and size() - 1.
* @param defaultValue A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index. NaN is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
*/
public double optDouble(int index) {
return optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index. The defaultValue
* is returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index subscript
* @param defaultValue The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
*/
public int optInt(int index) {
return optInt(index, 0);
}
/**
* Get the optional int value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index The index must be between 0 and size() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
*
* @param index subscript
* @return A JSONArray value, or null if the index has no value, or if the
* value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
/**
* Get the optional JSONObject associated with an index. Null is returned if
* the key is not found, or null if the index has no value, or if the value
* is not a JSONObject.
*
* @param index The index must be between 0 and size() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
/**
* Get the optional long value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index The index must be between 0 and size() - 1.
* @return The value.
*/
public long optLong(int index) {
return optLong(index, 0);
}
/**
* Get the optional long value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index The index must be between 0 and size() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value is not a
* string and is not null, then it is coverted to a string.
*
* @param index The index must be between 0 and size() - 1.
* @return A String value.
*/
public String optString(int index) {
return optString(index, "");
}
/**
* Get the optional string associated with an index. The defaultValue is
* returned if the key is not found.
*
* @param index The index must be between 0 and size() - 1.
* @param defaultValue The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object o = opt(index);
return o != null ? o.toString() : defaultValue;
}
@Override
public Object remove(int index) {
return elements.remove(index);
}
@Override
public boolean remove(Object o) {
return elements.remove(o);
}
@Override
public boolean removeAll(Collection collection) {
return removeAll(collection, new JsonConfig());
}
public boolean removeAll(Collection collection, JsonConfig jsonConfig) {
return elements.removeAll(fromObject(collection, jsonConfig));
}
@Override
public boolean retainAll(Collection collection) {
return retainAll(collection, new JsonConfig());
}
public boolean retainAll(Collection collection, JsonConfig jsonConfig) {
return elements.retainAll(fromObject(collection, jsonConfig));
}
@Override
public Object set(int index, Object value) {
return set(index, value, new JsonConfig());
}
public Object set(int index, Object value, JsonConfig jsonConfig) {
Object previous = get(index);
element(index, value, jsonConfig);
return previous;
}
public void setExpandElements(boolean expandElements) {
this.expandElements = expandElements;
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
@Override
public int size() {
return this.elements.size();
}
@Override
public List subList(int fromIndex, int toIndex) {
return elements.subList(fromIndex, toIndex);
}
/**
* Produce an Object[] with the contents of this JSONArray.
*/
@Override
public Object[] toArray() {
return this.elements.toArray();
}
@Override
public Object[] toArray(Object[] array) {
return elements.toArray(array);
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values of
* this JSONArray.
*
* @param names A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) {
if (names == null || names.size() == 0 || size() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.size(); i++) {
jo.element(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no unnecessary
* whitespace is added. If it is not possible to produce a syntactically
* correct JSON text then null will be returned instead. This could occur if
* the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable representation of the
* array.
*/
@Override
public String toString() {
return JSONBuilderProvider.simplest().toJson(JsonMapper.toJsonTreeNode(this));
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical.
*
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, transmittable representation of the
* object, beginning with <code>[</code> <small>(left
* bracket)</small> and ending with <code>]</code> <small>(right
* bracket)</small>.
* @throws JSONException
*/
@Override
public String toString(int indentFactor) {
return JSONBuilderProvider.create().prettyFormat(indentFactor > 0).build().toJson(JsonMapper.toJsonTreeNode(this));
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical.
*
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indention of the top level.
* @return a printable, displayable, transmittable representation of the
* array.
* @throws JSONException
*/
@Override
public String toString(int indentFactor, int indent) {
return JSONBuilderProvider.create().prettyFormat(indentFactor > 0 || indent > 0).build().toJson(JsonMapper.toJsonTreeNode(this));
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
@Override
public Writer write(Writer writer) {
String str = toString();
try {
writer.write(str);
} catch (IOException e) {
throw new JSONException(e);
}
return writer;
}
/**
* Adds a String without performing any conversion on it.
*/
protected JSONArray addString(String str) {
if (str != null) {
elements.add(str);
}
return this;
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
*/
private JSONArray _addValue(Object value, JsonConfig jsonConfig) {
this.elements.add(value);
return this;
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, JSONFunction, Long, String,
* JSONString or the JSONNull object.
* @return this.
*/
private JSONArray addValue(Object value, JsonConfig jsonConfig) {
return _addValue(processValue(value, jsonConfig), jsonConfig);
}
private Object processValue(Object value, JsonConfig jsonConfig) {
return JsonMapper.fromJavaObject(value, jsonConfig);
}
private class JSONArrayListIterator implements ListIterator {
int currentIndex = 0;
int lastIndex = -1;
JSONArrayListIterator() {
}
JSONArrayListIterator(int index) {
currentIndex = index;
}
@Override
public boolean hasNext() {
return currentIndex != size();
}
@Override
public Object next() {
try {
Object next = get(currentIndex);
lastIndex = currentIndex++;
return next;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
if (lastIndex == -1) {
throw new IllegalStateException();
}
try {
JSONArray.this.remove(lastIndex);
if (lastIndex < currentIndex) {
currentIndex--;
}
lastIndex = -1;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasPrevious() {
return currentIndex != 0;
}
@Override
public Object previous() {
try {
int index = currentIndex - 1;
Object previous = get(index);
lastIndex = currentIndex = index;
return previous;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
@Override
public int nextIndex() {
return currentIndex;
}
@Override
public int previousIndex() {
return currentIndex - 1;
}
@Override
public void set(Object obj) {
if (lastIndex == -1) {
throw new IllegalStateException();
}
try {
JSONArray.this.set(lastIndex, obj);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void add(Object obj) {
try {
JSONArray.this.add(currentIndex++, obj);
lastIndex = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
}
|
924278e8b3f2f40359da25d37e8c30d986945267
| 1,741 |
java
|
Java
|
src/test/java/com/android/tools/r8/ir/optimize/ThrowNPEWithMessageIfParameterIsNullTest.java
|
ganadist/r8
|
850b5a4725954b677103a3a575239d0f330c0b0f
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 8 |
2019-02-16T19:27:05.000Z
|
2020-10-30T20:10:42.000Z
|
src/test/java/com/android/tools/r8/ir/optimize/ThrowNPEWithMessageIfParameterIsNullTest.java
|
ganadist/r8
|
850b5a4725954b677103a3a575239d0f330c0b0f
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
src/test/java/com/android/tools/r8/ir/optimize/ThrowNPEWithMessageIfParameterIsNullTest.java
|
ganadist/r8
|
850b5a4725954b677103a3a575239d0f330c0b0f
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 5 |
2019-03-03T04:49:03.000Z
|
2021-11-23T15:47:38.000Z
| 29.508475 | 78 | 0.717978 | 1,002,286 |
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.ir.optimize;
import com.android.tools.r8.NeverInline;
import com.android.tools.r8.TestBase;
import com.android.tools.r8.TestParameters;
import com.android.tools.r8.TestParametersCollection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class ThrowNPEWithMessageIfParameterIsNullTest extends TestBase {
private final TestParameters parameters;
@Parameterized.Parameters(name = "{0}")
public static TestParametersCollection data() {
return getTestParameters().withAllRuntimesAndApiLevels().build();
}
public ThrowNPEWithMessageIfParameterIsNullTest(TestParameters parameters) {
this.parameters = parameters;
}
@Test
public void test() throws Exception {
testForR8(parameters.getBackend())
.addInnerClasses(ThrowNPEWithMessageIfParameterIsNullTest.class)
.addKeepMainRule(TestClass.class)
.enableInliningAnnotations()
.setMinApi(parameters.getApiLevel())
.compile()
.run(parameters.getRuntime(), TestClass.class)
.assertSuccessWithOutputLines("Hello world!");
}
static class TestClass {
public static void main(String[] args) {
try {
checkNotNull(null);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@NeverInline
static void checkNotNull(Object o) {
if (o == null) {
throw new NullPointerException("Hello world!");
}
}
}
}
|
924279ca0a5814984cf5819b115d56f683b588f4
| 1,076 |
java
|
Java
|
test/slots/NoteSlotTest.java
|
ehabarman/Vending-Machine
|
39c080b0ccfe1debc324dcd20b82334ded53d422
|
[
"MIT"
] | null | null | null |
test/slots/NoteSlotTest.java
|
ehabarman/Vending-Machine
|
39c080b0ccfe1debc324dcd20b82334ded53d422
|
[
"MIT"
] | null | null | null |
test/slots/NoteSlotTest.java
|
ehabarman/Vending-Machine
|
39c080b0ccfe1debc324dcd20b82334ded53d422
|
[
"MIT"
] | null | null | null | 32.606061 | 91 | 0.659851 | 1,002,287 |
package slots;
import Exceptions.SlotSupportLimitationException;
import enums.Currency;
import org.junit.Test;
import payments.money.Note;
import java.util.ArrayList;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class NoteSlotTest {
@Test
public void NoteSlotTest() {
Note[] acceptableNotes = {new Note(Currency.USD, 20), new Note(Currency.USD, 50)};
NoteSlot noteSlot = new NoteSlot(acceptableNotes);
assertThrows(SlotSupportLimitationException.class, () -> {
noteSlot.insertNote(new Note(Currency.USD, 0.6));
});
Note note = new Note(Currency.USD, 20);
assertEquals(true, noteSlot.insertNote(note) == 20);
note = new Note(Currency.USD, 50);
assertEquals(50, noteSlot.insertNote(note), 0);
assertEquals(70, noteSlot.getInsertedMoney(), 0);
assertEquals(true, noteSlot.refund() instanceof ArrayList);
assertEquals(0.0, noteSlot.getInsertedMoney(), 0);
}
}
|
92427ad0bb0f206f7db0671c10a932f8df4ea7db
| 4,492 |
java
|
Java
|
spring-cache/src/main/java/top/banner/cache/config/SpringCacheConfig.java
|
bannerxu/boot-learning
|
4d0e1ce9f06fe9d8ba87c071a4a6ea67b313b3c0
|
[
"MIT"
] | null | null | null |
spring-cache/src/main/java/top/banner/cache/config/SpringCacheConfig.java
|
bannerxu/boot-learning
|
4d0e1ce9f06fe9d8ba87c071a4a6ea67b313b3c0
|
[
"MIT"
] | null | null | null |
spring-cache/src/main/java/top/banner/cache/config/SpringCacheConfig.java
|
bannerxu/boot-learning
|
4d0e1ce9f06fe9d8ba87c071a4a6ea67b313b3c0
|
[
"MIT"
] | null | null | null | 44.92 | 124 | 0.766474 | 1,002,288 |
package top.banner.cache.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
* @author XGL
*/
@Configuration
@EnableCaching //启动 Cache 功能
public class SpringCacheConfig extends CachingConfigurerSupport {
public static final String DATE_FORMAT_10 = "yyyy-MM-dd";
public static final String DATE_FORMAT_19 = "yyyy-MM-dd HH:mm:ss";
private final ObjectMapper om = new ObjectMapper();
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheManager redisCacheManager = new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
// 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationWithTtl(60 * 5),
// 指定 key 策略
this.getRedisCacheConfigurationMap()
);
redisCacheManager.setTransactionAware(true);
return redisCacheManager;
}
/**
* 处理LocalDateTime的JavaTimeModule
*/
private JavaTimeModule javaTimeModule() {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT_10)));
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT_19)));
javaTimeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT_10)));
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT_19)));
return javaTimeModule;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
// Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
//
// //解决时间序列化问题
// om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// om.registerModule(javaTimeModule());
//
// jackson2JsonRedisSerializer.setObjectMapper(om);
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jdkSerializationRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(16);
redisCacheConfigurationMap.put("users", this.getRedisCacheConfigurationWithTtl(5 * 60));//自定义设置缓存时间
return redisCacheConfigurationMap;
}
}
|
92427b0975cb61d7897ceeab199e5a7454a57f27
| 1,917 |
java
|
Java
|
src/main/java/org/esupportail/esupsignature/dss/service/KeystoreService.java
|
prigaux/esup-signature
|
32b27c36b61ad1dbe42482314ec25cb1d6d46c42
|
[
"Apache-2.0"
] | 8 |
2019-06-03T14:27:34.000Z
|
2022-03-25T14:22:34.000Z
|
src/main/java/org/esupportail/esupsignature/dss/service/KeystoreService.java
|
prigaux/esup-signature
|
32b27c36b61ad1dbe42482314ec25cb1d6d46c42
|
[
"Apache-2.0"
] | 66 |
2019-12-02T08:31:33.000Z
|
2021-12-03T15:33:01.000Z
|
src/main/java/org/esupportail/esupsignature/dss/service/KeystoreService.java
|
prigaux/esup-signature
|
32b27c36b61ad1dbe42482314ec25cb1d6d46c42
|
[
"Apache-2.0"
] | 5 |
2020-06-12T16:48:41.000Z
|
2022-03-22T11:03:00.000Z
| 33.051724 | 110 | 0.793949 | 1,002,289 |
package org.esupportail.esupsignature.dss.service;
import eu.europa.esig.dss.enumerations.DigestAlgorithm;
import eu.europa.esig.dss.model.x509.CertificateToken;
import eu.europa.esig.dss.utils.Utils;
import org.esupportail.esupsignature.dss.config.DSSBeanConfig;
import org.esupportail.esupsignature.dss.model.CertificateDTO;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConditionalOnBean(DSSBeanConfig.class)
public class KeystoreService {
public List<CertificateDTO> getCertificatesDTOFromKeyStore(List<CertificateToken> certificatesFromKeyStore) {
List<CertificateDTO> list = new ArrayList<CertificateDTO>();
for (CertificateToken certificateToken : certificatesFromKeyStore) {
list.add(getCertificateDTO(certificateToken));
}
return list;
}
public CertificateDTO getCertificateDTO(CertificateToken certificate) {
CertificateDTO dto = new CertificateDTO();
dto.setDssId(certificate.getDSSIdAsString());
dto.setIssuerName(certificate.getIssuer().getCanonical());
dto.setSubjectName(certificate.getSubject().getCanonical());
dto.setNotBefore(certificate.getNotBefore());
dto.setNotAfter(certificate.getNotAfter());
byte[] digestSHA256 = certificate.getDigest(DigestAlgorithm.SHA256);
byte[] digestSHA1 = certificate.getDigest(DigestAlgorithm.SHA1);
dto.setSha256Hex(getPrintableHex(digestSHA256));
dto.setSha1Hex(getPrintableHex(digestSHA1));
dto.setSha256Base64(Utils.toBase64(digestSHA256));
dto.setSha1Base64(Utils.toBase64(digestSHA1));
return dto;
}
/**
* This method adds space every two characters to the hexadecimal encoded digest
*
* @param digest
* @return
*/
private String getPrintableHex(byte[] digest) {
String hexString = Utils.toHex(digest);
return hexString.replaceAll("..", "$0 ");
}
}
|
92427b611c51a81bc29dd9b46bc7bd619e517d71
| 491 |
java
|
Java
|
quarkus-rest-caps/src/main/java/org/keycloak/quickstart/CapsResource.java
|
sebastienblanc/quarkus-quickstart
|
11e46c4891d81af648ab7c3656c84db99438f0bb
|
[
"Apache-2.0"
] | 17 |
2019-03-22T21:55:44.000Z
|
2021-11-16T13:00:15.000Z
|
quarkus-rest-caps/src/main/java/org/keycloak/quickstart/CapsResource.java
|
sebastienblanc/quarkus-quickstart
|
11e46c4891d81af648ab7c3656c84db99438f0bb
|
[
"Apache-2.0"
] | 1 |
2019-03-24T16:10:53.000Z
|
2019-12-09T12:13:04.000Z
|
quarkus-rest-caps/src/main/java/org/keycloak/quickstart/CapsResource.java
|
sebastienblanc/quarkus-quickstart
|
11e46c4891d81af648ab7c3656c84db99438f0bb
|
[
"Apache-2.0"
] | 5 |
2019-03-26T14:20:45.000Z
|
2020-06-08T13:10:25.000Z
| 23.380952 | 66 | 0.737271 | 1,002,290 |
package org.keycloak.quickstart;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@Path("caps/{username}")
@RequestScoped
public class CapsResource {
@GET
@RolesAllowed({"user"})
@Produces("application/json")
public String toCaps(@PathParam("username") String username) {
return username.toUpperCase();
}
}
|
92427c72d741eaacc188daa19d651fdc395bc504
| 739 |
java
|
Java
|
BackEnd/src/main/java/com/unosquare/admin_core/back_end/entity/Team.java
|
UnosquareBelfast/AdminCore
|
2f3ec9be3d9694271196b6eefd46ce1d89c15abd
|
[
"MIT"
] | 1 |
2018-06-13T17:15:13.000Z
|
2018-06-13T17:15:13.000Z
|
BackEnd/src/main/java/com/unosquare/admin_core/back_end/entity/Team.java
|
UnosquareBelfast/AdminCore
|
2f3ec9be3d9694271196b6eefd46ce1d89c15abd
|
[
"MIT"
] | 68 |
2018-04-23T11:26:36.000Z
|
2018-12-14T10:12:13.000Z
|
BackEnd/src/main/java/com/unosquare/admin_core/back_end/entity/Team.java
|
UnosquareBelfast/AdminCore
|
2f3ec9be3d9694271196b6eefd46ce1d89c15abd
|
[
"MIT"
] | 3 |
2018-04-04T13:25:18.000Z
|
2019-04-15T11:15:41.000Z
| 21.735294 | 86 | 0.717185 | 1,002,291 |
package com.unosquare.admin_core.back_end.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@NoArgsConstructor
@Table(name = "Team")
public class Team implements java.io.Serializable {
@Id
@SequenceGenerator(name="seq",sequenceName="team_team_id_seq", allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
@Column(name = "team_id", unique = true, nullable = false)
private int teamId;
@ManyToOne
@JoinColumn(name = "client_id")
private Client client;
private String teamName;
private String contactName;
private String contactEmail;
public Team(int teamId){
this.teamId = teamId;
}
}
|
92427d54edd29ee8c00d9dc1846f21daaab60047
| 163 |
java
|
Java
|
Assignment/JAVA + GDX incomplete assignments/GUIapp - iteration 5 - TODO (maven)/src/main/java/edu/hr/infdev024/IIterator.java
|
hogeschool/INFSEN01-2
|
4198e0aa83c565eb33418927366192383daa3ed4
|
[
"MIT"
] | 2 |
2017-06-06T08:04:30.000Z
|
2017-06-30T14:24:14.000Z
|
Assignment/JAVA + GDX incomplete assignments/GUIapp - iteration 5 - TODO (maven)/src/main/java/edu/hr/infdev024/IIterator.java
|
hogeschool/INFSEN01-2
|
4198e0aa83c565eb33418927366192383daa3ed4
|
[
"MIT"
] | null | null | null |
Assignment/JAVA + GDX incomplete assignments/GUIapp - iteration 5 - TODO (maven)/src/main/java/edu/hr/infdev024/IIterator.java
|
hogeschool/INFSEN01-2
|
4198e0aa83c565eb33418927366192383daa3ed4
|
[
"MIT"
] | null | null | null | 16.3 | 62 | 0.711656 | 1,002,292 |
package edu.hr.infdev024;
// Describes a common interface for iterating over collections
interface IIterator<T> {
IOption<T> getNext();
void reset();
}
|
92427e63e5ec1cd4195026d058a5c0ef1c471e97
| 11,195 |
java
|
Java
|
draughts-online-client/src/main/java/com/catnbear/model/game/Board.java
|
notmyf4ulty/draughts-online
|
9a73be5dc474053dcfc84b1028d667bb1a36f1bc
|
[
"MIT"
] | null | null | null |
draughts-online-client/src/main/java/com/catnbear/model/game/Board.java
|
notmyf4ulty/draughts-online
|
9a73be5dc474053dcfc84b1028d667bb1a36f1bc
|
[
"MIT"
] | null | null | null |
draughts-online-client/src/main/java/com/catnbear/model/game/Board.java
|
notmyf4ulty/draughts-online
|
9a73be5dc474053dcfc84b1028d667bb1a36f1bc
|
[
"MIT"
] | null | null | null | 35.88141 | 123 | 0.529522 | 1,002,293 |
package com.catnbear.model.game;
import java.util.*;
public class Board extends Observable {
private static final int BOARD_DIMENSION = 5;
private Field [][] board;
private Field [][] boardBackup;
private GameModel gameModel;
private boolean multiBeatMode;
private Field multiBeatingPieceField;
private int enemyPiecesNumber;
public Board() {
board = generateBoard();
backupBoard();
gameModel = GameModel.getInstance();
multiBeatMode = false;
}
private Field [][] generateBoard() {
Field [][] board = new Field [BOARD_DIMENSION][BOARD_DIMENSION];
for (int i = 0 ; i < BOARD_DIMENSION ; i++) {
for (int j = 0 ; j < BOARD_DIMENSION ; j++) {
Position position = new Position(i,j);
Field field = setInitialConfiguration(position);
board[i][j] = field;
}
}
return board;
}
private Field setInitialConfiguration(Position position) {
Field field = new Field(position);
if (position.isXySumEven()) {
int playerOnePieceGenerationBorder = 2;
int playerTwoPieceGenerationBorder = 2;
if (position.getY() < playerOnePieceGenerationBorder) {
Piece piece = new Piece(Piece.PieceType.MEN, Player.WHITE);
piece.assignField(field);
} else if (position.getY() > playerTwoPieceGenerationBorder) {
Piece piece = new Piece(Piece.PieceType.MEN, Player.BLACK);
piece.assignField(field);
}
}
return field;
}
public void chooseField(Position position) {
Field chosenField = board[position.getX()][position.getY()];
if (gameModel.isMoveAvailable()) {
Field activePieceField;
if (multiBeatMode) {
activePieceField = multiBeatingPieceField;
} else {
activePieceField = getFieldOfActivePiece();
}
if (activePieceField != null) {
moveActivePiece(activePieceField, chosenField);
}
if (chosenField.containsPiece()) {
if (!multiBeatMode) {
selectPiece(chosenField);
}
}
setChanged();
notifyObservers();
}
}
private Field getFieldOfActivePiece() {
for(Field [] fields : board) {
for (Field field : fields) {
if (field.containsPiece() && field.isPieceSelcted()) {
return field;
}
}
}
return null;
}
private void moveActivePiece(Field fromField, Field toField) {
if (!toField.containsPiece() &&
isProperDirection(fromField.getPosition(),toField.getPosition())) {
switch (Position.getMoveDistance(fromField.getPosition(),toField.getPosition())) {
case ONE_FIELD_DISTANCE:
if (!multiBeatMode) {
movePiece(fromField, toField);
}
break;
case TWO_FIELDS_DISTANCE:
movePieceByTwoFields(fromField,toField);
break;
case INCORRECT_DISTANCE:
break;
}
}
if (!multiBeatMode) {
resetSelection();
}
}
private boolean isProperDirection(Position fromPosition, Position toPosition) {
if(Position.getMoveDistance(fromPosition,toPosition).equals(MoveDistance.ONE_FIELD_DISTANCE)) {
int yFrom = fromPosition.getY();
int yTo = toPosition.getY();
switch (gameModel.getPlayer()) {
case WHITE:
return yTo > yFrom;
case BLACK:
return yTo < yFrom;
}
return false;
} else {
return true;
}
}
private void movePiece(Field fromField, Field toField) {
Piece piece = fromField.getPiece();
fromField.resetPiece();
toField.setPiece(piece);
gameModel.setMoveAvailable(false);
}
private void movePieceByTwoFields(Field fromField, Field toField) {
Player activePlayer = gameModel.getPlayer();
int x = (toField.getPosition().getX() + fromField.getPosition().getX()) / 2;
int y = (toField.getPosition().getY() + fromField.getPosition().getY()) / 2;
Field enemyField = board[x][y];
if (enemyField.containsPiece() &&
!enemyField.getPiece().getPlayer().equals(activePlayer)) {
enemyField.resetPiece();
movePiece(fromField,toField);
multiBeatMode = isOpponentToBeatAround(toField);
if (multiBeatMode) {
gameModel.setMoveAvailable(true);
}
}
}
private boolean isOpponentToBeatAround(Field field) {
Field [] opponentFields = getNeighbouringOpponents(field);
if (isPlaceBehindOpponents(field, opponentFields)) {
multiBeatingPieceField = field;
return true;
} else {
multiBeatingPieceField = null;
}
return false;
}
private Field [] getNeighbouringOpponents(Field field) {
ArrayList<Field> opponentFields = new ArrayList<>();
Position [] neighbouringPositions = field.getPosition().getDiagonalNeighboursPositions(1,BOARD_DIMENSION);
for (Position position : neighbouringPositions) {
Field opponentField = board[position.getX()][position.getY()];
if (opponentField.containsPiece() &&
!opponentField
.getPiece()
.getPlayer()
.equals(gameModel.getPlayer())) {
opponentFields.add(opponentField);
}
}
Field [] opponentFieldsArray = new Field[opponentFields.size()];
opponentFieldsArray = opponentFields.toArray(opponentFieldsArray);
return opponentFieldsArray;
}
private boolean isPlaceBehindOpponents(Field attackingField, Field [] opponents) {
Position [] neighbouringPositions = attackingField.getPosition().getDiagonalNeighboursPositions(2,BOARD_DIMENSION);
for (Position position : neighbouringPositions) {
Field behindOpponentField = board[position.getX()][position.getY()];
if (!behindOpponentField.containsPiece() &&
Position
.getMoveDistance(attackingField.getPosition(),behindOpponentField.getPosition())
.equals(MoveDistance.TWO_FIELDS_DISTANCE) &&
isOpponentInTheMiddle(attackingField.getPosition(),behindOpponentField.getPosition())) {
return true;
}
}
return false;
}
private boolean isOpponentInTheMiddle(Position fromPosition, Position toPosition) {
int opponentX = (fromPosition.getX() + toPosition.getX()) / 2;
int opponentY = (fromPosition.getY() + toPosition.getY()) / 2;
if (opponentX != 0 && opponentY != 0) {
Field opponentField = board[opponentX][opponentY];
if (opponentField.containsPiece()) {
return !opponentField.getPiece().getPlayer().equals(gameModel.getPlayer());
}
}
return false;
}
private void selectPiece(Field field) {
resetSelection();
Player activePlayer = gameModel.getPlayer();
if (field.getPiece().getPlayer().equals(activePlayer)) {
field.selectPiece();
}
}
private void resetSelection() {
for (Field[] fields : board) {
for (Field field : fields) {
if (field.containsPiece()) {
field.unselectPiece();
}
}
}
}
private Field[][] getCopy(Field[][] fromBoard) {
Field [][] copyBoard = new Field[BOARD_DIMENSION][BOARD_DIMENSION];
for (int i = 0 ; i < BOARD_DIMENSION ; i++) {
for (int j = 0 ; j < BOARD_DIMENSION ; j++) {
copyBoard[i][j] = fromBoard[i][j].getCopy();
}
}
return copyBoard;
}
void backupBoard() {
boardBackup = getCopy(board);
}
void retrieveBackup() {
board = getCopy(boardBackup);
multiBeatMode = false;
multiBeatingPieceField = null;
enemyPiecesNumber = countPieces();
setChanged();
notifyObservers();
}
String prepareToSend() {
String boardString = "";
for (Field [] fields : board) {
for (Field field : fields) {
if (field.containsPiece()) {
switch (field.getPiece().getPlayer()) {
case WHITE:
boardString += "w";
break;
case BLACK:
boardString += "b";
break;
}
} else {
boardString += "o";
}
}
boardString += ";";
}
return boardString;
}
boolean createBoardFromString(String boardString) {
try {
System.out.println("Creating board from String: " + boardString);
String[] boardColumns = boardString.split(";");
Field[][] newBoard = new Field[BOARD_DIMENSION][BOARD_DIMENSION];
for (int i = 0; i < BOARD_DIMENSION; i++) {
for (int j = 0; j < BOARD_DIMENSION; j++) {
Field field = new Field(new Position(i, j));
switch (boardColumns[i].charAt(j)) {
case 'w':
Piece whitePiece = new Piece(Piece.PieceType.MEN, Player.WHITE);
field.setPiece(whitePiece);
break;
case 'b':
Piece blackPiece = new Piece(Piece.PieceType.MEN, Player.BLACK);
field.setPiece(blackPiece);
break;
}
newBoard[i][j] = field;
}
}
boardBackup = getCopy(newBoard);
retrieveBackup();
System.out.println("New board is: " + prepareToSend());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public int countPieces() {
int counter = 0;
for (int i = 0; i < BOARD_DIMENSION; i++) {
for (int j = 0; j < BOARD_DIMENSION; j++) {
Field field = board[i][j];
if (field.containsPiece() && !field.getPiece().getPlayer().equals(gameModel.getPlayer())) {
counter++;
}
}
}
System.out.println("Returning " + counter);
return counter;
}
public Field[][] getBoard() {
return board;
}
}
|
92427ed44d0e11dc0b9097f7233d4ba7d3cbdb5b
| 200 |
java
|
Java
|
src/main/java/com/chapter4/Car.java
|
foreverbayern/Spring4Learn
|
630c8abd337587cf8a4fd1c9b25e423479df4ff6
|
[
"MIT"
] | null | null | null |
src/main/java/com/chapter4/Car.java
|
foreverbayern/Spring4Learn
|
630c8abd337587cf8a4fd1c9b25e423479df4ff6
|
[
"MIT"
] | null | null | null |
src/main/java/com/chapter4/Car.java
|
foreverbayern/Spring4Learn
|
630c8abd337587cf8a4fd1c9b25e423479df4ff6
|
[
"MIT"
] | null | null | null | 10.526316 | 31 | 0.65 | 1,002,294 |
package com.chapter4;
import lombok.Data;
import lombok.ToString;
/**
* @author:lucky date:2018/5/29
* time:18:26
*/
/**
* 作用域
*/
@Data
@ToString
public class Car {
private String name;
}
|
92427fa3cb4514557ad8120a03a29a9a7e95dec5
| 3,643 |
java
|
Java
|
web-ide/src/name/martingeisse/ecosim/cpu/usermode/unix/ReadingPipeFilePointer.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | 1 |
2015-06-16T13:18:45.000Z
|
2015-06-16T13:18:45.000Z
|
web-ide/src/name/martingeisse/ecosim/cpu/usermode/unix/ReadingPipeFilePointer.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | 3 |
2022-03-08T21:11:04.000Z
|
2022-03-08T21:11:15.000Z
|
web-ide/src/name/martingeisse/ecosim/cpu/usermode/unix/ReadingPipeFilePointer.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | null | null | null | 28.460938 | 223 | 0.733187 | 1,002,296 |
/**
* Copyright (c) 2011 Martin Geisse
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.ecosim.cpu.usermode.unix;
import name.martingeisse.ecosim.cpu.toolhost.IToolhostSleepHandler;
import name.martingeisse.ecosim.cpu.toolhost.StatResult;
import name.martingeisse.ecosim.cpu.toolhost.ToolhostProcess;
import name.martingeisse.ecosim.cpu.usermode.CopyFromBufferAction;
import name.martingeisse.ecosim.cpu.usermode.SparseMemory;
import name.martingeisse.ecosim.util.ByteQueue;
/**
* The reading end of a pipe. This class synchronizes on the queue to
* allow reading and writing from different threads.
*/
public class ReadingPipeFilePointer extends AbstractFilePointer {
/**
* the queue
*/
private final ByteQueue queue;
/**
* Constructor.
* @param queue the queue to read from
*/
public ReadingPipeFilePointer(ByteQueue queue) {
this.queue = queue;
}
/**
* Getter method for the queue.
* @return the queue
*/
public ByteQueue getQueue() {
return queue;
}
/* (non-Javadoc)
* @see name.martingeisse.ecotools.simulator.cpu.usermode.unix.IFilePointer#read(name.martingeisse.ecotools.simulator.cpu.toolhost.ToolhostProcess, name.martingeisse.ecotools.simulator.cpu.usermode.SparseMemory, int, int)
*/
@Override
public int read(final ToolhostProcess process, final SparseMemory memory, final int startAddress, final int count) throws UnixSyscallException {
// try to read without blocking
final byte[] buffer = new byte[count];
int n = readHelper(buffer, memory, startAddress, count);
if (n > 0) {
return n;
}
// no data available -- might be EOF
boolean eof;
synchronized(queue) {
eof = queue.isEof();
}
if (eof) {
return 0;
}
// block until some data is available
process.setSleeping(new IToolhostSleepHandler() {
@Override
public void handle(ToolhostProcess process) {
int n = readHelper(buffer, memory, startAddress, count);
if (n > 0) {
process.getCpu().getGeneralRegisters().write(2, n, false);
process.setRunning();
}
}
});
return 0;
}
// common handling for blocked and unblocked reading
private int readHelper(final byte[] buffer, final SparseMemory memory, final int startAddress, final int count) {
int n;
synchronized(queue) {
n = queue.read(buffer, 0, count);
}
if (n > 0) {
CopyFromBufferAction action = new CopyFromBufferAction(memory, buffer, false);
action.execute(startAddress, n);
}
return n;
}
/* (non-Javadoc)
* @see name.martingeisse.ecotools.simulator.cpu.usermode.unix.IFilePointer#write(name.martingeisse.ecotools.simulator.cpu.toolhost.ToolhostProcess, name.martingeisse.ecotools.simulator.cpu.usermode.SparseMemory, int, int)
*/
@Override
public int write(ToolhostProcess process, SparseMemory memory, int startAddress, int count) throws UnixSyscallException {
return 0;
}
/* (non-Javadoc)
* @see name.martingeisse.ecotools.simulator.cpu.usermode.unix.IFilePointer#seek(int, name.martingeisse.ecotools.simulator.cpu.usermode.unix.SeekOrigin)
*/
@Override
public int seek(int offset, SeekOrigin origin) throws UnixSyscallException {
return 0;
}
/* (non-Javadoc)
* @see name.martingeisse.ecotools.simulator.cpu.usermode.unix.IFilePointer#stat()
*/
@Override
public StatResult stat() throws UnixSyscallException {
throw new RuntimeException("not yet implemented");
}
/* (non-Javadoc)
* @see name.martingeisse.ecotools.simulator.cpu.usermode.unix.AbstractFilePointer#dispose()
*/
@Override
protected void dispose() {
synchronized(queue) {
queue.notifyReaderStopped();
}
}
}
|
9242801185f42f0f1e83a5f7888dae465fe6d43f
| 547 |
java
|
Java
|
worf-kaptcha/src/main/java/orj/worf/kaptcha/util/ConfigException.java
|
liu-project/worf
|
c4372bb17f44ac964631759104e71e106d8f703f
|
[
"Apache-2.0"
] | null | null | null |
worf-kaptcha/src/main/java/orj/worf/kaptcha/util/ConfigException.java
|
liu-project/worf
|
c4372bb17f44ac964631759104e71e106d8f703f
|
[
"Apache-2.0"
] | 7 |
2020-05-15T22:05:51.000Z
|
2021-08-25T15:46:25.000Z
|
worf-kaptcha/src/main/java/orj/worf/kaptcha/util/ConfigException.java
|
liu-project/worf
|
c4372bb17f44ac964631759104e71e106d8f703f
|
[
"Apache-2.0"
] | null | null | null | 42.076923 | 105 | 0.700183 | 1,002,297 |
package orj.worf.kaptcha.util;
public class ConfigException extends RuntimeException {
private static final long serialVersionUID = 6937416954897707291L;
public ConfigException(String paramName, String paramValue, Throwable cause) {
super("Invalid value '" + paramValue + "' for config parameter '" + paramName + "'.", cause);
}
public ConfigException(String paramName, String paramValue, String message) {
super("Invalid value '" + paramValue + "' for config parameter '" + paramName + "'. " + message);
}
}
|
924280700049b4bf2dc834749e3c4eeaf2cdd475
| 13,192 |
java
|
Java
|
raptor/src/main/java/raptor/chess/Move.java
|
mipper/raptor-chess-interface
|
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
|
[
"BSD-3-Clause"
] | 12 |
2015-04-07T17:57:23.000Z
|
2021-03-21T21:40:09.000Z
|
raptor/src/main/java/raptor/chess/Move.java
|
mipper/raptor-chess-interface
|
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
|
[
"BSD-3-Clause"
] | 7 |
2015-06-16T21:37:34.000Z
|
2021-03-12T18:49:03.000Z
|
raptor/src/main/java/raptor/chess/Move.java
|
mipper/raptor-chess-interface
|
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
|
[
"BSD-3-Clause"
] | 6 |
2016-05-28T23:32:51.000Z
|
2021-01-25T04:47:46.000Z
| 25.565891 | 758 | 0.71134 | 1,002,298 |
/**
* New BSD License
* http://www.opensource.org/licenses/bsd-license.php
* Copyright 2009-2011 RaptorProject (http://code.google.com/p/raptor-chess-interface/)
* 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 RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package raptor.chess;
import java.util.ArrayList;
import raptor.chess.pgn.Arrow;
import raptor.chess.pgn.Comment;
import raptor.chess.pgn.Highlight;
import raptor.chess.pgn.MoveAnnotation;
import raptor.chess.pgn.Nag;
import raptor.chess.pgn.SublineNode;
import raptor.chess.pgn.TimeTakenForMove;
import raptor.chess.util.GameUtils;
public class Move implements GameConstants {
public static final int DOUBLE_PAWN_PUSH_CHARACTERISTIC = 4;
public static final int DROP_CHARACTERISTIC = 32;
public static final int EN_PASSANT_CHARACTERISTIC = 16;
public static final int LONG_CASTLING_CHARACTERISTIC = 2;
public static final int PROMOTION_CHARACTERISTIC = 8;
public static final int SHORT_CASTLING_CHARACTERISTIC = 1;
/**
* May or may not be used. It is obviously not suitable to use this for a
* chess engine. That is why it starts out null.
*/
protected ArrayList<MoveAnnotation> annotations = null;
protected byte capture = EMPTY;
protected byte castlingType = CASTLE_NONE;
protected byte color = 0;
protected byte epSquare = EMPTY_SQUARE;
// Bytes are used because they take up less space than ints and there is no
// need for the extra space.
protected byte from = EMPTY_SQUARE;
/**
* May or may not be used.
*/
protected int fullMoveCount = 0;
/**
* May or may not be used.
*/
protected int halfMoveCount = 0;
protected byte lastWhiteCastlingState = CASTLE_NONE;
protected byte lastBlackCastlingState = CASTLE_NONE;
protected byte moveCharacteristic = 0;
protected byte piece = EMPTY;
protected byte piecePromotedTo = EMPTY;
protected byte previous50MoveCount = 0;
/**
* May or may not be used.
*/
protected String san;
protected byte to = EMPTY_SQUARE;
/**
* Used during rollbacks.
*/
protected String previousEcoHeader;
/**
* Used during rollbacks.
*/
protected String previousOpeningHeader;
/**
* Used only for atomic.
*
* @see AtomicExplosionInfo For more details.
*/
protected AtomicExplosionInfo[] atomicExplosionInfo = null;
/**
* Constructor for drop moves. From square will be set to the drop square
* for the piece.
*/
public Move(int to, int piece, int color) {
this.to = (byte) to;
this.piece = (byte) piece;
from = (byte) GameUtils.getDropSquareFromColoredPiece(GameUtils
.getColoredPiece(piece, color));
moveCharacteristic = DROP_CHARACTERISTIC;
this.color = (byte) color;
}
public Move(int from, int to, int piece, int color, int capture) {
this.piece = (byte) piece;
this.color = (byte) color;
this.capture = (byte) capture;
this.from = (byte) from;
this.to = (byte) to;
}
public Move(int from, int to, int piece, int color, int capture,
int moveCharacteristic) {
this.piece = (byte) piece;
this.color = (byte) color;
this.capture = (byte) capture;
this.from = (byte) from;
this.to = (byte) to;
this.moveCharacteristic = (byte) moveCharacteristic;
}
public Move(int from, int to, int piece, int color, int capture,
int piecePromotedTo, int epSquare, int moveCharacteristic) {
this.piece = (byte) piece;
this.color = (byte) color;
this.capture = (byte) capture;
this.from = (byte) from;
this.to = (byte) to;
this.piecePromotedTo = (byte) piecePromotedTo;
this.epSquare = (byte) epSquare;
this.moveCharacteristic = (byte) moveCharacteristic;
}
public void addAnnotation(MoveAnnotation annotation) {
if (annotations == null) {
annotations = new ArrayList<MoveAnnotation>(5);
}
annotations.add(annotation);
}
public MoveAnnotation[] getAnnotations() {
if (annotations == null) {
return new MoveAnnotation[0];
}
return annotations.toArray(new MoveAnnotation[0]);
}
public Arrow[] getArrows() {
if (annotations == null) {
return new Arrow[0];
}
ArrayList<Arrow> result = new ArrayList<Arrow>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof Arrow) {
result.add((Arrow) annotation);
}
}
return result.toArray(new Arrow[0]);
}
/**
* Used only for atomic.
*
* @see AtomicExplosionInfo For more details.
*/
public AtomicExplosionInfo[] getAtomicExplosionInfo() {
return atomicExplosionInfo;
}
/**
* Returns the capture without the promote mask.
*/
public int getCapture() {
return capture & NOT_PROMOTED_MASK;
}
public int getCaptureColor() {
return GameUtils.getOppositeColor(getColor());
}
/**
* Returns the capture with the promote mask.
*/
public int getCaptureWithPromoteMask() {
return capture;
}
public int getColor() {
return color;
}
public Comment[] getComments() {
if (annotations == null) {
return new Comment[0];
}
ArrayList<Comment> result = new ArrayList<Comment>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof Comment) {
result.add((Comment) annotation);
}
}
return result.toArray(new Comment[0]);
}
public int getEpSquare() {
return epSquare;
}
public int getFrom() {
return from;
}
public int getFullMoveCount() {
return fullMoveCount;
}
public int getHalfMoveCount() {
return halfMoveCount;
}
public Highlight[] getHighlights() {
if (annotations == null) {
return new Highlight[0];
}
ArrayList<Highlight> result = new ArrayList<Highlight>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof Highlight) {
result.add((Highlight) annotation);
}
}
return result.toArray(new Highlight[0]);
}
public String getLan() {
return isCastleShort() ? "O-O" : isCastleLong() ? "O-O-O"
: isDrop() ? COLOR_PIECE_TO_CHAR[color].charAt(getPiece())
+ "@" + GameUtils.getSan(getTo()) : ""
+ GameUtils.getSan(getFrom())
+ "-"
+ GameUtils.getSan(getTo())
+ (isPromotion() ? "="
+ PIECE_TO_SAN.charAt(piecePromotedTo
& NOT_PROMOTED_MASK) : "");
}
public int getLastBlackCastlingState() {
return lastBlackCastlingState;
}
public byte getLastWhiteCastlingState() {
return lastWhiteCastlingState;
}
public int getMoveCharacteristic() {
return moveCharacteristic;
}
public Nag[] getNags() {
if (annotations == null) {
return new Nag[0];
}
ArrayList<Nag> result = new ArrayList<Nag>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof Nag) {
result.add((Nag) annotation);
}
}
return result.toArray(new Nag[0]);
}
public int getNumAnnotations() {
return annotations.size();
}
public int getNumAnnotationsExcludingSublines() {
int result = 0;
for (MoveAnnotation annotation : annotations) {
if (!(annotation instanceof SublineNode)) {
result++;
}
}
return result;
}
public int getPiece() {
return piece & NOT_PROMOTED_MASK;
}
public int getPiecePromotedTo() {
return piecePromotedTo;
}
/**
* Returns the piece with its promotion mask.
*
* @return
*/
public int getPieceWithPromoteMask() {
return piece;
}
public int getPrevious50MoveCount() {
return previous50MoveCount;
}
/**
* Used to reset the header during a rollback.
*
* @param previousOpeningHeader
*/
public String getPreviousEcoHeader() {
return previousEcoHeader;
}
/**
* Used to reset the header during a rollback.
*
* @param previousOpeningHeader
*/
public String getPreviousOpeningHeader() {
return previousOpeningHeader;
}
public String getSan() {
return san;
}
public SublineNode[] getSublines() {
if (annotations == null) {
return new SublineNode[0];
}
ArrayList<SublineNode> result = new ArrayList<SublineNode>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof SublineNode) {
result.add((SublineNode) annotation);
}
}
return result.toArray(new SublineNode[0]);
}
public TimeTakenForMove[] getTimeTakenForMove() {
if (annotations == null) {
return new TimeTakenForMove[0];
}
ArrayList<TimeTakenForMove> result = new ArrayList<TimeTakenForMove>(3);
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof TimeTakenForMove) {
result.add((TimeTakenForMove) annotation);
}
}
return result.toArray(new TimeTakenForMove[0]);
}
public int getTo() {
return to;
}
public boolean hasNag() {
if (annotations == null) {
return false;
}
boolean result = false;
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof Nag) {
result = true;
break;
}
}
return result;
}
public boolean hasSubline() {
if (annotations == null) {
return false;
}
boolean result = false;
for (MoveAnnotation annotation : annotations) {
if (annotation instanceof SublineNode) {
result = true;
break;
}
}
return result;
}
public boolean isCapture() {
return getCapture() != GameConstants.EMPTY;
}
public boolean isCastleLong() {
return (moveCharacteristic & LONG_CASTLING_CHARACTERISTIC) != 0;
}
public boolean isCastleShort() {
return (moveCharacteristic & SHORT_CASTLING_CHARACTERISTIC) != 0;
}
public boolean isDrop() {
return (moveCharacteristic & DROP_CHARACTERISTIC) != 0;
}
public boolean isEnPassant() {
return (moveCharacteristic & EN_PASSANT_CHARACTERISTIC) != 0;
}
public boolean isPromotion() {
return piecePromotedTo != GameConstants.EMPTY;
}
public boolean isWhitesMove() {
return color == GameConstants.WHITE;
}
public void removeAnnotation(MoveAnnotation annotation) {
if (annotations == null) {
return;
}
annotations.remove(annotation);
}
/**
* Used only for atomic.
*
* @see AtomicExplosionInfo For more details.
*/
public void setAtomicExplosionInfo(AtomicExplosionInfo[] atomicExplosionInfo) {
this.atomicExplosionInfo = atomicExplosionInfo;
}
public void setCapture(int capture) {
this.capture = (byte) capture;
}
public void setColor(int color) {
this.color = (byte) color;
}
public void setEpSquare(int epSquare) {
this.epSquare = (byte) epSquare;
}
public void setFrom(int from) {
this.from = (byte) from;
}
public void setFullMoveCount(int fullMoveCount) {
this.fullMoveCount = fullMoveCount;
}
public void setHalfMoveCount(int halfMoveCount) {
this.halfMoveCount = halfMoveCount;
}
public void setLastBlackCastlingState(int lastBlackCastlingState) {
this.lastBlackCastlingState = (byte) lastBlackCastlingState;
}
public void setLastWhiteCastlingState(int lastWhiteCastlingState) {
this.lastWhiteCastlingState = (byte) lastWhiteCastlingState;
}
public void setMoveCharacteristic(int moveCharacteristic) {
this.moveCharacteristic = (byte) moveCharacteristic;
}
public void setPiece(int piece) {
this.piece = (byte) piece;
}
public void setPiecePromotedTo(int piecePromotedTo) {
this.piecePromotedTo = (byte) piecePromotedTo;
}
public void setPrevious50MoveCount(int previous50MoveCount) {
this.previous50MoveCount = (byte) previous50MoveCount;
}
/**
* Used to reset the header during a rollback.
*
* @param previousOpeningHeader
*/
public void setPreviousEcoHeader(String previousEcoHeader) {
this.previousEcoHeader = previousEcoHeader;
}
/**
* Used to reset the header during a rollback.
*
* @param previousOpeningHeader
*/
public void setPreviousOpeningHeader(String previousOpeningHeader) {
this.previousOpeningHeader = previousOpeningHeader;
}
public void setSan(String san) {
this.san = san;
}
public void setTo(int to) {
this.to = (byte) to;
}
@Override
public String toString() {
return san != null ? san : getLan();
}
}
|
924280c69650e79c6e51517b02cb14144e064908
| 107 |
java
|
Java
|
plugin/site-plugin/src/main/java/com/frankdevhub/site/core/constants/BusinessConstants.java
|
lezaz/lezaz.github.io
|
17592a82d31aa41574806e6ad1a52128eef145b4
|
[
"MIT"
] | 10 |
2017-08-08T06:30:37.000Z
|
2021-11-17T11:33:52.000Z
|
plugin/site-plugin/src/main/java/com/frankdevhub/site/core/constants/BusinessConstants.java
|
00mjk/frankdevhub.github.io
|
f2dc0ced991d93eeee610e8faef7651929629a28
|
[
"MIT"
] | 55 |
2017-07-28T07:21:36.000Z
|
2022-03-31T20:40:06.000Z
|
plugin/site-plugin/src/main/java/com/frankdevhub/site/core/constants/BusinessConstants.java
|
lezaz/lezaz.github.com
|
17592a82d31aa41574806e6ad1a52128eef145b4
|
[
"MIT"
] | 4 |
2017-08-08T06:30:42.000Z
|
2021-10-17T18:53:17.000Z
| 15.285714 | 44 | 0.794393 | 1,002,299 |
package com.frankdevhub.site.core.constants;
@SuppressWarnings("all")
public class BusinessConstants {
}
|
924282e8b1093ebc7bc48dfb302909e91c20af8c
| 9,740 |
java
|
Java
|
src/edu/comp373/view/FacilityClient_WithSpringAndDAO.java
|
johnosullivan/AOOP
|
a5df782d05d7574b34305d1c8b5fdd0db852be7d
|
[
"MIT"
] | null | null | null |
src/edu/comp373/view/FacilityClient_WithSpringAndDAO.java
|
johnosullivan/AOOP
|
a5df782d05d7574b34305d1c8b5fdd0db852be7d
|
[
"MIT"
] | null | null | null |
src/edu/comp373/view/FacilityClient_WithSpringAndDAO.java
|
johnosullivan/AOOP
|
a5df782d05d7574b34305d1c8b5fdd0db852be7d
|
[
"MIT"
] | null | null | null | 55.028249 | 215 | 0.708727 | 1,002,300 |
package edu.comp373.view;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import edu.comp373.dal.Configs;
import edu.comp373.model.facility.Address;
import edu.comp373.model.facility.Facility;
import edu.comp373.model.facility.Location;
import edu.comp373.model.facility.Facility.DetailType;
import edu.comp373.model.inspections.Inspection;
import edu.comp373.model.maintenance.MaintenanceRequest;
import edu.comp373.model.maintenance.MaintenanceRequest.MaintenanceStatus;
import edu.comp373.model.manager.FacilityManager;
import edu.comp373.model.manager.MaintenanceManager;
//import edu.comp373.model.manager.MaintenanceManager;
import edu.comp373.model.reservations.Reservation;
import edu.comp373.model.users.FacilityUser;
import edu.comp373.model.users.Inspector;
public class FacilityClient_WithSpringAndDAO {
static boolean DEBUGGING = false;
public static void main(String[] args) {
Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/app-context.xml");
System.out.println("***************** Application Context Instantiated! ******************");
// Creating the manager objects from spring bean
FacilityManager facilityManager = (FacilityManager)context.getBean("facilitymanager");
MaintenanceManager maintenanceManager= (MaintenanceManager)context.getBean("maintenancemanager");
//MaintenanceManager maintenanceManager = (MaintenanceManager)context.getBean("maintenancemanager");
System.out.println("Advanced Object Oriented Programming (OOP)");
// Creating the address object from spring bean
Address address1 = (Address)context.getBean("address");
address1.setAddress("1032 W Sheridan Rd");
address1.setCity("Chicago");
address1.setState("IL");
address1.setZip("60660");
// Creating the location object from spring bean
Location location1 = (Location)context.getBean("location_basic");
location1.setAddress(address1);
location1.setBuidlingName("Damen Student Center");
location1.setRoomName("RM 345");
// Creating the facility object from spring bean
Facility facility1 = (Facility)context.getBean("facility");
facility1.setCapacity(125);
facility1.setLocation(location1);
facility1.setCreated(LocalDateTime.now());
facility1.addDetail(DetailType.CAPACITY, 120);
facility1 = facilityManager.addNewFacility(facility1);
System.out.println("Facility ID: " + facility1.getID());
// listFacilities
ArrayList<Facility> list = facilityManager.listFacilities();
Iterator<Facility> iters_list = list.iterator();
System.out.println("listFacilities_count: " + list.size());
while(iters_list.hasNext()) {
Facility item = iters_list.next();
System.out.println("Capacity: " + item.getCapacity() + " Location: " + item.getLocation().getBuildingName() + " " + item.getLocation().getRoom() + " Address: " + item.getLocation().getAddress().getFullAddress());
}
// requestAvailableCapacity
ArrayList<Facility> respond = facilityManager.requestAvailableCapacity(150);
Iterator<Facility> iters = respond.iterator();
System.out.println("Facility_RequestAvailableCapacity: " + respond.size());
while(iters.hasNext()) {
Facility item = iters.next();
System.out.println("Capacity: " + item.getCapacity() + " Location: " + item.getLocation().getBuildingName() + " " + item.getLocation().getRoom() + " Address: " + item.getLocation().getAddress().getFullAddress());
}
// creating a facility user from the bean
FacilityUser facilityUser = (FacilityUser)context.getBean("facilityuser");
facilityUser.setFirstName("Rachel");
facilityUser.setMiddleName("Louise");
facilityUser.setLastName("Cundiff");
facilityUser.setTitle("Ms.");
System.out.println("FacilityUser: " + facilityUser.save());
// Making a reservation
LocalDateTime start = LocalDateTime.now().minusHours(2);
LocalDateTime end = LocalDateTime.now();
if (facility1.assignFacilityToUse(facilityUser,start, end)) { }
// Gets facility with a constructor injection
Facility facility2 = (Facility)context.getBean("facility_id",facility1.getID());
// Prints the results
System.out.println("Building: " + facility2.getLocation().getBuildingName());
System.out.println("Room: " + facility2.getLocation().getRoom());
System.out.println("Capacity: " + facility2.getCapacity());
System.out.println("Address: " + facility2.getLocation().getAddress().getAddress());
System.out.println("City: " + facility2.getLocation().getAddress().getCity());
System.out.println("State: " + facility2.getLocation().getAddress().getState());
System.out.println("Zip: " + facility2.getLocation().getAddress().getZip());
// Prints the usage rate
System.out.println("calcUsageRate: " + facilityManager.calcUsageRate(facility2, LocalDateTime.now()) + "%");
TreeMap<String,Long> tree = facilityManager.listActualUsage();
for (Entry<String, Long> entry: tree.entrySet()) {
System.out.println("listActualUsage_Facility: " + entry.getKey() + " ActualUsage: " + Duration.ofSeconds(entry.getValue()).toHours() + " hrs");
}
// Gets all the reservations
Iterator<Reservation> res = facility2.getReservations().iterator();
while(res.hasNext()) {
Reservation item = res.next();
System.out.println("Reservation_ID: " + item.getID() + "Facility_ID: " + item.getFacilityID() + " Start: " + item.getStart().toString() + " End: " + item.getEnd().toString());
}
// Prints the facility information
System.out.println("Facility Information: " + facility1.getFacilityInformation());
// Creates a inspector
Inspector inspector = (Inspector)context.getBean("inspector");
inspector.setFirstName("John");
inspector.setMiddleName("Nikolas");
inspector.setLastName("O'Sullivan");
inspector.setTitle("Mr.");
String in_id = inspector.save();
System.out.println("<-- Inspector -->");
// Gets the inspector just created from the constructor injections
Inspector inspector2 = (Inspector)context.getBean("inspector_id",in_id);
System.out.println("FirstName: " + inspector2.getFirstName());
System.out.println("MiddleName: " + inspector2.getMiddleName());
System.out.println("LastName: " + inspector2.getLastName());
System.out.println("Title: " + inspector2.getTitle());
System.out.println("ID: " + inspector2.getID());
// Creates a inspetions
Inspection inspection = (Inspection)context.getBean("inspection");
inspection.setReport("There is a water pipe broken :/");
inspection.setInspector(inspector);
inspection.setDateTime(LocalDateTime.now());
System.out.println("Inspection_ID: " + facility1.addInspection(inspection));
// Lists all the inspections
Iterator<Inspection> inspecs = facility1.listInspections().iterator();
while(inspecs.hasNext()) {
Inspection item = inspecs.next();
System.out.println("Inspection_ID: " + item.getID() + " Facility_ID: " + item.getFacility() + " DateTime: " + item.getDateTime().toString() + " Report: " + item.getReport());
}
// Creates a maintenance request
MaintenanceRequest maintenanceRequest = (MaintenanceRequest)context.getBean("maintenancerequest");
maintenanceRequest.setFacility(facility2);
maintenanceRequest.setProblem("Fix the broken pipe in the den");
maintenanceRequest.setStatus(MaintenanceStatus.PENDING);
maintenanceRequest.setStartDateTime(start);
maintenanceRequest.setEndDateTime(end);
maintenanceRequest.setCost(123.3);
System.out.println("MaintenanceRequest_ID: " + maintenanceRequest.saveMaintenanceRequest());
// Creates another maintenance request
MaintenanceRequest maintenanceRequest2 = (MaintenanceRequest)context.getBean("maintenancerequest");
maintenanceRequest2.setFacility(facility2);
maintenanceRequest2.setProblem("It is really broken lol");
maintenanceRequest2.setStatus(MaintenanceStatus.PROBLEM);
maintenanceRequest2.setStartDateTime(start);
maintenanceRequest2.setEndDateTime(end.minusHours(1));
maintenanceRequest2.setCost(231.1);
System.out.println("MaintenanceRequest2_ID: " + maintenanceRequest2.saveMaintenanceRequest());
// Prints some maintenance stats
System.out.println("calcMaintenanceCostForFacility: $" + maintenanceManager.calcMaintenanceCostForFacility(facility2));
System.out.println("calcProblemRateForFacility: " + maintenanceManager.calcProblemRateForFacility(facility2) + "%");
System.out.println("calcDownTimeForFacility: " + maintenanceManager.calcDownTimeForFacility(facility2) + " hrs");
// Cleaning up the session
if (!DEBUGGING) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase(Configs.DB_NAME);
database.drop();
mongoClient.close();
}
// Closes the context
((ClassPathXmlApplicationContext) context).close();
}
}
|
9242832d71967ede5776a5558f98f6a7f5eb5969
| 382 |
java
|
Java
|
chat-utils/src/main/java/com/weixin/utils/plugins/ContextHelper.java
|
guozhihua/Wechat1.0
|
f5aba92ea019a825d036c612258f31539302a3f5
|
[
"Apache-2.0"
] | null | null | null |
chat-utils/src/main/java/com/weixin/utils/plugins/ContextHelper.java
|
guozhihua/Wechat1.0
|
f5aba92ea019a825d036c612258f31539302a3f5
|
[
"Apache-2.0"
] | null | null | null |
chat-utils/src/main/java/com/weixin/utils/plugins/ContextHelper.java
|
guozhihua/Wechat1.0
|
f5aba92ea019a825d036c612258f31539302a3f5
|
[
"Apache-2.0"
] | 1 |
2022-01-09T04:17:32.000Z
|
2022-01-09T04:17:32.000Z
| 22.470588 | 119 | 0.746073 | 1,002,301 |
package com.weixin.utils.plugins;
import com.weixin.utils.util.SpringBeanUtils;
/**
* Created by :Guozhihua
* Date: 2017/3/6.
*/
public class ContextHelper {
private static final StrategyManager strategyManager =(StrategyManager) SpringBeanUtils.getBean("strategyManager");
public static StrategyManager getStrategyManager(){
return strategyManager;
}
}
|
9242842884fd105d0b077f8c75b9b6c0c24d2da5
| 2,174 |
java
|
Java
|
HwAREngineDemo/src/main/java/com/huawei/arengine/demos/common/converter/BmpProducer.java
|
Ar4enal/hms-AREngine-demo
|
d38657e9ee7521125eb8c41e67cb21b365ebef66
|
[
"Apache-2.0"
] | null | null | null |
HwAREngineDemo/src/main/java/com/huawei/arengine/demos/common/converter/BmpProducer.java
|
Ar4enal/hms-AREngine-demo
|
d38657e9ee7521125eb8c41e67cb21b365ebef66
|
[
"Apache-2.0"
] | null | null | null |
HwAREngineDemo/src/main/java/com/huawei/arengine/demos/common/converter/BmpProducer.java
|
Ar4enal/hms-AREngine-demo
|
d38657e9ee7521125eb8c41e67cb21b365ebef66
|
[
"Apache-2.0"
] | null | null | null | 29.378378 | 104 | 0.626495 | 1,002,302 |
package com.huawei.arengine.demos.common.converter;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
public class BmpProducer extends Thread {
public static final String TAG="BmpProducer";
CustomFrameAvailableListner customFrameAvailableListner;
private boolean running = false;
long timestamp;
int destinationTextureId;
int viewWidth = 720;
int viewHeight = 1280;
boolean sendVaild = false;
public BmpProducer(Context context){
//start();
running = true;
}
BmpProducer(Bitmap bitmap, CustomFrameAvailableListner customFrameAvailableListner){
this.customFrameAvailableListner = customFrameAvailableListner;
start();
}
public void setCustomFrameAvailableListner(CustomFrameAvailableListner customFrameAvailableListner){
this.customFrameAvailableListner = customFrameAvailableListner;
}
public void setBitmapData( long ts, int TextureId, int width, int height) {
Log.d(TAG, "setBitmapData: ");
timestamp = ts;
destinationTextureId = TextureId;
viewWidth = width;
viewHeight = height;
sendVaild = true;
if(customFrameAvailableListner == null)
return;
customFrameAvailableListner.onFrame(timestamp, destinationTextureId, viewWidth, viewHeight);
}
@Override
public void run() {
super.run();
while ((running)){
if(customFrameAvailableListner == null || sendVaild == false)
continue;
Log.d(TAG,"Writing frame");
customFrameAvailableListner.onFrame(timestamp, destinationTextureId, viewWidth, viewHeight);
sendVaild = false;
/*OTMainActivity.imageView.post(new Runnable() {
@Override
public void run() {
OTMainActivity.imageView.setImageBitmap(bg);
}
});*/
try{
Thread.sleep(5);
}catch (Exception e){
Log.d(TAG,e.toString());
}
}
}
public void close(){
running = false;
}
}
|
9242851d111917e7651b793717c93835932d1ebf
| 6,875 |
java
|
Java
|
blog-system/src/main/java/com/blog/module/business/controller/BlogController.java
|
duktig666/blog
|
1c48414d40c0fda7778b5eed8b1c5608dbfe07e0
|
[
"Apache-2.0"
] | 3 |
2021-09-15T12:55:01.000Z
|
2021-09-26T03:02:05.000Z
|
blog-system/src/main/java/com/blog/module/business/controller/BlogController.java
|
duktig666/blog
|
1c48414d40c0fda7778b5eed8b1c5608dbfe07e0
|
[
"Apache-2.0"
] | null | null | null |
blog-system/src/main/java/com/blog/module/business/controller/BlogController.java
|
duktig666/blog
|
1c48414d40c0fda7778b5eed8b1c5608dbfe07e0
|
[
"Apache-2.0"
] | null | null | null | 42.438272 | 150 | 0.688291 | 1,002,303 |
package com.blog.module.business.controller;
import com.blog.module.business.domain.Blog;
import com.blog.module.business.domain.bo.BlogBO;
import com.blog.module.business.service.BlogService;
import com.blog.module.business.service.dto.BlogCountDTO;
import com.blog.module.business.domain.vo.BlogAndLabelVO;
import com.blog.page.dto.PageResultDTO;
import com.blog.page.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 功能描述:
*
* @author RenShiWei
* Date: 2020/4/11 11:07
**/
@RestController
@RequestMapping("/api/blog")
@Api(tags = "博客管理模块")
public class BlogController {
@Autowired
private BlogService blogService;
@ApiOperation(value = "新增博客", notes = "新增一条博客信息;\nauthor:RSW")
@PostMapping
public ResponseEntity<Void> saveBlogType (
@ApiParam(name = "blog", value = "新增的博客信息", required = true)
@RequestBody @Validated BlogAndLabelVO blogAndLabelVO
) {
blogService.saveBlog(blogAndLabelVO.getBlog(), blogAndLabelVO.getBlogLabelIds());
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@ApiOperation(value = "删除一条博客", notes = "根据博客id,删除一条博客(并维护中间表);\nauthor:RSW")
@DeleteMapping("/{blogId}")
public ResponseEntity<Void> deleteBlog (
@ApiParam(name = "blogId", value = "博客id", required = true) @PathVariable Long blogId ) {
blogService.deleteBlog(blogId);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@ApiOperation(value = "批量删除博客", notes = "根据博客id集合,批量删除博客(并维护中间表);\nauthor:RSW")
@PostMapping("/ids")
public ResponseEntity<Void> deleteBlogs (
@ApiParam(name = "blogIds", value = "博客id集合", required = true) @RequestBody List<Long> blogIds ) {
blogService.deleteBlogs(blogIds);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@ApiOperation(value = "修改博客信息", notes = "修改博客信息(并维护中间表,先删除,在新增);\nauthor:RSW")
@PutMapping
public ResponseEntity<Void> updateBlog (
@ApiParam(name = "blog", value = "修改的博客信息", required = true) @RequestBody @Validated(Blog.UpdateGroup.class) BlogAndLabelVO blogAndLabelVO
) {
blogService.updateBlog(blogAndLabelVO.getBlog(), blogAndLabelVO.getBlogLabelIds());
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@ApiOperation(value = "查询一条博客信息", notes = "根据博客id,查询一条博客的详细信息(包含博客类型和博客标签);\nauthor:RSW")
@GetMapping("/{blogId}")
public ResponseEntity<BlogBO> queryBlogById (
@ApiParam(name = "blogId", value = "博客标签id", required = true) @PathVariable Long blogId ) {
return ResponseEntity.ok(blogService.queryBlogByBlogId(blogId));
}
@ApiOperation(value = "查询所有的博客信息(包含博客类型和博客标签)", notes = "可以分页和排序,可以根据博客标题、博客正文、博客摘要进行模糊查询;\nauthor:RSW")
@GetMapping("/all")
public ResponseEntity<PageResultDTO<BlogBO>> queryBlogList (
@ApiParam(name = "pageVo", value = "分页信息") PageVO pageVo,
@ApiParam(name = "blogDimSearchStr", value = "博客模糊查询所需数据")
@RequestParam(required = false) String blogDimSearchStr,
@ApiParam(name = "blogDateRange", value = "按照时间区间查询博客,开始时间")
@RequestParam(required = false,defaultValue = "2020-01-01 00:00:00") String blogDateStart,
@ApiParam(name = "blogDateEnd", value = "按照时间区间查询博客,结束时间")
@RequestParam(required = false) String blogDateEnd
) {
//转换开始时间
Timestamp blogDateTimeStart = Timestamp.valueOf(blogDateStart);
// 给时间区间结束时间设置默认时间为当前时间
Timestamp blogDateTimeEnd;
if(blogDateEnd==null) { // 如果结束时间为空,设置默认时间为当前时间
blogDateTimeEnd = new Timestamp((new Date()).getTime());
} else {
blogDateTimeEnd = Timestamp.valueOf(blogDateEnd);
}
return ResponseEntity.ok(blogService.queryBlogList(pageVo, blogDimSearchStr, blogDateTimeStart,blogDateTimeEnd));
}
@ApiOperation(value = "查询所有的博客信息(不包含博客类型和博客标签)", notes = "可以分页和排序,可以根据博客标题、博客正文、博客摘要进行模糊查询;\nauthor:RSW")
@GetMapping("/all/single")
public ResponseEntity<PageResultDTO<Blog>> queryBlogAll (
@ApiParam(name = "pageVo", value = "分页信息") PageVO pageVo,
@ApiParam(name = "blogDimSearchStr", value = "博客模糊查询所需数据")
@RequestParam(required = false) String blogDimSearchStr
) {
return ResponseEntity.ok(blogService.queryBlogAll(pageVo, blogDimSearchStr));
}
@ApiOperation(value = "查询博客的总访问量、点赞量、评论量", notes = "查询博客的总访问量、点赞量、评论量;\nauthor:RSW")
@GetMapping("/count")
public ResponseEntity<BlogCountDTO> queryBlogCount () {
return ResponseEntity.ok(blogService.queryBlogCount());
}
@ApiOperation(value = "根据博客类型id查询所有的博客信息", notes = "可以分页和排序;\nauthor:JQJ")
@GetMapping("/all/byTypeId")
public ResponseEntity<PageResultDTO<Blog>> queryBlogByType (
@ApiParam(name = "pageVo", value = "分页信息") PageVO pageVo,
@ApiParam(name = "typeId", value = "博客类型ID")
@RequestParam(required = false) Integer typeId
) {
return ResponseEntity.ok(blogService.queryBlogByType(pageVo, typeId));
}
@ApiOperation(value = "根据博客标签id查询所有的博客信息", notes = "可以分页和排序;\nauthor:JQJ")
@GetMapping("/all/buLabelIds")
public ResponseEntity<PageResultDTO<Blog>> queryBlogByLabelIds (
@ApiParam(name = "pageVo", value = "分页信息") PageVO pageVo,
@ApiParam(name = "labelId", value = "博客标签ID")
@RequestParam("labelId") Long labelId
) {
return ResponseEntity.ok(blogService.queryBlogByLabelId(pageVo, labelId));
}
@ApiOperation(value = "增加博客的浏览量", notes = "增加博客的浏览量;\nauthor:RSW")
@PutMapping("/increase-view-number/{blogId}")
public ResponseEntity<Void> increaseViewCount (
@ApiParam(name = "blogId", value = "博客id", required = true) @PathVariable Long blogId
) {
blogService.increaseViewCount(blogId);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@ApiOperation(value = "增加博客的点赞量", notes = "增加博客的点赞量;\nauthor:RSW")
@PutMapping("/increase-like-number/{blogId}")
public ResponseEntity<Void> increaseLikeCount (
@ApiParam(name = "blogId", value = "博客id", required = true) @PathVariable Long blogId
) {
blogService.increaseLikeCount(blogId);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}
|
924285f7b5d6f492adbf6b8b2a279aca51b114ed
| 1,176 |
java
|
Java
|
src/main/java/com/project/schoolsystem/ui/departments/DepartmentTile.java
|
muiz6/school-management-system
|
b9771565385578aa555019b174cbe334c17746ba
|
[
"MIT"
] | null | null | null |
src/main/java/com/project/schoolsystem/ui/departments/DepartmentTile.java
|
muiz6/school-management-system
|
b9771565385578aa555019b174cbe334c17746ba
|
[
"MIT"
] | null | null | null |
src/main/java/com/project/schoolsystem/ui/departments/DepartmentTile.java
|
muiz6/school-management-system
|
b9771565385578aa555019b174cbe334c17746ba
|
[
"MIT"
] | null | null | null | 24 | 107 | 0.693878 | 1,002,304 |
package com.project.schoolsystem.ui.departments;
import com.project.schoolsystem.R;
import io.reactivex.annotations.Nullable;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class DepartmentTile implements Initializable {
@FXML
private Label labelTitle;
@FXML
private Label labelDepartmentCode;
@FXML
private HBox root;
@Override
public void initialize(URL location, ResourceBundle resources) {}
@Nullable
public static DepartmentTile inflate() {
final FXMLLoader loader = new FXMLLoader(DepartmentTile.class.getResource(R.Fxml.DEPARTMENT_TILE));
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
return loader.getController();
}
public Label getLabelTitle() {
return labelTitle;
}
public Label getLabelDepartmentCode() {
return labelDepartmentCode;
}
public HBox getRoot() {
return root;
}
}
|
9242862326b3b8d9908bf13366b561f1d4501d77
| 389 |
java
|
Java
|
src/main/java/com/wangxt/mybatis/test/dao/UserDao.java
|
wxt1471520488/wxt-mybatis-test
|
992231c62150d3a6f5f8c4012b683a7c03e6e524
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/wangxt/mybatis/test/dao/UserDao.java
|
wxt1471520488/wxt-mybatis-test
|
992231c62150d3a6f5f8c4012b683a7c03e6e524
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/wangxt/mybatis/test/dao/UserDao.java
|
wxt1471520488/wxt-mybatis-test
|
992231c62150d3a6f5f8c4012b683a7c03e6e524
|
[
"Apache-2.0"
] | null | null | null | 16.913043 | 43 | 0.601542 | 1,002,305 |
package com.wangxt.mybatis.test.dao;
import com.wangxt.mybatis.test.pojo.UserDo;
import java.util.List;
public interface UserDao {
/**
* @author wangxt
* @description 查询所有用户
* @date 2022/2/8 9:57
**/
List<UserDo> queryList();
/**
* @author wangxt
* @description 查询单个用户
* @date 2022/2/8 9:58
**/
UserDo queryUser(UserDo user);
}
|
9242864cf1299db79b245c06b5e5c1c31bfe85ef
| 1,584 |
java
|
Java
|
aliyun-java-sdk-polardbx-v5/src/main/java/com/aliyuncs/v5/polardbx/transform/v20200202/UpgradeDBInstanceKernelVersionResponseUnmarshaller.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | 4 |
2020-05-14T05:04:30.000Z
|
2021-08-20T11:08:46.000Z
|
aliyun-java-sdk-polardbx-v5/src/main/java/com/aliyuncs/v5/polardbx/transform/v20200202/UpgradeDBInstanceKernelVersionResponseUnmarshaller.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | 2 |
2020-10-13T07:47:10.000Z
|
2021-06-04T02:42:57.000Z
|
aliyun-java-sdk-polardbx-v5/src/main/java/com/aliyuncs/v5/polardbx/transform/v20200202/UpgradeDBInstanceKernelVersionResponseUnmarshaller.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | null | null | null | 49.5 | 171 | 0.834596 | 1,002,306 |
/*
* 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.aliyuncs.v5.polardbx.transform.v20200202;
import com.aliyuncs.v5.polardbx.model.v20200202.UpgradeDBInstanceKernelVersionResponse;
import com.aliyuncs.v5.transform.UnmarshallerContext;
public class UpgradeDBInstanceKernelVersionResponseUnmarshaller {
public static UpgradeDBInstanceKernelVersionResponse unmarshall(UpgradeDBInstanceKernelVersionResponse upgradeDBInstanceKernelVersionResponse, UnmarshallerContext _ctx) {
upgradeDBInstanceKernelVersionResponse.setRequestId(_ctx.stringValue("UpgradeDBInstanceKernelVersionResponse.RequestId"));
upgradeDBInstanceKernelVersionResponse.setDBInstanceName(_ctx.stringValue("UpgradeDBInstanceKernelVersionResponse.DBInstanceName"));
upgradeDBInstanceKernelVersionResponse.setTaskId(_ctx.stringValue("UpgradeDBInstanceKernelVersionResponse.TaskId"));
upgradeDBInstanceKernelVersionResponse.setTargetMinorVersion(_ctx.stringValue("UpgradeDBInstanceKernelVersionResponse.TargetMinorVersion"));
return upgradeDBInstanceKernelVersionResponse;
}
}
|
924286bc4774f2de915ced2f8e5ef3f286bce36b
| 6,354 |
java
|
Java
|
src/test/java/com/codeberry/tadlib/tensor/LargeGradientTest.java
|
pingng/tadlib
|
bbfcad4e52af40adaa9e736444763fd02e0e995c
|
[
"MIT"
] | 3 |
2021-07-25T17:19:06.000Z
|
2022-01-07T02:59:47.000Z
|
src/test/java/com/codeberry/tadlib/tensor/LargeGradientTest.java
|
pingng/tadlib
|
bbfcad4e52af40adaa9e736444763fd02e0e995c
|
[
"MIT"
] | null | null | null |
src/test/java/com/codeberry/tadlib/tensor/LargeGradientTest.java
|
pingng/tadlib
|
bbfcad4e52af40adaa9e736444763fd02e0e995c
|
[
"MIT"
] | null | null | null | 38.743902 | 182 | 0.683664 | 1,002,307 |
package com.codeberry.tadlib.tensor;
import com.codeberry.tadlib.array.NDArray;
import com.codeberry.tadlib.example.TrainingData;
import com.codeberry.tadlib.nn.model.Model;
import com.codeberry.tadlib.nn.model.ModelFactory;
import com.codeberry.tadlib.nn.model.SequentialModel;
import com.codeberry.tadlib.nn.model.TrainStats;
import com.codeberry.tadlib.nn.model.optimizer.SGD;
import com.codeberry.tadlib.provider.ProviderStore;
import com.codeberry.tadlib.provider.java.JavaProvider;
import com.codeberry.tadlib.provider.opencl.OpenCLProvider;
import com.codeberry.tadlib.util.MatrixTestUtils;
import com.codeberry.tadlib.util.StringUtils;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import static com.codeberry.tadlib.example.mnist.MNISTLoader.generate;
import static com.codeberry.tadlib.example.mnist.TrainConfiguredConvMNISTMain.ModelSize;
import static com.codeberry.tadlib.example.mnist.TrainConfiguredConvMNISTMain.createModelFactory;
import static com.codeberry.tadlib.nn.model.optimizer.FixedLearningRate.fixedLearningRate;
import static com.codeberry.tadlib.provider.java.JavaProvider.ThreadMode.MULTI_THREADED;
import static com.codeberry.tadlib.provider.java.JavaProvider.ThreadMode.SINGLE_THREADED;
import static org.junit.jupiter.api.Assertions.fail;
public class LargeGradientTest {
public static final int TEST_EPOCHS = 3;
public static final int TRAINING_EXAMPLES = 16;
public static final double LEARNING_RATE = 0.1;
@Test
public void testGradientWhileTrainingModel_SingleThreaded() {
ProviderStore.setProvider(new JavaProvider(SINGLE_THREADED));
doTest();
}
@Test
public void testGradientWhileTrainingModel_MultiThreaded() {
ProviderStore.setProvider(new JavaProvider(MULTI_THREADED));
doTest();
}
@Test
public void testGradientWhileTrainingModel_OpenCL() {
ProviderStore.setProvider(new OpenCLProvider());
doTest();
}
private void doTest() {
Random rand = new Random(4);
TrainingData data = generate(rand, TRAINING_EXAMPLES);
ModelFactory modelFactory =
createConvolutionModelFactory()
// createFullyConnectedModelFactory()
;
Model model = modelFactory.createModel();
System.out.println("Model: " + model.getClass().getSimpleName());
double sumError = 0;
for (int epoch = 0; epoch <= TEST_EPOCHS; epoch++) {
System.out.println("=== Epoch " + epoch);
sumError += testGradients(data, model, epoch);
System.out.println("* avgError=" + (sumError / (epoch + 1)));
trainModel(data, model, epoch);
}
}
private static SequentialModel.Factory createConvolutionModelFactory() {
return createModelFactory(ModelSize.TINY);
}
private double testGradients(TrainingData trainingData, Model model, int epoch) {
model.calcGradient(new Random(epoch), trainingData.getTrainingBatchAll(), new Model.IterationInfo(0, 0, 1));
List<NDArray> gradients = model.getGradients();
List<Object> gradientDoubles = gradients.stream()
.map(NDArray::toDoubles)
.collect(Collectors.toList());
ErrorValidator errorValidator = new ErrorValidator();
NumericalGradientEstimator estimator = new NumericalGradientEstimator(trainingData, model, epoch);
for (int i = 0; i < gradientDoubles.size(); i++) {
Object autoGradGradient = gradientDoubles.get(i);
NDArray numericalEstimatedGrad = estimator.estimateParamGradIndex(i);
errorValidator.validateAndAccumulateErr(autoGradGradient, numericalEstimatedGrad);
}
return errorValidator.getAvgError();
}
private static class ErrorValidator {
private static final double IDEAL_ERR_ASPECT = 5e-7;
private static final double MAX_ERR_ASPECT = 0.055;
private static final int MAX_CONSECUTIVE_LARGE_ASPECT_TIMES = 4;
private int consecutiveLargeAspectCount = 0;
private int sumErrorCount;
private double sumError;
public boolean isNotOk(double errAspect) {
return errAspect >= IDEAL_ERR_ASPECT;
}
public void failWhenTooLargeOrTooOften(double errAspect) {
if (isNotOk(errAspect)) {
consecutiveLargeAspectCount++;
} else {
consecutiveLargeAspectCount = 0;
}
System.out.println("errAspect = " + errAspect + " consecutiveLargeAspectCount=" + consecutiveLargeAspectCount);
if (consecutiveLargeAspectCount > MAX_CONSECUTIVE_LARGE_ASPECT_TIMES) {
fail("Err Aspect was big too often!");
}
if (errAspect > MAX_ERR_ASPECT) {
fail("Too large error aspect!");
}
}
private void validateAndAccumulateErr(Object autoGradGradient, NDArray numericalGrad) {
Object numericalGradient = numericalGrad.toDoubles();
double errAspect = MatrixTestUtils.calcErrAspect(
autoGradGradient,
numericalGradient);
if (isNotOk(errAspect)) {
System.err.println("ErrAspect: " + errAspect + " (ideally below " + IDEAL_ERR_ASPECT + ")");
System.err.println("Backprop: " + StringUtils.toString(numericalGrad.getShape(), autoGradGradient));
System.err.println("Numerical: " + StringUtils.toString(numericalGrad.getShape(), numericalGradient));
}
failWhenTooLargeOrTooOften(errAspect);
this.sumError += errAspect;
this.sumErrorCount++;
}
public double getAvgError() {
return sumError / sumErrorCount;
}
}
private void trainModel(TrainingData trainingData, Model model, int epoch) {
Random dropRnd = new Random(epoch);
TrainStats stats = new TrainStats();
Model.PredictionAndLosses pl = model.trainSingleIteration(dropRnd, trainingData.getTrainingBatchAll(), new SGD(fixedLearningRate(0.1)), new Model.IterationInfo(epoch, 0, 1));
stats.accumulate(pl, trainingData.yTrain);
System.out.println("Trained: " + stats);
}
}
|
924286c6142b7864ab1d5f3aa2f4155d67074a55
| 6,615 |
java
|
Java
|
src/main/java/net/justminecraft/minigames/minigamecore/worldbuffer/WorldBuffer.java
|
KK964/MinigameCore
|
fd83f7889b99b57994d2f7d53b345447c751fbef
|
[
"MIT"
] | null | null | null |
src/main/java/net/justminecraft/minigames/minigamecore/worldbuffer/WorldBuffer.java
|
KK964/MinigameCore
|
fd83f7889b99b57994d2f7d53b345447c751fbef
|
[
"MIT"
] | null | null | null |
src/main/java/net/justminecraft/minigames/minigamecore/worldbuffer/WorldBuffer.java
|
KK964/MinigameCore
|
fd83f7889b99b57994d2f7d53b345447c751fbef
|
[
"MIT"
] | 2 |
2021-01-16T19:07:47.000Z
|
2021-01-16T20:58:03.000Z
| 39.142012 | 157 | 0.567649 | 1,002,308 |
package net.justminecraft.minigames.minigamecore.worldbuffer;
import com.sk89q.jnbt.*;
import net.minecraft.server.v1_8_R3.NBTCompressedStreamTools;
import net.minecraft.server.v1_8_R3.RegionFileCache;
import org.bukkit.Location;
import org.bukkit.Material;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* A basic API that allows for fast world modifications on unloaded chunks
*
* @author PureGero
*/
public class WorldBuffer {
public byte defaultBlockLight = 0x0;
public byte defaultSkyLight = 0xF;
public File worldFolder;
public ArrayList<Chunk> chunks = new ArrayList<>();
public WorldBuffer(File worldFolder) {
this.worldFolder = worldFolder;
}
private static byte Nibble4(byte[] arr, int index) {
return (byte) ((index & 1) == 0 ? arr[index >> 1] & 0x0F : (arr[index >> 1] >> 4) & 0x0F);
}
private static void Nibble4(byte[] arr, int index, byte value) {
arr[index >> 1] = (byte) ((index & 1) == 0 ? ((arr[index >> 1] >> 4) << 4) + (value & 0x0F) : (arr[index >> 1] & 0x0F) + (value << 4));
}
/**
* Get child tag of a NBT structure.
*
* @param items The parent tag map
* @param key The name of the tag to get
* @param expected The expected type of the tag
* @return child tag casted to the expected type
* @throws IOException if the tag does not exist or the tag is not of the expected type
*/
private static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws IOException {
if (!items.containsKey(key)) {
throw new IOException("Schematic file is missing a \"" + key + "\" tag");
}
Tag tag = items.get(key);
if (!expected.isInstance(tag)) {
throw new IOException(key + " tag is not of tag type " + expected.getName());
}
return expected.cast(tag);
}
public Chunk getChunkAt(int x, int z) {
for (int i = 0; i < chunks.size(); i++)
if (chunks.get(i).x == x && chunks.get(i).y == z)
return chunks.get(i);
return null;
}
public void blankChunk(int x, int z) {
Chunk c = getChunkAt(x, z);
if (c == null) new Chunk(x, z, this);
}
public void setBlockAt(Location l, Material m) {
setBlockAt(l, m, (byte) 0);
}
public void setBlockAt(Location l, Material m, byte dat) {
setBlockAt(l.getBlockX(), l.getBlockY(), l.getBlockZ(), m.getId(), dat);
}
public void setBlockAt(int x, int y, int z, int id) {
Chunk c = getChunkAt(x >> 4, z >> 4);
if (c == null) c = new Chunk(x >> 4, z >> 4, this);
c.setBlockId(x & 15, y, z & 15, id);
}
public void setBlockAt(int x, int y, int z, int id, byte dat) {
Chunk c = getChunkAt(x >> 4, z >> 4);
if (c == null) c = new Chunk(x >> 4, z >> 4, this);
c.setBlockIdAndData(x & 15, y, z & 15, id, dat);
}
/**
* @return The block id of the block at {@code x,y,z}
*/
public int getBlockAt(int x, int y, int z) {
Chunk c = getChunkAt(x >> 4, z >> 4);
if (c == null) return 0;
return c.getBlockId(x & 15, y, z & 15);
}
public int getBlockAt(Location l) {
return getBlockAt(l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
public HashMap<Material, ArrayList<Location>> placeSchematic(Location l, File schem, Material... search) {
return placeSchematic(l.getBlockX(), l.getBlockY(), l.getBlockZ(), schem, search);
}
public HashMap<Material, ArrayList<Location>> placeSchematic(int x, int y, int z, File schem, Material... search) {
HashMap<Material, ArrayList<Location>> l = new HashMap<>();
for (int i = 0; i < search.length; i++)
l.put(search[i], new ArrayList<>());
try {
// Based off https://github.com/sk89q/WorldEdit/blob/master/worldedit-core/src/main/java/com/sk89q/worldedit/schematic/MCEditSchematicFormat.java
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(new FileInputStream(schem)));
NamedTag rootTag = nbtStream.readNamedTag();
nbtStream.close();
if (!rootTag.getName().equals("Schematic")) {
throw new IOException("Tag \"Schematic\" does not exist or is not first");
}
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
Map<String, Tag> schematic = schematicTag.getValue();
if (!schematic.containsKey("Blocks")) {
throw new IOException("Schematic file is missing a \"Blocks\" tag");
}
short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
short height = getChildTag(schematic, "Height", ShortTag.class).getValue();
int ox = getChildTag(schematic, "WEOffsetX", IntTag.class).getValue();
int oy = getChildTag(schematic, "WEOffsetY", IntTag.class).getValue();
int oz = getChildTag(schematic, "WEOffsetZ", IntTag.class).getValue();
byte[] blockId = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
for (int j = 0; j < height; j++)
for (int k = 0; k < length; k++)
for (int i = 0; i < width; i++) {
byte id = blockId[((j * length) + k) * width + i];
setBlockAt(x + i + ox, y + j + oy, z + k + oz,
id, blockData[((j * length) + k) * width + i]);
for (int a = 0; a < search.length; a++)
if (id == search[a].getId())
l.get(search[a]).add(new Location(null, x + i + ox, y + j + oy, z + k + oz));
}
} catch (Exception e) {
e.printStackTrace();
}
return l;
}
/**
* Saves the modified chunks to the world file
*/
public void save() {
for (int i = 0; i < chunks.size(); i++) {
Chunk c = chunks.get(i);
try (DataOutputStream out = RegionFileCache.d(worldFolder, c.x, c.y)) {
NBTCompressedStreamTools.a(c.compile(), (DataOutput) out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
924287296423d0930d82da04a7feb7bf011fe0ff
| 2,653 |
java
|
Java
|
src/fi/aalto/pekman/energywastingapp/components/AbstractFileWriter.java
|
pekman/EnergyWastingApp
|
2344c973f407d4bd45c6e812f9c163930b163bae
|
[
"MIT"
] | 1 |
2017-08-29T11:30:41.000Z
|
2017-08-29T11:30:41.000Z
|
src/fi/aalto/pekman/energywastingapp/components/AbstractFileWriter.java
|
pekman/EnergyWastingApp
|
2344c973f407d4bd45c6e812f9c163930b163bae
|
[
"MIT"
] | null | null | null |
src/fi/aalto/pekman/energywastingapp/components/AbstractFileWriter.java
|
pekman/EnergyWastingApp
|
2344c973f407d4bd45c6e812f9c163930b163bae
|
[
"MIT"
] | null | null | null | 23.6875 | 98 | 0.639276 | 1,002,309 |
package fi.aalto.pekman.energywastingapp.components;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.util.Log;
public abstract class AbstractFileWriter extends Component {
protected static final String filename = "tmpfile";
protected static final int chunkSize = 65536;
/** Returns the directory to which the file is written */
protected abstract File getPath();
/** Returns maximum file size */
protected long getMaxFileSize() { return 32 * 1024 * 1024; }
protected WriterThread thread = null;
protected volatile boolean stopThread = false;
protected static final byte[] buffer;
static {
buffer = new byte[chunkSize];
new Random().nextBytes(buffer);
}
protected class WriterThread extends Thread {
private void onError() {
stopThread = true;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
markTurnedOff();
}
});
}
@Override
public void run() {
Log.d("AbstractFileWriter thread", "Starting write thread");
File file = new File(getPath(), filename);
long maxSize = getMaxFileSize();
while (! stopThread) {
// open file for writing (truncate if it exists)
FileOutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Log.e("AbstractFileWriter thread", e.getMessage(), e);
onError();
return;
}
Log.d("AbstractFileWriter thread", "File " + file.getAbsolutePath() + " opened");
long size = 0;
try {
// write to file until size limit reached
while (! stopThread && size <= maxSize) {
out.write(buffer, 0, chunkSize);
out.flush();
out.getFD().sync();
size += chunkSize;
}
} catch (IOException e) {
Log.e("AbstractFileWriter thread", e.getMessage(), e);
onError();
} finally {
Log.d("AbstractFileWriter thread", "Closing and deleting file (" + size + " bytes written)");
// close and delete file
try {
out.close();
} catch (IOException e) {
Log.e("AbstractFileWriter thread", "close: " + e.getMessage(), e);
}
if (! file.delete()) {
Log.w("AbstractFileWriter thread",
"cannot delete " + file.getAbsolutePath());
}
}
}
Log.d("AbstractFileWriter thread",
"Write thread stopped (" + file.getAbsolutePath() + ")");
}
}
@Override
public void start() {
thread = new WriterThread();
stopThread = false;
thread.start();
}
@Override
public void stop() {
stopThread = true;
}
}
|
9242881d0fed6e5cceebaf9f71f76a81f7598c95
| 1,145 |
java
|
Java
|
db/db-mybatis-plus-postgresql/src/main/java/com/chenbo/daomybatisplus/auth/enums/TypeEnum.java
|
wugenshui/demo-springboot
|
c665e3b317936a19a9782d31eb63113fafaa0116
|
[
"MIT"
] | null | null | null |
db/db-mybatis-plus-postgresql/src/main/java/com/chenbo/daomybatisplus/auth/enums/TypeEnum.java
|
wugenshui/demo-springboot
|
c665e3b317936a19a9782d31eb63113fafaa0116
|
[
"MIT"
] | 1 |
2022-02-16T01:16:07.000Z
|
2022-02-16T01:16:07.000Z
|
db/db-mybatis-plus-postgresql/src/main/java/com/chenbo/daomybatisplus/auth/enums/TypeEnum.java
|
wugenshui/demo-springboot
|
c665e3b317936a19a9782d31eb63113fafaa0116
|
[
"MIT"
] | null | null | null | 20.446429 | 100 | 0.620961 | 1,002,310 |
package com.chenbo.daomybatisplus.auth.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum TypeEnum {
USER(1, "用户"),
STAFF(2, "员工"),
SUPPLIER(3, "供应商");
/**
* 对应数据库的数据
*/
@EnumValue
private int code;
private String name;
TypeEnum(int code, String name) {
this.code = code;
this.name = name;
}
/**
* 反序列化
*
* @param code 数据库对应的值
* @return 枚举对象
*/
@JsonCreator
public static TypeEnum getByCode(@JsonProperty("code") int code) {
return Arrays.stream(TypeEnum.values()).filter(item -> item.code == code).findFirst().get();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
92428915115aea46f8e35c7a76da72db84f121e1
| 78 |
java
|
Java
|
arithmetic/leetcode/src/main/java/com/treeyh/example/arithmetic/leetcode/Application.java
|
treeyh/java-example
|
3b288007c8706cff064dea37f72d86bc532ccc5f
|
[
"MIT"
] | null | null | null |
arithmetic/leetcode/src/main/java/com/treeyh/example/arithmetic/leetcode/Application.java
|
treeyh/java-example
|
3b288007c8706cff064dea37f72d86bc532ccc5f
|
[
"MIT"
] | null | null | null |
arithmetic/leetcode/src/main/java/com/treeyh/example/arithmetic/leetcode/Application.java
|
treeyh/java-example
|
3b288007c8706cff064dea37f72d86bc532ccc5f
|
[
"MIT"
] | null | null | null | 15.6 | 47 | 0.807692 | 1,002,311 |
package com.treeyh.example.arithmetic.leetcode;
public class Application {
}
|
924289bbb4e6843ae737c45b88b43c211d9a4c90
| 1,040 |
java
|
Java
|
src/main/java/me/unp0wnable/groupeo/model/entities/UserAddress.java
|
unp0wnable/groupeo-backend
|
9dbb13ca6f0533ec458a253812ef68b94c6574b0
|
[
"CC0-1.0"
] | null | null | null |
src/main/java/me/unp0wnable/groupeo/model/entities/UserAddress.java
|
unp0wnable/groupeo-backend
|
9dbb13ca6f0533ec458a253812ef68b94c6574b0
|
[
"CC0-1.0"
] | 3 |
2022-02-14T13:33:46.000Z
|
2022-02-23T10:33:15.000Z
|
src/main/java/me/unp0wnable/groupeo/model/entities/UserAddress.java
|
unp0wnable/groupeo-backend
|
9dbb13ca6f0533ec458a253812ef68b94c6574b0
|
[
"CC0-1.0"
] | null | null | null | 26.666667 | 81 | 0.675962 | 1,002,312 |
package me.unp0wnable.groupeo.model.entities;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.util.UUID;
@Data
@Entity
@Table(name = "UserAddress")
public class UserAddress {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Type(type = "org.hibernate.type.PostgresUUIDType")
@Column(name = "userProfileID", nullable = false)
private UUID userAddressID;
@Column(name = "city", length = 50)
private String city;
@Column(name = "region", length = 50)
private String region;
@Column(name = "postalCode", length = 10)
private String postalCode;
@Column(name = "country", length = 50)
private String country;
@OneToOne(optional = false,
orphanRemoval = true,
fetch = FetchType.LAZY)
@JoinColumn(name = "userProfileID")
private UserProfile userProfile;
}
|
92428a9593bf797e5c36a09a6ab42cef3c35c066
| 3,047 |
java
|
Java
|
core/src/test/java/org/infinispan/lock/StaleEagerLocksOnPrepareFailureTest.java
|
hhstechgroup/infinispan
|
5972ce34a47cc9da836d5144d45e0d47c5caa5a8
|
[
"Apache-2.0"
] | 2 |
2015-04-28T21:43:44.000Z
|
2016-11-24T10:11:26.000Z
|
core/src/test/java/org/infinispan/lock/StaleEagerLocksOnPrepareFailureTest.java
|
hhstechgroup/infinispan
|
5972ce34a47cc9da836d5144d45e0d47c5caa5a8
|
[
"Apache-2.0"
] | 41 |
2019-06-11T11:25:03.000Z
|
2021-08-02T16:57:31.000Z
|
core/src/test/java/org/infinispan/lock/StaleEagerLocksOnPrepareFailureTest.java
|
hhstechgroup/infinispan
|
5972ce34a47cc9da836d5144d45e0d47c5caa5a8
|
[
"Apache-2.0"
] | null | null | null | 32.073684 | 91 | 0.70233 | 1,002,313 |
package org.infinispan.lock;
import org.infinispan.Cache;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.InterceptorChain;
import org.infinispan.interceptors.distribution.TxDistributionInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNull;
@Test(testName = "lock.StaleEagerLocksOnPrepareFailureTest", groups = "functional")
@CleanupAfterMethod
public class StaleEagerLocksOnPrepareFailureTest extends MultipleCacheManagersTest {
Cache<MagicKey, String> c1, c2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cfg
.transaction()
.lockingMode(LockingMode.PESSIMISTIC)
.useSynchronization(false)
.recovery()
.disable()
.locking()
.lockAcquisitionTimeout(100);
EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(cfg);
EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(cfg);
registerCacheManager(cm1, cm2);
c1 = cm1.getCache();
c2 = cm2.getCache();
waitForClusterToForm();
}
public void testNoModsCommit() throws Exception {
doTest(false);
}
public void testModsCommit() throws Exception {
doTest(true);
}
private void doTest(boolean mods) throws Exception {
// force the prepare command to fail on c2
FailInterceptor interceptor = new FailInterceptor();
interceptor.failFor(PrepareCommand.class);
InterceptorChain ic = TestingUtil.extractComponent(c2, InterceptorChain.class);
ic.addInterceptorBefore(interceptor, TxDistributionInterceptor.class);
MagicKey k1 = new MagicKey("k1", c1);
MagicKey k2 = new MagicKey("k2", c2);
tm(c1).begin();
if (mods) {
c1.put(k1, "v1");
c1.put(k2, "v2");
assertKeyLockedCorrectly(k1);
assertKeyLockedCorrectly(k2);
} else {
c1.getAdvancedCache().lock(k1);
c1.getAdvancedCache().lock(k2);
assertNull(c1.get(k1));
assertNull(c1.get(k2));
assertKeyLockedCorrectly(k1);
assertKeyLockedCorrectly(k2);
}
try {
tm(c1).commit();
assert false : "Commit should have failed";
} catch (Exception e) {
// expected
}
assertNotLocked(c1, k1);
assertNotLocked(c2, k1);
assertNotLocked(c1, k2);
assertNotLocked(c2, k2);
}
}
|
92428b346bc6d268ce5a2753ce4f9126da149044
| 2,119 |
java
|
Java
|
src/main/java/discovery/table/FakeInMemoryTable.java
|
amccurry/discovery
|
eb6674dea38755e811f7ad9f90bbeaa34a60855c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/discovery/table/FakeInMemoryTable.java
|
amccurry/discovery
|
eb6674dea38755e811f7ad9f90bbeaa34a60855c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/discovery/table/FakeInMemoryTable.java
|
amccurry/discovery
|
eb6674dea38755e811f7ad9f90bbeaa34a60855c
|
[
"Apache-2.0"
] | null | null | null | 25.53012 | 75 | 0.683341 | 1,002,314 |
/**
* 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 discovery.table;
import java.util.List;
import discovery.DiscoveryResultSet;
import discovery.Table;
import discovery.request.DataRequest;
public class FakeInMemoryTable extends Table {
private String _id;
private List<String> _cols;
public FakeInMemoryTable(String id, List<String> columnNames) {
_id = id;
_cols = columnNames;
}
public long getRecordTotal() {
return 1000000000000L;
}
public List<String> getColumnNames() {
return _cols;
}
public String getTableId() {
return _id;
}
@Override
public DiscoveryResultSet executeRequest(DataRequest dataRequest) {
System.out.println(dataRequest);
long start = dataRequest.getStart();
int length = dataRequest.getLength();
return new BaseDiscoveryResultSet(dataRequest) {
@Override
public long getRecordCount() {
return 100000l;
}
private int count = 0;
@Override
public boolean next() {
if (count < length) {
count++;
return true;
}
return false;
}
@Override
public String getRowId() {
return Long.toString(start + count);
}
@Override
public Object getColumnValue(String columnName) {
return columnName + " " + getRowId();
}
};
}
}
|
92428b9db842c1272a5fe8aac89fe02a90097941
| 8,155 |
java
|
Java
|
interpreter/virtualmachine/RunTimeStack.java
|
tzphuang/interpreter
|
8c9c01b245a0af254ad096f14d96329829c198ff
|
[
"MIT"
] | null | null | null |
interpreter/virtualmachine/RunTimeStack.java
|
tzphuang/interpreter
|
8c9c01b245a0af254ad096f14d96329829c198ff
|
[
"MIT"
] | null | null | null |
interpreter/virtualmachine/RunTimeStack.java
|
tzphuang/interpreter
|
8c9c01b245a0af254ad096f14d96329829c198ff
|
[
"MIT"
] | null | null | null | 29.440433 | 115 | 0.579277 | 1,002,315 |
package interpreter.virtualmachine;
import java.util.ArrayList;
import java.util.Stack;
class RunTimeStack {
private ArrayList<Integer> runTimeStack;
private Stack<Integer> framePointer;
public RunTimeStack() {
runTimeStack = new ArrayList<>();
framePointer = new Stack<>();
// Add initial Frame Pointer, main is the entry
// point of our language, so its frame pointer is 0.
framePointer.push(0);
}
public void dump ()
{/*
* Used for dumping the current state of the runTimeStack.
* * It will print portions of the stack based on respective * frame markers.
* Example [1,2,3] [4,5,6] [7,8]
* Frame pointers would be 0,3,6
*/
ArrayList<String> dumpString = new ArrayList<>();
Stack<Integer> currStack = new Stack<>();
Integer curInt = -1;
String printString = "";
//this is so the currStack doesnt empty out early so I can
//loop through the currStack entirely
currStack.push(curInt);
//reverse order of stack and store in currStack
while(!(framePointer.empty())){
curInt= framePointer.pop();
currStack.push(curInt);
}
Integer currFramePointer;
Integer count = 0;
Integer countPlusOne = 1;
//keep looping through currStack until empty
while (!currStack.empty()) {
currFramePointer = currStack.pop();
//if the currentFramePointer is 0,
//ignore it move onto the next frame pointer
if(currFramePointer.equals(0)){
framePointer.push(currFramePointer);
//if the current frame stack is now empty since 0
//was the only frame pointer, set currFramePointer to -1
if(!(currStack.empty())){
currFramePointer = currStack.pop();
}
else{
currFramePointer = -1;
}
}
//System.out.print("[");
dumpString.add("[");
for(; count < runTimeStack.size(); count++, countPlusOne++){
if(countPlusOne.equals(currFramePointer)){
//System.out.print(runTimeStack.get(count));
dumpString.add(runTimeStack.get(count) + "");
count++;
countPlusOne++;
break;
}
else{
//System.out.print(runTimeStack.get(count) + ",");
dumpString.add(runTimeStack.get(count) + ",");
}
/*if(!countPlusOne.equals(currFramePointer)){
System.out.print(",");
}*/
}
//System.out.print("]");
dumpString.add("]");
framePointer.push(currFramePointer); //push back currFramePointer onto
}
for(String currString: dumpString){
printString += currString;
}
printString = printString.replace(",]", "]");
System.out.println(printString);
//pops the Integer -1 off the frame pointer stack that was used
//for printing purposes
framePointer.pop();
//System.out.println();
}
public int peek ()
{/*
* returns the top of the runtime stack, but does not remove
* @return copy of the top of the stack.
*/
int returnInt = runTimeStack.get(runTimeStack.size()-1);
return returnInt;
}
public int push(int i)
{/*
* push the value i to the top of the stack.
* @param i value to be pushed.
* @return value pushed
*/
Integer pushInt = i;
runTimeStack.add(pushInt);
return this.peek();
}
public int pop()
{/*
* removes to the top of the runtime stack.
* @return the value popped.
*/
int returnInt = runTimeStack.get(runTimeStack.size()-1);
runTimeStack.remove(runTimeStack.size()-1);
return returnInt;
}
public int store(int offset)
{/*
* Takes the top item of the run Time stack, and stores
* it into a offset starting from the current frame.
* @param offset number of slots above current frame marker
* @return the item just stored
*/
Integer currFrame = framePointer.peek();
Integer lastItem = runTimeStack.get(runTimeStack.size()-1);
currFrame = currFrame + offset;
runTimeStack.add(currFrame, lastItem);
return lastItem;
}
public int load(int offset)
{/*
* Takes a value from the run time stack that is at offset
* from the current frame marker and pushes it onto the top of the stack.
* @param offset number of slots above current frame marker
* @return item just loaded into the offset
*/
Integer currFrame = framePointer.peek();
currFrame = currFrame + offset;
Integer loadedItem = runTimeStack.get( (int) currFrame );
runTimeStack.add(loadedItem);
return (int) loadedItem;
}
public void newFrameAt(int offset) //this is different because offset is from the top of RunTimeStack
{/*
* create a new frame pointer at the index offset slots down
* from the top of the runtime stack.
* @param offset slots down from the top of the runtime stack
* */
Integer newFramePtr = runTimeStack.size() - offset;
if(0 > newFramePtr ){
newFramePtr = 0;
}
framePointer.push(newFramePtr);
}
public void popFrame()
{/*
* pop the current frame off the runtime stack. Also removes
* the frame pointer value from the FramePointer Stack.
*/
//inside runTimeStack keep deleting elements at index[framePointer stack]
//until the size of the runTimeStack is equivalent to the framePointer at the top of the FramePointer stack
Integer peekedInt = framePointer.peek();
while( !( ( (Integer) runTimeStack.size() ).equals( peekedInt ) ) ){
runTimeStack.remove( (int) peekedInt );
}
framePointer.pop();
}
//returns size of the RunTimeStack
public int sizeStack(){
return runTimeStack.size();
}
public int peekTopFramePtr(){
return framePointer.peek();
}
public int numIntInFrame() {
int sizeOfRTStack;
int currFramePointer;
int numIntsInCurrFrame;
sizeOfRTStack = runTimeStack.size();
currFramePointer = peekTopFramePtr();
numIntsInCurrFrame = sizeOfRTStack - currFramePointer;
return numIntsInCurrFrame;
}
/*
public static void main(String[] args){
RunTimeStack currRTStack = new RunTimeStack();
currRTStack.push(1);
currRTStack.push(2);
//currRTStack.push(3);
currRTStack.push(4);
currRTStack.push(5);
currRTStack.push(6);
currRTStack.push(7);
currRTStack.push(8);
//checking if the peek() inside push() works and it does
System.out.println(currRTStack.push(3));
currRTStack.runTimeStack.forEach( val -> System.out.println(val)); //enhanced for each loop
for(int val: currRTStack.runTimeStack){
System.out.println(val);
}
//Example [1,2,3] [4,5,6] [7,8]
//Frame pointers would be 0,3,6
currRTStack.dump();
System.out.println("peeking " + currRTStack.peek());
System.out.println("storing " + currRTStack.store(2));
currRTStack.dump();
currRTStack.pop();
currRTStack.dump();
currRTStack.newFrameAt(5);
currRTStack.dump();
currRTStack.newFrameAt(2);
currRTStack.dump();
currRTStack.load(0);
currRTStack.load(1);
currRTStack.newFrameAt(2);
currRTStack.dump();
currRTStack.popFrame();
currRTStack.dump();
currRTStack.popFrame();
currRTStack.dump();
currRTStack.popFrame();
currRTStack.dump();
currRTStack.popFrame();
currRTStack.dump();
}*/
}
|
92428c66a4e03768c195232acec141ebb25c4915
| 814 |
java
|
Java
|
study-java-questions/src/com/example/StudyString2.java
|
kenanatasoy/Core-Spring-5
|
80a0dfdc092e7f76c22e5e4ebc245117942df261
|
[
"MIT"
] | 3 |
2022-01-04T11:31:02.000Z
|
2022-01-06T11:35:48.000Z
|
study-java-questions/src/com/example/StudyString2.java
|
kenanatasoy/Core-Spring-5
|
80a0dfdc092e7f76c22e5e4ebc245117942df261
|
[
"MIT"
] | null | null | null |
study-java-questions/src/com/example/StudyString2.java
|
kenanatasoy/Core-Spring-5
|
80a0dfdc092e7f76c22e5e4ebc245117942df261
|
[
"MIT"
] | 1 |
2022-01-06T04:43:29.000Z
|
2022-01-06T04:43:29.000Z
| 30.148148 | 81 | 0.72113 | 1,002,316 |
package com.example;
import java.text.DecimalFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class StudyString2 {
public static void main(String[] args) {
// java -Duser.language=tr -Duser.country=TR -jar myapp.jar
var city = "izmir";
// Locale
var tr = new Locale("tr", "TR");
System.out.println(city.toUpperCase(tr));
ZonedDateTime birthDate = ZonedDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
.withLocale(Locale.GERMAN);
System.out.println(dtf.format(birthDate));
var money = 10_345_786.56;
var df = DecimalFormat.getCurrencyInstance(Locale.KOREA);
System.out.println(df.format(money));
}
}
|
92428c6d6eb0b3d891e8a5d8c0edab6d42e849c9
| 2,571 |
java
|
Java
|
car-admin/src/main/java/com/car/modules/exam/entity/CategoryEntity.java
|
yangwenbang/car
|
22c27003fdbf448a257151bba39535022539a8d0
|
[
"Apache-2.0"
] | null | null | null |
car-admin/src/main/java/com/car/modules/exam/entity/CategoryEntity.java
|
yangwenbang/car
|
22c27003fdbf448a257151bba39535022539a8d0
|
[
"Apache-2.0"
] | 2 |
2021-04-22T16:53:26.000Z
|
2021-09-20T20:50:53.000Z
|
car-admin/src/main/java/com/car/modules/exam/entity/CategoryEntity.java
|
yangwenbang/car
|
22c27003fdbf448a257151bba39535022539a8d0
|
[
"Apache-2.0"
] | null | null | null | 14.878613 | 83 | 0.639472 | 1,002,317 |
package com.car.modules.car.entity;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author lzp
* @email [email protected]
* @date 2019-01-23 00:54:45
*/
@TableName("category")
public class CategoryEntity extends Model<CategoryEntity> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 分类id
*/
@TableId
private Long id;
/**
* 项目id
*/
private Long projectId;
/**
* 分类名字
*/
private String categoryName;
/**
* 分类描述
*/
private String categoryDesc;
/**
* 分类图片
*/
private String categoryPicture;
/**
* 是否有效
*/
private Integer effective;
/**
* 排序
*/
private Integer seq;
/**
* 创建时间
*/
private Date createDate;
/**
* 更新时间
*/
private Date updateTime;
/**
* 设置:分类id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取:分类id
*/
public Long getId() {
return id;
}
/**
* 设置:项目id
*/
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
/**
* 获取:项目id
*/
public Long getProjectId() {
return projectId;
}
/**
* 设置:分类名字
*/
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
/**
* 获取:分类名字
*/
public String getCategoryName() {
return categoryName;
}
/**
* 设置:分类描述
*/
public void setCategoryDesc(String categoryDesc) {
this.categoryDesc = categoryDesc;
}
/**
* 获取:分类描述
*/
public String getCategoryDesc() {
return categoryDesc;
}
/**
* 设置:分类图片
*/
public void setCategoryPicture(String categoryPicture) {
this.categoryPicture = categoryPicture;
}
/**
* 获取:分类图片
*/
public String getCategoryPicture() {
return categoryPicture;
}
/**
* 设置:是否有效
*/
public void setEffective(Integer effective) {
this.effective = effective;
}
/**
* 获取:是否有效
*/
public Integer getEffective() {
return effective;
}
/**
* 设置:排序
*/
public void setSeq(Integer seq) {
this.seq = seq;
}
/**
* 获取:排序
*/
public Integer getSeq() {
return seq;
}
/**
* 设置:创建时间
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* 获取:创建时间
*/
public Date getCreateDate() {
return createDate;
}
/**
* 设置:更新时间
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* 获取:更新时间
*/
public Date getUpdateTime() {
return updateTime;
}
@Override
protected Serializable pkVal() {
return id;
}
}
|
92428d124762a4575848501b1c4f52bb5acefa4f
| 1,960 |
java
|
Java
|
itsnatdroid/src/main/java/org/itsnat/droid/impl/xmlinflater/drawable/classtree/ClassDescGradientDrawableChildCorners.java
|
jmarranz/itsnat_droid
|
6b4e350ce6a52d82634b157a64395cffd090643c
|
[
"Apache-2.0"
] | 15 |
2015-09-16T04:47:26.000Z
|
2018-04-19T08:08:18.000Z
|
itsnatdroid/src/main/java/org/itsnat/droid/impl/xmlinflater/drawable/classtree/ClassDescGradientDrawableChildCorners.java
|
jmarranz/itsnat_droid
|
6b4e350ce6a52d82634b157a64395cffd090643c
|
[
"Apache-2.0"
] | null | null | null |
itsnatdroid/src/main/java/org/itsnat/droid/impl/xmlinflater/drawable/classtree/ClassDescGradientDrawableChildCorners.java
|
jmarranz/itsnat_droid
|
6b4e350ce6a52d82634b157a64395cffd090643c
|
[
"Apache-2.0"
] | 7 |
2015-09-16T04:48:14.000Z
|
2020-09-22T09:44:44.000Z
| 42.608696 | 196 | 0.778571 | 1,002,318 |
package org.itsnat.droid.impl.xmlinflater.drawable.classtree;
import org.itsnat.droid.impl.dom.drawable.DOMElemDrawable;
import org.itsnat.droid.impl.xmlinflated.drawable.ElementDrawableChild;
import org.itsnat.droid.impl.xmlinflated.drawable.ElementDrawableChildBase;
import org.itsnat.droid.impl.xmlinflated.drawable.GradientDrawableChildCorners;
import org.itsnat.droid.impl.xmlinflater.drawable.AttrDrawableContext;
import org.itsnat.droid.impl.xmlinflater.drawable.ClassDescDrawableMgr;
import org.itsnat.droid.impl.xmlinflater.shared.attr.AttrDescReflecMethodDimensionIntRound;
/**
* Created by jmarranz on 10/11/14.
*/
public class ClassDescGradientDrawableChildCorners extends ClassDescElementDrawableChildNormal<GradientDrawableChildCorners>
{
public ClassDescGradientDrawableChildCorners(ClassDescDrawableMgr classMgr)
{
super(classMgr,"shape:corners",null);
}
@Override
public Class<GradientDrawableChildCorners> getDrawableOrElementDrawableClass()
{
return GradientDrawableChildCorners.class;
}
@Override
public ElementDrawableChild createElementDrawableChild(DOMElemDrawable domElement, DOMElemDrawable domElementParent, ElementDrawableChildBase parentChildDrawable, AttrDrawableContext attrCtx)
{
return new GradientDrawableChildCorners(parentChildDrawable);
}
@SuppressWarnings("unchecked")
protected void init()
{
super.init();
addAttrDescAN(new AttrDescReflecMethodDimensionIntRound(this, "radius", 0f));
addAttrDescAN(new AttrDescReflecMethodDimensionIntRound(this, "topLeftRadius", 0f));
addAttrDescAN(new AttrDescReflecMethodDimensionIntRound(this, "topRightRadius", 0f));
addAttrDescAN(new AttrDescReflecMethodDimensionIntRound(this, "bottomRightRadius", 0f));
addAttrDescAN(new AttrDescReflecMethodDimensionIntRound(this, "bottomLeftRadius", 0f));
}
}
|
92428dff38b2d6d78194b742f92d4de92961e66a
| 2,301 |
java
|
Java
|
core/src/main/java/org/cybergarage/http/HTTPResponse.java
|
kforeverisback/cybergarage-upnp
|
3fe4c2d3617038d4d95c706d8aea2e798392343d
|
[
"BSD-3-Clause"
] | 290 |
2015-02-15T03:18:46.000Z
|
2022-03-03T02:52:42.000Z
|
cybergarage-upnp/src/main/java/org/cybergarage/http/HTTPResponse.java
|
laojiang19/MediaPlayer
|
5b7c3f2ebbff33b2fcb370c3bc0f389230a8b232
|
[
"Unlicense"
] | 23 |
2015-05-26T11:19:00.000Z
|
2022-02-06T14:55:29.000Z
|
cybergarage-upnp/src/main/java/org/cybergarage/http/HTTPResponse.java
|
flyingwjw/DLNAPlayer
|
88a4cfb08e21b70b6735b2f9c61f2954a32d2b4a
|
[
"Unlicense"
] | 103 |
2015-02-28T15:53:21.000Z
|
2022-03-16T03:21:02.000Z
| 19.666667 | 111 | 0.530639 | 1,002,319 |
/******************************************************************
*
* CyberHTTP for Java
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: HTTPResponse.java
*
* Revision;
*
* 11/18/02
* - first revision.
* 10/22/03
* - Changed to initialize a content length header.
* 10/22/04
* - Added isSuccessful().
*
******************************************************************/
package org.cybergarage.http;
import java.io.InputStream;
public class HTTPResponse extends HTTPPacket
{
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
public HTTPResponse()
{
setVersion(HTTP.VERSION_11);
setContentType(HTML.CONTENT_TYPE);
setServer(HTTPServer.getName());
setContent("");
}
public HTTPResponse(HTTPResponse httpRes)
{
set(httpRes);
}
public HTTPResponse(InputStream in)
{
super(in);
}
public HTTPResponse(HTTPSocket httpSock)
{
this(httpSock.getInputStream());
}
////////////////////////////////////////////////
// Status Line
////////////////////////////////////////////////
private int statusCode = 0;
public void setStatusCode(int code)
{
statusCode = code;
}
public int getStatusCode()
{
if (statusCode != 0)
return statusCode;
HTTPStatus httpStatus = new HTTPStatus(getFirstLine());
return httpStatus.getStatusCode();
}
public boolean isSuccessful()
{
return HTTPStatus.isSuccessful(getStatusCode());
}
public String getStatusLineString()
{
return "HTTP/" + getVersion() + " " + getStatusCode() + " " + HTTPStatus.code2String(statusCode) + HTTP.CRLF;
}
////////////////////////////////////////////////
// getHeader
////////////////////////////////////////////////
public String getHeader()
{
StringBuffer str = new StringBuffer();
str.append(getStatusLineString());
str.append(getHeaderString());
return str.toString();
}
////////////////////////////////////////////////
// toString
////////////////////////////////////////////////
public String toString()
{
StringBuffer str = new StringBuffer();
str.append(getStatusLineString());
str.append(getHeaderString());
str.append(HTTP.CRLF);
str.append(getContentString());
return str.toString();
}
public void print()
{
System.out.println(toString());
}
}
|
92428e8fab0e54a37ece02eb0454f148ed9c417a
| 1,404 |
java
|
Java
|
src/main/java/com/salesforce/einsteinbot/sdk/model/AnyVariable.java
|
forcedotcom/einstein-bot-sdk-java
|
8a25ef23f4f10313e439633cfd77ff6b6f66afa5
|
[
"BSD-3-Clause"
] | 3 |
2022-03-24T03:14:12.000Z
|
2022-03-30T18:17:09.000Z
|
src/main/java/com/salesforce/einsteinbot/sdk/model/AnyVariable.java
|
forcedotcom/einstein-bot-sdk-java
|
8a25ef23f4f10313e439633cfd77ff6b6f66afa5
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/com/salesforce/einsteinbot/sdk/model/AnyVariable.java
|
forcedotcom/einstein-bot-sdk-java
|
8a25ef23f4f10313e439633cfd77ff6b6f66afa5
|
[
"BSD-3-Clause"
] | null | null | null | 39 | 121 | 0.727208 | 1,002,320 |
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.salesforce.einsteinbot.sdk.model;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* AnyVariable - Base type to support polymorphic anyOf for Variables. Uses Jackson annotations to
* resolve subclass type based on value of 'type' field.
*
* @author relango
* @since 234
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = TextVariable.class, name = "text"),
@JsonSubTypes.Type(value = BooleanVariable.class, name = "boolean"),
@JsonSubTypes.Type(value = DateVariable.class, name = "date"),
@JsonSubTypes.Type(value = DateTimeVariable.class, name = "dateTime"),
@JsonSubTypes.Type(value = MoneyVariable.class, name = "money"),
@JsonSubTypes.Type(value = NumberVariable.class, name = "number"),
@JsonSubTypes.Type(value = ObjectVariable.class, name = "object"),
@JsonSubTypes.Type(value = ListVariable.class, name = "list"),
@JsonSubTypes.Type(value = RefVariable.class, name = "ref")
})
public interface AnyVariable {
String getName();
}
|
92428f3149e98d0cb6c8061f49f64beef5eaa438
| 353 |
java
|
Java
|
src/main/java/com/burakyildiz/springboot/business/exceptions/users/UserNotFoundException.java
|
n11-TalentHub-Java-Bootcamp/second-homework-byofficial
|
f715a6d0ce353b9e740f424bfce62b2ac049ce0b
|
[
"MIT"
] | null | null | null |
src/main/java/com/burakyildiz/springboot/business/exceptions/users/UserNotFoundException.java
|
n11-TalentHub-Java-Bootcamp/second-homework-byofficial
|
f715a6d0ce353b9e740f424bfce62b2ac049ce0b
|
[
"MIT"
] | null | null | null |
src/main/java/com/burakyildiz/springboot/business/exceptions/users/UserNotFoundException.java
|
n11-TalentHub-Java-Bootcamp/second-homework-byofficial
|
f715a6d0ce353b9e740f424bfce62b2ac049ce0b
|
[
"MIT"
] | null | null | null | 29.416667 | 62 | 0.813031 | 1,002,321 |
package com.burakyildiz.springboot.business.exceptions.users;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(String message) {
super(message);
}
}
|
92428f4cf660c9c413269c9bcf6ca1da1f3997ce
| 14,205 |
java
|
Java
|
jmix-dynattr/dynattr-ui/src/main/java/io/jmix/dynattrui/panel/DynamicAttributesPanel.java
|
jmix-framework/jmix
|
44d99aae5159ca322c20a13bbcda76d8f6274f94
|
[
"Apache-2.0"
] | 30 |
2019-02-26T07:42:11.000Z
|
2022-03-31T16:46:03.000Z
|
jmix-dynattr/dynattr-ui/src/main/java/io/jmix/dynattrui/panel/DynamicAttributesPanel.java
|
jmix-framework/jmix
|
44d99aae5159ca322c20a13bbcda76d8f6274f94
|
[
"Apache-2.0"
] | 909 |
2019-02-26T08:29:19.000Z
|
2022-03-31T16:56:18.000Z
|
jmix-dynattr/dynattr-ui/src/main/java/io/jmix/dynattrui/panel/DynamicAttributesPanel.java
|
jmix-framework/jmix
|
44d99aae5159ca322c20a13bbcda76d8f6274f94
|
[
"Apache-2.0"
] | 15 |
2019-05-08T19:17:03.000Z
|
2022-03-31T06:24:22.000Z
| 39.024725 | 129 | 0.659908 | 1,002,322 |
/*
* Copyright 2021 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jmix.dynattrui.panel;
import com.google.common.base.Strings;
import io.jmix.core.DevelopmentException;
import io.jmix.core.Messages;
import io.jmix.core.metamodel.model.MetaProperty;
import io.jmix.dynattr.AttributeDefinition;
import io.jmix.dynattr.CategoryDefinition;
import io.jmix.dynattr.DynAttrMetadata;
import io.jmix.dynattr.DynAttrQueryHints;
import io.jmix.dynattr.model.Categorized;
import io.jmix.dynattr.model.Category;
import io.jmix.ui.GuiDevelopmentException;
import io.jmix.ui.UiComponents;
import io.jmix.ui.component.*;
import io.jmix.ui.component.data.ValueSource;
import io.jmix.ui.component.data.value.ContainerValueSource;
import io.jmix.ui.component.data.value.ContainerValueSourceProvider;
import io.jmix.ui.meta.CanvasIconSize;
import io.jmix.ui.meta.PropertyType;
import io.jmix.ui.meta.StudioComponent;
import io.jmix.ui.meta.StudioProperty;
import io.jmix.ui.model.DataLoader;
import io.jmix.ui.model.HasLoader;
import io.jmix.ui.model.InstanceContainer;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Nullable;
import javax.validation.constraints.Positive;
import java.util.*;
import java.util.stream.Collectors;
@StudioComponent(category = "Components",
unsupportedProperties = {"enable", "responsive"},
xmlns = "http://jmix.io/schema/dynattr/ui",
xmlnsAlias = "dynattr",
icon = "io/jmix/dynattrui/icon/component/dynamicAttributesPanel.svg",
canvasIcon = "io/jmix/dynattrui/icon/component/dynamicAttributesPanel_canvas.svg",
canvasIconSize = CanvasIconSize.LARGE)
@CompositeDescriptor("dynamic-attributes-panel.xml")
public class DynamicAttributesPanel extends CompositeComponent<VBoxLayout> implements Validatable {
public static final String NAME = "dynamicAttributesPanel";
public static final String DEFAULT_FIELD_WIDTH = null;
@Autowired
protected UiComponentsGenerator uiComponentsGenerator;
@Autowired
protected UiComponents uiComponents;
@Autowired
protected Messages messages;
@Autowired
protected DynAttrMetadata dynAttrMetadata;
protected InstanceContainer<?> instanceContainer;
protected Integer cols;
protected Integer rows;
protected String fieldWidth = DEFAULT_FIELD_WIDTH;
protected String fieldCaptionWidth;
protected Form propertiesForm;
protected HBoxLayout categoryFieldBox;
protected ComboBox<Category> categoryField;
public DynamicAttributesPanel() {
addCreateListener(this::onCreate);
}
protected void onCreate(CreateEvent createEvent) {
categoryField = getInnerComponent("categoryField");
categoryField.addValueChangeListener(e -> initPropertiesForm());
propertiesForm = getInnerComponent("propertiesForm");
propertiesForm.setHeightAuto();
categoryFieldBox = getInnerComponent("categoryFieldBox");
categoryField.setWidth(fieldWidth);
}
protected void initPropertiesForm() {
propertiesForm.removeAll();
Map<AttributeDefinition, Component> fields = new HashMap<>();
for (AttributeDefinition attribute : getAttributesByCategory()) {
Component resultComponent = generateFieldComponent(attribute);
fields.put(attribute, resultComponent);
}
addFieldsToForm(propertiesForm, fields);
initFieldCaptionWidth(propertiesForm);
}
protected void addFieldsToForm(Form newPropertiesForm, Map<AttributeDefinition, Component> fields) {
if (fields.keySet().stream().anyMatch(attr -> attr.getConfiguration().getColumnNumber() != null
&& attr.getConfiguration().getRowNumber() != null)) {
List<AttributeDefinition> attributesToAdd = fields.keySet().stream()
.filter(attr -> attr.getConfiguration().getColumnNumber() != null
&& attr.getConfiguration().getRowNumber() != null)
.collect(Collectors.toList());
int maxColumnIndex = attributesToAdd.stream()
.mapToInt(attr -> attr.getConfiguration().getColumnNumber())
.max()
.orElse(0);
newPropertiesForm.setColumns(maxColumnIndex + 1);
for (int i = 0; i <= maxColumnIndex; i++) {
int columnIndex = i;
List<AttributeDefinition> columnAttributes = attributesToAdd.stream()
.filter(attr -> columnIndex == attr.getConfiguration().getColumnNumber())
.sorted(Comparator.comparing(attr -> attr.getConfiguration().getRowNumber()))
.collect(Collectors.toList());
int currentRowNumber = 0;
for (AttributeDefinition attr : columnAttributes) {
while (attr.getConfiguration().getRowNumber() > currentRowNumber) {
//add empty row
newPropertiesForm.add(createEmptyComponent(), columnIndex, currentRowNumber);
currentRowNumber++;
}
newPropertiesForm.add(fields.get(attr), columnIndex, currentRowNumber);
currentRowNumber++;
}
}
} else {
int propertiesCount = getAttributesByCategory().size();
int rowsPerColumn = getRowsPerColumn(propertiesCount);
int columnNo = 0;
int fieldsCount = 0;
for (Component field : fields.values()) {
fieldsCount++;
newPropertiesForm.add(field, columnNo);
if (fieldsCount % rowsPerColumn == 0) {
columnNo++;
newPropertiesForm.setColumns(columnNo + 1);
}
}
}
}
private Component createEmptyComponent() {
Label<String> component = uiComponents.create(Label.TYPE_STRING);
component.setValue("\u2060");
return component;
}
protected int getRowsPerColumn(int propertiesCount) {
if (cols != null) {
if (propertiesCount % cols == 0) {
return propertiesCount / cols;
}
return propertiesCount / cols + 1;
}
if (rows != null) {
return rows;
}
return propertiesCount;
}
protected Collection<AttributeDefinition> getAttributesByCategory() {
Category category = categoryField.getValue();
if (category != null) {
for (CategoryDefinition categoryDefinition : dynAttrMetadata.getCategories(instanceContainer.getEntityMetaClass())) {
if (category.equals(categoryDefinition.getSource())) {
return categoryDefinition.getAttributeDefinitions();
}
}
}
return Collections.emptyList();
}
protected Component generateFieldComponent(AttributeDefinition attribute) {
MetaProperty metaProperty = attribute.getMetaProperty();
ValueSource valueSource = new ContainerValueSource<>(instanceContainer, metaProperty.getName());
ComponentGenerationContext componentContext =
new ComponentGenerationContext(instanceContainer.getEntityMetaClass(), metaProperty.getName());
componentContext.setValueSource(valueSource);
Component resultComponent = uiComponentsGenerator.generate(componentContext);
setWidth(resultComponent, attribute);
return resultComponent;
}
protected void setWidth(Component component, AttributeDefinition attribute) {
String formWidth = attribute.getConfiguration().getFormWidth();
if (!Strings.isNullOrEmpty(formWidth)) {
component.setWidth(formWidth);
} else {
component.setWidth(fieldWidth);
}
}
protected void initCategoryField(InstanceContainer<?> instanceContainer) {
if (instanceContainer.getEntityMetaClass().getPropertyPath("category") == null) {
throw new DevelopmentException("Entity have to implement 'io.jmix.dynattr.model.Categorized' and contain " +
"'category' attribute in order to use DynamicAttributesPanel.");
}
categoryField.setOptionsList(getCategoriesOptionsList());
categoryField.setValueSource(new ContainerValueSource<>(instanceContainer, "category"));
}
@Nullable
protected Category getDefaultCategory() {
for (CategoryDefinition category : getCategoryDefinitions()) {
if (category != null && category.isDefault()) {
return (Category) category.getSource();
}
}
return null;
}
protected Collection<CategoryDefinition> getCategoryDefinitions() {
return dynAttrMetadata.getCategories(instanceContainer.getEntityMetaClass());
}
protected List<Category> getCategoriesOptionsList() {
Collection<CategoryDefinition> options = getCategoryDefinitions();
return options.stream().
map(definition -> (Category) definition.getSource())
.collect(Collectors.toList());
}
protected void initFieldCaptionWidth(Form newRuntimeForm) {
if (fieldCaptionWidth != null) {
SizeWithUnit sizeWithUnit = SizeWithUnit.parseStringSize(fieldCaptionWidth);
if (SizeUnit.PERCENTAGE.equals(sizeWithUnit.getUnit())) {
throw new IllegalStateException("DynamicAttributesPanel fieldCaptionWidth with '%' unit is unsupported");
}
newRuntimeForm.setChildrenCaptionWidth(Math.round(sizeWithUnit.getSize()));
}
}
protected void onInstanceContainerItemChangeEvent(InstanceContainer.ItemChangeEvent<?> event) {
if (event.getItem() instanceof Categorized
&& ((Categorized) event.getItem()).getCategory() == null) {
((Categorized) event.getItem()).setCategory(getDefaultCategory());
}
if (event.getItem() == null) {
propertiesForm.removeAll();
}
}
/**
* Defines InstanceContainer for DynamicAttributesPanel.
*
* @param container {@link InstanceContainer} object with editing entity
*/
@StudioProperty(name = "dataContainer", type = PropertyType.DATACONTAINER_REF, required = true)
public void setInstanceContainer(InstanceContainer<Object> container) {
this.instanceContainer = container;
propertiesForm.setValueSourceProvider(new ContainerValueSourceProvider<>(instanceContainer));
initCategoryField(instanceContainer);
initPropertiesForm();
instanceContainer.addItemChangeListener(this::onInstanceContainerItemChangeEvent);
if (instanceContainer instanceof HasLoader) {
DataLoader loader = ((HasLoader) instanceContainer).getLoader();
if (loader != null) {
loader.setHint(DynAttrQueryHints.LOAD_DYN_ATTR, true);
}
}
}
/**
* Sets the number of columns. If {@code null} value is passed, columns count will be determined
* based on the {@code rows} parameter.
*
* @param cols positive integer or {@code null}
*/
@StudioProperty(name = "cols")
@Positive
public void setColumnsCount(Integer cols) {
if (cols != null && cols <= 0) {
throw new GuiDevelopmentException(
"DynamicAttributesPanel element has incorrect value of the 'cols' attribute", this.id);
}
this.cols = cols;
}
/**
* Sets the number of rows. This parameter will only be taken into account if {@code cols == null}.
*
* @param rows positive integer or {@code null}
*/
@StudioProperty(name = "rows")
@Positive
public void setRowsCount(Integer rows) {
if (rows != null && rows <= 0) {
throw new GuiDevelopmentException(
"DynamicAttributesPanel element has incorrect value of the 'rows' attribute", this.id);
}
this.rows = rows;
}
/**
* Sets the width of the fields. This parameter is used if some dynamic attribute does not have own width value.
*
* @param fieldWidth width of the fields
*/
@StudioProperty(type = PropertyType.SIZE)
public void setFieldWidth(String fieldWidth) {
this.fieldWidth = fieldWidth;
}
/**
* Sets the width of the fields caption. {@code fieldCaptionWidth} with '%' unit is unsupported.
*
* @param fieldCaptionWidth width of the fields caption
*/
@StudioProperty(type = PropertyType.SIZE)
public void setFieldCaptionWidth(String fieldCaptionWidth) {
this.fieldCaptionWidth = fieldCaptionWidth;
}
/**
* Sets visibility of the {@code CategoryField} component.
*
* @param visible visibility flag
*/
public void setCategoryFieldVisible(boolean visible) {
categoryFieldBox.setVisible(visible);
}
@Override
public boolean isValid() {
Collection<Component> components = ComponentsHelper.getComponents(propertiesForm);
for (Component component : components) {
if (component instanceof Validatable) {
Validatable validatable = (Validatable) component;
if (validatable.isValidateOnCommit() && !validatable.isValid())
return false;
}
}
return true;
}
@Override
public void validate() throws ValidationException {
ComponentsHelper.traverseValidatable(propertiesForm, Validatable::validate);
}
}
|
92428f747d3aa136d3cac7df438ef55955e943e4
| 1,451 |
java
|
Java
|
duel-fake-server/src/main/java/org/leadpony/duel/fake/server/servlets/EchoServlet.java
|
leadpony/duel
|
c6c2b509e2e10dd8535680f7b8b59ab5b388a51c
|
[
"Apache-2.0"
] | null | null | null |
duel-fake-server/src/main/java/org/leadpony/duel/fake/server/servlets/EchoServlet.java
|
leadpony/duel
|
c6c2b509e2e10dd8535680f7b8b59ab5b388a51c
|
[
"Apache-2.0"
] | null | null | null |
duel-fake-server/src/main/java/org/leadpony/duel/fake/server/servlets/EchoServlet.java
|
leadpony/duel
|
c6c2b509e2e10dd8535680f7b8b59ab5b388a51c
|
[
"Apache-2.0"
] | null | null | null | 33.744186 | 84 | 0.758098 | 1,002,323 |
/*
* Copyright 2019 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
*
* 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.leadpony.duel.fake.server.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author leadpony
*/
@WebServlet("/echo")
@SuppressWarnings("serial")
public class EchoServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(request.getContentType());
response.setCharacterEncoding(request.getCharacterEncoding());
request.getInputStream().transferTo(response.getOutputStream());
}
}
|
92428fdf93d22ed10fb1e714e6714b0b9473ae90
| 1,010 |
java
|
Java
|
appusagemonitor/src/main/java/bot/box/appusage/utils/UsageManager.java
|
lenastankovic/AppsUsageMonitorAPI-master
|
511f87b0640dc9fc1a265f591d557cb315155d40
|
[
"Unlicense"
] | 49 |
2019-04-13T15:48:13.000Z
|
2022-02-15T07:16:03.000Z
|
appusagemonitor/src/main/java/bot/box/appusage/utils/UsageManager.java
|
lenastankovic/AppsUsageMonitorAPI-master
|
511f87b0640dc9fc1a265f591d557cb315155d40
|
[
"Unlicense"
] | 7 |
2019-04-19T11:37:35.000Z
|
2022-01-11T09:11:01.000Z
|
appusagemonitor/src/main/java/bot/box/appusage/utils/UsageManager.java
|
lenastankovic/AppsUsageMonitorAPI-master
|
511f87b0640dc9fc1a265f591d557cb315155d40
|
[
"Unlicense"
] | 13 |
2019-05-07T17:51:00.000Z
|
2022-01-13T10:31:43.000Z
| 19.843137 | 71 | 0.602767 | 1,002,324 |
package bot.box.appusage.utils;
import java.util.ArrayList;
import java.util.List;
import bot.box.appusage.model.AppData;
/**
* Created by BarryAllen
*
* @TheBotBox [email protected]
*/
public class UsageManager {
private static UsageManager ourInstance;
private List<AppData> mList;
private long mTotalUsage;
private UsageManager() {
mList = new ArrayList<>();
}
public static UsageManager getInstance() {
if (ourInstance == null) {
synchronized (UsageManager.class) {
if (ourInstance == null) {
ourInstance = new UsageManager();
}
}
}
return ourInstance;
}
public void setAppUsageList(List<AppData> mList, long totalUsage) {
this.mList = mList;
this.mTotalUsage = totalUsage;
}
public List<AppData> getAppUsageList() {
return this.mList;
}
public long getTotalUsage() {
return this.mTotalUsage;
}
}
|
9242904a67ae943c8436cede500e69a7e5aba5cd
| 1,934 |
java
|
Java
|
library/src/main/java/com/tatuas/android/polley/UploadManager.java
|
tatuas/polley
|
1adec3a0853fae542f93e717062dd626d0c4da0b
|
[
"MIT"
] | null | null | null |
library/src/main/java/com/tatuas/android/polley/UploadManager.java
|
tatuas/polley
|
1adec3a0853fae542f93e717062dd626d0c4da0b
|
[
"MIT"
] | null | null | null |
library/src/main/java/com/tatuas/android/polley/UploadManager.java
|
tatuas/polley
|
1adec3a0853fae542f93e717062dd626d0c4da0b
|
[
"MIT"
] | null | null | null | 28.028986 | 93 | 0.640641 | 1,002,325 |
package com.tatuas.android.polley;
import android.support.annotation.NonNull;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class UploadManager {
private static UploadManager sUploadManager;
private static boolean mIsShutDownedFlag;
private ThreadPoolExecutor mPoolExecutor;
@NonNull
public static UploadManager getInstance() {
if (sUploadManager == null || mIsShutDownedFlag) {
sUploadManager = new UploadManager();
}
return sUploadManager;
}
public int numberOfThreads() {
return Runtime.getRuntime().availableProcessors();
}
public UploadManager() {
mPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads());
mIsShutDownedFlag = false;
}
public void terminate() {
/*
* ShutdownNow is a method that dequeue all and stop threads gently.
*/
mPoolExecutor.shutdownNow();
mIsShutDownedFlag = true;
/*
* TODO: awaitTerminationが問題ないか検討
int shutDownTimeOut = 100000;
try {
mPoolExecutor.awaitTermination(shutDownTimeOut, TimeUnit.SECONDS);
} catch (Exception e) {
return;
}
*/
}
public boolean enQueue(UploadTask task) {
try {
mPoolExecutor.execute(task.newUploadThread());
return true;
} catch (Exception e) {
// Rejected or Null Exception
return false;
}
}
public boolean deQueue(UploadTask task) {
return mPoolExecutor.getQueue().contains(task.newUploadThread())
&& mPoolExecutor.remove(task.newUploadThread());
}
public void deQueueAll() {
final BlockingQueue<Runnable> blockingQueue = mPoolExecutor.getQueue();
blockingQueue.clear();
}
}
|
9242905ff78ac014ad9218cf95e3a0ddfa0f3b8d
| 1,217 |
java
|
Java
|
java/ch/epfl/cs107/play/window/Mouse.java
|
eloigrndl/mini-projet2
|
d7571c0118672207d733e16d1cff71f408f01a3f
|
[
"CC-BY-4.0"
] | null | null | null |
java/ch/epfl/cs107/play/window/Mouse.java
|
eloigrndl/mini-projet2
|
d7571c0118672207d733e16d1cff71f408f01a3f
|
[
"CC-BY-4.0"
] | null | null | null |
java/ch/epfl/cs107/play/window/Mouse.java
|
eloigrndl/mini-projet2
|
d7571c0118672207d733e16d1cff71f408f01a3f
|
[
"CC-BY-4.0"
] | null | null | null | 26.456522 | 84 | 0.650781 | 1,002,326 |
package ch.epfl.cs107.play.window;
import ch.epfl.cs107.play.math.Positionable;
import ch.epfl.cs107.play.math.Transform;
import ch.epfl.cs107.play.math.Vector;
/**
* Represents the mouse pointer.
*/
public interface Mouse extends Positionable {
/**
* Getter for the button corresponding to the given index
* @param index (int): given index
* @return (Button): button corresponding of the state of the given index button
*/
Button getButton(int index);
/**@return (Button): the left button (by default index = 0)*/
default Button getLeftButton() {
return getButton(0);
}
/**@return (Button): the Middle button (by default index = 1)*/
default Button getMiddleButton() {
return getButton(1);
}
/**@return (Button): the right button (by default index = 2)*/
default Button getRightButton() {
return getButton(2);
}
// TODO wheel/scroll
// TODO other position getters and screen space things?
/// Mouse extends Positionable
@Override
default Transform getTransform() {
Vector position = getPosition();
return new Transform(1.0f, 0.0f, position.x, 0.0f, 1.0f, position.y);
}
}
|
9242907ee31906d6787a05e1a9fa7b2e36d1e3ac
| 942 |
java
|
Java
|
Basic Java/Lista 4/src/computing/Number.java
|
JacekLeja/Java-projects
|
2c7c35d15a2ac91a0977cb6d6107a0151d93e50d
|
[
"MIT"
] | null | null | null |
Basic Java/Lista 4/src/computing/Number.java
|
JacekLeja/Java-projects
|
2c7c35d15a2ac91a0977cb6d6107a0151d93e50d
|
[
"MIT"
] | null | null | null |
Basic Java/Lista 4/src/computing/Number.java
|
JacekLeja/Java-projects
|
2c7c35d15a2ac91a0977cb6d6107a0151d93e50d
|
[
"MIT"
] | null | null | null | 23.55 | 80 | 0.546709 | 1,002,327 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package computing;
/**
*
* @author jacek
*/
public class Number extends Expression {
public final double value;
public Number (double value) {
this.value = value;
}
public double Compute(){
return this.value;
}
public String toString () {
return "Number(" + this.value + ")";
}
public boolean equals (Object o) {
if (o instanceof Constant) {
return ((Constant) o).value == this.value;
}
if (o instanceof Number) {
return((Number) o).value == this.value;
}
if (o instanceof Variable){
return((Variable) o).value == this.value;
}
return false;
}
}
|
9242909d7a7270cb13627dc12815a49b1b51c261
| 981 |
java
|
Java
|
commons-jsymbol/src/main/java/io/onedev/commons/jsymbol/less/symbols/LessSymbol.java
|
mhoffrog/onedev-commons
|
fb30454f9a4a4e9670428397553c536aa8dc5bbc
|
[
"MIT"
] | 1 |
2021-05-30T03:52:26.000Z
|
2021-05-30T03:52:26.000Z
|
commons-jsymbol/src/main/java/io/onedev/commons/jsymbol/less/symbols/LessSymbol.java
|
mhoffrog/onedev-commons
|
fb30454f9a4a4e9670428397553c536aa8dc5bbc
|
[
"MIT"
] | 18 |
2019-12-13T05:00:34.000Z
|
2021-12-09T08:08:58.000Z
|
commons-jsymbol/src/main/java/io/onedev/commons/jsymbol/less/symbols/LessSymbol.java
|
isabella232/commons-3
|
41b4eb2490e3b5b17c8e9df2142930f2ec2d3e28
|
[
"MIT"
] | 5 |
2019-10-17T15:53:26.000Z
|
2022-03-15T20:24:37.000Z
| 16.913793 | 83 | 0.727829 | 1,002,328 |
package io.onedev.commons.jsymbol.less.symbols;
import javax.annotation.Nullable;
import io.onedev.commons.jsymbol.Symbol;
import io.onedev.commons.utils.PlanarRange;
/**
* @author robin
*
*/
public abstract class LessSymbol extends Symbol {
private static final long serialVersionUID = 1L;
private final LessSymbol parent;
private final String name;
private final PlanarRange position;
private final PlanarRange scope;
public LessSymbol(LessSymbol parent, String name, @Nullable PlanarRange position,
@Nullable PlanarRange scope) {
this.parent = parent;
this.name = name;
this.position = position;
this.scope = scope;
}
@Override
public String getName() {
return name;
}
@Override
public LessSymbol getParent() {
return parent;
}
@Override
public PlanarRange getPosition() {
return position;
}
@Override
public PlanarRange getScope() {
return scope;
}
@Override
public String getFQNSeparator() {
return " ";
}
}
|
924290fe9b4e6e34faa76b46baed00212fbd04e7
| 754 |
java
|
Java
|
flipped-common/flipped-common-core/src/main/java/com/flipped/common/core/contants/CacheConstants.java
|
chiwenda/wenda
|
0e2993fa4e6e9fa7031e362da0c811e2c5c6afe4
|
[
"MIT"
] | null | null | null |
flipped-common/flipped-common-core/src/main/java/com/flipped/common/core/contants/CacheConstants.java
|
chiwenda/wenda
|
0e2993fa4e6e9fa7031e362da0c811e2c5c6afe4
|
[
"MIT"
] | null | null | null |
flipped-common/flipped-common-core/src/main/java/com/flipped/common/core/contants/CacheConstants.java
|
chiwenda/wenda
|
0e2993fa4e6e9fa7031e362da0c811e2c5c6afe4
|
[
"MIT"
] | null | null | null | 18.85 | 83 | 0.612732 | 1,002,329 |
package com.flipped.common.core.contants;
/**
* 缓存Key常量接口
*
* @author cwd
* @date 2022/1/14 上午11:48
*/
public class CacheConstants {
/**
* 验证码前缀
*/
public final static String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY:";
/**
* 用户信息缓存
*/
public final static String USER_DETAILS = "user_details";
/**
* oauth 客户端信息
*/
public final static String CLIENT_DETAILS_KEY = "flipped_oauth:client:details";
/**
* oauth 缓存前缀
*/
public final static String PROJECT_OAUTH_ACCESS = "flipped_oauth:access:";
/**
* 菜单信息缓存
*/
public final static String MENU_DETAILS = "menu_details";
/**
* 字典信息缓存
*/
public final static String DICT_DETAILS = "dict_details";
}
|
924291ab0a96d8310172f2af83840fa173b8849a
| 2,251 |
java
|
Java
|
app/src/main/java/com/smlnskgmail/jaman/hashcheckerlite/utils/WebUtils.java
|
hash-checker/hash-checker-lite
|
c44e6f6260358f25886439787fafc761c8699cc1
|
[
"MIT"
] | 6 |
2021-04-11T19:13:21.000Z
|
2022-03-03T15:41:28.000Z
|
app/src/main/java/com/smlnskgmail/jaman/hashcheckerlite/utils/WebUtils.java
|
vipozdn/hash-checker-lite
|
600ee67bc34be8d89fac1cbbff6f707d203ee25f
|
[
"MIT"
] | 47 |
2021-01-05T10:23:00.000Z
|
2021-09-26T12:08:42.000Z
|
app/src/main/java/com/smlnskgmail/jaman/hashcheckerlite/utils/WebUtils.java
|
vipozdn/hash-checker-lite
|
600ee67bc34be8d89fac1cbbff6f707d203ee25f
|
[
"MIT"
] | 9 |
2021-01-05T08:20:48.000Z
|
2022-02-12T14:35:58.000Z
| 28.1375 | 89 | 0.490004 | 1,002,330 |
package com.smlnskgmail.jaman.hashcheckerlite.utils;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import androidx.annotation.NonNull;
import com.smlnskgmail.jaman.hashcheckerlite.R;
import com.smlnskgmail.jaman.hashcheckerlite.components.dialogs.system.AppSnackbar;
import com.smlnskgmail.jaman.hashcheckerlite.logic.themes.api.ThemeHelper;
public class WebUtils {
private WebUtils() {
}
public static void openGooglePlay(
@NonNull Context context,
@NonNull View view,
ThemeHelper themeHelper
) {
final String appPackageName = context.getPackageName();
Uri link;
try {
link = Uri.parse("market://details?id=" + appPackageName);
context.startActivity(
new Intent(
Intent.ACTION_VIEW,
link
)
);
} catch (ActivityNotFoundException e) {
try {
link = Uri.parse(
"https://play.google.com/store/apps/details?id=" + appPackageName
);
context.startActivity(
new Intent(
Intent.ACTION_VIEW,
link
)
);
} catch (ActivityNotFoundException e2) {
new AppSnackbar(
context,
view,
context.getString(
R.string.message_error_start_google_play
),
themeHelper
).show();
}
}
}
public static void openWebLink(
@NonNull Context context,
@NonNull String link
) {
try {
context.startActivity(
new Intent(
Intent.ACTION_VIEW,
Uri.parse(link)
)
);
} catch (ActivityNotFoundException e) {
LogUtils.e(e);
}
}
}
|
92429253df902b694fab6a67cda23cbd68fc4aad
| 1,060 |
java
|
Java
|
java/src/test/java/com/yourtion/leetcode/daily/m10/d28/SolutionTest.java
|
yourtion/LeetCode
|
61ee9fb1f97274e1621f8415dcdd8c7e424d20b3
|
[
"MIT"
] | null | null | null |
java/src/test/java/com/yourtion/leetcode/daily/m10/d28/SolutionTest.java
|
yourtion/LeetCode
|
61ee9fb1f97274e1621f8415dcdd8c7e424d20b3
|
[
"MIT"
] | null | null | null |
java/src/test/java/com/yourtion/leetcode/daily/m10/d28/SolutionTest.java
|
yourtion/LeetCode
|
61ee9fb1f97274e1621f8415dcdd8c7e424d20b3
|
[
"MIT"
] | null | null | null | 33.125 | 75 | 0.687736 | 1,002,331 |
package com.yourtion.leetcode.daily.m10.d28;
import com.yourtion.leetcode.TestUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.params.provider.Arguments.arguments;
@DisplayName("每日一题 - 20201028")
class SolutionTest {
static Stream<Arguments> testDataProvider() {
return Stream.of(
arguments("[1,2,2,1,1,3]", true),
arguments("[1,2]", false),
arguments("[-3,0,1,-3,1,1,1,-3,10,0]", true)
);
}
@ParameterizedTest()
@MethodSource("testDataProvider")
void uniqueOccurrences(String source, boolean res) {
System.out.printf("runTest: %s , res: %b", source, res);
int[] ss = TestUtils.stringToIntegerArray(source);
Assertions.assertEquals(res, new Solution().uniqueOccurrences(ss));
}
}
|
9242925fb741038b680fbab3a6b364575f6bf107
| 652 |
java
|
Java
|
src/main/java/niu/study/test/niu2.java
|
chillman21/NIUstudy
|
8d0803534e4716441b4f980716aadde6452c78d9
|
[
"MIT"
] | null | null | null |
src/main/java/niu/study/test/niu2.java
|
chillman21/NIUstudy
|
8d0803534e4716441b4f980716aadde6452c78d9
|
[
"MIT"
] | null | null | null |
src/main/java/niu/study/test/niu2.java
|
chillman21/NIUstudy
|
8d0803534e4716441b4f980716aadde6452c78d9
|
[
"MIT"
] | null | null | null | 25.076923 | 52 | 0.529141 | 1,002,332 |
package niu.study.test;
import java.util.ArrayList;
import java.util.Iterator;
public interface niu2 {
public static void main(String[] args) {
System.out.println("Aa");
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
iterator.remove();
}
for (String s : list) {
list.remove(1);
}
System.out.println(list.toString());
}
}
|
92429294d978c24e10f5bfb414cee630e4593626
| 2,488 |
java
|
Java
|
library/src/main/java/es/rafaco/inappdevtools/library/view/components/items/EditTextViewHolder.java
|
rafaco/InAppDevTools
|
774e777fbd524410fa80b35953b0ce2e26c0f438
|
[
"Apache-2.0"
] | 26 |
2019-01-16T00:20:44.000Z
|
2022-02-06T01:27:26.000Z
|
library/src/main/java/es/rafaco/inappdevtools/library/view/components/items/EditTextViewHolder.java
|
rafaco/InAppDevTools
|
774e777fbd524410fa80b35953b0ce2e26c0f438
|
[
"Apache-2.0"
] | 12 |
2019-09-10T17:11:15.000Z
|
2022-02-05T18:52:08.000Z
|
library/src/main/java/es/rafaco/inappdevtools/library/view/components/items/EditTextViewHolder.java
|
rafaco/InAppDevTools
|
774e777fbd524410fa80b35953b0ce2e26c0f438
|
[
"Apache-2.0"
] | 4 |
2020-08-11T21:22:50.000Z
|
2021-11-21T16:21:34.000Z
| 36.588235 | 77 | 0.690916 | 1,002,333 |
/*
* This source file is part of InAppDevTools, which is available under
* Apache License, Version 2.0 at https://github.com/rafaco/InAppDevTools
*
* Copyright 2018-2019 Rafael Acosta Alvarez
*
* 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 es.rafaco.inappdevtools.library.view.components.items;
import es.rafaco.compat.TextInputEditText;
import es.rafaco.compat.TextInputLayout;
import android.view.View;
import es.rafaco.inappdevtools.library.R;
import es.rafaco.inappdevtools.library.view.components.FlexAdapter;
import es.rafaco.inappdevtools.library.view.components.FlexViewHolder;
public class EditTextViewHolder extends FlexViewHolder {
private final TextInputEditText editText;
private final TextInputLayout layout;
public EditTextViewHolder(View view, FlexAdapter adapter) {
super(view, adapter);
//this.titleView = view.findViewById(R.id.title);
this.editText = view.findViewById(R.id.text_input_edit_txt);
this.layout = view.findViewById(R.id.text_input_layout);
}
@Override
public void bindTo(Object abstractData, int position) {
final EditTextData data = (EditTextData) abstractData;
if (data!=null){
//titleView.setText(data.getTitle());
editText.setHint(data.getTitle());
editText.setText(data.getText());
editText.addTextChangedListener(data.getTextWatcher());
if (data.getLineNumber()>0){
//editText.setSingleLine(false);
//editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
//editText.setLines(data.getLineNumber());
//editText.setMaxLines(data.getLineNumber() + 10);
//editText.setHorizontallyScrolling(false);
}
if (data.getMaxLength() > 0){
layout.setCounterEnabled(true);
layout.setCounterMaxLength(data.getMaxLength());
}
}
}
}
|
924292dc4baa793a61cd7c0ea98e159fe6e3e9d4
| 5,837 |
java
|
Java
|
java/mvvm-essence/src/main/java/com/example/viewmodel/StudentViewModel.java
|
lvan100/mvvm-essence
|
e5dbc537bc32df18a5e1e93c1558292bedee6a17
|
[
"Apache-2.0"
] | 1 |
2016-10-15T12:28:44.000Z
|
2016-10-15T12:28:44.000Z
|
java/mvvm-essence/src/main/java/com/example/viewmodel/StudentViewModel.java
|
lvan100/mvvm-essence
|
e5dbc537bc32df18a5e1e93c1558292bedee6a17
|
[
"Apache-2.0"
] | null | null | null |
java/mvvm-essence/src/main/java/com/example/viewmodel/StudentViewModel.java
|
lvan100/mvvm-essence
|
e5dbc537bc32df18a5e1e93c1558292bedee6a17
|
[
"Apache-2.0"
] | null | null | null | 30.401042 | 108 | 0.634573 | 1,002,334 |
package com.example.viewmodel;
import com.example.model.Student;
import com.example.view.StudentView;
import com.mvvm.binding.BindingType;
import com.mvvm.binding.DataBinding;
import com.mvvm.binding.ValueConverter;
import static com.print.PrintHelper.PRINT_HELPER;
/**
* 视图和领域模型。
*/
public class StudentViewModel {
// 学生信息
public final Student student = new Student();
// 学生信息视图
public final StudentView studentView = new StudentView("studentView");
public StudentViewModel() {
// 更新未绑定的学生信息视图标题
// studentView.titleValue --> ...show
studentView.setTitle("Student");
System.out.println();
// 赋相同的值不会引发任何变化
studentView.setTitle("Student");
System.out.println();
// 未绑定前修改学生姓名
// student.name --> ...
student.setName("Lily");
System.out.println();
// 单向绑定学生姓名
// student.name --> studentView.textBoxStudentName --> ...show
PRINT_HELPER.enterPrint("studentView.textBoxStudentName.setDataBinding.begin");
studentView.textBoxStudentName.textValue.setDataBinding(
new DataBinding<>(BindingType.OneWay, student.nameValue));
PRINT_HELPER.exitPrint("studentView.textBoxStudentName.setDataBinding.end");
System.out.println();
// 单向绑定学生名称后修改学生姓名
// student.name --> studentView.textBoxStudentName --> ...show
student.setName("Jim");
System.out.println();
// 单向绑定学生名称后修改学生姓名
// studentView.textBoxStudentName --> ...
studentView.textBoxStudentName.setText("Green");
System.out.println();
// 双向绑定学生分数
// student.score --> studentView.textBoxStudentScore --> ...show
PRINT_HELPER.enterPrint("studentView.textBoxStudentScore.setDataBinding.begin");
DataBinding<String> binding = new DataBinding<>(
BindingType.TwoWay, student.scoreValue);
binding.setValueConverter(new ValueConverter<String>() {
@Override
public String convert(Object value) {
return value.toString();
}
@Override
public Object reverseConvert(String value) {
return Integer.valueOf(value);
}
});
studentView.textBoxStudentScore.textValue.setDataBinding(binding);
PRINT_HELPER.exitPrint("studentView.textBoxStudentScore.setDataBinding.end");
System.out.println();
// 双向绑定修改学生分数
// student.score --> studentView.textBoxStudentScore --> ...show
student.setScore(45);
System.out.println();
// 双向绑定修改学生分数
// studentView.textBoxStudentScore --> student.score --> studentView.textBoxStudentScore --> ...show
studentView.textBoxStudentScore.setText("75");
System.out.println();
// 单向绑定学生成绩水平
// studentView.textBoxStudentScore --> studentView.textBoxStudentLevel --> ...show
PRINT_HELPER.enterPrint("studentView.textBoxStudentLevel.setDataBinding.begin");
binding = new DataBinding<>(BindingType.OneWay,
studentView.textBoxStudentScore.textValue);
binding.setValueConverter(new ValueConverter<String>() {
@Override
public String convert(Object value) {
int score = Integer.valueOf((String) value);
if (score < 60) {
return "不及格";
} else if (score < 80) {
return "一般";
} else
return "优秀";
}
});
studentView.textBoxStudentLevel.textValue.setDataBinding(binding);
PRINT_HELPER.exitPrint("studentView.textBoxStudentLevel.setDataBinding.end");
System.out.println();
// 学生分数和成绩水平单向绑定后修改学生分数
// student.score --> studentView.textBoxStudentScore --> studentView.textBoxStudentLevel -->...show
student.setScore(90);
System.out.println();
// 学生分数和成绩水平单向绑定后修改学生分数
// studentView.textBoxStudentScore --> student.score --> studentView.textBoxStudentScore -->
// studentView.textBoxStudentLevel -->...show
studentView.textBoxStudentScore.setText("10");
System.out.println();
// 双向绑定学生分数控件和其备份控件
// studentView.textBoxStudentScore --> studentView.textBoxStudentLevel -->
// studentView.textBoxStudentScoreCopy --> ...show
PRINT_HELPER.enterPrint("studentView.textBoxStudentScoreCopy.setDataBinding.begin");
studentView.textBoxStudentScoreCopy.textValue.setDataBinding(new DataBinding<>(
BindingType.TwoWay, studentView.textBoxStudentScore.textValue));
PRINT_HELPER.exitPrint("studentView.textBoxStudentScoreCopy.setDataBinding.end");
System.out.println();
// 学生分数控件和其备份控件双向绑定后修改学生分数
// student.score --> studentView.textBoxStudentScore --> studentView.textBoxStudentLevel -->
// studentView.textBoxStudentScoreCopy --> ...show
student.setScore(90);
System.out.println();
// 学生分数控件和其备份控件双向绑定后修改学生分数备份
// studentView.textBoxStudentScoreCopy --> studentView.textBoxStudentScore --> student.score -->
// studentView.textBoxStudentScore --> studentView.textBoxStudentLevel -->
// studentView.textBoxStudentScoreCopy --> ...show
studentView.textBoxStudentScoreCopy.setText("10");
System.out.println();
// 赋相同的值不会引发任何变化
student.setScore(10);
System.out.println();
// 赋相同的值不会引发任何变化
studentView.textBoxStudentScore.setText("10");
System.out.println();
// 赋相同的值不会引发任何变化
studentView.textBoxStudentScoreCopy.setText("10");
System.out.println();
}
public void show() {
studentView.show();
}
}
|
924292fa286b55e77e519d2938ca49e542cabf62
| 989 |
java
|
Java
|
optaplanner-core/src/main/java/org/optaplanner/core/api/score/comparator/NaturalScoreComparator.java
|
kiereleaseuser/optaplanner
|
969be51e574a47f29a10a20b42d8e3b9feb8fec8
|
[
"Apache-2.0"
] | 2 |
2017-03-21T22:57:37.000Z
|
2019-02-13T16:06:06.000Z
|
optaplanner-core/src/main/java/org/optaplanner/core/api/score/comparator/NaturalScoreComparator.java
|
kiereleaseuser/optaplanner
|
969be51e574a47f29a10a20b42d8e3b9feb8fec8
|
[
"Apache-2.0"
] | null | null | null |
optaplanner-core/src/main/java/org/optaplanner/core/api/score/comparator/NaturalScoreComparator.java
|
kiereleaseuser/optaplanner
|
969be51e574a47f29a10a20b42d8e3b9feb8fec8
|
[
"Apache-2.0"
] | 1 |
2018-03-19T23:02:36.000Z
|
2018-03-19T23:02:36.000Z
| 29.088235 | 80 | 0.741153 | 1,002,335 |
/*
* Copyright 2010 JBoss 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 org.optaplanner.core.api.score.comparator;
import java.io.Serializable;
import java.util.Comparator;
import org.optaplanner.core.api.score.Score;
/**
* Compares by the natural order of scores.
*/
public class NaturalScoreComparator implements Comparator<Score>, Serializable {
public int compare(Score score1, Score score2) {
return score1.compareTo(score2);
}
}
|
92429352e2650bc77f7a8e3aa78840bdeb9e8bc4
| 1,649 |
java
|
Java
|
app/src/main/java/com/djunicode/queuingapp/activity/EmailActivity.java
|
DhruvBhagadia/QueueingApp
|
997b471454cc73f21f4a28916e9558cf040503df
|
[
"MIT"
] | 1 |
2019-10-30T15:12:20.000Z
|
2019-10-30T15:12:20.000Z
|
app/src/main/java/com/djunicode/queuingapp/activity/EmailActivity.java
|
Ruturaj123/QueueingApp
|
997b471454cc73f21f4a28916e9558cf040503df
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/djunicode/queuingapp/activity/EmailActivity.java
|
Ruturaj123/QueueingApp
|
997b471454cc73f21f4a28916e9558cf040503df
|
[
"MIT"
] | 1 |
2018-06-05T17:52:03.000Z
|
2018-06-05T17:52:03.000Z
| 33.653061 | 76 | 0.742874 | 1,002,336 |
package com.djunicode.queuingapp.activity;
import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.djunicode.queuingapp.R;
public class EmailActivity extends AppCompatActivity {
private TextInputLayout signUpEmailTIL, verifyTIL;
private EditText signUpEmailEditText, verifyEditText;
private Button sendCodeButton, verifyEmailButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
Intent intent = getIntent();
final String user = intent.getStringExtra("user");
signUpEmailTIL = (TextInputLayout) findViewById(R.id.signUpEmailTIL);
verifyTIL = (TextInputLayout) findViewById(R.id.verifyTIL);
signUpEmailEditText = (EditText) findViewById(R.id.signUpEmailEditText);
verifyEditText = (EditText) findViewById(R.id.verifyEditText);
sendCodeButton = (Button) findViewById(R.id.sendCodeButton);
verifyEmailButton = (Button) findViewById(R.id.verifyEmailButton);
verifyEmailButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EmailActivity.this, LogInActivity.class);
if (user.equals("teacher")) {
intent.putExtra("user", user);
} else {
intent.putExtra("user", "student");
}
startActivity(intent);
}
});
}
}
|
92429472a42292b0ef72350b8eba21d19cda3df6
| 1,041 |
java
|
Java
|
jsourcemap/src/java/org/hibnet/jsourcemap/GeneratedPosition.java
|
nlalevee/jsourcemap
|
361a99c73d51c11afa5579dd83d477c4d0345599
|
[
"Apache-2.0"
] | null | null | null |
jsourcemap/src/java/org/hibnet/jsourcemap/GeneratedPosition.java
|
nlalevee/jsourcemap
|
361a99c73d51c11afa5579dd83d477c4d0345599
|
[
"Apache-2.0"
] | null | null | null |
jsourcemap/src/java/org/hibnet/jsourcemap/GeneratedPosition.java
|
nlalevee/jsourcemap
|
361a99c73d51c11afa5579dd83d477c4d0345599
|
[
"Apache-2.0"
] | null | null | null | 29.742857 | 80 | 0.705091 | 1,002,337 |
/*
* Copyright 2015 JSourceMap contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibnet.jsourcemap;
public class GeneratedPosition extends Position {
Integer lastColumn;
public GeneratedPosition() {
super(null, null);// not found position
}
public GeneratedPosition(Integer line, Integer column, Integer lastColumn) {
super(line, column);
this.lastColumn = lastColumn;
}
public Integer getLastColumn() {
return lastColumn;
}
}
|
9242956a36965869a8c5b6a5593480cab17dd1a9
| 3,920 |
java
|
Java
|
src/test/java/es/upm/miw/betca_tpv_core/infrastructure/api/resources/MessengerResourceIT.java
|
miw-upm/betca-tpv-core
|
93d995ab6df4f69f231251049d830dcbf6630715
|
[
"MIT"
] | 6 |
2021-05-04T01:32:10.000Z
|
2022-03-24T05:46:24.000Z
|
src/test/java/es/upm/miw/betca_tpv_core/infrastructure/api/resources/MessengerResourceIT.java
|
miw-upm/betca-tpv-core
|
93d995ab6df4f69f231251049d830dcbf6630715
|
[
"MIT"
] | null | null | null |
src/test/java/es/upm/miw/betca_tpv_core/infrastructure/api/resources/MessengerResourceIT.java
|
miw-upm/betca-tpv-core
|
93d995ab6df4f69f231251049d830dcbf6630715
|
[
"MIT"
] | 8 |
2021-02-22T10:15:24.000Z
|
2021-11-30T04:00:42.000Z
| 38.058252 | 97 | 0.575765 | 1,002,338 |
package es.upm.miw.betca_tpv_core.infrastructure.api.resources;
import es.upm.miw.betca_tpv_core.domain.model.Message;
import es.upm.miw.betca_tpv_core.domain.model.User;
import es.upm.miw.betca_tpv_core.infrastructure.api.RestClientTestService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
@RestTestConfig
class MessengerResourceIT {
@Autowired
private WebTestClient webTestClient;
@Autowired
private RestClientTestService restClientTestService;
@Test
void testCreate() {
Message message = new Message("Subject", "Text message", "6", "6", false,
LocalDate.of(2021, 9, 15));
Message createdMessage = this.restClientTestService.loginAdmin(webTestClient)
.post()
.uri(MessengerResource.MESSENGER)
.body(Mono.just(message), Message.class)
.exchange()
.expectStatus().isOk()
.expectBody(Message.class)
.value(Assertions::assertNotNull)
.value(returnMessage -> {
assertNotNull(returnMessage.getSubject());
assertEquals("Subject", returnMessage.getSubject());
assertNotNull(returnMessage.getCreationDate());
assertEquals(new User("6").getMobile(), returnMessage.getUserTo());
assertEquals(new User("6").getMobile(), returnMessage.getUserFrom());
}).returnResult().getResponseBody();
assertNotNull(createdMessage);
}
@Test
void testGetSentMessages() {
this.restClientTestService.loginManager(webTestClient)
.get()
.uri(MessengerResource.MESSENGER + MessengerResource.SENT_MESSAGES)
.exchange()
.expectStatus().isOk()
.expectBodyList(Message.class)
.value(messages -> assertTrue(
messages.stream()
.anyMatch(message -> message.getSubject().equals("Message 2"))
)
);
}
@Test
void testGetReceivedMessages() {
this.restClientTestService.loginManager(webTestClient)
.get()
.uri(MessengerResource.MESSENGER + MessengerResource.RECEIVED_MESSAGES)
.exchange()
.expectStatus().isOk()
.expectBodyList(Message.class)
.value(messages -> assertTrue(
messages.stream()
.anyMatch(message -> message.getSubject().equals("Message 4"))
)
);
}
@Test
void testCheckNewMessages() {
Message newMessage = new Message("Test subject", "Text message", "6", "666666001",
false, LocalDate.of(2021, 9, 15));
this.restClientTestService.loginAdmin(webTestClient)
.post()
.uri(MessengerResource.MESSENGER)
.body(Mono.just(newMessage), Message.class)
.exchange()
.expectStatus().isOk();
this.restClientTestService.loginManager(webTestClient)
.get()
.uri(MessengerResource.MESSENGER + MessengerResource.CHECK_NEW_MESSAGES)
.exchange()
.expectStatus().isOk()
.expectBodyList(Message.class)
.value(messages -> assertTrue(
messages.stream()
.anyMatch(message -> message.getSubject().equals("Test subject"))
)
);
}
}
|
924295fc130d45d3609bd898c0b477a63d84c8a7
| 3,550 |
java
|
Java
|
core-vm/java/java/security/IdentityScope.java
|
kifferltd/open-mika
|
079bcf51dce9442deee2cc728ee1d4a303f738ed
|
[
"ICU"
] | 41 |
2015-05-14T12:03:18.000Z
|
2021-11-28T20:18:59.000Z
|
core-vm/java/java/security/IdentityScope.java
|
kifferltd/open-mika
|
079bcf51dce9442deee2cc728ee1d4a303f738ed
|
[
"ICU"
] | 11 |
2015-04-11T10:45:33.000Z
|
2020-12-14T18:08:58.000Z
|
core-vm/java/java/security/IdentityScope.java
|
kifferltd/open-mika
|
079bcf51dce9442deee2cc728ee1d4a303f738ed
|
[
"ICU"
] | 9 |
2016-05-05T15:19:17.000Z
|
2021-07-13T11:35:45.000Z
| 46.103896 | 88 | 0.662254 | 1,002,339 |
/**************************************************************************
* Copyright (c) 2001 by Punch Telematix. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. Neither the name of Punch Telematix nor the names of *
* other contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission.*
* *
* THIS SOFTWARE IS PROVIDED ``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 PUNCH TELEMATIX OR OTHER 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 java.security;
import wonka.vm.DeprecatedMethodError;
import java.util.Enumeration;
/**
*
* @version $Id: IdentityScope.java,v 1.1.1.1 2004/07/12 14:07:46 cvs Exp $
* @deprecated
*/
public abstract class IdentityScope extends Identity {
private static final long serialVersionUID = -2337346281189773310L;
protected IdentityScope(){
}
public IdentityScope(String name){
throw new DeprecatedMethodError("class java.security.IdentityScope is deprecated");
}
public IdentityScope(String name, IdentityScope scope) throws KeyManagementException{}
public static IdentityScope getSystemScope(){
throw new DeprecatedMethodError("class java.security.IdentityScope is deprecated");
}
protected static void setSystemScope(IdentityScope scope){
throw new DeprecatedMethodError("class java.security.IdentityScope is deprecated");
}
public abstract int size();
public abstract Identity getIdentity(String name);
public Identity getIdentity(Principal principal){
throw new DeprecatedMethodError("class java.security.IdentityScope is deprecated");
}
public abstract Identity getIdentity(PublicKey key);
public abstract void addIdentity(Identity identity) throws KeyManagementException;
public abstract void removeIdentity(Identity identity) throws KeyManagementException;
public abstract Enumeration identities();
public String toString(){
throw new DeprecatedMethodError("class java.security.IdentityScope is deprecated");
}
}
|
9242964029ac069d749488af647763ec4dd43725
| 593 |
java
|
Java
|
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/q10.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null |
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/q10.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null |
examples/ru.iiec.cxxdroid/sources/com/google/android/gms/internal/ads/q10.java
|
vietnux/CodeEditorMobile
|
acd29a6a647342276eb557f3af579535092ab377
|
[
"Apache-2.0"
] | null | null | null | 31.210526 | 125 | 0.645868 | 1,002,340 |
package com.google.android.gms.internal.ads;
import java.util.Comparator;
/* access modifiers changed from: package-private */
public final class q10 implements Comparator<w10> {
q10(p10 p10) {
}
/* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object, java.lang.Object] */
@Override // java.util.Comparator
public final /* synthetic */ int compare(w10 w10, w10 w102) {
w10 w103 = w10;
w10 w104 = w102;
int i2 = w103.f5869c - w104.f5869c;
return i2 != 0 ? i2 : (int) (w103.a - w104.a);
}
}
|
9242977d67162974f177e9befc9c0665361b1d02
| 5,476 |
java
|
Java
|
src/main/java/io/choerodon/test/manager/api/controller/v1/TestIssueFolderController.java
|
open-hand/test-manager-service
|
cea2a7cb38fff37e3fce7397f1973a23e343243d
|
[
"Apache-2.0"
] | 6 |
2020-10-17T02:04:19.000Z
|
2021-12-12T13:34:01.000Z
|
src/main/java/io/choerodon/test/manager/api/controller/v1/TestIssueFolderController.java
|
open-hand/test-manager-service
|
cea2a7cb38fff37e3fce7397f1973a23e343243d
|
[
"Apache-2.0"
] | 5 |
2021-08-02T17:16:00.000Z
|
2022-03-14T01:06:46.000Z
|
src/main/java/io/choerodon/test/manager/api/controller/v1/TestIssueFolderController.java
|
open-hand/test-manager-service
|
cea2a7cb38fff37e3fce7397f1973a23e343243d
|
[
"Apache-2.0"
] | 9 |
2020-10-09T09:23:34.000Z
|
2022-03-11T01:23:48.000Z
| 46.820513 | 116 | 0.66192 | 1,002,341 |
package io.choerodon.test.manager.api.controller.v1;
import java.util.Optional;
import java.util.regex.Pattern;
import io.choerodon.core.iam.ResourceLevel;
import io.choerodon.test.manager.api.vo.TestTreeIssueFolderVO;
import io.choerodon.test.manager.infra.dto.TestIssueFolderDTO;
import io.swagger.annotations.ApiOperation;
import org.hzero.core.util.Results;
import org.hzero.starter.keyencrypt.core.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.choerodon.swagger.annotation.Permission;
import io.choerodon.core.exception.CommonException;
import io.choerodon.test.manager.api.vo.TestIssueFolderVO;
import io.choerodon.test.manager.app.service.TestIssueFolderService;
/**
* Created by [email protected] on 08/30/2018
*/
@RestController
@RequestMapping(value = "/v1/projects/{project_id}/issueFolder")
public class TestIssueFolderController {
public static final String TEST_ISSUE_FOLDER_NAME_REG = "^[^/%]{1,50}$";
@Autowired
private TestIssueFolderService testIssueFolderService;
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("查询文件夹,返回树结构")
@GetMapping("/query")
public ResponseEntity<TestTreeIssueFolderVO> query(@PathVariable(name = "project_id") Long projectId) {
return Optional.ofNullable(testIssueFolderService.queryTreeFolder(projectId))
.map(result -> new ResponseEntity<>(result, HttpStatus.OK))
.orElseThrow(() -> new CommonException("error.testIssueFolder.query"));
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("删除文件夹")
@DeleteMapping("/{folderId}")
public ResponseEntity delete(@PathVariable(name = "project_id") Long projectId,
@PathVariable(name = "folderId")
@Encrypt Long folderId) {
testIssueFolderService.delete(projectId, folderId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("创建文件夹")
@PostMapping
public ResponseEntity<TestIssueFolderVO> create(@PathVariable(name = "project_id") Long projectId,
@RequestBody TestIssueFolderVO testIssueFolderVO) {
if (!Pattern.matches(TEST_ISSUE_FOLDER_NAME_REG, testIssueFolderVO.getName())) {
throw new CommonException("error.testIssueFolder.name.invalid");
}
return Optional.ofNullable(testIssueFolderService.create(projectId, testIssueFolderVO))
.map(result -> new ResponseEntity<>(result, HttpStatus.CREATED))
.orElseThrow(() -> new CommonException("error.testIssueFolder.insert"));
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("更新文件夹")
@PutMapping("/update")
public ResponseEntity<TestIssueFolderVO> update(@PathVariable(name = "project_id") Long projectId,
@RequestBody TestIssueFolderVO testIssueFolderVO) {
if (!Pattern.matches(TEST_ISSUE_FOLDER_NAME_REG, testIssueFolderVO.getName())) {
throw new CommonException("error.testIssueFolder.name.invalid");
}
return Optional.ofNullable(testIssueFolderService.update(testIssueFolderVO))
.map(result -> new ResponseEntity<>(result, HttpStatus.CREATED))
.orElseThrow(() -> new CommonException("error.testIssueFolder.update"));
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("移动文件夹")
@PutMapping("/move")
public ResponseEntity<String> moveFolder(@PathVariable(name = "project_id") Long projectId,
@RequestParam(name = "targetFolderId", required = false)
@Encrypt Long targetFolderId,
@RequestBody TestIssueFolderVO issueFolderVO) {
return Optional.ofNullable(testIssueFolderService.moveFolder(projectId, targetFolderId, issueFolderVO))
.map(result -> new ResponseEntity<>(result, HttpStatus.OK))
.orElseThrow(() -> new CommonException("error.testIssueFolder.move"));
}
/**
* 复制计划文件夹
*/
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("复制计划文件夹")
@PostMapping("/folder/{folderId}/clone")
public ResponseEntity<TestIssueFolderDTO> cloneTestCaseFolder(@PathVariable(name = "project_id") Long projectId,
@PathVariable(name = "folderId")
@Encrypt Long folderId) {
return Results.success(testIssueFolderService.cloneFolder(projectId, folderId));
}
/**
* 复制计划文件夹
*/
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("检查复制文件夹名称合规")
@GetMapping("/folder/{folderId}/clone/check_name")
public ResponseEntity<Boolean> checkCopyFolderName(@PathVariable(name = "project_id") Long projectId,
@PathVariable(name = "folderId")
@Encrypt Long folderId) {
return Results.success(testIssueFolderService.checkCopyFolderName(projectId, folderId));
}
}
|
924299ab9c0aef4a527dba0d6324db1a0bc04609
| 586 |
java
|
Java
|
stdole2/src/main/java/eu/doppel_helix/jna/tlb/stdole2/LoadPictureConstants.java
|
matthiasblaesing/COMTypelibraries
|
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
|
[
"MIT"
] | 15 |
2016-11-30T17:25:43.000Z
|
2021-07-10T22:32:06.000Z
|
stdole2/src/main/java/eu/doppel_helix/jna/tlb/stdole2/LoadPictureConstants.java
|
matthiasblaesing/COMTypelibraries
|
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
|
[
"MIT"
] | null | null | null |
stdole2/src/main/java/eu/doppel_helix/jna/tlb/stdole2/LoadPictureConstants.java
|
matthiasblaesing/COMTypelibraries
|
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
|
[
"MIT"
] | 1 |
2019-09-10T02:40:33.000Z
|
2019-09-10T02:40:33.000Z
| 14.65 | 54 | 0.513652 | 1,002,342 |
package eu.doppel_helix.jna.tlb.stdole2;
import com.sun.jna.platform.win32.COM.util.IComEnum;
/**
* <p>uuid({E6C8FA08-BD9F-11D0-985E-00C04FC29993})</p>
*/
public enum LoadPictureConstants implements IComEnum {
/**
* (0)
*/
_Default(0),
/**
* (1)
*/
Monochrome(1),
/**
* (2)
*/
VgaColor(2),
/**
* (4)
*/
Color(4),
;
private LoadPictureConstants(long value) {
this.value = value;
}
private long value;
public long getValue() {
return this.value;
}
}
|
92429b707d07cda515365b9b9b49570464784a00
| 308 |
java
|
Java
|
coop/src/main/java/com/coopsystem/coop/CoopApplication.java
|
RebeccaDmello/CO-OPSYSTEM
|
6833dcacecb1210d05dc190bcbed69b371d0760a
|
[
"MIT"
] | 1 |
2021-07-07T17:52:24.000Z
|
2021-07-07T17:52:24.000Z
|
coop/src/main/java/com/coopsystem/coop/CoopApplication.java
|
RebeccaDmello/CO-OPSYSTEM
|
6833dcacecb1210d05dc190bcbed69b371d0760a
|
[
"MIT"
] | 7 |
2021-03-27T16:30:34.000Z
|
2021-03-28T19:37:51.000Z
|
coop/src/main/java/com/coopsystem/coop/CoopApplication.java
|
RebeccaDmello/CO-OPSYSTEM
|
6833dcacecb1210d05dc190bcbed69b371d0760a
|
[
"MIT"
] | null | null | null | 22 | 68 | 0.818182 | 1,002,343 |
package com.coopsystem.coop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoopApplication {
public static void main(String[] args) {
SpringApplication.run(CoopApplication.class, args);
}
}
|
92429c095e4653697c5b7e5d83466d61e418b186
| 1,103 |
java
|
Java
|
src/test/java/org/testfun/jee/examples/DaoTest.java
|
michaelyaakoby/testfun
|
646680797042878e48d365170514635ac26f501a
|
[
"Apache-2.0"
] | 13 |
2015-01-14T18:19:57.000Z
|
2021-04-06T06:44:09.000Z
|
src/test/java/org/testfun/jee/examples/DaoTest.java
|
michaelyaakoby/testfun
|
646680797042878e48d365170514635ac26f501a
|
[
"Apache-2.0"
] | 11 |
2016-03-24T21:19:55.000Z
|
2018-01-28T20:21:13.000Z
|
src/test/java/org/testfun/jee/examples/DaoTest.java
|
michaelyaakoby/testfun
|
646680797042878e48d365170514635ac26f501a
|
[
"Apache-2.0"
] | 8 |
2015-06-22T05:45:03.000Z
|
2018-08-16T04:12:16.000Z
| 27.575 | 121 | 0.661831 | 1,002,344 |
package org.testfun.jee.examples;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testfun.jee.EjbWithMockitoRunner;
import org.testfun.jee.real.SomeDao;
import org.testfun.jee.real.SomeEntity;
import javax.ejb.EJB;
import java.util.Arrays;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
@RunWith(EjbWithMockitoRunner.class)
public class DaoTest {
@EJB
private SomeDao dao;
@Test
public void saveOne() {
dao.save(new SomeEntity(0, "1. one", "s"));
List<SomeEntity> entities = dao.getAll();
assertEquals(1, entities.size());
}
@Test
public void getMany() {
dao.save(new SomeEntity(0, "1. one", "s"));
dao.save(new SomeEntity(0, "2. two", "r"));
List<SomeEntity> entities = dao.getAll();
assertEquals(2, entities.size());
assertThat(entities).
onProperty("name").
isEqualTo(Arrays.asList("1. one", "2. two"));//Note, this using org.fest.assertions.Assertions.assertThat
}
}
|
92429c696eebd68176e96ed78b914089aa36fa00
| 313 |
java
|
Java
|
MicroservicesSpringCloud/user-service/src/main/java/com/dailycodebuffer/user/vo/ResponseTemplateVO.java
|
ggranados/Spring
|
036fc36cb25a37f189e39c67281fb2ec9d068570
|
[
"MIT"
] | null | null | null |
MicroservicesSpringCloud/user-service/src/main/java/com/dailycodebuffer/user/vo/ResponseTemplateVO.java
|
ggranados/Spring
|
036fc36cb25a37f189e39c67281fb2ec9d068570
|
[
"MIT"
] | null | null | null |
MicroservicesSpringCloud/user-service/src/main/java/com/dailycodebuffer/user/vo/ResponseTemplateVO.java
|
ggranados/Spring
|
036fc36cb25a37f189e39c67281fb2ec9d068570
|
[
"MIT"
] | null | null | null | 17.388889 | 44 | 0.811502 | 1,002,345 |
package com.dailycodebuffer.user.vo;
import com.dailycodebuffer.user.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseTemplateVO {
private User user;
private Department department;
}
|
92429e39e426f779d4619e4fa2d52591631ec8bd
| 3,492 |
java
|
Java
|
src/cli/lombok/core/ThreadingAwareConstants.java
|
griffon/griffon-lombok-plugin
|
d682b0d2c3f3ce2986de6f0d893108bb3c2820f8
|
[
"Apache-2.0"
] | 1 |
2015-01-10T11:09:19.000Z
|
2015-01-10T11:09:19.000Z
|
src/cli/lombok/core/ThreadingAwareConstants.java
|
griffon/griffon-lombok-plugin
|
d682b0d2c3f3ce2986de6f0d893108bb3c2820f8
|
[
"Apache-2.0"
] | 1 |
2016-12-09T16:53:38.000Z
|
2016-12-09T16:53:38.000Z
|
src/cli/lombok/core/ThreadingAwareConstants.java
|
griffon/griffon-lombok-plugin
|
d682b0d2c3f3ce2986de6f0d893108bb3c2820f8
|
[
"Apache-2.0"
] | null | null | null | 35.632653 | 101 | 0.681271 | 1,002,346 |
/*
* Copyright 2012-2013 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
*
* 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 lombok.core;
import lombok.core.util.MethodDescriptor;
import java.util.LinkedHashMap;
import java.util.Map;
import static lombok.core.util.MethodDescriptor.args;
import static lombok.core.util.MethodDescriptor.type;
import static lombok.core.util.MethodDescriptor.typeParams;
/**
* @author Andres Almiray
*/
public interface ThreadingAwareConstants extends BaseConstants {
String UITHREAD_MANAGER_TYPE = "griffon.core.UIThreadManager";
String THREADING_HANDLER_TYPE = "griffon.core.ThreadingHandler";
String METHOD_IS_UITHREAD = "isUIThread";
String METHOD_EXEC_INSIDE_UI_ASYNC = "execInsideUIAsync";
String METHOD_EXEC_INSIDE_UI_SYNC = "execInsideUISync";
String METHOD_EXEC_OUTSIDE_UI = "execOutsideUI";
String METHOD_EXEC_FUTURE = "execFuture";
String JAVA_UTIL_CONCURRENT_FUTURE = "java.util.concurrent.Future";
String JAVA_UTIL_CONCURRENT_CALLABLE = "java.util.concurrent.Callable";
String JAVA_UTIL_CONCURRENT_EXECUTOR_SERVICE = "java.util.concurrent.ExecutorService";
Map<String, String> METHOD_MAPPER = new LinkedHashMap<String, String>() {{
put(METHOD_EXEC_INSIDE_UI_ASYNC, "executeAsync");
put(METHOD_EXEC_INSIDE_UI_SYNC, "executeSync");
put(METHOD_EXEC_OUTSIDE_UI, "executeOutside");
put(METHOD_EXEC_FUTURE, "executeFuture");
}};
MethodDescriptor[] METHODS = new MethodDescriptor[]{
MethodDescriptor.method(
type(BOOLEAN),
METHOD_IS_UITHREAD
),
MethodDescriptor.method(
type(VOID),
METHOD_EXEC_INSIDE_UI_ASYNC,
args(type(JAVA_LANG_RUNNABLE))
),
MethodDescriptor.method(
type(VOID),
METHOD_EXEC_INSIDE_UI_SYNC,
args(type(JAVA_LANG_RUNNABLE))
),
MethodDescriptor.method(
type(VOID),
METHOD_EXEC_OUTSIDE_UI,
args(type(JAVA_LANG_RUNNABLE))
),
MethodDescriptor.method(
type(JAVA_UTIL_CONCURRENT_FUTURE, R),
typeParams(R),
METHOD_EXEC_FUTURE,
args(type(JAVA_UTIL_CONCURRENT_EXECUTOR_SERVICE), type(GROOVY_LANG_CLOSURE, R))
),
MethodDescriptor.method(
type(JAVA_UTIL_CONCURRENT_FUTURE, R),
typeParams(R),
METHOD_EXEC_FUTURE,
args(type(JAVA_UTIL_CONCURRENT_EXECUTOR_SERVICE), type(JAVA_UTIL_CONCURRENT_CALLABLE, R))
),
MethodDescriptor.method(
type(JAVA_UTIL_CONCURRENT_FUTURE, R),
typeParams(R),
METHOD_EXEC_FUTURE,
args(type(GROOVY_LANG_CLOSURE, R))
),
MethodDescriptor.method(
type(JAVA_UTIL_CONCURRENT_FUTURE, R),
typeParams(R),
METHOD_EXEC_FUTURE,
args(type(JAVA_UTIL_CONCURRENT_CALLABLE, R))
)
};
}
|
92429e5e15660231d956e9e88fd69097284afd15
| 835 |
java
|
Java
|
src/test/java/com/melprobe/tdd/hello/HelloWorldTest.java
|
MelProbe/hello_TDD
|
b8f8fbabb2678917a8de9fa6daccae3ffd134762
|
[
"MIT"
] | null | null | null |
src/test/java/com/melprobe/tdd/hello/HelloWorldTest.java
|
MelProbe/hello_TDD
|
b8f8fbabb2678917a8de9fa6daccae3ffd134762
|
[
"MIT"
] | 6 |
2022-03-15T02:41:33.000Z
|
2022-03-17T05:01:14.000Z
|
src/test/java/com/melprobe/tdd/hello/HelloWorldTest.java
|
MelProbe/calculator_TDD
|
2174114457d0ac1735a180c1ec327bd7c1cb5429
|
[
"MIT"
] | null | null | null | 18.977273 | 50 | 0.582036 | 1,002,347 |
package com.melprobe.tdd.hello;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HelloWorldTest {
private HelloWorld hello;
@Before
public void setup() {
hello = new HelloWorld();
}
@Test
public void test() {
String msg = hello.getMessage();
assertEquals("Hello World", msg);
}
@Test
public void testGetMessage() {
String msg = hello.getMessage("MelProbe");
assertEquals("Hello MelProbe", msg);
}
@Test
public void testGetMessageNull() {
String msg = hello.getMessage(null);
assertEquals("Hello World", msg);
}
@After
public void tearDown() {
System.out.println("...");
}
}
|
92429f6527266af332d8f4b6df9bb77508b4678c
| 830 |
java
|
Java
|
PalindromeNumber.java
|
intern0t/leetcode
|
a0fc4fc49d2c2ef77ba8737731531c3d04c0bc84
|
[
"MIT"
] | null | null | null |
PalindromeNumber.java
|
intern0t/leetcode
|
a0fc4fc49d2c2ef77ba8737731531c3d04c0bc84
|
[
"MIT"
] | null | null | null |
PalindromeNumber.java
|
intern0t/leetcode
|
a0fc4fc49d2c2ef77ba8737731531c3d04c0bc84
|
[
"MIT"
] | null | null | null | 28.62069 | 69 | 0.481928 | 1,002,348 |
class PalindromeNumber {
public static void main(String[] args) {
int testCases[] = { 121, -121, 10, -101, 0 };
for (int i = 0; i < testCases.length; i++) {
System.out.println(
testCases[i] +
" is palindrome? : " +
(isPalindrome(testCases[i]) ? "true" : "false")
);
}
}
public static boolean isPalindrome(int x) {
// Valid integers would not allow anything in format of -123-
// Therefore, if anything is negative, it's not a plaindrome.
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int half_of_x = 0;
while (half_of_x < x) {
half_of_x = half_of_x * 10 + x % 10;
x /= 10;
}
return (x == half_of_x || half_of_x / 10 == x);
}
}
|
92429fd8e26da5e3505c1ba17ad35d9a49b52d60
| 4,714 |
java
|
Java
|
src/main/java/net/daw/connection/implementation/DriverManagerConnectionImpl.java
|
virtudesp/gesmusic-server
|
a7ec985c27ad9b3a3db4bf9127df9ef32fcf5709
|
[
"MIT"
] | null | null | null |
src/main/java/net/daw/connection/implementation/DriverManagerConnectionImpl.java
|
virtudesp/gesmusic-server
|
a7ec985c27ad9b3a3db4bf9127df9ef32fcf5709
|
[
"MIT"
] | null | null | null |
src/main/java/net/daw/connection/implementation/DriverManagerConnectionImpl.java
|
virtudesp/gesmusic-server
|
a7ec985c27ad9b3a3db4bf9127df9ef32fcf5709
|
[
"MIT"
] | null | null | null | 46.215686 | 306 | 0.733984 | 1,002,349 |
/*
* Copyright (c) 2016 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane-server: Helps you to develop easily AJAX web applications
* by copying and modifying this Java Server.
*
* Sources at https://github.com/rafaelaznar/sisane-server
*
* sisane-server is distributed under the MIT License (MIT)
*
* 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.daw.connection.implementation;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.daw.connection.publicinterface.ConnectionInterface;
import net.daw.helper.statics.ConnectionClassHelper;
import net.daw.helper.statics.Log4j;
public class DriverManagerConnectionImpl implements ConnectionInterface {
@Override
public Connection newConnection() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://" + ConnectionClassHelper.getDatabaseHost() + ":" + ConnectionClassHelper.getDatabasePort() + "/" + ConnectionClassHelper.getDatabaseName(), ConnectionClassHelper.getDatabaseLogin(), ConnectionClassHelper.getDatabasePassword());
return connection;
} catch (ClassNotFoundException | SQLException ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
}
}
@Override
public void disposeConnection() throws Exception {
}
}
// Cadena de conexión
//http://localhost:8081/gesmusic-server/json?ob=usuario&op=login&user=cacun&pass=cacun
//
//http://localhost:8081/gesmusic-server/json?ob=tipousuario&op=getall
//http://localhost:8081/gesmusic-server/json?ob=tipousuario&op=get&id=2
//http://localhost:8081/gesmusic-server/json?ob=tipousuario&op=set&json={"tipousuario":"nsnc"}
//
//http://localhost:8081/gesmusic-server/json?ob=rol&op=getpage&page=2&10
//
// RELACIONES 1:N
//http://localhost:8081/gesmusic-server/json?ob=obra&op=getpage&id=3&page=1&rpp=10
//http://localhost:8081/gesmusic-server/json?ob=usuario&op=getpage&id=4&page=1&rpp=10
//http://localhost:8081/gesmusic-server/json?ob=obra&op=set&foreign=7&json={"titulo":"Habia una vez"}
//http://localhost:8081/gesmusic-server/json?ob=obra&op=set&id=18&foreign=7&json={"id":"17","subtitulo":"pasodoble"}
//
// N:M
//http://localhost:8081/gesmusic-server/json?ob=participa&op=getpage&id=31
// ob=participa&op=set&id=0&foreign=9&json={"id":"11","subtitulo":"grupo jazz"}
// ob=repertorio&op=getpage&id=9&foreign=1
// ob=repertorio&op=getpage&foreign=9&foreign2=1
// ob=obra&op=getpage&id=9&foreign=1
// ob=obra&op=getpage&id=9
///http://localhost:8081/gesmusic-server/json?ob=elenco&op=set&json={"id_miembro":"1","id_agrupacion":"1","id_rol":"1"}
//http://localhost:8081/gesmusic-server/json?ob=tipomiembro&op=set&json={"id":"4","tipomiembro":"cocineroooooo"}
//http://localhost:8081/gesmusic-server/json?ob=usuario&op=set&json={"id":"0","username":"David","userpass":"iniested","id_tipousuario":"4"}
//ob=miembro&op=remove&id=63
//ob=miembro&op=set&json={"numero":"S00022","nombre":"Rosa","apellidos":"Uno Dos","id_sociedad":"1","id_tipomiembro":"2"}
//ALTER TABLE participa DROP FOREIGN KEY fk_participa_acto1;
//json?ob=compositor&op=getcount
//json?ob=usuario&op=getcount&id=4
//json?ob=miembro&op=getcount&id=1
//json?
/*
http://localhost:8081/gesmusic-server/json?ob=tipomiembro&op=set&json={"id":4,"tipomiembro":"cocineroo de mi amorrrr","total":0}
ob=tipomiembro&op=set&json={"tipomiembro":"casual"}
https://github.com/virtudesp/gesmusic-client/blob/master/public_html/js/compositor/plist.js
*/
|
9242a007693b37aa0430774e774bf44989183e7c
| 335 |
java
|
Java
|
src/com/retailsstore/discount/ThresholdDiscount.java
|
ajitlawand123/projects
|
6b828b52a405985c2817fea9016d81c9a2453104
|
[
"MIT"
] | null | null | null |
src/com/retailsstore/discount/ThresholdDiscount.java
|
ajitlawand123/projects
|
6b828b52a405985c2817fea9016d81c9a2453104
|
[
"MIT"
] | null | null | null |
src/com/retailsstore/discount/ThresholdDiscount.java
|
ajitlawand123/projects
|
6b828b52a405985c2817fea9016d81c9a2453104
|
[
"MIT"
] | 1 |
2021-12-08T16:12:33.000Z
|
2021-12-08T16:12:33.000Z
| 19.705882 | 64 | 0.752239 | 1,002,350 |
package com.retailsstore.discount;
public class ThresholdDiscount implements ProductDiscountPolicy{
public double applyDiscount(double totalAmount) {
if (totalAmount < 100) {
return totalAmount;
}
int discountFactor = (int) totalAmount / 100;
double discount = discountFactor * 5;
return totalAmount - discount;
}
}
|
9242a21d48912b3b57e2a4e9ebbeb73d0bdeac88
| 447 |
java
|
Java
|
neural-common/src/main/java/cn/neural/common/plugin/context/PluginContextListener.java
|
yu120/neural
|
63a69bcdce7b7d19dd222165624ff877791ceab7
|
[
"MIT"
] | 475 |
2016-07-28T07:32:23.000Z
|
2022-03-25T07:24:47.000Z
|
neural-common/src/main/java/cn/neural/common/plugin/context/PluginContextListener.java
|
herozeng/neural
|
39c61cc87fd31253f8aef0343716900da9a276ca
|
[
"MIT"
] | null | null | null |
neural-common/src/main/java/cn/neural/common/plugin/context/PluginContextListener.java
|
herozeng/neural
|
39c61cc87fd31253f8aef0343716900da9a276ca
|
[
"MIT"
] | 132 |
2016-07-28T07:30:37.000Z
|
2022-02-22T17:17:38.000Z
| 17.88 | 54 | 0.653244 | 1,002,351 |
package cn.neural.common.plugin.context;
/**
* PluginContextListener
*
* @author lry
*/
public interface PluginContextListener {
/**
* The context initialized
*
* @param event {@link PluginContextEvent}
*/
void contextInitialized(PluginContextEvent event);
/**
* The context destroyed
*
* @param event {@link PluginContextEvent}
*/
void contextDestroyed(PluginContextEvent event);
}
|
9242a2241727a66830c342fca8f0e63edbf1665e
| 2,387 |
java
|
Java
|
IHMCRoboticsToolkit/test/us/ihmc/robotics/math/filters/AlphaFilteredYoVariableTest.java
|
wxmerkt/ihmc-open-robotics-software
|
2c47c9a9bd999e7811038e99c3888683f9973a2a
|
[
"Apache-2.0"
] | null | null | null |
IHMCRoboticsToolkit/test/us/ihmc/robotics/math/filters/AlphaFilteredYoVariableTest.java
|
wxmerkt/ihmc-open-robotics-software
|
2c47c9a9bd999e7811038e99c3888683f9973a2a
|
[
"Apache-2.0"
] | null | null | null |
IHMCRoboticsToolkit/test/us/ihmc/robotics/math/filters/AlphaFilteredYoVariableTest.java
|
wxmerkt/ihmc-open-robotics-software
|
2c47c9a9bd999e7811038e99c3888683f9973a2a
|
[
"Apache-2.0"
] | null | null | null | 37.888889 | 146 | 0.750733 | 1,002,352 |
package us.ihmc.robotics.math.filters;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Test;
import us.ihmc.robotics.dataStructures.registry.YoVariableRegistry;
import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable;
import us.ihmc.robotics.math.filters.AlphaFilteredYoVariable;
import us.ihmc.tools.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest;
public class AlphaFilteredYoVariableTest
{
private final Random rng = new Random();
@ContinuousIntegrationTest(estimatedDuration = 0.0)
@Test(timeout=300000)
public void testNoisyFixedPosition()
{
// Use a reasonably large alpha for a reasonably large amount of noise
double alpha = 0.8;
YoVariableRegistry registry = new YoVariableRegistry("testRegistry");
DoubleYoVariable positionVariable = new DoubleYoVariable("positionVariable", registry);
AlphaFilteredYoVariable alphaFilteredYoVariable = new AlphaFilteredYoVariable("alphaFilteredYoVariable", registry, alpha, positionVariable);
double pseudoNoise = 0;
positionVariable.set(10);
for (int i = 0; i < 10000; i++)
{
// Oscillate the position about some uniformly distributed fixed point slightly larger than 10
if (i % 2 == 0)
{
pseudoNoise = rng.nextDouble();
}
positionVariable.add(Math.pow(-1, i) * pseudoNoise);
alphaFilteredYoVariable.update();
}
assertEquals(10, alphaFilteredYoVariable.getDoubleValue(), 1);
}
@ContinuousIntegrationTest(estimatedDuration = 0.0)
@Test(timeout=300000)
public void testAlphaAndBreakFrequencyComputations()
{
double DT = 0.1;
double randomAlpha = rng.nextDouble();
double computedBreakFrequency = AlphaFilteredYoVariable.computeBreakFrequencyGivenAlpha(randomAlpha, DT);
double computedAlpha = AlphaFilteredYoVariable.computeAlphaGivenBreakFrequencyProperly(computedBreakFrequency, DT);
assertEquals(randomAlpha, computedAlpha, 1e-7);
assertEquals(computedBreakFrequency, AlphaFilteredYoVariable.computeBreakFrequencyGivenAlpha(computedAlpha, DT), 1e-7);
System.out.println("Random Alpha: " + randomAlpha);
System.out.println("Computed Alpha: " + AlphaFilteredYoVariable.computeAlphaGivenBreakFrequencyProperly(computedBreakFrequency, DT));
}
}
|
9242a363700ef63dcae50ea4ad1d0e1a6d5562c8
| 2,271 |
java
|
Java
|
aliyun-spring-boot-starters/aliyun-oss-spring-boot-starter/src/main/java/com/alibaba/cloud/spring/boot/oss/actuate/OssEndpoint.java
|
yinhudongtian/aliyun-spring-boot
|
972a2aed8010878e15ecac09c3722434b7edfda9
|
[
"Apache-2.0"
] | 320 |
2020-03-18T08:20:42.000Z
|
2022-03-31T06:45:41.000Z
|
aliyun-spring-boot-starters/aliyun-oss-spring-boot-starter/src/main/java/com/alibaba/cloud/spring/boot/oss/actuate/OssEndpoint.java
|
mercyblitz/aliyun-spring-boot
|
cb59bb1e2f61dfc73a4a7b8a0ee4a2b7b29b56a0
|
[
"Apache-2.0"
] | 44 |
2020-03-18T01:31:09.000Z
|
2022-02-12T08:52:34.000Z
|
aliyun-spring-boot-starters/aliyun-oss-spring-boot-starter/src/main/java/com/alibaba/cloud/spring/boot/oss/actuate/OssEndpoint.java
|
mercyblitz/aliyun-spring-boot
|
cb59bb1e2f61dfc73a4a7b8a0ee4a2b7b29b56a0
|
[
"Apache-2.0"
] | 92 |
2020-03-19T15:46:53.000Z
|
2022-03-30T15:26:02.000Z
| 31.611111 | 77 | 0.744728 | 1,002,353 |
/*
* Copyright 2013-2018 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 com.alibaba.cloud.spring.boot.oss.actuate;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.context.ApplicationContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Actuator {@link Endpoint} to expose OSS Meta Data.
*
* @author <a href="mailto:[email protected]">Jim</a>
*/
@Endpoint(id = "oss")
public class OssEndpoint {
@Autowired
private ApplicationContext applicationContext;
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>();
Map<String, OSSClient> ossClientMap = applicationContext
.getBeansOfType(OSSClient.class);
int size = ossClientMap.size();
List<Object> ossClientList = new ArrayList<>();
ossClientMap.keySet().forEach(beanName -> {
Map<String, Object> ossProperties = new HashMap<>();
OSSClient client = ossClientMap.get(beanName);
ossProperties.put("beanName", beanName);
ossProperties.put("endpoint", client.getEndpoint().toString());
ossProperties.put("clientConfiguration", client.getClientConfiguration());
ossProperties.put("credentials",
client.getCredentialsProvider().getCredentials());
ossProperties.put("bucketList", client.listBuckets().stream()
.map(bucket -> bucket.getName()).toArray());
ossClientList.add(ossProperties);
});
result.put("size", size);
result.put("info", ossClientList);
return result;
}
}
|
9242a3b79798ea9cee5fbeea5c559a28bbb09f08
| 1,660 |
java
|
Java
|
learnnetty/telnetservice/src/main/java/com/alison/NettyTelnetServer.java
|
GavinAlison/advanceJava
|
93766361c7bb934d0c0abbf3eca87a5beb463cee
|
[
"Apache-2.0"
] | null | null | null |
learnnetty/telnetservice/src/main/java/com/alison/NettyTelnetServer.java
|
GavinAlison/advanceJava
|
93766361c7bb934d0c0abbf3eca87a5beb463cee
|
[
"Apache-2.0"
] | 2 |
2019-10-19T13:49:01.000Z
|
2019-12-10T08:25:58.000Z
|
learnnetty/telnetservice/src/main/java/com/alison/NettyTelnetServer.java
|
GavinAlison/advanceJava
|
93766361c7bb934d0c0abbf3eca87a5beb463cee
|
[
"Apache-2.0"
] | null | null | null | 34.583333 | 84 | 0.696386 | 1,002,354 |
package com.alison;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* @Author alison
* @Date 2019/9/19 22:06
* @Version 1.0
* @Description 主程序
* @link https://www.jianshu.com/p/5dcbc0456376
*/
public class NettyTelnetServer {
// 指定端口号
private static final int PORT = 8888;
private ServerBootstrap serverBootstrap;
// NioEventLoopGroup对应一个被封装好的NIO线程池,bossGroup负责收集客户端连接,workerGroup负责处理每个连接的IO读写。
private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
private EventLoopGroup workerGroup = new NioEventLoopGroup();
public void open() throws InterruptedException {
// ServerBootstrap是Socket服务端启动类。
serverBootstrap = new ServerBootstrap();
// 指定socket的一些属性
serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // 指定是一个NIO连接通道
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new NettyTelnetInitializer());
// 绑定对应的端口号,并启动开始监听端口上的连接
Channel ch = serverBootstrap.bind(PORT).sync().channel();
// 等待关闭,同步端口
ch.closeFuture().sync();
}
public void close(){
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
|
9242a3f9bf4721844d663d2131da53b7bb7d381d
| 4,296 |
java
|
Java
|
src/main/java/me/mrdaniel/npcs/commands/armor/CommandEquipmentRemove.java
|
MGlolenstine/NPCs
|
986a96de8e6cb3525843ea183aeaa12c34ee8dde
|
[
"MIT"
] | null | null | null |
src/main/java/me/mrdaniel/npcs/commands/armor/CommandEquipmentRemove.java
|
MGlolenstine/NPCs
|
986a96de8e6cb3525843ea183aeaa12c34ee8dde
|
[
"MIT"
] | null | null | null |
src/main/java/me/mrdaniel/npcs/commands/armor/CommandEquipmentRemove.java
|
MGlolenstine/NPCs
|
986a96de8e6cb3525843ea183aeaa12c34ee8dde
|
[
"MIT"
] | null | null | null | 40.149533 | 146 | 0.76513 | 1,002,355 |
package me.mrdaniel.npcs.commands.armor;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.ArmorEquipable;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import me.mrdaniel.npcs.NPCs;
import me.mrdaniel.npcs.catalogtypes.menupages.PageTypes;
import me.mrdaniel.npcs.commands.NPCCommand;
import me.mrdaniel.npcs.events.NPCEvent;
import me.mrdaniel.npcs.io.NPCFile;
import me.mrdaniel.npcs.managers.menu.NPCMenu;
public abstract class CommandEquipmentRemove extends NPCCommand {
public CommandEquipmentRemove(@Nonnull final NPCs npcs) {
super(npcs, PageTypes.ARMOR);
}
@Override
public void execute(final Player p, final NPCMenu menu, final CommandContext args) throws CommandException {
if (!(menu.getNPC() instanceof ArmorEquipable)) { throw new CommandException(Text.of(TextColors.RED, "The selected NPC can not wear armor!")); }
ArmorEquipable ae = (ArmorEquipable) menu.getNPC();
this.get(ae).orElseThrow(() -> new CommandException(Text.of(TextColors.RED, "The selected NPC does not have that piece of equipment.")));
if (super.getGame().getEventManager().post(new NPCEvent.Edit(super.getContainer(), p, menu.getNPC(), menu.getFile()))) {
throw new CommandException(Text.of(TextColors.RED, "Could not edit NPC: Event was cancelled!"));
}
this.clear(ae);
this.clear(menu.getFile());
}
public abstract Optional<ItemStack> get(@Nonnull final ArmorEquipable ae);
public abstract void clear(@Nonnull final ArmorEquipable ae);
public abstract void clear(@Nonnull final NPCFile file);
public static class Helmet extends CommandEquipmentRemove {
public Helmet(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getHelmet(); }
@Override public void clear(final ArmorEquipable ae) { ae.setHelmet(null); }
@Override public void clear(final NPCFile file) { file.setHelmet(null); }
}
public static class Chestplate extends CommandEquipmentRemove {
public Chestplate(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getChestplate(); }
@Override public void clear(final ArmorEquipable ae) { ae.setChestplate(null); }
@Override public void clear(final NPCFile file) { file.setChestplate(null); }
}
public static class Leggings extends CommandEquipmentRemove {
public Leggings(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getLeggings(); }
@Override public void clear(final ArmorEquipable ae) { ae.setLeggings(null); }
@Override public void clear(final NPCFile file) { file.setLeggings(null); }
}
public static class Boots extends CommandEquipmentRemove {
public Boots(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getBoots(); }
@Override public void clear(final ArmorEquipable ae) { ae.setBoots(null); }
@Override public void clear(final NPCFile file) { file.setBoots(null); }
}
public static class MainHand extends CommandEquipmentRemove {
public MainHand(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getItemInHand(HandTypes.MAIN_HAND); }
@Override public void clear(final ArmorEquipable ae) { ae.setItemInHand(HandTypes.MAIN_HAND, null); }
@Override public void clear(final NPCFile file) { file.setMainHand(null); }
}
public static class OffHand extends CommandEquipmentRemove {
public OffHand(@Nonnull final NPCs npcs) {
super(npcs);
}
@Override public Optional<ItemStack> get(final ArmorEquipable ae) { return ae.getItemInHand(HandTypes.OFF_HAND); }
@Override public void clear(final ArmorEquipable ae) { ae.setItemInHand(HandTypes.OFF_HAND, null); }
@Override public void clear(final NPCFile file) { file.setOffHand(null); }
}
}
|
9242a48665ce59758efded9981d02c71f6455938
| 5,703 |
java
|
Java
|
noc/NOC.java
|
TheSav1101/JavaNocCalculator
|
5e43d1b45422cb5100de95feaa1602623b238424
|
[
"Apache-2.0"
] | null | null | null |
noc/NOC.java
|
TheSav1101/JavaNocCalculator
|
5e43d1b45422cb5100de95feaa1602623b238424
|
[
"Apache-2.0"
] | null | null | null |
noc/NOC.java
|
TheSav1101/JavaNocCalculator
|
5e43d1b45422cb5100de95feaa1602623b238424
|
[
"Apache-2.0"
] | null | null | null | 44.554688 | 167 | 0.367526 | 1,002,356 |
package noc;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NOC{
//Usage: java NOC <path_to_project> $(find . -name '*.java' -print)
public static void main(String[] args){
Path start = Paths.get(args[0]);
List<String> collect = null;
try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());
//collect.forEach(System.out::println);
}catch(Exception e){
System.out.println("Something bad happened...");
}
ClassTree t = new ClassTree();
File f = null;
Scanner sc = null;
Iterator<String> lit = collect.iterator();
String fs = null;
while(lit.hasNext()){
try{
fs = lit.next();
boolean inComment = false;
boolean willBeComment = false;
if(fs.substring(fs.length() - 5,fs.length()).equals(".java")){
f = new File(fs);
sc = new Scanner(f);
while(sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("/**") || line.contains("/*")){
line = line.substring(0, line.indexOf("/*"));
willBeComment = true;
}
if(line.contains("}")){
line = line.substring(0, line.indexOf("}"));
}
if(!inComment && (line.contains("class ") || line.contains("interface ")) && (!line.substring(line.length() - 2, line.length()).equals("*/"))){
String className = null;
Vector<String> v = new Vector<String>();
String[] knownSuperclassesNames = null;
Scanner lineScan = new Scanner(line);
String[] words = line.split("[ ,{]+");
int k = 0;
for(int z = 0; z < words.length; z++){
if(words[z].equals("//")){
break;
}else if(words[z].equals("/*") || words[z].equals("/**")){
inComment = true;
break;
}
else if(words[z].equals("class") || words[z].equals("interface"))
k = 1;
else if(words[z].equals("extends"))
k = 2;
else if(words[z].equals("implements"))
k = 3;
else if(k == 1 && words[z] != ""){
className = words[z];
if(className.contains("<"))
while(!className.contains(">") && z < words.length - 1){
z++;
className += words[z];
}
//System.out.println(className + " was added as a class.");
}
else if((k == 2 || k == 3) && words[z] != ""){
String toAdd = "";
toAdd += words[z];
if(toAdd.contains("<"))
while(!toAdd.contains(">") && z < words.length - 1){
z++;
toAdd += words[z];
}
v.add(toAdd);
//System.out.println(words[z] + " is a superclass or super interface of " + className + ".");
}
}
knownSuperclassesNames = new String[v.size()];
for(int r = 0; r < v.size(); r ++){
knownSuperclassesNames[r] = v.get(r);
}
lineScan.close();
if(!inComment && className != null)
t.addClass(new ClassInfo(className, knownSuperclassesNames));
}else if(inComment){
if(line.contains("*/"))
inComment = false;
}else if(willBeComment){
willBeComment = false;
inComment = true;
}
}
sc.close();
}
}catch(FileNotFoundException e){
System.out.println("File: " + fs + " was not found!");
}
}
t.magic();
Vector<String> vs = t.allCounted();
Iterator<String> it = vs.iterator();
while(it.hasNext()){
System.out.print(it.next());
}
}
}
|
9242a68e5e7bc49067fa148672ac65461814fa78
| 455 |
java
|
Java
|
src/main/java/com/infosys/api/shipment/events/OrderCreatedEvent.java
|
prashantonline/shipmentservice-1
|
27950182b8509bc98cef2e2291c23271a8873981
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/infosys/api/shipment/events/OrderCreatedEvent.java
|
prashantonline/shipmentservice-1
|
27950182b8509bc98cef2e2291c23271a8873981
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/infosys/api/shipment/events/OrderCreatedEvent.java
|
prashantonline/shipmentservice-1
|
27950182b8509bc98cef2e2291c23271a8873981
|
[
"Apache-2.0"
] | null | null | null | 20.681818 | 65 | 0.679121 | 1,002,357 |
package com.infosys.api.shipment.events;
import java.util.UUID;
public class OrderCreatedEvent {
public OrderCreatedEvent(UUID orderIdentifier, String name) {
this.orderIdentifier = orderIdentifier;
this.name = name;
}
private final UUID orderIdentifier;
private final String name;
public UUID getOrderIdentifier() {
return orderIdentifier;
}
public String getName() {
return name;
}
}
|
9242a6e107c5e5d4bbb761a24fb1f71c078e9084
| 158 |
java
|
Java
|
DesignPatterns/iterator/List.java
|
huoji555/Shadow
|
87335cc689506f13b0420611161573f5261cff7f
|
[
"MIT"
] | 31 |
2019-01-24T05:46:46.000Z
|
2021-11-26T07:41:03.000Z
|
DesignPatterns/iterator/List.java
|
huoji555/Shadow
|
87335cc689506f13b0420611161573f5261cff7f
|
[
"MIT"
] | null | null | null |
DesignPatterns/iterator/List.java
|
huoji555/Shadow
|
87335cc689506f13b0420611161573f5261cff7f
|
[
"MIT"
] | 11 |
2019-04-10T04:12:48.000Z
|
2022-01-06T09:26:43.000Z
| 11.285714 | 30 | 0.658228 | 1,002,358 |
package iterator;
public interface List {
Iterator iterator();
Object get(Integer index);
Integer getSize();
void add(Object object);
}
|
9242a79f809e6eefe49f4c35106db38a3fc39db9
| 4,167 |
java
|
Java
|
app/src/main/java/com/lx/hd/adapter/LogisticsFahuoAdapter.java
|
zyhchinese/huodi_huzhu
|
334ea5ff558b47b81f8b4689bce1311c5c4f068e
|
[
"Apache-2.0"
] | 3 |
2018-10-23T03:54:41.000Z
|
2020-01-03T07:01:52.000Z
|
app/src/main/java/com/lx/hd/adapter/LogisticsFahuoAdapter.java
|
zyhchinese/huodi_huzhu
|
334ea5ff558b47b81f8b4689bce1311c5c4f068e
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/lx/hd/adapter/LogisticsFahuoAdapter.java
|
zyhchinese/huodi_huzhu
|
334ea5ff558b47b81f8b4689bce1311c5c4f068e
|
[
"Apache-2.0"
] | null | null | null | 34.725 | 107 | 0.648188 | 1,002,359 |
package com.lx.hd.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.lx.hd.R;
import com.lx.hd.bean.WuLiuFaHuoEntity;
import com.lx.hd.ui.activity.LogisticsOrderActivity;
import java.util.List;
/**
* Created by Administrator on 2018/1/2.
*/
public class LogisticsFahuoAdapter extends RecyclerView.Adapter<LogisticsFahuoAdapter.ViewHolder> {
private Context context;
private List<WuLiuFaHuoEntity> list;
private int type;
private OnClickItem onClickItem;
public void setOnClickItem(OnClickItem onClickItem) {
this.onClickItem = onClickItem;
}
public LogisticsFahuoAdapter(Context context, List<WuLiuFaHuoEntity> list, int type) {
this.context = context;
this.list = list;
this.type = type;
}
public interface OnClickItem {
void onClick(int position);
}
@Override
public LogisticsFahuoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.act_logistics_fahuo_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final LogisticsFahuoAdapter.ViewHolder holder, int position) {
//-1已取消 0等待接货 1服务开始 2已完成
holder.tv_dingdanhao.setText("订单号:" + list.get(position).getOwner_orderno());
holder.tv_car_type.setText(list.get(position).getCar_type());
holder.tv_money.setText("¥" + list.get(position).getOwner_totalprice());
holder.tv_time.setText(list.get(position).getOwner_createtime());
if (list.get(position).getCust_orderstatus() == -1) {
holder.img_status.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.GONE);
holder.img_status.setImageResource(R.mipmap.img_yiquxiao);
} else if (list.get(position).getCust_orderstatus() == 0) {
holder.img_status.setVisibility(View.GONE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_status.setText("等待接货");
} else if (list.get(position).getCust_orderstatus() == 1) {
holder.img_status.setVisibility(View.GONE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_status.setText("服务开始");
} else {
holder.img_status.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.GONE);
holder.img_status.setImageResource(R.mipmap.img_yiwancheng);
}
holder.img_jiantou.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onClickItem != null) {
onClickItem.onClick(holder.getAdapterPosition());
}
}
});
}
@Override
public int getItemCount() {
int num=0;
if (type == 1) {
if (list.size() > 3) {
num = 3;
} else {
num = list.size();
}
} else {
num = list.size();
}
return num;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView tv_dingdanhao, tv_car_type, tv_money, tv_time, tv_status;
private ImageView img_jiantou, img_status;
public ViewHolder(View itemView) {
super(itemView);
tv_dingdanhao = (TextView) itemView.findViewById(R.id.tv_dingdanhao);
tv_car_type = (TextView) itemView.findViewById(R.id.tv_car_type);
tv_money = (TextView) itemView.findViewById(R.id.tv_money);
tv_time = (TextView) itemView.findViewById(R.id.tv_time);
tv_status = (TextView) itemView.findViewById(R.id.tv_status);
img_jiantou = (ImageView) itemView.findViewById(R.id.img_jiantou);
img_status = (ImageView) itemView.findViewById(R.id.img_status);
}
}
}
|
9242a9a54ab54ac7c5a2da9df513ddc7e1ab9889
| 2,018 |
java
|
Java
|
xchange-examples/src/main/java/com/xeiam/xchange/examples/anx/v2/service/account/BitcoinDepositAddressDemo.java
|
MHarris021/XChange
|
f55aee5a422ee007b530943cd219616c4c3a9726
|
[
"MIT"
] | 1 |
2018-08-01T17:10:09.000Z
|
2018-08-01T17:10:09.000Z
|
xchange-examples/src/main/java/com/xeiam/xchange/examples/anx/v2/service/account/BitcoinDepositAddressDemo.java
|
MHarris021/XChange
|
f55aee5a422ee007b530943cd219616c4c3a9726
|
[
"MIT"
] | null | null | null |
xchange-examples/src/main/java/com/xeiam/xchange/examples/anx/v2/service/account/BitcoinDepositAddressDemo.java
|
MHarris021/XChange
|
f55aee5a422ee007b530943cd219616c4c3a9726
|
[
"MIT"
] | null | null | null | 42.93617 | 89 | 0.757681 | 1,002,360 |
/**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.xeiam.xchange.examples.anx.v2.service.account;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.Currencies;
import com.xeiam.xchange.examples.anx.v2.ANXExamplesUtils;
import com.xeiam.xchange.service.polling.PollingAccountService;
import java.io.IOException;
/**
* Demo requesting account info at ANX
*/
public class BitcoinDepositAddressDemo {
public static void main(String[] args) throws IOException {
Exchange ANX = ANXExamplesUtils.createExchange();
// Interested in the private account functionality (authentication)
PollingAccountService accountService = ANX.getPollingAccountService();
// Request a Bitcoin deposit address
String address = accountService.requestDepositAddress(Currencies.BTC.toString());
System.out.println("Address to deposit Bitcoins to: " + address);
}
}
|
9242a9f3384b4c7b36b41627897f6323a9e9b595
| 843 |
java
|
Java
|
Holding/src/com/holding/mapper/RegionMapper.java
|
wuzongbo/SpringBoot2M_Learn
|
26843e74ac55739ab2f1e77014c534409db0a2d9
|
[
"Apache-2.0"
] | null | null | null |
Holding/src/com/holding/mapper/RegionMapper.java
|
wuzongbo/SpringBoot2M_Learn
|
26843e74ac55739ab2f1e77014c534409db0a2d9
|
[
"Apache-2.0"
] | null | null | null |
Holding/src/com/holding/mapper/RegionMapper.java
|
wuzongbo/SpringBoot2M_Learn
|
26843e74ac55739ab2f1e77014c534409db0a2d9
|
[
"Apache-2.0"
] | null | null | null | 28.1 | 107 | 0.7414 | 1,002,361 |
package com.holding.mapper;
import com.holding.po.Region;
import com.holding.po.RegionExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface RegionMapper {
long countByExample(RegionExample example);
int deleteByExample(RegionExample example);
int deleteByPrimaryKey(Integer id);
int insert(Region record);
int insertSelective(Region record);
List<Region> selectByExample(RegionExample example);
Region selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Region record, @Param("example") RegionExample example);
int updateByExample(@Param("record") Region record, @Param("example") RegionExample example);
int updateByPrimaryKeySelective(Region record);
int updateByPrimaryKey(Region record);
}
|
9242aa1cd3bb0b57f52e4b637aa1da85fd9ef864
| 690 |
java
|
Java
|
src/main/java/com/mxgraph/server/biz/bean/DrawResult.java
|
caomingjie-code/coral-draw
|
8c85e6c6ac6a6c51eebca100f9a9b475c128f248
|
[
"Apache-2.0"
] | 8 |
2020-06-19T16:17:51.000Z
|
2022-03-02T05:28:25.000Z
|
src/main/java/com/mxgraph/server/biz/bean/DrawResult.java
|
caomingjie-code/coral-draw
|
8c85e6c6ac6a6c51eebca100f9a9b475c128f248
|
[
"Apache-2.0"
] | 1 |
2022-01-17T03:25:36.000Z
|
2022-01-17T08:35:31.000Z
|
src/main/java/com/mxgraph/server/biz/bean/DrawResult.java
|
caomingjie-code/coral-draw
|
8c85e6c6ac6a6c51eebca100f9a9b475c128f248
|
[
"Apache-2.0"
] | 9 |
2020-09-07T07:13:22.000Z
|
2021-12-29T00:57:38.000Z
| 14.040816 | 52 | 0.65843 | 1,002,362 |
package com.mxgraph.server.biz.bean;
import java.io.Serializable;
/**
* @Author bootdo [email protected]
*/
public class DrawResult<T> implements Serializable {
private int code;
private String msg;
private T data;
public DrawResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public DrawResult(int code, T data) {
this.code = code;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
9242aa8ad8da85beb6d1ecbe10cba07c8624f33e
| 391 |
java
|
Java
|
nicefish-auth-shiro/src/main/java/com/nicefish/auth/exception/LoginLimitException.java
|
ChenLin12138/nicefish-springboot
|
3d9df498c7419e0bdf92038bf56bf96f1b347124
|
[
"MIT"
] | 10 |
2019-09-28T02:49:44.000Z
|
2021-04-09T13:15:55.000Z
|
nicefish-auth-shiro/src/main/java/com/nicefish/auth/exception/LoginLimitException.java
|
damoqiongqiu/nicefish-spring-boot
|
bc780a52e9e00abf64ff6accd1c5a58cc98f5746
|
[
"MIT"
] | 1 |
2022-03-31T21:35:47.000Z
|
2022-03-31T21:35:47.000Z
|
nicefish-auth-shiro/src/main/java/com/nicefish/auth/exception/LoginLimitException.java
|
ChenLin12138/nicefish-springboot
|
3d9df498c7419e0bdf92038bf56bf96f1b347124
|
[
"MIT"
] | 10 |
2019-08-29T15:54:42.000Z
|
2021-07-15T03:07:35.000Z
| 23 | 80 | 0.741688 | 1,002,363 |
package com.nicefish.auth.exception;
import com.nicefish.core.exception.FishBaseException;
/**
* 用户错误记数异常类
*
* @author 大漠穷秋
*/
public class LoginLimitException extends FishBaseException {
private static final long serialVersionUID = 1L;
public LoginLimitException(int retryLimitCount) {
super("user.password.retry.limit.count", new Object[]{retryLimitCount});
}
}
|
9242ab798faad8ccfc18953475e8052777552444
| 4,545 |
java
|
Java
|
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/datavec/export/StringToDataSetExportFunction.java
|
basedrhys/deeplearning4j
|
4f6a9f8f7df569613ee6ea1b56095c55b147227c
|
[
"Apache-2.0"
] | 2,206 |
2019-06-12T18:57:14.000Z
|
2022-03-29T08:14:27.000Z
|
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/datavec/export/StringToDataSetExportFunction.java
|
basedrhys/deeplearning4j
|
4f6a9f8f7df569613ee6ea1b56095c55b147227c
|
[
"Apache-2.0"
] | 1,685 |
2019-06-12T17:41:33.000Z
|
2022-03-29T21:45:15.000Z
|
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/datavec/export/StringToDataSetExportFunction.java
|
basedrhys/deeplearning4j
|
4f6a9f8f7df569613ee6ea1b56095c55b147227c
|
[
"Apache-2.0"
] | 572 |
2019-06-12T22:13:57.000Z
|
2022-03-31T16:46:46.000Z
| 40.221239 | 155 | 0.684268 | 1,002,364 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.deeplearning4j.spark.datavec.export;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.broadcast.Broadcast;
import org.datavec.api.records.reader.RecordReader;
import org.datavec.api.records.reader.impl.collection.CollectionRecordReader;
import org.datavec.api.split.StringSplit;
import org.datavec.api.writable.Writable;
import org.datavec.spark.util.DefaultHadoopConfig;
import org.datavec.spark.util.SerializableHadoopConfig;
import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator;
import org.deeplearning4j.core.util.UIDProvider;
import org.nd4j.linalg.dataset.DataSet;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StringToDataSetExportFunction implements VoidFunction<Iterator<String>> {
private final Broadcast<SerializableHadoopConfig> conf;
private final URI outputDir;
private final RecordReader recordReader;
private final int batchSize;
private final boolean regression;
private final int labelIndex;
private final int numPossibleLabels;
private String uid = null;
private int outputCount;
public StringToDataSetExportFunction(URI outputDir, RecordReader recordReader, int batchSize, boolean regression,
int labelIndex, int numPossibleLabels) {
this(outputDir, recordReader, batchSize, regression, labelIndex, numPossibleLabels, null);
}
public StringToDataSetExportFunction(URI outputDir, RecordReader recordReader, int batchSize, boolean regression,
int labelIndex, int numPossibleLabels, Broadcast<SerializableHadoopConfig> configuration) {
this.outputDir = outputDir;
this.recordReader = recordReader;
this.batchSize = batchSize;
this.regression = regression;
this.labelIndex = labelIndex;
this.numPossibleLabels = numPossibleLabels;
this.conf = configuration;
}
@Override
public void call(Iterator<String> stringIterator) throws Exception {
String jvmuid = UIDProvider.getJVMUID();
uid = Thread.currentThread().getId() + jvmuid.substring(0, Math.min(8, jvmuid.length()));
List<List<Writable>> list = new ArrayList<>(batchSize);
while (stringIterator.hasNext()) {
String next = stringIterator.next();
recordReader.initialize(new StringSplit(next));
list.add(recordReader.next());
processBatchIfRequired(list, !stringIterator.hasNext());
}
}
private void processBatchIfRequired(List<List<Writable>> list, boolean finalRecord) throws Exception {
if (list.isEmpty())
return;
if (list.size() < batchSize && !finalRecord)
return;
RecordReader rr = new CollectionRecordReader(list);
RecordReaderDataSetIterator iter = new RecordReaderDataSetIterator(rr, null, batchSize, labelIndex, labelIndex, numPossibleLabels, -1, regression);
DataSet ds = iter.next();
String filename = "dataset_" + uid + "_" + (outputCount++) + ".bin";
URI uri = new URI(outputDir.getPath() + "/" + filename);
Configuration c = conf == null ? DefaultHadoopConfig.get() : conf.getValue().getConfiguration();
FileSystem file = FileSystem.get(uri, c);
try (FSDataOutputStream out = file.create(new Path(uri))) {
ds.save(out);
}
list.clear();
}
}
|
9242ac00d37f97691b9dd884748b37107c009c30
| 11,790 |
java
|
Java
|
src/gov/nasa/worldwind/StereoOptionSceneController.java
|
WorldWindEarth/WorldWindJava
|
6ed9d5b27ef4e3ea1aca83cb5d5d03f28a25ceab
|
[
"Apache-2.0",
"MIT"
] | 37 |
2019-04-06T18:23:31.000Z
|
2022-03-31T12:30:58.000Z
|
src/gov/nasa/worldwind/StereoOptionSceneController.java
|
WorldWindEarth/WorldWindJava
|
6ed9d5b27ef4e3ea1aca83cb5d5d03f28a25ceab
|
[
"Apache-2.0",
"MIT"
] | 66 |
2019-04-07T14:50:07.000Z
|
2021-09-08T19:50:46.000Z
|
src/gov/nasa/worldwind/StereoOptionSceneController.java
|
WorldWindEarth/WorldWindJava
|
6ed9d5b27ef4e3ea1aca83cb5d5d03f28a25ceab
|
[
"Apache-2.0",
"MIT"
] | 14 |
2019-04-08T10:34:58.000Z
|
2021-09-07T06:03:22.000Z
| 37.788462 | 120 | 0.653096 | 1,002,365 |
/*
* Copyright 2006-2009, 2017, 2020 United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA World Wind Java (WWJ) platform is 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.
*
* NASA World Wind Java (WWJ) also contains the following 3rd party Open Source
* software:
*
* Jackson Parser – Licensed under Apache 2.0
* GDAL – Licensed under MIT
* JOGL – Licensed under Berkeley Software Distribution (BSD)
* Gluegen – Licensed under Berkeley Software Distribution (BSD)
*
* A complete listing of 3rd Party software notices and licenses included in
* NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party
* notices and licenses PDF found in code directory.
*/
package gov.nasa.worldwind;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.render.DrawContext;
import com.jogamp.opengl.*;
/**
* TODO: This file needs to be updated to implement "correct" stereo, as described at:
* http://www.orthostereo.com/geometryopengl.html
* <p>
* This scene controller draws in stereo, either red-blue anaglyph or device supported if the display device provides
* stereo directly. It can also draw without applying stereo. To select stereo, prior to calling this class' constructor
* set the Java VM property <code>gov.nasa.worldwind.stereo.mode</code> to "device" for device supported stereo (if
* provided by the device) or "redblue" for red-blue anaglyph stereo. If the property is not set or is any other value,
* this class does not draw in stereo.
* <p>
* The {@link WorldWindow} instance must support stereo in order to use device-supported stereo. A stereo
* <code>WorldWindow</code> is selected by specifying the Java VM property described above prior to creating it. See
* {@link gov.nasa.worldwind.awt.WorldWindowGLCanvas} for further details.
* <p>
* Note: The logic and much of the code here was contributed by Xander Enzmann of Mitre Corporation.
*
* @author tag
* @version $Id: StereoOptionSceneController.java 1171 2013-02-11 21:45:02Z dcollins $
*/
public class StereoOptionSceneController extends BasicSceneController implements StereoSceneController
{
/**
* The default focus angle. May be specified in the WorldWind configuration file as the
* <code>gov.nasa.worldwind.StereoFocusAngle</code> property. The default if not specified in the configuration is
* 1.6 degrees.
*/
protected static final double DEFAULT_FOCUS_ANGLE = Configuration.getDoubleValue(AVKey.STEREO_FOCUS_ANGLE, 1.6);
/** The current stereo mode. May not be set to null; use {@link AVKey#STEREO_MODE_NONE} instead. */
protected String stereoMode = AVKey.STEREO_MODE_NONE;
/** The angle between eyes. Larger angles give increased 3D effect. */
protected Angle focusAngle = Angle.fromDegrees(DEFAULT_FOCUS_ANGLE);
/** Indicates whether left and right eye positions are swapped. */
protected boolean swapEyes = false;
/** Indicates the GL drawable capabilities. Non-null only after this scene controller draws once. */
protected GLCapabilitiesImmutable capabilities;
/** Indicates whether hardware device stereo is available. Valid only after this scene controller draws once. */
protected boolean hardwareStereo = false;
/**
* Indicates whether stereo is being applied, either because a stereo device is being used or a stereo mode is in
* effect. This field is included because the question is asked every frame, and tracking the answer via a boolean
* avoids the overhead of more complicated logic that determines the stereo-drawing implementation to call.
*/
protected boolean inStereo = false;
/** Constructs an instance and initializes its stereo mode to */
public StereoOptionSceneController()
{
String stereo = System.getProperty(AVKey.STEREO_MODE);
if ("redblue".equalsIgnoreCase(stereo))
this.setStereoMode(AVKey.STEREO_MODE_RED_BLUE);
else if ("device".equalsIgnoreCase(stereo))
this.setStereoMode(AVKey.STEREO_MODE_DEVICE);
}
public void setStereoMode(String mode)
{
this.stereoMode = mode != null ? mode : AVKey.STEREO_MODE_NONE;
// If device-implemented stereo is used, stereo is considered always in effect no matter what the stereo mode.
this.inStereo = this.isHardwareStereo() || AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode);
}
public String getStereoMode()
{
return this.stereoMode;
}
/**
* {@inheritDoc} The default focus angle is 1.6 degrees.
*
* @param a the left-right eye direction difference. If null, the angle is set to 0.
*/
public void setFocusAngle(Angle a)
{
this.focusAngle = a != null ? a : Angle.ZERO;
}
public Angle getFocusAngle()
{
return this.focusAngle;
}
public void setSwapEyes(boolean swapEyes)
{
this.swapEyes = swapEyes;
}
public boolean isSwapEyes()
{
return this.swapEyes;
}
public boolean isHardwareStereo()
{
return this.hardwareStereo;
}
/**
* {@inheritDoc}
* <p>
* If the display device is providing stereo -- {@link #isHardwareStereo()} is <code>true</code> -- this method
* returns true even if the stereo mode is {@link AVKey#STEREO_MODE_NONE}. In this case, individual stereo images
* are drawn for left and right eyes in order to prevent a blurred scene.
*/
public boolean isInStereo()
{
return this.inStereo;
}
@Override
protected void draw(DrawContext dc)
{
// Capture the capabilities actually in use.
if (this.capabilities == null)
{
this.capabilities = dc.getGLContext().getGLDrawable().getChosenGLCapabilities();
this.hardwareStereo = this.capabilities.getStereo();
this.inStereo = this.isHardwareStereo() ? true : this.isInStereo();
}
// If stereo isn't to be applied, just draw and return.
if (!isInStereo())
{
super.draw(dc);
return;
}
// Check if pitch is in correct range (50 - 90 degrees) for current stereo implementation to
// work correctly (temporary hack)
View dcView = dc.getView();
Boolean pitchInRange = (dcView.getPitch().compareTo(Angle.fromDegrees(50)) > 0
&& dcView.getPitch().compareTo(Angle.POS90) < 0);
if (AVKey.STEREO_MODE_DEVICE.equals(this.stereoMode) && this.isHardwareStereo() && pitchInRange)
this.doDrawToStereoDevice(dc);
else if (AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode) && pitchInRange)
this.doDrawStereoRedBlue(dc);
else // AVKey.STEREO_MODE_NONE
this.doDrawStereoNone(dc);
}
/**
* Implement no stereo ("Mono") while using a stereo device.
* <p>
* Note that this method draws the image twice, once to each of the left and right eye buffers, even when stereo is
* not in effect. This is to prevent the stereo device from drawing blurred scenes.
*
* @param dc the current draw context.
*/
protected void doDrawStereoNone(DrawContext dc)
{
// If running on a stereo device but want to draw a normal image, both buffers must be filled or the
// display will be blurry.
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
gl.glDrawBuffer(GL2.GL_BACK_LEFT);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
gl.glDrawBuffer(GL2.GL_BACK_RIGHT);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
}
/**
* Implement stereo using the red-blue anaglyph technique.
*
* @param dc the current draw context.
*/
protected void doDrawStereoRedBlue(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
View dcView = dc.getView();
// Draw the left eye
if (this.isSwapEyes())
{
if (this.isHardwareStereo())
gl.glDrawBuffer(GL2.GL_BACK_RIGHT);
gl.glColorMask(false, true, true, true); // right eye in green/blue
}
else
{
if (this.isHardwareStereo())
gl.glDrawBuffer(GL2.GL_BACK_LEFT);
gl.glColorMask(true, false, false, true); // left eye in red only
}
if (this.isHardwareStereo())
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
// Move the view to the right eye
Angle viewHeading = dcView.getHeading();
dcView.setHeading(dcView.getHeading().subtract(this.getFocusAngle()));
dcView.apply(dc);
// Draw the right eye frame green and blue only
try
{
gl.glClear(GL.GL_DEPTH_BUFFER_BIT);
if (this.isSwapEyes())
{
if (this.isHardwareStereo())
gl.glDrawBuffer(GL2.GL_BACK_RIGHT);
gl.glColorMask(true, false, false, true); // right eye in red only
}
else
{
if (this.isHardwareStereo())
gl.glDrawBuffer(GL2.GL_BACK_LEFT);
gl.glColorMask(false, true, true, true); // right eye in green/blue
}
if (this.isHardwareStereo())
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
}
finally
{
// Restore the original view heading
dcView.setHeading(viewHeading);
dcView.apply(dc);
gl.glColorMask(true, true, true, true);
}
}
/**
* Implement stereo using the stereo-enabled graphics device. The mode has an effect only if the display device
* implements stereo.
*
* @param dc the current draw context.
*/
protected void doDrawToStereoDevice(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
View dcView = dc.getView();
// Draw the left eye
if (this.isSwapEyes())
gl.glDrawBuffer(GL2.GL_BACK_RIGHT);
else
gl.glDrawBuffer(GL2.GL_BACK_LEFT);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
// Move the view to the right eye
Angle viewHeading = dcView.getHeading();
dcView.setHeading(dcView.getHeading().subtract(this.getFocusAngle()));
dcView.apply(dc);
// Draw the right eye
try
{
if (this.isSwapEyes())
gl.glDrawBuffer(GL2.GL_BACK_LEFT);
else
gl.glDrawBuffer(GL2.GL_BACK_RIGHT);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
super.draw(dc);
}
finally
{
// Restore the original view heading
dcView.setHeading(viewHeading);
dcView.apply(dc);
}
}
}
|
9242ac7140d9cfa2a833d1a6832d02b7b4390907
| 2,469 |
java
|
Java
|
aliyun-java-sdk-nas/src/main/java/com/aliyuncs/nas/model/v20170626/ListRecentlyRecycledDirectoriesResponse.java
|
carldea/aliyun-openapi-java-sdk
|
2d7c54d31cfb41af85a3f110c85f1b28ea1edf47
|
[
"Apache-2.0"
] | 1 |
2022-02-12T06:01:36.000Z
|
2022-02-12T06:01:36.000Z
|
aliyun-java-sdk-nas/src/main/java/com/aliyuncs/nas/model/v20170626/ListRecentlyRecycledDirectoriesResponse.java
|
carldea/aliyun-openapi-java-sdk
|
2d7c54d31cfb41af85a3f110c85f1b28ea1edf47
|
[
"Apache-2.0"
] | 27 |
2021-06-11T21:08:40.000Z
|
2022-03-11T21:25:09.000Z
|
aliyun-java-sdk-nas/src/main/java/com/aliyuncs/nas/model/v20170626/ListRecentlyRecycledDirectoriesResponse.java
|
carldea/aliyun-openapi-java-sdk
|
2d7c54d31cfb41af85a3f110c85f1b28ea1edf47
|
[
"Apache-2.0"
] | 1 |
2020-03-05T07:30:16.000Z
|
2020-03-05T07:30:16.000Z
| 22.243243 | 96 | 0.717699 | 1,002,366 |
/*
* 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.aliyuncs.nas.model.v20170626;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.nas.transform.v20170626.ListRecentlyRecycledDirectoriesResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class ListRecentlyRecycledDirectoriesResponse extends AcsResponse {
private String requestId;
private String nextToken;
private List<Entry> entries;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getNextToken() {
return this.nextToken;
}
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
public List<Entry> getEntries() {
return this.entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public static class Entry {
private String fileId;
private String path;
private String name;
private String lastDeleteTime;
public String getFileId() {
return this.fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getLastDeleteTime() {
return this.lastDeleteTime;
}
public void setLastDeleteTime(String lastDeleteTime) {
this.lastDeleteTime = lastDeleteTime;
}
}
@Override
public ListRecentlyRecycledDirectoriesResponse getInstance(UnmarshallerContext context) {
return ListRecentlyRecycledDirectoriesResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
9242ad739e283fe6807a6e8b08ef95bb624e81b6
| 6,397 |
java
|
Java
|
djobi-core/src/main/java/io/datatok/djobi/engine/stage/Stage.java
|
datatok/djobi
|
9f2a611b37218801b0084b6d18fb1fa9a84f85d8
|
[
"Apache-2.0"
] | null | null | null |
djobi-core/src/main/java/io/datatok/djobi/engine/stage/Stage.java
|
datatok/djobi
|
9f2a611b37218801b0084b6d18fb1fa9a84f85d8
|
[
"Apache-2.0"
] | 3 |
2022-01-20T08:59:00.000Z
|
2022-02-13T18:38:30.000Z
|
djobi-core/src/main/java/io/datatok/djobi/engine/stage/Stage.java
|
datatok/djobi
|
9f2a611b37218801b0084b6d18fb1fa9a84f85d8
|
[
"Apache-2.0"
] | null | null | null | 20.769481 | 94 | 0.601063 | 1,002,367 |
package io.datatok.djobi.engine.stage;
import io.datatok.djobi.engine.Job;
import io.datatok.djobi.engine.check.CheckResult;
import io.datatok.djobi.engine.enums.ExecutionStatus;
import io.datatok.djobi.engine.phases.StagePhaseMetaData;
import io.datatok.djobi.engine.stage.livecycle.ActionConfiguration;
import io.datatok.djobi.executors.Executor;
import io.datatok.djobi.plugins.logging.StageLog;
import io.datatok.djobi.utils.Bag;
import io.datatok.djobi.utils.Dumpable;
import io.datatok.djobi.utils.MyMapUtils;
import io.datatok.djobi.utils.Timeline;
import io.datatok.djobi.utils.interfaces.Labelized;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Stage implements Dumpable, Labelized {
final protected StageLog log;
final private Map<String, Object> metrics = new HashMap<>();
private Job job;
private String name;
private String kind;
private Boolean enabled = true;
private Boolean allowFailure = false;
private Bag spec;
private String condition;
/**
* @since v3.16.0
*/
private final List<StagePhaseMetaData> phases = new ArrayList<>();
/**
* @since v3.1.0
*/
private Boolean preCheckEnabled = true;
/**
* @since v3.1.0
*/
private Boolean postCheckEnabled = true;
/**
* @since v3.1.0
*/
private CheckResult preCheck = CheckResult.todo();
/**
* @since v3.1.0
*/
private CheckResult postCheck = CheckResult.todo();
/**
* @since v2.2.1
*/
private ExecutionStatus executionStatus = ExecutionStatus.NO;
/**
* @since v2.2.8
*/
private ActionConfiguration parameters;
/**
* Measure stage duration.
*
* @since v3.5.0
*/
final private Timeline timeline = new Timeline();
/**
* Hold labels for reporting/filtering.
*
* @since v5.0.0
*/
public Map<String, String> labels;
public Stage() {
this.log = new StageLog();
}
public Stage(final Bag config) {
this();
this.spec = config;
}
public String getUid() {
return this.getJob().getUid() + "-stage" + this.getJob().getStages().indexOf(this);
}
public String getName() {
return name;
}
public Stage setName(String name) {
this.name = name;
return this;
}
public String getKind() {
return kind;
}
public Stage setKind(String kind) {
this.kind = kind;
return this;
}
public Bag getSpec() {
return spec;
}
public Stage setSpec(Bag spec) {
this.spec = spec;
return this;
}
public Boolean getEnabled() {
return enabled;
}
public Stage setEnabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
public Boolean getAllowFailure() {
return allowFailure;
}
public Stage setAllowFailure(Boolean allowFailure) {
this.allowFailure = allowFailure;
return this;
}
public Job getJob() {
return job;
}
public Stage setJob(Job job) {
this.job = job;
return this;
}
public CheckResult getPreCheck() {
return preCheck;
}
public Stage setPreCheck(CheckResult preCheck) {
this.preCheck = preCheck;
return this;
}
public CheckResult getPostCheck() {
return postCheck;
}
public Stage setPostCheck(CheckResult postCheck) {
this.postCheck = postCheck;
return this;
}
public Boolean getPreCheckEnabled() {
return preCheckEnabled;
}
public Stage setPreCheckEnabled(Boolean preCheckEnabled) {
this.preCheckEnabled = preCheckEnabled;
return this;
}
public Boolean getPostCheckEnabled() {
return postCheckEnabled;
}
public Stage setPostCheckEnabled(Boolean postCheckEnabled) {
this.postCheckEnabled = postCheckEnabled;
return this;
}
public StageLog getLog() {
return log;
}
public ExecutionStatus getExecutionStatus() {
return executionStatus;
}
public Stage putMetric(final String key, final Object value) {
this.metrics.put(key, value);
return this;
}
public Map<String, Object> getMetrics() {
return metrics;
}
public ActionConfiguration getParameters() {
return parameters;
}
public Stage setParameters(ActionConfiguration parameters) {
this.parameters = parameters;
return this;
}
public Executor getExecutor() {
return job == null ? null : job.getExecutor();
}
public Timeline getTimeline() {
return timeline;
}
public Stage start() {
this.executionStatus = ExecutionStatus.IN_PROGRESS;
this.timeline.start();
return this;
}
public Stage end(boolean success) {
this.executionStatus = success ? ExecutionStatus.DONE_OK : ExecutionStatus.DONE_ERROR;
this.timeline.end();
return this;
}
public String getCondition() {
return condition;
}
public Stage setCondition(String condition) {
this.condition = condition;
return this;
}
public List<StagePhaseMetaData> getPhases() {
return phases;
}
public Stage addPhase(StagePhaseMetaData item) {
this.phases.add(item);
return this;
}
/**
* @since v5.0.0
*
* @return labels
*/
public Map<String, String> getLabels() {
return labels;
}
public String getLabel(String key)
{
return labels.get(key);
}
/**
* @since v5.0.0
*
* @param labels labels
* @return this
*/
public Stage setLabels(Map<String, String> labels) {
this.labels = labels;
return this;
}
@Override
public Map<String, Object> toHash() {
return MyMapUtils.map(
"name", name,
"kind", kind,
"allow_failure", allowFailure,
"enabled", enabled,
"config", spec
);
}
public Map<String, Object> toLog() {
return MyMapUtils.map(
"name", name,
"kind", kind,
"allow_failure", allowFailure
);
}
}
|
9242adb02d22addf69ff138639f6c59fce9697da
| 15,555 |
java
|
Java
|
src/main/java/ru/hiddenproject/progressive/basic/BasicDIContainer.java
|
CrissNamon/text-engine
|
6d2ef3b480de8d0e3288bfc7da3f1f65b28aae82
|
[
"Apache-2.0"
] | 3 |
2021-09-30T00:30:03.000Z
|
2021-11-20T20:46:02.000Z
|
src/main/java/ru/hiddenproject/progressive/basic/BasicDIContainer.java
|
CrissNamon/progressive
|
6d2ef3b480de8d0e3288bfc7da3f1f65b28aae82
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/hiddenproject/progressive/basic/BasicDIContainer.java
|
CrissNamon/progressive
|
6d2ef3b480de8d0e3288bfc7da3f1f65b28aae82
|
[
"Apache-2.0"
] | null | null | null | 35.432802 | 97 | 0.665381 | 1,002,368 |
package ru.hiddenproject.progressive.basic;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import ru.hiddenproject.progressive.annotation.ComponentScan;
import ru.hiddenproject.progressive.annotation.Components;
import ru.hiddenproject.progressive.annotation.Configuration;
import ru.hiddenproject.progressive.annotation.GameBean;
import ru.hiddenproject.progressive.basic.injection.*;
import ru.hiddenproject.progressive.basic.util.BasicComponentCreator;
import ru.hiddenproject.progressive.exception.*;
import ru.hiddenproject.progressive.injection.*;
import ru.hiddenproject.progressive.util.ComponentAnnotationProcessor;
/**
* Basic DI container implementation.
*/
public final class BasicDIContainer implements DIContainer {
private final String variant;
private final Map<BeanKey, Bean> beans;
private final Set<Method> viewedMethods;
private final GameBeanFactory gameBeanFactory;
public BasicDIContainer() {
BasicComponentManager.getGameLogger().info("Progressive DI initialization...\n");
beans = new ConcurrentHashMap<>();
viewedMethods = Collections.synchronizedSet(new HashSet<>());
gameBeanFactory = new BasicGameBeanFactory();
variant = GameBean.DEFAULT_VARIANT;
}
/**
* Basic constructor.
*
* @param variant Variant to be used in bean creation.
* See {@link ru.hiddenproject.progressive.annotation.GameBean}
* for more information.
*/
public BasicDIContainer(String variant) {
BasicComponentManager.getGameLogger().info("Progressive DI initialization of "
+ variant
+ " variant"
+ "...\n");
beans = new ConcurrentHashMap<>();
viewedMethods = Collections.synchronizedSet(new HashSet<>());
gameBeanFactory = new BasicGameBeanFactory();
this.variant = variant;
}
@Override
public String getVariant() {
return variant;
}
@Override
public synchronized void init() {
PackageLoader packageLoader = new SimplePackageLoader();
PackageScanner packageScanner = new SimplePackageScanner();
init(packageLoader, packageScanner);
}
@Override
public synchronized void init(PackageLoader packageLoader, PackageScanner packageScanner) {
Package[] packages = packageLoader.loadAllPackages();
for (Package p : packages) {
scanPackage(p.getName(), packageScanner);
}
for (BeanKey key : beans.keySet()) {
if (!key.getType().isInterface()) {
createBeanFromClass(key.getType());
}
}
}
@Override
public synchronized void scanPackage(String name, PackageScanner loader) {
Set<Class<?>> classesInPackage = loader.findAllClassesIn(name);
Set<Class<?>> beans = classesInPackage.stream().parallel()
.unordered()
.filter(c -> c.isAnnotationPresent(Configuration.class))
.collect(Collectors.toSet());
for (Class<?> bean : beans) {
loadConfiguration(bean, loader);
}
beans = classesInPackage.stream().parallel().unordered()
.filter(c -> ComponentAnnotationProcessor.isAnnotationPresent(GameBean.class, c))
.collect(Collectors.toSet());
for (Class<?> bean : beans) {
createBeanMetaInformation(bean);
}
}
@Override
public synchronized void loadBean(Class<?> beanClass) {
createBeanMetaInformation(beanClass);
loadBeanFrom(beanClass);
}
@Override
public <V> V getBean(Class<V> beanClass) {
Set<BeanKey> beansOfClass = beans.keySet().stream().parallel().unordered()
.filter(k -> k.getType() == beanClass)
.collect(Collectors.toSet());
if (beansOfClass.size() == 0) {
throw new BeanNotFoundException("There is no beans for "
+ beanClass.getName() + " were found!", beanClass);
}
if (beansOfClass.size() > 1) {
beansOfClass.forEach(k -> System.out.println(k.toString()));
throw new BeanConflictException("There are more than one beans of " + beanClass.getName()
+ " found! What to inject?");
}
BeanKey beanKey = beansOfClass.stream()
.parallel()
.unordered()
.findFirst().orElse(new BeanKey("", null));
Bean beanEntry = beans.get(beanKey);
if (beanEntry == null) {
throw new BeanNotFoundException("There is no beans for "
+ beanClass.getName() + " were found!", beanClass);
}
return getBean(beanKey.getName(), beanClass);
}
@Override
public <V> V getBean(String name, Class<V> beanClass) {
BeanKey beanKey = new BeanKey(name, beanClass);
Bean bean = beans.getOrDefault(beanKey, null);
if (bean == null) {
throw new BeanNotFoundException("GameBean called " + name
+ " for class " + beanClass.getName() + " not found!", beanClass, name);
}
if (!bean.isReady()) {
throw new BeanCircularDependencyException("GameBean "
+ name + " of class "
+ beanClass.getName()
+ " is not ready! Is there a circular dependency?", beanClass);
}
if (!bean.haveObject() && !bean.isCreated() && bean.isClass()) {
BasicComponentManager
.getGameLogger()
.info("GameBean "
+ name
+ " of type "
+ beanClass.getName()
+ " has not been created yet. Creating..");
createBeanFromClass(bean.getRealType());
}
V exists = (V) bean.getBean();
if (exists == null && bean.getCreationPolicy() == GameBeanCreationPolicy.SINGLETON) {
throw new BeanNotFoundException("GameBean called " + name
+ " for class " + beanClass.getName() + " not found!", beanClass, name);
}
if (bean.getCreationPolicy() == GameBeanCreationPolicy.OBJECT) {
exists = (V) updateObjectTypeBean(bean);
bean.setBean(exists);
updateRealTypeInterfaces(name, bean.getRealType(), bean);
}
return exists;
}
@Override
public synchronized <V> Optional<V> searchBean(Class<V> beanClass) {
try {
return Optional.of(
getBean(beanClass)
);
} catch (RuntimeException e) {
return Optional.empty();
}
}
@Override
public synchronized <V> Optional<V> searchBean(String name, Class<V> beanClass) {
try {
return Optional.of(
getBean(name, beanClass)
);
} catch (RuntimeException e) {
return Optional.empty();
}
}
@Override
public synchronized void loadConfiguration(Class<?> configClass)
throws BeanUndefinedException {
loadConfiguration(configClass, new SimplePackageScanner());
}
@Override
public void loadConfiguration(Class<?> config, PackageScanner scanner)
throws BeanUndefinedException {
Method[] methods = config.getDeclaredMethods();
Arrays.asList(methods).removeIf(m -> !m.isAnnotationPresent(GameBean.class));
Arrays.sort(methods, Comparator.comparingInt(Method::getParameterCount));
Arrays.sort(methods, Comparator.comparingInt(m -> m.getAnnotation(GameBean.class).order()));
Object configObj = BasicComponentCreator.create(config);
for (Method method : methods) {
if (viewedMethods.contains(method)) {
continue;
}
if (method.isAnnotationPresent(GameBean.class)) {
try {
createBeanFromMethod(method, configObj);
} catch (Throwable t) {
throw new BeanUndefinedException(t.getMessage(), t);
}
}
}
if (config.isAnnotationPresent(Components.class)) {
Components components = config.getAnnotation(Components.class);
Class<?>[] componentsClasses = components.value();
for (Class<?> componentClass : componentsClasses) {
createBeanMetaInformation(componentClass);
}
}
if (config.isAnnotationPresent(ComponentScan.class)) {
ComponentScan componentScan = config.getAnnotation(ComponentScan.class);
String[] packages = componentScan.value();
scanPackages(packages, scanner);
}
}
private synchronized void createBeanMetaInformation(Class<?> beanClass) {
GameBean gameBean = ComponentAnnotationProcessor.findAnnotation(beanClass, GameBean.class);
if (gameBean == null) {
throw new AnnotationException("Tried to create bean from "
+ beanClass
+ ", but it has no @GameBean annotation. Bean needs it, actually...");
}
String beanVariant = gameBean.variant();
if (!beanVariant.equals(variant) && !beanVariant.equals(GameBean.GLOBAL_VARIANT)) {
return;
}
Bean information = gameBeanFactory.createBeanMetaInformationFromClass(beanClass);
String beanName = gameBean.name();
if (beanName.isEmpty()) {
beanName = beanClass.getSimpleName().toLowerCase();
}
saveBeanMetaInformation(beanName, information);
}
private void saveBeanMetaInformation(String name, Bean metaInformation) {
BeanKey beanKey = new BeanKey(name, metaInformation.getRealType());
if (beans.containsKey(beanKey)) {
throw new BeanDuplicationException("GameBean name duplication ("
+ name + ") for "
+ metaInformation.getRealType().getName());
}
beans.put(beanKey, metaInformation);
Class<?>[] interfaces = metaInformation.getRealType().getInterfaces();
for (Class<?> interfaceClass : interfaces) {
beanKey = new BeanKey(name, interfaceClass);
if (beans.containsKey(beanKey)) {
throw new BeanDuplicationException("GameBean name duplication ("
+ name + ") for " + interfaceClass.getName());
}
beans.put(beanKey, metaInformation);
}
}
private synchronized void loadBeanFrom(Class<?> beanClass) {
viewedMethods.clear();
GameBean annotation = ComponentAnnotationProcessor
.findAnnotation(beanClass, GameBean.class);
if (annotation != null) {
createBeanFromClass(beanClass);
} else {
throw new AnnotationException("Tried to create bean from "
+ beanClass
+ ", but it has no @GameBean annotation. Bean needs it, actually...");
}
}
private void markBeanAsCreated(String name, Class<?> beanClass) {
BeanKey beanKey = new BeanKey(name, beanClass);
Bean beanData = beans.get(beanKey);
if (beanData == null) {
return;
}
beanData.setCreated(true);
updateRealTypeInterfaces(name, beanClass, beanData);
}
private void setBeanReadyStatus(String name, Class<?> beanClass, boolean status) {
BeanKey beanKey = new BeanKey(name, beanClass);
Bean beanData = beans.get(beanKey);
if (beanData == null) {
return;
}
beanData.setReady(status);
updateRealTypeInterfaces(name, beanClass, beanData);
}
private void updateRealTypeInterfaces(String name, Class<?> beanClass, Bean beanData) {
Class<?>[] interfaces = beanClass.getInterfaces();
BeanKey beanKey = new BeanKey(name, beanClass);
beans.putIfAbsent(beanKey, beanData);
for (Class<?> inter : interfaces) {
beanKey = new BeanKey(name, inter);
beans.putIfAbsent(beanKey, beanData);
}
}
private void updateBeanObject(String name, Class<?> beanClass, Object bean) {
BeanKey beanKey = new BeanKey(name, beanClass);
Bean beanData = beans.get(beanKey);
if (beanData == null) {
return;
}
beanData.setBean(bean);
updateRealTypeInterfaces(name, beanClass, beanData);
}
private void createBeanFromClass(Class<?> beanClass) {
GameBean annotation = ComponentAnnotationProcessor.findAnnotation(beanClass, GameBean.class);
if (annotation == null) {
return;
}
String beanVariant = annotation.variant();
if (!beanVariant.equals(variant) && !beanVariant.equals(GameBean.GLOBAL_VARIANT)) {
return;
}
BasicComponentManager
.getGameLogger().info("Found @GameBean annotation in "
+ beanClass.getName() + ". Trying to make bean...");
String name = annotation.name();
if (name.isEmpty()) {
name = beanClass.getSimpleName().toLowerCase();
}
setBeanReadyStatus(name, beanClass, false);
Object bean = BasicComponentCreator.create(beanClass);
updateBeanObject(name, beanClass, bean);
setBeanReadyStatus(name, beanClass, true);
markBeanAsCreated(name, beanClass);
BasicComponentManager
.getGameLogger().info("GameBean with name "
+ name + " created for " + beanClass.getName());
BasicComponentManager
.getGameLogger().log("", "");
}
private void createBeanFromMethod(Method m, Object o) {
if (viewedMethods.contains(m)) {
return;
}
m.setAccessible(true);
if (m.getReturnType() != Void.TYPE) {
GameBean annotation = m.getAnnotation(GameBean.class);
String beanVariant = annotation.variant();
if (!beanVariant.equals(variant) && !beanVariant.equals(GameBean.GLOBAL_VARIANT)) {
return;
}
BasicComponentManager
.getGameLogger().info("Found GameBean annotation in " + o.getClass().getName()
+ " in method " + m.getName()
+ ". Trying to make bean...");
String name = annotation.name();
if (name.isEmpty()) {
name = m.getName().toLowerCase();
}
if (checkIfBeanExists(name, m.getReturnType())) {
throw new BeanDuplicationException("GameBean name duplication "
+ name + " in " + o.getClass().getName());
}
Bean beanData = invoke(m, o);
viewedMethods.add(m);
beanData.setCreationPolicy(annotation.policy());
beanData.setMethod(m);
beanData.setMethodCaller(o);
beanData.setRealType(beanData.getBean().getClass());
updateRealTypeInterfaces(name, beanData.getRealType(), beanData);
BasicComponentManager
.getGameLogger().info("GameBean with name " + name + " created for "
+ beanData.getBean().getClass().getName() + " from method " + m.getName());
BasicComponentManager
.getGameLogger().log("", "");
}
}
private boolean checkIfBeanExists(String name, Class<?> beanClass) {
BeanKey beanKey = new BeanKey(name, beanClass);
Bean bean = beans.get(beanKey);
if (bean == null) {
return false;
}
Class<?>[] interfaces = beanClass.getInterfaces();
for (Class<?> inter : interfaces) {
checkIfBeanExists(name, inter);
}
return true;
}
private Bean invoke(Method m, Object obj) throws ArrayIndexOutOfBoundsException {
GameBean annotation = m.getAnnotation(GameBean.class);
Object[] args = BasicComponentCreator
.injectBeansToParameters(
m.getReturnType(), m.getParameterTypes(), m.getParameterAnnotations()
);
Object methodResult = BasicComponentCreator.invoke(m, obj, args);
Bean beanData = new Bean();
beanData.setBean(methodResult);
beanData.setCreationPolicy(annotation.policy());
beanData.setMethod(m);
beanData.setMethodArgs(args);
viewedMethods.add(m);
return beanData;
}
private Object updateObjectTypeBean(Bean bean) {
if (!bean.isClass()) {
bean.setMethodArgs(
BasicComponentCreator.injectBeansToParameters(
bean.getRealType(),
bean.getMethod().getParameterTypes(),
bean.getMethod().getParameterAnnotations()
)
);
return BasicComponentCreator
.invoke(bean.getMethod(), bean.getMethodCaller(), bean.getMethodArgs());
} else {
return BasicComponentCreator.create(bean.getRealType());
}
}
private void scanPackages(String[] packages, PackageScanner loader) {
for (String p : packages) {
scanPackage(p, loader);
}
}
}
|
9242adba81dd456ebe0fccad8c10273113b77888
| 5,931 |
java
|
Java
|
app/src/test/java/hotelproject/controllers/db/UserDBTest.java
|
mdeboute/hotel
|
78a843e264446f4132c04a34f423a2be69d1078f
|
[
"Unlicense"
] | null | null | null |
app/src/test/java/hotelproject/controllers/db/UserDBTest.java
|
mdeboute/hotel
|
78a843e264446f4132c04a34f423a2be69d1078f
|
[
"Unlicense"
] | null | null | null |
app/src/test/java/hotelproject/controllers/db/UserDBTest.java
|
mdeboute/hotel
|
78a843e264446f4132c04a34f423a2be69d1078f
|
[
"Unlicense"
] | null | null | null | 34.086207 | 130 | 0.604957 | 1,002,369 |
package hotelproject.controllers.db;
import hotelproject.controllers.objects.User;
import hotelproject.controllers.utils.PasswordAuth;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class UserDBTest {
private final String u_name_admin = "IsAdmin";
private final String u_name_staff = "IsStaff";
private final DatabaseManager dbm = new DatabaseManager();
private final User userIsAdmin = new User(u_name_admin, "admin123", 1);
private final User userIsStaff = new User(u_name_staff, "staff123", 0);
private final PasswordAuth passwordAuth = new PasswordAuth();
/**
* This user already exists in the database and the result should be true.
*/
@Test
public void test_001_IsUserExist() {
try {
assertTrue(dbm.udb.userExists(new User("admin", "root", 1)));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* These two user objects should be added in the users table of database. The result should be true.
*/
@Test
public void test_002_addUser() {
dbm.udb.addUser(userIsAdmin);
dbm.udb.addUser(userIsStaff);
try {
assertTrue(dbm.udb.userExists(userIsAdmin));
assertTrue(dbm.udb.userExists(userIsStaff));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* The user 'userIsStaff' should return '0'.
* The user 'userIsAdmin' should return '1'.
*/
@Test
public void test_003_GetU_is_admin() {
try {
int isAdmin = dbm.udb.getU_is_admin(userIsAdmin);
int isStaff = dbm.udb.getU_is_admin(userIsStaff);
Assert.assertEquals(isAdmin, 1);
Assert.assertEquals(isStaff, 0);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* All four users should be obtained from the database. The result should return true.
*/
@Test
public void test_004_GetAllUsers() {
List<User> allUsersForTest = new ArrayList<>();
allUsersForTest.add(new User("admin", "root", 1));
allUsersForTest.add(new User("rstaff", "rstaff", 0));
allUsersForTest.add(new User("IsAdmin", "admin123", 1));
allUsersForTest.add(new User("IsStaff", "staff123", 0));
List<User> allUserInDatabase;
int count = 0;
allUserInDatabase = dbm.udb.getAllUsers();
for (User userInDatabase : allUserInDatabase) {
for (User userForTest : allUsersForTest) {
if (userInDatabase.getU_name().equals(userForTest.getU_name()) &&
passwordAuth.authenticate(userForTest.getU_password(), userInDatabase.getU_password()) &&
userInDatabase.getU_is_admin() == userForTest.getU_is_admin()) {
count++;
}
}
}
Assert.assertEquals(count, 4);
}
/**
* The user object's attributes should be updated accordingly and should return true.
*/
@Test
public void test_005_UpdateUserInformation() {
boolean isUpdate = false;
try {
String old_username = userIsAdmin.getU_name();
userIsAdmin.setU_name("userIsBoss");
userIsAdmin.setU_password("boss123");
dbm.udb.updateUserInformation(userIsAdmin, old_username);
List<User> users = dbm.udb.getAllUsers();
for (User user : users) {
isUpdate = user.getU_name().equals("userIsBoss") &&
passwordAuth.authenticate("boss123", user.getU_password());
}
assertTrue(isUpdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* The user object's attributes should be updated accordingly and should return true.
*/
@Test
public void test_006_UpdateUserInformation2() {
boolean isUpdate = false;
String old_username = userIsStaff.getU_name();
userIsStaff.setU_name("userIsWorker");
try {
dbm.udb.updateUserInformation(userIsStaff, old_username);
List<User> users = dbm.udb.getAllUsers();
for (User user : users) {
isUpdate = user.getU_name().equals("userIsWorker") && passwordAuth.authenticate("staff123", user.getU_password());
}
assertTrue(isUpdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* The user 'userIsWorker' should be found and deleted in the database. The result should return true.
*/
@Test
public void test_007_DeleteUser() {
boolean isDeleted = true;
User userForDelete = new User("userIsWorker", "staff123", 0);
dbm.udb.deleteUser(userForDelete);
List<User> allUsersInDatabase = dbm.udb.getAllUsers();
for (User user : allUsersInDatabase) {
if (user.getU_name().equals("userIsWorker")) {
isDeleted = false;
break;
}
}
assertTrue(isDeleted);
}
/**
* The user 'userIsBoss' should be found and deleted in the database. The result should return true.
*/
@Test
public void test_008_DeleteUser2() {
boolean isDeleted = true;
dbm.udb.deleteUser(new User("userIsBoss", "boss123", 1));
List<User> allUsersInDatabase = dbm.udb.getAllUsers();
for (User user : allUsersInDatabase) {
if (user.getU_name().equals("userIsBoss")) {
isDeleted = false;
break;
}
}
assertTrue(isDeleted);
}
}
|
9242ae117fe02faa88cf3d72edcb96df0f433fb5
| 1,258 |
java
|
Java
|
src/poof-textui/src/poof/textui/main/Open.java
|
rodamber/oop
|
3ebdbd64bad611fa2c630bd99c7b4777b1a33188
|
[
"Unlicense"
] | null | null | null |
src/poof-textui/src/poof/textui/main/Open.java
|
rodamber/oop
|
3ebdbd64bad611fa2c630bd99c7b4777b1a33188
|
[
"Unlicense"
] | null | null | null |
src/poof-textui/src/poof/textui/main/Open.java
|
rodamber/oop
|
3ebdbd64bad611fa2c630bd99c7b4777b1a33188
|
[
"Unlicense"
] | null | null | null | 26.765957 | 128 | 0.63275 | 1,002,370 |
/** @version $Id: Open.java,v 1.13 2014/12/02 01:42:22 ist178942 Exp $ */
package poof.textui.main;
import static ist.po.ui.Dialog.IO;
import ist.po.ui.Command;
import ist.po.ui.DialogException;
import ist.po.ui.ValidityPredicate;
import java.io.FileNotFoundException;
import java.io.IOException;
import poof.FileManager;
/**
* Open existing file.
*/
public class Open extends Command<FileManager> {
/**
* @param fileManager
* the command receiver.
*/
public Open(FileManager fileManager) {
super(MenuEntry.OPEN, fileManager);
}
/** @see ist.po.ui.Command#execute() */
@Override
public final void execute() throws DialogException, IOException {
if (_receiver.getFileSystem() != null && _receiver.fileSystemWasChanged() && IO.readBoolean(Message.saveBeforeExit())) {
Save save = new Save(_receiver);
save.execute();
}
String filename = IO.readString(Message.openFile());
try {
_receiver.openFileSystem(filename);
}
catch (FileNotFoundException fnfe) {
IO.println(Message.fileNotFound());
}
catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
}
|
9242ae21e89e9b2efb492bbc69a24d6a08fbd4a8
| 3,810 |
java
|
Java
|
pia/phyutility/src/org/virion/jam/console/ConsoleFrame.java
|
MartinGuehmann/PIA2
|
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
|
[
"MIT"
] | null | null | null |
pia/phyutility/src/org/virion/jam/console/ConsoleFrame.java
|
MartinGuehmann/PIA2
|
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
|
[
"MIT"
] | null | null | null |
pia/phyutility/src/org/virion/jam/console/ConsoleFrame.java
|
MartinGuehmann/PIA2
|
d7af357f3f66ba45d7de50bd6701ef3a5ffd974e
|
[
"MIT"
] | 2 |
2019-07-06T12:43:53.000Z
|
2020-03-02T18:31:44.000Z
| 24.267516 | 95 | 0.682415 | 1,002,371 |
/**
* ConsoleFrame.java
*/
package org.virion.jam.console;
import org.virion.jam.framework.Application;
import org.virion.jam.framework.DocumentFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
public class ConsoleFrame extends DocumentFrame {
PipedInputStream piOut;
PipedInputStream piErr;
PipedOutputStream poOut;
PipedOutputStream poErr;
JTextArea textArea = new JTextArea();
public ConsoleFrame() throws IOException {
super();
// Set up System.out
piOut = new PipedInputStream();
poOut = new PipedOutputStream(piOut);
System.setOut(new PrintStream(poOut, true));
// Set up System.err
piErr = new PipedInputStream();
poErr = new PipedOutputStream(piErr);
System.setErr(new PrintStream(poErr, true));
textArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE ||
(e.getKeyCode() == KeyEvent.VK_C && e.isControlDown()) ||
(e.getKeyCode() == KeyEvent.VK_PERIOD && e.isMetaDown())) {
escapePressed();
}
}
});
}
protected void initializeComponents() {
// Add a scrolling text area
textArea.setEditable(false);
textArea.setRows( 25 );
textArea.setColumns( 80 );
textArea.setEditable(false);
textArea.setFont(new java.awt.Font("Monospaced", 0, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
getContentPane().add(scrollPane, BorderLayout.CENTER);
pack();
setVisible(true);
// Create reader threads
new ReaderThread(piOut).start();
new ReaderThread(piErr).start();
}
protected boolean readFromFile(File file) throws FileNotFoundException, IOException {
throw new RuntimeException("Cannot read file");
}
protected boolean writeToFile(File file) throws IOException {
textArea.write(new FileWriter(file));
return true;
}
public JComponent getExportableComponent() {
return textArea;
}
protected void escapePressed() {
int option = JOptionPane.showConfirmDialog(this, "Are you sure you wish to stop?",
"Stop",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.OK_OPTION) {
((ConsoleApplication)Application.getApplication()).doStop();
}
}
public void doCopy() {
textArea.copy();
}
public void doSelectAll() {
textArea.selectAll();
}
class ReaderThread extends Thread {
PipedInputStream pi;
ReaderThread(PipedInputStream pi) {
this.pi = pi;
}
public void run() {
try {
while (true) {
try {
Thread.sleep(100);
} catch(InterruptedException ie) {}
String input = "";
do {
int available = pi.available();
if (available == 0) break;
byte b[]=new byte[available];
pi.read(b);
input = input + new String(b);
} while( !input.endsWith("\n") && !input.endsWith("\r\n") );
if (input.length() > 0) {
SwingUtilities.invokeLater(new WriteText(input));
}
}
} catch (IOException e) {
}
}
class WriteText implements Runnable {
String text;
WriteText(String text) {
this.text = text;
}
public void run() {
textArea.append(text);
// Make sure the last line is always visible
textArea.setCaretPosition(textArea.getDocument().getLength());
// Keep the text area down to a certain character size
int idealSize = 128000;
int maxExcess = 16000 ;
int excess = textArea.getDocument().getLength() - idealSize;
if (excess >= maxExcess) {
textArea.replaceRange("", 0, excess);
}
setDirty();
}
};
}
}
|
9242aff43ce33aa18883896c6b6716a256c4a648
| 3,560 |
java
|
Java
|
src/main/java/ru/alesandrus/service/AdvertisementWatcher.java
|
Alesandrus/av-parser
|
c7cb0920ad43a5e83c67bfd65e69bae7189888a6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/alesandrus/service/AdvertisementWatcher.java
|
Alesandrus/av-parser
|
c7cb0920ad43a5e83c67bfd65e69bae7189888a6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/alesandrus/service/AdvertisementWatcher.java
|
Alesandrus/av-parser
|
c7cb0920ad43a5e83c67bfd65e69bae7189888a6
|
[
"Apache-2.0"
] | null | null | null | 36.701031 | 137 | 0.698596 | 1,002,372 |
package ru.alesandrus.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import ru.alesandrus.models.AdOwner;
import ru.alesandrus.models.Advertisement;
import ru.alesandrus.models.enumerations.OwnerType;
import ru.alesandrus.repositories.AdOwnerRepository;
import ru.alesandrus.utils.DateUtils;
import java.io.File;
import java.util.*;
/**
* @author Alexander Ivanov
* @version 1.0
* @since 13.01.2019
*/
@Component
public class AdvertisementWatcher {
private static final Logger LOGGER = LoggerFactory.getLogger(AdvertisementWatcher.class);
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private CompanyAdvertisementParser companyAdvertisementParser;
private MarketAdvertisementParser marketAdvertisementParser;
private ExcelCreator excelCreator;
private AdvertisementSender advertisementSender;
private AdOwnerRepository adOwnerRepository;
private AdChecker adChecker;
@Autowired
public void setCompanyAdvertisementParser(CompanyAdvertisementParser companyAdvertisementParser) {
this.companyAdvertisementParser = companyAdvertisementParser;
}
@Autowired
public void setMarketAdvertisementParser(MarketAdvertisementParser marketAdvertisementParser) {
this.marketAdvertisementParser = marketAdvertisementParser;
}
@Autowired
public void setAdvertisementSender(AdvertisementSender advertisementSender) {
this.advertisementSender = advertisementSender;
}
@Autowired
public void setExcelCreator(ExcelCreator excelCreator) {
this.excelCreator = excelCreator;
}
@Autowired
public void setAdOwnerRepository(AdOwnerRepository adOwnerRepository) {
this.adOwnerRepository = adOwnerRepository;
}
@Autowired
public void setAdChecker(AdChecker adChecker) {
this.adChecker = adChecker;
}
@Scheduled(cron = "0 0 8-22 * * *")
// @Scheduled(fixedRate = 300000)
public void watchAds() {
LOGGER.info("Start scan ads");
Iterable<AdOwner> adOwners = adOwnerRepository.findAll();
Map<AdOwner, List<Advertisement>> adsForSending = new TreeMap<>();
for (AdOwner adOwner : adOwners) {
List<Advertisement> updatedAds = new ArrayList<>();
if (adOwner.isActive()) {
List<Advertisement> ads;
if (adOwner.getOwnerType() == OwnerType.COMPANY) {
ads = companyAdvertisementParser.parsePageAndGetAds(adOwner);
} else {
ads = marketAdvertisementParser.parsePageAndGetAds(adOwner);
}
updatedAds = adChecker.checkAds(ads);
}
if (!updatedAds.isEmpty()) {
Collections.sort(updatedAds);
adsForSending.put(adOwner, updatedAds);
}
}
if (!adsForSending.isEmpty()) {
String creationTime = DateUtils.getCurrentTime();
String pathToTemp = String.format("%s%sreport_%s.xls", System.getProperty(JAVA_IO_TMPDIR), File.separatorChar, creationTime);
excelCreator.createReport(adsForSending, pathToTemp);
LOGGER.info("Report was created");
advertisementSender.sendReport(pathToTemp, creationTime);
LOGGER.info("Email was sent");
}
LOGGER.info("Scanning ads was finished");
}
}
|
9242b023c17de9c8495aee660599618f45dd58e8
| 1,688 |
java
|
Java
|
Paging/src/Driver.java
|
brusseau25/Winter_2016
|
cf083d0100b8e2872c777fb4a7ba38f3951d755a
|
[
"MIT"
] | null | null | null |
Paging/src/Driver.java
|
brusseau25/Winter_2016
|
cf083d0100b8e2872c777fb4a7ba38f3951d755a
|
[
"MIT"
] | null | null | null |
Paging/src/Driver.java
|
brusseau25/Winter_2016
|
cf083d0100b8e2872c777fb4a7ba38f3951d755a
|
[
"MIT"
] | null | null | null | 24.463768 | 110 | 0.634479 | 1,002,373 |
/*
* Brandon Russeau
* COSC 423
* Virtual Memory Page Replacement Project
* Driver class
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = null;
ArrayList<Integer> referenceString;
int frames;
try {
scan = new Scanner(new File("pages.dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scan.hasNextLine()) {
referenceString = new ArrayList<Integer>();
System.out.print("Number of Frames: ");
frames = scan.nextInt();
System.out.println(frames);
int tmp;
while (scan.hasNextLine()) {
tmp = scan.nextInt();
if (tmp != -1) {
referenceString.add(tmp);
} else {
break;
}
}
FIFO p = new FIFO(referenceString, frames);
p.fifoAlgo();
LRU q = new LRU(referenceString, frames);
q.lruAlgo();
// LFU r = new LFU(referenceString, frames);
// r.lfuAlgo();
Optimal s = new Optimal(referenceString, frames);
s.optimalAlgo();
System.out.println("Scheme Faults %Optimal");
System.out.printf("FIFO %5d %10.1f%%\n", p.getFaults(), ((double) p.getFaults() / s.getFaults()) * 100);
System.out.printf("LRU %6d %10.1f%%\n", q.getFaults(), ((double) q.getFaults() / s.getFaults()) * 100);
// System.out.printf("LFU %6d %10.1f%%\n", r.getFaults(), ((double)
// r.getFaults() / s.getFaults()) * 100);
System.out.printf("Optimal %1d %11.1f%%\n", s.getFaults(), ((double) s.getFaults() / s.getFaults()) * 100);
System.out.println();
}
}
}
|
9242b0937fe080bd0f670178089f91230aa02988
| 270 |
java
|
Java
|
monet/src/main/java/monet/ViewDimensions.java
|
tadfisher/monet
|
c40ffec132adcf393fe19664125d813a372aaff6
|
[
"Apache-2.0"
] | null | null | null |
monet/src/main/java/monet/ViewDimensions.java
|
tadfisher/monet
|
c40ffec132adcf393fe19664125d813a372aaff6
|
[
"Apache-2.0"
] | null | null | null |
monet/src/main/java/monet/ViewDimensions.java
|
tadfisher/monet
|
c40ffec132adcf393fe19664125d813a372aaff6
|
[
"Apache-2.0"
] | null | null | null | 18 | 55 | 0.744444 | 1,002,374 |
package monet;
import com.google.auto.value.AutoValue;
@AutoValue abstract class ViewDimensions {
static ViewDimensions create(int width, int height) {
return new AutoValue_ViewDimensions(width, height);
}
abstract int width();
abstract int height();
}
|
9242b094c3fdea38aea4baabcbf2e85f3d50f810
| 9,044 |
java
|
Java
|
src/main/java/frc/robot/MyRobot.java
|
Programmer3314/2021Code
|
a9b2ea084779f98d5ee6b2b6094e6432a8b54468
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/frc/robot/MyRobot.java
|
Programmer3314/2021Code
|
a9b2ea084779f98d5ee6b2b6094e6432a8b54468
|
[
"BSD-3-Clause"
] | 5 |
2021-10-31T04:42:48.000Z
|
2021-11-01T23:44:44.000Z
|
src/main/java/frc/robot/MyRobot.java
|
Programmer3314/2021Code
|
a9b2ea084779f98d5ee6b2b6094e6432a8b54468
|
[
"BSD-3-Clause"
] | null | null | null | 38.649573 | 111 | 0.665966 | 1,002,375 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot;
import com.kauailabs.navx.frc.AHRS;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.SPI;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public abstract class MyRobot extends AllRobots {
IDriveTrain drivetrain;
public static Shooter shooter;
TalonFXTest fxTest;
public static DriveController driveController;
ControlPanel controlPanel;
public static UltraSonicSensor uSSensor;
AnalogInput IRSensor;
AnalogInput AInput;
DigitalInput DInput;
public static AHRS navx;
public static PowerDistributionPanel pdp = new PowerDistributionPanel(0);
public static double rawGyro, cleanGyro, ultraSonicDistance;
public boolean isFalcon, hasShooter, hasControlPanel, isTalonFXTest;
// Sprak Max CAN IDs NEO
final int CANMcleftDriveFront = 1;
final int CANMcleftDriveMiddle = 2;
final int CANMcleftDriveBack = 3;
final int CANMcrightDriveFront = 4;
final int CANMcrightDriveMiddle = 5;
final int CANMcrightDriveBack = 6;
final int CANMcshooterLeft = 7;
final int CANMcshooterRight = 8;
// Talon FX CAN IDs Falcons
final int CANMcFalconFrontLeft = 1;
final int CANMcFalconBackLeft = 2;
final int CANMcFalconFrontRight = 3;
final int CANMcFalconBackRight = 4;
// Talon SRX CAN IDs Bag Motors
final int CANMcctrlPanel = 31;
final int CANMcBallQueuing = 12;
final int CANMcHood = 9;
final int CANMcIndexer = 11;
final int CANMcIntake = 10;
public int counter = 0;
@Override
public void MyRobotInit() {
SmartDashboard.putNumber("Target Offset", Constants.targettingOffset);
navx = new AHRS(SPI.Port.kMXP);
navx.reset();
String ControllerVersion = "";
try {
CANSparkMax controllerCheck = new CANSparkMax(5, MotorType.kBrushless);
SmartDashboard.putString("Controller Check 1", "Passed");
ControllerVersion = controllerCheck.getFirmwareString();
SmartDashboard.putString("Controller Check 4", ControllerVersion);
controllerCheck.close();
} catch (Exception cc) {
SmartDashboard.putString("Controller Check 3", "CATCH");
}
if (ControllerVersion.equalsIgnoreCase("v0.0.0")) {
isFalcon = true;
hasShooter = true;
isTalonFXTest = false;
hasControlPanel = false;
} else {
isFalcon = false;
hasShooter = true;
isTalonFXTest = true;
hasControlPanel = false;
}
if (isFalcon) {
SmartDashboard.putString("DriveTrain Type", "Falcons");
Constants.drivetrainTrackingMaxCorrection = Constants.falconTrackingMaxCorrection;
Constants.drivetrainTrackingMinCorrection = Constants.falconTrackingMinCorrection;
Constants.encoderTicksToFeet = Constants.falconEncoderTicksToFeet;
Constants.maxRPM = Constants.falconMaxRPM;
Constants.drivetrainKP = Constants.falconDrivetrainKP;
Constants.drivetrainKI = Constants.falconDrivetrainKI;
Constants.drivetrainKD = Constants.falconDrivetrainKD;
Constants.drivetrainKIz = Constants.falconDrivetrainKIz;
Constants.drivetrainKFF = Constants.falconDrivetrainKFF;
Constants.drivetrainKMaxOutput = Constants.falconDrivetrainKMaxOutput;
Constants.drivetrainKMinOutput = Constants.falconDrivetrainKMinOutput;
drivetrain = new DrivetrainFalcon(CANMcFalconFrontLeft, CANMcFalconBackLeft, CANMcFalconFrontRight,
CANMcFalconBackRight);
} else {
SmartDashboard.putString("DriveTrain Type", "Neos");
Constants.drivetrainTrackingMaxCorrection = Constants.neoMaxTrackingCorrection;
Constants.drivetrainTrackingMinCorrection = Constants.neoTrackingMinCorrection;
Constants.encoderTicksToFeet = Constants.neoEncoderTicksToFeet;
Constants.maxRPM = Constants.neoMaxRPM;
Constants.drivetrainKP = Constants.neoDrivetrainKP;
Constants.drivetrainKI = Constants.neoDrivetrainKI;
Constants.drivetrainKD = Constants.neoDrivetrainKD;
Constants.drivetrainKIz = Constants.neoDrivetrainKIz;
Constants.drivetrainKFF = Constants.neoDrivetrainKFF;
Constants.drivetrainKMaxOutput = Constants.neoDrivetrainKMaxOutput;
Constants.drivetrainKMinOutput = Constants.neoDrivetrainKMinOutput;
drivetrain = new DrivetrainNEO(CANMcleftDriveFront, CANMcleftDriveMiddle, CANMcleftDriveBack,
CANMcrightDriveFront, CANMcrightDriveMiddle, CANMcrightDriveBack);
}
IRSensor = new AnalogInput(3);
DInput = new DigitalInput(1);
AInput = new AnalogInput(0);
uSSensor = new UltraSonicSensor(Constants.USSensorMB1013ToInchFactor);
RechargeRobotInit();
}
@Override
public void MyAutonomousInit() {
navx.reset();
RechargeAutonomousInit();
}
@Override
public void MyAutonomousPeriodic() {
periodicInit();
RechargeAutonomousPeriodic();
}
@Override
public void MyTeleopInit() {
navx.reset();
RechargeTeleopInit();
}
@Override
public void MyTeleopPeriodic() {
periodicInit();
// SmartDashboard.putBoolean("useFixedSpeed", shooter.useFixedSpeed);
RechargeTeleopPeriodic();
}
@Override
public void MyTestInit() {
navx.reset();
RechargeTestInit();
}
@Override
public void MyTestPeriodic() {
periodicInit();
RechargeTestPeriodic();
}
private void periodicInit() {
boolean IRSensorValue;
if (IRSensor.getValue() > 3500) {
IRSensorValue = false;
} else {
IRSensorValue = true;
}
if(!HumanInput.KILLALLGYROS){
rawGyro = navx.getAngle();
} else {
rawGyro = 0;
}
cleanGyro = (rawGyro + 180 * Math.signum(rawGyro)) % 360 - 180 * Math.signum(rawGyro);
ultraSonicDistance = uSSensor.getDistance();
SmartDashboard.putNumber("Gyro Value", Robot.cleanGyro);
SmartDashboard.putNumber("Ultra Sonic Distance in Inches", ultraSonicDistance);
SmartDashboard.putNumber("Center of Robot to Wall", uSSensor.getDistanceFromWall2());
SmartDashboard.putBoolean("IR Sensor is Blocked", IRSensorValue);
SmartDashboard.putNumber("IR Sensor Value", IRSensor.getValue());
// SmartDashboard.putNumber("Counter for Rich", counter++);
SmartDashboard.putBoolean("New IR Sensor is Blocked", SensorInput.queuedShooter);
SmartDashboard.putBoolean("Digital Input Test", DInput.get());
SmartDashboard.putNumber("Analog Input Test", AInput.getValue());
SmartDashboard.putBoolean("Track 1 Sensor", SensorInput.queuedTrack1);
SmartDashboard.putBoolean("Track 2 Sensor", SensorInput.queuedTrack2);
SmartDashboard.putBoolean("Shooter Sensor", SensorInput.queuedShooter);
SmartDashboard.putBoolean("Hood Sensor", SensorInput.queuedHood);
SmartDashboard.putBoolean("Intake Sensor", SensorInput.queuedIntake);
SmartDashboard.putNumber("Operator POV Degrees", HumanInput.operatorController.getPOV());
SmartDashboard.putNumber("Left Motor 1 Current", pdp.getCurrent(2));
SmartDashboard.putNumber("Left Motor 2 Current", pdp.getCurrent(3));
SmartDashboard.putNumber("Right Motor 1 Current", pdp.getCurrent(14));
SmartDashboard.putNumber("Right Motor 2 Current", pdp.getCurrent(15));
}
@Override
public void MyDisabledInit() {
RechargeDisabledInit();
}
@Override
public void MyDisabledPeriodic() {
RechargeDisabledPeriodic();
}
public abstract void RechargeRobotInit();
public abstract void RechargeAutonomousInit();
public abstract void RechargeAutonomousPeriodic();
public abstract void RechargeTeleopInit();
public abstract void RechargeTeleopPeriodic();
public abstract void RechargeTestInit();
public abstract void RechargeTestPeriodic();
public abstract void RechargeDisabledInit();
public abstract void RechargeDisabledPeriodic();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.