hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
e2b08315b252f771ddbd93eabdeac6d5b1c9dc78
| 2,246
|
/*
* (C) Copyright IBM Corp. 2019,2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.ta.sdk.spi.recommendation;
import java.util.List;
/**
* TODO Separate into Issue and IssueSolution and allow multiples for the same Issue
* TODO allow IssueSolution to be Target specific
* TODO add Issue.getIssueDetail method that returns markdown describing exactly the problem found
*/
public interface Issue {
String getId();
/**
* Title should be written in a manner that tells the user what they need to do at a glance.
*
* For RED severity issues, it should be written like
* Fire detected. Use the Dry Powder fire extinguisher.
*
* For YELLOW severity issues it should be written like
* Smoke detected. Please check in the kitchen to see if you need to replace the dishwasher.
*
* For GREEN severity issues it should be written like
* Smell detected. Consider giving the utility a clean.
*
* @return the title of the issue
*/
String getTitle();
IssueCategory getCategory();
/**
* Note: currently this field is used as the title in the UI. It should use title instead.
* and this field should be used for the longer detail.
*
* TODO return markdown instead of plain text
*
* @return the solution test of the issue
*/
List<String> getSolutionText();
/**
* For GREEN severity issues, Cost should be zero as it does not need to count as part of the modernization effort
* A Cost can be provided however in case
*
* Cost = OverheadCost + (OccurenceCost x # occurences)
*
* @return cost (in Days)
*/
Float getCost();
/**
* Cost if at least one occurence of the issue is found
*
* @return overheadCost (in Days)
*/
Float getOverheadCost();
/**
* Cost to be added for each occurence found (including the first one)
*
* @return occurenceCost (in Days)
*/
Float getOccurrenceCost();
/**
* @see Severity
*
* @return the severity of the issue
*/
Severity getSeverity();
ComplexityContribution getComplexityContribution();
void setComplexityContribution(ComplexityContribution complexityContribution);
Occurrence getOccurrence();
Integer getOccurrencesCount();
}
| 25.816092
| 116
| 0.691006
|
806d56930d962c05ef5b1af8143612848db48acf
| 2,919
|
package com.fincatto.documentofiscal.cte300.classes.nota;
import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.DFStringValidador;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
/**
* @author Caio
* @info Informações das Ferrovias Envolvidas
*/
@Root(name = "ferroEnv")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeNotaInfoCTeNormalInfoModalFerroviarioTrafegoMutuoFerroviasEnvolvidas extends DFBase {
private static final long serialVersionUID = -7408236804856205178L;
@Element(name = "CNPJ")
private String cnpj;
@Element(name = "cInt", required = false)
private String codigoInterno;
@Element(name = "IE", required = false)
private String inscricaoEstadual;
@Element(name = "xNome")
private String razaoSocial;
@Element(name = "enderFerro")
private CTeNotaEnderecoFerrovia endereco;
public CTeNotaInfoCTeNormalInfoModalFerroviarioTrafegoMutuoFerroviasEnvolvidas() {
this.cnpj = null;
this.codigoInterno = null;
this.inscricaoEstadual = null;
this.razaoSocial = null;
this.endereco = null;
}
public String getCnpj() {
return this.cnpj;
}
/**
* Número do CNPJ<br>
* Informar o CNPJ da Ferrovia Envolvida. Caso a Ferrovia envolvida não seja inscrita no CNPJ o campo deverá preenchido com zeros. Informar os zeros não significativos.
*/
public void setCnpj(final String cnpj) {
DFStringValidador.cnpj(cnpj);
this.cnpj = cnpj;
}
public String getCodigoInterno() {
return this.codigoInterno;
}
/**
* Código interno da Ferrovia envolvida<br>
* Uso da transportadora
*/
public void setCodigoInterno(final String codigoInterno) {
DFStringValidador.tamanho10(codigoInterno, "Código interno da Ferrovia envolvida");
this.codigoInterno = codigoInterno;
}
public String getInscricaoEstadual() {
return this.inscricaoEstadual;
}
/**
* Inscrição Estadual
*/
public void setInscricaoEstadual(final String inscricaoEstadual) {
DFStringValidador.inscricaoEstadual(inscricaoEstadual);
this.inscricaoEstadual = inscricaoEstadual;
}
public String getRazaoSocial() {
return this.razaoSocial;
}
/**
* Razão Social ou Nome
*/
public void setRazaoSocial(final String razaoSocial) {
DFStringValidador.tamanho2ate60(razaoSocial, "Razão Social ou Nome");
this.razaoSocial = razaoSocial;
}
public CTeNotaEnderecoFerrovia getEndereco() {
return this.endereco;
}
/**
* Dados do endereço da ferrovia envolvida
*/
public void setEndereco(final CTeNotaEnderecoFerrovia endereco) {
this.endereco = endereco;
}
}
| 28.339806
| 172
| 0.690305
|
4884fb0cb5ee02dd234fd6fbfd32989a3a62282c
| 9,398
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.games.model;
/**
* This is a JSON template for room leave diagnostics.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Play Game Services API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class RoomLeaveDiagnostics extends com.google.api.client.json.GenericJson {
/**
* Android network subtype.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getSubtype()
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer androidNetworkSubtype;
/**
* Android network type.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getType()
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer androidNetworkType;
/**
* iOS network type as defined in Reachability.h.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer iosNetworkType;
/**
* Uniquely identifies the type of this resource. Value is always the fixed string
* games#roomLeaveDiagnostics.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The MCC+MNC code for the client's network connection. On Android: http://developer.android.com/
* reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see: https://dev
* eloper.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Ref
* erence.html
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String networkOperatorCode;
/**
* The name of the carrier of the client's network connection. On Android: http://developer.androi
* d.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS: https:
* //developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Referenc
* e/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String networkOperatorName;
/**
* Diagnostics about all peer sessions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PeerSessionDiagnostics> peerSession;
static {
// hack to force ProGuard to consider PeerSessionDiagnostics used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(PeerSessionDiagnostics.class);
}
/**
* Whether or not sockets were used.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean socketsUsed;
/**
* Android network subtype.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getSubtype()
* @return value or {@code null} for none
*/
public java.lang.Integer getAndroidNetworkSubtype() {
return androidNetworkSubtype;
}
/**
* Android network subtype.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getSubtype()
* @param androidNetworkSubtype androidNetworkSubtype or {@code null} for none
*/
public RoomLeaveDiagnostics setAndroidNetworkSubtype(java.lang.Integer androidNetworkSubtype) {
this.androidNetworkSubtype = androidNetworkSubtype;
return this;
}
/**
* Android network type.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getType()
* @return value or {@code null} for none
*/
public java.lang.Integer getAndroidNetworkType() {
return androidNetworkType;
}
/**
* Android network type.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getType()
* @param androidNetworkType androidNetworkType or {@code null} for none
*/
public RoomLeaveDiagnostics setAndroidNetworkType(java.lang.Integer androidNetworkType) {
this.androidNetworkType = androidNetworkType;
return this;
}
/**
* iOS network type as defined in Reachability.h.
* @return value or {@code null} for none
*/
public java.lang.Integer getIosNetworkType() {
return iosNetworkType;
}
/**
* iOS network type as defined in Reachability.h.
* @param iosNetworkType iosNetworkType or {@code null} for none
*/
public RoomLeaveDiagnostics setIosNetworkType(java.lang.Integer iosNetworkType) {
this.iosNetworkType = iosNetworkType;
return this;
}
/**
* Uniquely identifies the type of this resource. Value is always the fixed string
* games#roomLeaveDiagnostics.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* Uniquely identifies the type of this resource. Value is always the fixed string
* games#roomLeaveDiagnostics.
* @param kind kind or {@code null} for none
*/
public RoomLeaveDiagnostics setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The MCC+MNC code for the client's network connection. On Android: http://developer.android.com/
* reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see: https://dev
* eloper.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Ref
* erence.html
* @return value or {@code null} for none
*/
public java.lang.String getNetworkOperatorCode() {
return networkOperatorCode;
}
/**
* The MCC+MNC code for the client's network connection. On Android: http://developer.android.com/
* reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see: https://dev
* eloper.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Ref
* erence.html
* @param networkOperatorCode networkOperatorCode or {@code null} for none
*/
public RoomLeaveDiagnostics setNetworkOperatorCode(java.lang.String networkOperatorCode) {
this.networkOperatorCode = networkOperatorCode;
return this;
}
/**
* The name of the carrier of the client's network connection. On Android: http://developer.androi
* d.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS: https:
* //developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Referenc
* e/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
* @return value or {@code null} for none
*/
public java.lang.String getNetworkOperatorName() {
return networkOperatorName;
}
/**
* The name of the carrier of the client's network connection. On Android: http://developer.androi
* d.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS: https:
* //developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Referenc
* e/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
* @param networkOperatorName networkOperatorName or {@code null} for none
*/
public RoomLeaveDiagnostics setNetworkOperatorName(java.lang.String networkOperatorName) {
this.networkOperatorName = networkOperatorName;
return this;
}
/**
* Diagnostics about all peer sessions.
* @return value or {@code null} for none
*/
public java.util.List<PeerSessionDiagnostics> getPeerSession() {
return peerSession;
}
/**
* Diagnostics about all peer sessions.
* @param peerSession peerSession or {@code null} for none
*/
public RoomLeaveDiagnostics setPeerSession(java.util.List<PeerSessionDiagnostics> peerSession) {
this.peerSession = peerSession;
return this;
}
/**
* Whether or not sockets were used.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSocketsUsed() {
return socketsUsed;
}
/**
* Whether or not sockets were used.
* @param socketsUsed socketsUsed or {@code null} for none
*/
public RoomLeaveDiagnostics setSocketsUsed(java.lang.Boolean socketsUsed) {
this.socketsUsed = socketsUsed;
return this;
}
@Override
public RoomLeaveDiagnostics set(String fieldName, Object value) {
return (RoomLeaveDiagnostics) super.set(fieldName, value);
}
@Override
public RoomLeaveDiagnostics clone() {
return (RoomLeaveDiagnostics) super.clone();
}
}
| 34.936803
| 182
| 0.728134
|
9ffed44ad700f95f9bb4fc80cdb195979a9209e2
| 10,870
|
/**
* vertigo - application development platform
*
* Copyright (C) 2013-2022, Vertigo.io, team@vertigo.io
*
* 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.vertigo.stella.plugins.work.rest.master;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.vertigo.commons.codec.CodecManager;
import io.vertigo.core.lang.Assertion;
import io.vertigo.core.lang.WrappedException;
import io.vertigo.stella.impl.master.WorkResult;
import io.vertigo.stella.impl.work.WorkItem;
/**
* WorkQueue distribuée - partie serveur en REST.
* @author npiedeloup
*/
final class RestQueueServer {
//pas besoin de synchronized la map, car le obtain est le seul accès et est synchronized
private final Map<String, BlockingQueue<WaitingWorkInfos>> workQueueMap = new HashMap<>();
private static final Logger LOG = LogManager.getLogger(RestQueueServer.class);
//On conserve l'état des work en cours, afin de pouvoir les relancer si besoin (avec un autre uuid)
private final ConcurrentMap<String, RunningWorkInfos> runningWorkInfosMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, NodeState> knownNodes = new ConcurrentHashMap<>();
private final CodecManager codecManager;
private final BlockingQueue<WorkResult> resultQueue = new LinkedBlockingQueue<>();
private final int deadWorkTypeTimeoutSec;
private final long nodeTimeOutSec;
private final int pullTimeoutSec;
/**
* Constructeur.
* @param nodeTimeOutSec Timeout (secondes) avant de considérer un noeud comme mort
* @param codecManager Manager de codec
* @param pullTimeoutSec Timeout (secondes) utilisé lors des long pull
* @param daemonManager Daemons manager
*/
public RestQueueServer(final int nodeTimeOutSec, final CodecManager codecManager, final int pullTimeoutSec) {
Assertion.check().isNotNull(codecManager);
//-----
this.nodeTimeOutSec = nodeTimeOutSec;
this.pullTimeoutSec = pullTimeoutSec;
deadWorkTypeTimeoutSec = 60; //by convention : dead workType timeout after 60s
this.codecManager = codecManager;
}
/**
* Vérifie les noeuds morts, et si oui remets les workItems dans la pile.
*/
void checkDeadNodes() {
final Set<String> deadNodes = new HashSet<>();
//Comme défini dans le contrat de la ConcurrentMap : l'iterator est weakly consistent : et ne lance pas de ConcurrentModificationException
for (final NodeState nodeState : knownNodes.values()) {
//sans signe de vie depuis deadNodeTimeout, on considère le noeud comme mort
if (!isActiveNode(nodeState)) {
deadNodes.add(nodeState.getNodeUID());
}
}
if (!deadNodes.isEmpty()) {
LOG.warn("Stopped nodes detected : {}", deadNodes);
for (final RunningWorkInfos runningWorkInfos : runningWorkInfosMap.values()) {
if (deadNodes.contains(runningWorkInfos.getNodeUID())) {
putWorkItem(runningWorkInfos.getWorkItem());
}
}
}
}
/**
* Vérifie les WorkItems sur des workTypes inactifs
*/
void checkDeadWorkItems() {
for (final String workType : new ArrayList<>(workQueueMap.keySet())) {
BlockingQueue<WaitingWorkInfos> workItemQueue;
try {
workItemQueue = obtainWorkQueue(workType);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
if (!workItemQueue.isEmpty() && !isActiveWorkType(workType)) {
//Comme défini dans le contrat de la BlockingQueue : l'iterator est weakly consistent : et ne lance pas de ConcurrentModificationException
for (final Iterator<WaitingWorkInfos> it = workItemQueue.iterator(); it.hasNext();) {
final WaitingWorkInfos waitingWorkInfos = it.next();
if (waitingWorkInfos.getWaitingAge() > deadWorkTypeTimeoutSec * 1000) {
it.remove();
LOG.info("waiting timeout ({})", waitingWorkInfos.getWorkItem().getId());
resultQueue.add(new WorkResult(waitingWorkInfos.getWorkItem().getId(), null, new IOException(
"Timeout workId " + waitingWorkInfos.getWorkItem().getId() + " after " + deadWorkTypeTimeoutSec + "s : No active node for this workType (" + workType + ")")));
}
}
}
}
}
private boolean isActiveNode(final NodeState nodeState) {
return System.currentTimeMillis() - nodeState.getLastSeenTime() < nodeTimeOutSec * 1000;
}
private boolean isActiveWorkType(final String workType) {
for (final NodeState nodeState : knownNodes.values()) {
if (isActiveNode(nodeState) && nodeState.isWorkTypeSupported(workType)) {
return true;
}
}
return false;
}
/**
* Signalement de vie d'un node, avec le type de work qu'il annonce.
* Le type de work annoncé, vient compléter les précédents.
* @param nodeUID UID du node
* @param nodeWorkType Type de work traité
*/
private void touchNode(final String nodeUID, final String nodeWorkType) {
final NodeState nodeState = knownNodes.putIfAbsent(nodeUID, new NodeState(nodeUID, nodeWorkType));
if (nodeState != null) {
nodeState.touch(nodeWorkType);
}
}
/**
* Get a work todo. returned as Json.
* @param workType Type of work
* @param nodeId client node id
* @return Work as json array : [workItemId, base64WorkItem]
*/
String[] pollWork(final String workType, final String nodeId) {
//-----
touchNode(nodeId, workType);
final WorkItem workItem = pollWorkItem(workType, pullTimeoutSec);
final String[] sendPack;
if (workItem != null) {
runningWorkInfosMap.put(workItem.getId(), new RunningWorkInfos(workItem, nodeId));
final byte[] serializedWorkItem = codecManager.getCompressedSerializationCodec().encode((Serializable) workItem.getWork());
final String base64WorkItem = codecManager.getBase64Codec().encode(serializedWorkItem);
sendPack = new String[] { workItem.getId(), base64WorkItem };
LOG.info("pollWork({},{}) : 1 Work", workType, nodeId);
} else {
sendPack = new String[] {}; //vide si pas de tache en attente
LOG.info("pollWork({},{}) : no Work", workType, nodeId);
}
return sendPack;
}
/**
* Signal the start of the work.
* @param workId work id
*/
void onStart(final String workId) {
LOG.info("onStart({})", workId);
}
/**
* Signal the end of the work.
* @param success if success
* @param workId work id
* @param base64Result result base64 encoded
*/
void onDone(final boolean success, final String workId, final String base64Result) {
LOG.info("onDone {} : ({})", success, workId);
//-----
final RunningWorkInfos runningWorkInfos = runningWorkInfosMap.remove(workId);
Assertion.check().isNotNull(runningWorkInfos, "Ce travail ({0}) n''est pas connu, ou n''est plus en cours.", workId);
final byte[] serializedResult = codecManager.getBase64Codec().decode(base64Result);
final Object value = codecManager.getCompressedSerializationCodec().decode(serializedResult);
final Object result = success ? value : null;
final Throwable error = (Throwable) (success ? null : value);
resultQueue.add(new WorkResult(workId, result, error));
}
/**
* Poll next result.
* @param waitTimeSeconds Time to wait next result
* @return WorkResult or null
*/
WorkResult pollResult(final int waitTimeSeconds) {
try {
return resultQueue.poll(waitTimeSeconds, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
/**
* @return Api version
*/
String getApiVersion() {
return "1.0.0";
}
private WorkItem<?, ?> pollWorkItem(final String workType, final int pullTimeoutInSeconds) {
try {
//take attend qu'un élément soit disponible toutes les secondes.
//Poll attend (1s) qu'un élément soit disponible et sinon renvoit null
final WaitingWorkInfos waitingWorkInfos = obtainWorkQueue(workType).poll(pullTimeoutInSeconds, TimeUnit.SECONDS);
return waitingWorkInfos != null ? waitingWorkInfos.getWorkItem() : null;
} catch (final InterruptedException e) {
//dans le cas d'une interruption on arrête de dépiler
return null;
}
}
/**
* Ajoute un travail à faire.
* @param<R> result
* @param <W> Travail à effectué
* @param workItem Work et WorkResultHandler
*/
<R, W> void putWorkItem(final WorkItem<R, W> workItem) {
Assertion.check().isNotNull(workItem);
if (!isActiveWorkType(workItem.getWorkEngineClass().getName())) {
LOG.warn("No active node for this workType : {}", workItem.getWorkEngineClass().getName());
}
try {
obtainWorkQueue(workItem.getWorkEngineClass().getName()).put(new WaitingWorkInfos(workItem));
} catch (final InterruptedException e) {
//dans le cas d'une interruption on interdit d'empiler de nouveaux Works
throw WrappedException.wrap(e, "putWorkItem");
}
}
private synchronized BlockingQueue<WaitingWorkInfos> obtainWorkQueue(final String workType) throws InterruptedException {
checkInterrupted();
BlockingQueue<WaitingWorkInfos> workQueue = workQueueMap.get(workType);
if (workQueue == null) {
workQueue = new LinkedBlockingQueue<>();
workQueueMap.put(workType, workQueue);
}
return workQueue;
}
private static class WaitingWorkInfos {
private final WorkItem workItem;
private final long startWaitingTime;
public WaitingWorkInfos(final WorkItem workItem) {
this.workItem = workItem;
startWaitingTime = System.currentTimeMillis();
}
public WorkItem getWorkItem() {
return workItem;
}
public long getWaitingAge() {
return System.currentTimeMillis() - startWaitingTime;
}
}
private static class RunningWorkInfos {
private final WorkItem workItem;
private final String nodeUID;
public RunningWorkInfos(final WorkItem workItem, final String nodeUID) {
this.workItem = workItem;
this.nodeUID = nodeUID;
}
public WorkItem getWorkItem() {
return workItem;
}
public String getNodeUID() {
return nodeUID;
}
}
private static void checkInterrupted() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread interruption required");
}
}
}
| 34.951768
| 167
| 0.733487
|
69f6b75b5b8c10678cb01f38f0b58e5a3f17b7c2
| 2,084
|
package br.com.acmattos.election.employee;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
/**
* Credentials that allows anyone to access the application.
*
* Lombok helps with getters, setter toString, equals and hashcode of the class.
*
* @author acmattos
* @since 16/01/2018
* TODO CHECK, UNIT TEST
* TODO https://www.concretepage.com/java/jpa/jpa-entitylisteners-example-with-callbacks-prepersist-postpersist-postload-preupdate-postupdate-preremove-postremove
* TODO http://www.baeldung.com/database-auditing-jpa
*/
@Builder
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "profiles")
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(CredentialListener.class)
@Entity
public class Credential {
/** Credential's Identity. */
@Id
@SequenceGenerator(name = "user_id_seq",
sequenceName = "user_id_seq",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "user_id_seq")
@NotNull
private Long id;
/** Credential's Username. Cannot return null. */
@NotNull
@Size(min=1, max=50)
private String username;
/** Credential's Password (encrypted). Cannot return null. */
@NotNull
@Size(min=1, max=100)
private String password;
/** Credential's Profiles. Cannot return null. */
@ManyToMany// TODO MAP CORRECTLY http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/
@JoinTable(name = "credential_profile",
joinColumns = @JoinColumn(name = "credential_id"),
inverseJoinColumns = @JoinColumn(name = "profile_id"))
private List<Profile> profiles;
/**
* Credential's 'Enabled' Indicator. Indicates whether the user is enabled
* or disabled. A disabled user cannot be authenticated.
*/
private boolean enabled;
/** Credential's Raw Password (as it was typed). */
@Size(min=4, max=30)
private String rawPassword; //TODO DOCUMENT SOLUTION
}
| 33.079365
| 162
| 0.703935
|
47e3f071dc7dc8c5b0b590c77122df1c8596ec68
| 755
|
/*
* 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 client.inventory;
/**
*
* @author Pungin
*/
public enum EchantEquipStat {
WATK(0x01),
MATK(0x02),
STR(0x04),
DEX(0x08),
INT(0x10),
LUK(0x20),
WDEF(0x40),
MDEF(0x80),
MHP(0x100),
MMP(0x200),
ACC(0x400),
AVOID(0x800),
JUMP(0x1000),
SPEED(0x2000);
private final int value;
private EchantEquipStat(int value) {
this.value = value;
}
public final int getValue() {
return value;
}
public final boolean check(int flag) {
return (flag & value) != 0;
}
}
| 17.97619
| 79
| 0.601325
|
3437f6acc2111273eae32596b195f12474817104
| 1,504
|
package uk.gov.dhsc.htbhf.claimant.testsupport;
import uk.gov.dhsc.htbhf.claimant.entity.Claimant;
import uk.gov.dhsc.htbhf.claimant.entity.EligibilityOverride;
import uk.gov.dhsc.htbhf.claimant.service.ClaimRequest;
import uk.gov.dhsc.htbhf.claimant.service.ClaimRequest.ClaimRequestBuilder;
import static uk.gov.dhsc.htbhf.TestConstants.MAGGIE_AND_LISA_DOBS;
import static uk.gov.dhsc.htbhf.claimant.testsupport.ClaimantTestDataFactory.aClaimantWithChildrenDob;
import static uk.gov.dhsc.htbhf.claimant.testsupport.NewClaimDTOTestDataFactory.DEVICE_FINGERPRINT;
public class ClaimRequestTestDataFactory {
public static final String WEB_UI_VERSION = "1.1.1";
public static ClaimRequest aValidClaimRequest() {
return aClaimRequestBuilderForClaimant(aClaimantWithChildrenDob(MAGGIE_AND_LISA_DOBS)).build();
}
public static ClaimRequest aClaimRequestWithEligibilityOverride(Claimant claimant, EligibilityOverride eligibilityOverride) {
return aClaimRequestBuilderForClaimant(claimant).eligibilityOverride(eligibilityOverride).build();
}
public static ClaimRequest aClaimRequestForClaimant(Claimant claimant) {
return aClaimRequestBuilderForClaimant(claimant).build();
}
public static ClaimRequestBuilder aClaimRequestBuilderForClaimant(Claimant claimant) {
return ClaimRequest.builder()
.claimant(claimant)
.deviceFingerprint(DEVICE_FINGERPRINT)
.webUIVersion(WEB_UI_VERSION);
}
}
| 41.777778
| 129
| 0.791223
|
ee90ce60cdbf65158e25596b2f2451233595379a
| 7,534
|
package com.activity.asyncadpter;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.fedorvlasov.lazylist.R;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
AsyncAdapter adapter;
ProgressBar progressBar1;
Button search;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//EditText searchedit=(EditText)findViewById(R.id.search_edit);
//String searchterm=searchedit.getText().toString();
list=(ListView)findViewById(R.id.list);
}
@Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public void searchTwitter(View view) throws Exception{
progressBar1=(ProgressBar)findViewById(R.id.progressBar1);
search=(Button)findViewById(R.id.search_btn);
EditText searchedit=(EditText)findViewById(R.id.search_edit);
if(searchedit.length()<1)
{
Toast.makeText(getApplicationContext(), "Please enter a query to search", Toast.LENGTH_SHORT).show();
return;
}
search.setEnabled(false);
progressBar1.setVisibility(View.VISIBLE);
//get user entered search term
if(checkInternetConnection())
{
String searchterm=searchedit.getText().toString();
try
{
String encodedSearch = URLEncoder.encode(searchterm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Please check your network connectivity!", Toast.LENGTH_LONG).show();
search.setEnabled(true);
progressBar1.setVisibility(View.INVISIBLE);
return;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected())
{
return true;
}
return false;
}
private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private class GetTweets extends AsyncTask<String, Void, String> {
/*
* Carry out fetching task in background
* - receives search URL via execute method
*/
//ArrayList<Tweet> tweets=new ArrayList<Tweet>();
@Override
protected String doInBackground(String... twitterURL) {
//start building result which will be json string
StringBuilder tweetFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet tweetGet = new HttpGet(searchURL);
//execute request
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
//check status, only proceed if ok
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity tweetEntity = tweetResponse.getEntity();
InputStream tweetContent = tweetEntity.getContent();
//process the results
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
}
}
else
{
Toast.makeText(getApplicationContext(), "Connection could not be established!", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "Connection could not be established!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
break;
}
}
//return result string
return tweetFeedBuilder.toString();
}
/*
* Process result of search query
* - this receives JSON string representing tweets with search term included
*/
protected void onPostExecute(String result) {
//start preparing result string for display
ArrayList<String> list_image=new ArrayList<String>();
ArrayList<String> list_username=new ArrayList<String>();
ArrayList<String> list_tweet=new ArrayList<String>();
String[] images=null;
String[] usernames=null;
String[] tweets=null;
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray tweetArray = resultObject.getJSONArray("results");
//loop through each item in the tweet array
for (int t=0; t<tweetArray.length(); t++) {
//each item is a JSONObject
JSONObject tweetObject = tweetArray.getJSONObject(t);
//get the username and text content for each tweet
list_username.add(tweetObject.get("from_user").toString());
list_tweet.add(tweetObject.get("text").toString());
list_image.add(tweetObject.get("profile_image_url").toString());
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Whoops - something went wrong!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//check result exists
if(list_tweet.size()<1 && list_username.size()<1)
{
Toast.makeText(getApplicationContext(), "No tweets found!", Toast.LENGTH_LONG).show();
}
else
{
images=list_image.toArray(new String[list_image.size()]);
usernames=list_username.toArray(new String[list_username.size()]);
tweets=list_tweet.toArray(new String[list_tweet.size()]);
adapter=new AsyncAdapter(MainActivity.this, images,usernames,tweets);
list.setAdapter(adapter);
}
progressBar1.setVisibility(View.INVISIBLE);
search.setEnabled(true);
}
}
}
| 28.8659
| 116
| 0.663658
|
5bb3640b9a17f9cbcd84dd8911eb98345a5c4b35
| 1,673
|
package com.health.anytime;
import java.io.Serializable;
// implemented Serializable to pass object from activity to activity
public class PatientModel implements Serializable{
private String patientProfilepic;
private String patientName;
private String patientPhoneNum;
private String patientEmail;
private boolean status;
private String role;
private String medId;
public PatientModel(){
}
public PatientModel(String pic, String name , String email , boolean status , String role, String med) {
this.patientProfilepic = pic;
this.patientName = name;
this.patientEmail = email;
this.status = status;
this.role = role;
this.medId = med;
}
public String getPatientProfilepic() {
return patientProfilepic;
}
public void setPatientProfilepic(String patientProfilepic) {
this.patientProfilepic = patientProfilepic;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPatientEmail() {
return patientEmail;
}
public void setPatientEmail(String patientEmail) {
this.patientEmail = patientEmail;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getRole() {
return role;
}
public String getPatientPhoneNum() {
return patientPhoneNum;
}
public void setPatientPhoneNum(String patientPhoneNum) {
this.patientPhoneNum = patientPhoneNum;
}
public String getMedid() {
return medId;
}
public void setMedid(String medid) {
this.medId = medid;
}
}
| 22.608108
| 106
| 0.719068
|
505d14352094ac55381fb2d98b047fb0e54d3706
| 867
|
package us.codecraft.webmagic.model.samples;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.model.ConsolePageModelPipeline;
import us.codecraft.webmagic.model.OOSpider;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.TargetUrl;
/**
* @author code4crafter@gmail.com
*/
@TargetUrl("https://www.chinapp.com/pinpai/canyin-0-0-[1-9]*")
//@ExtractBy(value = "//ul[@class=pplb_items_lists]/")
public class QQMeishi {
@ExtractBy("//li[@class=pplb_item]//a/@title")
private String shopName;
// @ExtractBy("//div[@class=info]/a[@class=title]/text()")
// private String promo;
public static void main(String[] args) {
OOSpider.create(Site.me(), new ConsolePageModelPipeline(), QQMeishi.class).addUrl("https://www.chinapp.com/pinpai/canyin-0-0-1").thread(4).run();
}
}
| 32.111111
| 153
| 0.723183
|
b0f405975ec6fe1e9fd4af669b9e520e8a001054
| 10,219
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches;
import static org.apache.datasketches.GenericInequalitySearch.find;
import static org.apache.datasketches.GenericInequalitySearch.Inequality.EQ;
import static org.apache.datasketches.GenericInequalitySearch.Inequality.GE;
import static org.apache.datasketches.GenericInequalitySearch.Inequality.GT;
import static org.apache.datasketches.GenericInequalitySearch.Inequality.LE;
import static org.apache.datasketches.GenericInequalitySearch.Inequality.LT;
import static org.testng.Assert.assertEquals;
import java.util.Comparator;
import java.util.Random;
import org.apache.datasketches.GenericInequalitySearch.Inequality;
import org.testng.annotations.Test;
/**
* @author Lee Rhodes
*/
@SuppressWarnings("javadoc")
public class GenericInequalitySearchTest {
static Random rand = new Random(1);
private static final String LS = System.getProperty("line.separator");
private static int randDelta() { return rand.nextDouble() < 0.4 ? 0 : 1; }
private final Comparator<Float> comparator = Comparator.naturalOrder();
private static Float[] buildRandFloatArr(final int len) {
final Float[] arr = new Float[len];
Float v = 1.0f; //lgtm [java/non-null-boxed-variable]
for (int i = 0; i < len; i++) {
arr[i] = v;
v += randDelta();
}
return arr;
}
@Test //visual testing only
//@SuppressWarnings("unused")
private static void checkBuildRandArr() {
final int len = 10;
for (int i = 0; i < 10; i++) {
final Float[] tarr = buildRandFloatArr(len);
for (int j = 0; j < len; j++) {
printf("%4.1f,", tarr[j]);
}
println("");
}
}
private static String listFltArray(final Float[] arr, final int low, final int high) {
final StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("arr: ");
for (int i = 0; i < arr.length; i++) {
if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); }
else { sb.append(String.format("%.0f ", arr[i])); }
}
return sb.toString();
}
@Test
public void checkBinSearchFltLimits() {
for (int len = 10; len <= 13; len++) {
final Float[] tarr = buildRandFloatArr(len);
final int low = 2;
final int high = len - 2;
println(listFltArray(tarr, low, high));
checkBinarySearchFloatLimits(tarr, low, high);
}
}
private void checkBinarySearchFloatLimits(final Float[] arr, final int low, final int high) {
final Float lowV = arr[low];
final Float highV = arr[high];
Float v;
int res;
v = lowV - 1f;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, -1);
v = lowV;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, -1);
v = highV + 1;
res = find(arr, low, high, v, LT, comparator);
println(desc(arr, low, high, v, res, LT, comparator));
assertEquals(res, high);
v = lowV -1;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, -1);
v = highV;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, high);
v = highV + 1;
res = find(arr, low, high, v, LE, comparator);
println(desc(arr, low, high, v, res, LE, comparator));
assertEquals(res, high);
v = lowV - 1;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(res, -1);
v = highV;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(arr[res], v);
v = highV + 1;
res = find(arr, low, high, v, EQ, comparator);
println(desc(arr, low, high, v, res, EQ, comparator));
assertEquals(res, -1);
v = lowV - 1;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, low);
v = highV;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, -1);
v = highV + 1;
res = find(arr, low, high, v, GT, comparator);
println(desc(arr, low, high, v, res, GT, comparator));
assertEquals(res, -1);
v = lowV - 1;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, low);
v = lowV;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, low);
v = highV + 1;
res = find(arr, low, high, v, GE, comparator);
println(desc(arr, low, high, v, res, GE, comparator));
assertEquals(res, -1);
}
@Test // visual only
public void exerciseFltBinSearch() {
checkFindFloat(LT);
checkFindFloat(LE);
checkFindFloat(GT);
checkFindFloat(GE);
}
private void checkFindFloat(final GenericInequalitySearch.Inequality inequality) {
println("Inequality: " + inequality.name());
// 0 1 2 3 4 5 6 7 8 9
final Float[] arr = {5f,5f,5f,6f,6f,6f,7f,8f,8f,8f};
final int len = arr.length;
for (Float v = 0.5f; v <= arr[len - 1] + 0.5f; v += .5f) { //lgtm [java/non-null-boxed-variable]
final int low = 0;
final int high = len - 1;
final int idx = find(arr, low, high, v, inequality, comparator);
if (idx == -1) {
println("LT: " + v + " Not resolved, return -1.");
}
else {
println(desc(arr, low, high, v, idx, inequality, comparator));
}
}
println("");
}
/**
* Optional call that describes the details of the results of the search.
* Used primarily for debugging.
* @param arr The underlying sorted array of generic values
* @param low the low index of the range
* @param high the high index of the range
* @param v the generic value to search for
* @param idx the resolved index from the search
* @param inequality one of LT, LE, EQ, GE, GT.
* @param comparator for the type T
* @param <T> The generic type of value to be used in the search process.
* @return the descriptive string.
*/
public static <T> String desc(final T[] arr, final int low, final int high, final T v, final int idx,
final Inequality inequality, final Comparator<T> comparator) {
switch (inequality) {
case LT: {
if (idx == -1) {
return "LT: " + v + " <= arr[" + low + "]=" + arr[low]
+ "; return -1";
}
if (idx == high) {
return "LT: " + v + " > arr[" + high + "]=" + arr[high]
+ "; return arr[" + high + "]=" + arr[high];
} //idx < high
return "LT: " + v
+ ": arr[" + idx + "]=" + arr[idx] + " < " + v
+ " <= arr[" + (idx + 1) + "]=" + arr[idx + 1]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case LE: {
if (idx == -1) {
return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1";
}
if (idx == high) {
return "LE: " + v + " >= arr[" + high + "]=" + arr[high]
+ "; return arr[" + high + "]=" + arr[high];
}
return "LE: " + v
+ ": arr[" + idx + "]=" + arr[idx] + " <= " + v
+ " < arr[" + (idx + 1) + "]=" + arr[idx + 1]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case EQ: {
if (idx == -1) {
if (comparator.compare(v, arr[high]) > 0) {
return "EQ: " + v + " > arr[" + high + "]; return -1";
}
if (comparator.compare(v, arr[low]) < 0) {
return "EQ: " + v + " < arr[" + low + "]; return -1";
}
return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high
+ "]; return -1";
}
return "EQ: " + v + " == arr[" + idx + "]; return " + idx;
}
case GE: {
if (idx == -1) {
return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1";
}
if (idx == low) {
return "GE: " + v + " <= arr[" + low + "]=" + arr[low]
+ "; return arr[" + low + "]=" + arr[low];
} //idx > low
return "GE: " + v
+ ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx]
+ "; return arr[" + idx + "]=" + arr[idx];
}
case GT: {
if (idx == -1) {
return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1";
}
if (idx == low) {
return "GT: " + v + " < arr[" + low + "]=" + arr[low]
+ "; return arr[" + low + "]=" + arr[low];
} //idx > low
return "GT: " + v
+ ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx]
+ "; return arr[" + idx + "]=" + arr[idx];
}
}
return "";
}
/**
* @param format the format
* @param args the args
*/
static final void printf(final String format, final Object ...args) {
//System.out.printf(format, args);
}
/**
* @param o the Object to print
*/
static final void println(final Object o) {
//System.out.println(o.toString());
}
}
| 33.726073
| 103
| 0.557393
|
698af841dad895ec589b415d15f3066e26e2e3d8
| 730
|
package de.fhg.iais.roberta.ast.syntax.expr;
import org.junit.Ignore;
import org.junit.Test;
import de.fhg.iais.roberta.util.test.ardu.HelperBotNrollForXmlTest;
public class MathConstantTest {
private final HelperBotNrollForXmlTest h = new HelperBotNrollForXmlTest();
@Test
public void Test() throws Exception {
String a = "PIM_EGOLDEN_RATIOM_SQRT2M_SQRT1_2INFINITY";
//"Float.POSITIVE_INFINITY";
this.h.assertCodeIsOk(a, "/syntax/math/math_constant.xml", false);
}
@Ignore
public void Test1() throws Exception {
final String a = "RotateMotor(B,PI,360.0*((1.0+sqrt(5.0))/2.0)))";
this.h.assertCodeIsOk(a, "/syntax/math/math_constant1.xml", false);
}
}
| 25.172414
| 78
| 0.691781
|
8c043863621c0847ef83e0058af528d2206625d0
| 3,059
|
package at.uibk.dps.ee.control.verticles;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import at.uibk.dps.ee.guice.starter.VertxProvider;
import at.uibk.dps.ee.model.graph.EnactmentGraph;
import at.uibk.dps.ee.model.graph.EnactmentGraphProvider;
import at.uibk.dps.ee.model.properties.PropertyServiceData;
import at.uibk.dps.ee.model.utils.UtilsEnactmentGraph;
import io.vertx.core.eventbus.EventBus;
import net.sf.opendse.model.Task;
/**
* The {@link InputDataHandler} processes the input JSON by annotating the root
* nodes of the graph and broadcasting the data-available events on the event
* bus.
*
* @author Fedor Smirnov
*/
public class InputDataHandler {
protected final EnactmentGraph eGraph;
protected final EventBus eBus;
protected final Logger logger = LoggerFactory.getLogger(InputDataHandler.class);
/**
* The injection constructor.
*
* @param eGraphProvider provides the e graph
* @param vertxProvider provides the vertX instance
*/
@Inject
public InputDataHandler(final EnactmentGraphProvider eGraphProvider,
final VertxProvider vertxProvider) {
this.eGraph = eGraphProvider.getEnactmentGraph();
this.eBus = vertxProvider.geteBus();
}
/**
* Processes the workflow input by annotating the corresponding root nodes of
* the graph and sending event bus messages with the information that the
* corresponding data is available.
*
* @param input the workflow input
*/
public void processInput(final JsonObject input) {
UtilsEnactmentGraph.getNonConstRootNodes(eGraph)
.forEach(rootNode -> processRootNode(rootNode, input));
UtilsEnactmentGraph.getConstantDataNodes(eGraph)
.forEach(constantNode -> processConstantNode(constantNode));
}
/**
* Processes the given constant node: Sends an event bus message signaling the
* availability of the node's data.
*
* @param constantNode the constant node to process
*/
protected void processConstantNode(final Task constantNode) {
logger.debug("Availability of constant node {} advertized.", constantNode.getId());
eBus.send(ConstantsVertX.addressDataAvailable, constantNode.getId());
}
/**
* Processes the given root node by annotating it with the entry from the json
* input
*
* @param rootNode the given root node
*/
protected void processRootNode(final Task rootNode, final JsonObject jsonInput) {
final String jsonKey = PropertyServiceData.getJsonKey(rootNode);
final JsonElement content =
Optional.ofNullable(jsonInput.get(jsonKey)).orElseThrow(() -> new IllegalArgumentException(
"No entry with the key " + jsonKey + " in the WF input."));
PropertyServiceData.setContent(rootNode, content);
logger.debug("Availability of the input data modeled by node {} advertized.", rootNode.getId());
eBus.send(ConstantsVertX.addressDataAvailable, rootNode.getId());
}
}
| 35.988235
| 100
| 0.746649
|
ead4e1057543ba474b6142a25f50aa0a70494374
| 1,085
|
package com.lhy.xposed.mhzs.plugin;
import com.lhy.xposed.mhzs.helper.XPrefUtils;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
/**
* 这是一个插件开发模板
*/
public class TemplatePlugin implements IPlugin {
/**
* 请在此进行Hook
*
* @param classLoader
* @throws Throwable
*/
@Override
public void run(ClassLoader classLoader) throws Throwable {
//Xposed框架的Hook方法
XposedHelpers.findAndHookMethod("xxx", classLoader, "x", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
super.beforeHookedMethod(param);
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
}
});
}
/**
* 插件的启用与关闭
*
* @return
*/
@Override
public boolean isOpen() {
// return false;
return XPrefUtils.getPref().getBoolean("xxx", false);
}
}
| 23.586957
| 87
| 0.611982
|
9cb26bb3f0ceb505091319ff7231b0da1db5be2f
| 1,539
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.tools;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.impl.ActionConfigurationCustomizer;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.options.SchemeManagerFactory;
import com.intellij.openapi.options.SchemeProcessor;
import org.jetbrains.annotations.NotNull;
@Service
public final class ToolManager extends BaseToolManager<Tool> {
public ToolManager() {
super(SchemeManagerFactory.getInstance(), "tools", ToolsBundle.message("tools.settings"));
}
static final class MyActionTuner implements ActionConfigurationCustomizer {
@Override
public void customize(@NotNull ActionManager manager) {
getInstance().registerActions(manager);
}
}
public static ToolManager getInstance() {
return ServiceManager.getService(ToolManager.class);
}
@Override
protected SchemeProcessor<ToolsGroup<Tool>, ToolsGroup<Tool>> createProcessor() {
return new ToolsProcessor<Tool>() {
@Override
protected ToolsGroup<Tool> createToolsGroup(String groupName) {
return new ToolsGroup<>(groupName);
}
@Override
protected Tool createTool() {
return new Tool();
}
};
}
@Override
protected String getActionIdPrefix() {
return Tool.ACTION_ID_PREFIX;
}
}
| 31.408163
| 140
| 0.751787
|
62cfebd0ef56d01c095cf4c98c4b6c7d2075fc34
| 4,300
|
/*
* [The "BSD license"]
* Copyright (c) 2010 Terence Parr
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.antlr.test;
import org.antlr.misc.Graph;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/** Test topo sort in GraphNode. */
public class TestTopologicalSort extends BaseTest {
@Test
public void testFairlyLargeGraph() throws Exception {
Graph<String> g = new Graph<String>();
g.addEdge("C", "F");
g.addEdge("C", "G");
g.addEdge("C", "A");
g.addEdge("C", "B");
g.addEdge("A", "D");
g.addEdge("A", "E");
g.addEdge("B", "E");
g.addEdge("D", "E");
g.addEdge("D", "F");
g.addEdge("F", "H");
g.addEdge("E", "F");
String expecting = "[H, F, E, D, G, A, B, C]";
List<String> nodes = g.sort();
String result = nodes.toString();
assertEquals(expecting, result);
}
@Test
public void testCyclicGraph() throws Exception {
Graph<String> g = new Graph<String>();
g.addEdge("A", "B");
g.addEdge("B", "C");
g.addEdge("C", "A");
g.addEdge("C", "D");
String expecting = "[D, C, B, A]";
List<String> nodes = g.sort();
String result = nodes.toString();
assertEquals(expecting, result);
}
@Test
public void testRepeatedEdges() throws Exception {
Graph<String> g = new Graph<String>();
g.addEdge("A", "B");
g.addEdge("B", "C");
g.addEdge("A", "B"); // dup
g.addEdge("C", "D");
String expecting = "[D, C, B, A]";
List<String> nodes = g.sort();
String result = nodes.toString();
assertEquals(expecting, result);
}
@Test
public void testSimpleTokenDependence() throws Exception {
Graph<String> g = new Graph<String>();
g.addEdge("Java.g", "MyJava.tokens"); // Java feeds off manual token file
g.addEdge("Java.tokens", "Java.g");
g.addEdge("Def.g", "Java.tokens"); // walkers feed off generated tokens
g.addEdge("Ref.g", "Java.tokens");
String expecting = "[MyJava.tokens, Java.g, Java.tokens, Ref.g, Def.g]";
List<String> nodes = g.sort();
String result = nodes.toString();
assertEquals(expecting, result);
}
@Test
public void testParserLexerCombo() throws Exception {
Graph<String> g = new Graph<String>();
g.addEdge("JavaLexer.tokens", "JavaLexer.g");
g.addEdge("JavaParser.g", "JavaLexer.tokens");
g.addEdge("Def.g", "JavaLexer.tokens");
g.addEdge("Ref.g", "JavaLexer.tokens");
String expecting = "[JavaLexer.g, JavaLexer.tokens, JavaParser.g, Ref.g, Def.g]";
List<String> nodes = g.sort();
String result = nodes.toString();
assertEquals(expecting, result);
}
}
| 37.068966
| 89
| 0.621395
|
b617334606304047beb5ca1b4001d8e24e420bcc
| 763
|
package com.sczhaoqi.news.blog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
* @author sczhaoqi
* @date 2021-11-22 下午5:37
*/
interface BlogPageMapper extends BaseMapper<BlogPage> {
/**
* truncate
*/
@Update("delete from b_page where 1")
void truncate();
}
@Service
public class BlogPageServiceImpl extends ServiceImpl<BlogPageMapper, BlogPage> implements IService<BlogPage> {
public void truncate() {
this.baseMapper.truncate();
}
}
| 26.310345
| 110
| 0.757536
|
7732c2e04b3cd1cfb9e869cda76239b126f0d7f2
| 1,776
|
package com.pokemongostats.view.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import androidx.annotation.NonNull;
import com.pokemongostats.model.bean.Type;
import com.pokemongostats.view.rows.TypeRow;
import java.util.List;
/**
* @author Zapagon
*/
public class TypeAdapter extends ArrayAdapter<Type> {
public TypeAdapter(Context context, int textViewResourceId, Type[] list) {
super(context, textViewResourceId, list);
}
public TypeAdapter(Context context, int textViewResourceId,
List<Type> list) {
super(context, textViewResourceId, list);
}
public TypeAdapter(Context applicationContext, int simpleSpinnerItem) {
super(applicationContext, simpleSpinnerItem);
}
/**
* {@inheritDoc}
*/
@Override
@NonNull
public View getView(int position, View v, @NonNull ViewGroup parent) {
return getTextViewAtPosition(position, v);
}
/**
* {@inheritDoc}
*/
@Override
public View getDropDownView(int position, View v, @NonNull ViewGroup parent) {
return getTextViewAtPosition(position, v);
}
private View getTextViewAtPosition(int position, View v) {
Type type = getItem(position);
if (type == null) {
return v;
}
final TypeRow view;
if (!(v instanceof TypeRow)) {
view = new TypeRow(getContext());
view.setType(type);
view.update();
} else {
view = (TypeRow) v;
if (!type.equals(view.getType())) {
view.setType(type);
view.update();
}
}
return view;
}
}
| 25.73913
| 82
| 0.617117
|
c36d5beb8f1034764a3c5504d290c2acbf6da292
| 98
|
class Example1 {
private String msg;
String getMsg() {
return this.msg;
}
}
| 10.888889
| 24
| 0.55102
|
ba24b25904343af1265fecc433b83bd806a948ce
| 2,239
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cdn.v2020_09_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The RankingsResponseTablesItemDataItemMetricsItem model.
*/
public class RankingsResponseTablesItemDataItemMetricsItem {
/**
* The metric property.
*/
@JsonProperty(value = "metric")
private String metric;
/**
* The value property.
*/
@JsonProperty(value = "value")
private Long value;
/**
* The percentage property.
*/
@JsonProperty(value = "percentage")
private Double percentage;
/**
* Get the metric value.
*
* @return the metric value
*/
public String metric() {
return this.metric;
}
/**
* Set the metric value.
*
* @param metric the metric value to set
* @return the RankingsResponseTablesItemDataItemMetricsItem object itself.
*/
public RankingsResponseTablesItemDataItemMetricsItem withMetric(String metric) {
this.metric = metric;
return this;
}
/**
* Get the value value.
*
* @return the value value
*/
public Long value() {
return this.value;
}
/**
* Set the value value.
*
* @param value the value value to set
* @return the RankingsResponseTablesItemDataItemMetricsItem object itself.
*/
public RankingsResponseTablesItemDataItemMetricsItem withValue(Long value) {
this.value = value;
return this;
}
/**
* Get the percentage value.
*
* @return the percentage value
*/
public Double percentage() {
return this.percentage;
}
/**
* Set the percentage value.
*
* @param percentage the percentage value to set
* @return the RankingsResponseTablesItemDataItemMetricsItem object itself.
*/
public RankingsResponseTablesItemDataItemMetricsItem withPercentage(Double percentage) {
this.percentage = percentage;
return this;
}
}
| 23.322917
| 92
| 0.640911
|
1720a9d7c41c81dca373f921d37569c10acd13dd
| 2,564
|
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.kie.server.services.swagger;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentMap;
import org.junit.Test;
import org.kie.server.api.KieServerEnvironment;
import io.swagger.config.SwaggerConfig;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.config.SwaggerConfigLocator;
import io.swagger.jaxrs.config.SwaggerContextService;
public class SwaggerKierServerExtensionTest {
@Test
public void testInit() throws Exception {
resetSwaggerConfig(SwaggerContextService.CONFIG_ID_DEFAULT);
KieServerEnvironment.setContextRoot("kie-server");
SwaggerKieServerExtension extension = new SwaggerKieServerExtension();
extension.init(null, null);
BeanConfig config = (BeanConfig) SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT);
assertEquals("/kie-server/services/rest", config.getBasePath());
}
@Test
public void testInitWithEmptyContextRoot() throws Exception {
resetSwaggerConfig(SwaggerContextService.CONFIG_ID_DEFAULT);
KieServerEnvironment.setContextRoot("");
SwaggerKieServerExtension extension = new SwaggerKieServerExtension();
extension.init(null, null);
BeanConfig config = (BeanConfig) SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT);
assertEquals("/services/rest", config.getBasePath());
}
//Swagger only allows to load a config once for a given id, so for testing purposes, we need to reset the config.
private void resetSwaggerConfig(String configId) throws Exception {
SwaggerConfigLocator swaggerConfigLocator = SwaggerConfigLocator.getInstance();
Field configMapField = SwaggerConfigLocator.class.getDeclaredField("configMap");
configMapField.setAccessible(true);
ConcurrentMap<String, SwaggerConfig> configMap = (ConcurrentMap<String, SwaggerConfig>) configMapField.get(swaggerConfigLocator);
configMap.remove(SwaggerContextService.CONFIG_ID_DEFAULT);
}
}
| 38.268657
| 131
| 0.794852
|
98c664b0d68bcb04f5544cc77c85df2902c4a372
| 1,834
|
package com.caobo.slideviewdemo;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import com.caobo.slideviewdemo.utils.StatusBarUtils;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import butterknife.ButterKnife;
/**
* Created by Administrator on 2020/6/16 0016
* Describe:
**/
public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar toolbar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResID());
toolbar = findViewById(R.id.toolbar);
ButterKnife.bind(this);
StatusBarUtils.setColor(this, ContextCompat.getColor(this, R.color.colorPrimary));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
initView();
}
protected void setToolbarTitle(String toolbarTitle){
toolbar.setTitle(toolbarTitle);
}
protected void setToolBarCallBack() {
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.abc_vector_test, null));
// 设置Navigation Button监听
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
protected abstract void initView();
protected abstract int getLayoutResID();
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.bind(this).unbind();
}
public void startActivity(Class<?> clz) {
Intent intent = new Intent(this, clz);
startActivity(intent);
}
}
| 27.787879
| 96
| 0.699564
|
aed5b438a3dab3445271db07541403330a9c0424
| 1,823
|
package com.nikita.trello.fw;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.BrowserType;
import java.util.concurrent.TimeUnit;
public class ApplicationManager {
public WebDriver wd;
BoardHelper boardHelper;
TeamHelper teamHelper;
HeaderHelper headerHelper;
SessionHelper sessionHelper;
Helperbase helperbase;
public void init() {
String browser = System.getProperty("browser", BrowserType.FIREFOX);
if (browser.equals(BrowserType.CHROME)) {
wd = new ChromeDriver();
} else if (browser.equals(BrowserType.FIREFOX)) {
wd = new FirefoxDriver();
} else if (browser.equals(BrowserType.EDGE)) {
wd = new EdgeDriver();
}
wd.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
maximize();
wd.get("https://trello.com/");
sessionHelper = new SessionHelper(wd);
boardHelper = new BoardHelper(wd);
headerHelper = new HeaderHelper(wd);
teamHelper = new TeamHelper(wd);
helperbase = new Helperbase(wd);
}
public void stop() throws InterruptedException {
getHelperbase().pause(5000);
wd.quit();
}
public void maximize(){
wd.manage().window().maximize();
}
public Helperbase getHelperbase() {
return helperbase;
}
public BoardHelper getBoardHelper() {
return boardHelper;
}
public TeamHelper getTeamHelper() {
return teamHelper;
}
public HeaderHelper getHeaderHelper() {
return headerHelper;
}
public SessionHelper getSessionHelper() {
return sessionHelper;
}
}
| 27.208955
| 76
| 0.653319
|
8216df75b8175a5c6389226565fc41ee4d4d6054
| 1,105
|
package tests.services;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import services.WeatherService;
import java.util.Map;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class WeatherService_getTemps {
private WeatherService weatherService;
@BeforeAll
void beforeAll() {
weatherService = new WeatherService();
}
@Test
public void testWeatherService_getTemps_RoundRock(){
weatherService.getWeather("Round Rock","TX")
.validateHttpStatusCode(200)
.validateResponseFieldValues(
Map.of("Code","Success")
);
}
@Test
public void testWeatherService_getTemps_Tampa(){
weatherService.getWeather("Tampa","TX")
.validateHttpStatusCode(404);
}
@Test
public void testWeatherService_getTemps_empty(){
weatherService.getWeather("","")
.validateHttpStatusCode(400);
}
}
| 26.95122
| 56
| 0.670588
|
d2d3d0eb1c3ae32783c04c56a0fb2ac062af4536
| 5,496
|
package jstaffor.android.jobsight.utilities;
import android.content.Context;
import java.util.List;
import java.util.Map;
import jstaffor.android.jobsight.database.DatabaseAccess;
import jstaffor.android.jobsight.datamodel.DataModel;
public class Validation
{
private static final String TAG = "Validation";
private DataModel dataModel;
private Context context;
private DatabaseAccess databaseAccess;
public Validation(Context context)
{
if(context == null)
throw new IllegalArgumentException("Validation(Context context) - context cannot be null");
this.context = context;
databaseAccess = new DatabaseAccess(context);
dataModel = databaseAccess.populateDataModelUsingDatabaseData(DataModel.USER_GUID);
}
public static String returnUIStringForSaving(String inputForParent)
{
if(inputForParent == null)
throw new IllegalArgumentException("Validation.Validation(Context context) - input cannot be null");
return inputForParent.trim().toUpperCase();
}
/**
*
* @param inputForParent
* @return lParent ID is returned, -1L if not found
*/
public Long getParentIDForParentName(String inputForParent)
{
final String sInputForParent = returnUIStringForSaving(inputForParent);
Long lParent = -1L;
if(dataModel.getMapParentName_ParentID() == null)
throw new IllegalArgumentException("Validation.doesParentCurrentlyExist(String inputForParent) - getMapParentName_ParentID() cannot be null");
if( dataModel.getMapParentName_ParentID().size() != 0 && dataModel.getMapParentName_ParentID().containsKey(sInputForParent) )
lParent = dataModel.getMapParentName_ParentID().get(sInputForParent);
return lParent;
}
/**
*
* @param inputForChild
* @return lChild ID is returned, -1L if not found
*/
public Long getChildIDForParentID(Long lInputForParent, String inputForChild)
{
final String sInputForChild = returnUIStringForSaving(inputForChild);
Long lChild = -1L;
if(lInputForParent == null)
throw new IllegalArgumentException("Validation.getChildIDUsingChildName(Long lInputForParent, String sInputForChild) - inputs cannot be null");
if(dataModel.getMapParentID_mapChildNameChildID() == null)
throw new IllegalArgumentException("Validation.getChildIDUsingChildName(Long lInputForParent, String sInputForChild) - getMapParentID_ChildIDList() cannot be null");
if(dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent) != null )
{
for(String currentSChild : dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent).keySet() )
{
if(sInputForChild.equals(currentSChild))
{
lChild = dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent).get(sInputForChild);
}
}
}
return lChild;
}
/**
*
* @param lInputForParent
* @param lInputForChild
* @return sChild is returned, {@code null} if not found
*/
public String getChildNameForParentID(Long lInputForParent, Long lInputForChild)
{
String sChild = null;
if(lInputForParent == null || lInputForChild == null)
throw new IllegalArgumentException("Validation.getChildIDUsingChildName(Long lInputForParent, Long lInputForChild) - inputs cannot be null");
if(dataModel.getMapParentID_mapChildNameChildID() == null)
throw new IllegalArgumentException("Validation.getChildIDUsingChildName(Long lInputForParent, Long lInputForChild) - getMapParentID_ChildIDList() cannot be null");
//(1) If 'inputForParent' contains a list of children
if(dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent) != null && dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent).values().contains(lInputForChild) )
{
for(int currentIndex = 0; currentIndex < dataModel.getMapParentID_mapChildNameChildID().get(lInputForParent).keySet().size(); currentIndex++)
{
if(dataModel.getMapParentID_mapChildNameChildID().values().toArray()[currentIndex] == lInputForChild)
{
sChild = (String) dataModel.getMapParentID_mapChildNameChildID().keySet().toArray()[currentIndex];
}
}
}
return sChild;
}
/**
*
* @param sTemplate
* @return setting for 'sTemplate' of DataModel.DEFAULT_VALUE_COLUMN_TEMPLATE_SETTING if not found
*/
public Long doesTemplateCurrentlyExist(String sTemplate)
{
if(sTemplate == null)
throw new IllegalArgumentException("Validation.doesTemplateCurrentlyExist(String inputForTemplate) - input cannot be null");
if(dataModel.getMapTempName_TempSetting() == null)
throw new IllegalArgumentException("Validation.doesParentCurrentlyExist(String inputForParent) - getMapTempName_TempSetting() cannot be null");
final String validatedParentString = this.returnUIStringForSaving(sTemplate);
if( dataModel.getMapTempName_TempSetting().get(validatedParentString) != null)
return dataModel.getMapTempName_TempSetting().get(validatedParentString);
else
return DataModel.DEFAULT_VALUE_COLUMN_TEMPLATE_SETTING;
}
}
| 39.826087
| 193
| 0.694869
|
3f17648fc42794ea6079e2008bac8e8270eca2ef
| 2,073
|
/*
* 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 de.unioninvestment.eai.portal.portlet.crud.scripting.model;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import de.unioninvestment.eai.portal.portlet.crud.domain.container.JmxDelegate;
import de.unioninvestment.eai.portal.portlet.crud.domain.model.DataContainer;
import de.unioninvestment.eai.portal.support.scripting.ScriptJMXWrapper;
public class ScriptJMXContainerTest {
@Mock
private ScriptJMXWrapper wrapperMock;
@Mock
private DataContainer containerMock;
@Mock
private JmxDelegate delegateMock;
private ScriptJMXContainer scriptJMXContainer;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
scriptJMXContainer = new ScriptJMXContainer(wrapperMock, containerMock, delegateMock);
}
@Test
public void shouldSetQuery() {
scriptJMXContainer.setQuery("4711");
verify(delegateMock).setQuery("4711");
}
@Test
public void shouldGetServer() {
assertThat(scriptJMXContainer.getServer(), is(wrapperMock));
}
@Test
public void shouldConnect() {
scriptJMXContainer.connect("4711");
verify(wrapperMock).connect("4711");
}
}
| 30.043478
| 88
| 0.785335
|
69fee2e210071833dfb0c67478f17b2ddc68e5f2
| 4,189
|
/**
* Copyright (c) 2016 European Organisation for Nuclear Research (CERN), All Rights Reserved.
*/
package de.gsi.chart.plugins;
import de.gsi.chart.axes.Axis;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Orientation;
import javafx.geometry.Point2D;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Line;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.PathElement;
/**
* Horizontal and vertical {@link Line} drawn on the plot area, crossing at the mouse cursor location, together with a
* {@link Label} displaying the cursor coordinates in data units.
* <p>
* CSS style class names: {@value #STYLE_CLASS_PATH} and {@value #STYLE_CLASS_LABEL}
*
* @author Grzegorz Kruk
*/
public class CrosshairIndicator extends AbstractDataFormattingPlugin {
/**
* Name of the CSS class of the horizontal and vertical lines path.
*/
public static final String STYLE_CLASS_PATH = "chart-crosshair-path";
/**
* Name of the CSS class of the label displaying mouse coordinates.
*/
public static final String STYLE_CLASS_LABEL = "chart-crosshair-label";
private static final int LABEL_X_OFFSET = 15;
private static final int LABEL_Y_OFFSET = 5;
private final Path crosshairPath = new Path();
private final Label coordinatesLabel = new Label();
private final EventHandler<MouseEvent> mouseMoveHandler = (final MouseEvent event) -> {
final Bounds plotAreaBounds = getChart().getBoundsInLocal();
if (!plotAreaBounds.contains(event.getX(), event.getY())) {
getChartChildren().clear();
return;
}
updatePath(event, plotAreaBounds);
updateLabel(event, plotAreaBounds);
if (!getChartChildren().contains(crosshairPath)) {
getChartChildren().addAll(crosshairPath, coordinatesLabel);
}
};
/**
* Creates a new instance of CrosshairIndicator class.
*/
public CrosshairIndicator() {
crosshairPath.getStyleClass().add(CrosshairIndicator.STYLE_CLASS_PATH);
crosshairPath.setManaged(false);
coordinatesLabel.getStyleClass().add(CrosshairIndicator.STYLE_CLASS_LABEL);
coordinatesLabel.setManaged(false);
registerInputEventHandler(MouseEvent.MOUSE_MOVED, mouseMoveHandler);
}
private String formatLabelText(final Point2D displayPointInPlotArea) {
final Axis yAxis = getChart().getFirstAxis(Orientation.VERTICAL);
if (yAxis == null) {
return getChart() + " - " + "no y-axis present to translate point " + displayPointInPlotArea;
}
return formatData(getChart(), toDataPoint(yAxis, displayPointInPlotArea));
}
private void updateLabel(final MouseEvent event, final Bounds plotAreaBounds) {
coordinatesLabel.setText(formatLabelText(getLocationInPlotArea(event)));
final double width = coordinatesLabel.prefWidth(-1);
final double height = coordinatesLabel.prefHeight(width);
double xLocation = event.getX() + CrosshairIndicator.LABEL_X_OFFSET;
double yLocation = event.getY() + CrosshairIndicator.LABEL_Y_OFFSET;
if (xLocation + width > plotAreaBounds.getMaxX()) {
xLocation = event.getX() - CrosshairIndicator.LABEL_X_OFFSET - width;
}
if (yLocation + height > plotAreaBounds.getMaxY()) {
yLocation = event.getY() - CrosshairIndicator.LABEL_Y_OFFSET - height;
}
coordinatesLabel.resizeRelocate(xLocation, yLocation, width, height);
}
private void updatePath(final MouseEvent event, final Bounds plotAreaBounds) {
final ObservableList<PathElement> path = crosshairPath.getElements();
path.clear();
path.add(new MoveTo(plotAreaBounds.getMinX() + 1, event.getY()));
path.add(new LineTo(plotAreaBounds.getMaxX(), event.getY()));
path.add(new MoveTo(event.getX(), plotAreaBounds.getMinY() + 1));
path.add(new LineTo(event.getX(), plotAreaBounds.getMaxY()));
}
}
| 38.431193
| 118
| 0.701838
|
71d1b4cf3635ec509973f9b068eb7854854a914e
| 739
|
package com.junglezhang.autobannerlibrary.transformer;
import android.view.View;
/**
* Created by Jungle on 2019/2/14 0014.
*
* @author JungleZhang
* @version 1.0.0
* @Description
*/
public class RotateDownTransformer extends ABaseTransformer {
private static final float ROT_MOD = -15.0F;
public RotateDownTransformer() {
}
protected void onTransform(View view, float position) {
float width = (float)view.getWidth();
float height = (float)view.getHeight();
float rotation = -15.0F * position * -1.25F;
view.setPivotX(width * 0.5F);
view.setPivotY(height);
view.setRotation(rotation);
}
protected boolean isPagingEnabled() {
return true;
}
}
| 23.09375
| 61
| 0.657645
|
ae00b6b0251ae7fd5f5f256b95caa7ed30a3cf8e
| 2,548
|
package com.jam.common;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.jam.common.config.SiteConfig;
import com.jam.module.user.entity.User;
import com.jam.module.user.service.UserService;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by eclipse.
* Copyright (c) 2016, All Rights Reserved.
*/
@Log4j
public class BaseController {
@Autowired
private SiteConfig siteConfig;
@Autowired
private UserService userService;
public SiteConfig getSiteConfig() {
return siteConfig;
}
/**
* 带参重定向
*
* @param path
* @return
*/
protected String redirect(String path) {
return "redirect:" + path;
}
/**
* 不带参重定向
*
* @param response
* @param path
* @return
*/
protected String redirect(HttpServletResponse response, String path) {
try {
response.sendRedirect(path);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 渲染页面
*
* @param path 前面必须要加上 /
* @return
*/
protected String render(String path) {
return siteConfig.getTheme() + path;
}
protected void renderText(HttpServletResponse response, String msg) {
try {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取Security用户
*
* @return
*/
protected UserDetails getSecurityUser() {
Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
boolean b = o instanceof UserDetails;
if(b) {
log.info(o.toString());
return (UserDetails) o;
}
return null;
}
/**
*
*/
protected void destoryPrincipal() {
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false);
}
/**
* 获取用户信息
* @return
*/
protected User getUser() {
UserDetails userDetails = getSecurityUser();
if(userDetails != null) {
return userService.findByUsername(userDetails.getUsername());
}
return null;
}
}
| 22.954955
| 90
| 0.607143
|
6daa1e48fba22992018f41a97ffc46b1a495b588
| 886
|
package de.florianmarsch.fussballmanager.db.entity.divisionalTable;
import java.util.ArrayList;
import java.util.List;
import de.florianmarsch.fussballmanager.db.entity.matchday.Matchday;
import de.florianmarsch.fussballmanager.db.service.AbstractService;
public class DivisionalTableService extends AbstractService<DivisionalTable> {
public DivisionalTableService() {
super(QDivisionalTable.divisionalTable);
}
@Override
public DivisionalTable getNewInstance() {
return new DivisionalTable();
}
public List<DivisionalTable> getAllByMatchday(Matchday aMatchday) {
ArrayList<DivisionalTable> arrayList = new ArrayList<DivisionalTable>();
List<DivisionalTable> all = getAll();
for (DivisionalTable standing : all) {
if(standing.getMatchday() != null && standing.getMatchday().equals(aMatchday)){
arrayList.add(standing);
}
}
return arrayList;
}
}
| 26.848485
| 82
| 0.77991
|
ce1f9a186796e9c182ae6dfb7f310423928f388a
| 2,900
|
package com.yilian.networkingmodule.entity;
import com.google.gson.annotations.SerializedName;
import com.yilian.networkingmodule.httpresult.HttpResultBean;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ray_L_Pain on 2017/10/11 0011.
*/
public class MerchantManagerDetailEntity extends HttpResultBean {
@SerializedName("data")
public DataBean data;
public class DataBean {
@SerializedName("goods_index")
public String goods_index;
@SerializedName("goods_name")
public String goods_name;
@SerializedName("goods_icon")
public String goods_icon;
@SerializedName("goods_sale")
public String goods_sale;
@SerializedName("goods_sku_count")
public String goods_sku_count;
@Override
public String toString() {
return "ListBean{" +
"goods_index='" + goods_index + '\'' +
", goods_name='" + goods_name + '\'' +
", goods_icon='" + goods_icon + '\'' +
", goods_sale='" + goods_sale + '\'' +
", goods_sku_count='" + goods_sku_count + '\'' +
", is_normal='" + is_normal + '\'' +
", is_yhs='" + is_yhs + '\'' +
", is_jfg='" + is_jfg + '\'' +
", goods_price='" + goods_price + '\'' +
", goods_cost='" + goods_cost + '\'' +
", retail_price='" + retail_price + '\'' +
", goods_sku='" + goods_sku + '\'' +
", goods_integral='" + goods_integral + '\'' +
", goodsSkuPrice=" + goodsSkuPrice +
", goodsSkuProperty=" + goodsSkuProperty +
", goodsSkuValues=" + goodsSkuValues +
'}';
}
@SerializedName("is_normal")
public String is_normal;
@SerializedName("is_yhs")
public String is_yhs;
@SerializedName("is_jfg")
public String is_jfg;
@SerializedName("goods_price")
public String goods_price;
@SerializedName("goods_cost")
public String goods_cost;
@SerializedName("retail_price")
public String retail_price;
@SerializedName("goods_sku")
public String goods_sku;
@SerializedName("goods_integral")
public String goods_integral;
@SerializedName("goods_album")
public ArrayList<String> goods_album;
@SerializedName("authority")
public String authority;
@SerializedName("goods_sku_price")
public List<GoodsSkuPriceBean> goodsSkuPrice;
@SerializedName("goods_sku_property")
public List<GoodsSkuPropertyBean> goodsSkuProperty;
@SerializedName("goods_sku_values")
public List<GoodsSkuPropertyBean> goodsSkuValues;
}
}
| 35.365854
| 68
| 0.567241
|
ede5e4ad2a15597d004772c951ce89fbd2707b02
| 288
|
package normaan.org.conway.domain.repository;
import normaan.org.conway.domain.entity.StoresEntity;
import org.springframework.data.repository.CrudRepository;
public interface StoresRepo extends CrudRepository<StoresEntity, Long> {
StoresEntity findByStoreName(String storeName);
}
| 32
| 72
| 0.836806
|
809ef185ce067190e9a619b628c472dfbb7e309c
| 5,534
|
/**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.javaagent;
import org.evosuite.Properties;
import org.evosuite.TestUtil;
import org.evosuite.classpath.ClassPathHandler;
import org.evosuite.instrumentation.InstrumentingClassLoader;
import org.evosuite.instrumentation.testability.TestabilityTransformationClassLoader;
import org.evosuite.testcase.execution.ExecutionTrace;
import org.evosuite.testcase.execution.ExecutionTracer;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class InstrumentingClassLoaderTest {
@BeforeClass
public static void initClass() {
ClassPathHandler.getInstance().changeTargetCPtoTheSameAsEvoSuite();
}
@Test
public void testClassWithStaticInitializationCallingGetPackage()
throws ClassNotFoundException {
InstrumentingClassLoader instrumentingClassLoader = new InstrumentingClassLoader();
Class<?> stat = Class.forName("com.examples.with.different.packagename.StatInitIssue",
true, instrumentingClassLoader);
}
/*
* Tests the child-first/parent-last property of the classloader.
*/
@Ignore
@Test
public void testDependingInstrumentation() throws Exception {
Class<?> originalClass = DependentClassLoaderTestSubject.class;
Properties.TARGET_CLASS = originalClass.getName();
Properties.PROJECT_PREFIX = originalClass.getPackage().getName();
Properties.TARGET_CLASS_PREFIX = Properties.PROJECT_PREFIX;
TestabilityTransformationClassLoader instrumentingClassLoader = new TestabilityTransformationClassLoader();
Class<?> changedClass = instrumentingClassLoader.loadClass(ClassLoaderTestSubject.class.getName());
Assert.assertEquals(instrumentingClassLoader, changedClass.getClassLoader());
Object changed = changedClass.getConstructor().newInstance();
ExecutionTracer.enable();
ExecutionTracer.getExecutionTracer().clear();
TestUtil.invokeMethod(changed, "trySomethingElse");
ExecutionTrace execTrace = ExecutionTracer.getExecutionTracer().getTrace();
execTrace = ExecutionTracer.getExecutionTracer().getTrace();
Assert.assertFalse(execTrace.getTrueDistances().isEmpty());
Assert.assertFalse(execTrace.getFalseDistances().isEmpty());
ExecutionTracer.getExecutionTracer().clear();
}
@Ignore
@Test
public void testDirectInstrumentation() throws Exception {
Class<?> originalClass = ClassLoaderTestSubject.class;
Properties.TARGET_CLASS = originalClass.getName();
Properties.PROJECT_PREFIX = originalClass.getPackage().getName();
ClassLoaderTestSubject original = new ClassLoaderTestSubject();
ExecutionTracer.enable();
ExecutionTracer.getExecutionTracer().clear();
original.assess(6);
ExecutionTrace execTrace = ExecutionTracer.getExecutionTracer().getTrace();
Assert.assertTrue(execTrace.getTrueDistances().isEmpty());
Assert.assertTrue(execTrace.getFalseDistances().isEmpty());
TestabilityTransformationClassLoader instrumentingClassLoader = new TestabilityTransformationClassLoader();
Class<?> changedClass = instrumentingClassLoader.loadClass(ClassLoaderTestSubject.class.getName());
Assert.assertEquals(instrumentingClassLoader, changedClass.getClassLoader());
Assert.assertTrue(changedClass.hashCode() != originalClass.hashCode());
Assert.assertFalse(changedClass.equals(originalClass));
Object changed = changedClass.getConstructor().newInstance();
try {
@SuppressWarnings("unused")
ClassLoaderTestSubject casted = (ClassLoaderTestSubject) changed;
Assert.fail();
} catch (ClassCastException exc) {
// expected
}
ExecutionTracer.getExecutionTracer().clear();
TestUtil.invokeMethod(changed, "assess", Integer.valueOf(6));
execTrace = ExecutionTracer.getExecutionTracer().getTrace();
Assert.assertFalse(execTrace.getTrueDistances().isEmpty());
Assert.assertFalse(execTrace.getFalseDistances().isEmpty());
ExecutionTracer.getExecutionTracer().clear();
}
@Ignore
@Test
public void testInnerClasses() throws Exception {
Class<? extends InnerClassesTestSubject> originalClass = InnerClassesTestSubject.class;
Properties.TARGET_CLASS = originalClass.getName();
Properties.PROJECT_PREFIX = originalClass.getPackage().getName();
TestabilityTransformationClassLoader instrumentingClassLoader = new TestabilityTransformationClassLoader();
Class<?> changedClass = instrumentingClassLoader.loadClass(InnerClassesTestSubject.class.getName());
Assert.assertEquals(instrumentingClassLoader, changedClass.getClassLoader());
Assert.assertTrue(changedClass.hashCode() != originalClass.hashCode());
InnerClassesTestSubject original = originalClass.newInstance();
Assert.assertEquals("abcd", original.toString());
Object modified = changedClass.newInstance();
Assert.assertEquals("abcd", modified.toString());
}
}
| 42.899225
| 109
| 0.791652
|
843f03f88c99f826c21613b43e113cbb7e5f2282
| 1,021
|
package org.mitre.springboot.openid.connect.web;
import javax.transaction.Transactional;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
@Transactional
public class DataApiAuthorizationTests extends ApiAuthorizationTestsBase {
@Test
public void adminGetApiDataUnauthorized() throws Exception {
adminSession();
checkGetAccess("/api/data", 200);
}
@Test
@Rollback(true)
public void adminPostApiDataSuccess() throws Exception {
adminSession();
checkPostAccess("/api/data", 200);
}
@Test
public void userGetApiDataUnauthorized() throws Exception {
userSession();
checkGetAccess("/api/data", 403);
}
@Test
public void userPostApiDataUnauthorized() throws Exception {
userSession();
checkPostAccess("/api/data", 403);
}
@Test
public void anonymousGetApiDataUnauthenticated() throws Exception {
checkGetAccess("/api/data", 401);
}
@Test
public void anonymousPostApiDataUnauthenticated() throws Exception {
checkPostAccess("/api/data", 401);
}
}
| 21.723404
| 74
| 0.756121
|
a3ffb52d4a863b8cb5e82402486a5bafefeaa08b
| 10,825
|
package com.kc.shiptransport.mvp.plan;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.kc.shiptransport.data.source.DataRepository;
import com.kc.shiptransport.data.source.remote.RemoteDataSource;
import com.kc.shiptransport.db.WeekTask;
import com.kc.shiptransport.util.CalendarUtil;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
* @author qiuyongheng
* @time 2017/5/17 10:53
* @desc ${TODD}
*/
public class PlanPresenter implements PlanContract.Presenter {
private final Context context;
private final PlanContract.View view;
private final RemoteDataSource remoteDataSource;
private final Gson gson;
private int day_0 = 0;
private int day_1 = 0;
private int day_2 = 0;
private int day_3 = 0;
private int day_4 = 0;
private int day_5 = 0;
private int day_6 = 0;
private final DataRepository mDataRepository;
public PlanPresenter(Context context, PlanContract.View view) {
this.context = context;
this.view = view;
view.setPresenter(this);
remoteDataSource = new RemoteDataSource();
mDataRepository = new DataRepository();
gson = new Gson();
}
@Override
public void start(int jumpWeek) {
// 1. 获取供应商, 周
getTitle(jumpWeek);
// 2. 获取当前月
getCurrentDate(jumpWeek);
// 3. 刷新
doRefresh(jumpWeek);
}
/**
* 获取每日需求
* @param jumpWeek
*/
@Override
public void getDemandDayCount(int jumpWeek) {
mDataRepository
.getDemandDayCount(jumpWeek)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer[]>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer[] value) {
view.showDemandDayCount(value);
}
@Override
public void onError(Throwable e) {
view.showError("获取计划需求失败");
}
@Override
public void onComplete() {
}
});
}
/**
* 计算每日船舶数
* @param jumpWeek
*/
@Override
public void getDemanDayShipCount(int jumpWeek) {
mDataRepository
.getDemanDayShipCount(jumpWeek)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<Integer>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull List<Integer> list) {
view.showDemanDayShipCount(list);
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
@Override
public void subscribe() {
}
@Override
public void unsubscribe() {
}
/**
* 获取标题数据
*/
@Override
public void getTitle(final int jumpWeek) {
mDataRepository
.getTitle(jumpWeek)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String value) {
view.showTitle(value);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 获取当前月数据
*/
@Override
public void getCurrentDate(final int jumpWeek) {
mDataRepository
.getCurrentMouthDate(jumpWeek)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String value) {
view.showCurrentDate(value);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 获取任务缺口
*/
@Override
public void getTaskVolume(final int jumpWeek) {
// 一周计划任务量
Observable<Integer[]> daycount = mDataRepository
.getDayCount()
.subscribeOn(Schedulers.io());
// 获取一周计划需求量
Observable<Integer> taskvolume = mDataRepository
.getTaskVolume(jumpWeek)
.subscribeOn(Schedulers.io());
Observable.zip(daycount, taskvolume, new BiFunction<Integer[], Integer, Integer>() {
@Override
public Integer apply(@NonNull Integer[] integers, @NonNull Integer integer) throws Exception {
int total = 0;
for (Integer i : integers) {
total += i;
}
int v = integer - total;
return v > 0 ? v : 0;
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer value) {
view.showTaskVolume(value);
}
@Override
public void onError(Throwable e) {
view.showError("获取任务缺口失败");
}
@Override
public void onComplete() {
// 获取每日需求
getDemandDayCount(jumpWeek);
}
});
}
/**
* 获取任务要求
*/
@Override
public void getTaskRequire() {
}
/**
* 计算总任务量
*
* @param integers
*/
@Override
public void getTotalTaskVolume(Integer[] integers) {
int total = 0;
for (Integer integer : integers) {
total += integer;
}
view.showTotalTaskVolume(total);
}
/**
* 从本地数据库获取计划表
*/
@Override
public void getWeekTask(final int jumpWeek) {
mDataRepository
.getWeekTask(jumpWeek)
.subscribeOn(Schedulers.io())
.doOnNext(new Consumer<List<WeekTask>>() {
@Override
public void accept(List<WeekTask> weekTasks) throws Exception {
// 统计每日计划量
getDayCount();
// 统计每日船舶
getDemanDayShipCount(jumpWeek);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<WeekTask>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(List<WeekTask> value) {
// 获取一周日期数据
List<String> dates = CalendarUtil.getdateOfWeek("dd", jumpWeek);
Log.d("==", dates.toString());
view.showWeekTask(dates, value);
view.showLoading(false);
}
@Override
public void onError(Throwable e) {
view.showLoading(false);
}
@Override
public void onComplete() {
// 4. 获取供应商计划量缺口
getTaskVolume(jumpWeek);
}
});
}
/**
* 计算每天任务总量
*/
@Override
public void getDayCount() {
mDataRepository
.getDayCount()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer[]>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer[] value) {
// 计算总计划量
view.showDayCount(value);
getTotalTaskVolume(value);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 提交数据
*/
@Override
public void doCommit() {
}
/**
* 网络请求
* 保存数据到数据库
*/
@Override
public void doRefresh(final int jumpWeek) {
view.showLoading(true);
mDataRepository
.doRefresh(jumpWeek)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Boolean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Boolean value) {
}
@Override
public void onError(Throwable e) {
view.showLoading(false);
view.showError(e.getMessage());
}
@Override
public void onComplete() {
getWeekTask(jumpWeek);
}
});
}
}
| 27.0625
| 106
| 0.464573
|
7d831ad1ce255fd69f981cf36f3601aefed15f54
| 1,601
|
/*
* Copyright 2006-2013 ICEsoft Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icepdf.core.tag.query;
/**
* @author mcollette
* @since 4.0
*/
public abstract class Function implements Expression {
protected String[] arguments;
public void setArguments(String[] arguments) {
this.arguments = arguments;
}
public String describe(int indent) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++)
sb.append(" ");
String className = getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
sb.append(className);
sb.append(" ( ");
int num = (arguments != null) ? arguments.length : 0;
for (int i = 0; i < num; i++) {
sb.append('\'');
sb.append(arguments[i]);
sb.append('\'');
if (i < (num - 1))
sb.append(", ");
}
sb.append(" )\n");
return sb.toString();
}
}
| 32.673469
| 73
| 0.589631
|
2bc8485486cf9a8c1d71f96ed6d1fa8e06e5fe1b
| 785
|
package cn.zerokirby.note;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import cn.zerokirby.note.data.AvatarDataHelper;
import cn.zerokirby.note.data.NoteDataHelper;
import cn.zerokirby.note.data.UserDataHelper;
/**
* MyApplication
*/
public class MyApplication extends Application {
@SuppressLint("StaticFieldLeak")
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
UserDataHelper.initUserDataHelper();//初始化用户数据库
NoteDataHelper.initNoteDataHelper();//初始化笔记数据库
AvatarDataHelper.initAvatarDataHelper();//初始化头像数据库
}
public static Context getContext() {
return context;
}
}
| 23.787879
| 58
| 0.728662
|
943e799b09c9d2e35a73716b1475dd9b410951a5
| 7,157
|
package map;
import interfaces.Dessineur;
import interfaces.Fermable;
import interfaces.LocaliseDessinable;
import interfaces.StyleListe;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import listeners.AjoutPersoListener;
import listeners.ChangePersoListener;
import listeners.RemovePersoListener;
import perso.Perso;
import vision.Camera;
import divers.Listenable;
import ecrans.ApercuMap;
import exceptions.HorsLimiteException;
public abstract class MapDessinable<E extends LocaliseDessinable> extends Listenable
implements Dessineur, Fermable, StyleListe, ChangePersoListener, AjoutPersoListener, RemovePersoListener, DessineurElementMap<E> {
public static final boolean HD = false;
private final List<LocaliseDessinable> dessinables;
private final VolatileImage dessin, surdessin;
private final Graphics2D gDessin, gSurdessin;
private Graphics2D gPredessin;
private DessineurElementMap<E> dessineur;
public MapDessinable() {
dessinables = new ArrayList<LocaliseDessinable>();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
dessin = getVolatileImage(d.width, d.height);
surdessin = getVolatileImage(d.width, d.height);
gDessin = dessin.createGraphics();
gSurdessin = surdessin.createGraphics();
Color c = new Color(0, 0, 0, 0);
gDessin.setBackground(c);
gSurdessin.setBackground(c);
setHauteQualite(HD);
dessineur = this;
}
public abstract boolean dansMap(int x);
public abstract int getNombreObjets();
public abstract String getSuperficie();
public abstract int getLargeur();
public abstract int getAltitude(int x) throws HorsLimiteException;
public abstract E getObjet(int x, int y) throws HorsLimiteException;
public void setHauteQualite(boolean hd) {
Object r1, r2, r3;
if(hd) {
r1 = RenderingHints.VALUE_ANTIALIAS_ON;
r2 = RenderingHints.VALUE_COLOR_RENDER_QUALITY;
r3 = RenderingHints.VALUE_RENDER_QUALITY;
} else {
r1 = RenderingHints.VALUE_ANTIALIAS_OFF;
r2 = RenderingHints.VALUE_COLOR_RENDER_SPEED;
r3 = RenderingHints.VALUE_RENDER_SPEED;
}
for(final Graphics2D g : new Graphics2D[]{gDessin, gSurdessin}) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, r1);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, r2);
g.setRenderingHint(RenderingHints.KEY_RENDERING, r3);
}
}
public void setDessineur(DessineurElementMap<E> dessineur) {
this.dessineur = dessineur;
}
public VolatileImage getDessin() {
return dessin;
}
public VolatileImage getSurdessin() {
return surdessin;
}
public Graphics2D getgPredessin() {
return gPredessin;
}
public Graphics2D getgDessin() {
return gDessin;
}
public Graphics2D getgSurdessin() {
return gSurdessin;
}
public void setMasqueFond(Color c) {
gDessin.setBackground(c);
}
public void setMasqueCentre(Color c) {
gSurdessin.setBackground(c);
}
public List<LocaliseDessinable> getDessinables() {
return dessinables;
}
public void dessiner(Graphics g, Camera c) {
gPredessin = (Graphics2D) g;
effaceTampons(c.getEcran());
try {
c.nouvelleFrame();
dessineMap(c);
dessineDessinables(c);
} catch(Exception e) {}
dessineTampons();
}
public void dessineDessinables(Camera c) {
for(int i=0 ; i<dessinables.size() ; i++) try {
LocaliseDessinable d = dessinables.get(i);
if(c.estVisible(d, 0))
dessineur.dessinerDessinable(gPredessin, gDessin, gSurdessin, d, c);
} catch(Exception err) {
err.printStackTrace();
}
}
public void effacerFond(Component c) {
gPredessin.clearRect(0, 0, c.getWidth(), c.getHeight());
}
public void effaceTampons(Component c) {
effacerFond(c);
gDessin.clearRect(0, 0, c.getWidth(), c.getHeight());
gSurdessin.clearRect(0, 0, c.getWidth(), c.getHeight());
}
public void dessineTampons() {
gPredessin.drawImage(dessin, 0, 0, null);
gPredessin.drawImage(surdessin, 0, 0, null);
}
public void dessineMap(Camera c) throws HorsLimiteException {
int min = c.getMinX(), max = Math.min(c.getMaxX(), getLargeur()), centre = Map.checkX(c.getX());
for(int x=max ; x>centre ; x--)
dessinerColonne(c, x);
for(int x=min ; x<=centre ; x++)
dessinerColonne(c, x);
}
public void dessinerColonne(Camera c, int x) throws HorsLimiteException {
if(dansMap(x)) {
int alt = getAltitude(x);
if(alt > 0) {
int min = c.getMinY(), max = Math.min(c.getMaxY(), alt) - 1, centre = Map.checkY(c.getY());
for(int y=max ; y>centre ; y--)
dessiner(x, y, c);
for(int y=min ; y<=centre && y < alt ; y++)
dessiner(x, y, c);
}
}
}
public void dessiner(int x, int y, Camera c) throws HorsLimiteException {
E e = getObjet(x, y);
if(e != null)
dessineur.dessinerElementMap(gPredessin, gDessin, gSurdessin, e, c);
}
public E getObjet(MouseEvent e, Camera c) throws HorsLimiteException {
return getObjet(c.revertX(e.getX()), c.revertY(e.getY()));
}
@Override
public void dessinerDessinable(Graphics2D gPredessin, Graphics2D gDessin, Graphics2D gSurdessin, LocaliseDessinable e, Camera c) {
e.dessiner(c, gPredessin, gDessin, gSurdessin);
}
@Override
public void dessinerElementMap(Graphics2D gPredessin, Graphics2D gDessin, Graphics2D gSurdessin, E e, Camera c) {
int equipe = c.getSource().getEquipe();
Rectangle fond = c.getZoneFond(e, 0);
e.predessiner(gPredessin, fond, equipe);
e.dessiner(gDessin, c.getZone(e, 0), equipe);
e.surdessiner(gSurdessin, fond, equipe);
}
@Override
public void ajoutDessinable(LocaliseDessinable dessinable) {
dessinables.add(dessinable);
}
@Override
public void removeDessinable(LocaliseDessinable dessinable) {
dessinables.remove(dessinable);
}
@Override
public JComponent creerVue() {
return new ApercuMap<E>(this, false);
}
@Override
public void change(int id, Perso ancien, Perso nouveau) {
remove(id, ancien);
ajout(nouveau);
}
public static final BufferedImage getImage(int width, int height) {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(width, height, VolatileImage.TRANSLUCENT);
}
public static final VolatileImage getVolatileImage(int width, int height) {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleVolatileImage(width, height, VolatileImage.TRANSLUCENT);
}
}
| 30.849138
| 135
| 0.700573
|
c211913dc040421cd93cbbee18e4a4128c7cacec
| 8,453
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|io
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|BufferOverflowException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|ByteBuffer
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Arrays
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|nio
operator|.
name|ByteBuff
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|util
operator|.
name|ByteBufferUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|util
operator|.
name|Bytes
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|yetus
operator|.
name|audience
operator|.
name|InterfaceAudience
import|;
end_import
begin_comment
comment|/** * Our own implementation of ByteArrayOutputStream where all methods are NOT synchronized and * supports writing ByteBuffer directly to it. */
end_comment
begin_class
annotation|@
name|InterfaceAudience
operator|.
name|Private
specifier|public
class|class
name|ByteArrayOutputStream
extends|extends
name|OutputStream
implements|implements
name|ByteBufferWriter
block|{
comment|// Borrowed from openJDK:
comment|// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/ArrayList.java#221
specifier|private
specifier|static
specifier|final
name|int
name|MAX_ARRAY_SIZE
init|=
name|Integer
operator|.
name|MAX_VALUE
operator|-
literal|8
decl_stmt|;
specifier|private
name|byte
index|[]
name|buf
decl_stmt|;
specifier|private
name|int
name|pos
init|=
literal|0
decl_stmt|;
specifier|public
name|ByteArrayOutputStream
parameter_list|()
block|{
name|this
argument_list|(
literal|32
argument_list|)
expr_stmt|;
block|}
specifier|public
name|ByteArrayOutputStream
parameter_list|(
name|int
name|capacity
parameter_list|)
block|{
name|this
operator|.
name|buf
operator|=
operator|new
name|byte
index|[
name|capacity
index|]
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|write
parameter_list|(
name|ByteBuffer
name|b
parameter_list|,
name|int
name|off
parameter_list|,
name|int
name|len
parameter_list|)
block|{
name|checkSizeAndGrow
argument_list|(
name|len
argument_list|)
expr_stmt|;
name|ByteBufferUtils
operator|.
name|copyFromBufferToArray
argument_list|(
name|this
operator|.
name|buf
argument_list|,
name|b
argument_list|,
name|off
argument_list|,
name|this
operator|.
name|pos
argument_list|,
name|len
argument_list|)
expr_stmt|;
name|this
operator|.
name|pos
operator|+=
name|len
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|writeInt
parameter_list|(
name|int
name|i
parameter_list|)
block|{
name|checkSizeAndGrow
argument_list|(
name|Bytes
operator|.
name|SIZEOF_INT
argument_list|)
expr_stmt|;
name|Bytes
operator|.
name|putInt
argument_list|(
name|this
operator|.
name|buf
argument_list|,
name|this
operator|.
name|pos
argument_list|,
name|i
argument_list|)
expr_stmt|;
name|this
operator|.
name|pos
operator|+=
name|Bytes
operator|.
name|SIZEOF_INT
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|write
parameter_list|(
name|int
name|b
parameter_list|)
block|{
name|checkSizeAndGrow
argument_list|(
name|Bytes
operator|.
name|SIZEOF_BYTE
argument_list|)
expr_stmt|;
name|buf
index|[
name|this
operator|.
name|pos
index|]
operator|=
operator|(
name|byte
operator|)
name|b
expr_stmt|;
name|this
operator|.
name|pos
operator|++
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|write
parameter_list|(
name|byte
index|[]
name|b
parameter_list|,
name|int
name|off
parameter_list|,
name|int
name|len
parameter_list|)
block|{
name|checkSizeAndGrow
argument_list|(
name|len
argument_list|)
expr_stmt|;
name|System
operator|.
name|arraycopy
argument_list|(
name|b
argument_list|,
name|off
argument_list|,
name|this
operator|.
name|buf
argument_list|,
name|this
operator|.
name|pos
argument_list|,
name|len
argument_list|)
expr_stmt|;
name|this
operator|.
name|pos
operator|+=
name|len
expr_stmt|;
block|}
specifier|private
name|void
name|checkSizeAndGrow
parameter_list|(
name|int
name|extra
parameter_list|)
block|{
name|long
name|capacityNeeded
init|=
name|this
operator|.
name|pos
operator|+
operator|(
name|long
operator|)
name|extra
decl_stmt|;
if|if
condition|(
name|capacityNeeded
operator|>
name|this
operator|.
name|buf
operator|.
name|length
condition|)
block|{
comment|// guarantee it's possible to fit
if|if
condition|(
name|capacityNeeded
operator|>
name|MAX_ARRAY_SIZE
condition|)
block|{
throw|throw
operator|new
name|BufferOverflowException
argument_list|()
throw|;
block|}
comment|// double until hit the cap
name|long
name|nextCapacity
init|=
name|Math
operator|.
name|min
argument_list|(
name|this
operator|.
name|buf
operator|.
name|length
operator|<<
literal|1
argument_list|,
name|MAX_ARRAY_SIZE
argument_list|)
decl_stmt|;
comment|// but make sure there is enough if twice the existing capacity is still too small
name|nextCapacity
operator|=
name|Math
operator|.
name|max
argument_list|(
name|nextCapacity
argument_list|,
name|capacityNeeded
argument_list|)
expr_stmt|;
if|if
condition|(
name|nextCapacity
operator|>
name|MAX_ARRAY_SIZE
condition|)
block|{
throw|throw
operator|new
name|BufferOverflowException
argument_list|()
throw|;
block|}
name|byte
index|[]
name|newBuf
init|=
operator|new
name|byte
index|[
operator|(
name|int
operator|)
name|nextCapacity
index|]
decl_stmt|;
name|System
operator|.
name|arraycopy
argument_list|(
name|buf
argument_list|,
literal|0
argument_list|,
name|newBuf
argument_list|,
literal|0
argument_list|,
name|buf
operator|.
name|length
argument_list|)
expr_stmt|;
name|buf
operator|=
name|newBuf
expr_stmt|;
block|}
block|}
comment|/** * Resets the<code>pos</code> field of this byte array output stream to zero. The output stream * can be used again. */
specifier|public
name|void
name|reset
parameter_list|()
block|{
name|this
operator|.
name|pos
operator|=
literal|0
expr_stmt|;
block|}
comment|/** * Copies the content of this Stream into a new byte array. * @return the contents of this output stream, as new byte array. */
specifier|public
name|byte
index|[]
name|toByteArray
parameter_list|()
block|{
return|return
name|Arrays
operator|.
name|copyOf
argument_list|(
name|buf
argument_list|,
name|pos
argument_list|)
return|;
block|}
specifier|public
name|void
name|toByteBuff
parameter_list|(
name|ByteBuff
name|buff
parameter_list|)
block|{
name|buff
operator|.
name|put
argument_list|(
name|buf
argument_list|,
literal|0
argument_list|,
name|pos
argument_list|)
expr_stmt|;
block|}
comment|/** * @return the underlying array where the data gets accumulated */
specifier|public
name|byte
index|[]
name|getBuffer
parameter_list|()
block|{
return|return
name|this
operator|.
name|buf
return|;
block|}
comment|/** * @return The current size of the buffer. */
specifier|public
name|int
name|size
parameter_list|()
block|{
return|return
name|this
operator|.
name|pos
return|;
block|}
block|}
end_class
end_unit
| 14.855888
| 814
| 0.78623
|
2d95a30deb6e9c851b9a785c8552004ffdae089f
| 1,179
|
package com.journaldev.jaxws.service.test;
import java.util.Arrays;
import com.journaldev.jaxws.service.Person;
import com.journaldev.jaxws.service.PersonService;
import com.journaldev.jaxws.service.PersonServiceImplService;
public class TestPersonService {
public static void main(String[] args) {
PersonServiceImplService serviceImpl = new PersonServiceImplService();
PersonService service = serviceImpl.getPersonServiceImplPort();
Person p1 = new Person(); p1.setName("Pankaj"); p1.setId(1); p1.setAge(30);
Person p2 = new Person(); p2.setName("Meghna"); p2.setId(2); p2.setAge(25);
System.out.println("Add Person Status="+service.addPerson(p1));
System.out.println("Add Person Status="+service.addPerson(p2));
//get person
System.out.println(service.getPerson(1));
//get all persons
System.out.println(Arrays.asList(service.getAllPersons()));
//delete person
System.out.println("Delete Person Status="+service.deletePerson(2));
//get all persons
System.out.println(Arrays.asList(service.getAllPersons()));
}
}
| 31.026316
| 83
| 0.6743
|
76e98dca974c935b1544fab1f32eadf512baa3b5
| 1,854
|
package org.web3j.protocol.core;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import io.reactivex.Flowable;
import java8.util.concurrent.CompletableFuture;
import org.web3j.protocol.Web3jService;
public class Request<S, T extends Response> {
private static AtomicLong nextId = new AtomicLong(0);
private String jsonrpc = "2.0";
private String method;
private List<S> params;
private long id;
private Web3jService web3jService;
// Unfortunately require an instance of the type too, see
// http://stackoverflow.com/a/3437930/3211687
private Class<T> responseType;
public Request() {
}
public Request(String method, List<S> params,
Web3jService web3jService, Class<T> type) {
this.method = method;
this.params = params;
this.id = nextId.getAndIncrement();
this.web3jService = web3jService;
this.responseType = type;
}
public String getJsonrpc() {
return jsonrpc;
}
public void setJsonrpc(String jsonrpc) {
this.jsonrpc = jsonrpc;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public List<S> getParams() {
return params;
}
public void setParams(List<S> params) {
this.params = params;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public T send() throws IOException {
return web3jService.send(this, responseType);
}
public CompletableFuture<T> sendAsync() {
return web3jService.sendAsync(this, responseType);
}
public Flowable<T> flowable() {
return new RemoteCall<>(this::send).flowable();
}
}
| 22.071429
| 62
| 0.637001
|
a950d2b7b730189a941e46e71963af0ab78cd0fc
| 361
|
package com.csculb.interfaceDemo;
public class InterfaceDemo {
public static void main(String[] args) {
BaseRepository repo = new StudentRepository();
Student studentOne = new Student("Lin Thant Zin", 20);
Student studentTwo = new Student("Su Shoon Lae", 16);
repo.save(studentOne);
repo.save(studentTwo);
}
}
| 25.785714
| 62
| 0.65374
|
d2cc0079262acf635c6dab32a00cea62b6f7fda7
| 406
|
//- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved.
//- Limelight and all included source files are distributed under terms of the MIT License.
package limelight.ui.model;
import limelight.ui.painting.PaintAction;
import java.awt.*;
public class MockAfterPaintAction implements PaintAction
{
public boolean invoked;
public void invoke(Graphics2D graphics)
{
invoked = true;
}
}
| 21.368421
| 91
| 0.756158
|
57a8539631fe8b00aa3ab5a717833ad100cc00dc
| 3,470
|
/*
* Copyright 2015-2016 Dark Phoenixs (Open-Source Organization).
*
* 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.darkphoenixs.pool.jdbc;
import org.darkphoenixs.pool.ConnectionPool;
import org.darkphoenixs.pool.PoolBase;
import org.darkphoenixs.pool.PoolConfig;
import java.sql.Connection;
import java.util.Properties;
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: Jdbc连接池</p>
*
* @author Victor.Zxy
* @version 1.0
* @see PoolBase
* @see ConnectionPool
* @since 2015年11月17日
*/
public class JdbcConnectionPool extends PoolBase<Connection> implements ConnectionPool<Connection> {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 2743612676107943708L;
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: 默认构造方法</p>
*/
public JdbcConnectionPool() {
this(JdbcConfig.DEFAULT_DRIVER_CLASS, JdbcConfig.DEFAULT_JDBC_URL, JdbcConfig.DEFAULT_JDBC_USERNAME, JdbcConfig.DEFAULT_JDBC_PASSWORD);
}
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: 构造方法</p>
*
* @param properties JDBC参数
*/
public JdbcConnectionPool(final Properties properties) {
this(new PoolConfig(), properties);
}
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: 构造方法</p>
*
* @param driverClass 驱动类
* @param jdbcUrl 数据库URL
* @param username 数据库用户名
* @param password 数据密码
*/
public JdbcConnectionPool(final String driverClass, final String jdbcUrl, final String username, final String password) {
this(new PoolConfig(), driverClass, jdbcUrl, username, password);
}
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: 构造方法</p>
*
* @param poolConfig 池配置
* @param properties JDBC参数
*/
public JdbcConnectionPool(final PoolConfig poolConfig, final Properties properties) {
super(poolConfig, new JdbcConnectionFactory(properties));
}
/**
* <p>Title: JdbcConnectionPool</p>
* <p>Description: 构造方法</p>
*
* @param poolConfig 池配置
* @param driverClass 驱动类
* @param jdbcUrl 数据库URL
* @param username 数据库用户名
* @param password 数据密码
*/
public JdbcConnectionPool(final PoolConfig poolConfig, final String driverClass, final String jdbcUrl, final String username, final String password) {
super(poolConfig, new JdbcConnectionFactory(driverClass, jdbcUrl, username, password));
}
@Override
public Connection getConnection() {
return super.getResource();
}
@Override
public void returnConnection(Connection conn) {
super.returnResource(conn);
}
@Override
public void invalidateConnection(Connection conn) {
super.invalidateResource(conn);
}
}
| 28.442623
| 155
| 0.65389
|
b7f8f5127d23649db1968a9496e647e78f8b0eda
| 2,133
|
package io.opensphere.core.util.zip;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.log4j.Logger;
import net.jcip.annotations.NotThreadSafe;
/** An iterator over the names of the entries in a {@link ZipInputStream}. */
@NotThreadSafe
public class ZipEntryNameIterator implements Iterator<String>
{
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(ZipEntryNameIterator.class);
/** The input stream. */
private final ZipInputStream myInputStream;
/** The next entry name, if it has been retrieved. */
private String myNextEntryName;
/**
* Constructor.
*
* @param inputStream The input stream.
*/
public ZipEntryNameIterator(ZipInputStream inputStream)
{
myInputStream = inputStream;
}
@Override
public boolean hasNext()
{
return getNextEntryName() != null;
}
@Override
public String next()
{
String next = getNextEntryName();
myNextEntryName = null;
if (next == null)
{
throw new NoSuchElementException();
}
return next;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
/**
* Retrieve the next entry name, or return the one already retrieved.
*
* @return The next entry name, or {@code null} if there was an error or
* there are no more entries.
*/
private String getNextEntryName()
{
if (myNextEntryName == null)
{
try
{
ZipEntry nextEntry = myInputStream.getNextEntry();
myNextEntryName = nextEntry == null ? null : nextEntry.getName();
}
catch (IOException e)
{
LOGGER.warn("Failed to read from zip stream: " + e, e);
}
}
return myNextEntryName;
}
}
| 25.698795
| 87
| 0.58556
|
9baa4313b622c3a104fb895d7058ad6c046f108d
| 1,295
|
package remote.vr.com.remote_android.util;
import android.util.Log;
public class PerformanceLogger {
private static final String TAG = "VR-REMOTE";
private int counter = 0;
private long startTime = 0;
private long stopTime = 0;
private double maxTime = 0;
private double minTime = Double.MAX_VALUE;
private double totalTime = 0;
private String prefix = "";
private int nrOfRounds = 1000;
public PerformanceLogger(int nrOfRounds, String prefix) {
this.prefix = prefix;
this.nrOfRounds = 100;
}
public void start() {
startTime = System.nanoTime();
}
public void stop() {
stopTime = System.nanoTime();
double timeInMs = (stopTime - startTime) / (1000 * 1000);
counter++;
totalTime += timeInMs;
maxTime = Math.max(maxTime, timeInMs);
minTime = Math.min(minTime, timeInMs);
if(counter >= nrOfRounds) {
Log.d(TAG, prefix +
" - average: " + String.format("%.3f", totalTime / counter) + "ms, " +
"max: " + String.format("%.3f", maxTime) + "ms, " +
"min: " + String.format("%.3f", minTime) + "ms");
maxTime = 0;
counter = 0;
totalTime = 0;
}
}
}
| 24.903846
| 86
| 0.559846
|
16a94b79216326d86ffa867eb5514822fbb0e764
| 106
|
package Soru_1;
public enum Type {
PLUS,MINUS,TIMES,DIVIDE,PARANTHESISOPENED,PARANTHESISCLOSED
}
| 15.142857
| 61
| 0.764151
|
069b26c2acd97831f55dc4f2e6bc2c0717570143
| 1,133
|
package com.zhihuianxin.xyaxf.app.me.contract;
import modellib.thrift.customer.VerifyField;
import modellib.thrift.ecard.ECard;
import modellib.thrift.ecard.ECardAccount;
import modellib.thrift.fee.FeeAccount;
import com.zhihuianxin.xyaxf.app.BasePresenter;
import com.zhihuianxin.xyaxf.app.BaseView;
import java.util.ArrayList;
/**
* Created by Vincent on 2016/11/10.
*/
public interface IMeStuMsgContract {
interface IMeStuMsgView extends BaseView<IMeStuMsgPresenter>{
void modifyECardAccountSuccess(ECardAccount ecArdAccount, ECard eCard);
void modifyStuNoSuccess(FeeAccount feeAccount);
void modifyIDSuccess(FeeAccount feeAccount);
void getmodifyPwdInfoResult(ArrayList<VerifyField> verify_fields);
}
interface IMeStuMsgPresenter extends BasePresenter{
void modifyECardAccount(String account_no, String ecard_password, String login_password);
void modifyStuNo(String student_no, String id_card_no, String login_password);
void modifyID(String student_no, String id_card_no, String login_password);
void getmodifyPwdInfo(String mobile);
}
}
| 34.333333
| 97
| 0.778464
|
9a3d48e4912a1736c550a428f04bbe4c49d3844c
| 8,479
|
package jbse.algo;
import static jbse.algo.Util.ensureClassInitialized;
import static jbse.algo.Util.exitFromAlgorithm;
import static jbse.algo.Util.failExecution;
import static jbse.algo.Util.invokeClassLoaderLoadClass;
import static jbse.algo.Util.throwNew;
import static jbse.algo.Util.throwVerifyError;
import static jbse.bc.Signatures.ABSTRACT_METHOD_ERROR;
import static jbse.bc.Signatures.ILLEGAL_ACCESS_ERROR;
import static jbse.bc.Signatures.INCOMPATIBLE_CLASS_CHANGE_ERROR;
import static jbse.bc.Signatures.OUT_OF_MEMORY_ERROR;
import java.util.function.Supplier;
import jbse.algo.exc.NotYetImplementedException;
import jbse.bc.ClassFile;
import jbse.bc.Signature;
import jbse.bc.exc.BadClassFileVersionException;
import jbse.bc.exc.ClassFileIllFormedException;
import jbse.bc.exc.ClassFileNotAccessibleException;
import jbse.bc.exc.ClassFileNotFoundException;
import jbse.bc.exc.IncompatibleClassFileException;
import jbse.bc.exc.MethodAbstractException;
import jbse.bc.exc.MethodCodeNotFoundException;
import jbse.bc.exc.MethodNotAccessibleException;
import jbse.bc.exc.MethodNotFoundException;
import jbse.bc.exc.NullMethodReceiverException;
import jbse.bc.exc.PleaseLoadClassException;
import jbse.bc.exc.WrongClassNameException;
import jbse.dec.DecisionProcedureAlgorithms;
import jbse.mem.exc.HeapMemoryExhaustedException;
import jbse.mem.exc.InvalidProgramCounterException;
import jbse.mem.exc.InvalidSlotException;
import jbse.tree.DecisionAlternative_NONE;
import jbse.val.exc.InvalidTypeException;
/**
* Algorithm for completing the semantics of the
* invoke* bytecodes (invoke[interface/special/static/virtual]).
*
* @author Pietro Braione
*/
final class Algo_INVOKEX_Completion extends Algo_INVOKEX_Abstract {
public Algo_INVOKEX_Completion(boolean isInterface, boolean isSpecial, boolean isStatic) {
super(isInterface, isSpecial, isStatic);
}
private boolean shouldFindImplementation; //set by methods
public void setImplementation(ClassFile methodImplClass, Signature methodImplSignature) {
this.shouldFindImplementation = false;
this.methodImplClass = methodImplClass;
this.methodImplSignature = methodImplSignature;
this.isMethodImplSignaturePolymorphic = false;
}
public void shouldFindImplementation() {
this.shouldFindImplementation = true;
}
private int pcOffsetReturn; //set by methods
public void setProgramCounterOffset(int pcOffset) {
this.pcOffsetReturn = pcOffset;
}
@Override
protected BytecodeCooker bytecodeCooker() {
return (state) -> {
//performs method resolution again (this info is still necessary)
try {
resolveMethod(state);
} catch (PleaseLoadClassException e) {
invokeClassLoaderLoadClass(state, this.ctx.getCalculator(), e);
exitFromAlgorithm();
} catch (ClassFileNotFoundException |
ClassFileNotAccessibleException |
ClassFileIllFormedException |
BadClassFileVersionException |
WrongClassNameException |
IncompatibleClassFileException |
MethodNotFoundException |
MethodNotAccessibleException e) {
//this should never happen (Algo_INVOKEX already checked them)
failExecution(e);
}
//since a method can be base-level overridden by a static method,
//we need to know whether the implementation is or is not static
boolean isStaticImpl = false; //to keep the compiler happy
if (this.shouldFindImplementation) {
//if the method is looked up, the implementation is static
//if we are executing an invokestatic bytecode
isStaticImpl = this.isStatic;
//looks for the method implementation with standard lookup
try {
findImpl(state);
} catch (IncompatibleClassFileException e) {
throwNew(state, this.ctx.getCalculator(), INCOMPATIBLE_CLASS_CHANGE_ERROR);
exitFromAlgorithm();
} catch (MethodNotAccessibleException e) {
throwNew(state, this.ctx.getCalculator(), ILLEGAL_ACCESS_ERROR);
exitFromAlgorithm();
} catch (MethodAbstractException e) {
throwNew(state, this.ctx.getCalculator(), ABSTRACT_METHOD_ERROR);
exitFromAlgorithm();
}
} else {
//otherwise, the implementation's signature is already in this.methodSignatureImpl,
//and it could be static, so we need to check
try {
isStaticImpl = this.methodImplClass.isMethodStatic(this.methodImplSignature) ? true : this.isStatic;
} catch (MethodNotFoundException e) {
//this should never happen
failExecution(e);
}
}
//checks that the method has an implementation
try {
if (this.methodImplClass == null || this.methodImplClass.isMethodAbstract(this.methodImplSignature)) {
//Algo_INVOKEX found a standard implementation, so this should never happen
failExecution("Unexpected missing method implementation.");
}
} catch (MethodNotFoundException e) {
//this should never happen after resolution
failExecution(e);
}
//initializes the class of the implementation method; this is necessary for
//static base-level overriding methods; note that in the ordinary invokestatic case the
//class of the method implementation is the class of the resolved method, so this just
//repeats what was already done in Algo_INVOKEX
if (isStaticImpl) {
try {
ensureClassInitialized(state, this.methodImplClass, this.ctx);
} catch (HeapMemoryExhaustedException e) {
throwNew(state, this.ctx.getCalculator(), OUT_OF_MEMORY_ERROR);
exitFromAlgorithm();
}
}
//if the method is native, fails (should have an
//overriding implementation)
try {
if (this.methodImplClass.isMethodNative(this.methodImplSignature)) {
throw new NotYetImplementedException("Method " + this.methodImplSignature + " is native and has no overriding implementation.");
}
} catch (MethodNotFoundException e) {
//this should never happen
failExecution(e);
}
};
}
@Override
protected Class<DecisionAlternative_NONE> classDecisionAlternative() {
return DecisionAlternative_NONE.class;
}
@Override
protected StrategyDecide<DecisionAlternative_NONE> decider() {
return (state, result) -> {
result.add(DecisionAlternative_NONE.instance());
return DecisionProcedureAlgorithms.Outcome.FF;
};
}
@Override
protected StrategyRefine<DecisionAlternative_NONE> refiner() {
return (state, alt) -> { };
}
@Override
protected StrategyUpdate<DecisionAlternative_NONE> updater() {
return (state, alt) -> {
try {
state.pushFrame(this.ctx.getCalculator(), this.methodImplClass, this.methodImplSignature, false, this.pcOffsetReturn, this.data.operands());
} catch (InvalidProgramCounterException | InvalidSlotException | InvalidTypeException e) {
//TODO is it ok?
throwVerifyError(state, this.ctx.getCalculator());
} catch (NullMethodReceiverException | MethodNotFoundException | MethodCodeNotFoundException e) {
//this should never happen
failExecution(e);
}
};
}
@Override
protected Supplier<Boolean> isProgramCounterUpdateAnOffset() {
return () -> true;
}
@Override
protected Supplier<Integer> programCounterUpdate() {
return () -> 0; //nothing to add to the program counter of the pushed frame
}
}
| 41.975248
| 156
| 0.645359
|
a2917cd32ac45b67599232da654578382c4bd73b
| 14,579
|
/* Copyright 2017 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------*/
package sawtooth.examples.xo;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.lang3.StringUtils;
import sawtooth.sdk.processor.State;
import sawtooth.sdk.processor.TransactionHandler;
import sawtooth.sdk.processor.Utils;
import sawtooth.sdk.processor.exceptions.InternalError;
import sawtooth.sdk.processor.exceptions.InvalidTransactionException;
import sawtooth.sdk.protobuf.TpProcessRequest;
import sawtooth.sdk.protobuf.TransactionHeader;
import java.io.UnsupportedEncodingException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.logging.Logger;
public class XoHandler implements TransactionHandler {
private final Logger logger = Logger.getLogger(XoHandler.class.getName());
private String xoNameSpace;
/**
* constructor.
*/
public XoHandler() {
try {
this.xoNameSpace = Utils.hash512(
this.transactionFamilyName().getBytes("UTF-8")).substring(0, 6);
} catch (UnsupportedEncodingException usee) {
usee.printStackTrace();
this.xoNameSpace = "";
}
}
@Override
public String transactionFamilyName() {
return "xo";
}
@Override
public String getVersion() {
return "1.0";
}
@Override
public Collection<String> getNameSpaces() {
ArrayList<String> namespaces = new ArrayList<>();
namespaces.add(this.xoNameSpace);
return namespaces;
}
class TransactionData {
final String gameName;
final String action;
final String space;
TransactionData(String gameName, String action, String space) {
this.gameName = gameName;
this.action = action;
this.space = space;
}
}
class GameData {
final String gameName;
final String board;
final String state;
final String playerOne;
final String playerTwo;
GameData(String gameName, String board, String state, String playerOne, String playerTwo) {
this.gameName = gameName;
this.board = board;
this.state = state;
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
@Override
public void apply(TpProcessRequest transactionRequest, State stateStore)
throws InvalidTransactionException, InternalError {
TransactionData transactionData = getUnpackedTransaction(transactionRequest);
// The transaction signer is the player
String player;
TransactionHeader header = transactionRequest.getHeader();
player = header.getSignerPublicKey();
if (transactionData.gameName.equals("")) {
throw new InvalidTransactionException("Name is required");
}
if (transactionData.gameName.contains("|")) {
throw new InvalidTransactionException("Game name cannot contain '|'");
}
if (transactionData.action.equals("")) {
throw new InvalidTransactionException("Action is required");
}
if (transactionData.action.equals("take")) {
try {
int space = Integer.parseInt(transactionData.space);
if (space < 1 || space > 9) {
throw new InvalidTransactionException(
String.format("Invalid space: %s", transactionData.space));
}
} catch (NumberFormatException e) {
throw new InvalidTransactionException("Space could not be converted to an integer.");
}
}
if (!transactionData.action.equals("take") && !transactionData.action.equals("create")) {
throw new InvalidTransactionException(
String.format("Invalid action: %s", transactionData.action));
}
String address = makeGameAddress(transactionData.gameName);
// stateStore.get() returns a list.
// If no data has been stored yet at the given address, it will be empty.
String stateEntry = stateStore.get(
Collections.singletonList(address)
).get(address).toStringUtf8();
GameData stateData = getStateData(stateEntry, transactionData.gameName);
GameData updatedGameData = playXo(transactionData, stateData, player);
storeGameData(address, updatedGameData, stateEntry, stateStore);
}
/**
* Helper function to retrieve game gameName, action, and space from transaction request.
*/
private TransactionData getUnpackedTransaction(TpProcessRequest transactionRequest)
throws InvalidTransactionException {
String payload = transactionRequest.getPayload().toStringUtf8();
ArrayList<String> payloadList = new ArrayList<>(Arrays.asList(payload.split(",")));
if (payloadList.size() > 3) {
throw new InvalidTransactionException("Invalid payload serialization");
}
while (payloadList.size() < 3) {
payloadList.add("");
}
return new TransactionData(payloadList.get(0), payloadList.get(1), payloadList.get(2));
}
/**
* Helper function to retrieve the board, state, playerOne, and playerTwo from state store.
*/
private GameData getStateData(String stateEntry, String gameName)
throws InternalError, InvalidTransactionException {
if (stateEntry.length() == 0) {
return new GameData("", "", "", "", "");
} else {
try {
String gameCsv = getGameCsv(stateEntry, gameName);
ArrayList<String> gameList = new ArrayList<>(Arrays.asList(gameCsv.split(",")));
while (gameList.size() < 5) {
gameList.add("");
}
return new GameData(gameList.get(0), gameList.get(1),
gameList.get(2), gameList.get(3), gameList.get(4));
} catch (Error e) {
throw new InternalError("Failed to deserialize game data");
}
}
}
/**
* Helper function to generate game address.
*/
private String makeGameAddress(String gameName) throws InternalError {
try {
String hashedName = Utils.hash512(gameName.getBytes("UTF-8"));
return xoNameSpace + hashedName.substring(0, 64);
} catch (UnsupportedEncodingException e) {
throw new InternalError("Internal Error: " + e.toString());
}
}
/**
* Helper function to retrieve the correct game info from the list of game data CSV.
*/
private String getGameCsv(String stateEntry, String gameName) {
ArrayList<String> gameCsvList = new ArrayList<>(Arrays.asList(stateEntry.split("\\|")));
for (String gameCsv : gameCsvList) {
if (gameCsv.regionMatches(0, gameName, 0, gameName.length())) {
return gameCsv;
}
}
return "";
}
/**
* Helper function to store state data.
*/
private void storeGameData(String address, GameData gameData, String stateEntry, State stateStore)
throws InternalError, InvalidTransactionException {
String gameDataCsv = String.format("%s,%s,%s,%s,%s",
gameData.gameName, gameData.board, gameData.state, gameData.playerOne, gameData.playerTwo);
if (stateEntry.length() == 0) {
stateEntry = gameDataCsv;
} else {
ArrayList<String> dataList = new ArrayList<>(Arrays.asList(stateEntry.split("\\|")));
for (int i = 0; i <= dataList.size(); i++) {
if (i == dataList.size()
|| dataList.get(i).regionMatches(0, gameData.gameName, 0, gameData.gameName.length())) {
dataList.set(i, gameDataCsv);
break;
}
}
stateEntry = StringUtils.join(dataList, "|");
}
ByteString csvByteString = ByteString.copyFromUtf8(stateEntry);
Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<>(address, csvByteString);
Collection<Map.Entry<String, ByteString>> addressValues = Collections.singletonList(entry);
Collection<String> addresses = stateStore.set(addressValues);
if (addresses.size() < 1) {
throw new InternalError("State Error");
}
}
/**
* Function that handles game logic.
*/
private GameData playXo(TransactionData transactionData, GameData gameData, String player)
throws InvalidTransactionException, InternalError {
switch (transactionData.action) {
case "create":
return applyCreate(transactionData, gameData, player);
case "take":
return applyTake(transactionData, gameData, player);
default:
throw new InvalidTransactionException(String.format(
"Invalid action: %s", transactionData.action));
}
}
/**
* Function that handles game logic for 'create' action.
*/
private GameData applyCreate(TransactionData transactionData, GameData gameData, String player)
throws InvalidTransactionException {
if (!gameData.board.equals("")) {
throw new InvalidTransactionException("Invalid Action: Game already exists");
}
display(String.format("Player %s created a game", abbreviate(player)));
return new GameData(transactionData.gameName, "---------", "P1-NEXT", "", "");
}
/**
* Function that handles game logic for 'take' action.
*/
private GameData applyTake(TransactionData transactionData, GameData gameData, String player)
throws InvalidTransactionException, InternalError {
if (Arrays.asList("P1-WIN", "P2-WIN", "TIE").contains(gameData.state)) {
throw new InvalidTransactionException("Invalid action: Game has ended");
}
if (gameData.board.equals("")) {
throw new InvalidTransactionException("Invalid action: 'take' requires an existing game");
}
if (!Arrays.asList("P1-NEXT", "P2-NEXT").contains(gameData.state)) {
throw new InternalError(String.format(
"Internal Error: Game has reached an invalid state: %s", gameData.state));
}
// Assign players if new game
String updatedPlayerOne = gameData.playerOne;
String updatedPlayerTwo = gameData.playerTwo;
if (gameData.playerOne.equals("")) {
updatedPlayerOne = player;
} else if (gameData.playerTwo.equals("")) {
updatedPlayerTwo = player;
}
// Verify player identity and take space
int space = Integer.parseInt(transactionData.space);
char[] boardList = gameData.board.toCharArray();
String updatedState;
if (boardList[space - 1] != '-') {
throw new InvalidTransactionException("Space already taken");
}
if (gameData.state.equals("P1-NEXT") && player.equals(updatedPlayerOne)) {
boardList[space - 1] = 'X';
updatedState = "P2-NEXT";
} else if (gameData.state.equals("P2-NEXT") && player.equals(updatedPlayerTwo)) {
boardList[space - 1] = 'O';
updatedState = "P1-NEXT";
} else {
throw new InvalidTransactionException(String.format(
"Not this player's turn: %s", abbreviate(player)));
}
String updatedBoard = String.valueOf(boardList);
updatedState = determineState(boardList, updatedState);
GameData updatedGameData = new GameData(
gameData.gameName, updatedBoard, updatedState, updatedPlayerOne, updatedPlayerTwo);
display(
String.format("Player %s takes space %d \n", abbreviate(player), space)
+ gameDataToString(updatedGameData));
return updatedGameData;
}
/**
* Helper function that updates game state based on the current board position.
*/
private String determineState(char[] boardList, String state) {
if (isWin(boardList, 'X')) {
state = "P1-WIN";
} else if (isWin(boardList, 'O')) {
state = "P2-WIN";
} else if (!(String.valueOf(boardList).contains("-"))) {
state = "TIE";
}
return state;
}
/**
* Helper function that analyzes board position to determine if it is in a winning state.
*/
private boolean isWin(char[] board, char letter) {
int[][] wins = new int[][]{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{1, 4, 7}, {2, 5, 8}, {3, 6, 9},
{1, 5, 9}, {3, 5, 7},
};
for (int[] win : wins) {
if (board[win[0] - 1] == letter
&& board[win[1] - 1] == letter
&& board[win[2] - 1] == letter) {
return true;
}
}
return false;
}
/**
* Helper function to create an ASCII representation of the board.
*/
private String gameDataToString(GameData gameData) {
String out = "";
out += String.format("GAME: %s\n", gameData.gameName);
out += String.format("PLAYER 1: %s\n", abbreviate(gameData.playerOne));
out += String.format("PLAYER 2: %s\n", abbreviate(gameData.playerTwo));
out += String.format("STATE: %s\n", gameData.state);
out += "\n";
char[] board = gameData.board.replace('-',' ').toCharArray();
out += String.format("%c | %c | %c\n", board[0], board[1], board[2]);
out += "---|---|---\n";
out += String.format("%c | %c | %c\n", board[3], board[4], board[5]);
out += "---|---|---\n";
out += String.format("%c | %c | %c\n", board[6], board[7], board[8]);
return out;
}
/**
* Helper function to print game data to the logger.
*/
private void display(String msg) {
String displayMsg = "";
int length = 0;
String[] msgLines = msg.split("\n");
if (msg.contains("\n")) {
for (String line : msgLines) {
if (line.length() > length) {
length = line.length();
}
}
} else {
length = msg.length();
}
displayMsg = displayMsg.concat("\n+" + printDashes(length + 2) + "+\n");
for (String line : msgLines) {
displayMsg = displayMsg.concat("+" + StringUtils.center(line, length + 2) + "+\n");
}
displayMsg = displayMsg.concat("+" + printDashes(length + 2) + "+");
logger.info(displayMsg);
}
/**
* Helper function to create a string with a specified number of dashes (for logging purposes).
*/
private String printDashes(int length) {
String dashes = "";
for (int i = 0; i < length; i++) {
dashes = dashes.concat("-");
}
return dashes;
}
/**
* Helper function to shorten a string to a max of 6 characters for logging purposes.
*/
private Object abbreviate(String player) {
return player.substring(0, Math.min(player.length(), 6));
}
}
| 34.465721
| 100
| 0.65711
|
e4bbef930b68958630108303d41e331a6bf1b765
| 3,066
|
/*
* Copyright (c) 2018, Gobinath Loganathan (http://github.com/slgobinath) All Rights Reserved.
*
* Gobinath 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. In addition, if you are using
* this file in your research work, you are required to cite
* WISDOM as mentioned at https://github.com/slgobinath/wisdom.
* 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.javahelps.wisdom.dev.util;
import com.google.gson.Gson;
import com.javahelps.wisdom.core.event.Event;
import com.javahelps.wisdom.dev.optimize.multivariate.Constraint;
import java.util.List;
import java.util.Map;
public class Utility {
private static final Gson gson = new Gson();
private Utility() {
}
public static Constraint[] velocityBound(Constraint... bounds) {
int length = bounds.length;
Constraint[] velocityBounds = new Constraint[length];
for (int i = 0; i < length; i++) {
double max = Math.abs(bounds[i].getHigh() - bounds[i].getLow());
double min = -max;
velocityBounds[i] = new Constraint(min, max);
}
return velocityBounds;
}
public static int getMinPos(double[] list) {
int pos = 0;
double minValue = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < minValue) {
pos = i;
minValue = list[i];
}
}
return pos;
}
/**
* Convert JSON string to java.util.Map.
*
* @param jsonString
* @return
*/
public static Map<String, Object> toMap(String jsonString) {
return gson.fromJson(jsonString, Map.class);
}
/**
* Convert given java.util.Map to JSON string.
*
* @param data
* @return
*/
public static String toJson(Map<String, ?> data) {
return gson.toJson(data);
}
/**
* Create a JSON string containing all attributes of the event.
*
* @param event Wisdom event
* @return JSON string
*/
public static String toJson(Event event) {
return gson.toJson(event.getData());
}
/**
* Create a JSON string array containing attributes of all events.
*
* @param events a list of Wisdom events
* @return JSON string
*/
public static String toJson(List<Event> events) {
int length = events.size();
Map<String, Object>[] dataArray = new Map[length];
for (int i = 0; i < length; i++) {
dataArray[i] = events.get(i).getData();
}
return gson.toJson(dataArray);
}
}
| 28.12844
| 94
| 0.616438
|
2bed2952c061176cdeb4d144aa16b437e1814400
| 1,635
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FRC Team 4639. 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.subsystems;
import edu.wpi.first.wpilibj.SPI.Port;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import com.kauailabs.navx.frc.AHRS;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
public class DriveTrainSys extends InjectedSubsystem {
private static final int frontLeftPort = 0;
private static final int frontRightPort = 1;
private final DifferentialDrive drive;
private final Solenoid front, rear;
private final AHRS navx;
public DriveTrainSys() {
WPI_TalonSRX frontLeft = new WPI_TalonSRX(frontLeftPort);
WPI_TalonSRX frontRight = new WPI_TalonSRX(frontRightPort);
navx = new AHRS(Port.kMXP);
front = new Solenoid(0, 0);
rear = new Solenoid(0, 1);
frontLeft.configFactoryDefault();
frontRight.configFactoryDefault();
drive = new DifferentialDrive(frontLeft, frontRight);
}
public AHRS getAhrs() {
return navx;
}
public void drive(double speed, double rotation) {
drive.arcadeDrive(speed, rotation);
}
public void setFrontSolenoid(boolean on) {
front.set(on);
}
public void setRearSolenoid(boolean on) {
rear.set(on);
}
}
| 29.196429
| 80
| 0.637309
|
cd52cc3a9c971a9abf6c603a4b7cac3c511ac74d
| 1,657
|
/*******************************************************************************
* Copyright (c) 2013, 2015 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andrew Eidsness - Initial implementation
*******************************************************************************/
package org.eclipse.cdt.core.dom.ast.tag;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IBinding;
/**
* Implementations are contributed with the org.eclipse.cdt.core.tagger extension-point.
* The implementation is responsible for populating the tag's data using a given input binding.
*
* @see #process(ITagWriter, IBinding, IASTName)
* @since 5.5
*/
public interface IBindingTagger {
/**
* Examines the given input binding to decide if a tag should be created. Use the given
* tagWriter to create data if needed. Return the tag if one was created and null otherwise.
* A tagger (as identified by it's unique id string) is allowed to create only one tag for each
* binding.
*
* @param tagWriter
* the writer to use for creating new tags
* @param binding
* the binding to examine when populating the tag (if needed)
* @param ast
* the AST name from which the binding was created
* @return the tag if one was created and null otherwise
*/
public ITag process(ITagWriter tagWriter, IBinding binding, IASTName ast);
}
| 41.425
| 96
| 0.657212
|
5e90fc8c25fdd381a55c01812517dac7d3caed69
| 2,277
|
/*
* Copyright (c) 2018. Age of the Phoenix and B. H. Gorden. All rights reserved.
*/
package com.infiniteeggcreations.aopcraft.core.objects.item;
import com.infiniteeggcreations.aopcraft.core.AoPCraft;
import com.infiniteeggcreations.aopcraft.core.client.gui.GuiBookMaroon;
import com.infiniteeggcreations.aopcraft.core.init.AoPItemInit;
import com.infiniteeggcreations.aopcraft.core.util.interfaces.IHasModel;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
/**
* Reference: https://www.youtube.com/watch?v=rQLhheYcnrY
*
* This item is used to display a written page on the player screen (HUD).
*/
public class ItemBookMaroon extends Item implements IHasModel
{
// ========== Constructor ==========
public ItemBookMaroon(String name)
{
setUnlocalizedName(name);
setRegistryName(name);
setMaxStackSize(1);
setCreativeTab(AoPCraft.AOPCRAFTTAB);
AoPItemInit.ITEMS.add(this);
}
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
{
if(!worldIn.isRemote)
{
playerIn.sendMessage(new TextComponentString("Hmm, nothing is written inside."));
playerIn.sendMessage(new TextComponentString("How disappointing..."));
}
else
{
// Right clicking the note, the message will appear on the HUD:
Minecraft.getMinecraft().displayGuiScreen(new GuiBookMaroon());
}
return super.onItemRightClick(worldIn, playerIn, handIn);
}
@Override
public boolean isDamageable()
{
return false;
}
@Override
public boolean canHarvestBlock(IBlockState blockIn)
{
return false;
}
@Override
public void registerModels()
{
AoPCraft.proxy.registerItemRenderer(this, 0, "inventory");
}
}
| 31.191781
| 107
| 0.674572
|
44b1122a3dd7097a6e56e773430ed8a660fd1697
| 1,838
|
package org.bc.pqc.crypto.gmss.util;
public class GMSSUtil {
public byte[] intToBytesLittleEndian(int var1) {
byte[] var2 = new byte[]{(byte)(var1 & 255), (byte)(var1 >> 8 & 255), (byte)(var1 >> 16 & 255), (byte)(var1 >> 24 & 255)};
return var2;
}
public int bytesToIntLittleEndian(byte[] var1) {
return var1[0] & 255 | (var1[1] & 255) << 8 | (var1[2] & 255) << 16 | (var1[3] & 255) << 24;
}
public int bytesToIntLittleEndian(byte[] var1, int var2) {
return var1[var2++] & 255 | (var1[var2++] & 255) << 8 | (var1[var2++] & 255) << 16 | (var1[var2] & 255) << 24;
}
public byte[] concatenateArray(byte[][] var1) {
byte[] var2 = new byte[var1.length * var1[0].length];
int var3 = 0;
for(int var4 = 0; var4 < var1.length; ++var4) {
System.arraycopy(var1[var4], 0, var2, var3, var1[var4].length);
var3 += var1[var4].length;
}
return var2;
}
public void printArray(String var1, byte[][] var2) {
System.out.println(var1);
int var3 = 0;
for(int var4 = 0; var4 < var2.length; ++var4) {
for(int var5 = 0; var5 < var2[0].length; ++var5) {
System.out.println(var3 + "; " + var2[var4][var5]);
++var3;
}
}
}
public void printArray(String var1, byte[] var2) {
System.out.println(var1);
int var3 = 0;
for(int var4 = 0; var4 < var2.length; ++var4) {
System.out.println(var3 + "; " + var2[var4]);
++var3;
}
}
public boolean testPowerOfTwo(int var1) {
int var2;
for(var2 = 1; var2 < var1; var2 <<= 1) {
;
}
return var1 == var2;
}
public int getLog(int var1) {
int var2 = 1;
for(int var3 = 2; var3 < var1; ++var2) {
var3 <<= 1;
}
return var2;
}
}
| 25.527778
| 128
| 0.520675
|
bad09d7fd5fd13192421659664a50ce099ce7d98
| 3,527
|
package GameConsole.Core;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;
import GameConsole.Model.Player.Player;
import GameConsole.View.LogPanel;
/**
* This class is for single game mode
*/
public class SingleGameMode extends SwingWorker<Boolean, Boolean> {
private GameState gameState;
private List<Player> players;
private WindowMain win;
private LogPanel lp = LogPanel.getInstance();
private final int sleepTime = 300;
/**
* Constructor for SingleGameMode class
*
* @param gs
* game state with GameState type
*/
public SingleGameMode(GameState gs) {
this.gameState = gs;
this.win = gs.getWindow();
this.players = gs.getAllPlayers().getPlayers();
}
/**
* This method is mainly to display the detail of the game on the log panel
*
* @return true if the game is end otherwise return false
* @throws Exception
*/
@Override
protected Boolean doInBackground() throws Exception {
Player tempP = gameState.getCurrPlayer();
while (true) {
System.out.println(tempP.getName() + " inits " + tempP.getInitTroop());
updateLabel();
Thread.sleep(sleepTime);
lp.addLog("=====It's " + gameState.getCurrPlayer().getName() + "'s turn.=====");
tempP.reinforce();
gameState.setNextPlayer();
gameState.updateCountryLabels();
tempP = gameState.getCurrPlayer();
updateLabel();
boolean isFinished = true;
for (Player p : players) {
if (p.getInitTroop() > 0)
isFinished = false;
}
if (isFinished)
break;
}
gameState.setFirstRound(2);
while (true) {
Player currPlayer = gameState.getCurrPlayer();
lp.addLog("=====It's " + currPlayer.getName() + "'s turn.=====");
if (currPlayer.getStrategy().getName().equals("Human")) {
currPlayer.setInitTroop(currPlayer.getBonus());
} else {
currPlayer.setInitTroop(currPlayer.getBonusAndChangeCard());
}
updateLabel();
Thread.sleep(sleepTime);
currPlayer.reinforce();
gameState.updateCountryLabels();
gameState.setNextPhase();
clearLabel();
System.out.println("attack");
Thread.sleep(sleepTime);
currPlayer.attack();
gameState.updateCountryLabels();
if (gameState.getCurrPhase() == 1) {
gameState.setNextPhase();
}
clearLabel();
if (gameState.getCurrPlayer().checkWinGame()) {
win.initializeEndGame();
return true;
}
System.out.println("fortify");
Thread.sleep(sleepTime);
currPlayer.fortify();
gameState.updateCountryLabels();
if (gameState.getCurrPhase() == 2) {
gameState.setNextPhase();
}
clearLabel();
List<Player> removeList = new ArrayList<>();
for (Player p : players) {
if (p.getCountries().size() == 0) {
removeList.add(p);
}
System.out.println(p.getName() + ":" + p.getCountries().size());
}
this.players.removeAll(removeList);
lp.addLog("\r\n" + "Conquest Number:");
for (Player p : players) {
lp.addLog(p.getName() + " : " + p.getCountries().size() + " countries!");
}
gameState.setNextPlayer();
}
}
/**
* Method to set the labels clean
*/
public void clearLabel() {
gameState.setCountry1(null);
gameState.setCountry2(null);
gameState.setCurrClick(null);
}
/**
* Method to update the labels
*/
public void updateLabel() {
gameState.updateCountryLabels();
win.country1.setText((String) null);
win.country2.setText((String) null);
win.troopsLeft = gameState.getCurrPlayer().getInitTroop();
win.numberOfTroops.setText("" + win.troopsLeft);
}
}
| 23.513333
| 83
| 0.666572
|
83deed4791c2187640f989e957ea9da6a79aae93
| 4,146
|
/*
* Copyright (c) 2017-2020 Software Architecture Group, Hasso Plattner Institute
*
* Licensed under the MIT License.
*/
package de.hpi.swa.trufflesqueak.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import org.junit.Test;
import de.hpi.swa.trufflesqueak.interop.WrapToSqueakNode;
import de.hpi.swa.trufflesqueak.model.AbstractSqueakObject;
import de.hpi.swa.trufflesqueak.model.ArrayObject;
import de.hpi.swa.trufflesqueak.model.BooleanObject;
import de.hpi.swa.trufflesqueak.model.LargeIntegerObject;
import de.hpi.swa.trufflesqueak.model.NilObject;
public class SqueakPrimitiveTest extends AbstractSqueakTestCaseWithDummyImage {
@Test
public void testPrimEquivalent() {
final AbstractSqueakObject rcvr = image.specialObjectsArray;
assertTrue((boolean) runBinaryPrimitive(110, rcvr, rcvr));
assertFalse((boolean) runBinaryPrimitive(110, rcvr, NilObject.SINGLETON));
}
@Test
public void testPrimReplaceFromTo() {
final ArrayObject rcvr = image.asArrayOfObjects(NilObject.SINGLETON, BooleanObject.FALSE, BooleanObject.TRUE, image.characterClass, image.metaClass,
image.schedulerAssociation, image.smallIntegerClass, image.smalltalk,
image.specialObjectsArray);
assertSame(NilObject.SINGLETON, rcvr.getObject(0));
for (int i = 1; i < 8; i++) {
assertNotSame(NilObject.SINGLETON, rcvr.getObject(i));
}
final Object result = runQuinaryPrimitive(105, rcvr, 1L, 6L, ArrayObject.createEmptyStrategy(image, image.arrayClass, 10), 1L);
assertSame(result, rcvr);
for (int i = 0; i < 6; i++) {
assertSame(NilObject.SINGLETON, rcvr.getObject(i));
}
for (int i = 7; i < 8; i++) {
assertNotSame(NilObject.SINGLETON, rcvr.getObject(i));
}
}
@Test
public void testAdd() {
final Object[][] testValues = new Object[][]{
{(long) Integer.MAX_VALUE, (long) Integer.MAX_VALUE, 2 * (long) Integer.MAX_VALUE},
{Long.MAX_VALUE, Long.MAX_VALUE, new LargeIntegerObject(image, BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2)))},
{Long.MAX_VALUE, Long.MIN_VALUE, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(Long.MIN_VALUE)).longValue()}};
final WrapToSqueakNode wrapNode = WrapToSqueakNode.getUncached();
for (int i = 0; i < testValues.length; i++) {
final Object[] values = testValues[i];
assertEquals(wrapNode.executeWrap(values[2]), runBinaryPrimitive(1, wrapNode.executeWrap(values[0]), wrapNode.executeWrap(values[1])));
}
}
@Test
public void testSub() {
final Object[][] testValues = new Object[][]{
{(long) Integer.MAX_VALUE, (long) Integer.MAX_VALUE, 0L},
{Long.MAX_VALUE, Long.MAX_VALUE, 0L},
{Long.MAX_VALUE, Long.MAX_VALUE - 1, 1L},
{Long.MAX_VALUE, Long.MAX_VALUE - Integer.MAX_VALUE, (long) Integer.MAX_VALUE},
{Long.MIN_VALUE, 1L, new LargeIntegerObject(image, BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE))},
{Long.MAX_VALUE, Long.MAX_VALUE - Integer.MAX_VALUE, (long) Integer.MAX_VALUE}};
final WrapToSqueakNode wrapNode = WrapToSqueakNode.getUncached();
for (int i = 0; i < testValues.length; i++) {
final Object[] values = testValues[i];
assertEquals(wrapNode.executeWrap(values[2]), runBinaryPrimitive(2, wrapNode.executeWrap(values[0]), wrapNode.executeWrap(values[1])));
}
assertEquals(wrapNode.executeWrap(Long.MAX_VALUE),
runBinaryPrimitive(22, wrapNode.executeWrap(new LargeIntegerObject(image, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE))), wrapNode.executeWrap(1L)));
}
}
| 49.951807
| 183
| 0.668114
|
57761ee57b4b8140a986c2a724fae4f4a19860b6
| 1,090
|
package cn.bubi.baas.utils.http.agent;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
class HttpServiceConnection implements ServiceConnection{
private ServiceEndpoint endpoint;
private CloseableHttpClient httpClient;
HttpServiceConnection(ServiceEndpoint endpoint, CloseableHttpClient httpClient){
this.endpoint = endpoint;
this.httpClient = httpClient;
}
CloseableHttpClient getHttpClient(){
CloseableHttpClient cli = httpClient;
if (cli == null) {
throw new IllegalArgumentException("HttpServiceConnection has been closed!");
}
return cli;
}
@Override
public void close(){
CloseableHttpClient cli = httpClient;
if (cli != null) {
httpClient = null;
try {
cli.close();
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
@Override
public ServiceEndpoint getEndpoint(){
return endpoint;
}
}
| 24.772727
| 89
| 0.630275
|
6c6f55ce01cbfa2f05b8832a10290e74fede2c4d
| 7,162
|
package net.andreinc.markovneat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Character.toUpperCase;
import static java.util.stream.Collectors.toList;
/**
* An extension of the {@code MChain} class specialised in the generation of "English" text.
*/
public class MChainText extends MChain<String> {
private static final Pattern PT_PATTERN = Pattern.compile("[\\p{Punct}\\s]+");
public MChainText() {
super();
}
public MChainText(final int noStates) {
super(noStates);
}
public MChainText(final int noStates, Random random) {
super(noStates, random);
}
/**
* Trains the chain using a txt file as the source.
* <p>
* Splits the text into words, removes quotes and trains the chain.
*
* @param path The path to the source text file.
*/
public void train(final Path path) {
try {
train(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public void train(final List<String> lines) {
final Iterator<String> wordsIt = lines.stream()
.map(line -> line.replaceAll("\"", ""))
.map(MChainText::split)
.map(words ->
words
.stream()
.map(word -> word.trim().toLowerCase())
.filter(word -> !"".equals(word))
.collect(toList())
)
.flatMap(List::stream)
.collect(toList())
.iterator();
train(wordsIt);
}
/**
* Generates random text starting with a supplied initial {@code MState<String>}.
* <p>
* If the state doesn't exist in the chain an {@code IllegalArgumentException} is thrown.
* <p>
* If the state starts with a "." a new random state will be arbitrary picked form the chain.
*
* @param approximateLength The approximate length of the text.
* The generated output can be smaller or bigger than the desired size with a few characters.
* @param state The initial state.
* @return The arbitrary generated text.
*/
public String generateText(final MState<String> state, final int approximateLength) {
if (chain.isEmpty()) {
throw new IllegalArgumentException("Markov chain is empty. Please train the chain first.");
}
if (approximateLength < 0) {
throw new IllegalArgumentException("The approximate text length cannot be a negative number.");
}
if (!chain.containsKey(state)) {
throw new IllegalArgumentException("The initial state cannot be found in the Markov Chain. Please use an existing state.");
}
final StringBuilder result = new StringBuilder();
MState<String> currentState = state;
// Avoid starting the text with punctuation
while (isPunctuation(currentState.data().getFirst())) {
currentState = randomState();
}
appendState(result, currentState);
// Finish abruptly if the first state gets bigger than the approximate size.
if (result.length() > approximateLength) {
return result.append(".").toString();
}
// Works until the approximate length is bigger than the actual length.
String cElement;
while (result.length() <= approximateLength) {
// If chain is not cyclic start from a random state again.
if (!chain.containsKey(currentState)) {
currentState = randomState();
}
cElement = chain.get(currentState).next();
if (!isPunctuation(cElement)) {
result.append(" ");
}
// If last element (before the space)
// in the result buffer is "." capitalise next String
if (result.charAt(result.length() - 2) == '.') {
result.append(capital(cElement));
} else {
result.append(cElement);
}
currentState = currentState.nextState(cElement);
}
// Even if the "dot" is not the last element in the chain
// Add it to the result.
return result.append(".").toString();
}
/**
* Generates text starting with an arbitrary state from the chain.
*
* @param approximateLength The approximate length of the text.
* The generated output can be smaller or bigger than the desired size with a few characters.
* @return Arbitrary text from the chain
*/
public String generateText(final int approximateLength) {
return generateText(randomState(), approximateLength);
}
/**
* Appends the initial state to the result buffer (StringBuilder)
*
* @param buff The buffer where the state is appended
* @param firstState The initial Markov Chain state
*/
private static void appendState(final StringBuilder buff, final MState<String> firstState) {
// Append first state to the buffer
for (final String element : firstState.data()) {
if (!isPunctuation(element)) {
buff.append(' ');
}
buff.append(element);
}
// Delete initial " " <space>"
buff.deleteCharAt(0);
// Replace the first character with the upper letter
final char newChar = toUpperCase(buff.charAt(0));
buff.deleteCharAt(0).insert(0, newChar);
}
/**
* Capitalise the first letter of a string. Locale is not taken into consideration.
*
* @param element
* @return
*/
private static String capital(final String element) {
return element.substring(0, 1).toUpperCase()
+ element.substring(1);
}
private static boolean isPunctuation(final String element) {
return PT_PATTERN.matcher(element).matches();
}
/**
* Splits a string by punctuation, keeping also the punctuation signs.
*
* @param source The strings to be split.
* @return
*/
private static final List<String> split(final String source) {
final List<String> result = new ArrayList<>();
final Matcher matcher = PT_PATTERN.matcher(source);
int last = 0;
int start = 0;
while (matcher.find()) {
start = matcher.start();
if (last != start) {
result.add(source.substring(last, start));
}
final String delim = matcher.group();
result.add(delim);
final int end = matcher.end();
last = end;
}
if (last != source.length()) {
result.add(source.substring(last));
}
return result;
}
}
| 31.550661
| 135
| 0.580564
|
8616f64f6c6ea375ee7b7def7d79d6ec37de19ca
| 2,709
|
package datadog.trace.core;
import static datadog.trace.util.DaemonThreadFactory.TRACE_MONITOR;
import java.util.concurrent.TimeUnit;
import org.jctools.queues.MessagePassingQueue;
import org.jctools.queues.MpscBlockingConsumerArrayQueue;
class PendingTraceBuffer implements AutoCloseable {
private static final int BUFFER_SIZE = 1 << 12; // 4096
private final long FORCE_SEND_DELAY_MS = TimeUnit.SECONDS.toMillis(5);
private final long SEND_DELAY_NS = TimeUnit.MILLISECONDS.toNanos(500);
private final long SLEEP_TIME_MS = 100;
private final MpscBlockingConsumerArrayQueue<PendingTrace> queue =
new MpscBlockingConsumerArrayQueue<>(BUFFER_SIZE);
private final Thread worker = TRACE_MONITOR.newThread(new Worker());
private volatile boolean closed = false;
/** if the queue is full, pendingTrace trace will be written immediately. */
public void enqueue(PendingTrace pendingTrace) {
if (!queue.offer(pendingTrace)) {
// Queue is full, so we can't buffer this trace, write it out directly instead.
pendingTrace.write();
}
}
public void start() {
worker.start();
}
@Override
public void close() {
closed = true;
worker.interrupt();
}
public void flush() {
queue.drain(WriteDrain.WRITE_DRAIN);
}
private static final class WriteDrain implements MessagePassingQueue.Consumer<PendingTrace> {
private static final WriteDrain WRITE_DRAIN = new WriteDrain();
@Override
public void accept(PendingTrace pendingTrace) {
pendingTrace.write();
}
}
private final class Worker implements Runnable {
@Override
public void run() {
try {
while (!closed && !Thread.currentThread().isInterrupted()) {
PendingTrace pendingTrace = queue.take(); // block until available.
long oldestFinishedTime = pendingTrace.oldestFinishedTime();
long finishTimestampMillis = TimeUnit.NANOSECONDS.toMillis(oldestFinishedTime);
if (finishTimestampMillis <= System.currentTimeMillis() - FORCE_SEND_DELAY_MS) {
// Root span is getting old. Send the trace to avoid being discarded by agent.
pendingTrace.write();
continue;
}
if (pendingTrace.lastReferencedNanosAgo(SEND_DELAY_NS)) {
// Trace has been unmodified long enough, go ahead and write whatever is finished.
pendingTrace.write();
} else {
// Trace is too new. Requeue it and sleep to avoid a hot loop.
enqueue(pendingTrace);
Thread.sleep(SLEEP_TIME_MS);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
| 31.5
| 95
| 0.6866
|
9d360febe67f20364e8146e772389bdcadeb93de
| 728
|
package nl.underkoen.jetbrains.adventofcode.general.tree;
import javax.swing.tree.TreeNode;
import java.util.Enumeration;
public interface TreeLeaf<T extends TreeNode> extends TreeNode {
@Override
default TreeNode getChildAt(int childIndex) {
return null;
}
@Override
default int getChildCount() {
return 0;
}
@Override
T getParent();
@Override
default int getIndex(TreeNode node) {
return -1;
}
@Override
default boolean getAllowsChildren() {
return false;
}
@Override
default boolean isLeaf() {
return true;
}
@Override
default Enumeration<? extends TreeNode> children() {
return null;
}
}
| 18.2
| 64
| 0.633242
|
56bba677cd2048597ec09aea7730a729fea96d3f
| 882
|
package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.Com4jObject;
import com4j.DISPID;
import com4j.DefaultValue;
import com4j.Holder;
import com4j.IID;
import com4j.NativeType;
import com4j.Optional;
import com4j.ReturnValue;
import com4j.VTID;
@IID("{9CE1D9AD-3CCE-4FE2-B750-350947B0ED77}")
public abstract interface IExcelReportQuery
extends Com4jObject
{
@DISPID(1)
@VTID(7)
public abstract void setParamValue(String paramString1, String paramString2);
@DISPID(2)
@VTID(8)
@ReturnValue(type=NativeType.Dispatch)
public abstract Com4jObject execute(int paramInt, Holder<Integer> paramHolder, @Optional @DefaultValue("0") boolean paramBoolean);
@DISPID(3)
@VTID(9)
public abstract void cancel();
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IExcelReportQuery
* JD-Core Version: 0.7.0.1
*/
| 25.2
| 132
| 0.751701
|
e9634e228df65b24413d605c810f447a918f62c5
| 262
|
package nl.gridshore.dwes.index;
/**
* Exception thrown when the index creator was mis configured.
*/
public class IndexCreatorConfigException extends RuntimeException {
public IndexCreatorConfigException(String message) {
super(message);
}
}
| 23.818182
| 67
| 0.748092
|
3d8f7ab733fc8ad7f56baf074db2654747f92b87
| 1,505
|
package blservice.customerblservice;
import java.rmi.Remote;
import java.util.ArrayList;
import util.ResultMessage;
import util.UserLimits;
import vo.CustomerAddVO;
import vo.CustomerVO;
import vo.UserVO;
/**
* created by zlk on 2017/10/21
*/
public interface CustomerBLService extends Remote{
//管理客户界面得到客户编号
/**
* 创建客户时得到客户编号
*
* @return customerID
* @author zlk
*
*/
public String getNewCustomerID();
//管理客户的步骤
/**
* 管理客户中的添加客户
*
* @param vo
* @return 处理信息
* @author zlk
*/
public ResultMessage addCustomer(CustomerVO vo);
/**
* 管理客户中的删除客户
*
* @param name
* @return 处理信息
* @author zlk
*/
public ResultMessage deleteCustomer(String customerID);
/**
* 通过关键字查找客户
*
* @param keywords
* @return 满足条件的客户
* @author zlk
*/
public ArrayList<CustomerVO> findCustomerByKeywords(String keywords);
/**
* 通过客户编号查找客户
*
* @param customerID
* @return 满足条件的客户
* @author zlk
*/
public ArrayList<CustomerVO> findCustomerByCustomerID(String customerID);
/**
* 不选择查找方式查找客户
*
* @param input
* @return
*/
public ArrayList<CustomerVO> findCustomer(String input);
/**
* 管理客户中的更新客户
*
* @param vo
* @return 处理信息
* @author zlk
*/
public ResultMessage updateCustomer(CustomerVO vo);
/**
* 展示所有客户
* @return
*/
public ArrayList<CustomerVO> show();
/**
* 得到所有业务员
* @return
*/
public ArrayList<UserVO> getAllSalesman();
/**
* 得到当前登录用户的权限
* @return
*/
public UserLimits getCurrentUserLimit();
}
| 16.722222
| 74
| 0.664452
|
404eceb3f1dc46de1d10ea560de46801dda33a4d
| 2,345
|
/*
* Copyright (c) 2014-2015 University of Ulm
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 components.scalability.aggregation;
import de.uniulm.omi.cloudiator.axe.aggregator.communication.rmi.AggregatorServiceAccess;
import java.rmi.RemoteException;
import models.ComposedMonitor;
import models.Monitor;
import models.service.ModelService;
import play.db.jpa.JPAApi;
/**
* Created by Frank on 30.07.2015.
*/
public class RemoveAggregation extends MonitorAggregation {
private final ModelService<ComposedMonitor> composedMonitorModelService;
private final JPAApi jpaApi;
public RemoveAggregation(Monitor monitor, ModelService<ComposedMonitor> composedMonitorModelService, JPAApi jpaApi) {
super(monitor);
this.composedMonitorModelService = composedMonitorModelService;
this.jpaApi = jpaApi;
}
@Override
public void execute(AggregatorServiceAccess service) {
try {
service.stopAggregation(getObject().getId());
try {
jpaApi.withTransaction(() -> {
ComposedMonitor entity = composedMonitorModelService.getById(getObject().getId());
if (entity == null) {
LOGGER.info("Could not remove stopped ComposedMonitor from DB, since it was not available.");
return;
}
composedMonitorModelService.delete(entity);
});
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
} catch (RemoteException e) {
LOGGER.error("Error when calling remote object to stop aggregation.");
}
}
}
| 34.485294
| 121
| 0.678038
|
71209c87ab3fd1ab4472bbbc2b848f4171261879
| 971
|
package com.guitar.store;
import java.util.Iterator;
import java.util.List;
public class FindGuitarTester {
public static void main(String[] args) {
// Set up Rick’s guitar inventory
Inventory inv = new Inventory();
GuitarSpec whatErinLikes = new GuitarSpec("Stratocastor", Builder.FENDER, Type.ELECTRIC, Wood.ALDER,
Wood.ALDER,12);
List<Guitar> matchingGuitars = inv.search(whatErinLikes);
if (!matchingGuitars.isEmpty()) {
for (Iterator<Guitar> i = matchingGuitars.iterator(); i.hasNext();) {
Guitar guitar = (Guitar) i.next();
System.out.println(" We have a " + guitar.getSpec().getBuilder() + " " + guitar.getSpec().getModel() + " "
+ guitar.getSpec().getType() + " guitar:\n " + guitar.getSpec().getBackwood() + " back and sides,\n "
+ guitar.getSpec().getTopwood() + " top.\n You can have it for only $" + guitar.getPrice() + "!\n ----");
}
} else {
System.out.println("Sorry, we have nothing for you");
}
}
}
| 33.482759
| 111
| 0.658084
|
30b21cadf480cd96534f57bf7e2a3741a48a2806
| 4,596
|
/*
* Copyright 2015 FUJITSU LIMITED.
*
* 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.o3project.ocnrm.rest;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import org.o3project.ocnrm.lib.OcnMFSequenceLib;
import org.o3project.ocnrm.odenos.lib.OdenOsPropertyLoader;
import org.o3project.ocnrm.odenos.lib.OdenOsSender;
import org.o3project.odenos.remoteobject.message.Request.Method;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class RMNodeRestApi extends ServerResource {
private Logger logger = LoggerFactory.getLogger(RMNodeRestApi.class);
private static OdenOsPropertyLoader loader = OdenOsPropertyLoader.getInstance();
private static final String RESTAPI_SUCCESS_MSG = loader.getRestAPIResultMsg();
private static final String RESTAPI_ERROR_MSG = loader.getRestAPIErrorMsg();
private static final String RESTAPI_SUCCESS = loader.getRestAPISuccess();
private static final String RESTAPI_ERROR = loader.getRestAPIError();
private static final String DRIVER = "optDriver";
private static final String SEQNO_PREFIX = "#";
private OcnMFSequenceLib mf = OcnMFSequenceLib.getInstance();
private String seqNo = "";
/**
* Creation REST API of initial resource information.
*
* <br><br>The return value is the following.
* <br>Example<br>
* {"ResultRevel":"0"}(Success)<br>
* {"ResultRevel":"1","ErrorMessage":"100 An error has occurred."}(Failure)
*
* @param nodeInfoFromMF Registered physical resource information
* @return 要求を受け付けた結果。
* @throws Representation
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@Post
public Representation createNodeInfo(String nodeInfoFromMF)
throws JSONException, JsonParseException, JsonMappingException, IOException {
seqNo = SEQNO_PREFIX + mf.requestNoToString();
logger.info(seqNo + "\t" + "createNodeInfo() Start");
logger.info(seqNo + "\t" + "getParam : " + nodeInfoFromMF);
final JSONObject jsonObj = new JSONObject(nodeInfoFromMF);
JSONObject result = new JSONObject();
if (jsonObj.has("lower")) {
logger.debug("make lower topology.");
Thread task = new Thread(new Runnable() {
@Override
public void run() {
OdenOsSender.getInstance()
.sendRequest("systemmanager", Method.PUT,
"components/" + DRIVER + "/settings/och/topology",
jsonObj.toString());
}
});
task.start();
result.put(RESTAPI_SUCCESS_MSG, RESTAPI_SUCCESS);
} else if (jsonObj.has("upper")) {
logger.debug("make upper topology.");
Thread task = new Thread(new Runnable() {
@Override
public void run() {
OdenOsSender.getInstance()
.sendRequest("systemmanager",
Method.PUT,
"components/" + DRIVER + "/settings/odu/topology",
jsonObj.toString());
}
});
task.start();
result.put(RESTAPI_SUCCESS_MSG, RESTAPI_SUCCESS);
} else {
result.put(RESTAPI_SUCCESS_MSG, RESTAPI_ERROR);
result.put(RESTAPI_ERROR_MSG, "100 An error has occurred.");
logger.info("物理リソース情報に不備があります");
}
logger.info(seqNo + "\t" + "response : " + result.toString());
logger.info(seqNo + "\t" + "createNodeInfo() End");
return new JsonRepresentation(result);
}
}
| 39.282051
| 89
| 0.646649
|
f88f5d12bf160a67bd896deb56003e8ede3707f0
| 5,385
|
package jadx.core.dex.info;
import jadx.api.plugins.input.data.AccessFlags;
import jadx.core.Consts;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class AccessInfo {
public static final int VISIBILITY_FLAGS = AccessFlags.PUBLIC | AccessFlags.PROTECTED | AccessFlags.PRIVATE;
private final int accFlags;
public enum AFType {
CLASS, FIELD, METHOD
}
private final AFType type;
public AccessInfo(int accessFlags, AFType type) {
this.accFlags = accessFlags;
this.type = type;
}
public boolean containsFlag(int flag) {
return (accFlags & flag) != 0;
}
public AccessInfo remove(int flag) {
if (containsFlag(flag)) {
return new AccessInfo(accFlags & ~flag, type);
}
return this;
}
public AccessInfo add(int flag) {
if (!containsFlag(flag)) {
return new AccessInfo(accFlags | flag, type);
}
return this;
}
public AccessInfo changeVisibility(int flag) {
int currentVisFlags = accFlags & VISIBILITY_FLAGS;
if (currentVisFlags == flag) {
return this;
}
int unsetAllVisFlags = accFlags & ~VISIBILITY_FLAGS;
return new AccessInfo(unsetAllVisFlags | flag, type);
}
public AccessInfo getVisibility() {
return new AccessInfo(accFlags & VISIBILITY_FLAGS, type);
}
public boolean isVisibilityWeakerThan(AccessInfo otherAccInfo) {
int thisVis = accFlags & VISIBILITY_FLAGS;
int otherVis = otherAccInfo.accFlags & VISIBILITY_FLAGS;
if (thisVis == otherVis) {
return false;
}
return orderedVisibility(thisVis) < orderedVisibility(otherVis);
}
private static int orderedVisibility(int flag) {
switch (flag) {
case AccessFlags.PRIVATE:
return 1;
case 0: // package-private
return 2;
case AccessFlags.PROTECTED:
return 3;
case AccessFlags.PUBLIC:
return 4;
default:
throw new JadxRuntimeException("Unexpected visibility flag: " + flag);
}
}
public boolean isPublic() {
return (accFlags & AccessFlags.PUBLIC) != 0;
}
public boolean isProtected() {
return (accFlags & AccessFlags.PROTECTED) != 0;
}
public boolean isPrivate() {
return (accFlags & AccessFlags.PRIVATE) != 0;
}
public boolean isPackagePrivate() {
return (accFlags & VISIBILITY_FLAGS) == 0;
}
public boolean isAbstract() {
return (accFlags & AccessFlags.ABSTRACT) != 0;
}
public boolean isInterface() {
return (accFlags & AccessFlags.INTERFACE) != 0;
}
public boolean isAnnotation() {
return (accFlags & AccessFlags.ANNOTATION) != 0;
}
public boolean isNative() {
return (accFlags & AccessFlags.NATIVE) != 0;
}
public boolean isStatic() {
return (accFlags & AccessFlags.STATIC) != 0;
}
public boolean isFinal() {
return (accFlags & AccessFlags.FINAL) != 0;
}
public boolean isConstructor() {
return (accFlags & AccessFlags.CONSTRUCTOR) != 0;
}
public boolean isEnum() {
return (accFlags & AccessFlags.ENUM) != 0;
}
public boolean isSynthetic() {
return (accFlags & AccessFlags.SYNTHETIC) != 0;
}
public boolean isBridge() {
return (accFlags & AccessFlags.BRIDGE) != 0;
}
public boolean isVarArgs() {
return (accFlags & AccessFlags.VARARGS) != 0;
}
public boolean isSynchronized() {
return (accFlags & (AccessFlags.SYNCHRONIZED | AccessFlags.DECLARED_SYNCHRONIZED)) != 0;
}
public boolean isTransient() {
return (accFlags & AccessFlags.TRANSIENT) != 0;
}
public boolean isVolatile() {
return (accFlags & AccessFlags.VOLATILE) != 0;
}
public boolean isModuleInfo() {
return (accFlags & AccessFlags.MODULE) != 0;
}
public AFType getType() {
return type;
}
public String makeString() {
StringBuilder code = new StringBuilder();
if (isPublic()) {
code.append("public ");
}
if (isPrivate()) {
code.append("private ");
}
if (isProtected()) {
code.append("protected ");
}
if (isStatic()) {
code.append("static ");
}
if (isFinal()) {
code.append("final ");
}
if (isAbstract()) {
code.append("abstract ");
}
if (isNative()) {
code.append("native ");
}
switch (type) {
case METHOD:
if (isSynchronized()) {
code.append("synchronized ");
}
if (isBridge()) {
code.append("/* bridge */ ");
}
if (Consts.DEBUG && isVarArgs()) {
code.append("/* varargs */ ");
}
break;
case FIELD:
if (isVolatile()) {
code.append("volatile ");
}
if (isTransient()) {
code.append("transient ");
}
break;
case CLASS:
if ((accFlags & AccessFlags.STRICT) != 0) {
code.append("strict ");
}
if (isModuleInfo()) {
code.append("/* module-info */ ");
}
if (Consts.DEBUG) {
if ((accFlags & AccessFlags.SUPER) != 0) {
code.append("/* super */ ");
}
if ((accFlags & AccessFlags.ENUM) != 0) {
code.append("/* enum */ ");
}
}
break;
}
if (isSynthetic()) {
code.append("/* synthetic */ ");
}
return code.toString();
}
public String visibilityName() {
if (isPackagePrivate()) {
return "package-private";
}
if (isPublic()) {
return "public";
}
if (isPrivate()) {
return "private";
}
if (isProtected()) {
return "protected";
}
throw new JadxRuntimeException("Unknown visibility flags: " + getVisibility());
}
public int rawValue() {
return accFlags;
}
@Override
public String toString() {
return "AccessInfo: " + type + " 0x" + Integer.toHexString(accFlags) + " (" + makeString() + ')';
}
}
| 21.454183
| 109
| 0.648839
|
4916bea61436e3bd22310360cc23b1262cb33ee5
| 3,694
|
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atlasmap.v2;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ActionParameter implements Serializable {
private static final long serialVersionUID = 1L;
protected List<String> values;
protected String name;
protected String displayName;
protected String description;
protected FieldType fieldType;
/**
* Gets the value of the values 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 values property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getValues().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
* @return A list of parameter values
*/
public List<String> getValues() {
if (values == null) {
values = new ArrayList<String>();
}
return this.values;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the displayName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDisplayName() {
return displayName;
}
/**
* Sets the value of the displayName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDisplayName(String value) {
this.displayName = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the fieldType property.
*
* @return
* possible object is
* {@link FieldType }
*
*/
public FieldType getFieldType() {
return fieldType;
}
/**
* Sets the value of the fieldType property.
*
* @param value
* allowed object is
* {@link FieldType }
*
*/
public void setFieldType(FieldType value) {
this.fieldType = value;
}
}
| 22.944099
| 82
| 0.565782
|
f81b486e53809bdb29297e5268b0ad4859174dbf
| 385
|
package com.github.simondan.svl.app.communication;
import okhttp3.*;
/**
* @author Simon Danner, 09.11.2019
*/
interface IRestCallConfig<RESULT>
{
Class<RESULT> getResultType();
Request.Builder prepareRequest();
Call buildCall(Request.Builder pBuilder);
default Call justCreateCall()
{
return buildCall(prepareRequest());
}
Call createAuthenticationCall();
}
| 16.73913
| 50
| 0.727273
|
b0857b886214fd7d7e70a1f7f7bc265c2582ad1a
| 690
|
package com.chenxi.cebim.utils;
import java.text.DecimalFormat;
/**
* Created by qfdn on 2018/3/21.
*/
public class NumberUtil {
public static String numLengthControl(int i){
String str = (i+"").toString();
StringBuffer sb = new StringBuffer();
for(int j = 0; j < 2 - str.length(); j++) {
sb.append("0");
}
sb.append(str);
str = sb.toString();
return str;
}
/**
* double转String,保留小数点后两位
* @param num
* @return
*/
public static double doubleToString(double num){
//使用0.00不足位补0,#.##仅保留有效位
return Double.parseDouble(new DecimalFormat("0.00").format(num));
}
}
| 20.294118
| 73
| 0.55942
|
af66ac1983f750bed46bbbdb96212a708ded20ba
| 4,251
|
/*
* MIT License
*
* Copyright (c) 2020 ALİ GÜNGÖR
*
* 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 tr.havelsan.ueransim.nas.impl.ies;
import tr.havelsan.ueransim.nas.core.ProtocolEnum;
import tr.havelsan.ueransim.nas.core.ies.InformationElement4;
import tr.havelsan.ueransim.utils.OctetInputStream;
import tr.havelsan.ueransim.utils.OctetOutputStream;
import tr.havelsan.ueransim.utils.bits.Bit3;
import tr.havelsan.ueransim.utils.octets.Octet;
import tr.havelsan.ueransim.utils.octets.OctetString;
public class IENetworkName extends InformationElement4 {
public Bit3 numOfSpareBits;
public EAddCountryInitials addCi;
public ECodingScheme codingScheme;
public OctetString textString;
public IENetworkName() {
}
public IENetworkName(Bit3 numOfSpareBits, EAddCountryInitials addCi, ECodingScheme codingScheme, OctetString textString) {
this.numOfSpareBits = numOfSpareBits;
this.addCi = addCi;
this.codingScheme = codingScheme;
this.textString = textString;
}
@Override
protected IENetworkName decodeIE4(OctetInputStream stream, int length) {
int flags = stream.readOctetI();
var res = new IENetworkName();
res.numOfSpareBits = new Bit3(flags);
res.addCi = EAddCountryInitials.fromValue(flags >> 3 & 0b1);
res.codingScheme = ECodingScheme.fromValue(flags >> 4 & 0b111);
res.textString = stream.readOctetString(length - 1);
return res;
}
@Override
public void encodeIE4(OctetOutputStream stream) {
var flags = new Octet();
flags = flags.setBitRange(0, 2, numOfSpareBits.intValue());
flags = flags.setBit(3, addCi.intValue());
flags = flags.setBitRange(4, 6, codingScheme.intValue());
stream.writeOctet(flags);
stream.writeOctetString(textString);
}
public static class EAddCountryInitials extends ProtocolEnum {
public static final EAddCountryInitials SHOULD_NOT_ADD
= new EAddCountryInitials(0b0, "The MS should not add the letters for the Country's Initials to the text string");
public static final EAddCountryInitials SHOULD_ADD
= new EAddCountryInitials(0b1, "The MS should add the letters for the Country's Initials and a separator (e.g. a space) to the text string");
private EAddCountryInitials(int value, String name) {
super(value, name);
}
public static EAddCountryInitials fromValue(int value) {
return fromValueGeneric(EAddCountryInitials.class, value, null);
}
}
public static class ECodingScheme extends ProtocolEnum {
public static final ECodingScheme DEFAULT
= new ECodingScheme(0b000, "Cell Broadcast data coding scheme, GSM default alphabet, language unspecified, defined in 3GPP TS 23.038");
public static final ECodingScheme UCS2
= new ECodingScheme(0b001, "UCS2 (16 bit)");
private ECodingScheme(int value, String name) {
super(value, name);
}
public static ECodingScheme fromValue(int value) {
return fromValueGeneric(ECodingScheme.class, value, null);
}
}
}
| 41.271845
| 157
| 0.711127
|
90edd477447ab689f919cb1fa92e4565ab786c44
| 5,851
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Copyright (C) 2019 The Android Open Source Project
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Licensed under the Apache License, Version 2.0 (the "License");
end_comment
begin_comment
comment|// you may not use this file except in compliance with the License.
end_comment
begin_comment
comment|// You may obtain a copy of the License at
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// http://www.apache.org/licenses/LICENSE-2.0
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Unless required by applicable law or agreed to in writing, software
end_comment
begin_comment
comment|// distributed under the License is distributed on an "AS IS" BASIS,
end_comment
begin_comment
comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
end_comment
begin_comment
comment|// See the License for the specific language governing permissions and
end_comment
begin_comment
comment|// limitations under the License.
end_comment
begin_package
DECL|package|com.google.gerrit.acceptance.server.event
package|package
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|server
operator|.
name|event
package|;
end_package
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|truth
operator|.
name|Truth
operator|.
name|assertThat
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|AbstractDaemonTest
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|ExtensionRegistry
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|ExtensionRegistry
operator|.
name|Registration
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|NoHttpd
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|acceptance
operator|.
name|config
operator|.
name|GerritConfig
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|events
operator|.
name|RevisionCreatedListener
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Inject
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
annotation|@
name|NoHttpd
DECL|class|EventPayloadIT
specifier|public
class|class
name|EventPayloadIT
extends|extends
name|AbstractDaemonTest
block|{
DECL|field|extensionRegistry
annotation|@
name|Inject
specifier|private
name|ExtensionRegistry
name|extensionRegistry
decl_stmt|;
annotation|@
name|Test
DECL|method|defaultOptions ()
specifier|public
name|void
name|defaultOptions
parameter_list|()
throws|throws
name|Exception
block|{
name|RevisionCreatedListener
name|listener
init|=
operator|new
name|RevisionCreatedListener
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|onRevisionCreated
parameter_list|(
name|Event
name|event
parameter_list|)
block|{
name|assertThat
argument_list|(
name|event
operator|.
name|getChange
argument_list|()
operator|.
name|submittable
argument_list|)
operator|.
name|isNotNull
argument_list|()
expr_stmt|;
name|assertThat
argument_list|(
name|event
operator|.
name|getRevision
argument_list|()
operator|.
name|files
argument_list|)
operator|.
name|isNotEmpty
argument_list|()
expr_stmt|;
block|}
block|}
decl_stmt|;
try|try
init|(
name|Registration
name|registration
init|=
name|extensionRegistry
operator|.
name|newRegistration
argument_list|()
operator|.
name|add
argument_list|(
name|listener
argument_list|)
init|)
block|{
name|createChange
argument_list|()
expr_stmt|;
block|}
block|}
annotation|@
name|Test
annotation|@
name|GerritConfig
argument_list|(
name|name
operator|=
literal|"event.payload.listChangeOptions"
argument_list|,
name|value
operator|=
literal|"SKIP_MERGEABLE"
argument_list|)
DECL|method|configuredOptions ()
specifier|public
name|void
name|configuredOptions
parameter_list|()
throws|throws
name|Exception
block|{
name|RevisionCreatedListener
name|listener
init|=
operator|new
name|RevisionCreatedListener
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|onRevisionCreated
parameter_list|(
name|Event
name|event
parameter_list|)
block|{
name|assertThat
argument_list|(
name|event
operator|.
name|getChange
argument_list|()
operator|.
name|submittable
argument_list|)
operator|.
name|isNull
argument_list|()
expr_stmt|;
name|assertThat
argument_list|(
name|event
operator|.
name|getChange
argument_list|()
operator|.
name|mergeable
argument_list|)
operator|.
name|isNull
argument_list|()
expr_stmt|;
name|assertThat
argument_list|(
name|event
operator|.
name|getRevision
argument_list|()
operator|.
name|files
argument_list|)
operator|.
name|isNull
argument_list|()
expr_stmt|;
name|assertThat
argument_list|(
name|event
operator|.
name|getChange
argument_list|()
operator|.
name|subject
argument_list|)
operator|.
name|isNotEmpty
argument_list|()
expr_stmt|;
block|}
block|}
decl_stmt|;
try|try
init|(
name|Registration
name|registration
init|=
name|extensionRegistry
operator|.
name|newRegistration
argument_list|()
operator|.
name|add
argument_list|(
name|listener
argument_list|)
init|)
block|{
name|createChange
argument_list|()
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 14.201456
| 83
| 0.811656
|
73fd86e1caac081d86a2b76168e9e92a956f3686
| 1,494
|
package org.hkyaxhfg.tat.springfox;
import springfox.documentation.schema.ScalarType;
/**
* springfox 数据类型.
*
* @author: wjf
* @date: 2022/1/12
*/
public enum DataType {
/**
* Int
*/
Int(ScalarType.INTEGER),
/**
* Long
*/
Long(ScalarType.LONG),
/**
* 日期
*/
Date(ScalarType.DATE),
/**
* 日期时间
*/
DateTime(ScalarType.DATE_TIME),
/**
* 字符串
*/
String(ScalarType.STRING),
/**
* 字节
*/
Byte(ScalarType.BYTE),
/**
* 二进制
*/
Binary(ScalarType.BINARY),
/**
* 密码
*/
Password(ScalarType.PASSWORD),
/**
* 布尔
*/
Boolean(ScalarType.BOOLEAN),
/**
* Double
*/
Double(ScalarType.DOUBLE),
/**
* Float
*/
Float(ScalarType.FLOAT),
/**
* BigInt
*/
BigInt(ScalarType.BIGINTEGER),
/**
* BigDecimal
*/
BigDecimal(ScalarType.BIGDECIMAL),
/**
* Uuid
*/
Uuid(ScalarType.UUID),
/**
* 邮箱
*/
Email(ScalarType.EMAIL),
/**
* 货币
*/
Currency(ScalarType.CURRENCY),
/**
* Uri
*/
Uri(ScalarType.URI),
/**
* Url
*/
Url(ScalarType.URL),
/**
* Object
*/
Object(ScalarType.OBJECT)
;
private final ScalarType scalarType;
DataType(ScalarType scalarType) {
this.scalarType = scalarType;
}
public ScalarType getScalarType() {
return scalarType;
}
}
| 14.792079
| 49
| 0.493307
|
c9a2d4beba801eaead59b0bfc411455184a4ff26
| 1,313
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBoxDemo extends JApplet implements ItemListener
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout());
// Create icons
ImageIcon normal = new ImageIcon("s1.jpg");
ImageIcon rollover = new ImageIcon("s2.jpg");
ImageIcon selected = new ImageIcon("s4.jpg");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C");
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
| 27.93617
| 67
| 0.718964
|
2606eae9ee66a017bfdd746d9cbe93628d42e240
| 1,746
|
package WayofTime.bloodmagic.util.helper;
import WayofTime.bloodmagic.core.data.Binding;
import WayofTime.bloodmagic.util.Constants;
import WayofTime.bloodmagic.event.ItemBindEvent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class BindableHelper {
public static void applyBinding(ItemStack stack, EntityPlayer player) {
Binding binding = new Binding(player.getGameProfile().getId(), player.getGameProfile().getName());
applyBinding(stack, binding);
}
public static void applyBinding(ItemStack stack, Binding binding) {
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setTag("binding", binding.serializeNBT());
}
/**
* Sets the Owner Name of the item without checking if it is already bound.
* Also bypasses {@link ItemBindEvent}.
*
* @param stack - The ItemStack to bind
* @param ownerName - The username to bind the ItemStack to
*/
public static void setItemOwnerName(ItemStack stack, String ownerName) {
stack = NBTHelper.checkNBT(stack);
stack.getTagCompound().setString(Constants.NBT.OWNER_NAME, ownerName);
}
/**
* Sets the Owner UUID of the item without checking if it is already bound.
* Also bypasses {@link ItemBindEvent}.
*
* @param stack - The ItemStack to bind
* @param ownerUUID - The UUID to bind the ItemStack to
*/
public static void setItemOwnerUUID(ItemStack stack, String ownerUUID) {
stack = NBTHelper.checkNBT(stack);
stack.getTagCompound().setString(Constants.NBT.OWNER_UUID, ownerUUID);
}
}
| 34.92
| 106
| 0.701031
|
10dac8600a2c27da9ef23037bce968fd29c694f8
| 1,636
|
package com.citrus.backoffice.jobapplication.domain;
import com.citrus.backoffice.employee.domain.Employee;
import com.citrus.backoffice.jobapplication.domain.valueobjects.ApplicationDate;
import com.citrus.backoffice.jobapplication.domain.valueobjects.ApplicationId;
import com.citrus.backoffice.jobapplication.domain.valueobjects.ApplicationStatus;
import com.citrus.backoffice.joboffer.domain.JobOffer;
import com.citrus.backoffice.shared.domain.valueobjects.DateFormat;
public class JobApplication {
ApplicationId id;
DateFormat date;
Employee employee;
JobOffer jobOffer;
ApplicationStatus status;
public JobApplication(ApplicationId id) {
this.id = id;
}
public static JobApplication createApplication(
ApplicationId id,
DateFormat date,
Employee employee,
JobOffer jobOffer,
ApplicationStatus status) {
var ja = new JobApplication(id);
ja.setDate(date);
ja.setEmployee(employee);
ja.setJobOffer(jobOffer);
ja.setStatus(status);
return ja;
}
public ApplicationId getId() {
return id;
}
public void setId(ApplicationId id) {
this.id = id;
}
public DateFormat getDate() {
return date;
}
public void setDate(DateFormat date) {
this.date = date;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public JobOffer getJobOffer() {
return jobOffer;
}
public void setJobOffer(JobOffer jobOffer) {
this.jobOffer = jobOffer;
}
public ApplicationStatus getStatus() {
return status;
}
public void setStatus(ApplicationStatus status) {
this.status = status;
}
}
| 21.526316
| 82
| 0.756724
|
a4dacd1a336dd300ee31d841ef6dd02b74d457e6
| 2,349
|
package network.warzone.tgm.nickname;
import lombok.Getter;
import lombok.Setter;
import network.warzone.tgm.TGM;
import network.warzone.warzoneapi.models.Punishment;
import network.warzone.warzoneapi.models.UserProfile;
public class NickedUserProfile extends UserProfile {
@Getter @Setter
private boolean frozen;
public NickedUserProfile(UserProfile profile) {
super(profile.getId(),
profile.getName(),
profile.getNameLower(),
profile.getUuid(),
profile.getInitialJoinDate(),
profile.getLastOnlineDate(),
profile.getIps(),
profile.getRanks(),
profile.getRanksLoaded(),
profile.getWins(),
profile.getLosses(),
profile.getKills(),
profile.getDeaths(),
profile.getWool_destroys(),
profile.getPunishments(),
profile.getTags(),
null,
profile.isNew());
this.frozen = false;
}
@Override
public void addKill() {
super.addKill();
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addKill();
}
@Override
public void addDeath() {
super.addDeath();
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addDeath();
}
@Override
public void addLoss() {
super.addLoss();
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addLoss();
}
@Override
public void addWin() {
super.addWin();
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addWin();
}
@Override
public void addWoolDestroy() {
super.addWoolDestroy();
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addWoolDestroy();
}
@Override
public void addPunishment(Punishment punishment) {
super.addPunishment(punishment);
if (!frozen) TGM.get().getPlayerManager().getPlayerContext(getUuid()).getUserProfile(true).addPunishment(punishment);
}
@Override
public boolean isStaff() {
return super.isStaff();
}
}
| 30.506494
| 125
| 0.610047
|
49186420330a5b2c6456b964c17998b2d33cced2
| 810
|
package com.jeet.jds;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ListExamples {
public static boolean run(){
List<String> stockList= Arrays.asList("AAPL","AMGN","AXP","BA","CAT","CRM","CSCO","CVX","DIS","DOW","GS","HD","HON","IBM","INTC","JNJ","JPM","KO",
"MCD","MMM","MRK","MSFT","NKE","PG","TRV","UNH","V","VZ","WBA","WMT");
System.out.println("List Size: " + stockList.size());
for (String stock :
stockList) {
System.out.println(stock);
}
Iterator<String> stringIterator=stockList.listIterator();
System.out.println("Using Iterator");
while (stringIterator.hasNext()){
System.out.println(stringIterator.next());
}
return true;
}
}
| 33.75
| 154
| 0.579012
|
1cf42090d53e482eb74b2c368ddc68a461d28777
| 7,927
|
package com.example.liangjie06.zuche.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.liangjie06.zuche.R;
import com.example.liangjie06.zuche.base.BaseActivity;
import com.example.liangjie06.zuche.bean.Account;
import com.example.liangjie06.zuche.bean.User;
import com.example.liangjie06.zuche.utils.ThreadPool;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
/**
* 通用Activity,用于加载Fragment。
*/
public class PayActivity extends BaseActivity {
private TextView id;
private TextView money;
private TextView bankCard;
private Button close;
private Button pay;
private LinearLayout llcard;
private User myUser;
private float allMoney;
private boolean isPay;
private ArrayList<Account> bankList;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
break;
case 1:
if (bankList.get(0)!=null){
String str = bankList.get(0).getBankCard().substring(bankList.get(0).getBankCard().length()-4,bankList.get(0).getBankCard().length());
bankCard.setText(bankList.get(0).getBank()+"("+str+")");
}else {
bankCard.setText("请添加银行卡");
}
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*setTheme(R.style.MyTheme_BackDialog);
Window window = getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
window.setGravity(Gravity.BOTTOM);
window.setAttributes(lp);*/
setContentView(R.layout.fragment_pay);
initView();
allMoney = getIntent().getFloatExtra("money", 0);
myUser = BmobUser.getCurrentUser(User.class);
getInfo();
initData();
}
private void initView(){
id = (TextView) findViewById(R.id.tv_account);
money = (TextView) findViewById(R.id.tv_money);
bankCard = (TextView) findViewById(R.id.bank_card_id);
close = (Button) findViewById(R.id.btn_close);
pay = (Button) findViewById(R.id.btn_pay);
llcard = (LinearLayout) findViewById(R.id.bankcard);
}
private void initData(){
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PayActivity.this.setResult(0);
PayActivity.this.finish();
}
});
pay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
String str = myUser.getUsername();
String temp = str.substring(3,str.length()-4 );
String newStr = str.replace(temp, "****");
id.setText(newStr);
Log.e("lj","allmoney"+allMoney);
money.setText(""+allMoney);
llcard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(),SelectBankCardActivity.class);
intent.putExtra("card", bankList);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
startActivityForResult(intent,11);
}
});
}
private void getInfo(){
ThreadPool.runOnPool(new Runnable() {
@Override
public void run() {
BmobQuery<Account> accountBmobQuery = new BmobQuery<Account>();
accountBmobQuery.addWhereEqualTo("userName",myUser.getUsername()).findObjects(new FindListener<Account>() {
@Override
public void done(List<Account> list, BmobException e) {
if (e == null){
bankList = (ArrayList<Account>) list;
Message msg= Message.obtain();
msg.what = 1;
Log.e("lj", "银行卡列表查询成功"+ list.size() );
mHandler.sendEmptyMessage(msg.what);
}else {
Message msg= Message.obtain();
msg.what = 0;
Log.e("lj", "银行卡列表查询失败"+e.toString());
mHandler.sendEmptyMessage(msg.what);
}
}
});
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 10){
Log.e("lj", "未选择银行卡,直接返回了");
}else {
String str = bankList.get(resultCode).getBankCard().substring(bankList.get(resultCode).getBankCard().length()-4,bankList.get(resultCode).getBankCard().length());
bankCard.setText(bankList.get(resultCode).getBank()+"("+str+")");
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
PayActivity.this.setResult(0);
PayActivity.this.finish();
}
private void showDialog() {
LayoutInflater li = LayoutInflater.from(mContext);
View promptsView = li.inflate(R.layout.dialog_pay_pwd, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.et_input);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("支付",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
if (!TextUtils.isEmpty(userInput.getText())) {
if ("123456".equals(String.valueOf(userInput.getText()))){
Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
Log.e("lj","ispay" +isPay);
PayActivity.this.setResult(1);
PayActivity.this.finish();
}else {
Log.e("lj","else ispay" +isPay);
Toast.makeText(mContext, "支付密码错误,请重试", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(mContext, "支付密码错误,请重试", Toast.LENGTH_SHORT).show();
}
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
| 36.362385
| 173
| 0.54901
|
abddd5d7581180834971b64811a3428fb5d00fb8
| 2,247
|
package com.cerner.jwala.ui.selenium.steps.admin;
import com.cerner.jwala.ui.selenium.component.JwalaUi;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.Properties;
/**
* Created by Sharvari Barve on 7/21/2017.
*/
public class AdminRunSteps {
@Autowired
private JwalaUi jwalaUi;
@Autowired
@Qualifier("parameterProperties")
private Properties paramProp;
@When("^I fill in the \"data to be secured\" field with \"(.*)\"$")
public void fillDataToEncrypt(String data) {
jwalaUi.sendKeys(By.xpath("//input[@class='toEncrypt']"), data);
}
@And("^I click the admin's tab \"(.*)\" button$")
public void clickEncryptBtn(final String btnLabel) {
jwalaUi.click(By.xpath("//button/span[text() = '" + btnLabel + "']"));
}
@Then("^I see the \"Encryption Succeeded\" message$")
public void verifyText() {
jwalaUi.find(By.xpath("//h4[text()='Encryption Succeeded']"));
}
@And("^I see the \"(.*)\" heading$")
public void verifyHeader(final String headerCaption) {
jwalaUi.find(By.xpath("//h3[text()='" + headerCaption + "']"));
}
@And("^I see \"(.*)\" in the \"(.*)\" text box$")
public void verifyTextAreaItem(final String itemName, final String textAreaHeading) {
final WebElement webElement = jwalaUi.find(By.xpath("//h3[text()='" + textAreaHeading + "']/following-sibling::p//textArea"));
final String val = webElement.getAttribute("value");
assert StringUtils.isNotEmpty(val) && val.contains(itemName);
}
@And("I see in the web banner that the client details = \"(.*)\" and data mode = \"(.*)\"")
public void verifyClientDetails(final String clientDetails, final String dataMode){
jwalaUi.find(By.xpath("//span[text() = '" + paramProp.getProperty(clientDetails) + "']"));
jwalaUi.find(By.xpath("//span[text() = '" + paramProp.getProperty(dataMode) + "']"));
}
}
| 37.45
| 134
| 0.660881
|
12e48d463fdfb05d5bf4137f1a7ee66372066a98
| 2,067
|
/* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.getstarted.background.objects;
// [START getting_started_background_translate_message]
public class TranslateMessage {
public String data;
public TranslateAttributes attributes;
public String messageId;
public String publishTime;
public String translatedText;
public String sourceLang = "en";
public String targetLang = "en";
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public TranslateAttributes getAttributes() {
return attributes;
}
public void setAttributes(TranslateAttributes attributes) {
this.attributes = attributes;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(String publishTime) {
this.publishTime = publishTime;
}
public String getTranslatedText() {
return translatedText;
}
public void setTranslatedText(String translatedText) {
this.translatedText = translatedText;
}
public String getSourceLang() {
return sourceLang;
}
public void setSourceLang(String sourceLang) {
this.sourceLang = sourceLang;
}
public String getTargetLang() {
return targetLang;
}
public void setTargetLang(String targetLang) {
this.targetLang = targetLang;
}
}
// [END getting_started_background_translate_message]
| 24.317647
| 75
| 0.730044
|
0dd8b2c3a489382a37465d395f3fe7f4a5576b0b
| 249
|
package BookRental;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface RentalStatusRepository extends CrudRepository<RentalStatus, Long> {
}
| 22.636364
| 84
| 0.839357
|
57a21cda6741dbed81f517b1ff5c69da19e0b575
| 1,411
|
package org.assertj.core.api;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class Assertions_sync_assertThatRuntimeException_with_BDDAssertions_and_WithAssertions_Test extends BaseAssertionsTest {
@Test
void Assertions_assertThatRuntimeException_and_BDDAssertions_thenRuntimeException_should_be_the_same() {
Method[] assertThatRuntimeExceptionInAssertions = findMethodsWithName(Assertions.class, "assertThatRuntimeException");
Method[] thenRuntimeExceptionInBDDAssertions = findMethodsWithName(BDDAssertions.class, "thenRuntimeException");
assertThat(thenRuntimeExceptionInBDDAssertions).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME)
.containsExactlyInAnyOrder(assertThatRuntimeExceptionInAssertions);
}
@Test
void Assertions_assertThatRuntimeException_and_WithAssertions_assertThatRuntimeException_should_be_the_same() {
Method[] assertThatRuntimeExceptionInAssertions = findMethodsWithName(Assertions.class, "assertThatRuntimeException");
Method[] assertThatRuntimeExceptionInWithAssertions = findMethodsWithName(WithAssertions.class, "assertThatRuntimeException");
assertThat(assertThatRuntimeExceptionInWithAssertions).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY)
.containsExactlyInAnyOrder(assertThatRuntimeExceptionInAssertions);
}
}
| 48.655172
| 130
| 0.8618
|
81291177c527d7e3abb7a5947fd7245e846d5453
| 3,560
|
package io.github.dunwu.javatool.monitor.zipkin;
import brave.CurrentSpanCustomizer;
import brave.SpanCustomizer;
import brave.Tracing;
import brave.context.log4j2.ThreadContextScopeDecorator;
import brave.http.HttpTracing;
import brave.httpclient.TracingHttpClientBuilder;
import brave.propagation.B3Propagation;
import brave.propagation.ExtraFieldPropagation;
import brave.propagation.ThreadLocalCurrentTraceContext;
import brave.spring.webmvc.DelegatingTracingFilter;
import brave.spring.webmvc.SpanCustomizingAsyncHandlerInterceptor;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import zipkin2.Span;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.Sender;
import zipkin2.reporter.okhttp3.OkHttpSender;
/**
* This adds tracing configuration to any web mvc controllers or rest template clients.
*
* <p>This is a {@link Initializer#getRootConfigClasses() root config class}, so the
* {@linkplain DelegatingTracingFilter} added in {@link Initializer#getServletFilters()} can wire up properly.
*/
@Configuration
// Importing this class is effectively the same as declaring bean methods
@Import(SpanCustomizingAsyncHandlerInterceptor.class)
public class TracingConfiguration extends WebMvcConfigurerAdapter {
/** Configuration for how to send spans to Zipkin */
@Bean
Sender sender() {
return OkHttpSender.create("http://127.0.0.1:9411/api/v2/spans");
}
/** Configuration for how to buffer spans into messages for Zipkin */
@Bean
AsyncReporter<Span> spanReporter() {
return AsyncReporter.create(sender());
}
/** Controls aspects of tracing such as the service name that shows up in the UI */
@Bean
Tracing tracing(@Value("${zipkin.service:brave-webmvc-example}") String serviceName) {
return Tracing.newBuilder()
.localServiceName(serviceName)
.propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(ThreadContextScopeDecorator.create()) // puts trace IDs into logs
.build()
)
.spanReporter(spanReporter()).build();
}
/** Allows someone to add tags to a span if a trace is in progress. */
@Bean
SpanCustomizer spanCustomizer(Tracing tracing) {
return CurrentSpanCustomizer.create(tracing);
}
/** Decides how to name and tag spans. By default they are named the same as the http method. */
@Bean
HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.create(tracing);
}
/** adds tracing to any underlying http client calls */
@Bean
HttpClient httpClient(HttpTracing httpTracing) {
return TracingHttpClientBuilder.create(httpTracing).build();
}
@Autowired
SpanCustomizingAsyncHandlerInterceptor serverInterceptor;
/** adds tracing to the application-defined web controller */
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(serverInterceptor);
}
}
| 39.120879
| 110
| 0.756461
|
64e7fd1701b68c471c28bfc3cd50a934be4d98c4
| 2,013
|
package com.example.android.camera2basic.camera2.util;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.view.Surface;
import androidx.annotation.NonNull;
public class NoOpCaptureCallback extends CameraCaptureSession.CaptureCallback {
@Override
public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
super.onCaptureStarted(session, request, timestamp, frameNumber);
}
@Override
public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
super.onCaptureProgressed(session, request, partialResult);
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
}
@Override
public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
super.onCaptureFailed(session, request, failure);
}
@Override
public void onCaptureSequenceCompleted(@NonNull CameraCaptureSession session, int sequenceId, long frameNumber) {
super.onCaptureSequenceCompleted(session, sequenceId, frameNumber);
}
@Override
public void onCaptureSequenceAborted(@NonNull CameraCaptureSession session, int sequenceId) {
super.onCaptureSequenceAborted(session, sequenceId);
}
@Override
public void onCaptureBufferLost(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull Surface target, long frameNumber) {
super.onCaptureBufferLost(session, request, target, frameNumber);
}
}
| 41.9375
| 152
| 0.784898
|
6e0056cbaf68b24ad0fda87073ec550511476bf8
| 578
|
package com.aliya.adapter.click;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* item长按事件的回调 - 接口
* 使用方式:让你的ViewHolder实现此接口
*
* @author a_liYa
* @date 2018/1/4 16:30.
*/
public interface ItemLongClickCallback {
/**
* 在 {@link OnItemLongClickListener#onItemLongClick(View, int)} 之后被调用
*
* @param itemView {@link RecyclerView.ViewHolder#itemView}
* @param position .
* @return true:表示处理 {@link View.OnLongClickListener#onLongClick(View)}
*/
boolean onItemLongClick(View itemView, int position);
}
| 22.230769
| 75
| 0.700692
|
a16c2fdf44c9f57ceada2a16ded365f62a0d000e
| 1,216
|
/**
* Copyright (C) 2006-2012 The Parancoe Team <info@parancoe.org>
*
* This file is part of Parancoe Plugin Spring Security Evolution.
*
* 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.parancoe.plugins.securityevolution;
/**
* Defines useful functions for security purpose
* @author Enrico Giurin
*
*/
public class SecureUtility {
/**
* Builds a new User with enable set to false and password equals to username.
* @param username
* @return
*/
public static User newUserToValidate(String username)
{
User user = new User();
user.setEnabled(false);
user.setUsername(username);
user.setPassword(username);
return user;
}
}
| 29.658537
| 80
| 0.705592
|
8cd9d2d47b9eaac25e0c22b8138027ee8193c8fb
| 437
|
import java.util.Arrays;
public class Decimal2Binary {
public static int[] dec2Bin(int n){
int noOfBits=(int) Math.floor(Math.log(n)/Math.log(2)) + 1;
int[] ans = new int[noOfBits];
int i = 0;
while(n!=0){
ans[i++] = n%2;
n = n/2;
}
return ans;
}
public static void main(String[] args) {
int[] n = dec2Bin(6);//n[0] = lsb, n[noOfBits-1] = msb
System.out.println(Arrays.toString(n));
}
}
| 20.809524
| 62
| 0.576659
|
6026d5f5aa94cd135d64f5beb3519919d5308a02
| 581
|
package crafttweaker.mc1120.entity;
import crafttweaker.api.entity.IEntityItem;
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.minecraft.CraftTweakerMC;
import net.minecraft.entity.item.EntityItem;
public class MCEntityItem extends MCEntity implements IEntityItem {
private final EntityItem item;
public MCEntityItem(EntityItem entityItem) {
super(entityItem);
item = entityItem;
}
@Override
public IItemStack getItem() {
return CraftTweakerMC.getIItemStack(item.getItem());
}
}
| 27.666667
| 68
| 0.710843
|
afd2fe6d2cfe646c82fbdeec153a60ea075f33d3
| 3,790
|
package com.github.example;
import com.fasterxml.jackson.annotation.JsonView;
import com.github.example.model.Order;
import com.github.example.model.Product;
import com.github.example.model.User;
import com.github.example.repository.OrderRepository;
import com.github.example.repository.ProductRepository;
import com.github.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.datatables.DataTablesInput;
import org.springframework.data.mongodb.datatables.DataTablesOutput;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.PostConstruct;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private UserRepository userRepository;
@PostConstruct
public void seed() {
if(orderRepository.count() == 0) {
List<Product> products = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
Product p = new Product();
p.setId(i + 1000);
p.setLabel("Product " + i);
p.setEnabled(i % 2 == 0);
p.setCreatedAt(LocalDateTime.now());
products.add(p);
}
productRepository.saveAll(products);
List<User> users = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
User u = new User();
u.setId(i);
u.setFirstName("Firstname");
u.setLastName("Lastname");
users.add(u);
}
userRepository.saveAll(users);
List<Order> orders = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
Order o = new Order();
o.setId(i + 1000);
o.setLabel("Order " + i);
o.setEnabled(i % 2 == 1);
o.setCreatedAt(LocalDateTime.now());
o.setProduct(products.get(i - 1));
o.setUser(users.get(i - 1));
orders.add(o);
}
for (int i = 2000; i <= 2100; i++) {
Order o = new Order();
o.setId(i);
o.setLabel("Order " + i);
o.setEnabled(i % 2 == 1);
o.setCreatedAt(LocalDateTime.now());
orders.add(o);
}
orderRepository.saveAll(orders);
}
}
@GetMapping(value = "/datatable")
@ResponseBody
@JsonView(DataTablesOutput.View.class)
public DataTablesOutput<Order> getOrders(@Valid DataTablesInput input) {
DataTablesInput.SearchConfiguration searchConfiguration = new DataTablesInput.SearchConfiguration();
input.setSearchConfiguration(searchConfiguration);
List<String> productRefColumns = new ArrayList<>();
productRefColumns.add("label");
productRefColumns.add("isEnabled");
productRefColumns.add("createdAt");
searchConfiguration.addRefConfiguration("product", "product", productRefColumns, "label");
searchConfiguration.setSearchType("id", DataTablesInput.SearchType.Integer);
searchConfiguration.setSearchType("isEnabled", DataTablesInput.SearchType.Boolean);
searchConfiguration.getExcludedColumns().add("user");
return orderRepository.findAll(input);
}
}
| 32.956522
| 108
| 0.621636
|
bc65747723e1477962ebcf59b2cb2ff29b593685
| 1,632
|
package com.example.prasoon.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int teamAScore=0;
int teamBScore=0;
private void displayTeamAScore(int scoreTeamA)
{
TextView t =(TextView) findViewById(R.id.Score_TeamA);
t.setText(String.valueOf(scoreTeamA));
}
private void displayTeamBScore(int scoreTeamB)
{
TextView t =(TextView) findViewById(R.id.Score_TeamB);
t.setText(String.valueOf(scoreTeamB));
}
public void threeTeamA(View view){
teamAScore+=3;
displayTeamAScore(teamAScore);
}
public void twoTeamA(View view)
{
teamAScore+=2;
displayTeamAScore(teamAScore);
}
public void freeThrowTeamA(View view)
{
++teamAScore;
displayTeamAScore(teamAScore);
}
public void threeTeamB(View view){
teamBScore+=3;
displayTeamBScore(teamBScore);
}
public void twoTeamB(View view)
{
teamBScore+=2;
displayTeamBScore(teamBScore);
}
public void freeThrowTeamB(View view)
{
++teamBScore;
displayTeamBScore(teamBScore);
}
public void resetScore(View view)
{
teamAScore=0;
teamBScore=0;
displayTeamAScore(teamAScore);
displayTeamBScore(teamBScore);
}
}
| 24.727273
| 62
| 0.656863
|
a4857df7f909b5ca707e4fdd21f246a7b8db277f
| 4,892
|
package com.mathroule.chifootmi.game.match;
import com.mathroule.chifootmi.IBuilder;
import com.mathroule.chifootmi.game.player.Player;
import com.mathroule.chifootmi.game.rule.Basic;
import com.mathroule.chifootmi.game.rule.Rule;
import com.mathroule.chifootmi.game.rule.Rules;
import com.mathroule.chifootmi.game.weapon.Weapon;
/**
* Abstract a round of a match between two players.
*/
public class Round extends RuledVersus {
/**
* Number of the round.
*/
private final int round;
/**
* The first player weapon.
*/
private final Weapon weapon1;
/**
* The second player weapon.
*/
private final Weapon weapon2;
/**
* The used rule to determinate the issue of the round.
*/
private final Rule rule;
/**
* The round result.
*/
private final Result result;
/**
* The round result.
*/
public enum Result {
DRAW,
PLAYER_1_WIN,
PLAYER_2_WIN
}
/**
* Round constructor from a builder.
*
* @param builder the round builder
*/
private Round(Builder builder) {
super(builder.player1, builder.player2, builder.rules);
// Check round number
if (builder.round < 1) {
throw new IllegalArgumentException("Round number must be equal or greater than one");
}
// Check weapon 1 is not null
if (builder.weapon1 == null) {
throw new NullPointerException("Weapon 1 should not be null");
}
// Check weapon 2 is not null
if (builder.weapon2 == null) {
throw new NullPointerException("Weapon 2 should not be null");
}
// Get round result and determinate winner and looser or draw
int comparison = rules.compare(builder.weapon1, builder.weapon2);
if (comparison > 0) {
result = Result.PLAYER_1_WIN;
player1.won();
player2.loose();
} else if (comparison < 0) {
result = Result.PLAYER_2_WIN;
player2.won();
player1.loose();
} else {
result = Result.DRAW;
}
// Try to get used rule from normal case: first weapon vs second weapon
Rule usedRule = rules.getWiningRule(builder.weapon1, builder.weapon2);
// Otherwise, try to get used rule from inverted case: second weapon vs first weapon
if (usedRule == null) {
usedRule = rules.getWiningRule(builder.weapon2, builder.weapon1);
}
this.rule = usedRule;
this.round = builder.round;
this.weapon1 = builder.weapon1;
this.weapon2 = builder.weapon2;
}
/**
* Get the round number value.
*
* @return the round number
*/
public int getRound() {
return round;
}
/**
* Get the round result value.
*
* @return the round result
*/
public Result getResult() {
return result;
}
@Override
public String toString() {
return "Round #" + round + ": " + player1 + " (" + weapon1 + ") vs " + player2 + " (" + weapon2 + "): "
+ (rule != null ? rule : "draw");
}
/**
* The round builder.
*/
public final static class Builder implements IBuilder<Round> {
private final Player player1;
private final Player player2;
private final Weapon weapon1;
private final Weapon weapon2;
private int round = 1;
private Rules rules = Basic.getInstance();
/**
* Build a round with two players, with the weapons and basic rules.
*
* @param player1 the first player of the round
* @param weapon1 the first player weapon for the round
* @param player2 the second player of the round
* @param weapon2 the second player weapon for the round
*/
public Builder(Player player1, Weapon weapon1, Player player2, Weapon weapon2) {
this.player1 = player1;
this.player2 = player2;
this.weapon1 = weapon1;
this.weapon2 = weapon2;
}
/**
* Set the round rules.
*
* @param rules the round rules
* @return This Builder object to allow chaining
*/
public Builder rules(Rules rules) {
this.rules = rules;
return this;
}
/**
* Set the round number.
*
* @param round the round number
* @return This Builder object to allow chaining
*/
public Builder round(int round) {
this.round = round;
return this;
}
/**
* Build a round.
*
* @return the built round
*/
@Override
public Round build() {
return new Round(this);
}
}
}
| 26.73224
| 111
| 0.562551
|
fe6ee13337fbd659f6c4fcf017b8023f587d0562
| 743
|
package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ModifyContactData;
import ru.stqa.pft.addressbook.model.NewContactData;
/**
* Created by 0tanya0 on 10/15/2016.
*/
public class ContactModificationTests extends TestBase{
@Test
public void testContactModification(){
app.getContactHelper().submitFirstContactEdit();
app.getContactHelper().changeContact(new ModifyContactData("Tanya", "Jr", "Loz", "user", "Home", "Canada", "+14169937617", "+14325678488", "+54636666666", "+44444444443", "loz@gmail.com", "www.test.ru", "4", "April", "1983", "7", "May", "2000", "Russia", "test", "blabla"));
app.getContactHelper().submitUpdateContact();
}
}
| 39.105263
| 282
| 0.701211
|
4cb8bf8a4327c8f295cd3c4512a0b2012327f152
| 1,626
|
package io.nebula.leaf.service.impl;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.segment.SegmentIDGenImpl;
import com.sankuai.inf.leaf.segment.model.LeafAlloc;
import com.sankuai.inf.leaf.snowflake.SnowflakeIDGenImpl;
import io.nebula.kernel.service.IDGenerateService;
import io.nebula.leaf.support.SegmentAllocDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IDGenServiceImpl implements IDGenerateService {
@Autowired
private SegmentIDGenImpl segmentIDGen;
@Autowired
private SnowflakeIDGenImpl snowflakeIDGen;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private SegmentAllocDao segmentAllocDao;
@Override
public Result getSegmentID(String key) {
//如果找不到对应key就重新创建一个
boolean check = checkBizTag(key);
if (check == false) {
segmentAllocDao.insertLeafAlloc(key);
segmentIDGen.init();
}
return segmentIDGen.get(key);
}
@Override
public Object getSnowflakeID(String key) {
return snowflakeIDGen.get(key);
}
/**
* 判断DB里面是否有该biz_tag
*
* @param key
* @return
*/
private boolean checkBizTag(String key) {
List<LeafAlloc> listLc = segmentIDGen.getAllLeafAllocs();
if (listLc.size() > 0) {
for (LeafAlloc lc : listLc) {
if (key.equals(lc.getKey())) {
return true;
}
}
}
return false;
}
}
| 28.034483
| 70
| 0.667897
|
deb99195fc42d93c925259407569066aa1c34ac6
| 669
|
package com.cerner.hexagonal.architecture.demo.customer.outbound.port;
import com.cerner.hexagonal.architecture.demo.customer.messages.AbstractMessage;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.MimeTypeUtils;
public final class MessageCreator {
public static <T extends AbstractMessage> Message<?> create(final T t) {
return MessageBuilder.withPayload(t)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build();
}
}
| 39.352941
| 100
| 0.747384
|
33a5ea81b7b227c2e822475a0c0e943bd4d1dd83
| 317
|
package annotationInject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component(value = "newBean") // 此注解可以让ComponentScan可以扫到该类,并为之创建Bean,不同于在配置上下文的类中创建,此注解只能指定一个名字,因为源码显示value不是String[],默认为类名,一旦指定,则类名无效。
@Scope(value = "singleton")
public class BeanY {
}
| 31.7
| 135
| 0.820189
|
5e0ea0b36d08d7bc644fdae60328f1629e7a31f7
| 2,229
|
package com.boot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicUpdate;
@Entity
@DynamicUpdate
@Table(name="employee")
public class Employee {
@Id
@Column(name="employeeid",unique=true)
@GeneratedValue(strategy=GenerationType.AUTO)
private int employeeid;
@Column(name="firstname",length=100,nullable=false)
private String firstname;
@Column(name="lastname",length=100,nullable=false)
private String lastname;
@Column(name="city",length=100,nullable=true)
private String city;
@Column(name="email",unique=true,length=200)
private String email;
public Employee() {
}
public Employee(int employeeid, String firstname, String lastname, String city, String email) {
this.employeeid = employeeid;
this.firstname = firstname;
this.lastname = lastname;
this.city = city;
this.email = email;
}
public Employee(String firstname, String lastname, String city, String email) {
this.firstname = firstname;
this.lastname = lastname;
this.city = city;
this.email = email;
}
public int getEmployeeid() {
return employeeid;
}
public void setEmployeeid(int employeeid) {
this.employeeid = employeeid;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee [employeeid=" + employeeid + ", firstname=" + firstname + ", lastname=" + lastname + ", city="
+ city + ", email=" + email + ", getEmployeeid()=" + getEmployeeid() + ", getFirstname()="
+ getFirstname() + ", getLastname()=" + getLastname() + ", getCity()=" + getCity() + ", getEmail()="
+ getEmail() + "]";
}
}
| 22.29
| 113
| 0.707044
|
c9b6a67cbb0953ff377c981f421071480e56131c
| 4,719
|
package com.zqr.study.spring.framework.aop.support;
import com.zqr.study.spring.framework.aop.ZqrAopConfig;
import com.zqr.study.spring.framework.aop.aspect.ZqrAfterReturningAdvice;
import com.zqr.study.spring.framework.aop.aspect.ZqrAfterThrowingAdvice;
import com.zqr.study.spring.framework.aop.aspect.ZqrMethodBeforeAdvice;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description:
* @Auther: qingruizhu
* @Date: 2019-04-30 16:14
*/
public class ZqrAdvicedSupport {
private Class targetClass;
private Object target;
private Pattern pointCutPattern;
private transient Map<Method, List<Object>> methodCache;
private ZqrAopConfig config;
public boolean pointCutMatch() {
return pointCutPattern.matcher(this.targetClass.toString()).matches();
}
public ZqrAdvicedSupport(ZqrAopConfig config) {
this.config = config;
}
public Class getTargetClass() {
return targetClass;
}
public void setTargetClass(Class targetClass) {
this.targetClass = targetClass;
parse();
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public Pattern getPointCutPattern() {
return pointCutPattern;
}
public void setPointCutPattern(Pattern pointCutPattern) {
this.pointCutPattern = pointCutPattern;
}
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) throws Exception {
List<Object> caches = methodCache.get(method);
if (null == caches) {
Method targetMethod = targetClass.getMethod(method.getName(), method.getParameterTypes());
caches = methodCache.get(targetMethod);
//存入缓存
this.methodCache.put(targetMethod, caches);
}
return caches;
}
//织入增强的方法,设置methodCache
private void parse() {
//pointCut 表达式
String pointCut = config.getPointCut()
.replaceAll("\\.", "\\\\.")
.replaceAll("\\\\.\\*", ".*")
.replaceAll("\\(", "\\\\(")
.replaceAll("\\)", "\\\\)");
//切点class表达式匹配
String pointCutForClass = pointCut.substring(0, pointCut.lastIndexOf("\\(") - 4);
pointCutPattern = Pattern.compile("class " + pointCutForClass.substring(pointCutForClass.lastIndexOf(" ") + 1));
//设置切点的通知方法=mehtodCache
methodCache = new HashMap<Method, List<Object>>();
try {
Class<?> aspectClass = Class.forName(config.getAspectClass());
//切面的所有方法
Map<String, Method> aspectMethods = new HashMap<String, Method>();
for (Method method : aspectClass.getMethods()) {
aspectMethods.put(method.getName(), method);
}
//匹配目标类的有关方法
Pattern pattern = Pattern.compile(pointCut);
for (Method method : targetClass.getMethods()) {
String methodStr = method.toString();
if (methodStr.contains("throws")) {
methodStr = methodStr.substring(0, methodStr.indexOf("throws")).trim();
}
Matcher matcher = pattern.matcher(methodStr);
if (matcher.matches()) {
List<Object> advices = new ArrayList<Object>();
if (null != config.getAspectBefore() && !"".equals(config.getAspectBefore())) {
ZqrMethodBeforeAdvice beforeAdvice = new ZqrMethodBeforeAdvice(aspectMethods.get(config.getAspectBefore()), aspectClass.newInstance());
advices.add(beforeAdvice);
}
if (null != config.getAspectAfter() && !"".equals(config.getAspectAfter())) {
ZqrAfterReturningAdvice afterAdvice = new ZqrAfterReturningAdvice(aspectMethods.get(config.getAspectAfter()), aspectClass.newInstance());
advices.add(afterAdvice);
}
if (null != config.getAspectAfterThrow() && !"".equals(config.getAspectAfterThrow())) {
ZqrAfterThrowingAdvice throwingAdvice = new ZqrAfterThrowingAdvice(aspectMethods.get(config.getAspectAfterThrow()), aspectClass.newInstance());
advices.add(throwingAdvice);
}
methodCache.put(method, advices);
}
}
} catch (Exception e) {
e.fillInStackTrace();
}
}
}
| 36.867188
| 167
| 0.608392
|
170e133db6c5d9b06b4f40088f40429bb46ed395
| 1,660
|
import java.lang.reflect.Array;
import java.util.Arrays;
public class RadixSort {
public static void main(String[] args) {
int[] arr = new int[]{23,6,189,45,9,287,56,1,798,34,65,653,5};
radixSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void radixSort(int[] arr){
//save the maximal number of the array;
int max = Integer.MIN_VALUE;
for(int i =0;i<arr.length;i++){
if(arr[i]>max){
max = arr[i];
}
}
//decide how much round should we take
int round = (max+"").length();
//define a two-dimensional array to store numbers
int[][] temp = new int[10][arr.length];
//define a array to count numbers in each col of the two-dimensional array
int[] counts = new int[10];
for(int i=0,n=1;i<round;i++,n*=10) {
//take the reminder of each number in the arr
for (int j = 0; j < arr.length; j++) {
int reminder = arr[j] / n % 10;
//把当前遍历的数字放到指定的数组中
temp[reminder][counts[reminder]] = arr[j];
counts[reminder]++;
}
//记录取的元素需要放的位置;
int index = 0;
for(int k=0;k<counts.length;k++){
//记录数量的数组中当前余数记录的数量不为零
if(counts[k]!=0){
//循环取出元素
for(int l = 0;l<counts[k];l++){
//取出元素
arr[index]=temp[k][l];
index++;
}
counts[k]=0;
}
}
}
}
}
| 33.2
| 82
| 0.459639
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.