hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e09891d8f2e287c25528e2c0f6163ca6613ecad | 1,970 | java | Java | osgp/platform/osgp-adapter-domain-smartmetering/src/test/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/mapping/GetPowerQualityProfileRequestMapperTest.java | ekmixon/open-smart-grid-platform | ca095718390ce8b33db399722e86fc43f252057a | [
"Apache-2.0"
] | 77 | 2018-10-25T12:05:06.000Z | 2022-02-03T12:49:56.000Z | osgp/platform/osgp-adapter-domain-smartmetering/src/test/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/mapping/GetPowerQualityProfileRequestMapperTest.java | OSGP/open-smart-grid-platform | f431e30820fe79dbde7da963f51b087a8a0c91d0 | [
"Apache-2.0"
] | 526 | 2018-10-24T15:58:01.000Z | 2022-03-31T20:06:59.000Z | osgp/platform/osgp-adapter-domain-smartmetering/src/test/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/mapping/GetPowerQualityProfileRequestMapperTest.java | ekmixon/open-smart-grid-platform | ca095718390ce8b33db399722e86fc43f252057a | [
"Apache-2.0"
] | 30 | 2018-12-27T07:11:35.000Z | 2021-09-09T06:57:44.000Z | 41.914894 | 106 | 0.794924 | 4,018 | /*
* Copyright 2017 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.adapter.domain.smartmetering.application.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Date;
import org.junit.jupiter.api.Test;
import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.GetPowerQualityProfileRequest;
import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.GetPowerQualityProfileRequestData;
public class GetPowerQualityProfileRequestMapperTest {
private final MonitoringMapper mapper = new MonitoringMapper();
private static final Date DATE = new Date();
private static final String DEVICE_NAME = "TEST10240000001";
private static final String MAPPED_VALUE_MESSAGE = "mapped values should be identical.";
@Test
public void testGetPowerQualityProfileRequest() {
final GetPowerQualityProfileRequest getPowerQualityProfileRequest = this.makeRequest();
final GetPowerQualityProfileRequestData result =
this.mapper.map(getPowerQualityProfileRequest, GetPowerQualityProfileRequestData.class);
assertThat(result)
.withFailMessage("mapping GetPowerQualityProfileRequest should not return null")
.isNotNull();
assertThat(result)
.withFailMessage("mapping GetPowerQualityProfileRequest should return correct type")
.isOfAnyClassIn(GetPowerQualityProfileRequestData.class);
assertThat(result.getBeginDate()).withFailMessage(MAPPED_VALUE_MESSAGE).isEqualTo(DATE);
assertThat(result.getEndDate()).withFailMessage(MAPPED_VALUE_MESSAGE).isEqualTo(DATE);
}
private GetPowerQualityProfileRequest makeRequest() {
return new GetPowerQualityProfileRequest("PUBLIC", DATE, DATE, DEVICE_NAME);
}
}
|
3e0989481e4c2985f3902d326a413b0b2b35023e | 6,634 | java | Java | projects/core/src/main/java/am/app/lexicon/wordnet/WordNetLexiconBuilder.java | ulaskeles/agreementmaker | 0b83f71b3158c9aa169e4cc0cf612bfdb48f442c | [
"NCSA"
] | 32 | 2015-09-01T10:10:57.000Z | 2021-05-22T03:11:42.000Z | projects/core/src/main/java/am/app/lexicon/wordnet/WordNetLexiconBuilder.java | ulaskeles/agreementmaker | 0b83f71b3158c9aa169e4cc0cf612bfdb48f442c | [
"NCSA"
] | 34 | 2015-09-27T10:51:23.000Z | 2022-01-27T20:18:43.000Z | projects/core/src/main/java/am/app/lexicon/wordnet/WordNetLexiconBuilder.java | ulaskeles/agreementmaker | 0b83f71b3158c9aa169e4cc0cf612bfdb48f442c | [
"NCSA"
] | 27 | 2015-09-01T15:16:05.000Z | 2020-10-27T05:34:11.000Z | 35.281915 | 162 | 0.723805 | 4,019 | package am.app.lexicon.wordnet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import am.app.Core;
import am.app.lexicon.GeneralLexicon;
import am.app.lexicon.GeneralLexiconSynSet;
import am.app.lexicon.Lexicon;
import am.app.lexicon.LexiconBuilder;
import am.app.lexicon.LexiconSynSet;
import am.app.mappingEngine.LexiconStore.LexiconRegistry;
import am.app.ontology.Ontology;
import com.hp.hpl.jena.ontology.OntResource;
import edu.smu.tspell.wordnet.api.Synset;
import edu.smu.tspell.wordnet.api.SynsetType;
import edu.smu.tspell.wordnet.api.WordNetDatabase;
/**
* Enriches an ontology lexicon with synonyms from WordNet.
*
* @author Cosmin Stroe <lyhxr@example.com>
*
*/
public class WordNetLexiconBuilder implements LexiconBuilder {
private static final Logger LOG = LogManager.getLogger(WordNetLexiconBuilder.class);
Lexicon wordnetLexicon;
Lexicon ontologyLexicon; // depends on the ontology lexicon
Ontology currentOntology;
private WordNetDatabase WordNet; // the WordNet Interface
/**
*
* @param ont The ontology for which we are building the lexicon.
* @param ontLexicon An ontology lexicon built for the specific ontology.
*/
public WordNetLexiconBuilder( Ontology ont, Lexicon ontLexicon ) {
currentOntology = ont;
wordnetLexicon = new GeneralLexicon( LexiconRegistry.WORDNET_LEXICON);
ontologyLexicon = ontLexicon;
// Initialize the WordNet interface.
String wordnetdir = Core.getInstance().getRoot() + "/wordnet-3.0";
System.setProperty("wordnet.database.dir", wordnetdir);
// Instantiate wordnet.
try {
WordNet = WordNetDatabase.getFileInstance();
WordNet.getSynsets("test");
} catch( Exception e ) {
String message = "Cannot open WordNet files.\nWordNet should be in the following directory:\n" + wordnetdir;
LOG.error(message, e);
throw new RuntimeException(message + "\n" + e.getMessage(), e);
}
}
@Override
public Lexicon buildLexicon() {
//long id = 0;
// Iterate through all the Synsets in the ontology lexicon
for( Entry<OntResource, LexiconSynSet> currentEntry : ontologyLexicon.getSynSetMap().entrySet() ) {
LexiconSynSet currentOntologySynSet = currentEntry.getValue(); // current synset in the ontology lexicon
List<String> currentOntologySynonyms = currentOntologySynSet.getSynonyms(); // synonyms of the current ontology synset.
ArrayList<String> wordnetWordForms = new ArrayList<String>();
ArrayList<String> wordnetDefinitions = new ArrayList<String>();
// Step 1. Lookup all the word forms of the current ontology synset in WordNet. Gather the results in a list.
for( String currentOntologySynonym : currentOntologySynonyms ) {
ArrayList<String> wordFormsFound = getAllWordForms(currentOntologySynonym);
ArrayList<String> definitionsFound = getAllDefinitions(currentOntologySynonym); // TODO: Merge with above method. No sense in looking up the same word twice.
if( wordFormsFound.isEmpty() ) continue; // this word was not found in the wordnet dictionary.
for( String wordform : wordFormsFound ) {
if( !wordnetWordForms.contains(wordform) ) wordnetWordForms.add(wordform);
}
for( String def : definitionsFound ) {
if( !wordnetDefinitions.contains(def) ) wordnetDefinitions.add(def);
}
}
// Step 2. Check if any of the wordnet word forms are in the ontology Lexicon already. Keep a list of the unique entries found in wordnet.
ArrayList<String> uniqueWordForms = new ArrayList<String>();
for( String currentWordForm : wordnetWordForms ) {
if( !wordnetWordForms.contains(currentWordForm) ) {
uniqueWordForms.add(currentWordForm);
}
}
// Step 2a. Check to make sure we found new information.
//if( uniqueWordForms.isEmpty() ) continue; // no unique wordnet word forms found for the ontology synset.
// Step 3. Create a new synset for this class.
GeneralLexiconSynSet wordNetNewSynSet = new GeneralLexiconSynSet(LexiconRegistry.WORDNET_LEXICON);
// Step 3a. add all the unique wornet wordforms to the new synset.
for( String wordnetWordForm : uniqueWordForms ) {
wordNetNewSynSet.addSynonym(wordnetWordForm);
}
// Step 4. Set the definition. (Problem: for multiple wordnet synsets, which definition do we choose????????) TODO
//( TODO: Answer: a robust disambiguation solution is required here. (ha ha ha, that's not going to happen anytime soon) )
if( currentOntologySynSet.getGloss() == null && !wordnetDefinitions.isEmpty() ) {
wordNetNewSynSet.setGloss( wordnetDefinitions.get(0) ); // the first definition found
}
if( !wordnetDefinitions.isEmpty() ) {
// the ontology definition exists. That's fine, but we will set a wordnet definition also.
wordNetNewSynSet.setGloss( wordnetDefinitions.get(0)); // TODO: for multiple wordnet synsets, we need a robust disambiguation solution
}
if( wordNetNewSynSet.isEmpty() ) continue; // no new information
// Step 5. Create link from ontology synset to wordnet synset (and back).
currentOntologySynSet.addRelatedSynSet(wordNetNewSynSet);
wordNetNewSynSet.setOntologyConcept( currentOntologySynSet.getOntologyConcept() );
wordNetNewSynSet.addRelatedSynSet(currentOntologySynSet);
// Done creating the SynSet.
wordnetLexicon.addSynSet(wordNetNewSynSet);
}
return wordnetLexicon;
}
private ArrayList<String> getAllWordForms(String searchTerm) {
ArrayList<String> wordFormsFound = new ArrayList<String>();
// lookup
for (SynsetType t : SynsetType.ALL_TYPES) {
Synset[] synsets = WordNet.getSynsets(searchTerm, t);
for (int i = 0; i < synsets.length; i++) {
String[] words = synsets[i].getWordForms(); // get the wordforms of this synset
for (int j = 0; j < words.length; j++) {
if( !words[j].trim().equals("") && !wordFormsFound.contains( words[j] ) ) wordFormsFound.add(words[j]);
}
}
}
return wordFormsFound;
}
private ArrayList<String> getAllDefinitions(String searchTerm) {
ArrayList<String> definitionsFound = new ArrayList<String>();
// lookup
for (SynsetType t : SynsetType.ALL_TYPES) {
Synset[] synsets = WordNet.getSynsets(searchTerm, t);
for (int i = 0; i < synsets.length; i++) {
String definition = synsets[i].getDefinition(); // get the definition of this synset
if( !definitionsFound.contains( definition ) ) definitionsFound.add(definition);
}
}
return definitionsFound;
}
}
|
3e09897ce4a5530c6d0d96e3243c4608b106e9cf | 1,080 | java | Java | up-core/src/main/java/com/github/restup/mapping/fields/composition/BasicImmutability.java | restup/up-framework | ca477e927a3c1bbe94b9ea477486544aa98e72e0 | [
"MIT"
] | 2 | 2018-01-26T17:01:37.000Z | 2018-02-24T15:20:02.000Z | up-core/src/main/java/com/github/restup/mapping/fields/composition/BasicImmutability.java | restup/up-framework | ca477e927a3c1bbe94b9ea477486544aa98e72e0 | [
"MIT"
] | null | null | null | up-core/src/main/java/com/github/restup/mapping/fields/composition/BasicImmutability.java | restup/up-framework | ca477e927a3c1bbe94b9ea477486544aa98e72e0 | [
"MIT"
] | null | null | null | 24.545455 | 72 | 0.651852 | 4,020 | package com.github.restup.mapping.fields.composition;
import java.util.Objects;
class BasicImmutability implements Immutability {
private final boolean immutable;
private final boolean errorOnUpdateAttempt;
BasicImmutability(boolean immutable, boolean errorOnUpdateAttempt) {
this.immutable = immutable;
this.errorOnUpdateAttempt = errorOnUpdateAttempt;
}
@Override
public boolean isImmutable() {
return immutable;
}
@Override
public boolean isErrorOnUpdateAttempt() {
return errorOnUpdateAttempt;
}
@Override
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (! ( o instanceof BasicImmutability )) {
return false;
}
BasicImmutability that = (BasicImmutability) o;
return errorOnUpdateAttempt == that.errorOnUpdateAttempt &&
immutable == that.immutable;
}
@Override
public final int hashCode() {
return Objects.hash(immutable, errorOnUpdateAttempt);
}
}
|
3e0989cdd1eeeef128e74d98dae3e7664108f5af | 600 | java | Java | src/org/sosy_lab/cpachecker/core/algorithm/pcc/package-info.java | DulangDev/cpachecker | 234211fdb2fb5459ea99d79ccc24d031bee160d1 | [
"Apache-2.0"
] | 16 | 2015-01-19T15:52:14.000Z | 2015-11-30T14:12:31.000Z | src/org/sosy_lab/cpachecker/core/algorithm/pcc/package-info.java | teodorov/cpachecker | 16e37b76c5b9e3d203992c6c7bf96b64da6fbae1 | [
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/core/algorithm/pcc/package-info.java | teodorov/cpachecker | 16e37b76c5b9e3d203992c6c7bf96b64da6fbae1 | [
"Apache-2.0"
] | 18 | 2015-02-17T19:22:41.000Z | 2015-11-24T09:12:39.000Z | 35.294118 | 74 | 0.795 | 4,021 | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
/**
* The algorithms dealing with (preparation for) proof generation and
* proof checking in Proof-Carrying Code like scenarios
*/
@javax.annotation.ParametersAreNonnullByDefault
@org.sosy_lab.common.annotations.FieldsAreNonnullByDefault
@org.sosy_lab.common.annotations.ReturnValuesAreNonnullByDefault
package org.sosy_lab.cpachecker.core.algorithm.pcc;
|
3e098a144b698402e8433280716a54dff6557170 | 3,137 | java | Java | hedera-node/src/main/java/com/hedera/services/sigs/sourcing/SigListPubKeyToSigBytes.java | subfallen/hedera-services | ddb3f7540a0e4c0f62f72829ea20532aed1271ac | [
"Apache-2.0"
] | null | null | null | hedera-node/src/main/java/com/hedera/services/sigs/sourcing/SigListPubKeyToSigBytes.java | subfallen/hedera-services | ddb3f7540a0e4c0f62f72829ea20532aed1271ac | [
"Apache-2.0"
] | null | null | null | hedera-node/src/main/java/com/hedera/services/sigs/sourcing/SigListPubKeyToSigBytes.java | subfallen/hedera-services | ddb3f7540a0e4c0f62f72829ea20532aed1271ac | [
"Apache-2.0"
] | null | null | null | 37.345238 | 96 | 0.746892 | 4,022 | package com.hedera.services.sigs.sourcing;
/*-
*
* Hedera Services Node
*
* Copyright (C) 2018 - 2021 Hedera Hashgraph, 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.
*
*/
import com.google.protobuf.ByteString;
import com.hederahashgraph.api.proto.java.Signature;
import com.hedera.services.legacy.exception.KeySignatureCountMismatchException;
import java.util.List;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
/**
* A source of cryptographic signatures backed by a list of Hedera {@link Signature} instances.
*
* <b>IMPORTANT:</b> The (deprecated) {@link com.hederahashgraph.api.proto.java.SignatureList}
* approach to signing a gRPC transaction does not explicitly map from public keys to their raw
* signatures. Instead, it uses the convention that a left-to-right DFS traversal of the raw
* signatures in the {@link com.hederahashgraph.api.proto.java.SignatureList} will encounter
* them in exactly the order that their public keys appear when doing a left-to-right
* traversal of the Hedera keys required to sign the gRPC transaction (as ordered by
* {@link com.hedera.services.sigs.order.HederaSigningOrder}).
*
* This fragile, unenforceable, thinly documented protocol is much inferior to the
* explicit public-key-to-cryptographic-signature mapping given by a
* {@link com.hederahashgraph.api.proto.java.SignatureMap}.
*
* @author Michael Tinker
*/
public class SigListPubKeyToSigBytes implements PubKeyToSigBytes {
private List<Signature> simpleSigs;
private int i = 0;
public SigListPubKeyToSigBytes(List<Signature> hederaSigs) {
simpleSigs = hederaSigs.stream().flatMap(this::flattened).collect(toList());
}
private Stream<Signature> flattened(Signature sig) {
if (sig.hasThresholdSignature()) {
return sig.getThresholdSignature().getSigs().getSigsList().stream().flatMap(this::flattened);
} else if (sig.hasSignatureList()) {
return sig.getSignatureList().getSigsList().stream().flatMap(this::flattened);
} else {
return Stream.of(sig);
}
}
@Override
public byte[] sigBytesFor(byte[] pubKey) throws KeySignatureCountMismatchException {
if (i == simpleSigs.size()) {
throw new KeySignatureCountMismatchException("No more signatures available in the list!");
}
return sigBytesFor(simpleSigs.get(i++));
}
private byte[] sigBytesFor(Signature sig) {
if (sig.getRSA3072() != ByteString.EMPTY) {
return sig.getRSA3072().toByteArray();
} else if (sig.getECDSA384() != ByteString.EMPTY) {
return sig.getECDSA384().toByteArray();
} else {
return sig.getEd25519().toByteArray();
}
}
}
|
3e098bacb163df06dd3c23ad81b7a03b653e5ec1 | 472 | java | Java | src/main/java/dev/popov/bookify/domain/model/view/EventViewModel.java | Nikola-Popov/Bookify | b62f987bfad96ffba2b96968b88ec49a977b31db | [
"MIT"
] | null | null | null | src/main/java/dev/popov/bookify/domain/model/view/EventViewModel.java | Nikola-Popov/Bookify | b62f987bfad96ffba2b96968b88ec49a977b31db | [
"MIT"
] | 36 | 2019-10-03T05:01:32.000Z | 2021-07-23T03:16:26.000Z | src/main/java/dev/popov/bookify/domain/model/view/EventViewModel.java | Nikola-Popov/Bookify | b62f987bfad96ffba2b96968b88ec49a977b31db | [
"MIT"
] | null | null | null | 21.454545 | 51 | 0.824153 | 4,023 | package dev.popov.bookify.domain.model.view;
import java.math.BigDecimal;
import java.time.LocalDate;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class EventViewModel extends BaseViewModel {
private String title;
private String address;
private EventTypeViewModel eventType;
private int vouchersCount;
private String description;
private BigDecimal price;
private LocalDate expiresOn;
}
|
3e098c20271275adca5a03dee5432a18b126928e | 5,908 | java | Java | rt/src/com/sun/xml/wss/provider/wsit/SecurityContextImpl.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | rt/src/com/sun/xml/wss/provider/wsit/SecurityContextImpl.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | rt/src/com/sun/xml/wss/provider/wsit/SecurityContextImpl.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 40.190476 | 100 | 0.642011 | 4,024 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.wss.provider.wsit;
import com.sun.xml.ws.security.spi.SecurityContext;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.Subject;
/**
*Provides a Default Implementation (tailored for GlassFish)
* of the SecurityContext interface
*/
public class SecurityContextImpl implements SecurityContext {
private static final String GF_SEC_CONTEXT="com.sun.enterprise.security.SecurityContext";
private Class c = null;
private Method getCurrent = null;
private Method serverGenCred =null;
private Method getSubject = null;
private Constructor ctor = null;
@SuppressWarnings("unchecked")
public SecurityContextImpl() {
try {
Class[] params = new Class[]{};
c = Class.forName(GF_SEC_CONTEXT, true, Thread.currentThread().getContextClassLoader());
getCurrent = c.getMethod("getCurrent", params);
serverGenCred = c.getMethod("didServerGenerateCredentials", params);
getSubject = c.getMethod("getSubject", params);
params = new Class[]{Subject.class};
ctor = c.getConstructor(params);
} catch (NoSuchMethodException ex) {
//Logger.getLogger(SecurityContextImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
//Logger.getLogger(SecurityContextImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
//Logger.getLogger(SecurityContextImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Subject getSubject() {
Subject s = null;
Class[] params = new Class[]{};
Object[] args = new Object[]{};
try {
if(getCurrent == null || serverGenCred == null ||getSubject == null) {
return null;
}
Object currentSC = getCurrent.invoke(null, args);
if (currentSC == null) {
return null;
}
Boolean didServerGenerateCredentials = (Boolean)serverGenCred.invoke(currentSC, args);
if (!didServerGenerateCredentials.booleanValue()) {
s = (Subject)getSubject.invoke(currentSC, args);
}
return s;
} catch (IllegalAccessException ex) {
return null;
} catch (IllegalArgumentException ex) {
return null;
} catch (InvocationTargetException ex) {
return null;
} catch (SecurityException ex) {
return null;
}
}
public void setSubject(Subject subject) {
//SecurityContext sC = new SecurityContext(s);
//SecurityContext.setCurrent(sC);
Class[] params = null;
Object[] args = null;
try {
args = new Object[] {subject};
if (ctor == null) {
//TODO: log warning here
return;
}
Object secContext = ctor.newInstance(args);
params = new Class[]{secContext.getClass()};
@SuppressWarnings("unchecked")
Method setCurrent = c.getMethod("setCurrent", params);
args = new Object[]{secContext};
if (setCurrent == null) {
//TODO: log warning here
return;
}
setCurrent.invoke(null, args);
} catch (InstantiationException ex) {
//ignore
} catch (IllegalAccessException ex) {
//ignore
} catch (IllegalArgumentException ex) {
//ignore
} catch (InvocationTargetException ex) {
//ignore
} catch (NoSuchMethodException ex) {
//ignore
} catch (SecurityException ex) {
//ignore
}
}
}
|
3e098c20d0ec361934dae68e52b48e9b7e1a31a8 | 572 | java | Java | Rebuild/app/src/main/java/com/nwhacks2020/rebuild/data/CurrentLocationSingleton.java | nwhacks-2020/rebuild | 3b86e9df18e9b71de0b8ec5d0cbde0bb0250c27c | [
"MIT"
] | 3 | 2020-02-04T15:45:18.000Z | 2022-03-05T20:34:58.000Z | Rebuild/app/src/main/java/com/nwhacks2020/rebuild/data/CurrentLocationSingleton.java | nwhacks-2020/rebuild | 3b86e9df18e9b71de0b8ec5d0cbde0bb0250c27c | [
"MIT"
] | null | null | null | Rebuild/app/src/main/java/com/nwhacks2020/rebuild/data/CurrentLocationSingleton.java | nwhacks-2020/rebuild | 3b86e9df18e9b71de0b8ec5d0cbde0bb0250c27c | [
"MIT"
] | 8 | 2020-01-11T21:46:56.000Z | 2022-03-15T08:38:27.000Z | 21.185185 | 62 | 0.702797 | 4,025 | package com.nwhacks2020.rebuild.data;
import android.location.Location;
@SuppressWarnings("WeakerAccess")
public class CurrentLocationSingleton {
private static Location location = null;
public static void setCurrentLocation(Location location) {
CurrentLocationSingleton.location = location;
}
public static double getLatitude() {
return location.getLatitude();
}
public static double getLongitude() {
return location.getLongitude();
}
public static Location getLocation() {
return location;
}
}
|
3e098e42e8a984afbcf3a64d3299975c28d4e14a | 2,568 | java | Java | src/test/java/com/novaordis/series/LinkedListSeriesTest.java | NovaOrdis/series | 978cd2290bcd6b15c2395e18081ba2d2d467f42d | [
"Apache-2.0"
] | null | null | null | src/test/java/com/novaordis/series/LinkedListSeriesTest.java | NovaOrdis/series | 978cd2290bcd6b15c2395e18081ba2d2d467f42d | [
"Apache-2.0"
] | null | null | null | src/test/java/com/novaordis/series/LinkedListSeriesTest.java | NovaOrdis/series | 978cd2290bcd6b15c2395e18081ba2d2d467f42d | [
"Apache-2.0"
] | null | null | null | 38.954545 | 141 | 0.346947 | 4,026 | package com.novaordis.series;
import com.novaordis.series.metric.DoubleHeader;
import com.novaordis.series.metric.LongHeader;
import com.novaordis.series.metric.StringHeader;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
/**
* @author <a href="mailto:lyhxr@example.com">Ovidiu Feodorov</a>
*
* Copyright 2012 Nova Ordis LLC
*/
public class LinkedListSeriesTest extends SeriesTest
{
// Constants ---------------------------------------------------------------------------------------------------------------------------
// Static ------------------------------------------------------------------------------------------------------------------------------
// Attributes --------------------------------------------------------------------------------------------------------------------------
// Constructors ------------------------------------------------------------------------------------------------------------------------
// Public ------------------------------------------------------------------------------------------------------------------------------
@Test
public void testHeadersInConstructor() throws Exception
{
Series s = new LinkedListSeries(new StringHeader("a"), new LongHeader("b"), new DoubleHeader("c"));
List<Header> headers = s.getHeaders();
assertEquals(3, headers.size());
assertEquals("a", ((StringHeader)headers.get(0)).getName());
assertEquals("b", ((LongHeader)headers.get(1)).getName());
assertEquals("c", ((DoubleHeader)headers.get(2)).getName());
Iterator<Row> ri = s.iterator();
assertFalse(ri.hasNext());
}
// Package protected -------------------------------------------------------------------------------------------------------------------
// Protected ---------------------------------------------------------------------------------------------------------------------------
@Override
protected LinkedListSeries getSeriesToTest(Row... rows) throws Exception
{
LinkedListSeries s = new LinkedListSeries();
for(Row r: rows)
{
s.add(r);
}
return s;
}
// Private -----------------------------------------------------------------------------------------------------------------------------
// Inner classes -----------------------------------------------------------------------------------------------------------------------
}
|
3e098f947d13089f824eb7b571a3ad3cb5ce5e7d | 3,956 | java | Java | app/src/main/java/com/sheshu/ttstextselectionmenu/TTSBackgroundService.java | skumaringuva/TTSTextSelectionMenu | e6b5629d891cf7a903d1551966fa20c325d1a508 | [
"Unlicense"
] | 2 | 2017-11-25T12:41:14.000Z | 2020-06-07T03:44:48.000Z | app/src/main/java/com/sheshu/ttstextselectionmenu/TTSBackgroundService.java | skumaringuva/TTSTextSelectionMenu | e6b5629d891cf7a903d1551966fa20c325d1a508 | [
"Unlicense"
] | null | null | null | app/src/main/java/com/sheshu/ttstextselectionmenu/TTSBackgroundService.java | skumaringuva/TTSTextSelectionMenu | e6b5629d891cf7a903d1551966fa20c325d1a508 | [
"Unlicense"
] | null | null | null | 32.42623 | 109 | 0.618301 | 4,027 | package com.sheshu.ttstextselectionmenu;
import android.app.Service;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.util.Log;
import java.util.Locale;
/**
* Created by Sheshu on 4/14/17.
*/
public class TTSBackgroundService extends Service implements TextToSpeech.OnInitListener {
static final String ACTION_SPEAK = "com.sheshu.ttstextselectionmenu.speak";
static final String DATA_TEXT = "com.sheshu.ttstextselectionmenu.data.text";
static final String ACTION_STOP = "com.sheshu.ttstextselectionmenu.stop";
static final String COMMAND = "com.sheshu.ttstextselectionmenu.command";
private static final String TAG = "TTSService";
private String str;
private TextToSpeech mTts;
private ClipboardManager mClipboard;
private ClipboardManager.OnPrimaryClipChangedListener mClipBoardListener;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
mTts = new TextToSpeech(this,
this // OnInitListener
);
mTts.setSpeechRate(0.5f);
setClipboardListener();
Log.v(TAG, "oncreate_service");
// str ="turn left please ";
super.onCreate();
}
private void setClipboardListener() {
mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
mClipBoardListener = new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
if (mClipboard.hasPrimaryClip()) {
String contents = mClipboard.getPrimaryClip().getItemAt(0).getText().toString();
//ClipData newCopy = ClipData.newPlainText("copiedText", TextUtils.noCharWrap(contents));
Log.v(TAG,"TEXT: "+contents);
if(!TextUtils.isEmpty(contents))
SpeakText(contents);
}
}
};
mClipboard.addPrimaryClipChangedListener(mClipBoardListener);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
if(mClipboard!=null && mClipBoardListener!=null)
mClipboard.removePrimaryClipChangedListener(mClipBoardListener);
mClipboard = null;
mClipBoardListener = null;
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
// SpeakText(str);
Log.v(TAG, "onstart_service");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent!=null && intent.getAction().equals(ACTION_SPEAK)) {
String text = intent.getExtras().getString(DATA_TEXT);
Log.v(TAG, "text to speak: " + text);
str = text;
SpeakText(text);
}
Log.v(TAG, "onStartCommand");
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onInit(int status) {
Log.v(TAG, "oninit");
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Please download the tts language from settings.");
} else {
SpeakText(str);
}
} else {
Log.v(TAG, "Could not initialize TextToSpeech.");
}
}
private void SpeakText(String str) {
mTts.speak(str,
TextToSpeech.QUEUE_FLUSH,
null);
}
} |
3e098fa26d3e5f6e72284e6e96d5df909a3e25ca | 9,154 | java | Java | src/main/java/com/davidbracewell/reflection/ValueType.java | dbracewell/mango | 2cec08826f1fccd658694dd03abce10fc97618ec | [
"Apache-2.0"
] | null | null | null | src/main/java/com/davidbracewell/reflection/ValueType.java | dbracewell/mango | 2cec08826f1fccd658694dd03abce10fc97618ec | [
"Apache-2.0"
] | null | null | null | src/main/java/com/davidbracewell/reflection/ValueType.java | dbracewell/mango | 2cec08826f1fccd658694dd03abce10fc97618ec | [
"Apache-2.0"
] | null | null | null | 30.718121 | 128 | 0.643653 | 4,028 | /*
* (c) 2005 David B. Bracewell
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.davidbracewell.reflection;
import com.davidbracewell.config.Config;
import com.davidbracewell.conversion.Cast;
import com.davidbracewell.conversion.Convert;
import lombok.NonNull;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
/**
* <p>Encapsulates the definition of an object including methods to read its definition via configuration and convert
* values to is type. Definition via configuration is done in the following manner:</p> <p>For simple types:</p>
* <pre>{@code
* property = TypeName
* # or
* property.type = TypeName
* # or
* property {
* _ = TypeName
* }
* }</pre>
* <p>where <code>property</code> is the name of the object whose value type we want. Collections can be defined in the
* following manner:</p>
* <pre>{@code
* collection {
* type = List
* elementType = Integer
* }
* } </pre>
* <p>where <code>collection</code> is the name of the collection'whose value type we want, type is the collection type,
* and elementType is the generic type (omitted elementType will result in String being used). Maps can be defined in
* the following manner:</p>
* <pre>{@code
* map {
* type = List
* keyType = Integer
* valueType = Double
* }
* } </pre>
* <p>where <code>map</code> is the name of the map whose value type we want, type is the map type, keyType is the class
* of the key, and valueType is the class of the value (omitted keyType or valueType will result in String being
* used).</p>
*
* @author David B. Bracewell
*/
public abstract class ValueType implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The property component defining the class type of a value
*/
public static final String TYPE_PROPERTY = "type";
/**
* The property component defining the class type of the elements in a collection
*/
public static final String ELEMENT_TYPE_PROPERTY = "elementType";
/**
* The property component defining the class type of the keys in a map
*/
public static final String KEY_TYPE_PROPERTY = "keyType";
/**
* The property component defining the class type of the values in a map
*/
public static final String VALUE_TYPE_PROPERTY = "valueType";
/**
* Gets the type, i.e. class, this value type will convert.
*
* @return the type this value represents and will convert to
*/
public abstract Class<?> getType();
/**
* Gets the parameter types, e.g. elementType, keyType, valueType.
*
* @return An array of the parameter, e.g. generic types.
*/
public abstract Class<?>[] getParameterTypes();
/**
* Determines if this value type represents a collection
*
* @return True if this value type is a collection, False otherwise
*/
public boolean isCollection() {
return false;
}
/**
* Determines if this value type represents a map
*
* @return True if this value type is a map, False otherwise
*/
public boolean isMap() {
return false;
}
/**
* Creates a <code>ValueType</code> for the given configuration property. T
*
* @param property the property name to create a ValueType from
* @return the value type representing the property
*/
public static ValueType fromConfig(String property) {
//If the property is valid and we cannot find a "property.type" then the value of the property represents its simple type.
if (Config.hasProperty(property) && !Config.hasProperty(property, TYPE_PROPERTY)) {
return new SimpleValueType(Config.get(property).asClass());
}
if( Config.isBean(property) ){
Object o = Config.get(property);
return new SimpleValueType(o.getClass());
}
//Read in the value type parameters from the configuration using the property as the prefix
Map<String, Class> typeInfo = Config.getMap(property, String.class, Class.class);
//Set the type class to the type property defaulting to String if not found
Class<?> typeClass = typeInfo.getOrDefault(TYPE_PROPERTY, String.class);
//Check for a collection
if (Collection.class.isAssignableFrom(typeClass)) {
return new CollectionValueType(typeClass,
typeInfo.getOrDefault(ELEMENT_TYPE_PROPERTY, String.class)
);
}
//Check for a Map
if (Map.class.isAssignableFrom(typeClass)) {
return new MapValueType(typeClass,
typeInfo.getOrDefault(KEY_TYPE_PROPERTY, String.class),
typeInfo.getOrDefault(VALUE_TYPE_PROPERTY, String.class)
);
}
return new SimpleValueType(typeClass);
}
/**
* Converts the given input to the type wrapped by the ValueType
*
* @param <T> the wrapped type
* @param input the object to be converted
* @return the result of the conversion
*/
public abstract <T> T convert(Object input);
@Override
public String toString() {
return this.getClass()
.getSimpleName() + "{type=" + getType() + ", generics=" + Arrays.toString(getParameterTypes()) + "}";
}
/**
* Creates a value type for the given class
*
* @param clazz the class information for the value type
* @return the value type
*/
public static ValueType of(@NonNull Class<?> clazz) {
return new SimpleValueType(clazz);
}
private static class SimpleValueType extends ValueType implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<?> clazz;
SimpleValueType(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public Class<?> getType() {
return clazz;
}
@Override
public Class<?>[] getParameterTypes() {
return new Class<?>[0];
}
@Override
public <T> T convert(Object input) {
if (clazz.isInstance(input)) {
return Cast.as(input);
}
return Cast.as(Convert.convert(input, clazz));
}
}
private static class CollectionValueType extends ValueType implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<?> collectionType;
private final Class<?> genericType;
/**
* Instantiates a new Collection value type.
*
* @param collectionType the collection type
* @param genericType the generic type
*/
CollectionValueType(Class<?> collectionType, Class<?> genericType) {
this.collectionType = collectionType;
this.genericType = genericType;
}
@Override
public Class<?> getType() {
return collectionType;
}
@Override
public Class<?>[] getParameterTypes() {
return new Class<?>[]{genericType};
}
@Override
public <T> T convert(Object input) {
return Cast.as(Convert.convert(input, collectionType, genericType));
}
@Override
public boolean isCollection() {
return true;
}
}
private static class MapValueType extends ValueType implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<?> mapType;
private final Class<?> keyType;
private final Class<?> valueType;
/**
* Instantiates a new Map value type.
*
* @param mapType the map type
* @param keyType the key type
* @param valueType the value type
*/
MapValueType(Class<?> mapType, Class<?> keyType, Class<?> valueType) {
this.keyType = keyType;
this.mapType = mapType;
this.valueType = valueType;
}
@Override
public Class<?> getType() {
return mapType;
}
@Override
public Class<?>[] getParameterTypes() {
return new Class<?>[]{keyType, valueType};
}
@Override
public <T> T convert(Object input) {
return Cast.as(Convert.convert(input, mapType, keyType, valueType));
}
@Override
public boolean isMap() {
return true;
}
}
}//END OF ValueType
|
3e0990668446123355a023f84ba897bbcfc3f25d | 16,147 | java | Java | trunk/test/org/apache/pig/test/TestStreamingLocal.java | kaituo/sedge | 2e5d37da0f82a65cd5bd5bcd88f85cc6913e3f0f | [
"MIT"
] | 8 | 2015-03-24T20:30:12.000Z | 2022-03-13T09:03:39.000Z | trunk/test/org/apache/pig/test/TestStreamingLocal.java | kaituo/sedge | 2e5d37da0f82a65cd5bd5bcd88f85cc6913e3f0f | [
"MIT"
] | null | null | null | trunk/test/org/apache/pig/test/TestStreamingLocal.java | kaituo/sedge | 2e5d37da0f82a65cd5bd5bcd88f85cc6913e3f0f | [
"MIT"
] | 1 | 2018-08-10T20:38:49.000Z | 2018-08-10T20:38:49.000Z | 43.640541 | 130 | 0.556574 | 4,029 | /*
* 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.pig.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.builtin.PigStorage;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestStreamingLocal extends TestCase {
private TupleFactory tf = TupleFactory.getInstance();
PigServer pigServer;
private static final String simpleEchoStreamingCommand;
static {
if (System.getProperty("os.name").toUpperCase().startsWith("WINDOWS"))
simpleEchoStreamingCommand = "perl -ne 'print \\\"$_\\\"'";
else
simpleEchoStreamingCommand = "perl -ne 'print \"$_\"'";
}
@Before
@Override
protected void setUp() throws Exception {
pigServer = new PigServer("local");
}
@After
@Override
protected void tearDown() throws Exception {
pigServer.shutdown();
}
private Tuple[] setupExpectedResults(Object[] firstField,
Object[] secondField) throws ExecException {
Assert.assertEquals(firstField.length, secondField.length);
Tuple[] expectedResults = new Tuple[firstField.length];
for (int i=0; i < expectedResults.length; ++i) {
expectedResults[i] = tf.newTuple(2);
expectedResults[i].set(0, firstField[i]);
expectedResults[i].set(1, secondField[i]);
}
return expectedResults;
}
@Test
public void testSimpleMapSideStreaming()
throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1", "B,2", "C,3", "D,2",
"A,5", "B,5", "C,8", "A,8",
"D,8", "A,9"});
// Expected results
String[] expectedFirstFields = new String[] {"A", "B", "C", "A", "D", "A"};
Integer[] expectedSecondFields = new Integer[] {5, 5, 8, 8, 8, 9};
boolean[] withTypes = {true, false};
for (int i = 0; i < withTypes.length; i++) {
Tuple[] expectedResults = null;
if(withTypes[i] == true) {
expectedResults =
setupExpectedResults(expectedFirstFields, expectedSecondFields);
} else {
expectedResults = setupExpectedResults(Util
.toDataByteArrays(expectedFirstFields), Util
.toDataByteArrays(expectedSecondFields));
}
// Pig query to run
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';");
pigServer.registerQuery("S1 = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "`;");
if(withTypes[i] == true) {
pigServer.registerQuery("OP = stream S1 through `" +
simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);");
} else {
pigServer.registerQuery("OP = stream S1 through `" +
simpleEchoStreamingCommand + "`;");
}
// Run the query and check the results
Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults);
}
}
@Test
public void testSimpleMapSideStreamingWithOutputSchema()
throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1", "B,2", "C,3", "D,2",
"A,5", "B,5", "C,8", "A,8",
"D,8", "A,9"});
// Expected results
Object[] expectedFirstFields = new String[] {"C", "A", "D", "A"};
Object[] expectedSecondFields = new Integer[] {8, 8, 8, 9};
boolean[] withTypes = {true, false};
for (int i = 0; i < withTypes.length; i++) {
Tuple[] expectedResults = null;
if(withTypes[i] == true) {
expectedResults =
setupExpectedResults(expectedFirstFields, expectedSecondFields);
} else {
expectedResults = setupExpectedResults(Util
.toDataByteArrays(expectedFirstFields), Util
.toDataByteArrays(expectedSecondFields));
}
// Pig query to run
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';");
if(withTypes[i] == true) {
pigServer.registerQuery("STREAMED_DATA = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);");
} else {
pigServer.registerQuery("STREAMED_DATA = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "` as (f0, f1);");
}
pigServer.registerQuery("OP = filter STREAMED_DATA by f1 > 6;");
// Run the query and check the results
Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults);
}
}
@Test
public void testSimpleReduceSideStreamingAfterFlatten()
throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1", "B,2", "C,3", "D,2",
"A,5", "B,5", "C,8", "A,8",
"D,8", "A,9"});
// Expected results
String[] expectedFirstFields = new String[] {"A", "A", "A", "B", "C", "D"};
Integer[] expectedSecondFields = new Integer[] {5, 8, 9, 5, 8, 8};
boolean[] withTypes = {true, false};
for (int i = 0; i < withTypes.length; i++) {
Tuple[] expectedResults = null;
if(withTypes[i] == true) {
expectedResults =
setupExpectedResults(expectedFirstFields, expectedSecondFields);
} else {
expectedResults = setupExpectedResults(Util
.toDataByteArrays(expectedFirstFields), Util
.toDataByteArrays(expectedSecondFields));
}
// Pig query to run
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';");
pigServer.registerQuery("GROUPED_DATA = group FILTERED_DATA by $0;");
pigServer.registerQuery("FLATTENED_GROUPED_DATA = foreach GROUPED_DATA " +
"generate flatten($1);");
pigServer.registerQuery("S1 = stream FLATTENED_GROUPED_DATA through `" +
simpleEchoStreamingCommand + "`;");
if(withTypes[i] == true) {
pigServer.registerQuery("OP = stream S1 through `" +
simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);");
} else {
pigServer.registerQuery("OP = stream S1 through `" +
simpleEchoStreamingCommand + "`;");
}
// Run the query and check the results
Util.checkQueryOutputsAfterSort(pigServer.openIterator("OP"), expectedResults);
}
}
@Test
public void testSimpleOrderedReduceSideStreamingAfterFlatten() throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1,2,3", "B,2,4,5",
"C,3,1,2", "D,2,5,2",
"A,5,5,1", "B,5,7,4",
"C,8,9,2", "A,8,4,5",
"D,8,8,3", "A,9,2,5"}
);
// Expected results
String[] expectedFirstFields =
new String[] {"A", "A", "A", "A", "B", "B", "C", "C", "D", "D"};
Integer[] expectedSecondFields = new Integer[] {1, 9, 8, 5, 2, 5, 3, 8, 2, 8};
Integer[] expectedThirdFields = new Integer[] {2, 2, 4, 5, 4, 7, 1, 9, 5, 8};
Integer[] expectedFourthFields = new Integer[] {3, 5, 5, 1, 5, 4, 2, 2, 2, 3};
Tuple[] expectedResults = new Tuple[10];
for (int i = 0; i < expectedResults.length; ++i) {
expectedResults[i] = tf.newTuple(4);
expectedResults[i].set(0, expectedFirstFields[i]);
expectedResults[i].set(1, expectedSecondFields[i]);
expectedResults[i].set(2, expectedThirdFields[i]);
expectedResults[i].set(3, expectedFourthFields[i]);
}
//setupExpectedResults(expectedFirstFields, expectedSecondFields);
// Pig query to run
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';");
pigServer.registerQuery("S1 = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "`;");
pigServer.registerQuery("S2 = stream S1 through `" +
simpleEchoStreamingCommand + "`;");
pigServer.registerQuery("GROUPED_DATA = group IP by $0;");
pigServer.registerQuery("ORDERED_DATA = foreach GROUPED_DATA { " +
" D = order IP BY $2, $3;" +
" generate flatten(D);" +
"};");
pigServer.registerQuery("S3 = stream ORDERED_DATA through `" +
simpleEchoStreamingCommand + "`;");
pigServer.registerQuery("OP = stream S3 through `" +
simpleEchoStreamingCommand + "` as (f0:chararray, f1:int, f2:int, f3:int);");
// Run the query and check the results
Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults);
}
@Test
public void testSimpleMapSideStreamingWithUnixPipes()
throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1", "B,2", "C,3", "D,2",
"A,5", "B,5", "C,8", "A,8",
"D,8", "A,9"});
// Expected results
String[] expectedFirstFields =
new String[] {"A", "B", "C", "D", "A", "B", "C", "A", "D", "A"};
Integer[] expectedSecondFields = new Integer[] {1, 2, 3, 2, 5, 5, 8, 8, 8, 9};
boolean[] withTypes = {true, false};
for (int i = 0; i < withTypes.length; i++) {
Tuple[] expectedResults = null;
if(withTypes[i] == true) {
expectedResults =
setupExpectedResults(expectedFirstFields, expectedSecondFields);
} else {
expectedResults =
setupExpectedResults(Util.toDataByteArrays(expectedFirstFields), Util.toDataByteArrays(expectedSecondFields));
}
// Pig query to run
pigServer.registerQuery("define CMD `" + simpleEchoStreamingCommand +
" | " + simpleEchoStreamingCommand + "`;");
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
if(withTypes[i] == true) {
pigServer.registerQuery("OP = stream IP through CMD as (f0:chararray, f1:int);");
} else {
pigServer.registerQuery("OP = stream IP through CMD;");
}
// Run the query and check the results
Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults);
}
}
@Test
public void testJoinTwoStreamingRelations()
throws Exception {
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<10000; i++) {
list.add("A," + i);
}
File input = Util.createInputFile("tmp", "", list.toArray(new String[0]));
// Expected results
Tuple expected = TupleFactory.getInstance().newTuple(4);
expected.set(0, "A");
expected.set(1, 0);
expected.set(2, "A");
expected.set(3, 0);
pigServer.registerQuery("A = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',') as (a0, a1);");
pigServer.registerQuery("B = stream A through `head -1` as (a0, a1);");
pigServer.registerQuery("C = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',') as (a0, a1);");
pigServer.registerQuery("D = stream C through `head -1` as (a0, a1);");
pigServer.registerQuery("E = join B by a0, D by a0;");
Iterator<Tuple> iter = pigServer.openIterator("E");
int count = 0;
while (iter.hasNext()) {
Assert.assertEquals(expected.toString(), iter.next().toString());
count++;
}
Assert.assertTrue(count == 1);
}
@Test
public void testLocalNegativeLoadStoreOptimization() throws Exception {
testNegativeLoadStoreOptimization(ExecType.LOCAL);
}
private void testNegativeLoadStoreOptimization(ExecType execType)
throws Exception {
File input = Util.createInputFile("tmp", "",
new String[] {"A,1", "B,2", "C,3", "D,2",
"A,5", "B,5", "C,8", "A,8",
"D,8", "A,9"});
// Expected results
String[] expectedFirstFields = new String[] {"A", "B", "C", "A", "D", "A"};
Integer[] expectedSecondFields = new Integer[] {5, 5, 8, 8, 8, 9};
boolean[] withTypes = {true, false};
for (int i = 0; i < withTypes.length; i++) {
Tuple[] expectedResults = null;
if(withTypes[i] == true) {
expectedResults =
setupExpectedResults(expectedFirstFields, expectedSecondFields);
} else {
expectedResults = setupExpectedResults(Util
.toDataByteArrays(expectedFirstFields), Util
.toDataByteArrays(expectedSecondFields));
}
// Pig query to run
pigServer.registerQuery("define CMD `"+ simpleEchoStreamingCommand +
"` input(stdin);");
pigServer.registerQuery("IP = load 'file:" + Util.encodeEscape(input.toString()) + "' using " +
PigStorage.class.getName() + "(',');");
pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';");
if(withTypes[i] == true) {
pigServer.registerQuery("OP = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);");
} else {
pigServer.registerQuery("OP = stream FILTERED_DATA through `" +
simpleEchoStreamingCommand + "`;");
}
// Run the query and check the results
Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults);
}
}
}
|
3e0990f8a47a816e15668bcc647e636d6b5e2c10 | 5,278 | java | Java | Corpus/birt/1064.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | 1 | 2022-01-15T02:47:45.000Z | 2022-01-15T02:47:45.000Z | Corpus/birt/1064.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | Corpus/birt/1064.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | 24.211009 | 87 | 0.716938 | 4,030 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.views.attributes.providers;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ImageHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.TextItemHandle;
/**
* AttributeConstant defines property key constant.
*/
public class AttributeConstant
{
public final static String DIS = "DIS";//$NON-NLS-1$
/**
* Width property key
*/
public final static String WIDTH = ReportItemHandle.WIDTH_PROP;
/**
* Height property key
*/
public final static String HEIGHT = ReportItemHandle.HEIGHT_PROP;
/***************************************************************************
* Name property key
*/
public static final String NAME = DesignElementHandle.NAME_PROP;
/**
* Background color property key
*/
public static final String BACKGROUND_COLOR = StyleHandle.BACKGROUND_COLOR_PROP;
/**
* Cell Padding top property key
*/
public static final String PADDING_TOP = StyleHandle.PADDING_TOP_PROP;
/**
* Cell Padding bottom property key
*/
public static final String PADDING_BOTTOM = StyleHandle.PADDING_BOTTOM_PROP;
/**
* Cell Padding left property key
*/
public static final String PADDING_LEFT = StyleHandle.PADDING_LEFT_PROP;
/**
* Cell Padding right property key
*/
public static final String PADDING_RIGHT = StyleHandle.PADDING_RIGHT_PROP;
/**
* DataSet property key
*/
public static final String DATASET = ReportItemHandle.DATA_SET_PROP;
/**
* Font width property key
*/
public static final String FONT_WIDTH = StyleHandle.FONT_WEIGHT_PROP;
/**
* Font name property key
*/
public static final String FONT_FAMILY = StyleHandle.FONT_FAMILY_PROP;
/**
* Font style property key
*/
public static final String FONT_STYLE = StyleHandle.FONT_STYLE_PROP;
/**
* Text underline property key
*/
public static final String TEXT_UNDERLINE = StyleHandle.TEXT_UNDERLINE_PROP;
/**
* Text line through property key
*/
public static final String TEXT_LINE_THROUGH = StyleHandle.TEXT_LINE_THROUGH_PROP;
/**
* Font color property key
*/
public static final String FONT_COLOR = StyleHandle.COLOR_PROP;
/**
* Common presentation of 'border-top-style',
* 'border-left-style','border-bottom-style' and 'border-right-style'
* properties.
*/
public static final String BORDER_STYLE = "ui_border_style";//$NON-NLS-1$
/**
* Border top style property.
*/
public static final String BORDER_TOP_STYLE = StyleHandle.BORDER_TOP_STYLE_PROP;
/**
* Border bottom style property.
*/
public static final String BORDER_BOTTOM_STYLE = StyleHandle.BORDER_BOTTOM_STYLE_PROP;
/**
* Border left style property.
*/
public static final String BORDER_LEFT_STYLE = StyleHandle.BORDER_LEFT_STYLE_PROP;
/**
* Border right style property.
*/
public static final String BORDER_RIGHT_STYLE = StyleHandle.BORDER_RIGHT_STYLE_PROP;
/**
* Common presentation of 'border-top-width',
* 'border-left-width','border-bottom-width' and 'border-right-width'
* properties.
*/
public static final String BORDER_WIDTH = "ui_border_WIDTH";//$NON-NLS-1$
/**
* Border top width property.
*/
public static final String BORDER_TOP_WIDTH = StyleHandle.BORDER_TOP_WIDTH_PROP;
/**
* Border bottom width property.
*/
public static final String BORDER_BOTTOM_WIDTH = StyleHandle.BORDER_BOTTOM_WIDTH_PROP;
/**
* Border left width property.
*/
public static final String BORDER_LEFT_WIDTH = StyleHandle.BORDER_LEFT_WIDTH_PROP;
/**
* Border right width property.
*/
public static final String BORDER_RIGHT_WIDTH = StyleHandle.BORDER_RIGHT_WIDTH_PROP;
/**
* Border top color property.
*/
public static final String BORDER_TOP_COLOR = StyleHandle.BORDER_TOP_COLOR_PROP;
/**
* Border bottom color property.
*/
public static final String BORDER_BOTTOM_COLOR = StyleHandle.BORDER_BOTTOM_COLOR_PROP;
/**
* Border left color property.
*/
public static final String BORDER_LEFT_COLOR = StyleHandle.BORDER_LEFT_COLOR_PROP;
/**
* Border right color property.
*/
public static final String BORDER_RIGHT_COLOR = StyleHandle.BORDER_RIGHT_COLOR_PROP;
public static final String TEXT_FORMAT = TextItemHandle.CONTENT_TYPE_PROP;
public static final String TEXT_ALIGN = StyleHandle.TEXT_ALIGN_PROP;
public static final String FONT_SIZE = StyleHandle.FONT_SIZE_PROP;
// public static final String TEXT_ALTERNATE = TextItem.HELP_TEXT_PROP;
public static final String IMAGE_ALTERNATE = ImageHandle.ALT_TEXT_PROP;
public static final String HORIZONTAL_ALIGN = "GUI_HORIZONTAL_ALIGN";//$NON-NLS-1$
} |
3e0991d742d2f51b31ab9eecdeacb4fe2afa430e | 4,052 | java | Java | name.martingeisse.miner-server/src/generated/java/name/martingeisse/webide/entity/QPlayer.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | 1 | 2015-06-16T13:18:45.000Z | 2015-06-16T13:18:45.000Z | name.martingeisse.miner-server/src/generated/java/name/martingeisse/webide/entity/QPlayer.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | 3 | 2022-03-08T21:11:04.000Z | 2022-03-08T21:11:15.000Z | name.martingeisse.miner-server/src/generated/java/name/martingeisse/webide/entity/QPlayer.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | null | null | null | 30.69697 | 148 | 0.679911 | 4,031 | /**
* This file was generated from the database schema.
*/
package name.martingeisse.webide.entity;
import javax.annotation.Generated;
import com.mysema.query.types.*;
import com.mysema.query.types.path.*;
import static com.mysema.query.types.PathMetadataFactory.*;
/**
* QPlayer is a Querydsl query type for Player
*/
@Generated("name.martingeisse.sql.codegen.MetaDataSerializer")
public class QPlayer extends com.mysema.query.sql.RelationalPathBase<Player> {
private static final long serialVersionUID = 584492778;
/**
* The default instance of this class.
*/
public static final QPlayer player = new QPlayer("player");
/**
* Metamodel property for property 'coins'
*/
public final NumberPath<Long> coins = createNumber("coins", Long.class);
/**
* Metamodel property for property 'deleted'
*/
public final BooleanPath deleted = createBoolean("deleted");
/**
* Metamodel property for property 'faction_id'
*/
public final NumberPath<Long> factionId = createNumber("faction_id", Long.class);
/**
* Metamodel property for property 'id'
*/
public final NumberPath<Long> id = createNumber("id", Long.class);
/**
* Metamodel property for property 'left_angle'
*/
public final NumberPath<java.math.BigDecimal> leftAngle = createNumber("left_angle", java.math.BigDecimal.class);
/**
* Metamodel property for property 'name'
*/
public final StringPath name = createString("name");
/**
* Metamodel property for property 'up_angle'
*/
public final NumberPath<java.math.BigDecimal> upAngle = createNumber("up_angle", java.math.BigDecimal.class);
/**
* Metamodel property for property 'user_account_id'
*/
public final NumberPath<Long> userAccountId = createNumber("user_account_id", Long.class);
/**
* Metamodel property for property 'x'
*/
public final NumberPath<java.math.BigDecimal> x = createNumber("x", java.math.BigDecimal.class);
/**
* Metamodel property for property 'y'
*/
public final NumberPath<java.math.BigDecimal> y = createNumber("y", java.math.BigDecimal.class);
/**
* Metamodel property for property 'z'
*/
public final NumberPath<java.math.BigDecimal> z = createNumber("z", java.math.BigDecimal.class);
/**
* Metamodel property for primary key 'PRIMARY'
*/
public final com.mysema.query.sql.PrimaryKey<Player> pk_primary = createPrimaryKey(id);
/**
* Metamodel property for foreign key 'player_ibfk_1'
*/
public final com.mysema.query.sql.ForeignKey<UserAccount> fk_playerIbfk1 = createForeignKey(userAccountId, "id");
/**
* Metamodel property for foreign key 'player_ibfk_2'
*/
public final com.mysema.query.sql.ForeignKey<Faction> fk_playerIbfk2 = createForeignKey(factionId, "id");
/**
* Metamodel property for reverse foreign key 'player_awarded_achievement_ibfk_1'
*/
public final com.mysema.query.sql.ForeignKey<PlayerAwardedAchievement> fk__playerAwardedAchievementIbfk1 = createInvForeignKey(id, "player_id");
/**
* Metamodel property for reverse foreign key 'player_inventory_slot_ibfk_1'
*/
public final com.mysema.query.sql.ForeignKey<PlayerInventorySlot> fk__playerInventorySlotIbfk1 = createInvForeignKey(id, "player_id");
/**
* Path-variable based constructor.
* @param variable the path variable for this entity
*/
public QPlayer(String variable) {
super(Player.class, forVariable(variable), "null", "player");
}
/**
* Path based constructor
* @param path the path for this entity
*/
public QPlayer(Path<? extends Player> path) {
super(path.getType(), path.getMetadata(), "null", "player");
}
/**
* Path metadata based constructor
* @param metadata the path metadata for this entity
*/
public QPlayer(PathMetadata<?> metadata) {
super(Player.class, metadata, "null", "player");
}
}
|
3e09926aaf4cbfb0dc33c276e33ffb46748eca97 | 6,844 | java | Java | test/src/test/java/org/corfudb/integration/ServerRestartIT.java | hartsock/CorfuDB | c8ecd5d512231554feef39a3f9af60d127d5f87d | [
"Apache-2.0"
] | null | null | null | test/src/test/java/org/corfudb/integration/ServerRestartIT.java | hartsock/CorfuDB | c8ecd5d512231554feef39a3f9af60d127d5f87d | [
"Apache-2.0"
] | null | null | null | test/src/test/java/org/corfudb/integration/ServerRestartIT.java | hartsock/CorfuDB | c8ecd5d512231554feef39a3f9af60d127d5f87d | [
"Apache-2.0"
] | null | null | null | 38.022222 | 106 | 0.586937 | 4,032 | package org.corfudb.integration;
import org.corfudb.runtime.CorfuRuntime;
import org.corfudb.runtime.exceptions.NetworkException;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the recovery of the Corfu instance.
* WARNING: These tests kill all existing corfu instances on the node to run
* fresh servers.
* Created by zlokhandwala on 4/25/17.
*/
public class ServerRestartIT extends AbstractIT {
// Total number of iterations of randomized failovers.
static int ITERATIONS;
// Percentage of Client restarts.
static int CLIENT_RESTART_PERCENTAGE;
// Percentage of Server restarts.
static int SERVER_RESTART_PERCENTAGE;
static String corfuSingleNodeHost;
static int corfuSingleNodePort;
@Before
public void loadProperties() {
ITERATIONS = Integer.parseInt((String) PROPERTIES.get("RandomizedRecoveryIterations"));
CLIENT_RESTART_PERCENTAGE = Integer.parseInt((String) PROPERTIES.get("ClientRestartPercentage"));
SERVER_RESTART_PERCENTAGE = Integer.parseInt((String) PROPERTIES.get("ServerRestartPercentage"));
corfuSingleNodeHost = (String) PROPERTIES.get("corfuSingleNodeHost");
corfuSingleNodePort = Integer.parseInt((String) PROPERTIES.get("corfuSingleNodePort"));
}
/**
* Randomized tests with mixed client and server failovers.
*
* @throws Exception
*/
@Test
public void testRandomizedRecovery() throws Exception {
// Total percentage.
final int TOTAL_PERCENTAGE = 100;
// Number of maps or streams to test recovery on.
final int MAPS = 3;
// Number of insertions in map in each iteration.
final int INSERTIONS = 100;
// Number of keys to be used throughout the test in each map.
final int KEYS = 20;
// Logs the server and client state in each iteration with the
// maps used and keys and values inserted in each iteration.
final boolean TEST_SEQUENCE_LOGGING = true;
final File testSequenceLogFile = new File(TEST_SEQUENCE_LOG_PATH);
if (!testSequenceLogFile.exists()) {
testSequenceLogFile.createNewFile();
}
// Keep this print at all times to reproduce any failed test.
final Random randomSeed = new Random();
final long SEED = randomSeed.nextLong();
final Random rand = new Random(SEED);
System.out.println("SEED = " + SEED);
// Runs the corfu server. Expect slight delay until server is running.
Process corfuServerProcess = runCorfuServer(corfuSingleNodeHost, corfuSingleNodePort);
// List of runtimes to free resources when not needed.
List<CorfuRuntime> runtimeList = new ArrayList<>();
List<Map<String, Integer>> smrMapList = new ArrayList<>();
for (int i = 0; i < MAPS; i++) {
CorfuRuntime runtime = createDefaultRuntime();
runtimeList.add(runtime);
smrMapList.add(createMap(runtime, Integer.toString(i)));
}
List<Map<String, Integer>> expectedMapList = new ArrayList<>();
for (int i = 0; i < MAPS; i++) {
expectedMapList.add(new HashMap<>());
}
try (final FileOutputStream fos = new FileOutputStream(testSequenceLogFile)) {
for (int i = 0; i < ITERATIONS; i++) {
System.out.println("Iteration #" + i);
boolean serverRestart = rand.nextInt(TOTAL_PERCENTAGE) < SERVER_RESTART_PERCENTAGE;
boolean clientRestart = rand.nextInt(TOTAL_PERCENTAGE) < CLIENT_RESTART_PERCENTAGE;
if (TEST_SEQUENCE_LOGGING) {
fos.write(getRestartStateRecord(i, serverRestart, clientRestart).getBytes());
}
if (clientRestart) {
smrMapList.clear();
runtimeList.forEach(CorfuRuntime::shutdown);
for (int j = 0; j < MAPS; j++) {
CorfuRuntime runtime = createDefaultRuntime();
runtimeList.add(runtime);
smrMapList.add(createMap(runtime, Integer.toString(j)));
}
}
// Map assertions
while (true) {
try {
if (i != 0) {
for (int j = 0; j < MAPS; j++) {
assertThat(smrMapList.get(j)).isEqualTo(expectedMapList.get(j));
}
}
break;
} catch (NetworkException ne) {
Thread.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
}
}
// Map insertions
for (int j = 0; j < INSERTIONS; j++) {
int value = rand.nextInt();
int map = rand.nextInt(MAPS);
String key = Integer.toString(rand.nextInt(KEYS));
smrMapList.get(map).put(key, value);
expectedMapList.get(map).put(key, value);
if (TEST_SEQUENCE_LOGGING) {
fos.write(getMapInsertion(i, map, key, value).getBytes());
}
}
if (TEST_SEQUENCE_LOGGING) {
fos.write(getMapStateRecord(i, expectedMapList).getBytes());
}
if (serverRestart) {
assertThat(shutdownCorfuServer(corfuServerProcess)).isTrue();
corfuServerProcess = runCorfuServer();
}
}
assertThat(shutdownCorfuServer(corfuServerProcess)).isTrue();
} catch (Exception e) {
throw e;
}
}
private String getRestartStateRecord(int iteration, boolean serverRestart, boolean clientRestart) {
return "[" + iteration + "]: ServerRestart=" + serverRestart + ", ClientRestart=" + clientRestart;
}
private String getMapStateRecord(int iteration, List<Map<String, Integer>> mapStateList) {
StringBuilder sb = new StringBuilder();
sb.append("[" + iteration + "]: Map State :\n");
for (int i = 0; i < mapStateList.size(); i ++){
sb.append("map#" + i + " map = " + mapStateList.get(i).toString() + "\n");
}
return sb.toString();
}
private String getMapInsertion(int iteration, int streamId, String key, int value) {
return "[" + iteration + "]: Map put => streamId=" + streamId + " key=" + key + " value=" + value;
}
}
|
3e0992f2ba3f239b83ee33cf01edb33a4e350b91 | 3,362 | java | Java | src/chainrepublik/kernel/net_stat/tables/CRentContracts.java | chainrepublik/java | c046ac99bf74792812cc25ca59548a8610291ff8 | [
"MIT"
] | null | null | null | src/chainrepublik/kernel/net_stat/tables/CRentContracts.java | chainrepublik/java | c046ac99bf74792812cc25ca59548a8610291ff8 | [
"MIT"
] | null | null | null | src/chainrepublik/kernel/net_stat/tables/CRentContracts.java | chainrepublik/java | c046ac99bf74792812cc25ca59548a8610291ff8 | [
"MIT"
] | 1 | 2020-07-21T08:28:18.000Z | 2020-07-21T08:28:18.000Z | 40.506024 | 111 | 0.468174 | 4,033 | package chainrepublik.kernel.net_stat.tables;
import chainrepublik.kernel.UTILS;
import chainrepublik.kernel.net_stat.CTable;
import java.sql.ResultSet;
public class CRentContracts extends CTable
{
public CRentContracts()
{
super("rent_contracts");
}
public void create() throws Exception
{
if (!this.tableExist(this.name))
{
// Status
System.out.print("Creating table "+this.name+"...");
// Create
UTILS.DB.executeUpdate("CREATE TABLE rent_contracts (ID BIGINT(20) AUTO_INCREMENT PRIMARY KEY, "
+ "stocID VARCHAR(250) NOT NULL DEFAULT '', "
+ "from_adr VARCHAR(250) NOT NULL DEFAULT '', "
+ "to_adr VARCHAR(250) NOT NULL DEFAULT '', "
+ "price DOUBLE(20,4) NOT NULL DEFAULT '0.0000', "
+ "expires BIGINT(20) NOT NULL DEFAULT '0', "
+ "block BIGINT(20) NOT NULL DEFAULT '0')");
// Indexes
UTILS.DB.executeUpdate("CREATE INDEX rent_contracts_prod ON rent_contracts(stocID)");
UTILS.DB.executeUpdate("CREATE INDEX rent_contracts_from_adr ON rent_contracts(from_adr)");
UTILS.DB.executeUpdate("CREATE INDEX rent_contracts_to_adr ON rent_contracts(to_adr)");
UTILS.DB.executeUpdate("CREATE INDEX rent_contracts_expires ON rent_contracts(expires)");
UTILS.DB.executeUpdate("CREATE INDEX rent_contracts_block ON rent_contracts(block)");
// Confirm
System.out.println("Done.");
}
}
public void expired(long block) throws Exception
{
// Load expired contracts
ResultSet rs=UTILS.DB.executeQuery("SELECT * "
+ "FROM rent_contracts "
+ "WHERE expires>0 "
+ "AND expires<="+block);
// Loop
while (rs.next())
{
// Stoc ID
long stocID=rs.getLong("stocID");
// Update stocuri
UTILS.DB.executeUpdate("UPDATE stocuri "
+ "SET rented_to='', "
+ "rented_expires=0, "
+ "in_use=0 "
+ "WHERE stocID='"+stocID+"'");
// Refresh energy
UTILS.BASIC.refreshEnergy(rs.getString("to_adr"));
// Event
UTILS.BASIC.newEvent(rs.getString("to_adr"),
"One of your rent contracts has expired. Check your portofolio.",
block);
// Remove
UTILS.DB.executeUpdate("DELETE FROM rent_contracts WHERE stocID='"+stocID+"'");
}
}
public void reorganize(long block, String chk_hash) throws Exception
{
// Load checkpoint
loadCheckpoint(chk_hash);
}
}
|
3e0993abc5ba51f1ca37aba3a612db623d000a80 | 372 | java | Java | src/com/md/appuserconnect/core/utils/JSONObject2.java | michaeldtz/AppUserConnect | 1d0bc41e6b20014720a66e26059909ac05a7b87e | [
"MIT"
] | null | null | null | src/com/md/appuserconnect/core/utils/JSONObject2.java | michaeldtz/AppUserConnect | 1d0bc41e6b20014720a66e26059909ac05a7b87e | [
"MIT"
] | null | null | null | src/com/md/appuserconnect/core/utils/JSONObject2.java | michaeldtz/AppUserConnect | 1d0bc41e6b20014720a66e26059909ac05a7b87e | [
"MIT"
] | null | null | null | 20.666667 | 77 | 0.795699 | 4,034 | package com.md.appuserconnect.core.utils;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
public class JSONObject2 extends JSONObject {
public void sendAsRepsonse(HttpServletResponse response) throws IOException{
response.setContentType("text/plain");
response.getWriter().println(this.toString());
}
}
|
3e0994109a0c9f78480bce01b46e6a60e25cd73e | 2,256 | java | Java | src/main/java/it/fb5/imgshare/imgshare/controller/ImageController.java | mpotthoff/spring-boot-demo | edf86f8652ba850ad0062f92fab0f44e6d591b28 | [
"MIT"
] | null | null | null | src/main/java/it/fb5/imgshare/imgshare/controller/ImageController.java | mpotthoff/spring-boot-demo | edf86f8652ba850ad0062f92fab0f44e6d591b28 | [
"MIT"
] | null | null | null | src/main/java/it/fb5/imgshare/imgshare/controller/ImageController.java | mpotthoff/spring-boot-demo | edf86f8652ba850ad0062f92fab0f44e6d591b28 | [
"MIT"
] | null | null | null | 35.809524 | 89 | 0.741135 | 4,035 | package it.fb5.imgshare.imgshare.controller;
import it.fb5.imgshare.imgshare.configuration.SecurityPrincipal;
import it.fb5.imgshare.imgshare.dto.ImageDto;
import it.fb5.imgshare.imgshare.service.ImageService;
import java.io.IOException;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ImageController {
private final ImageService imageService;
@Autowired
public ImageController(ImageService imageService) {
this.imageService = imageService;
}
@GetMapping("/i/{id}.png")
public ResponseEntity<byte[]> getImage(@PathVariable long id,
@RequestParam(name = "maxWidth", defaultValue = "0") int maxWidth)
throws IOException {
byte[] data = this.imageService.getImageData(id, maxWidth);
if (data == null) {
return ResponseEntity.notFound()
.cacheControl(CacheControl.noCache())
.build();
}
var headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
headers.setCacheControl(CacheControl.maxAge(Duration.ofDays(1)));
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
@PostMapping("/upload")
public ResponseEntity<ImageDto> uploadImage(@RequestParam("file") MultipartFile file,
Authentication authentication) throws IOException {
final var principal = SecurityPrincipal.getPrincipal(authentication);
byte[] data = file.getBytes();
return ResponseEntity.ok(this.imageService.createImage(data, principal));
}
}
|
3e0994310979cbac2e0c9840a6b297a65b580400 | 5,009 | java | Java | app/src/main/java/com/italankin/fifteen/export/RecordsExporter.java | italankin/15Puzzle | 7ad97681c3a6424610c872d7f560cad3f4352dfb | [
"MIT"
] | 27 | 2017-05-08T10:10:55.000Z | 2022-01-27T21:20:55.000Z | app/src/main/java/com/italankin/fifteen/export/RecordsExporter.java | italankin/15Puzzle | 7ad97681c3a6424610c872d7f560cad3f4352dfb | [
"MIT"
] | 2 | 2017-05-05T02:52:07.000Z | 2020-03-08T00:24:13.000Z | app/src/main/java/com/italankin/fifteen/export/RecordsExporter.java | italankin/15Puzzle | 7ad97681c3a6424610c872d7f560cad3f4352dfb | [
"MIT"
] | 13 | 2017-12-05T18:05:16.000Z | 2021-12-27T13:49:35.000Z | 38.829457 | 121 | 0.5556 | 4,036 | package com.italankin.fifteen.export;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import com.italankin.fifteen.Constants;
import com.italankin.fifteen.DBHelper;
import com.italankin.fifteen.Logger;
import com.italankin.fifteen.R;
import com.italankin.fifteen.Settings;
import com.italankin.fifteen.Tools;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import static java.nio.charset.StandardCharsets.UTF_8;
public class RecordsExporter implements Exporter {
private static final String DEFAULT_FILENAME = "15-puzzle-records.csv";
private static final char DELIMITER = ';';
private final Context context;
private final DBHelper dbHelper;
private final Executor executor = Executors.newSingleThreadExecutor();
private final Handler handler;
public RecordsExporter(Context context, DBHelper dbHelper) {
this.context = context;
this.dbHelper = dbHelper;
this.handler = new Handler(context.getMainLooper());
}
@Override
public void export(Uri uri, Callback callback) {
executor.execute(new ExportTask(uri, callback));
}
@Override
public String defaultFilename() {
return DEFAULT_FILENAME;
}
private class ExportTask implements Runnable {
private final Uri uri;
private final Callback callback;
ExportTask(Uri uri, Callback callback) {
this.uri = uri;
this.callback = callback;
}
@Override
public void run() {
try {
ContentResolver resolver = context.getContentResolver();
try (OutputStreamWriter w = new OutputStreamWriter(resolver.openOutputStream(uri), UTF_8)) {
w.write(context.getString(R.string.export_type));
w.write(DELIMITER);
w.write(context.getString(R.string.export_hard));
w.write(DELIMITER);
w.write(context.getString(R.string.export_width));
w.write(DELIMITER);
w.write(context.getString(R.string.export_height));
w.write(DELIMITER);
w.write(context.getString(R.string.export_time));
w.write(DELIMITER);
w.write(context.getString(R.string.export_moves));
w.write(DELIMITER);
w.write(context.getString(R.string.export_date));
w.write('\n');
try (Cursor cursor = dbHelper.queryAll()) {
if (cursor.moveToFirst()) {
int indexType = cursor.getColumnIndex(DBHelper.KEY_TYPE);
int indexHard = cursor.getColumnIndex(DBHelper.KEY_HARDMODE);
int indexWidth = cursor.getColumnIndex(DBHelper.KEY_WIDTH);
int indexHeight = cursor.getColumnIndex(DBHelper.KEY_HEIGHT);
int indexTime = cursor.getColumnIndex(DBHelper.KEY_TIME);
int indexMoves = cursor.getColumnIndex(DBHelper.KEY_MOVES);
int indexDate = cursor.getColumnIndex(DBHelper.KEY_TIMESTAMP);
String[] types = context.getResources().getStringArray(R.array.game_types);
do {
w.write(types[cursor.getInt(indexType)]);
w.write(DELIMITER);
w.write(String.valueOf(cursor.getInt(indexHard)));
w.write(DELIMITER);
w.write(String.valueOf(cursor.getInt(indexWidth)));
w.write(DELIMITER);
w.write(String.valueOf(cursor.getInt(indexHeight)));
w.write(DELIMITER);
w.write(Tools.timeToString(Constants.TIME_FORMAT_SEC_MS_LONG, cursor.getInt(indexTime)));
w.write(DELIMITER);
w.write(String.valueOf(cursor.getInt(indexMoves)));
w.write(DELIMITER);
Date d = new Date(cursor.getLong(indexDate));
String timestamp = Settings.dateFormat.format(d);
w.write(timestamp);
w.write('\n');
} while (cursor.moveToNext());
}
}
handler.post(callback::onExportSuccess);
}
} catch (Exception e) {
Logger.e(e, "RecordsExporter error:");
handler.post(callback::onExportError);
}
}
}
}
|
3e099466c601a772a20679df31b05b9cc4b3a27b | 2,808 | java | Java | java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.desktop/sun/awt/shell/DefaultShellFolder.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.desktop/sun/awt/shell/DefaultShellFolder.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.desktop/sun/awt/shell/DefaultShellFolder.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | 22.645161 | 79 | 0.584046 | 4,037 | /*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package sun.awt.shell;
import java.io.File;
import java.security.AccessController;
import javax.swing.Icon;
import sun.security.action.GetPropertyAction;
/**
* @author Michael Martak
* @since 1.4
*/
@SuppressWarnings("serial") // JDK-implementation class
class DefaultShellFolder extends ShellFolder {
/**
* Create a file system shell folder from a file
*/
DefaultShellFolder(ShellFolder parent, File f) {
super(parent, f.getAbsolutePath());
}
/**
* This method is implemented to make sure that no instances
* of {@code ShellFolder} are ever serialized. An instance of
* this default implementation can always be represented with a
* {@code java.io.File} object instead.
*
* @return a java.io.File replacement object.
*/
protected Object writeReplace() throws java.io.ObjectStreamException {
return new File(getPath());
}
/**
* @return An array of shell folders that are children of this shell folder
* object, null if this shell folder is empty.
*/
public File[] listFiles() {
File[] files = super.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
files[i] = new DefaultShellFolder(this, files[i]);
}
}
return files;
}
/**
* @return Whether this shell folder is a link
*/
public boolean isLink() {
return false; // Not supported by default
}
/**
* @return Whether this shell folder is marked as hidden
*/
public boolean isHidden() {
String fileName = getName();
if (fileName.length() > 0) {
return (fileName.charAt(0) == '.');
}
return false;
}
/**
* @return The shell folder linked to by this shell folder, or null
* if this shell folder is not a link
*/
public ShellFolder getLinkLocation() {
return null; // Not supported by default
}
/**
* @return The name used to display this shell folder
*/
public String getDisplayName() {
return getName();
}
/**
* @return The type of shell folder as a string
*/
public String getFolderType() {
if (isDirectory()) {
return "File Folder"; // TODO : LOCALIZE THIS STRING!!!
} else {
return "File"; // TODO : LOCALIZE THIS STRING!!!
}
}
/**
* @return The executable type as a string
*/
public String getExecutableType() {
return null; // Not supported by default
}
}
|
3e0995d9497d12cbddf627a7326356922482b44b | 897 | java | Java | ASP_ConstrainedGraphPartitioning/src/java/tests/examples/VoronoiGeneratorDrawer.java | abuzreq/Taksim | 68e518f7e452ca4f099ba729b6900a43ad47be17 | [
"MIT"
] | 5 | 2018-02-03T19:23:09.000Z | 2022-02-24T05:12:16.000Z | ASP_ConstrainedGraphPartitioning/src/java/tests/examples/VoronoiGeneratorDrawer.java | abuzreq/Taksim | 68e518f7e452ca4f099ba729b6900a43ad47be17 | [
"MIT"
] | 1 | 2020-10-14T22:04:01.000Z | 2020-10-15T20:53:30.000Z | ASP_ConstrainedGraphPartitioning/src/java/tests/examples/VoronoiGeneratorDrawer.java | abuzreq/Taksim | 68e518f7e452ca4f099ba729b6900a43ad47be17 | [
"MIT"
] | null | null | null | 15.465517 | 51 | 0.634337 | 4,038 | package examples;
import java.util.concurrent.Callable;
import java.util.function.Function;
import processing.core.PApplet;
public class VoronoiGeneratorDrawer extends PApplet
{
int width,height;
public static VoronoiGeneratorDrawer instance;
public void settings()
{
instance = this;
width = VoronoiGenerator.instance.width;
height = VoronoiGenerator.instance.height;
size(width, height);
}
public void setup()
{
surface.setSize(width, height);
instance = this;
}
public void draw()
{
VoronoiGenerator.instance.draw(this);
}
public static Callable onRight,onLeft;
public void keyPressed()
{
if (key == CODED)
{
try
{
if (keyCode == RIGHT)
{
onRight.call();
}
else if (keyCode == LEFT)
{
onLeft.call();
}
}
catch(Exception e)
{
System.out.println("");
}
}
}
}
|
3e0995d9cca27093fe4317db6e8abe4a34abfa5f | 5,675 | java | Java | shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/context/EncryptSQLRewriteContextDecorator.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 4,372 | 2019-01-16T03:07:05.000Z | 2020-04-17T11:16:15.000Z | shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/context/EncryptSQLRewriteContextDecorator.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 3,040 | 2019-01-16T01:18:40.000Z | 2020-04-17T12:53:05.000Z | shardingsphere-features/shardingsphere-encrypt/shardingsphere-encrypt-core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/context/EncryptSQLRewriteContextDecorator.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 1,515 | 2019-01-16T08:44:17.000Z | 2020-04-17T09:07:53.000Z | 55.097087 | 172 | 0.776564 | 4,039 | /*
* 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.shardingsphere.encrypt.rewrite.context;
import org.apache.shardingsphere.encrypt.constant.EncryptOrder;
import org.apache.shardingsphere.encrypt.rewrite.condition.EncryptCondition;
import org.apache.shardingsphere.encrypt.rewrite.condition.EncryptConditionEngine;
import org.apache.shardingsphere.encrypt.rewrite.parameter.EncryptParameterRewriterBuilder;
import org.apache.shardingsphere.encrypt.rewrite.token.EncryptTokenGenerateBuilder;
import org.apache.shardingsphere.encrypt.rule.EncryptRule;
import org.apache.shardingsphere.infra.binder.statement.CommonSQLStatementContext;
import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;
import org.apache.shardingsphere.infra.binder.type.WhereAvailable;
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.infra.rewrite.context.SQLRewriteContext;
import org.apache.shardingsphere.infra.rewrite.context.SQLRewriteContextDecorator;
import org.apache.shardingsphere.infra.rewrite.parameter.rewriter.ParameterRewriter;
import org.apache.shardingsphere.infra.rewrite.sql.token.generator.SQLTokenGenerator;
import org.apache.shardingsphere.infra.route.context.RouteContext;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.predicate.WhereSegment;
import java.util.Collection;
import java.util.Collections;
/**
* SQL rewrite context decorator for encrypt.
*/
public final class EncryptSQLRewriteContextDecorator implements SQLRewriteContextDecorator<EncryptRule> {
@SuppressWarnings("rawtypes")
@Override
public void decorate(final EncryptRule encryptRule, final ConfigurationProperties props, final SQLRewriteContext sqlRewriteContext, final RouteContext routeContext) {
SQLStatementContext<?> sqlStatementContext = sqlRewriteContext.getSqlStatementContext();
if (((CommonSQLStatementContext) sqlStatementContext).getSqlHintExtractor().isHintSkipEncryptRewrite() || !containsEncryptTable(encryptRule, sqlStatementContext)) {
return;
}
Collection<EncryptCondition> encryptConditions = createEncryptConditions(encryptRule, sqlRewriteContext);
encryptRule.setSchemaMetaData(sqlRewriteContext.getDatabaseName(), sqlRewriteContext.getSchemas());
if (!sqlRewriteContext.getParameters().isEmpty()) {
Collection<ParameterRewriter> parameterRewriters = new EncryptParameterRewriterBuilder(encryptRule,
sqlRewriteContext.getDatabaseName(), sqlRewriteContext.getSchemas(), sqlStatementContext, encryptConditions).getParameterRewriters();
rewriteParameters(sqlRewriteContext, parameterRewriters);
}
Collection<SQLTokenGenerator> sqlTokenGenerators = new EncryptTokenGenerateBuilder(encryptRule,
sqlStatementContext, encryptConditions, sqlRewriteContext.getDatabaseName()).getSQLTokenGenerators();
sqlRewriteContext.addSQLTokenGenerators(sqlTokenGenerators);
}
private Collection<EncryptCondition> createEncryptConditions(final EncryptRule encryptRule, final SQLRewriteContext sqlRewriteContext) {
SQLStatementContext<?> sqlStatementContext = sqlRewriteContext.getSqlStatementContext();
if (!(sqlStatementContext instanceof WhereAvailable)) {
return Collections.emptyList();
}
Collection<WhereSegment> whereSegments = ((WhereAvailable) sqlStatementContext).getWhereSegments();
Collection<ColumnSegment> columnSegments = ((WhereAvailable) sqlStatementContext).getColumnSegments();
return new EncryptConditionEngine(encryptRule, sqlRewriteContext.getSchemas())
.createEncryptConditions(whereSegments, columnSegments, sqlStatementContext, sqlRewriteContext.getDatabaseName());
}
@SuppressWarnings("rawtypes")
private boolean containsEncryptTable(final EncryptRule encryptRule, final SQLStatementContext sqlStatementContext) {
for (String each : sqlStatementContext.getTablesContext().getTableNames()) {
if (encryptRule.findEncryptTable(each).isPresent()) {
return true;
}
}
return false;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void rewriteParameters(final SQLRewriteContext sqlRewriteContext, final Collection<ParameterRewriter> parameterRewriters) {
for (ParameterRewriter each : parameterRewriters) {
each.rewrite(sqlRewriteContext.getParameterBuilder(), sqlRewriteContext.getSqlStatementContext(), sqlRewriteContext.getParameters());
}
}
@Override
public int getOrder() {
return EncryptOrder.ORDER;
}
@Override
public Class<EncryptRule> getTypeClass() {
return EncryptRule.class;
}
}
|
3e0996bdd367f93b4779d8d8cc737e07bc62567c | 466 | java | Java | qwandaq/src/main/java/life/genny/qwandaq/data/BridgeInfo.java | genny-project/kogitoq2 | bb716aed817a3ed8409f2e8a5a3b553532ab41af | [
"Apache-2.0"
] | null | null | null | qwandaq/src/main/java/life/genny/qwandaq/data/BridgeInfo.java | genny-project/kogitoq2 | bb716aed817a3ed8409f2e8a5a3b553532ab41af | [
"Apache-2.0"
] | null | null | null | qwandaq/src/main/java/life/genny/qwandaq/data/BridgeInfo.java | genny-project/kogitoq2 | bb716aed817a3ed8409f2e8a5a3b553532ab41af | [
"Apache-2.0"
] | null | null | null | 23.3 | 87 | 0.785408 | 4,040 | package life.genny.qwandaq.data;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A Bridge Info storage class used with BridgeSwitch to map individual user bridge Ids
*
* @author Jasper Robison
*/
@RegisterForReflection
public class BridgeInfo {
public ConcurrentMap<String, String> mappings = new ConcurrentHashMap<>();
public BridgeInfo() {}
}
|
3e0997368eb9d84bf3fe7b49122c170023ea2ea2 | 5,218 | java | Java | TeamCode/src/main/java/TeamCode/AOpMode_BlueUltimateGoal.java | Voltage16592/FreightFrenzy | c5e1120e8ee483b30445cb6c165fc613d06e3771 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/TeamCode/AOpMode_BlueUltimateGoal.java | Voltage16592/FreightFrenzy | c5e1120e8ee483b30445cb6c165fc613d06e3771 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/TeamCode/AOpMode_BlueUltimateGoal.java | Voltage16592/FreightFrenzy | c5e1120e8ee483b30445cb6c165fc613d06e3771 | [
"MIT"
] | null | null | null | 40.765625 | 155 | 0.662706 | 4,041 | package TeamCode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
@Autonomous(name="AOpMode_BlueUltimateGoal", group="Linear Opmode")
//@Disabled
public class AOpMode_BlueUltimateGoal extends LinearOpMode {
/* Declare OpMode members. */
private ElapsedTime runtime = new ElapsedTime();
private SubSys_MecDrive mecDrive = new SubSys_MecDrive();
private SubSys_OneServo oneServo = new SubSys_OneServo();
@Override
public void runOpMode() {
mecDrive.init(hardwareMap);
oneServo.init(hardwareMap);
telemetry.addData("Status", "Initialized");
// Send telemetry message to signify robot waiting;
// Wait for the game to start (driver presses PLAY)
waitForStart();
int inches;
inches = -70;
encoderDrive(1, inches, inches, inches, inches, 5);//Just Moves Backwards
inches = -24;
encoderDrive(1, inches, -inches, -inches, inches, 4);//Move Left
inches = -60;
encoderDrive(0.5, inches, inches, inches, inches, 10);//Just Moves Backwards
whooshy(10);
inches = 50;
encoderDrive(1, inches, inches, inches, inches, 5);//Just Moves Forwards
}
public void encoderDrive(double speed,
double fleftInches, double frightInches, double bleftInches, double brightInches,
double timeoutS) {
// Ensure that the opmode is still active
if (opModeIsActive()) {
mecDrive.fleft_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
mecDrive.fright_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
mecDrive.bleft_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
mecDrive.bright_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
mecDrive.fleft_drive.setTargetPosition((int) (fleftInches * mecDrive.COUNTS_PER_INCH * mecDrive.Adjust));
mecDrive.fright_drive.setTargetPosition((int) (frightInches * mecDrive.COUNTS_PER_INCH * mecDrive.Adjust));
mecDrive.bleft_drive.setTargetPosition((int) (bleftInches * mecDrive.COUNTS_PER_INCH * mecDrive.Adjust));
mecDrive.bright_drive.setTargetPosition((int) (brightInches * mecDrive.COUNTS_PER_INCH * mecDrive.Adjust));
// Turn On RUN_TO_POSITION
mecDrive.fleft_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
mecDrive.fright_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
mecDrive.bleft_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
mecDrive.bright_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
mecDrive.fleft_drive.setPower(Math.abs(speed)*(Math.abs(fleftInches)/fleftInches));
mecDrive.fright_drive.setPower(Math.abs(speed)*(Math.abs(frightInches)/frightInches));
mecDrive.bleft_drive.setPower(Math.abs(speed)*(Math.abs(bleftInches)/bleftInches));
mecDrive.bright_drive.setPower(Math.abs(speed)*(Math.abs(brightInches)/brightInches));
// keep looping while we are still active, and there is time left, and both motors are running.
// Note: We use (isBusy() && isBusy()) in the loop test, which means that when EITHER motor hits
// its target position, the motion will stop. This is "safer" in the event that the robot will
// always end the motion as soon as possible.
// However, if you require that BOTH motors have finished their moves before the robot continues
// onto the next step, use (isBusy() || isBusy()) in the loop test.
while (opModeIsActive() &&
(runtime.seconds() < timeoutS) &&
(mecDrive.fleft_drive.isBusy() && mecDrive.fright_drive.isBusy()) && mecDrive.bleft_drive.isBusy() && mecDrive.bright_drive.isBusy()) {
}
// Stop all motion;
mecDrive.fleft_drive.setPower(0);
mecDrive.fright_drive.setPower(0);
mecDrive.bleft_drive.setPower(0);
mecDrive.bright_drive.setPower(0);
// Turn off RUN_TO_POSITION
mecDrive.fleft_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
mecDrive.fright_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
mecDrive.bleft_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
mecDrive.bright_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
}
public void whooshy(double timeoutS) {
// Ensure that the opmode is still active
if (opModeIsActive()) {
oneServo.leftWhoosh.setPower(1);
oneServo.rightWhoosh.setPower(-1);
oneServo.beltMotor.setPower(-0.5);
sleep(10 * 1000);
oneServo.leftWhoosh.setPower(0);
oneServo.rightWhoosh.setPower(0);
oneServo.beltMotor.setPower(0);
}
}
} |
3e0997efbfbf033e48c73fb2f72e9c99b7f4abc9 | 8,617 | java | Java | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/PositionStripeReader.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/PositionStripeReader.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/PositionStripeReader.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 14.805842 | 814 | 0.801787 | 4,042 | 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
DECL|package|org.apache.hadoop.hdfs
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|protocol
operator|.
name|ErasureCodingPolicy
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|protocol
operator|.
name|LocatedBlock
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|util
operator|.
name|StripedBlockUtil
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|util
operator|.
name|StripedBlockUtil
operator|.
name|StripingChunk
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|util
operator|.
name|StripedBlockUtil
operator|.
name|AlignedStripe
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|erasurecode
operator|.
name|ECChunk
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|erasurecode
operator|.
name|rawcoder
operator|.
name|RawErasureDecoder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|DFSUtilClient
operator|.
name|CorruptedBlocks
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|ByteBuffer
import|;
end_import
begin_comment
comment|/** * The reader for reading a complete {@link StripedBlockUtil.AlignedStripe} * which may cross multiple stripes with cellSize width. */
end_comment
begin_class
DECL|class|PositionStripeReader
class|class
name|PositionStripeReader
extends|extends
name|StripeReader
block|{
DECL|field|codingBuffer
specifier|private
name|ByteBuffer
name|codingBuffer
decl_stmt|;
DECL|method|PositionStripeReader (AlignedStripe alignedStripe, ErasureCodingPolicy ecPolicy, LocatedBlock[] targetBlocks, BlockReaderInfo[] readerInfos, CorruptedBlocks corruptedBlocks, RawErasureDecoder decoder, DFSStripedInputStream dfsStripedInputStream)
name|PositionStripeReader
parameter_list|(
name|AlignedStripe
name|alignedStripe
parameter_list|,
name|ErasureCodingPolicy
name|ecPolicy
parameter_list|,
name|LocatedBlock
index|[]
name|targetBlocks
parameter_list|,
name|BlockReaderInfo
index|[]
name|readerInfos
parameter_list|,
name|CorruptedBlocks
name|corruptedBlocks
parameter_list|,
name|RawErasureDecoder
name|decoder
parameter_list|,
name|DFSStripedInputStream
name|dfsStripedInputStream
parameter_list|)
block|{
name|super
argument_list|(
name|alignedStripe
argument_list|,
name|ecPolicy
argument_list|,
name|targetBlocks
argument_list|,
name|readerInfos
argument_list|,
name|corruptedBlocks
argument_list|,
name|decoder
argument_list|,
name|dfsStripedInputStream
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|prepareDecodeInputs ()
name|void
name|prepareDecodeInputs
parameter_list|()
block|{
if|if
condition|(
name|codingBuffer
operator|==
literal|null
condition|)
block|{
name|this
operator|.
name|decodeInputs
operator|=
operator|new
name|ECChunk
index|[
name|dataBlkNum
operator|+
name|parityBlkNum
index|]
expr_stmt|;
name|initDecodeInputs
argument_list|(
name|alignedStripe
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|prepareParityChunk (int index)
name|boolean
name|prepareParityChunk
parameter_list|(
name|int
name|index
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkState
argument_list|(
name|index
operator|>=
name|dataBlkNum
operator|&&
name|alignedStripe
operator|.
name|chunks
index|[
name|index
index|]
operator|==
literal|null
argument_list|)
expr_stmt|;
name|int
name|bufLen
init|=
operator|(
name|int
operator|)
name|alignedStripe
operator|.
name|getSpanInBlock
argument_list|()
decl_stmt|;
name|decodeInputs
index|[
name|index
index|]
operator|=
operator|new
name|ECChunk
argument_list|(
name|codingBuffer
operator|.
name|duplicate
argument_list|()
argument_list|,
name|index
operator|*
name|bufLen
argument_list|,
name|bufLen
argument_list|)
expr_stmt|;
name|alignedStripe
operator|.
name|chunks
index|[
name|index
index|]
operator|=
operator|new
name|StripingChunk
argument_list|(
name|decodeInputs
index|[
name|index
index|]
operator|.
name|getBuffer
argument_list|()
argument_list|)
expr_stmt|;
return|return
literal|true
return|;
block|}
annotation|@
name|Override
DECL|method|decode ()
name|void
name|decode
parameter_list|()
throws|throws
name|IOException
block|{
name|finalizeDecodeInputs
argument_list|()
expr_stmt|;
name|decodeAndFillBuffer
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
DECL|method|initDecodeInputs (AlignedStripe alignedStripe)
name|void
name|initDecodeInputs
parameter_list|(
name|AlignedStripe
name|alignedStripe
parameter_list|)
block|{
name|int
name|bufLen
init|=
operator|(
name|int
operator|)
name|alignedStripe
operator|.
name|getSpanInBlock
argument_list|()
decl_stmt|;
name|int
name|bufCount
init|=
name|dataBlkNum
operator|+
name|parityBlkNum
decl_stmt|;
name|codingBuffer
operator|=
name|dfsStripedInputStream
operator|.
name|getBufferPool
argument_list|()
operator|.
name|getBuffer
argument_list|(
name|useDirectBuffer
argument_list|()
argument_list|,
name|bufLen
operator|*
name|bufCount
argument_list|)
expr_stmt|;
name|ByteBuffer
name|buffer
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|dataBlkNum
condition|;
name|i
operator|++
control|)
block|{
name|buffer
operator|=
name|codingBuffer
operator|.
name|duplicate
argument_list|()
expr_stmt|;
name|decodeInputs
index|[
name|i
index|]
operator|=
operator|new
name|ECChunk
argument_list|(
name|buffer
argument_list|,
name|i
operator|*
name|bufLen
argument_list|,
name|bufLen
argument_list|)
expr_stmt|;
block|}
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|dataBlkNum
condition|;
name|i
operator|++
control|)
block|{
if|if
condition|(
name|alignedStripe
operator|.
name|chunks
index|[
name|i
index|]
operator|==
literal|null
condition|)
block|{
name|alignedStripe
operator|.
name|chunks
index|[
name|i
index|]
operator|=
operator|new
name|StripingChunk
argument_list|(
name|decodeInputs
index|[
name|i
index|]
operator|.
name|getBuffer
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
block|}
DECL|method|close ()
name|void
name|close
parameter_list|()
block|{
if|if
condition|(
name|decodeInputs
operator|!=
literal|null
condition|)
block|{
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|decodeInputs
operator|.
name|length
condition|;
name|i
operator|++
control|)
block|{
name|decodeInputs
index|[
name|i
index|]
operator|=
literal|null
expr_stmt|;
block|}
block|}
if|if
condition|(
name|codingBuffer
operator|!=
literal|null
condition|)
block|{
name|dfsStripedInputStream
operator|.
name|getBufferPool
argument_list|()
operator|.
name|putBuffer
argument_list|(
name|codingBuffer
argument_list|)
expr_stmt|;
name|codingBuffer
operator|=
literal|null
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
|
3e0998bfae8352d625bc99836dfaa3734790bfc4 | 3,255 | java | Java | src/main/java/fluxnetworks/common/handler/PacketHandler.java | Smollet777/Flux-Networks | 9f5dd7884fff8aa29aec5b063d2620f1fc978e35 | [
"MIT"
] | null | null | null | src/main/java/fluxnetworks/common/handler/PacketHandler.java | Smollet777/Flux-Networks | 9f5dd7884fff8aa29aec5b063d2620f1fc978e35 | [
"MIT"
] | 7 | 2020-04-18T21:34:57.000Z | 2020-08-07T14:57:45.000Z | src/main/java/fluxnetworks/common/handler/PacketHandler.java | Smollet777/Flux-Networks | 9f5dd7884fff8aa29aec5b063d2620f1fc978e35 | [
"MIT"
] | null | null | null | 69.255319 | 151 | 0.813518 | 4,043 | package fluxnetworks.common.handler;
import fluxnetworks.FluxNetworks;
import fluxnetworks.common.network.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
public class PacketHandler {
public static SimpleNetworkWrapper network = NetworkRegistry.INSTANCE.newSimpleChannel(FluxNetworks.MODID);
public static void registerMessages() {
network.registerMessage(PacketGeneral.class, PacketGeneral.GeneralMessage.class, 1, Side.SERVER);
network.registerMessage(PacketNetworkUpdate.class, PacketNetworkUpdate.NetworkUpdateMessage.class, 2, Side.CLIENT);
network.registerMessage(PacketByteBuf.class, PacketByteBuf.ByteBufMessage.class, 3, Side.SERVER);
network.registerMessage(PacketByteBuf.class, PacketByteBuf.ByteBufMessage.class, 4, Side.CLIENT);
network.registerMessage(PacketTile.class, PacketTile.TileMessage.class, 5, Side.SERVER);
network.registerMessage(PacketFeedback.class, PacketFeedback.FeedbackMessage.class, 6, Side.CLIENT);
network.registerMessage(PacketColorRequest.class, PacketColorRequest.ColorRequestMessage.class, 7, Side.SERVER);
network.registerMessage(PacketColorCache.class, PacketColorCache.ColorCacheMessage.class, 8, Side.CLIENT);
network.registerMessage(PacketNetworkUpdateRequest.class, PacketNetworkUpdateRequest.UpdateRequestMessage.class, 9, Side.SERVER);
network.registerMessage(PacketConnectionUpdate.class, PacketConnectionUpdate.NetworkConnectionMessage.class, 10, Side.CLIENT);
network.registerMessage(PacketConnectionUpdateRequest.class, PacketConnectionUpdateRequest.ConnectionRequestMessage.class, 11, Side.SERVER);
network.registerMessage(PacketBatchEditing.class, PacketBatchEditing.BatchEditingMessage.class, 12, Side.SERVER);
network.registerMessage(PacketPermissionRequest.class, PacketPermissionRequest.PermissionRequestMessage.class, 13, Side.SERVER);
network.registerMessage(PacketGUIPermission.class, PacketGUIPermission.GUIPermissionMessage.class, 14, Side.CLIENT);
network.registerMessage(PacketSuperAdmin.class, PacketSuperAdmin.SuperAdminMessage.class, 15, Side.CLIENT);
network.registerMessage(PacketActivateSuperAdmin.class, PacketActivateSuperAdmin.ActivateSuperAdminMessage.class, 16, Side.SERVER);
network.registerMessage(PacketConfiguratorSettings.class, PacketConfiguratorSettings.ConfiguratorSettingsMessage.class, 17, Side.SERVER);
network.registerMessage(PacketSetConfiguratorNetwork.class, PacketSetConfiguratorNetwork.SetConfiguratorNetworkMessage.class, 18, Side.SERVER);
}
public static EntityPlayer getPlayer(MessageContext ctx) {
return FluxNetworks.proxy.getPlayer(ctx);
}
public static void handlePacket(Runnable runnable, INetHandler netHandler) {
FMLCommonHandler.instance().getWorldThread(netHandler).addScheduledTask(runnable);
}
}
|
3e0998ef94b0988c30397dc4ce781e34734c71d6 | 5,788 | java | Java | hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SyncFuture.java | mahuacai/hbase | f4f2b68238a094d7b1931dc8b7939742ccbb2b57 | [
"Apache-2.0"
] | 2 | 2020-08-03T15:53:04.000Z | 2020-08-27T10:14:50.000Z | hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SyncFuture.java | mahuacai/hbase | f4f2b68238a094d7b1931dc8b7939742ccbb2b57 | [
"Apache-2.0"
] | 131 | 2019-01-25T07:53:30.000Z | 2021-07-07T07:17:14.000Z | hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SyncFuture.java | mahuacai/hbase | f4f2b68238a094d7b1931dc8b7939742ccbb2b57 | [
"Apache-2.0"
] | 3 | 2018-09-18T09:15:49.000Z | 2019-05-21T08:27:29.000Z | 34.248521 | 100 | 0.690048 | 4,044 | /**
* 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.hadoop.hbase.regionserver.wal;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
import org.apache.yetus.audience.InterfaceAudience;
/**
* A Future on a filesystem sync call. It given to a client or 'Handler' for it to wait on till the
* sync completes.
* <p>
* Handlers coming in call append, append, append, and then do a flush/sync of the edits they have
* appended the WAL before returning. Since sync takes a while to complete, we give the Handlers
* back this sync future to wait on until the actual HDFS sync completes. Meantime this sync future
* goes across a queue and is handled by a background thread; when it completes, it finishes up the
* future, the handler get or failed check completes and the Handler can then progress.
* <p>
* This is just a partial implementation of Future; we just implement get and failure.
* <p>
* There is not a one-to-one correlation between dfs sync invocations and instances of this class. A
* single dfs sync call may complete and mark many SyncFutures as done; i.e. we batch up sync calls
* rather than do a dfs sync call every time a Handler asks for it.
* <p>
* SyncFutures are immutable but recycled. Call #reset(long, Span) before use even if it the first
* time, start the sync, then park the 'hitched' thread on a call to #get().
*/
@InterfaceAudience.Private
class SyncFuture {
// Implementation notes: I tried using a cyclicbarrier in here for handler and sync threads
// to coordinate on but it did not give any obvious advantage and some issues with order in which
// events happen.
private static final long NOT_DONE = -1L;
/**
* The transaction id of this operation, monotonically increases.
*/
private long txid;
/**
* The transaction id that was set in here when we were marked done. Should be equal or > txnId.
* Put this data member into the NOT_DONE state while this class is in use.
*/
private long doneTxid;
/**
* If error, the associated throwable. Set when the future is 'done'.
*/
private Throwable throwable;
private Thread t;
private boolean forceSync;
/**
* Call this method to clear old usage and get it ready for new deploy.
* @param txid the new transaction id
* @param span current span, detached from caller. Don't forget to attach it when resuming after a
* call to {@link #get(long)}.
* @return this
*/
synchronized SyncFuture reset(long txid) {
if (t != null && t != Thread.currentThread()) {
throw new IllegalStateException();
}
t = Thread.currentThread();
if (!isDone()) {
throw new IllegalStateException("" + txid + " " + Thread.currentThread());
}
this.doneTxid = NOT_DONE;
this.txid = txid;
this.throwable = null;
return this;
}
@Override
public synchronized String toString() {
return "done=" + isDone() + ", txid=" + this.txid;
}
synchronized long getTxid() {
return this.txid;
}
synchronized boolean isForceSync() {
return forceSync;
}
synchronized SyncFuture setForceSync(boolean forceSync) {
this.forceSync = forceSync;
return this;
}
/**
* @param txid the transaction id at which this future 'completed'.
* @param t Can be null. Set if we are 'completing' on error (and this 't' is the error).
* @return True if we successfully marked this outstanding future as completed/done. Returns false
* if this future is already 'done' when this method called.
*/
synchronized boolean done(final long txid, final Throwable t) {
if (isDone()) {
return false;
}
this.throwable = t;
if (txid < this.txid) {
// Something badly wrong.
if (throwable == null) {
this.throwable =
new IllegalStateException("done txid=" + txid + ", my txid=" + this.txid);
}
}
// Mark done.
this.doneTxid = txid;
// Wake up waiting threads.
notify();
return true;
}
boolean cancel(boolean mayInterruptIfRunning) {
throw new UnsupportedOperationException();
}
synchronized long get(long timeoutNs) throws InterruptedException,
ExecutionException, TimeoutIOException {
final long done = System.nanoTime() + timeoutNs;
while (!isDone()) {
wait(1000);
if (System.nanoTime() >= done) {
throw new TimeoutIOException(
"Failed to get sync result after " + TimeUnit.NANOSECONDS.toMillis(timeoutNs)
+ " ms for txid=" + this.txid + ", WAL system stuck?");
}
}
if (this.throwable != null) {
throw new ExecutionException(this.throwable);
}
return this.doneTxid;
}
synchronized boolean isDone() {
return this.doneTxid != NOT_DONE;
}
synchronized boolean isThrowable() {
return isDone() && getThrowable() != null;
}
synchronized Throwable getThrowable() {
return this.throwable;
}
}
|
3e0999904b44124492df767bcfe4c05135b58036 | 608 | java | Java | src/test/java/com/okdevtv/tdd/HelloWorldTest.java | roy-junny/hello | 3e6b6dbb1f56c0bcd069fe151c267fc12f6b3fc8 | [
"MIT"
] | null | null | null | src/test/java/com/okdevtv/tdd/HelloWorldTest.java | roy-junny/hello | 3e6b6dbb1f56c0bcd069fe151c267fc12f6b3fc8 | [
"MIT"
] | 3 | 2022-03-15T02:42:07.000Z | 2022-03-16T02:11:17.000Z | src/test/java/com/okdevtv/tdd/HelloWorldTest.java | roy-junny/hello | 3e6b6dbb1f56c0bcd069fe151c267fc12f6b3fc8 | [
"MIT"
] | null | null | null | 16.888889 | 47 | 0.689145 | 4,045 | package com.okdevtv.tdd;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class HelloWorldTest {
private HelloWorld hello ;
@Before
public void setup() {
hello = new HelloWorld() ;
}
@Test
public void test() {
String helloMsg = hello.getMessage() ;
assertEquals("Hello World", helloMsg) ;
}
@Test
public void testMsgName() {
String helloMsg = hello.getMessage("sjlee") ;
assertEquals("Hello sjlee", helloMsg) ;
}
@Test
public void testMsgNull() {
String helloMsg = hello.getMessage(null) ;
assertEquals("Hello ", helloMsg) ;
}
}
|
3e099a8f59cfcbadd7c12e156e76598a280e5062 | 1,407 | java | Java | WebMarket18/src/mvc/database/DBConnectionProperties.java | daehyeonhong/JSP | fccf1688dabdca075e093a259cb0fdf5fb0c90bf | [
"MIT"
] | 1 | 2020-07-15T05:03:14.000Z | 2020-07-15T05:03:14.000Z | WebMarket18/src/mvc/database/DBConnectionProperties.java | daehyeonhong/JSP | fccf1688dabdca075e093a259cb0fdf5fb0c90bf | [
"MIT"
] | null | null | null | WebMarket18/src/mvc/database/DBConnectionProperties.java | daehyeonhong/JSP | fccf1688dabdca075e093a259cb0fdf5fb0c90bf | [
"MIT"
] | null | null | null | 26.055556 | 89 | 0.692964 | 4,046 | package mvc.database;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/* Singleton 으로 작성 */
public class DBConnectionProperties {
/* 자기 자신 타입의 instance_Field */
private static DBConnectionProperties instance = new DBConnectionProperties();
/* Constructor 캡슐화 */
private DBConnectionProperties() {
}
/* instance 얻기 */
public static DBConnectionProperties getInstance() {
return instance;
}
/* 외부 접근 가능한 getConnection_Method() */
public Connection getConnection() {
Connection connection = null;
String url = "", user = "", password = "";
try {
/* File 정보 얻기 */
File file = new File("C:\\WorkSpace\\JSP\\WebMarket18\\src\\DBConnection.properties");
/* 속성, 값 저장할 객체 생성 */
Properties properties = new Properties();
/* 파일 정보 읽을 통로 생성 */
FileReader fileReader = new FileReader(file);
/* 저장 */
properties.load(fileReader);
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
/* 드라이버 메모리에 로딩 */
Class.forName(properties.getProperty("driver"));
/* 연결 맺기 */
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(url);
System.out.println(user);
System.out.println(password);
return connection;
}
} |
3e099b14c10c3d7dc8a03764ace470b5db4e0060 | 174 | java | Java | androidcache/src/main/java/me/tomogoma/androidcache/Storable.java | TomOgoma/cache | 98fc39f3bee4ba7d30ef6899cf88aaf655fc45e1 | [
"MIT"
] | null | null | null | androidcache/src/main/java/me/tomogoma/androidcache/Storable.java | TomOgoma/cache | 98fc39f3bee4ba7d30ef6899cf88aaf655fc45e1 | [
"MIT"
] | null | null | null | androidcache/src/main/java/me/tomogoma/androidcache/Storable.java | TomOgoma/cache | 98fc39f3bee4ba7d30ef6899cf88aaf655fc45e1 | [
"MIT"
] | null | null | null | 15.818182 | 35 | 0.66092 | 4,047 | package me.tomogoma.androidcache;
/**
* Created by tomogoma on 29/08/16.
*/
public interface Storable {
String getKey();
String getValue();
String toJson();
}
|
3e099bbc682166885630edd6486a825f86857d2e | 3,053 | java | Java | pctsea-cl/src/main/java/edu/scripps/yates/pctsea/db/datasets/singlecellshuman/InputFileGenerator.java | proteomicsyates/pctsea-parent | dd18839b6d270527a8c125038a83ed73246c0b73 | [
"Apache-2.0"
] | null | null | null | pctsea-cl/src/main/java/edu/scripps/yates/pctsea/db/datasets/singlecellshuman/InputFileGenerator.java | proteomicsyates/pctsea-parent | dd18839b6d270527a8c125038a83ed73246c0b73 | [
"Apache-2.0"
] | null | null | null | pctsea-cl/src/main/java/edu/scripps/yates/pctsea/db/datasets/singlecellshuman/InputFileGenerator.java | proteomicsyates/pctsea-parent | dd18839b6d270527a8c125038a83ed73246c0b73 | [
"Apache-2.0"
] | null | null | null | 29.07619 | 106 | 0.662954 | 4,048 | package edu.scripps.yates.pctsea.db.datasets.singlecellshuman;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.commons.io.FilenameUtils;
import edu.scripps.yates.pctsea.model.SingleCell;
public class InputFileGenerator {
public static void main(String[] args) {
final InputFileGenerator ifg = new InputFileGenerator();
try {
ifg.run();
System.out.println("Everything ok!");
} catch (final IOException e) {
e.printStackTrace();
}
}
public void run() throws IOException {
final String folderName = "C:\\Users\\salvador\\Desktop\\casimir\\SARS_Cov2\\singlecell_human";
final String[] fileNames = { "spike_fullTable.txt", "mprotein_fullTable.txt" };
for (final String fileName : fileNames) {
final File inputFile = new File(folderName + File.separator + fileName);
final String baseName = FilenameUtils.getBaseName(fileName);
// single cells
final File singleCellsFile = new File(
folderName + File.separator + "input files" + File.separator + baseName + "_singleCells.txt");
final FileWriter scfw = new FileWriter(singleCellsFile);
// single cells
final File experimentalFile = new File(
folderName + File.separator + "input files" + File.separator + baseName + "_experimental.txt");
final FileWriter efw = new FileWriter(experimentalFile);
final BufferedReader br = new BufferedReader(new FileReader(inputFile));
String line;
int numLine = 0;
while ((line = br.readLine()) != null) {
numLine++;
final StringTokenizer tokenizer = new StringTokenizer(line, "\t");
int colIndex = 0;
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
// first line,
if (numLine == 1) {
scfw.write(token + "\t");
if (colIndex < 1) {
efw.write("\t" + token);
}
} else {
if (colIndex != 1) {
scfw.write(token + "\t");
}
if (colIndex < 2) {
efw.write(token + "\t");
}
}
colIndex++;
}
scfw.flush();
efw.flush();
scfw.write("\n");
efw.write("\n");
}
scfw.close();
efw.close();
br.close();
}
// metadata file
final File inputMetadata = new File(folderName + File.separator + "singleCellLinesTable_fullTable.txt");
final File outputMetadata = new File(
folderName + File.separator + "input files" + File.separator + "singleCellsMetadata.txt");
final FileWriter fw = new FileWriter(outputMetadata);
fw.write("cell_id\tcelltype\n");
final BufferedReader br = new BufferedReader(new FileReader(inputMetadata));
String line;
int numLine = 0;
while ((line = br.readLine()) != null) {
numLine++;
final String[] split = line.split("\t");
if (numLine == 1) {
continue;
}
final String cellID = split[0];
final String cellType = SingleCell.parseCellTypeTypos(split[1]);
fw.write(cellID + "\t" + cellType + "\n");
}
fw.close();
br.close();
}
}
|
3e099c0acb24fbfb1768910aaf98fb73c062ef0f | 2,413 | java | Java | javaone-demo-jaas-lm/src/main/java/com/serli/javaone/jaas/lm/CustomCallbackHandler.java | mullermarian/javaone-acn-azn | 00b7f86144763173afc12f1b3a00d833f15f5d21 | [
"MIT"
] | null | null | null | javaone-demo-jaas-lm/src/main/java/com/serli/javaone/jaas/lm/CustomCallbackHandler.java | mullermarian/javaone-acn-azn | 00b7f86144763173afc12f1b3a00d833f15f5d21 | [
"MIT"
] | null | null | null | javaone-demo-jaas-lm/src/main/java/com/serli/javaone/jaas/lm/CustomCallbackHandler.java | mullermarian/javaone-acn-azn | 00b7f86144763173afc12f1b3a00d833f15f5d21 | [
"MIT"
] | null | null | null | 40.898305 | 101 | 0.555325 | 4,049 | package com.serli.javaone.jaas.lm;
import javax.security.auth.callback.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
public class CustomCallbackHandler implements CallbackHandler {
private static final Logger logger = Logger.getLogger(CustomCallbackHandler.class.getName());
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback cb : callbacks) {
//logger.info("Callback received: " + cb.getClass().getCanonicalName());
if (cb instanceof TextOutputCallback) {
TextOutputCallback tocb = (TextOutputCallback) cb;
// Different display for each message type
switch (tocb.getMessageType()) {
case TextOutputCallback.INFORMATION:
logger.info(tocb.getMessage());
break;
case TextOutputCallback.WARNING:
logger.warning(tocb.getMessage());
break;
case TextOutputCallback.ERROR:
logger.severe(tocb.getMessage());
break;
// Unknown type
default:
throw new IOException("Unknown message type: " + tocb.getMessage());
}
}
else if (cb instanceof NameCallback) {
NameCallback ncb = (NameCallback) cb;
// Display prompt
System.out.print(ncb.getPrompt());
// Read name
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ncb.setName(br.readLine());
}
else if (cb instanceof PasswordCallback) {
PasswordCallback pwcb = (PasswordCallback) cb;
// Display prompt
System.out.print(pwcb.getPrompt());
// Read password
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
pwcb.setPassword(br.readLine().toCharArray());
}
// Other unsupported callbacks
else {
throw new UnsupportedCallbackException(cb, "Callback '" + cb + "' is not supported");
}
}
}
}
|
3e099c44df602b16978457b4e8fd2cf0dd81f742 | 10,795 | java | Java | web-admin/src/main/java/pl/edu/icm/unity/webadmin/reg/reqman/RequestsTable.java | olivier-maury/unity | 4681da2e7f33cb296baede87e4f7b58a474670a4 | [
"BSD-3-Clause"
] | null | null | null | web-admin/src/main/java/pl/edu/icm/unity/webadmin/reg/reqman/RequestsTable.java | olivier-maury/unity | 4681da2e7f33cb296baede87e4f7b58a474670a4 | [
"BSD-3-Clause"
] | null | null | null | web-admin/src/main/java/pl/edu/icm/unity/webadmin/reg/reqman/RequestsTable.java | olivier-maury/unity | 4681da2e7f33cb296baede87e4f7b58a474670a4 | [
"BSD-3-Clause"
] | 1 | 2017-11-20T13:18:06.000Z | 2017-11-20T13:18:06.000Z | 34.488818 | 114 | 0.77082 | 4,050 | /*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webadmin.reg.reqman;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.vaadin.data.ValueProvider;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.Orientation;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.engine.api.EnquiryManagement;
import pl.edu.icm.unity.engine.api.RegistrationsManagement;
import pl.edu.icm.unity.engine.api.msg.UnityMessageSource;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.types.basic.IdentityParam;
import pl.edu.icm.unity.types.registration.EnquiryResponse;
import pl.edu.icm.unity.types.registration.EnquiryResponseState;
import pl.edu.icm.unity.types.registration.RegistrationRequest;
import pl.edu.icm.unity.types.registration.RegistrationRequestAction;
import pl.edu.icm.unity.types.registration.RegistrationRequestState;
import pl.edu.icm.unity.types.registration.RegistrationRequestStatus;
import pl.edu.icm.unity.types.registration.UserRequestState;
import pl.edu.icm.unity.webui.WebSession;
import pl.edu.icm.unity.webui.bus.EventsBus;
import pl.edu.icm.unity.webui.common.ComponentWithToolbar;
import pl.edu.icm.unity.webui.common.ConfirmDialog;
import pl.edu.icm.unity.webui.common.ErrorComponent;
import pl.edu.icm.unity.webui.common.GridContextMenuSupport;
import pl.edu.icm.unity.webui.common.GridSelectionSupport;
import pl.edu.icm.unity.webui.common.Images;
import pl.edu.icm.unity.webui.common.NotificationPopup;
import pl.edu.icm.unity.webui.common.SingleActionHandler;
import pl.edu.icm.unity.webui.common.SmallGrid;
import pl.edu.icm.unity.webui.common.Toolbar;
import pl.edu.icm.unity.webui.forms.enquiry.EnquiryResponseChangedEvent;
import pl.edu.icm.unity.webui.forms.reg.RegistrationRequestChangedEvent;
/**
* Component showing a table with the registration requests. It is possible to register selection change
* listener and there is one action implemented to refresh the list.
* @author K. Benedyczak
*/
public class RequestsTable extends CustomComponent
{
private RegistrationsManagement registrationsManagement;
private EnquiryManagement enquiryManagement;
private UnityMessageSource msg;
private EventsBus bus;
private Grid<TableRequestBean> requestsTable;
public RequestsTable(RegistrationsManagement regMan, EnquiryManagement enquiryManagement, UnityMessageSource msg)
{
this.registrationsManagement = regMan;
this.enquiryManagement = enquiryManagement;
this.msg = msg;
this.bus = WebSession.getCurrent().getEventBus();
initUI();
}
private void initUI()
{
requestsTable = new SmallGrid<>();
requestsTable.setSelectionMode(SelectionMode.MULTI);
requestsTable.setSizeFull();
requestsTable.addColumn(TableRequestBean::getType, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.type"))
.setId("type");
requestsTable.addColumn(TableRequestBean::getForm, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.form"))
.setId("form");
requestsTable.addColumn(TableRequestBean::getRequestId, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.requestId"))
.setId("requestId");
requestsTable.addColumn(TableRequestBean::getSubmitTime, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.submitTime"))
.setId("submitTime");
requestsTable.addColumn(TableRequestBean::getStatus, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.status"))
.setId("status");
requestsTable.addColumn(TableRequestBean::getRequestedIdentity, ValueProvider.identity())
.setCaption(msg.getMessage("RegistrationRequest.requestedIdentity"))
.setId("requestedIdentity");
requestsTable.sort("type", SortDirection.ASCENDING);
GridContextMenuSupport<TableRequestBean> contextMenu = new GridContextMenuSupport<>(requestsTable);
contextMenu.addActionHandler(getRefreshAction());
contextMenu.addActionHandler(getAcceptAction());
contextMenu.addActionHandler(getRejectAction());
contextMenu.addActionHandler(getDropAction());
GridSelectionSupport.installClickListener(requestsTable);
Toolbar<TableRequestBean> toolbar = new Toolbar<>(Orientation.HORIZONTAL);
requestsTable.addSelectionListener(toolbar.getSelectionListener());
toolbar.addActionHandlers(contextMenu.getActionHandlers());
ComponentWithToolbar tableWithToolbar = new ComponentWithToolbar(requestsTable, toolbar);
tableWithToolbar.setSizeFull();
setCompositionRoot(tableWithToolbar);
refresh();
}
public void addValueChangeListener(final RequestSelectionListener listener)
{
requestsTable.addSelectionListener(event ->
{
TableRequestBean selected = getOnlyOneSelected();
if (selected == null)
listener.deselected();
else if (selected.request instanceof RegistrationRequestState)
listener.registrationChanged((RegistrationRequestState) selected.request);
else
listener.enquiryChanged((EnquiryResponseState) selected.request);
});
}
private TableRequestBean getOnlyOneSelected()
{
Collection<TableRequestBean> beans = requestsTable.getSelectedItems();
return beans == null || beans.isEmpty() || beans.size() > 1 ?
null : ((TableRequestBean)beans.iterator().next());
}
private SingleActionHandler<TableRequestBean> getRefreshAction()
{
return SingleActionHandler
.builder4Refresh(msg, TableRequestBean.class)
.withHandler(selection -> refresh())
.build();
}
public void refresh()
{
try
{
Stream<TableRequestBean> regRequestsStream = registrationsManagement.getRegistrationRequests().stream()
.map(registration -> new TableRequestBean(registration, msg));
Stream<TableRequestBean> enqRequestsStream = enquiryManagement.getEnquiryResponses().stream()
.map(enquiry -> new TableRequestBean(enquiry, msg));
List<TableRequestBean> requests = Stream.concat(regRequestsStream, enqRequestsStream)
.collect(Collectors.toList());
requestsTable.setItems(requests);
TableRequestBean selected = getOnlyOneSelected();
if (selected != null)
{
String requestId = selected.request.getRequestId();
requests.stream()
.filter(request -> requestId.equals(request.request.getRequestId()))
.findFirst()
.ifPresent(request -> requestsTable.select(request));
}
} catch (Exception e)
{
ErrorComponent error = new ErrorComponent();
error.setError(msg.getMessage("RequestsTable.errorGetRequests"), e);
setCompositionRoot(error);
}
}
public void process(Collection<?> items, RegistrationRequestAction action)
{
for (Object item: items)
{
try
{
processSingle((TableRequestBean) item, action);
} catch (EngineException e)
{
String info = msg.getMessage("RequestsTable.processError." + action.toString(),
((TableRequestBean)item).request.getRequestId());
NotificationPopup.showError(msg, info, e);
break;
}
}
}
private void processSingle(TableRequestBean item, RegistrationRequestAction action) throws EngineException
{
UserRequestState<?> request = item.request;
if (request instanceof RegistrationRequestState)
{
registrationsManagement.processRegistrationRequest(request.getRequestId(),
(RegistrationRequest) request.getRequest(),
action,
null,
null);
bus.fireEvent(new RegistrationRequestChangedEvent(request.getRequestId()));
} else
{
enquiryManagement.processEnquiryResponse(request.getRequestId(),
(EnquiryResponse) request.getRequest(),
action,
null,
null);
bus.fireEvent(new EnquiryResponseChangedEvent(request.getRequestId()));
}
}
private SingleActionHandler<TableRequestBean> getRejectAction()
{
return createAction(RegistrationRequestAction.reject, Images.reject);
}
private SingleActionHandler<TableRequestBean> getAcceptAction()
{
return createAction(RegistrationRequestAction.accept, Images.ok);
}
private SingleActionHandler<TableRequestBean> createAction(RegistrationRequestAction action, Images img)
{
return SingleActionHandler.builder(TableRequestBean.class)
.withCaption(msg.getMessage("RequestProcessingPanel." + action.toString()))
.withIcon(img.getResource())
.multiTarget()
.withHandler(items -> handleRegistrationAction(items, action))
.withDisabledPredicate(disableWhenNotPending())
.build();
}
private Predicate<TableRequestBean> disableWhenNotPending()
{
return bean -> bean.request.getStatus() != RegistrationRequestStatus.pending;
}
private SingleActionHandler<TableRequestBean> getDropAction()
{
return SingleActionHandler.builder(TableRequestBean.class)
.withCaption(msg.getMessage("RequestProcessingPanel.drop"))
.withIcon(Images.trashBin.getResource())
.multiTarget()
.withHandler(items -> handleRegistrationAction(items, RegistrationRequestAction.drop))
.build();
}
public void handleRegistrationAction(Set<TableRequestBean> items, RegistrationRequestAction action)
{
new ConfirmDialog(msg, msg.getMessage(
"RequestsTable.confirmAction."+action, items.size()),
() -> process(items, action)
).show();
}
public static class TableRequestBean
{
private UserRequestState<?> request;
private UnityMessageSource msg;
public TableRequestBean(UserRequestState<?> request, UnityMessageSource msg)
{
this.request = request;
this.msg = msg;
}
public String getType()
{
boolean enquiry = request instanceof EnquiryResponseState;
return msg.getMessage("RequestsTable.type." + (enquiry ? "enquiry" : "registration"));
}
public String getForm()
{
return request.getRequest().getFormId();
}
public String getRequestId()
{
return request.getRequestId();
}
public String getSubmitTime()
{
return new SimpleDateFormat(Constants.SIMPLE_DATE_FORMAT).format(request.getTimestamp());
}
public String getStatus()
{
return msg.getMessage("RegistrationRequestStatus." + request.getStatus());
}
public String getRequestedIdentity()
{
List<IdentityParam> identities = request.getRequest().getIdentities();
if (identities.isEmpty())
return "-";
IdentityParam id = identities.get(0);
return id == null ? "-" : id.toString();
}
}
public interface RequestSelectionListener
{
void registrationChanged(RegistrationRequestState request);
void enquiryChanged(EnquiryResponseState request);
void deselected();
}
}
|
3e099c8ebb84f1a926730278aef0ec44064c416c | 782 | java | Java | src/com/example/ORMLiteOneToMany/model/Commercial.java | SomniumOv/AFPA_ORMLiteOneToMany | 8a7d0713cdd7b779d4e3a8930dddd00c5fca5b86 | [
"MIT"
] | null | null | null | src/com/example/ORMLiteOneToMany/model/Commercial.java | SomniumOv/AFPA_ORMLiteOneToMany | 8a7d0713cdd7b779d4e3a8930dddd00c5fca5b86 | [
"MIT"
] | null | null | null | src/com/example/ORMLiteOneToMany/model/Commercial.java | SomniumOv/AFPA_ORMLiteOneToMany | 8a7d0713cdd7b779d4e3a8930dddd00c5fca5b86 | [
"MIT"
] | null | null | null | 18.619048 | 62 | 0.630435 | 4,051 | package com.example.ORMLiteOneToMany.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* Created by sam on 03/02/2016.
*/
@DatabaseTable
public class Commercial {
public static final String FIELD_NOM = "nom";
public Commercial(){}
public Commercial(String nom) {
this.nom = nom;
}
@DatabaseField (generatedId = true)
private int id;
@DatabaseField (canBeNull = false, columnName = FIELD_NOM)
private String nom;
public int getId() {
return id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
@Override
public String toString() {
return " Commercial :"+ this.nom;
}
}
|
3e099ceedbfc3377388f03f09daa8a07d61e664d | 912 | java | Java | Flubber/flubber/src/main/java/com/appolica/flubber/animation/providers/SlideUp.java | nedimf/Flubber | 9aeb46462be0a136c3ebd733f1b71be3f2763249 | [
"Apache-2.0"
] | 276 | 2017-08-11T12:53:49.000Z | 2022-03-29T17:56:23.000Z | Flubber/flubber/src/main/java/com/appolica/flubber/animation/providers/SlideUp.java | nedimf/Flubber | 9aeb46462be0a136c3ebd733f1b71be3f2763249 | [
"Apache-2.0"
] | 5 | 2017-09-09T12:06:17.000Z | 2021-07-05T11:36:41.000Z | Flubber/flubber/src/main/java/com/appolica/flubber/animation/providers/SlideUp.java | nedimf/Flubber | 9aeb46462be0a136c3ebd733f1b71be3f2763249 | [
"Apache-2.0"
] | 51 | 2017-08-11T13:18:24.000Z | 2021-08-09T09:47:03.000Z | 26.823529 | 79 | 0.735746 | 4,052 | package com.appolica.flubber.animation.providers;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.view.View;
import com.appolica.flubber.AnimationBody;
import com.appolica.flubber.Flubber;
import com.appolica.flubber.utils.DimensionUtils;
public class SlideUp extends BaseProvider {
public SlideUp() {
super(Flubber.Curve.SPRING);
}
@Override
public Animator getAnimationFor(AnimationBody animationBody, View view) {
final float startY = DimensionUtils.dp2px(800);
final float endY = 0f;
final PropertyValuesHolder translationPVH =
PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, startY, endY);
final ObjectAnimator animation =
ObjectAnimator.ofPropertyValuesHolder(view, translationPVH);
return animation;
}
}
|
3e099cfc446d863439aca2d32e5c0701e0077b14 | 1,987 | java | Java | titus-ext/cassandra-testkit/src/main/java/com/netflix/titus/ext/cassandra/testkit/junit/TitusCassandraResource.java | backwardn/titus-control-plane | 9b81a9bcba65ac6fa7e18dc93422c2a746c479b6 | [
"Apache-2.0"
] | 313 | 2018-04-18T16:51:10.000Z | 2022-03-11T02:07:48.000Z | titus-ext/cassandra-testkit/src/main/java/com/netflix/titus/ext/cassandra/testkit/junit/TitusCassandraResource.java | backwardn/titus-control-plane | 9b81a9bcba65ac6fa7e18dc93422c2a746c479b6 | [
"Apache-2.0"
] | 106 | 2018-06-11T22:17:05.000Z | 2022-03-22T21:06:05.000Z | titus-ext/cassandra-testkit/src/main/java/com/netflix/titus/ext/cassandra/testkit/junit/TitusCassandraResource.java | backwardn/titus-control-plane | 9b81a9bcba65ac6fa7e18dc93422c2a746c479b6 | [
"Apache-2.0"
] | 73 | 2018-04-18T16:53:07.000Z | 2021-12-31T05:21:25.000Z | 30.569231 | 97 | 0.718168 | 4,053 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.ext.cassandra.testkit.junit;
import com.datastax.driver.core.Session;
import org.cassandraunit.CQLDataLoader;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.rules.ExternalResource;
public class TitusCassandraResource extends ExternalResource {
private static final long STARTUP_TIMEOUT = 30000;
public static final String CASSANDRA_SCHEMA = "CassandraSchema";
private Session session;
@Override
protected void before() throws Throwable {
// This improves boot time by a few seconds
System.setProperty("cassandra.unsafesystem", "true");
EmbeddedCassandraServerHelper.startEmbeddedCassandra(STARTUP_TIMEOUT);
}
@Override
protected void after() {
cleanAll();
}
public Session getSession() {
if (session == null) {
loadSchema();
session = EmbeddedCassandraServerHelper.getSession();
}
return session;
}
public void cleanAll() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
session = null;
}
private void loadSchema() {
CQLDataLoader dataLoader = new CQLDataLoader(EmbeddedCassandraServerHelper.getSession());
dataLoader.load(new ClassPathCQLDataSet(CASSANDRA_SCHEMA, "Titus"));
}
}
|
3e099d0e1176149602c73cbf4ceaaa0f26f224c2 | 501 | java | Java | spring-boot-jsp/src/main/java/com/example/jsp/controller/WordController.java | jiangshaofen/spring-boot-example | 5b7cd90c72ea4d43d113db0b1800d06d4bc98319 | [
"MIT"
] | null | null | null | spring-boot-jsp/src/main/java/com/example/jsp/controller/WordController.java | jiangshaofen/spring-boot-example | 5b7cd90c72ea4d43d113db0b1800d06d4bc98319 | [
"MIT"
] | null | null | null | spring-boot-jsp/src/main/java/com/example/jsp/controller/WordController.java | jiangshaofen/spring-boot-example | 5b7cd90c72ea4d43d113db0b1800d06d4bc98319 | [
"MIT"
] | null | null | null | 29.470588 | 91 | 0.780439 | 4,054 | package com.example.jsp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class WordController {
@RequestMapping("/word")
public String hello(Model model,
@RequestParam(value = "name", required = false, defaultValue = "nanjing") String name) {
model.addAttribute("name", name);
return "word";
}
}
|
3e099d5c3e95ed21a577904778e7d5e9241ff972 | 1,376 | java | Java | quickSort/src/com/codeprep/quicksort/Solution.java | thejavamonk/algorithms | 56dbd9cf45201623c7ee426af19df8c09ec7c117 | [
"MIT"
] | null | null | null | quickSort/src/com/codeprep/quicksort/Solution.java | thejavamonk/algorithms | 56dbd9cf45201623c7ee426af19df8c09ec7c117 | [
"MIT"
] | null | null | null | quickSort/src/com/codeprep/quicksort/Solution.java | thejavamonk/algorithms | 56dbd9cf45201623c7ee426af19df8c09ec7c117 | [
"MIT"
] | null | null | null | 16.987654 | 56 | 0.515988 | 4,055 | package com.codeprep.quicksort;
import java.util.Scanner;
public class Solution {
public static void sort(int[] a, int n){
sort(a, 0, n-1);
}
private static void sort(int a[], int low, int up){
if(low >= up){
return;
}
int p = partition(a, low, up);
sort(a, low, p-1);
sort(a, p+1, up);
}
private static int partition(int[] a, int low, int up){
int temp, i, j, pivot;
pivot = a[low];
i = low + 1; // moves from left to right
j = up; // moves from right to left
while(1 <= j){
while(a[i] < pivot && i < up){
i++;
}
while(a[j] > pivot){
j--;
}
if(i < j){ // swap a[i] and a[j]
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}else{ // found proper place for pivot
break;
}
}
// proper place for pivot is j
a[low] = a[j];
a[j] = pivot;
return j;
}
public static void main(String[] args){
int i, n;
int[] a = new int[20];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
n = scan.nextInt();
for(i = 0; i < n; i++){
System.out.println("Enter element "+(i + 1)+" : ");
a[i] = scan.nextInt();
}
sort(a, n);
System.out.println("Sorted array is: ");
for(i = 0; i < n; i++){
System.out.println(a[i] + " ");
}
System.out.println();
scan.close();
}
}
|
3e099e508805c730085a54a0c705cd48237fc8df | 3,472 | java | Java | litemall-db/src/main/java/org/linlinjava/litemall/db/service/LitemallRoleService.java | gardeniasblue/litemall | 79f53c3c40afd57c03aeafb8314dc936ab343360 | [
"MIT"
] | 26 | 2019-05-16T06:48:38.000Z | 2022-02-12T05:38:45.000Z | litemall-db/src/main/java/org/linlinjava/litemall/db/service/LitemallRoleService.java | tanbinh123/springBoot-Vue-applet | 01468ea061bf516118f4ddde0cfc20f78b5bae6a | [
"MIT"
] | null | null | null | litemall-db/src/main/java/org/linlinjava/litemall/db/service/LitemallRoleService.java | tanbinh123/springBoot-Vue-applet | 01468ea061bf516118f4ddde0cfc20f78b5bae6a | [
"MIT"
] | 12 | 2019-06-05T06:42:05.000Z | 2021-11-04T14:35:56.000Z | 33.066667 | 118 | 0.68462 | 4,056 | package org.linlinjava.litemall.db.service;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallRoleMapper;
import org.linlinjava.litemall.db.domain.LitemallRole;
import org.linlinjava.litemall.db.domain.LitemallRoleExample;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class LitemallRoleService {
@Resource
private LitemallRoleMapper roleMapper;
public Set<String> queryByIds(Integer[] roleIds) {
Set<String> roles = new HashSet<String>();
if(roleIds.length == 0){
return roles;
}
LitemallRoleExample example = new LitemallRoleExample();
example.or().andIdIn(Arrays.asList(roleIds)).andEnabledEqualTo(true).andDeletedEqualTo(false);
List<LitemallRole> roleList = roleMapper.selectByExample(example);
for(LitemallRole role : roleList){
roles.add(role.getName());
}
return roles;
}
public List<LitemallRole> querySelective(String roleName, Integer page, Integer size, String sort, String order) {
LitemallRoleExample example = new LitemallRoleExample();
LitemallRoleExample.Criteria criteria = example.createCriteria();
if (!StringUtils.isEmpty(roleName)) {
criteria.andNameEqualTo("%" + roleName + "%");
}
criteria.andDeletedEqualTo(false);
if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
example.setOrderByClause(sort + " " + order);
}
PageHelper.startPage(page, size);
return roleMapper.selectByExample(example);
}
public int countSelective(String roleName, Integer page, Integer size, String sort, String order) {
LitemallRoleExample example = new LitemallRoleExample();
LitemallRoleExample.Criteria criteria = example.createCriteria();
if (!StringUtils.isEmpty(roleName)) {
criteria.andNameEqualTo("%" + roleName + "%");
}
criteria.andDeletedEqualTo(false);
if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
example.setOrderByClause(sort + " " + order);
}
PageHelper.startPage(page, size);
return (int)roleMapper.countByExample(example);
}
public LitemallRole findById(Integer id) {
return roleMapper.selectByPrimaryKey(id);
}
public void add(LitemallRole role) {
role.setAddTime(LocalDateTime.now());
role.setUpdateTime(LocalDateTime.now());
roleMapper.insertSelective(role);
}
public void deleteById(Integer id) {
roleMapper.logicalDeleteByPrimaryKey(id);
}
public void updateById(LitemallRole role) {
role.setUpdateTime(LocalDateTime.now());
roleMapper.updateByPrimaryKeySelective(role);
}
public boolean checkExist(String name) {
LitemallRoleExample example = new LitemallRoleExample();
example.or().andNameEqualTo(name).andDeletedEqualTo(false);
return roleMapper.countByExample(example) != 0;
}
public List<LitemallRole> queryAll() {
LitemallRoleExample example = new LitemallRoleExample();
example.or().andDeletedEqualTo(false);
return roleMapper.selectByExample(example);
}
}
|
3e099f97bd2dfad2b4b3a0aec4c6a535c75a5acd | 20,307 | java | Java | src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/regressionsuites/TestLimitOffsetSuite.java | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/regressionsuites/TestLimitOffsetSuite.java | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/tests/frontend/org/voltdb/regressionsuites/TestLimitOffsetSuite.java | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | 45.943439 | 134 | 0.608312 | 4,057 | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 org.voltdb.regressionsuites;
import java.io.IOException;
import org.voltdb.BackendTarget;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.ProcCallException;
import org.voltdb.client.SyncCallback;
import org.voltdb.compiler.VoltProjectBuilder;
public class TestLimitOffsetSuite extends RegressionSuite {
public TestLimitOffsetSuite(String name)
{
super(name);
}
private static void load(Client client) throws IOException, InterruptedException {
for (int i = 0; i < 10; i++) {
SyncCallback cb = new SyncCallback();
client.callProcedure(cb, "InsertA", i, i);
cb.waitForResponse();
assertEquals(1, cb.getResponse().getResults()[0].asScalarLong());
}
for (int i = 0; i < 10; i++) {
SyncCallback cb = new SyncCallback();
client.callProcedure(cb, "InsertB", i, i);
cb.waitForResponse();
assertEquals(1, cb.getResponse().getResults()[0].asScalarLong());
}
}
private static void doLimitOffsetAndCheck(Client client, String proc) throws IOException, ProcCallException {
ClientResponse resp = client.callProcedure(proc, 4, 0);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
VoltTable[] results = resp.getResults();
assertEquals(1, results.length);
VoltTable vt = results[0];
int i = 0;
while (vt.advanceRow()) {
assertEquals(i++, vt.getLong(1));
}
assertEquals(4, i);
resp = client.callProcedure(proc, 3, 1);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
results = resp.getResults();
assertEquals(1, results.length);
vt = results[0];
i = 1;
while (vt.advanceRow()) {
assertEquals(i++, vt.getLong(1));
}
assertEquals(4, i);
}
/** Check the result of a query that has only an OFFSET and no LIMIT clause.
* This is done by executing the query with and without the offset clause,
* and then skipping past the offset rows in the expected table here
* on the client side. */
private static void doOffsetAndCheck(Client client, String stmt) throws IOException, ProcCallException {
String stmtNoOffset = stmt.substring(0, stmt.indexOf("OFFSET"));
VoltTable expectedTable = client.callProcedure("@AdHoc", stmtNoOffset).getResults()[0];
int rowCountBeforeOffset = expectedTable.getRowCount();
int[] offsets = {0, 1, 5, 10, 11, 15};
for (int offset : offsets) {
VoltTable actualTable = client.callProcedure("@AdHoc", stmt, offset).getResults()[0];
int expectedRowCount = Math.max(rowCountBeforeOffset - offset, 0);
assertEquals("Actual table has wrong number of rows: ",
expectedRowCount, actualTable.getRowCount());
if (actualTable.getRowCount() == 0)
continue;
// non-empty result.
// Advance expected table past offset
// then compare what's left.
actualTable.resetRowPosition();
for (int i = 0; i < offset; ++i)
expectedTable.advanceRow();
while (actualTable.advanceRow() && expectedTable.advanceRow()) {
assertEquals(expectedTable.getLong(0), actualTable.getLong(0));
assertEquals(expectedTable.getLong(1), actualTable.getLong(1));
}
}
}
public void testBasicLimitOffsets() throws IOException, ProcCallException, InterruptedException
{
Client client = this.getClient();
load(client);
String[] procedureNames = {
"LimitAPKEY",
"LimitAI",
"LimitBPKEY",
"LimitBI"
};
for (String procedureName : procedureNames) {
doLimitOffsetAndCheck(client, procedureName);
}
String[] offsetOnlyStmts = {
"SELECT * FROM A ORDER BY PKEY OFFSET ?;",
"SELECT * FROM B ORDER BY PKEY OFFSET ?;",
"SELECT * FROM A ORDER BY I OFFSET ?;",
"SELECT * FROM B ORDER BY I OFFSET ?;"
};
for (String stmt : offsetOnlyStmts) {
doOffsetAndCheck(client, stmt);
}
doTestJoinAndLimitOffset(client);
}
public static void doTestJoinAndLimitOffset(Client client) throws IOException, ProcCallException {
int limits[] = new int[] { 1, 2, 5, 10, 12, 25, Integer.MAX_VALUE };
int offsets[] = new int[] { 0, 1, 2, 5, 10, 12, 25 };
String selecteds[] = new String[] { "*", "A.PKEY" };
String joinops[] = new String[] { ",", "LEFT JOIN", "RIGHT JOIN", " FULL JOIN" };
String conditions[] = new String[] { " A.PKEY < B.PKEY ", " A.PKEY = B.PKEY ", " A.I = B.I " };
client.callProcedure("InsertA", -1, 0);
for (String joinop : joinops) {
String onwhere = "ON";
if (joinop.equals(",")) {
onwhere = "WHERE";
}
for (String selected : selecteds) {
for (int limit : limits) {
for (int offset : offsets) {
for (String condition : conditions) {
String query;
VoltTable result;
query = "SELECT COUNT(*) FROM A " + joinop + " B " +
onwhere + condition +
";";
result = client.callProcedure("@AdHoc", query).getResults()[0];
long found = result.asScalarLong();
query = "SELECT " + selected +
" FROM A " + joinop + " B " +
onwhere + condition +
" ORDER BY A.PKEY, B.PKEY " +
((limit == Integer.MAX_VALUE) ? "" : "LIMIT " + limit) +
((offset == 0) ? "" : " OFFSET " + offset) +
";";
result = client.callProcedure("@AdHoc", query).getResults()[0];
long expectedRowCount = Math.max(0, Math.min(limit, found-offset));
assertEquals("Statement \"" + query + "\" produced wrong number of rows: ",
expectedRowCount, result.getRowCount());
}
}
}
}
}
}
public void testDistinctLimitOffset() throws IOException, ProcCallException {
Client client = getClient();
client.callProcedure("InsertA", 0, 1);
client.callProcedure("InsertA", 1, 1);
client.callProcedure("InsertA", 2, 2);
VoltTable result = null;
result = client.callProcedure("@AdHoc", "SELECT DISTINCT I FROM A LIMIT 1 OFFSET 1;").getResults()[0];
assertEquals(1, result.getRowCount());
result = client.callProcedure("@AdHoc", "SELECT DISTINCT I FROM A LIMIT 0 OFFSET 1;").getResults()[0];
assertEquals(0, result.getRowCount());
}
public void testENG3487() throws IOException, ProcCallException
{
Client client = this.getClient();
client.callProcedure("A.insert", 1, 1);
client.callProcedure("A.insert", 2, 1);
client.callProcedure("A.insert", 3, 1);
client.callProcedure("A.insert", 4, 4);
client.callProcedure("A.insert", 5, 4);
client.callProcedure("A.insert", 6, 9);
VoltTable result = client.callProcedure("@AdHoc", "select I, count(*) as tag from A group by I order by tag, I limit 1")
.getResults()[0];
assertEquals(1, result.getRowCount());
assertTrue(result.advanceRow());
//System.err.println("Result:\n" + result);
assertEquals(9, result.getLong(0));
assertEquals(1, result.getLong(1));
}
public void testENG1808() throws IOException, ProcCallException
{
Client client = this.getClient();
client.callProcedure("A.insert", 1, 1);
VoltTable result = client.callProcedure("@AdHoc", "select I from A limit 0").getResults()[0];
assertEquals(0, result.getRowCount());
}
public void testENG5156() throws IOException, ProcCallException {
Client client = this.getClient();
VoltTable result = null;
String insertProc = "SCORE.insert";
client.callProcedure(insertProc, 1, "b", 1, 1378827221795L, 1, 1);
client.callProcedure(insertProc, 2, "b", 2, 1378827221795L, 2, 2);
result = client.callProcedure("@ExplainProc", "GetTopScores").getResults()[0];
// using the "IDX_SCORE_VALUE_USER" index for sort order only.
assertTrue(result.toString().contains("IDX_SCORE_VALUE_USER"));
assertTrue(result.toString().contains("inline LIMIT with parameter"));
result = client.callProcedure("GetTopScores", 1378827221793L, 1378827421793L, 1).getResults()[0];
validateTableOfLongs(result, new long[][] {{2,2}});
// Test AdHoc.
result = client.callProcedure("@Explain",
"SELECT user_id, score_value FROM score " +
"WHERE score_date > 1378827221793 AND score_date <= 1378827421793 " +
"ORDER BY score_value DESC, user_id DESC LIMIT 1; ").getResults()[0];
assertTrue(result.toString().contains("IDX_SCORE_VALUE_USER"));
assertTrue(result.toString().contains("inline LIMIT with parameter"));
result = client.callProcedure("@AdHoc",
"SELECT user_id, score_value FROM score " +
"WHERE score_date > 1378827221793 AND score_date <= 1378827421793 " +
"ORDER BY score_value DESC, user_id DESC LIMIT 1; ").getResults()[0];
validateTableOfLongs(result, new long[][] {{2,2}});
}
public void testENG6485() throws IOException, ProcCallException {
Client client = this.getClient();
VoltTable result = null;
String insertProc = "C.insert";
client.callProcedure(insertProc, 1, 1, "foo");
client.callProcedure(insertProc, 2, 1, "foo");
client.callProcedure(insertProc, 3, 1, "foo");
client.callProcedure(insertProc, 4, 1, "bar");
client.callProcedure(insertProc, 5, 1, "bar");
client.callProcedure(insertProc, 7, 1, "woof");
client.callProcedure(insertProc, 8, 1, "woof");
client.callProcedure(insertProc, 9, 1, "foo");
client.callProcedure(insertProc, 10, 1, "foo");
client.callProcedure(insertProc, 11, 2, "foo");
client.callProcedure(insertProc, 12, 2, "foo");
client.callProcedure(insertProc, 13, 2, "woof");
client.callProcedure(insertProc, 14, 2, "woof");
client.callProcedure(insertProc, 15, 2, "woof");
client.callProcedure(insertProc, 16, 2, "bar");
client.callProcedure(insertProc, 17, 2, "bar");
client.callProcedure(insertProc, 18, 2, "foo");
client.callProcedure(insertProc, 19, 2, "foo");
result = client.callProcedure("@AdHoc", "SELECT COUNT(*) FROM C;").getResults()[0];
validateTableOfScalarLongs(result, new long[] {18});
result = client.callProcedure("@AdHoc", "SELECT name, count(id) FROM C GROUP BY name limit 1").getResults()[0];
if (result.advanceRow()) {
String name = result.getString(0);
long count = result.getLong(1);
switch (name){
case "foo":
assertEquals(9, count);
break;
case "bar":
assertEquals(4, count);
break;
case "woof":
assertEquals(5, count);
break;
}
}
else {
fail("cannot get data from table c");
}
}
public void testSubqueryLimit() throws Exception {
Client client = getClient();
ClientResponse cr;
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (8, 'nSAFoccWXxEGXR', -3364, 7.76005886643784892343e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (9, 'nSAFoccWXxEGXR', -3364, 8.65086522017155634678e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (10, 'nSAFoccWXxEGXR', 11411, 3.49977104648325210157e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (11, 'nSAFoccWXxEGXR', 11411, 4.96260220021031761561e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (12, 'ebWfhdmIZfYhRC', NULL, 3.94021683247165688257e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (13, 'ebWfhdmIZfYhRC', NULL, 2.97950296374613898820e-02);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (14, 'ebWfhdmIZfYhRC', 23926, 8.56241324965489991605e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (15, 'ebWfhdmIZfYhRC', 23926, 3.61291695704730075889e-01); ");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
String selectStmt = "select NUM from R1 where NUM in (select NUM from R1 where NUM <> 12 order by NUM limit 4) ORDER BY NUM;";
VoltTable tbl;
cr = client.callProcedure("@AdHoc", selectStmt);
tbl = cr.getResults()[0];
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
validateTableOfLongs(tbl, new long[][]{{-3364L}, {-3364}, {11411}, {11411}});
}
public void testLimitZeroWithOrderBy() throws Exception {
Client client = getClient();
ClientResponse cr;
VoltTable vt;
// Check that limit 0 on a table with no indices or partitions
// works as expected, and that it doesn't break other limits.
cr = client.callProcedure("PLAINJANE.insert", 100, 101, 102);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("PLAINJANE.insert", 200, 201, 202);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("PLAINJANE.insert", 300, 301, 302);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("PLAINJANE.insert", 400, 401, 402);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("PLAINJANE.insert", 500, 501, 502);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
for (int idx = 0; idx < 5; idx += 1) {
String sql = "SELECT * FROM PLAINJANE ORDER BY ID LIMIT " + idx + ";";
cr = client.callProcedure("@AdHoc", sql);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
vt = cr.getResults()[0];
assertEquals(idx, vt.getRowCount());
}
// Check the same thing using a table with an index. This is
// important since the plan may be different. The order by
// node of the plan may be avoided by scanning the index.
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (8, 'nSAFoccWXxEGXR', -3364, 7.76005886643784892343e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (9, 'nSAFoccWXxEGXR', -3364, 8.65086522017155634678e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (10, 'nSAFoccWXxEGXR', 11411, 3.49977104648325210157e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (11, 'nSAFoccWXxEGXR', 11411, 4.96260220021031761561e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (12, 'ebWfhdmIZfYhRC', NULL, 3.94021683247165688257e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (13, 'ebWfhdmIZfYhRC', NULL, 2.97950296374613898820e-02);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (14, 'ebWfhdmIZfYhRC', 23926, 8.56241324965489991605e-01);");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
cr = client.callProcedure("@AdHoc", "INSERT INTO R1 VALUES (15, 'ebWfhdmIZfYhRC', 23926, 3.61291695704730075889e-01); ");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
for (int idx = 0; idx < 5; idx += 1) {
String sql = "SELECT * FROM R1 ORDER BY ID LIMIT " + idx + ";";
cr = client.callProcedure("@AdHoc", sql);
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
vt = cr.getResults()[0];
assertEquals(idx, vt.getRowCount());
}
}
static public junit.framework.Test suite()
{
VoltServerConfig config = null;
MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(
TestLimitOffsetSuite.class);
VoltProjectBuilder project = new VoltProjectBuilder();
project.addSchema(TestLimitOffsetSuite.class.getResource("testlimitoffset-ddl.sql"));
project.addPartitionInfo("A", "PKEY");
project.addStmtProcedure("InsertA", "INSERT INTO A VALUES(?, ?);");
project.addStmtProcedure("InsertB", "INSERT INTO B VALUES(?, ?);");
project.addStmtProcedure("LimitAPKEY", "SELECT * FROM A ORDER BY PKEY LIMIT ? OFFSET ?;");
project.addStmtProcedure("LimitBPKEY", "SELECT * FROM B ORDER BY PKEY LIMIT ? OFFSET ?;");
project.addStmtProcedure("LimitAI", "SELECT * FROM A ORDER BY I LIMIT ? OFFSET ?;");
project.addStmtProcedure("LimitBI", "SELECT * FROM B ORDER BY I LIMIT ? OFFSET ?;");
// local
config = new LocalCluster("testlimitoffset-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
// Cluster
config = new LocalCluster("testlimitoffset-cluster.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
// HSQL for baseline
config = new LocalCluster("testlimitoffset-hsql.jar", 1, 1, 0, BackendTarget.HSQLDB_BACKEND);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
return builder;
}
}
|
3e09a0187448f08ad17feeb4a447bc717e6d1051 | 1,875 | java | Java | server/src/main/java/com/decathlon/ara/domain/projection/ExecutedScenarioWithErrorAndProblemJoin.java | youaxa/ara-poc-open | ebec1e751f34bf56930230c2476fbc536b7303a5 | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/decathlon/ara/domain/projection/ExecutedScenarioWithErrorAndProblemJoin.java | youaxa/ara-poc-open | ebec1e751f34bf56930230c2476fbc536b7303a5 | [
"Apache-2.0"
] | 1 | 2022-03-02T05:08:06.000Z | 2022-03-02T05:08:06.000Z | server/src/main/java/com/decathlon/ara/domain/projection/ExecutedScenarioWithErrorAndProblemJoin.java | youaxa/ara-poc-open | ebec1e751f34bf56930230c2476fbc536b7303a5 | [
"Apache-2.0"
] | null | null | null | 31.25 | 119 | 0.6992 | 4,058 | package com.decathlon.ara.domain.projection;
import com.decathlon.ara.domain.ExecutedScenario;
import com.decathlon.ara.domain.Problem;
import com.decathlon.ara.domain.Run;
import com.decathlon.ara.domain.Severity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Wither;
/**
* A join of {@link ExecutedScenario}, {@link Error} and {@link Problem}: provide a few information about the scenario,
* with handled (with not reappeared problem) and unhandled (without problem, or with reappeared problem) errors, if
* any.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Wither
public class ExecutedScenarioWithErrorAndProblemJoin {
/**
* The {@link ExecutedScenario#id} of this entity.
*/
private long id;
/**
* The {@link Run#id} in which this scenario is.
*/
private long runId;
/**
* The {@link Severity#code} of this scenario (can be a code not existing in database: it is user-provided).
*/
private String severity;
/**
* The name of this scenario.
*/
private String name;
/**
* Is > 0 if there are any unhandled errors for this scenario.<br>
* If both {@code unhandledCount} and {@link #handledCount} are > 1, the scenario is considered handled.<br>
* If both {@code unhandledCount} and {@link #handledCount} are 0, the scenario is successful (it has no error).
*/
private long unhandledCount;
/**
* Is > 0 if there are any handled errors for this scenario.<br>
* If both {@link #unhandledCount} and {@code handledCount} are > 1, the scenario is considered handled.<br>
* If both {@link #unhandledCount} and {@code handledCount} are 0, the scenario is successful (it has no error).
*/
private long handledCount;
}
|
3e09a104b55e2139a0ded8ac54153a283e17113b | 9,238 | java | Java | iddd_common/src/test/java/com/saasovation/common/port/adapter/persistence/leveldb/LevelDBPersistenceTest.java | epy0n0ff/IDDD_Samples | 05d95572f2ad6b85357b216d7d617b27359a360d | [
"Apache-2.0"
] | 2,945 | 2015-01-06T11:13:34.000Z | 2022-03-31T02:15:37.000Z | iddd_common/src/test/java/com/saasovation/common/port/adapter/persistence/leveldb/LevelDBPersistenceTest.java | kaminotsukai/IDDD_Samples | 05d95572f2ad6b85357b216d7d617b27359a360d | [
"Apache-2.0"
] | 27 | 2015-02-21T19:14:32.000Z | 2022-03-28T04:33:30.000Z | iddd_common/src/test/java/com/saasovation/common/port/adapter/persistence/leveldb/LevelDBPersistenceTest.java | kaminotsukai/IDDD_Samples | 05d95572f2ad6b85357b216d7d617b27359a360d | [
"Apache-2.0"
] | 801 | 2015-01-05T12:06:39.000Z | 2022-03-28T10:43:50.000Z | 34.342007 | 94 | 0.611496 | 4,059 | // Copyright 2012,2013 Vaughn Vernon
//
// 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.saasovation.common.port.adapter.persistence.leveldb;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class LevelDBPersistenceTest extends LevelDBTest {
private LevelRepository levelRepository = new LevelRepository();
public LevelDBPersistenceTest() {
super();
}
public void testSaveAndQuery() throws Exception {
Level level1 = new Level("1", "One", 1);
Level level2 = new Level("2", "Two", 2);
Level level3 = new Level("3", "Three", 3);
LevelDBUnitOfWork.start(this.database());
levelRepository.save(level1);
levelRepository.save(level2);
levelRepository.save(level3);
LevelDBUnitOfWork.current().commit();
assertEquals(3, levelRepository.allLevels().size());
assertEquals(level1.id(), levelRepository.levelOfId("1").id());
assertEquals(level2.id(), levelRepository.levelOfId("2").id());
assertEquals(level3.id(), levelRepository.levelOfId("3").id());
assertEquals(level1.name(), levelRepository.levelOfName("One").name());
assertEquals(level2.name(), levelRepository.levelOfName("Two").name());
assertEquals(level3.name(), levelRepository.levelOfName("Three").name());
assertEquals(level1.value(), levelRepository.levelOfId("1").value());
assertEquals(level2.value(), levelRepository.levelOfId("2").value());
assertEquals(level3.value(), levelRepository.levelOfId("3").value());
}
public void testRemoveAndQuery() throws Exception {
Level level1 = new Level("1", "One", 1);
Level level2 = new Level("2", "Two", 2);
Level level3 = new Level("3", "Three", 3);
LevelDBUnitOfWork.start(this.database());
levelRepository.save(level1);
levelRepository.save(level2);
levelRepository.save(level3);
LevelDBUnitOfWork.current().commit();
assertEquals(3, levelRepository.allLevels().size());
assertEquals(level1.id(), levelRepository.levelOfId("1").id());
assertEquals(level2.id(), levelRepository.levelOfId("2").id());
assertEquals(level3.id(), levelRepository.levelOfId("3").id());
LevelDBUnitOfWork.start(this.database());
levelRepository.remove(level2);
LevelDBUnitOfWork.current().commit();
assertEquals(2, levelRepository.allLevels().size());
assertNull(levelRepository.levelOfId("2"));
assertEquals(level1.id(), levelRepository.levelOfId("1").id());
assertEquals(level3.id(), levelRepository.levelOfId("3").id());
LevelDBUnitOfWork.start(this.database());
levelRepository.remove(level1);
LevelDBUnitOfWork.current().commit();
assertEquals(1, levelRepository.allLevels().size());
assertNull(levelRepository.levelOfId("1"));
assertNull(levelRepository.levelOfId("2"));
assertEquals(level3.id(), levelRepository.levelOfId("3").id());
LevelDBUnitOfWork.start(this.database());
levelRepository.remove(level3);
LevelDBUnitOfWork.current().commit();
assertTrue(levelRepository.allLevels().isEmpty());
assertNull(levelRepository.levelOfId("1"));
assertNull(levelRepository.levelOfId("2"));
assertNull(levelRepository.levelOfId("3"));
}
public void testConcurrentSaves() throws Exception {
final List<Integer> orderOfCommits = new ArrayList<Integer>();
Level level1 = new Level("1", "One", 1);
LevelDBUnitOfWork.start(this.database());
levelRepository.save(level1);
new Thread() {
@Override
public void run() {
Level level2 = new Level("2", "Two", 2);
Level level3 = new Level("3", "Three", 3);
System.out.println("Preparing to commit levels 2 and 3...");
LevelDBUnitOfWork.start(database());
levelRepository.save(level2);
levelRepository.save(level3);
LevelDBUnitOfWork.current().commit();
orderOfCommits.add(2);
orderOfCommits.add(3);
System.out.println("Committed levels 2 and 3.");
}
}.start();
System.out.println("Set to commit level 1, soon...");
Thread.sleep(250L);
System.out.println("Back to preparing to commit level 1...");
LevelDBUnitOfWork.current().commit();
orderOfCommits.add(1);
System.out.println("Committed level 1.");
for (int idx = 0; idx < orderOfCommits.size(); ++idx) {
assertEquals(idx + 1, orderOfCommits.get(idx).intValue());
}
Thread.sleep(250L);
Collection<Level> savedLevels = levelRepository.allLevels();
assertFalse(savedLevels.isEmpty());
assertEquals(3, savedLevels.size());
}
private static class LevelRepository extends AbstractLevelDBRepository {
private static final String PRIMARY = "LEVEL#PK";
private static final String ALL_LEVELS = "LEVEL#ALL";
private static final String NAME_OF_LEVEL = "LEVEL#NAME";
public LevelRepository() {
super(TEST_DATABASE);
}
public Collection<Level> allLevels() {
List<Level> levels = new ArrayList<Level>();
LevelDBKey allLevelsKey = new LevelDBKey(ALL_LEVELS);
LevelDBUnitOfWork uow = LevelDBUnitOfWork.readOnly(this.database());
List<Object> keys = uow.readKeys(allLevelsKey);
for (Object levelId : keys) {
Level level = uow.readObject(levelId.toString().getBytes(), Level.class);
if (level != null) {
levels.add(level);
}
}
return levels;
}
public Level levelOfName(String aName) {
Level level = null;
LevelDBKey nameKey = new LevelDBKey(NAME_OF_LEVEL, aName);
Object levelId = LevelDBUnitOfWork.readOnly(this.database()).readKey(nameKey);
if (levelId != null) {
LevelDBUnitOfWork uow = LevelDBUnitOfWork.readOnly(this.database());
level = uow.readObject(levelId.toString().getBytes(), Level.class);
}
return level;
}
public Level levelOfId(String anId) {
LevelDBKey primaryKey = new LevelDBKey(PRIMARY, anId);
Level level =
LevelDBUnitOfWork.readOnly(this.database())
.readObject(primaryKey.key().getBytes(), Level.class);
return level;
}
public void remove(Level aLevel) {
LevelDBKey lockKey = new LevelDBKey(PRIMARY);
LevelDBUnitOfWork uow = LevelDBUnitOfWork.current();
uow.lock(lockKey.key());
this.remove(aLevel, uow);
}
public void save(Level aLevel) {
LevelDBKey lockKey = new LevelDBKey(PRIMARY);
LevelDBUnitOfWork uow = LevelDBUnitOfWork.current();
uow.lock(lockKey.key());
this.save(aLevel, uow);
}
private void remove(Level aLevel, LevelDBUnitOfWork aUoW) {
LevelDBKey primaryKey = new LevelDBKey(PRIMARY, aLevel.id());
aUoW.remove(primaryKey);
LevelDBKey allLevels = new LevelDBKey(primaryKey, ALL_LEVELS);
aUoW.removeKeyReference(allLevels);
LevelDBKey nameOfLevel = new LevelDBKey(primaryKey, NAME_OF_LEVEL, aLevel.name());
aUoW.removeKeyReference(nameOfLevel);
}
private void save(Level aLevel, LevelDBUnitOfWork aUoW) {
LevelDBKey primaryKey = new LevelDBKey(PRIMARY, aLevel.id());
aUoW.write(primaryKey, aLevel);
LevelDBKey allLevels = new LevelDBKey(primaryKey, ALL_LEVELS);
aUoW.updateKeyReference(allLevels);
LevelDBKey nameOfLevel = new LevelDBKey(primaryKey, NAME_OF_LEVEL, aLevel.name());
aUoW.updateKeyReference(nameOfLevel);
}
}
private static class Level {
private String id;
private String name;
private int value;
public Level(String anId, String aName, int aValue) {
super();
this.id = anId;
this.name = aName;
this.value = aValue;
}
public String id() {
return this.id;
}
public String name() {
return this.name;
}
public int value() {
return this.value;
}
}
}
|
3e09a1373938579edd246f5aa36ea2164e392b37 | 9,177 | java | Java | asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/IntroduceCreateFlatObjectRule.java | wailyk/column | 7ac882ac26f11b4d071deb6bfb0cbb3ad5094508 | [
"Apache-2.0"
] | null | null | null | asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/IntroduceCreateFlatObjectRule.java | wailyk/column | 7ac882ac26f11b4d071deb6bfb0cbb3ad5094508 | [
"Apache-2.0"
] | null | null | null | asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/IntroduceCreateFlatObjectRule.java | wailyk/column | 7ac882ac26f11b4d071deb6bfb0cbb3ad5094508 | [
"Apache-2.0"
] | null | null | null | 49.605405 | 127 | 0.713305 | 4,060 | /*
* 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.asterix.optimizer.rules;
import java.util.ArrayList;
import java.util.List;
import org.apache.asterix.algebra.operators.CommitOperator;
import org.apache.asterix.lang.common.util.FunctionUtil;
import org.apache.asterix.metadata.declared.DatasetDataSource;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.AUnionType;
import org.apache.asterix.om.types.IAType;
import org.apache.asterix.om.utils.NonTaggedFormatUtil;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AssignOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.DelegateOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.InsertDeleteUpsertOperator;
import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;
public class IntroduceCreateFlatObjectRule implements IAlgebraicRewriteRule {
@Override
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
throws AlgebricksException {
return false;
}
@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
throws AlgebricksException {
ARecordType requiredRecordType;
LogicalVariable recordVar;
// We identify INSERT operators.
AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue();
if (op1.getOperatorTag() != LogicalOperatorTag.SINK
&& op1.getOperatorTag() != LogicalOperatorTag.DELEGATE_OPERATOR) {
return false;
}
/**
* pattern match: commit insert assign
* resulting plan: commit-insert-project-assign
*/
if (op1.getOperatorTag() == LogicalOperatorTag.DELEGATE_OPERATOR) {
DelegateOperator eOp = (DelegateOperator) op1;
if (!(eOp.getDelegate() instanceof CommitOperator)) {
return false;
}
}
AbstractLogicalOperator op2 = (AbstractLogicalOperator) op1.getInputs().get(0).getValue();
while (op2.getOperatorTag() != LogicalOperatorTag.INSERT_DELETE_UPSERT && !op2.getInputs().isEmpty()) {
op2 = (AbstractLogicalOperator) op2.getInputs().get(0).getValue();
}
if (op2.getOperatorTag() != LogicalOperatorTag.INSERT_DELETE_UPSERT) {
return false;
}
InsertDeleteUpsertOperator insertDeleteOp = (InsertDeleteUpsertOperator) op2;
if (insertDeleteOp.getOperation() == InsertDeleteUpsertOperator.Kind.DELETE) {
return false;
}
DatasetDataSource dataSource = (DatasetDataSource) insertDeleteOp.getDataSource();
if (!dataSource.isAllowPushdown()) {
return false;
}
requiredRecordType = (ARecordType) dataSource.getItemType();
// Derive the Variable which we will potentially wrap with cast/null functions
ILogicalExpression expr = insertDeleteOp.getPayloadExpression().getValue();
List<LogicalVariable> payloadVars = new ArrayList<>();
expr.getUsedVariables(payloadVars);
recordVar = payloadVars.get(0);
// Derive the statically-computed type of the record
IVariableTypeEnvironment env = insertDeleteOp.computeOutputTypeEnvironment(context);
IAType inputRecordType = (IAType) env.getVarType(recordVar);
if (inputRecordType.getTypeTag() != ATypeTag.OBJECT) {
return false;
}
/** the input record type can be an union type -- for the case when it comes from a subplan or left-outer join */
boolean checkUnknown = false;
while (NonTaggedFormatUtil.isOptional(inputRecordType)) {
/** while-loop for the case there is a nested multi-level union */
inputRecordType = ((AUnionType) inputRecordType).getActualType();
checkUnknown = true;
}
if (checkUnknown) {
recordVar = IntroduceDynamicTypeCastRule.addWrapperFunction(requiredRecordType, recordVar, insertDeleteOp,
context, BuiltinFunctions.CHECK_UNKNOWN);
}
createIDsFlatObjectRecord(context, insertDeleteOp, inputRecordType, recordVar);
return false;
}
private void createIDsFlatObjectRecord(IOptimizationContext context, InsertDeleteUpsertOperator insertOp,
IAType inputType, LogicalVariable recordVar) throws AlgebricksException {
//Flatten record
final AbstractFunctionCallExpression flatFunc =
new ScalarFunctionCallExpression(FunctionUtil.getFunctionInfo(BuiltinFunctions.CREATE_FLAT_OBJECT));
flatFunc.getArguments().add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(recordVar)));
flatFunc.setOpaqueParameters(new IAType[] { inputType });
//PK access
final List<Mutable<ILogicalExpression>> pkExpers = insertOp.getPrimaryKeyExpressions();
final DatasetDataSource dds = (DatasetDataSource) insertOp.getDataSource();
final List<String> pkeys = dds.getDataset().getPrimaryKeys().get(0);
if (pkeys.size() != pkExpers.size()) {
throw new AlgebricksException("Nested keys are not supported.");
}
//ClosedRecordConstructor
// List<Mutable<ILogicalExpression>> closedRecordConsArgs = new ArrayList<>();
//
// for (int i = 0; i < pkeys.size(); i++) {
// final Mutable<ILogicalExpression> pkFieldNameExpression =
// new MutableObject<>(new ConstantExpression(new AsterixConstantValue(new AString(pkeys.get(i)))));
// closedRecordConsArgs.add(pkFieldNameExpression);
// closedRecordConsArgs.add(pkExpers.get(i));
// }
//
// //Type is [key1, key2, ... keyn, flatObject] ==> length-1 is the index of the value.
// final Mutable<ILogicalExpression> flatObjectFieldName =
// new MutableObject<>(new ConstantExpression(new AsterixConstantValue(
// new AString(requiredType.getFieldNames()[requiredType.getFieldNames().length - 1]))));
// closedRecordConsArgs.add(flatObjectFieldName);
//
// //flatObject values
// closedRecordConsArgs.add(new MutableObject<>(flatFunc));
// final AbstractFunctionCallExpression closedRecordCons = new ScalarFunctionCallExpression(
// FunctionUtil.getFunctionInfo(BuiltinFunctions.CLOSED_RECORD_CONSTRUCTOR), closedRecordConsArgs);
final LogicalVariable newAssignVar = context.newVar();
final AssignOperator newAssignOp = new AssignOperator(newAssignVar, new MutableObject<>(flatFunc));
final Mutable<ILogicalOperator> insertInput = insertOp.getInputs().get(0);
newAssignOp.getInputs().add(new MutableObject<>(insertInput.getValue()));
insertInput.setValue(newAssignOp);
insertOp.getPayloadExpression().setValue(new VariableReferenceExpression(newAssignVar));
context.computeAndSetTypeEnvironmentForOperator(newAssignOp);
newAssignOp.computeOutputTypeEnvironment(context);
}
}
|
3e09a28e49e474ae86f348c717e2b038ff40cb67 | 612 | java | Java | weixin-pay/src/main/java/com/github/songxzj/wxpay/v3/bean/result/media/WxMediaUploadResult.java | songxzj/weixin-sdk-java | 42ab624384473f321d104682442dc23c649e744b | [
"Apache-2.0"
] | null | null | null | weixin-pay/src/main/java/com/github/songxzj/wxpay/v3/bean/result/media/WxMediaUploadResult.java | songxzj/weixin-sdk-java | 42ab624384473f321d104682442dc23c649e744b | [
"Apache-2.0"
] | null | null | null | weixin-pay/src/main/java/com/github/songxzj/wxpay/v3/bean/result/media/WxMediaUploadResult.java | songxzj/weixin-sdk-java | 42ab624384473f321d104682442dc23c649e744b | [
"Apache-2.0"
] | null | null | null | 23.538462 | 71 | 0.754902 | 4,061 | package com.github.songxzj.wxpay.v3.bean.result.media;
import com.github.songxzj.wxpay.v3.bean.result.BaseWxPayV3Result;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Setter
@Getter
@ToString
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class WxMediaUploadResult extends BaseWxPayV3Result {
private static final long serialVersionUID = -5296759796748982463L;
/**
* 媒体文件标识 Id
* media_id
* string(512)
* 是
*/
@SerializedName("media_id")
private String mediaId;
}
|
3e09a3ac34d3fd63010d129061800f9df6b1f55a | 4,073 | java | Java | src/main/java/io/github/logtube/core/outputs/EventRedisOutput.java | 137310853/logtube-java | 9df4793b5fbc57d04075e0ce19d49959f8d3db07 | [
"MIT"
] | 14 | 2019-05-10T07:07:37.000Z | 2021-08-03T06:16:37.000Z | src/main/java/io/github/logtube/core/outputs/EventRedisOutput.java | 137310853/logtube-java | 9df4793b5fbc57d04075e0ce19d49959f8d3db07 | [
"MIT"
] | 7 | 2021-01-19T03:15:14.000Z | 2022-03-31T20:07:39.000Z | src/main/java/io/github/logtube/core/outputs/EventRedisOutput.java | 137310853/logtube-java | 9df4793b5fbc57d04075e0ce19d49959f8d3db07 | [
"MIT"
] | 9 | 2019-06-20T02:43:03.000Z | 2021-11-26T07:22:17.000Z | 28.683099 | 96 | 0.571814 | 4,062 | package io.github.logtube.core.outputs;
import io.github.logtube.core.IEvent;
import io.github.logtube.core.IEventSerializer;
import io.github.logtube.core.serializers.EventRedisSerializer;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class EventRedisOutput extends BaseEventOutput {
private static final int QUEUE_CAPACITY = 1024;
private final IEventSerializer serializer = new EventRedisSerializer();
private final String[] hosts;
private final String key;
@NotNull
private final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
private EventRedisOutputWorker worker = null;
@NotNull
private JedisPool createJedisPool(@NotNull String host) {
String[] split = host.split(":");
// fix for HOST:PORT format
if (split.length == 2) {
return new JedisPool(split[0], Integer.valueOf(split[1]));
}
return new JedisPool(host);
}
public EventRedisOutput(String[] hosts, String key) {
this.hosts = hosts;
this.key = key;
}
@Override
public void doStart() {
super.doStart();
this.worker = new EventRedisOutputWorker(this.hosts, this.key);
this.worker.start();
}
@Override
public void doStop() {
this.worker.exit();
try {
this.worker.join();
} catch (InterruptedException ignored) {
}
this.worker = null;
super.doStop();
}
@Override
public void doAppendEvent(@NotNull IEvent e) {
this.queue.offer(serializer.toString(e));
}
private class EventRedisOutputWorker extends Thread {
private final ArrayList<JedisPool> pools = new ArrayList<>();
private final String key;
private final AtomicLong cursor = new AtomicLong();
private boolean shouldExit = false;
EventRedisOutputWorker(String[] hosts, String key) {
super("logtube-EventRedisOutputWorker");
for (String host : hosts) {
this.pools.add(createJedisPool(host));
}
this.key = key;
}
public void exit() {
this.shouldExit = true;
}
@NotNull
private Jedis getJedis(int retry) {
// if retry is too small, returns null
if (retry < 1) {
throw new JedisConnectionException("failed to find a reachable redis instance");
}
// roll the round robin
long index = this.cursor.addAndGet(1);
if (index < 0) {
index = 0;
}
// find a pool and get a jedis
try {
return this.pools.get((int) (index % (long) this.pools.size())).getResource();
} catch (Exception ignored) {
}
return getJedis(retry - 1);
}
@NotNull
private Jedis getJedis() {
return getJedis(this.pools.size());
}
@Override
public void run() {
while (!this.shouldExit) {
// take a message
String message = null;
try {
message = EventRedisOutput.this.queue.poll(5, TimeUnit.SECONDS);
} catch (Exception ignored) {
continue;
}
if (message == null) {
continue;
}
// push a message
try (Jedis jedis = getJedis()) { // use try-with-resource
jedis.rpush(this.key, message);
} catch (Exception ignored) {
}
}
// clear the pool on shutdown
this.pools.clear();
}
}
}
|
3e09a3adbb84642a377f1969ad98dd87ee226124 | 1,204 | java | Java | testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 23.153846 | 103 | 0.686047 | 4,063 | package com.baeldung.migration.junit4;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(JUnit4.class)
public class BeforeAndAfterAnnotationsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsUnitTest.class);
private List<String> list;
@Before
public void init() {
LOG.debug("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
@After
public void teardown() {
LOG.debug("teardown");
list.clear();
}
@Test
public void whenCheckingListSize_thenSizeEqualsToInit() {
LOG.debug("executing test");
assertEquals(2, list.size());
list.add("another test");
}
@Test
public void whenCheckingListSizeAgain_thenSizeEqualsToInit() {
LOG.debug("executing another test");
assertEquals(2, list.size());
list.add("yet another test");
}
}
|
3e09a3c9bbe7fed50d675a0ef9785f87924ac80d | 261 | java | Java | src/test/java/es/uniovi/asw/CalculatorTest.java | labra/citizensLoader0 | 6a71d8a3e014e2d2dc0a4ec240eddd65542cae00 | [
"Unlicense"
] | null | null | null | src/test/java/es/uniovi/asw/CalculatorTest.java | labra/citizensLoader0 | 6a71d8a3e014e2d2dc0a4ec240eddd65542cae00 | [
"Unlicense"
] | null | null | null | src/test/java/es/uniovi/asw/CalculatorTest.java | labra/citizensLoader0 | 6a71d8a3e014e2d2dc0a4ec240eddd65542cae00 | [
"Unlicense"
] | 2 | 2017-01-23T23:26:36.000Z | 2017-02-02T11:45:34.000Z | 15.352941 | 44 | 0.735632 | 4,064 | package es.uniovi.asw;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void evalAdd() {
Calculator calc = new Calculator();
Integer expected = 5;
assertEquals(calc.add(3, 2), expected);
}
}
|
3e09a48fb3757e432b2af34c7c2d53f9cf332a2d | 1,350 | java | Java | user-service/v3/src/test/java/com/atul/gitbook/learn/users/service/UserServiceTest.java | atulanand206/rest-using-spring-boot | c2c8bbbfc0cbb79861f845204336bda661dd108c | [
"MIT"
] | null | null | null | user-service/v3/src/test/java/com/atul/gitbook/learn/users/service/UserServiceTest.java | atulanand206/rest-using-spring-boot | c2c8bbbfc0cbb79861f845204336bda661dd108c | [
"MIT"
] | null | null | null | user-service/v3/src/test/java/com/atul/gitbook/learn/users/service/UserServiceTest.java | atulanand206/rest-using-spring-boot | c2c8bbbfc0cbb79861f845204336bda661dd108c | [
"MIT"
] | null | null | null | 35.315789 | 101 | 0.722057 | 4,065 | package com.atul.gitbook.learn.users.service;
import com.atul.gitbook.learn.AppConfig;
import com.atul.gitbook.learn.users.models.UserDto;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(
properties = "spring.main.allow-bean-definition-overriding=true",
classes = {AppConfig.class})
class UserServiceTest {
@Autowired
IUserService fUserService;
@Test
void testCreateUserWhenDtoIsNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> fUserService.createUser(null));
}
@Test
void testCreateUserWhenDtoContainsAllTheFields() {
final var userDto = new UserDto("Ramsay", "9876483456", "hzdkv@example.com");
Assertions.assertDoesNotThrow(() -> fUserService.createUser(userDto));
}
@Test
void testCreateUser() {
final var expected = new UserDto("Ramsay", "9876483456", "hzdkv@example.com");
final var actual = fUserService.createUser(expected);
Assertions.assertEquals(expected.getName(), actual.getName());
Assertions.assertEquals(expected.getPhone(), actual.getPhone());
Assertions.assertEquals(expected.getEmail(), actual.getEmail());
}
}
|
3e09a4ce5f3d42abcaf46ab677cf25f8d9cb227c | 1,955 | java | Java | google-account-plugin/src/com/google/gct/stats/UsageTrackerExtensionPointBean.java | etanshaul/travis-cobertura-test | 195ab49e76749b9e0fc0b1d0be51cd92daee4f87 | [
"Apache-2.0"
] | 2 | 2021-02-22T02:38:39.000Z | 2021-02-22T03:05:34.000Z | google-account-plugin/src/com/google/gct/stats/UsageTrackerExtensionPointBean.java | etanshaul/gcloud-intellij | 0855780ef0bf0871383908e9b07bb6eac4de9bf1 | [
"Apache-2.0"
] | 1 | 2017-01-27T22:04:26.000Z | 2017-01-30T17:27:58.000Z | google-account-plugin/src/com/google/gct/stats/UsageTrackerExtensionPointBean.java | etanshaul/gcloud-intellij | 0855780ef0bf0871383908e9b07bb6eac4de9bf1 | [
"Apache-2.0"
] | 1 | 2020-10-19T18:52:40.000Z | 2020-10-19T18:52:40.000Z | 32.04918 | 89 | 0.764706 | 4,066 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gct.stats;
import com.intellij.openapi.extensions.AbstractExtensionPointBean;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.LazyInstance;
import com.intellij.util.KeyedLazyInstance;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.NotNull;
/**
* Class that defines extensions points in plugin.xml, Extensions point will implement
* {@link UsageTrackerProvider}
*/
public class UsageTrackerExtensionPointBean extends AbstractExtensionPointBean implements
KeyedLazyInstance<UsageTracker> {
// TODO : when changing the package root for this plugin, update this
static final ExtensionPointName<UsageTracker> EP_NAME =
new ExtensionPointName<UsageTracker>("com.google.gct.login.usageTracker");
@Attribute("key")
public String key;
@Attribute("implementationClass")
public String implementationClass;
private final LazyInstance<UsageTracker> myHandler = new LazyInstance<UsageTracker>() {
@Override
protected Class<UsageTracker> getInstanceClass() throws ClassNotFoundException {
return findClass(implementationClass);
}
};
@NotNull
@Override
public UsageTracker getInstance() {
return myHandler.getValue();
}
@Override
public String getKey() {
return key;
}
}
|
3e09a5844f5cdf2f7f2bb9eb0dc1901799f4e3e5 | 92 | java | Java | LostTale/src/main/java/xyz/studiomango/losttale/core/items/MeleeWeapon.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | LostTale/src/main/java/xyz/studiomango/losttale/core/items/MeleeWeapon.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | LostTale/src/main/java/xyz/studiomango/losttale/core/items/MeleeWeapon.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | 30.666667 | 46 | 0.836957 | 4,067 | package xyz.studiomango.losttale.core.items;
public interface MeleeWeapon extends Weapon {} |
3e09a60f04daa85e78b3413510813743c53804be | 10,076 | java | Java | tests/tests/text/src/android/text/method/cts/TextKeyListenerTest.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | tests/tests/text/src/android/text/method/cts/TextKeyListenerTest.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | tests/tests/text/src/android/text/method/cts/TextKeyListenerTest.java | HelixOS/cts | 1956c3f1525d6b7bf668f1671e7c29cb6fbb9c9a | [
"Apache-2.0"
] | null | null | null | 36.773723 | 99 | 0.663259 | 4,068 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text.method.cts;
import android.os.SystemClock;
import android.test.UiThreadTest;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.cts.KeyListenerTestCase;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextKeyListenerTest extends KeyListenerTestCase {
/**
* time out of MultiTapKeyListener. longer than 2000ms in case the system is sluggish.
*/
private static final long TIME_OUT = 3000;
public void testConstructor() {
new TextKeyListener(Capitalize.NONE, true);
new TextKeyListener(null, true);
}
public void testShouldCap() {
String str = "hello world! man";
// Index of the characters(start with 0):
// 'h' = 0; 'w' = 6; 'm' = 13; 'a' = 14
assertFalse(TextKeyListener.shouldCap(Capitalize.NONE, str, 0));
assertTrue(TextKeyListener.shouldCap(Capitalize.SENTENCES, str, 0));
assertTrue(TextKeyListener.shouldCap(Capitalize.WORDS, str, 0));
assertTrue(TextKeyListener.shouldCap(Capitalize.CHARACTERS, str, 0));
assertFalse(TextKeyListener.shouldCap(Capitalize.NONE, str, 6));
assertFalse(TextKeyListener.shouldCap(Capitalize.SENTENCES, str, 6));
assertTrue(TextKeyListener.shouldCap(Capitalize.WORDS, str, 6));
assertTrue(TextKeyListener.shouldCap(Capitalize.CHARACTERS, str, 6));
assertFalse(TextKeyListener.shouldCap(Capitalize.NONE, str, 13));
assertTrue(TextKeyListener.shouldCap(Capitalize.SENTENCES, str, 13));
assertTrue(TextKeyListener.shouldCap(Capitalize.WORDS, str, 13));
assertTrue(TextKeyListener.shouldCap(Capitalize.CHARACTERS, str, 13));
assertFalse(TextKeyListener.shouldCap(Capitalize.NONE, str, 14));
assertFalse(TextKeyListener.shouldCap(Capitalize.SENTENCES, str, 14));
assertFalse(TextKeyListener.shouldCap(Capitalize.WORDS, str, 14));
assertTrue(TextKeyListener.shouldCap(Capitalize.CHARACTERS, str, 14));
try {
TextKeyListener.shouldCap(Capitalize.WORDS, null, 16);
fail("should throw NullPointerException.");
} catch (NullPointerException e) {
}
}
public void testOnSpanAdded() {
final MockTextKeyListener mockTextKeyListener
= new MockTextKeyListener(Capitalize.CHARACTERS, true);
final Spannable text = new SpannableStringBuilder("123456");
assertFalse(mockTextKeyListener.hadAddedSpan());
mActivity.runOnUiThread(new Runnable() {
public void run() {
mTextView.setKeyListener(mockTextKeyListener);
mTextView.setText(text, BufferType.EDITABLE);
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mockTextKeyListener.hadAddedSpan());
mockTextKeyListener.release();
}
public void testGetInstance1() {
TextKeyListener listener1 = TextKeyListener.getInstance(true, Capitalize.WORDS);
TextKeyListener listener2 = TextKeyListener.getInstance(true, Capitalize.WORDS);
TextKeyListener listener3 = TextKeyListener.getInstance(false, Capitalize.WORDS);
TextKeyListener listener4 = TextKeyListener.getInstance(true, Capitalize.CHARACTERS);
assertNotNull(listener1);
assertNotNull(listener2);
assertSame(listener1, listener2);
assertNotSame(listener1, listener3);
assertNotSame(listener1, listener4);
assertNotSame(listener4, listener3);
listener1.release();
listener2.release();
listener3.release();
listener4.release();
}
public void testGetInstance2() {
TextKeyListener listener1 = TextKeyListener.getInstance();
TextKeyListener listener2 = TextKeyListener.getInstance();
assertNotNull(listener1);
assertNotNull(listener2);
assertSame(listener1, listener2);
listener1.release();
listener2.release();
}
public void testOnSpanChanged() {
TextKeyListener textKeyListener = TextKeyListener.getInstance();
final Spannable text = new SpannableStringBuilder("123456");
textKeyListener.onSpanChanged(text, Selection.SELECTION_END, 0, 0, 0, 0);
try {
textKeyListener.onSpanChanged(null, Selection.SELECTION_END, 0, 0, 0, 0);
fail("should throw NullPointerException.");
} catch (NullPointerException e) {
}
textKeyListener.release();
}
@UiThreadTest
public void testClear() {
CharSequence text = "123456";
mTextView.setText(text, BufferType.EDITABLE);
Editable content = (Editable) mTextView.getText();
assertEquals(text, content.toString());
TextKeyListener.clear(content);
assertEquals("", content.toString());
}
public void testOnSpanRemoved() {
TextKeyListener textKeyListener = new TextKeyListener(Capitalize.CHARACTERS, true);
final Spannable text = new SpannableStringBuilder("123456");
textKeyListener.onSpanRemoved(text, new Object(), 0, 0);
textKeyListener.release();
}
/**
* Wait for TIME_OUT, or listener will accept key event as multi tap rather than a new key.
*/
private void waitForListenerTimeout() {
try {
Thread.sleep(TIME_OUT);
} catch (InterruptedException e) {
fail("thrown unexpected InterruptedException when sleep.");
}
}
/**
* Check point:
* 1. press KEYCODE_4 once. if it's ALPHA key board, text will be "4", if it's
* NUMERIC key board, text will be "g", else text will be "".
*/
public void testPressKey() {
final TextKeyListener textKeyListener
= TextKeyListener.getInstance(false, Capitalize.NONE);
mActivity.runOnUiThread(new Runnable() {
public void run() {
mTextView.setText("", BufferType.EDITABLE);
Selection.setSelection((Editable) mTextView.getText(), 0, 0);
mTextView.setKeyListener(textKeyListener);
mTextView.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
assertEquals("", mTextView.getText().toString());
sendKeys(KeyEvent.KEYCODE_4);
waitForListenerTimeout();
String text = mTextView.getText().toString();
int keyType = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD).getKeyboardType();
if (KeyCharacterMap.ALPHA == keyType
|| KeyCharacterMap.FULL == keyType) {
assertEquals("4", text);
} else if (KeyCharacterMap.NUMERIC == keyType) {
assertEquals("g", text);
} else {
assertEquals("", text);
}
textKeyListener.release();
}
public void testOnKeyOther() {
final String text = "abcd";
final TextKeyListener textKeyListener
= TextKeyListener.getInstance(false, Capitalize.NONE);
mActivity.runOnUiThread(new Runnable() {
public void run() {
mTextView.setText("", BufferType.EDITABLE);
Selection.setSelection((Editable) mTextView.getText(), 0, 0);
mTextView.setKeyListener(textKeyListener);
}
});
mInstrumentation.waitForIdleSync();
assertEquals("", mTextView.getText().toString());
// test ACTION_MULTIPLE KEYCODE_UNKNOWN key event.
KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), text,
1, KeyEvent.FLAG_WOKE_HERE);
mInstrumentation.sendKeySync(event);
mInstrumentation.waitForIdleSync();
// the text of TextView is never changed, onKeyOther never works.
// assertEquals(text, mTextView.getText().toString()); issue 1731439
textKeyListener.release();
}
public void testGetInputType() {
TextKeyListener listener = TextKeyListener.getInstance(false, Capitalize.NONE);
int expected = InputType.TYPE_CLASS_TEXT;
assertEquals(expected, listener.getInputType());
listener = TextKeyListener.getInstance(false, Capitalize.CHARACTERS);
expected = InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
assertEquals(expected, listener.getInputType());
listener.release();
}
/**
* A mocked {@link android.text.method.TextKeyListener} for testing purposes.
*
* Tracks whether {@link MockTextKeyListener#onSpanAdded(Spannable, Object, int, int)} has been
* called.
*/
private class MockTextKeyListener extends TextKeyListener {
private boolean mHadAddedSpan;
public MockTextKeyListener(Capitalize cap, boolean autotext) {
super(cap, autotext);
}
@Override
public void onSpanAdded(Spannable s, Object what, int start, int end) {
mHadAddedSpan = true;
super.onSpanAdded(s, what, start, end);
}
public boolean hadAddedSpan() {
return mHadAddedSpan;
}
}
}
|
3e09a677545bbccee348ff44a56c89e239ef7ba2 | 11,261 | java | Java | src/logisim_src/file/LogisimFile.java | HoussemNasri/Logisim-Dark | a8b22309a0ab609e92c3b2297573e60d536508bd | [
"MIT"
] | 5 | 2021-05-09T05:23:30.000Z | 2022-02-21T13:27:49.000Z | src/logisim_src/file/LogisimFile.java | HoussemNasri/Logisim-Dark | a8b22309a0ab609e92c3b2297573e60d536508bd | [
"MIT"
] | 7 | 2021-03-27T04:40:58.000Z | 2022-01-15T19:35:32.000Z | src/logisim_src/file/LogisimFile.java | HoussemNasri/Logisim-Dark | a8b22309a0ab609e92c3b2297573e60d536508bd | [
"MIT"
] | 4 | 2021-03-27T05:30:34.000Z | 2021-03-27T20:19:54.000Z | 25.535147 | 77 | 0.698872 | 4,069 | /* Copyright (c) 2010, Carl Burch. License information is located in the
* logisim_src.Main source code and at www.cburch.com/logisim/. */
package logisim_src.file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.SAXException;
import logisim_src.circuit.Circuit;
import logisim_src.circuit.SubcircuitFactory;
import logisim_src.comp.Component;
import logisim_src.comp.ComponentFactory;
import logisim_src.proj.Projects;
import logisim_src.tools.AddTool;
import logisim_src.tools.Library;
import logisim_src.tools.Tool;
import logisim_src.util.EventSourceWeakSupport;
import logisim_src.util.ListUtil;
import logisim_src.util.StringUtil;
public class LogisimFile extends Library implements LibraryEventSource {
private static class WritingThread extends Thread {
OutputStream out;
LogisimFile file;
WritingThread(OutputStream out, LogisimFile file) {
this.out = out;
this.file = file;
}
@Override
public void run() {
try {
file.write(out, file.loader);
} catch (IOException e) {
file.loader.showError(StringUtil.format(
Strings.get("fileDuplicateError"), e.toString()));
}
try {
out.close();
} catch (IOException e) {
file.loader.showError(StringUtil.format(
Strings.get("fileDuplicateError"), e.toString()));
}
}
}
private EventSourceWeakSupport<LibraryListener> listeners
= new EventSourceWeakSupport<LibraryListener>();
private Loader loader;
private LinkedList<String> messages = new LinkedList<String>();
private Options options = new Options();
private LinkedList<AddTool> tools = new LinkedList<AddTool>();
private LinkedList<Library> libraries = new LinkedList<Library>();
private Circuit main = null;
private String name;
private boolean dirty = false;
LogisimFile(Loader loader) {
this.loader = loader;
name = Strings.get("defaultProjectName");
if (Projects.windowNamed(name)) {
for (int i = 2; true; i++) {
if (!Projects.windowNamed(name + " " + i)) {
name += " " + i;
break;
}
}
}
}
//
// access methods
//
@Override
public String getName() { return name; }
@Override
public boolean isDirty() { return dirty; }
public String getMessage() {
if (messages.size() == 0) return null;
return messages.removeFirst();
}
public Loader getLoader() {
return loader;
}
public Options getOptions() {
return options;
}
@Override
public List<AddTool> getTools() {
return tools;
}
@Override
public List<Library> getLibraries() {
return libraries;
}
@Override
public List<?> getElements() {
return ListUtil.joinImmutableLists(tools, libraries);
}
public Circuit getCircuit(String name) {
if (name == null) return null;
for (AddTool tool : tools) {
SubcircuitFactory factory = (SubcircuitFactory) tool.getFactory();
if (name.equals(factory.getName())) return factory.getSubcircuit();
}
return null;
}
public boolean contains(Circuit circ) {
for (AddTool tool : tools) {
SubcircuitFactory factory = (SubcircuitFactory) tool.getFactory();
if (factory.getSubcircuit() == circ) return true;
}
return false;
}
public List<Circuit> getCircuits() {
List<Circuit> ret = new ArrayList<Circuit>(tools.size());
for (AddTool tool : tools) {
SubcircuitFactory factory = (SubcircuitFactory) tool.getFactory();
ret.add(factory.getSubcircuit());
}
return ret;
}
public AddTool getAddTool(Circuit circ) {
for (AddTool tool : tools) {
SubcircuitFactory factory = (SubcircuitFactory) tool.getFactory();
if (factory.getSubcircuit() == circ) {
return tool;
}
}
return null;
}
public Circuit getMainCircuit() {
return main;
}
public int getCircuitCount() {
return tools.size();
}
//
// listener methods
//
public void addLibraryListener(LibraryListener what) {
listeners.add(what);
}
public void removeLibraryListener(LibraryListener what) {
listeners.remove(what);
}
private void fireEvent(int action, Object data) {
LibraryEvent e = new LibraryEvent(this, action, data);
for (LibraryListener l : listeners) {
l.libraryChanged(e);
}
}
//
// modification actions
//
public void addMessage(String msg) {
messages.addLast(msg);
}
public void setDirty(boolean value) {
if (dirty != value) {
dirty = value;
fireEvent(LibraryEvent.DIRTY_STATE, value ? Boolean.TRUE : Boolean.FALSE);
}
}
public void setName(String name) {
this.name = name;
fireEvent(LibraryEvent.SET_NAME, name);
}
public void addCircuit(Circuit circuit) {
addCircuit(circuit, tools.size());
}
public void addCircuit(Circuit circuit, int index) {
AddTool tool = new AddTool(circuit.getSubcircuitFactory());
tools.add(index, tool);
if (tools.size() == 1) setMainCircuit(circuit);
fireEvent(LibraryEvent.ADD_TOOL, tool);
}
public void removeCircuit(Circuit circuit) {
if (tools.size() <= 1) {
throw new RuntimeException("Cannot remove last circuit");
}
int index = getCircuits().indexOf(circuit);
if (index >= 0) {
Tool circuitTool = tools.remove(index);
if (main == circuit) {
AddTool dflt_tool = tools.get(0);
SubcircuitFactory factory = (SubcircuitFactory) dflt_tool.getFactory();
setMainCircuit(factory.getSubcircuit());
}
fireEvent(LibraryEvent.REMOVE_TOOL, circuitTool);
}
}
public void moveCircuit(AddTool tool, int index) {
int oldIndex = tools.indexOf(tool);
if (oldIndex < 0) {
tools.add(index, tool);
fireEvent(LibraryEvent.ADD_TOOL, tool);
} else {
AddTool value = tools.remove(oldIndex);
tools.add(index, value);
fireEvent(LibraryEvent.MOVE_TOOL, tool);
}
}
public void addLibrary(Library lib) {
libraries.add(lib);
fireEvent(LibraryEvent.ADD_LIBRARY, lib);
}
public void removeLibrary(Library lib) {
libraries.remove(lib);
fireEvent(LibraryEvent.REMOVE_LIBRARY, lib);
}
public String getUnloadLibraryMessage(Library lib) {
HashSet<ComponentFactory> factories = new HashSet<ComponentFactory>();
for (Tool tool : lib.getTools()) {
if (tool instanceof AddTool) {
factories.add(((AddTool) tool).getFactory());
}
}
for (Circuit circuit : getCircuits()) {
for (Component comp : circuit.getNonWires()) {
if (factories.contains(comp.getFactory())) {
return StringUtil.format(Strings.get("unloadUsedError"),
circuit.getName());
}
}
}
ToolbarData tb = options.getToolbarData();
MouseMappings mm = options.getMouseMappings();
for (Tool t : lib.getTools()) {
if (tb.usesToolFromSource(t)) {
return Strings.get("unloadToolbarError");
}
if (mm.usesToolFromSource(t)) {
return Strings.get("unloadMappingError");
}
}
return null;
}
public void setMainCircuit(Circuit circuit) {
if (circuit == null) return;
this.main = circuit;
fireEvent(LibraryEvent.SET_MAIN, circuit);
}
//
// other methods
//
void write(OutputStream out, LibraryLoader loader) throws IOException {
try {
XmlWriter.write(this, out, loader);
} catch (TransformerConfigurationException e) {
loader.showError("internal error configuring transformer");
} catch (ParserConfigurationException e) {
loader.showError("internal error configuring parser");
} catch (TransformerException e) {
String msg = e.getMessage();
String err = Strings.get("xmlConversionError");
if (msg == null) err += ": " + msg;
loader.showError(err);
}
}
public LogisimFile cloneLogisimFile(Loader newloader) {
PipedInputStream reader = new PipedInputStream();
PipedOutputStream writer = new PipedOutputStream();
try {
reader.connect(writer);
} catch (IOException e) {
newloader.showError(StringUtil.format(
Strings.get("fileDuplicateError"), e.toString()));
return null;
}
new WritingThread(writer, this).start();
try {
return LogisimFile.load(reader, newloader);
} catch (IOException e) {
newloader.showError(StringUtil.format(
Strings.get("fileDuplicateError"), e.toString()));
return null;
}
}
Tool findTool(Tool query) {
for (Library lib : getLibraries()) {
Tool ret = findTool(lib, query);
if (ret != null) return ret;
}
return null;
}
private Tool findTool(Library lib, Tool query) {
for (Tool tool : lib.getTools()) {
if (tool.equals(query)) return tool;
}
return null;
}
//
// creation methods
//
public static LogisimFile createNew(Loader loader) {
LogisimFile ret = new LogisimFile(loader);
ret.main = new Circuit("main");
// The name will be changed in LogisimPreferences
ret.tools.add(new AddTool(ret.main.getSubcircuitFactory()));
return ret;
}
public static LogisimFile load(File file, Loader loader)
throws IOException {
InputStream in = new FileInputStream(file);
SAXException firstExcept = null;
try {
return loadSub(in, loader);
} catch (SAXException e) {
firstExcept = e;
} finally {
in.close();
}
if (firstExcept != null) {
// We'll now try to do it using a reader. This is to work around
// Logisim versions prior to 2.5.1, when files were not saved using
// UTF-8 as the encoding (though the XML file reported otherwise).
try {
in = new ReaderInputStream(new FileReader(file), "UTF8");
return loadSub(in, loader);
} catch (Throwable t) {
loader.showError(StringUtil.format(
Strings.get("xmlFormatError"), firstExcept.toString()));
} finally {
try {
in.close();
} catch (Throwable t) { }
}
}
return null;
}
public static LogisimFile load(InputStream in, Loader loader)
throws IOException {
try {
return loadSub(in, loader);
} catch (SAXException e) {
loader.showError(StringUtil.format(
Strings.get("xmlFormatError"), e.toString()));
return null;
}
}
public static LogisimFile loadSub(InputStream in, Loader loader)
throws IOException, SAXException {
// fetch first line and then reset
BufferedInputStream inBuffered = new BufferedInputStream(in);
String firstLine = getFirstLine(inBuffered);
if (firstLine == null) {
throw new IOException("File is empty");
} else if (firstLine.equals("Logisim v1.0")) {
// if this is a 1.0 file, then set up a pipe to translate to
// 2.0 and then interpret as a 2.0 file
throw new IOException("Version 1.0 files no longer supported");
}
XmlReader xmlReader = new XmlReader(loader);
LogisimFile ret = xmlReader.readLibrary(inBuffered);
ret.loader = loader;
return ret;
}
private static String getFirstLine(BufferedInputStream in)
throws IOException {
byte[] first = new byte[512];
in.mark(first.length - 1);
in.read(first);
in.reset();
int lineBreak = first.length;
for (int i = 0; i < lineBreak; i++) {
if (first[i] == '\n') {
lineBreak = i;
}
}
return new String(first, 0, lineBreak, "UTF-8");
}
}
|
3e09a693a04b031a80610d0d813ad5c7f8f1c104 | 478 | java | Java | gulimall-order/src/main/java/com/guo/gulimall/order/service/OrderOperateHistoryService.java | CheneyKwok/gulimall | 37d7b608ecfbba7df577184af4cb0687ef3c7903 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/guo/gulimall/order/service/OrderOperateHistoryService.java | CheneyKwok/gulimall | 37d7b608ecfbba7df577184af4cb0687ef3c7903 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/guo/gulimall/order/service/OrderOperateHistoryService.java | CheneyKwok/gulimall | 37d7b608ecfbba7df577184af4cb0687ef3c7903 | [
"Apache-2.0"
] | null | null | null | 22.952381 | 89 | 0.782158 | 4,070 | package com.guo.gulimall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.guo.common.utils.PageUtils;
import com.guo.gulimall.order.entity.OrderOperateHistoryEntity;
import java.util.Map;
/**
* 订单操作历史记录
*
* @author guozhicheng
* @email ychag@example.com
* @date 2020-12-26 17:21:34
*/
public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
3e09a6b492e59f06561a43cdcb58d51c5f83b9df | 2,084 | java | Java | src/cropcert/user/service/AbstractService.java | strandls/cropcert-users | de4a08b38db8420fcb886109d4a1fcd7632ffd83 | [
"Apache-2.0"
] | null | null | null | src/cropcert/user/service/AbstractService.java | strandls/cropcert-users | de4a08b38db8420fcb886109d4a1fcd7632ffd83 | [
"Apache-2.0"
] | 6 | 2019-11-13T11:31:05.000Z | 2022-02-16T00:56:04.000Z | src/cropcert/user/service/AbstractService.java | strandls/cropcert-users | de4a08b38db8420fcb886109d4a1fcd7632ffd83 | [
"Apache-2.0"
] | 2 | 2019-08-19T11:03:39.000Z | 2021-04-23T15:55:54.000Z | 22.901099 | 131 | 0.698656 | 4,071 | package cropcert.user.service;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import cropcert.user.dao.AbstractDao;
public abstract class AbstractService<T> {
public Class<T> entityClass;
protected AbstractDao<T, Long> dao;
@SuppressWarnings("unchecked")
public AbstractService(AbstractDao<T, Long> dao) {
System.out.println("\nAbstractService constructor");
this.dao = dao;
entityClass = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
public T save(T entity) {
try {
this.dao.save(entity);
return entity;
} catch (RuntimeException re) {
throw re;
}
}
public T update(T entity) {
try {
this.dao.update(entity);
return entity;
} catch (RuntimeException re) {
throw re;
}
}
public T delete(Long id) {
try {
T entity = (T) this.dao.findById(id);
this.dao.delete(entity);
return entity;
} catch (RuntimeException re) {
throw re;
}
}
public T findById(Long id) {
try {
T entity = (T) this.dao.findById(id);
return entity;
} catch (RuntimeException re) {
throw re;
}
}
public List<T> findAll(int limit, int offset) {
try {
List<T> entities = this.dao.findAll(limit, offset);
return entities;
} catch (RuntimeException re) {
throw re;
}
}
public List<T> findAll() {
try {
List<T> entities = this.dao.findAll();
return entities;
} catch (RuntimeException re) {
throw re;
}
}
public T findByPropertyWithCondition(String property, Object value, String condition) {
return dao.findByPropertyWithCondition(property, value, condition);
}
public List<T> getByPropertyWithCondtion(String property, Object value, String condition, int limit, int offset, String orderBy) {
return dao.getByPropertyWithCondtion(property, value, condition, limit, offset, orderBy);
}
public List<T> getByMultiplePropertyWithCondtion(String[] properties, Object[] values, Integer limit,
Integer offset) {
return dao.getByMultiplePropertyWithCondtion(properties, values, limit, offset);
}
}
|
3e09a70647c3516916552c3013defd3396345800 | 1,064 | java | Java | src/main/java/org/springframework/data/semantic/support/model/SemanticResource.java | meditos/spring-data-semantic | 984caa912afef013366a2afde2ff456d4385af3d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/springframework/data/semantic/support/model/SemanticResource.java | meditos/spring-data-semantic | 984caa912afef013366a2afde2ff456d4385af3d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/springframework/data/semantic/support/model/SemanticResource.java | meditos/spring-data-semantic | 984caa912afef013366a2afde2ff456d4385af3d | [
"Apache-2.0"
] | 1 | 2020-11-26T22:11:26.000Z | 2020-11-26T22:11:26.000Z | 27.282051 | 76 | 0.716165 | 4,072 | /**
* Copyright (C) 2014 Ontotext AD (ychag@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.semantic.support.model;
import org.eclipse.rdf4j.model.IRI;
import org.springframework.data.semantic.annotation.ResourceId;
import org.springframework.data.semantic.annotation.SemanticEntity;
@SemanticEntity
public class SemanticResource {
@ResourceId
private IRI id;
public IRI getId() {
return id;
}
public void setId(IRI id) {
this.id = id;
}
}
|
3e09a797270305a45488c237dab1a3ffeabfb39b | 22,196 | java | Java | redis/redis-integration-test/src/test/java/com/ctrip/xpipe/redis/integratedtest/console/AbstractXPipeClusterTest.java | z131031231/x-pipe | b175922e3cd4fb77bad4f821c9cf7f7c4e67731e | [
"Apache-2.0"
] | 1,652 | 2016-04-18T10:34:30.000Z | 2022-03-30T06:15:35.000Z | redis/redis-integration-test/src/test/java/com/ctrip/xpipe/redis/integratedtest/console/AbstractXPipeClusterTest.java | jiao-duan/x-pipe | b31d9712a0db529f854716e777d70db9bd220938 | [
"Apache-2.0"
] | 342 | 2016-07-27T10:38:01.000Z | 2022-03-31T11:11:46.000Z | redis/redis-integration-test/src/test/java/com/ctrip/xpipe/redis/integratedtest/console/AbstractXPipeClusterTest.java | jiao-duan/x-pipe | b31d9712a0db529f854716e777d70db9bd220938 | [
"Apache-2.0"
] | 492 | 2016-04-25T05:14:10.000Z | 2022-03-16T01:40:38.000Z | 45.577002 | 167 | 0.640971 | 4,073 | package com.ctrip.xpipe.redis.integratedtest.console;
import com.ctrip.xpipe.api.migration.auto.data.MonitorGroupMeta;
import com.ctrip.xpipe.api.server.Server;
import com.ctrip.xpipe.codec.JsonCodec;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.redis.console.AbstractConsoleDbTest;
import com.ctrip.xpipe.redis.console.controller.api.migrate.meta.*;
import com.ctrip.xpipe.redis.checker.healthcheck.HealthChecker;
import com.ctrip.xpipe.redis.checker.healthcheck.HealthChecker;
import com.ctrip.xpipe.redis.console.AbstractConsoleDbTest;
import com.ctrip.xpipe.redis.console.controller.api.migrate.meta.CheckPrepareRequest;
import com.ctrip.xpipe.redis.console.controller.api.migrate.meta.CheckPrepareResponse;
import com.ctrip.xpipe.redis.console.controller.api.migrate.meta.DoRequest;
import com.ctrip.xpipe.redis.console.controller.api.migrate.meta.DoResponse;
import com.ctrip.xpipe.redis.core.meta.DcInfo;
import com.ctrip.xpipe.redis.core.protocal.cmd.RoleCommand;
import com.ctrip.xpipe.redis.core.protocal.pojo.Role;
import com.ctrip.xpipe.redis.integratedtest.console.app.ConsoleApp;
import com.ctrip.xpipe.redis.integratedtest.console.app.MetaserverApp;
import com.ctrip.xpipe.redis.integratedtest.console.app.ProxyApp;
import com.ctrip.xpipe.redis.integratedtest.console.cmd.CrdtRedisStartCmd;
import com.ctrip.xpipe.redis.integratedtest.console.cmd.RedisKillCmd;
import com.ctrip.xpipe.redis.integratedtest.console.cmd.RedisStartCmd;
import com.ctrip.xpipe.redis.integratedtest.console.cmd.ServerStartCmd;
import com.ctrip.xpipe.redis.keeper.KeeperContainerApplication;
import com.ctrip.xpipe.redis.meta.server.config.DefaultMetaServerConfig;
import com.ctrip.xpipe.spring.AbstractProfile;
import com.ctrip.xpipe.spring.RestTemplateFactory;
import com.ctrip.xpipe.utils.FileUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.springframework.web.client.RestOperations;
import java.io.File;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import static com.ctrip.xpipe.foundation.DefaultFoundationService.DATA_CENTER_KEY;
import static com.ctrip.xpipe.redis.checker.cluster.GroupCheckerLeaderElector.KEY_CHECKER_ID;
import static com.ctrip.xpipe.redis.checker.config.CheckerConfig.KEY_CHECKER_META_REFRESH_INTERVAL;
import static com.ctrip.xpipe.redis.checker.config.CheckerConfig.KEY_SENTINEL_CHECK_INTERVAL;
import static com.ctrip.xpipe.redis.checker.spring.ConsoleServerModeCondition.KEY_SERVER_MODE;
import static com.ctrip.xpipe.redis.checker.spring.ConsoleServerModeCondition.SERVER_MODE.CHECKER;
import static com.ctrip.xpipe.redis.checker.spring.ConsoleServerModeCondition.SERVER_MODE.CONSOLE;
import static com.ctrip.xpipe.redis.console.cluster.ConsoleLeaderElector.KEY_CONSOLE_ID;
import static com.ctrip.xpipe.redis.console.config.impl.DefaultConsoleConfig.KEY_METASERVERS;
import static com.ctrip.xpipe.redis.console.service.meta.BeaconMetaService.BEACON_GROUP_SEPARATOR;
import static com.ctrip.xpipe.redis.core.config.AbstractCoreConfig.KEY_ZK_ADDRESS;
import static com.ctrip.xpipe.redis.keeper.config.DefaultKeeperConfig.KEY_REPLICATION_STORE_COMMANDFILE_SIZE;
import static com.ctrip.xpipe.redis.keeper.config.DefaultKeeperConfig.KEY_REPLICATION_STORE_MAX_COMMANDS_TO_TRANSFER_BEFORE_CREATE_RDB;
import static com.ctrip.xpipe.redis.keeper.config.DefaultKeeperContainerConfig.REPLICATION_STORE_DIR;
import static com.ctrip.xpipe.redis.meta.server.config.DefaultMetaServerConfig.KEY_CONSOLE_ADDRESS;
/**
* @author lishanglin
* date 2021/2/3
*/
public abstract class AbstractXPipeClusterTest extends AbstractConsoleDbTest {
protected RestOperations restTemplate;
private List<ForkProcessCmd> subProcessCmds;
private List<Integer> redisPorts;
private static int h2Port = 9123;
private static org.h2.tools.Server h2Server;
@BeforeClass
public static void setupAbstractXPipeClusterTest() throws Exception {
h2Server = org.h2.tools.Server.createTcpServer("-tcpPort", String.valueOf(h2Port), "-tcpAllowOthers");
h2Server.start();
}
@AfterClass
public static void afterAbstractXPipeClusterTest() throws Exception {
if (null != h2Server) {
h2Server.shutdown();
h2Server.stop();
}
}
@Override
public void before() throws Exception {
restTemplate = RestTemplateFactory.createRestTemplate();
subProcessCmds = new ArrayList<>();
redisPorts = new ArrayList<>();
}
protected RedisStartCmd startRedis(int port) {
RedisStartCmd redis = new RedisStartCmd(port, executors);
redis.execute(executors).addListener(redisFuture -> {
if (redisFuture.isSuccess()) {
logger.info("[startRedis] redis{} end {}", port, redisFuture.get());
} else {
logger.info("[startRedis] redis{} fail", port, redisFuture.cause());
}
});
redisPorts.add(port);
subProcessCmds.add(redis);
return redis;
}
protected RedisStartCmd startCrdtRedis(int gid, int port) {
RedisStartCmd redis = new CrdtRedisStartCmd(gid, port, executors);
redis.execute(executors).addListener(redisFuture -> {
if (redisFuture.isSuccess()) {
logger.info("[startRedis] redis{} end {}", port, redisFuture.get());
} else {
logger.info("[startRedis] redis{} fail", port, redisFuture.cause());
}
});
redisPorts.add(port);
subProcessCmds.add(redis);
return redis;
}
protected RedisStartCmd startSentinel(int port) {
RedisStartCmd redis = new RedisStartCmd(port, true, executors);
redis.execute(executors).addListener(redisFuture -> {
if (redisFuture.isSuccess()) {
logger.info("[startSentinel] sentinel{} end {}", port, redisFuture.get());
} else {
logger.info("[startSentinel] sentinel{} fail", port, redisFuture.cause());
}
});
redisPorts.add(port);
subProcessCmds.add(redis);
return redis;
}
protected ServerStartCmd startChecker(int port, String idc, String zk, List<String> localDcConsoles) {
return startConsole(port, idc, zk,
localDcConsoles, Collections.emptyMap(),
Collections.emptyMap(),
new HashMap<String, String>() {{
put(KEY_CONSOLE_ADDRESS, "http://" + localDcConsoles.get(0));
put(KEY_CHECKER_ID, idc + port);
put(KEY_SERVER_MODE, CHECKER.name());
}});
}
protected ServerStartCmd startStandaloneConsole(int port, String idc, String zk,
List<String> localDcConsoles, Map<String, String> crossDcConsole,
Map<String, String> metaservers) {
return startConsole(port, idc, zk,
localDcConsoles, crossDcConsole,
metaservers,
new HashMap<String, String>() {{
put(KEY_CONSOLE_ID, idc + port);
put(KEY_SERVER_MODE, CONSOLE.name());
}});
}
protected ServerStartCmd startConsole(int port, String idc, String zk, List<String> localDcConsoles,
Map<String, String> crossDcConsoles, Map<String, String> metaservers) {
return startConsole(port, idc, zk, localDcConsoles, crossDcConsoles, metaservers, Collections.emptyMap());
}
protected ServerStartCmd startConsole(int port, String idc, String zk, List<String> localDcConsoles,
Map<String, String> crossDcConsoles, Map<String, String> metaservers,
Map<String, String> extras) {
ServerStartCmd consoleServer = new ServerStartCmd(idc + port, ConsoleApp.class.getName(), new HashMap<String, String>() {{
put(HealthChecker.ENABLED, "true");
put("server.port", String.valueOf(port));
put("cat.client.enabled", "false");
put("spring.profiles.active", AbstractProfile.PROFILE_NAME_PRODUCTION);
put(DATA_CENTER_KEY, idc);
put(KEY_ZK_ADDRESS, zk);
put(KEY_METASERVERS, JsonCodec.INSTANCE.encode(metaservers));
put("console.domains", JsonCodec.INSTANCE.encode(crossDcConsoles));
put("console.all.addresses", String.join(",", localDcConsoles));
put(KEY_CHECKER_META_REFRESH_INTERVAL, "2000");
put(KEY_SENTINEL_CHECK_INTERVAL, "15000");
putAll(extras);
}}, executors);
consoleServer.execute(executors).addListener(consoleFuture -> {
if (consoleFuture.isSuccess()) {
logger.info("[startConsoleJQ] console {}-{} end {}", idc, port, consoleFuture.get());
} else {
logger.info("[startConsoleJQ] console {}-{} fail", idc, port, consoleFuture.cause());
}
});
subProcessCmds.add(consoleServer);
return consoleServer;
}
protected ServerStartCmd startMetaServer(String idc, String console, String zk, int port, Map<String, DcInfo> dcInfos) {
ServerStartCmd metaserver = new ServerStartCmd(idc + port, MetaserverApp.class.getName(), new HashMap<String, String>() {{
put("server.port", String.valueOf(port));
put("cat.client.enabled", "false");
put("spring.profiles.active", AbstractProfile.PROFILE_NAME_PRODUCTION);
put("meta.cluster.types", "one_way,bi_direction,ONE_WAY,BI_DIRECTION");
put(DATA_CENTER_KEY, idc);
put(KEY_CONSOLE_ADDRESS, console);
put(KEY_ZK_ADDRESS, zk);
put(DefaultMetaServerConfig.KEY_DC_INFOS, JsonCodec.INSTANCE.encode(dcInfos));
}}, executors);
metaserver.execute(executors).addListener(metaserverFuture -> {
if (metaserverFuture.isSuccess()) {
logger.info("[startMetaServer] metaserver {}-{} end {}", idc, port, metaserverFuture.get());
} else {
logger.info("[startMetaServer] metaserver {}-{} fail", idc, port, metaserverFuture.cause());
}
});
subProcessCmds.add(metaserver);
return metaserver;
}
protected ServerStartCmd startKeepercontainer(String idc, String zk, int port, String storeDir) {
ServerStartCmd keepercontainer = new ServerStartCmd(idc + port, KeeperContainerApplication.class.getName(), new HashMap<String, String>() {{
put("server.port", String.valueOf(port));
put("cat.client.enabled", "false");
put("spring.profiles.active", AbstractProfile.PROFILE_NAME_PRODUCTION);
put(DATA_CENTER_KEY, idc);
put(KEY_ZK_ADDRESS, zk);
put(REPLICATION_STORE_DIR, storeDir);
put(KEY_REPLICATION_STORE_COMMANDFILE_SIZE, "104857600");
put(KEY_REPLICATION_STORE_MAX_COMMANDS_TO_TRANSFER_BEFORE_CREATE_RDB, "524288000");
}}, executors);
keepercontainer.execute(executors).addListener(keepercontainerFuture -> {
if (keepercontainerFuture.isSuccess()) {
logger.info("[startKeepercontainer] metaserver {}-{} end {}", idc, port, keepercontainerFuture.get());
} else {
logger.info("[startKeepercontainer] metaserver {}-{} fail", idc, port, keepercontainerFuture.cause());
}
});
subProcessCmds.add(keepercontainer);
return keepercontainer;
}
protected void tryMigration(String console, String cluster, String src, String dest) {
long ticketId = tryPrepareMigration(console, cluster, src, dest);
tryDoMigration(console, ticketId);
}
protected long tryPrepareMigration(String console, String cluster, String src, String dest) {
CheckPrepareRequest prepareRequest = new CheckPrepareRequest();
prepareRequest.setClusters(Collections.singletonList(cluster));
prepareRequest.setFromIdc(src);
prepareRequest.setToIdc(dest);
prepareRequest.setIsForce(false);
CheckPrepareResponse prepareResp = restTemplate.postForObject(console + "/api/migration/checkandprepare", prepareRequest, CheckPrepareResponse.class);
if (!prepareResp.getResults().get(0).isSuccess()) {
logger.info("[tryPrepareMigration][{}][{}] {}->{}: {}", console, cluster, src, dest, prepareResp);
Assert.fail("migration prepare fail " + prepareResp.getResults().get(0).getFailReason());
}
return prepareResp.getTicketId();
}
protected void tryDoMigration(String console, long ticketId) {
DoRequest doRequest = new DoRequest();
doRequest.setTicketId(ticketId);
DoResponse doResp = restTemplate.postForObject(console + "/api/migration/domigration", doRequest, DoResponse.class);
if (!doResp.isSuccess()) {
logger.info("[tryDoMigration][{}][{}] {}", console, ticketId, doResp);
Assert.fail("do migration fail " + doResp.getMsg());
}
}
protected void tryBeaconAutoMigration(String console, String cluster, Set<MonitorGroupMeta> groups, Set<String> failDcs) {
BeaconMigrationRequest migrationReq = new BeaconMigrationRequest();
migrationReq.setClusterName(cluster);
migrationReq.setFailoverGroups(failDcs);
migrationReq.setGroups(groups);
BeaconMigrationResponse migrationResp = restTemplate.postForObject(console + "/api/beacon/migration/sync", migrationReq, BeaconMigrationResponse.class);
if (!migrationResp.isSuccess()) {
logger.info("[tryBeaconForceMigration][{}][{}] {}, {}", console, cluster, migrationReq, migrationResp);
Assert.fail("do migration fail " + migrationResp.getMsg());
}
}
protected Set<MonitorGroupMeta> buildMonitorMeta(Map<String, Map<String, Set<HostPort>>> meta, String activeDc) {
Set<MonitorGroupMeta> monitorMeta = new HashSet<>();
meta.forEach((dc, groupMeta) -> {
groupMeta.forEach((groupName, nodes) -> {
MonitorGroupMeta monitorGroupMeta = new MonitorGroupMeta(String.join(BEACON_GROUP_SEPARATOR, groupName, dc), dc, nodes, activeDc.equalsIgnoreCase(dc));
monitorGroupMeta.setDown(activeDc.equalsIgnoreCase(dc));
monitorMeta.add(monitorGroupMeta);
});
});
return monitorMeta;
}
protected void tryBeaconForceMigration(String console, String cluster, String dest) {
BeaconMigrationRequest migrationReq = new BeaconMigrationRequest();
migrationReq.setClusterName(cluster);
migrationReq.setIsForced(true);
migrationReq.setTargetIDC(dest);
BeaconMigrationResponse migrationResp = restTemplate.postForObject(console + "/api/beacon/migration/sync", migrationReq, BeaconMigrationResponse.class);
if (!migrationResp.isSuccess()) {
logger.info("[tryBeaconForceMigration][{}][{}] to {}, {}", console, cluster, dest, migrationResp);
Assert.fail("do migration fail " + migrationResp.getMsg());
}
}
/* --------- wait condition --------- */
protected void waitForServerAck(String healthUrl, Class<?> respType, int waitTimeMilli) throws Exception {
waitConditionUntilTimeOut(() -> {
try {
Object resp = restTemplate.getForObject(healthUrl, respType);
logger.info("[waitForServerAck] resp for {}, {}", healthUrl, resp);
return true;
} catch (Throwable th) {
logger.info("[waitForServerAck] {} fail", healthUrl, th);
return false;
}
}, waitTimeMilli, 2000);
}
protected void waitForServerResp(String healthUrl, Class<?> respType, int waitTimeMilli, Predicate<Object> predicate) throws Exception {
waitConditionUntilTimeOut(() -> {
try {
Object resp = restTemplate.getForObject(healthUrl, respType);
logger.info("[waitForServerRespAsExpected] resp for {}, {}", healthUrl, resp);
return predicate.test(resp);
} catch (Throwable th) {
return false;
}
}, waitTimeMilli, 2000);
}
protected void waitForServerRespAsExpected(String healthUrl, Class<?> respType, Object expected, int waitTimeMilli) throws Exception {
waitConditionUntilTimeOut(() -> {
try {
Object resp = restTemplate.getForObject(healthUrl, respType);
logger.info("[waitForServerRespAsExpected] resp for {}, {}", healthUrl, resp);
return expected.equals(resp);
} catch (Throwable th) {
return false;
}
}, waitTimeMilli, 2000);
}
protected void waitForRedisRole(String host, int port, Server.SERVER_ROLE expected, int waitTimeMilli) throws Exception {
waitConditionUntilTimeOut(() -> {
try {
Role current = new RoleCommand(host, port, scheduled).execute().get();
logger.info("[waitForRedisRole][{}][{}] current role {}", host, port, current);
return current.getServerRole().equals(expected);
} catch (Throwable th) {
logger.info("[waitForRedisRole][{}][{}] role cmd fail", host, port, th);
return false;
}
}, waitTimeMilli, 2000);
}
/* --------- cleanup --------- */
protected boolean stopServer(ForkProcessCmd server) throws TimeoutException {
if (subProcessCmds.remove(server)) {
server.killProcess();
waitConditionUntilTimeOut(() -> !server.isProcessAlive(), 5000, 100);
return true;
}
return false;
}
protected void cleanupKeeper() {
String userDir = System.getProperty("user.dir");
IntStream.of(7080, 7081, 7082, 7180, 7181, 7182).forEach(port -> {
File dir = new File(userDir + "/src/test/tmp/keepercontainer" + port);
if (dir.exists()) {
try {
FileUtils.recursiveDelete(dir);
} catch (Throwable th) {
logger.info("[cleanupKeeper][{}] delete dir fail", port, th);
}
} else {
logger.info("[cleanupKeeper][{}] no rsd dir {}", port, dir.getAbsolutePath());
}
});
}
protected void cleanupRDB() {
String userDir = System.getProperty("user.dir");
IntStream.of(6379, 7379).forEach(port -> {
File rdb = new File(userDir + "/src/test/tmp/dump" + port + ".rdb");
try {
if (rdb.exists()) rdb.delete();
else logger.info("[cleanupRDB][{}] no rdb {}", port, rdb.getAbsolutePath());
} catch (Throwable th) {
logger.info("[cleanupRDB][{}] delete rdb fail", port, th);
}
});
}
protected void cleanupConf() {
String userDir = System.getProperty("user.dir");
// TODO: override conf to be clean in sub-class
IntStream.of(36379, 36380, 37379, 37380, 38379, 38380, 6379, 7379, 5000, 5001, 5002, 17170, 17171, 17172).forEach(port -> {
File conf = new File(userDir + "/src/test/tmp/redis" + port + ".conf");
try {
if (conf.exists()) conf.delete();
else logger.info("[cleanupConf][{}] no conf {}", port, conf.getAbsolutePath());
} catch (Throwable th) {
logger.info("[cleanupConf][{}] delete conf fail", port, th);
}
});
}
protected void cleanupAllSubProcesses() {
for (ForkProcessCmd subProcess: subProcessCmds) {
try {
logger.info("[cleanupSubProcesses][{}]", subProcess);
subProcess.killProcess();
waitConditionUntilTimeOut(() -> !subProcess.isProcessAlive(), 5000, 100);
} catch (Throwable th) {
logger.info("[cleanupSubProcesses][{}] kill thread fail", subProcess, th);
}
}
}
protected boolean isAllProcessAlive() {
for (ForkProcessCmd subProcess: subProcessCmds) {
logger.info("[checkAllProcessAlive][{}]", subProcess);
if (!subProcess.isProcessAlive()) {
return false;
}
}
return true;
}
protected void checkAllProcessAlive() {
for (ForkProcessCmd subProcess: subProcessCmds) {
logger.info("[checkAllProcessAlive][{}]", subProcess);
if (!subProcess.isProcessAlive()) {
throw new IllegalStateException("sub process " + subProcess + " is down");
}
}
}
protected void killAllRedisServers() {
redisPorts.forEach(port -> {
try {
new RedisKillCmd(port, executors).execute().get();
} catch (Throwable th) {
logger.info("[killRedisServers][{}] fail", port, th);
}
});
}
public ServerStartCmd startProxy(String idc, int tcpPort, int tlsPort) {
ServerStartCmd proxyServer = new ServerStartCmd(idc + tcpPort + "-" + tlsPort, ProxyApp.class.getName(), new HashMap<String, String>() {{
put("tcp_port", String.valueOf(tcpPort));
put("tls_port", String.valueOf(tlsPort));
}}, executors);
proxyServer.execute(executors).addListener(consoleFuture -> {
if (consoleFuture.isSuccess()) {
logger.info("[proxyServer] proxyserver {}-{}-{} start {}", idc, tcpPort, tlsPort, consoleFuture.get());
} else {
logger.info("[proxyServer] proxyserver {}-{}-{} fail", idc, tcpPort, tlsPort, consoleFuture.cause());
}
});
subProcessCmds.add(proxyServer);
return proxyServer;
}
}
|
3e09a95554025537a4337af9c50c4d9aa2f064aa | 2,823 | java | Java | src/main/java/com/supervise/core/data/out/RecourseOutport.java | umindow/finance | 4e6918e4a3ee267328e3f01a31b16ea08086865d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/supervise/core/data/out/RecourseOutport.java | umindow/finance | 4e6918e4a3ee267328e3f01a31b16ea08086865d | [
"Apache-2.0"
] | 1 | 2018-02-01T14:44:59.000Z | 2018-02-05T15:17:07.000Z | src/main/java/com/supervise/core/data/out/RecourseOutport.java | umindow/finance | 4e6918e4a3ee267328e3f01a31b16ea08086865d | [
"Apache-2.0"
] | null | null | null | 45.532258 | 161 | 0.690046 | 4,074 | package com.supervise.core.data.out;
import com.supervise.config.role.DataType;
import com.supervise.controller.vo.DataSet;
import com.supervise.controller.vo.ViewVo;
import com.supervise.core.data.translate.GenericDataTranslate;
import com.supervise.dao.mysql.entity.BusinessDataEntity;
import com.supervise.dao.mysql.entity.RecourseEntity;
import com.supervise.dao.mysql.entity.UserEntity;
import com.supervise.dao.mysql.middleDao.BusinessDataDao;
import com.supervise.dao.mysql.middleDao.RecourseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xishui.hb on 2018/3/5 上午10:09.
*
* @author xishui
* Description:
* Modify Record
* ----------------------------------------
* User | Time | Note
*/
@Service
public class RecourseOutport extends AbstractDataOutport{
@Autowired
private BusinessDataDao businessDataDao;
@Autowired
private RecourseDao recourseDao;
@Override
public DataSet dataSet(ViewVo viewVo, DataType dataType,UserEntity userEntity) {
List<RecourseEntity> recourseEntities = recourseDao.queryRecourseByCondition(viewVo.getBatchDate(), viewVo.getProjId());
List<RecourseEntity> viewDataEntities = new ArrayList<RecourseEntity>();
if (!CollectionUtils.isEmpty(recourseEntities)) {
for(RecourseEntity recourseEntity:recourseEntities){
String projId = recourseEntity.getProjId();
//String orgId = recourseEntity.getOrgId();
List<BusinessDataEntity> businessDataEntities = businessDataDao.queryBusinessDataByExProj(viewVo.getBatchDate(), projId, viewVo.getClientName());
if(!CollectionUtils.isEmpty(businessDataEntities)){
BusinessDataEntity businessDataEntity = businessDataEntities.get(0);
String clientId = businessDataEntity.getClientId();
String clientName = businessDataEntity.getClientName();
recourseEntity.setClientId(clientId);
recourseEntity.setClientName(clientName);
viewDataEntities.add(recourseEntity);
}else{
//如果没有在业务表中查询到项目编号,则视为脏数据,删除
List<BusinessDataEntity> exentities = businessDataDao.queryBusinessDataByExProj(viewVo.getBatchDate(), projId, "");
if(CollectionUtils.isEmpty(exentities)){
recourseDao.deleteRecourseByID(recourseEntity.getId());
}
}
}
}
return new GenericDataTranslate<RecourseEntity>().translate(viewDataEntities,dataType.getDataLevel(),userEntity);
}
}
|
3e09a975763c564e596c6e296f14fdcfd7477c9f | 2,626 | java | Java | the-obfuscatorinator/src/main/java/com/theobfuscatorinator/graph/Graph.java | ThomasAndrasek/The-Obfuscatorinator | e1cd684cfa8a1691dad8fa5a46e240306130faba | [
"MIT"
] | null | null | null | the-obfuscatorinator/src/main/java/com/theobfuscatorinator/graph/Graph.java | ThomasAndrasek/The-Obfuscatorinator | e1cd684cfa8a1691dad8fa5a46e240306130faba | [
"MIT"
] | 1 | 2022-03-27T22:20:54.000Z | 2022-03-27T22:20:54.000Z | the-obfuscatorinator/src/main/java/com/theobfuscatorinator/graph/Graph.java | ThomasAndrasek/The-Obfuscatorinator | e1cd684cfa8a1691dad8fa5a46e240306130faba | [
"MIT"
] | null | null | null | 23.446429 | 64 | 0.447449 | 4,075 | package com.theobfuscatorinator.graph;
import java.util.ArrayList;
/**
* This class represents a directed graph.
*
* @author Thomas Andrasek
*/
public class Graph {
private ArrayList<Node> nodes;
/**
* Create an empty directed graph.
*/
public Graph() {
this.nodes = new ArrayList<Node>();
}
/**
* Add a node to the graph.
*
* @param node The node to add.
*/
public void addNode(String node) {
if (getNode(node) != null) {
return;
}
int low = 0;
int high = this.nodes.size();
while (low < high) {
int mid = (low + high) / 2;
Node n = this.nodes.get(mid);
int dif = node.compareTo(n.getName());
if (dif < 0) {
high = mid;
} else if (dif > 0) {
low = mid + 1;
} else {
break;
}
}
this.nodes.add(low, new Node(node));
}
/**
* Get a node from the graph.
*
* @param name The name of the node to get.
* @return The node with the given name.
*/
private Node getNode(String node) {
int low = 0;
int high = this.nodes.size();
while (low < high) {
int mid = (low + high) / 2;
Node n = this.nodes.get(mid);
int dif = node.compareTo(n.getName());
if (dif < 0) {
high = mid;
} else if (dif > 0) {
low = mid + 1;
} else {
return n;
}
}
return null;
}
/**
* Add an edge to the graph.
*
* @param from The node to add the edge from.
* @param to The node to add the edge to.
* @param value The value of the edge.
*/
public void addEdge(String from, String to, String value) {
this.addNode(from);
this.addNode(to);
Node n1 = this.getNode(from);
Node n2 = this.getNode(to);
n1.addEdge(new Edge(n1, n2, value));
}
/**
* Get the nodes of the graph.
*
* @return
*/
public ArrayList<Node> getNodes() {
return this.nodes;
}
/**
* Get the edges of the graph.
*
* @return
*/
public ArrayList<Edge> getEdges() {
ArrayList<Edge> edges = new ArrayList<Edge>();
for (Node n : this.nodes) {
edges.addAll(n.getEdges());
}
return edges;
}
}
|
3e09a9bc0014990cf9e7a9251fa00997025bb3a4 | 4,459 | java | Java | src/main/java/com/greenbudgie/genetica/item/FilledInjectorItem.java | GreenBudgie/Genetica | a045c4a1ea5ae96503128a2fc7fd7a56542dd557 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/greenbudgie/genetica/item/FilledInjectorItem.java | GreenBudgie/Genetica | a045c4a1ea5ae96503128a2fc7fd7a56542dd557 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/greenbudgie/genetica/item/FilledInjectorItem.java | GreenBudgie/Genetica | a045c4a1ea5ae96503128a2fc7fd7a56542dd557 | [
"CC0-1.0"
] | null | null | null | 43.291262 | 118 | 0.705315 | 4,076 | package com.greenbudgie.genetica.item;
import com.greenbudgie.genetica.block.entity.SubstanceHolderBlockEntity;
import com.greenbudgie.genetica.engineering.IEResult;
import com.greenbudgie.genetica.engineering.Substance;
import com.greenbudgie.genetica.engineering.handler.IEHandler;
import com.greenbudgie.genetica.engineering.handler.IEHandlers;
import com.greenbudgie.genetica.util.InventoryUtils;
import net.fabricmc.fabric.api.client.rendering.v1.ColorProviderRegistry;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
/**
* The main mod item. An injector, aka syringe, provides a player an ability to extract blood from
* any entity and make an injection of {@link com.greenbudgie.genetica.engineering.Substance Substance} to any entity.
*/
public class FilledInjectorItem extends SubstanceHolderItem {
public FilledInjectorItem(Settings settings) {
super(settings);
ColorProviderRegistry.ITEM.register((stack, tintIndex) ->
tintIndex == 0 ? getSubstanceColor(stack) : -1, this);
}
private IEResult makeInjection(ItemStack fromItem, LivingEntity toEntity, PlayerEntity player, Hand hand) {
IEHandler<?> handler = IEHandlers.getHandler(toEntity.getType());
IEResult result = handler.getIEResult();
if(result == IEResult.SUCCESS) {
emptyOnUse(fromItem, player, hand);
} else if(result == IEResult.ITEM_BREAK) {
breakOnUse(fromItem, player, hand);
}
return result;
}
/**
* Makes the injector broken. Also may play sounds TODO
* @param stack The injector stack to break
* @param player The player who used an item
* @param hand Hand in which the item has been used
*/
public void breakOnUse(ItemStack stack, PlayerEntity player, Hand hand) {
InventoryUtils.replaceOrDropHandItem(stack, new ItemStack(GeneticaItems.BROKEN_INJECTOR), player, hand);
}
/**
* Makes the injector empty. This not just remove the substance from the injector but also
* converts the item to another type of {@link EmptyInjectorItem}.
* Also may play sounds TODO
* @param stack The injector stack to empty
* @param player The player who used an item
* @param hand Hand in which the item has been used
*/
public void emptyOnUse(ItemStack stack, PlayerEntity player, Hand hand) {
InventoryUtils.replaceOrDropHandItem(stack, new ItemStack(GeneticaItems.EMPTY_INJECTOR), player, hand);
}
/**
* Transfers (sets or mixes) the substance to a block that can hold it.
* Empties the injector.
* @param stack The injector
* @param player The player who used an item
* @param hand Hand in which the item has been used
* @param holder A holder to the substance transfer to
* @return Whether the transfer has been completed
*/
public boolean transferSubstanceToBlockHolder(ItemStack stack, PlayerEntity player, Hand hand,
SubstanceHolderBlockEntity holder) {
Substance substance = getSubstance(stack);
if(substance != null) {
holder.fill(holder, substance);
emptyOnUse(stack, player, hand);
return true;
}
return false;
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
BlockEntity blockEntity = context.getWorld().getBlockEntity((context.getBlockPos()));
if(blockEntity instanceof SubstanceHolderBlockEntity) {
SubstanceHolderBlockEntity holder = (SubstanceHolderBlockEntity) blockEntity;
boolean complete = transferSubstanceToBlockHolder(
context.getStack(), context.getPlayer(), context.getHand(), holder);
if(complete) return ActionResult.SUCCESS;
}
return super.useOnBlock(context);
}
@Override
public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
ItemStack currentItem = user.getStackInHand(hand);
IEResult result = makeInjection(currentItem, entity, user, hand);
return result == IEResult.FAIL ? ActionResult.PASS : ActionResult.SUCCESS;
}
}
|
3e09aa36b345bf99309e96b048017a4e3bb15b74 | 4,049 | java | Java | Grid.java | zjwda2016/Tetris | b2fb41822ca2d1bff5c5a404d3fc34cfcfd2e15b | [
"Apache-2.0"
] | null | null | null | Grid.java | zjwda2016/Tetris | b2fb41822ca2d1bff5c5a404d3fc34cfcfd2e15b | [
"Apache-2.0"
] | null | null | null | Grid.java | zjwda2016/Tetris | b2fb41822ca2d1bff5c5a404d3fc34cfcfd2e15b | [
"Apache-2.0"
] | null | null | null | 25.626582 | 79 | 0.57792 | 4,077 | import java.awt.Color;
import java.awt.Graphics;
/**
* This is the Tetris board represented by a (HEIGHT - by - WIDTH) matrix of
* Squares.
*
* The upper left Square is at (0,0). The lower right Square is at (HEIGHT -1,
* WIDTH -1).
*
* Given a Square at (x,y) the square to the left is at (x-1, y) the square
* below is at (x, y+1)
*
* Each Square has a color. A white Square is EMPTY; any other color means that
* spot is occupied (i.e. a piece cannot move over/to an occupied square). A
* grid will also remove completely full rows.
*
* @author CSC 143
*/
public class Grid {
private Square[][] board;
// Width and Height of Grid in number of squares
public static final int HEIGHT = 20;
public static final int WIDTH = 10;
private static final int BORDER = 5;
public static final int LEFT = 100; // pixel position of left of grid
public static final int TOP = 50; // pixel position of top of grid
public static final Color EMPTY = Color.WHITE;
/**
* Creates the grid
*/
public Grid() {
board = new Square[HEIGHT][WIDTH];
// put squares in the board
for (int row = 0; row < HEIGHT; row++) {
for (int col = 0; col < WIDTH; col++) {
board[row][col] = new Square(this, row, col, EMPTY, false);
}
}
}
/**
* Returns true if the location (row, col) on the grid is occupied
*
* @param row
* the row in the grid
* @param col
* the column in the grid
*/
public boolean isSet(int row, int col) {
return !board[row][col].getColor().equals(EMPTY);
}
/**
* Changes the color of the Square at the given location
*
* @param row
* the row of the Square in the Grid
* @param col
* the column of the Square in the Grid
* @param c
* the color to set the Square
* @throws IndexOutOfBoundsException
* if row < 0 || row>= HEIGHT || col < 0 || col >= WIDTH
*/
public void set(int row, int col, Color c) {
board[row][col].setColor(c);
}
/**
* Change the color of the square to white, and move the rest squares to down
* @param r
*/
private void removeRow(int rRow)
{
// Change the color of the row to white
for (int col = 0; col < WIDTH; col++) {
set(rRow, col, EMPTY);
}
// Move the rest squares to down
for (int row = rRow - 1; row >= 0; row --) {
for (int col = 0; col < WIDTH; col ++) {
if(isSet(row, col))
{
Color color = board[row][col].getColor();
board[row][col].setColor(EMPTY);
board[row + 1][col].setColor(color);
}
}
}
}
/**
* Checks for and remove all solid rows of squares.
*
* If a solid row is found and removed, all rows above it are moved down and
* the top row set to empty
*/
public void checkRows() {
int row, col;
for(row = 0; row < HEIGHT; row ++) {
for(col = 0; col < WIDTH; col ++) {
if(!isSet(row, col)) {
break;
}
}
if(col == WIDTH) {
removeRow(row);
}
}
}
/**
* Draws the grid on the given Graphics context
*/
public void draw(Graphics g) {
// draw the edges as rectangles: left, right in blue then bottom in red
g.setColor(Color.BLUE);
g.fillRect(LEFT - BORDER, TOP, BORDER, HEIGHT * Square.HEIGHT);
g.fillRect(LEFT + WIDTH * Square.WIDTH, TOP, BORDER, HEIGHT
* Square.HEIGHT);
g.setColor(Color.RED);
g.fillRect(LEFT - BORDER, TOP + HEIGHT * Square.HEIGHT, WIDTH
* Square.WIDTH + 2 * BORDER, BORDER);
// draw all the squares in the grid
// empty ones first (to avoid masking the black lines of the pieces that
// have already fallen)
for (int r = 0; r < HEIGHT; r++) {
for (int c = 0; c < WIDTH; c++) {
if (board[r][c].getColor().equals(EMPTY)) {
board[r][c].draw(g);
}
}
}
for (int r = 0; r < HEIGHT; r++) {
for (int c = 0; c < WIDTH; c++) {
if (!board[r][c].getColor().equals(EMPTY)) {
board[r][c].draw(g);
}
}
}
}
}
|
3e09aa87d7458439b79ac1fb1e22c6ff3c8ba45a | 2,222 | java | Java | dm-uap-common/src/main/java/com/dm/uap/service/impl/LoginLogServiceImpl.java | ldwqh0/dm-parent | d790495777d24450cf84c210958bfad867ace9cd | [
"Apache-2.0"
] | 6 | 2019-02-25T06:53:12.000Z | 2021-02-04T07:37:08.000Z | dm-uap-common/src/main/java/com/dm/uap/service/impl/LoginLogServiceImpl.java | ldwqh0/dm-parent | d790495777d24450cf84c210958bfad867ace9cd | [
"Apache-2.0"
] | 4 | 2020-04-18T06:27:12.000Z | 2020-04-18T06:27:23.000Z | dm-uap-common/src/main/java/com/dm/uap/service/impl/LoginLogServiceImpl.java | ldwqh0/dm-parent | d790495777d24450cf84c210958bfad867ace9cd | [
"Apache-2.0"
] | 3 | 2019-06-11T05:57:49.000Z | 2022-03-16T12:33:22.000Z | 32.676471 | 105 | 0.70432 | 4,078 | package com.dm.uap.service.impl;
import com.dm.collections.Lists;
import com.dm.uap.converter.LoginLogConverter;
import com.dm.uap.dto.LoginLogDto;
import com.dm.uap.entity.LoginLog;
import com.dm.uap.entity.QLoginLog;
import com.dm.uap.repository.LoginLogRepository;
import com.dm.uap.service.LoginLogService;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
//@Service
public class LoginLogServiceImpl implements LoginLogService {
private final LoginLogRepository loginLogRepository;
private final QLoginLog qLoginLog = QLoginLog.loginLog;
public LoginLogServiceImpl(LoginLogRepository loginLogRepository) {
this.loginLogRepository = loginLogRepository;
}
@Override
@Transactional
public LoginLogDto save(LoginLogDto log) {
return LoginLogConverter.toDto(loginLogRepository.save(copyProperties(new LoginLog(), log)));
}
@Override
@Transactional
public List<LoginLogDto> save(List<LoginLogDto> logs) {
return Lists.transform(
loginLogRepository.saveAll(Lists.transform(logs, it -> copyProperties(new LoginLog(), it))),
LoginLogConverter::toDto
);
}
@Override
public Page<LoginLogDto> list(String key, Pageable pageable) {
BooleanBuilder query = new BooleanBuilder();
if (StringUtils.isNotBlank(key)) {
query.and(qLoginLog.ip.containsIgnoreCase(key)
.or(qLoginLog.loginName.containsIgnoreCase(key)));
}
return loginLogRepository.findAll(query, pageable).map(LoginLogConverter::toDto);
}
private LoginLog copyProperties(LoginLog dest, LoginLogDto source) {
dest.setIp(source.getIp());
dest.setLoginName(source.getLoginName());
dest.setResult(source.getResult());
dest.setTime(source.getTime());
dest.setType(source.getType());
return dest;
}
}
|
3e09aac7514f9dcc49f477023fb6610dc9c799e2 | 317 | java | Java | app/src/main/java/com/winsun/fruitmix/file/data/model/RemotePublicDrive.java | winsuntech/fruitmix.android | 069d7ec97bf22816334af83807e93ad146376473 | [
"Apache-2.0"
] | 1 | 2018-07-11T07:55:41.000Z | 2018-07-11T07:55:41.000Z | app/src/main/java/com/winsun/fruitmix/file/data/model/RemotePublicDrive.java | winsuntech/fruitmix.android | 069d7ec97bf22816334af83807e93ad146376473 | [
"Apache-2.0"
] | 292 | 2017-08-24T09:55:45.000Z | 2018-08-03T10:38:41.000Z | app/src/main/java/com/winsun/fruitmix/file/data/model/RemotePublicDrive.java | winsuntech/fruitmix.android | 069d7ec97bf22816334af83807e93ad146376473 | [
"Apache-2.0"
] | null | null | null | 15.85 | 53 | 0.66877 | 4,079 | package com.winsun.fruitmix.file.data.model;
import com.winsun.fruitmix.R;
/**
* Created by Administrator on 2017/10/16.
*/
public class RemotePublicDrive extends RemoteFolder {
public RemotePublicDrive() {
super();
setFileTypeResID(R.drawable.shared_drive);
setTime("");
}
}
|
3e09aaeb8ed2bb06eee0f882ffaa469b2e4d9f0c | 13,107 | java | Java | src/main/java/io/opensec/oval/core/interpreter/OvaldiProxy.java | nakamura5akihito/opensec-oval | 7afea82fd919d882231a34e73c0e59d4b184e3e7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/opensec/oval/core/interpreter/OvaldiProxy.java | nakamura5akihito/opensec-oval | 7afea82fd919d882231a34e73c0e59d4b184e3e7 | [
"Apache-2.0"
] | 3 | 2015-06-02T09:33:37.000Z | 2015-06-17T10:58:58.000Z | src/main/java/io/opensec/oval/core/interpreter/OvaldiProxy.java | nakamura5akihito/opensec-oval | 7afea82fd919d882231a34e73c0e59d4b184e3e7 | [
"Apache-2.0"
] | null | null | null | 27.136646 | 110 | 0.521096 | 4,080 | /**
* Opensec OVAL - https://nakamura5akihito.github.io/
* Copyright (C) 2015 Akihito Nakamura
*
* 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.opensec.oval.core.interpreter;
import io.opensec.oval.core.OpensecOvalContext;
import io.opensec.oval.interpreter.Option;
import io.opensec.oval.interpreter.Options;
import io.opensec.oval.interpreter.OvalInterpreter;
import io.opensec.oval.interpreter.OvalInterpreterException;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An ovaldi proxy.
* The ovaldi is a Mitre's reference implementation which evaluates OVAL Definitions.
* Based on a set of OVAL Definitions the interpreter collects system information,
* evaluates it, and generates a detailed OVAL Results file.
*
* @author Akihito Nakamura, AIST
* @see <a href="http://oval.mitre.org/language/interpreter.html">OVAL Interpreter</a>
*/
public class OvaldiProxy
implements OvalInterpreter
{
/**
* Command line entry point.
*
* @param args
* the OVAL Interpreter program and its arguments.
*/
public static void main(
final String[] args
)
throws Exception
{
// if (args.length < 1) {
// System.err.println( "no argument specified" );
// System.exit( 1 );
// }
List<String> options = Arrays.asList( args );
final OvaldiProxy ovaldi = new OvaldiProxy( options );
final int exit_value = ovaldi.execute();
System.exit( exit_value );
}
// /**
// * Configuration properties.
// */
// protected static class Config
// {
// public static final String DEFAULT_EXECUTABLE = "ovaldi";
//
// public static final String EXECUTABLE = "opensec.oval.ovaldi.executable";
// public static final String WORK_DIR = "opensec.oval.ovaldi.work_dir";
// public static final String OUTPUT_DIR = "opensec.oval.ovaldi.output_dir";
// }
// //Config
/**
* Logger.
*/
private static final Logger _LOG_ = LoggerFactory.getLogger( OvaldiProxy.class );
private final Map<String, String> _config = new HashMap<String, String>();
private Options _options;
/**
* Constructs an instance.
*/
public OvaldiProxy()
{
}
/**
* Constructs an instance with the specified command options.
*/
public OvaldiProxy(
final Options options
)
{
setOptions( options );
}
public OvaldiProxy(
final List<String> options
)
{
setOptions( OvaldiOptions.fromCommandLine( options ) );
}
// /**
// *
// * @param options
// */
// public void setOptions(
// final List<String> options
// )
// {
// setOptions( OvaldiOptions.fromCommandLine( options ) );
// }
/**
* Reads the output from the process and waits until the process has terminated.
*
* @return
* the exit value of the process.
* @throws OvalInterpreterException
*/
private int _waitFor(
final Process process
)
{
final String lineSeparator = System.getProperty( "line.separator" );
final BufferedReader reader = new BufferedReader(
new InputStreamReader( process.getInputStream() ) );
int exitValue = 0;
final StringBuilder log = new StringBuilder();
try {
String line = null;
while (true) {
if (line != null) {
log.append( lineSeparator );
}
line = reader.readLine();
//throws IOException
if (line == null) {
break;
}
log.append( line );
}
exitValue = process.waitFor();
//throws InterruptedException
} catch (final Exception ex) {
throw new OvalInterpreterException( ex );
} finally {
try {
reader.close();
//throws IOException
} catch (final Exception ex) {
// ignorable.
_LOG_.warn( ex.getMessage() );
}
}
_LOG_.debug( "==== ovaldi log ====\n" + log.toString() );
_LOG_.debug( "exit value=" + exitValue );
return exitValue;
}
/**
* Creates a process builder.
* The standard error and standard output are merged,
* so that both can be read using the Process.getInputStream() method.
*/
private ProcessBuilder _createProcessBuilder(
final OpensecOvalContext context
)
{
final List<String> command = _createCommand1( context );
final ProcessBuilder builder = new ProcessBuilder( command );
_configureWorkingDir( builder, context );
// Merging standard error and standard output!!!
builder.redirectErrorStream( true );
return builder;
}
private void _configureWorkingDir(
final ProcessBuilder builder,
final OpensecOvalContext context
)
{
String workdir = getWorkingDir();
if (workdir == null) {
workdir = context.getProperty( OvaldiConfig.WORK_DIR );
}
File dir = null;
if (workdir != null) {
dir = new File( workdir );
if (dir.exists()) {
if (!dir.isDirectory()) {
throw new OvalInterpreterException(
"specified working dir is NOT directory: " + workdir );
}
} else {
boolean created = dir.mkdir();
if (!created) {
throw new OvalInterpreterException(
"failed to create working dir: " + workdir );
}
}
}
_LOG_.debug( "ovaldi working dir=" + workdir );
if (dir != null) {
builder.directory( dir );
}
}
/**
* Creates a command line: the program and its arguments.
* E.g. ovaldi -m -o definitions.xml
*
* @throws OvalInterpreterException
*/
private List<String> _createCommand1(
final OpensecOvalContext context
)
{
final List<String> command = new ArrayList<String>();
String ovaldi_path = getExecutablePath();
if (ovaldi_path == null) {
ovaldi_path = context.getProperty( OvaldiConfig.EXECUTABLE, OvaldiConfig.DEFAULT_EXECUTABLE );
}
_LOG_.debug( "ovaldi path: " + ovaldi_path );
command.add( ovaldi_path );
Options options = getOptions();
if (options == null) {
options = new OvaldiOptions();
} else {
try {
options = options.clone();
} catch (Exception ex) {
throw new OvalInterpreterException( ex );
}
}
// _LOG_.debug( "ovaldi options: " + options );
for (Option opt : OvaldiOption.values()) {
if (options.contains( opt )) {
//nothing
} else {
String sys_prop = context.getProperty( opt.systemProperty );
if (sys_prop != null) {
if ("boolean".equals( opt.contentType ) && opt.hasArgument == false) {
if (Boolean.valueOf( sys_prop ).booleanValue() == true) {
options.set( opt );
}
} else {
options.set( opt, sys_prop );
}
}
}
}
command.addAll( options.toCommandLine() );
_LOG_.debug( "ovaldi command: " + String.valueOf( command ) );
return command;
}
// private List<String> _createCommand0(
// final OvalContext context
// )
// {
// final List<String> command = new ArrayList<String>();
//
// String ovaldi_path = getExecutablePath();
// if (ovaldi_path == null) {
// ovaldi_path = context.getProperty( Config.OVALDI_EXECUTABLE, Config.DEFAULT_OVALDI_EXECUTABLE );
// }
// _LOG_.debug( "ovaldi path: " + ovaldi_path );
// command.add( ovaldi_path );
//
// Options options = getOptions();
// if (options == null) {
// options = new OvaldiOptions();
// }
//// _LOG_.debug( "ovaldi options: " + options );
// command.addAll( options.toCommandLine() );
//
// _LOG_.debug( "ovaldi command: " + String.valueOf( command ) );
// return command;
// }
// private List<String> _createCommand()
// {
// final List<String> command = new ArrayList<String>();
//
// command.add( getExecutablePath() );
//
// Options options = _adjustDefaultOptions( getOptions() );
// if (options == null) {
// options = new Options();
// }
// _LOG_.debug( "options: " + options );
// command.addAll( options.toCommandLine() );
//
// _LOG_.debug( "command: " + String.valueOf( command ) );
// return command;
// }
//
//
// private Options _adjustDefaultOptions(
// final Options options
// )
// {
// Options complete_options = null;
//
// if (options != null) {
// try {
// complete_options = options.clone();
// } catch (CloneNotSupportedException ex) {
// // never happen
// }
// }
//
// if (complete_options == null) {
// complete_options = new OvaldiOptions();
// }
//
// for (Property property : Property.values()) {
// if (property.option != null) {
// String value = options.get( property.option );
// if (value == null) {
// value = _getConfigProperty( property );
// complete_options.set( property.option, value );
// }
// }
// }
//
// return complete_options;
// }
//*********************************************************************
// config
//*********************************************************************
/**
*/
public void setExecutablePath(
final String filepath
)
{
_config.put( OvaldiConfig.EXECUTABLE, filepath );
}
public String getExecutablePath()
{
return _config.get( OvaldiConfig.EXECUTABLE );
}
/**
*/
public void setOutputDir(
final String dirpath
)
{
_config.put( OvaldiConfig.OUTPUT_DIR, dirpath );
}
public String getOutputDir()
{
return _config.get( OvaldiConfig.OUTPUT_DIR );
}
/**
*/
public void setWorkingDir(
final String dirpath
)
{
_config.put( OvaldiConfig.WORK_DIR, dirpath );
}
public String getWorkingDir()
{
return _config.get( OvaldiConfig.WORK_DIR );
}
//*********************************************************************
// OvalInterpreter
//*********************************************************************
public int execute()
{
OpensecOvalContext context = OpensecOvalContext.basic();
final ProcessBuilder builder = _createProcessBuilder( context );
Process process = null;
int exitValue = 0;
try {
process = builder.start();
//throws IOException, SecurityException
} catch (final Exception ex) {
throw new OvalInterpreterException( ex );
}
exitValue = _waitFor( process );
return exitValue;
}
public void setOptions(
final Options options
)
{
_options = options;
}
public Options getOptions()
{
return _options;
}
}
//
|
3e09ac1fa6ce5227a6a993c76924262e2315b44b | 1,692 | java | Java | src/main/java/pw/pfg/randomoresmod/modresource/RegisterableBlockDefaults.java | pfgithub/randomoresmod | 4f2aeb8e9f9a9425d0a7d64b0d3ec3158b19995d | [
"MIT"
] | null | null | null | src/main/java/pw/pfg/randomoresmod/modresource/RegisterableBlockDefaults.java | pfgithub/randomoresmod | 4f2aeb8e9f9a9425d0a7d64b0d3ec3158b19995d | [
"MIT"
] | null | null | null | src/main/java/pw/pfg/randomoresmod/modresource/RegisterableBlockDefaults.java | pfgithub/randomoresmod | 4f2aeb8e9f9a9425d0a7d64b0d3ec3158b19995d | [
"MIT"
] | null | null | null | 27.737705 | 86 | 0.795508 | 4,081 | package pw.pfg.randomoresmod.modresource;
import java.util.List;
import com.swordglowsblue.artifice.api.ArtificeResourcePack.ClientResourcePackBuilder;
import com.swordglowsblue.artifice.api.ArtificeResourcePack.ServerResourcePackBuilder;
import com.swordglowsblue.artifice.api.builder.assets.TranslationBuilder;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.biome.Biome;
import pw.pfg.randomoresmod.IRegisterable;
import pw.pfg.randomoresmod.ObjectDetails;
import pw.pfg.randomoresmod.RegistrationHelper;
import pw.pfg.randomoresmod.TextureInfo;
public interface RegisterableBlockDefaults extends IRegisterable {
public ObjectDetails getResource();
public TextureInfo getTexture();
public Item getItem();
public Block getBlock();
@Override
default public void registerTranslations(TranslationBuilder trans) {}
@Override
default public void registerData(ServerResourcePackBuilder data) {}
@Override
default public void registerAssets(ClientResourcePackBuilder pack) {
RegistrationHelper.registerModels(
pack,
getTexture(),
model -> {
RegistrationHelper.registerDefaultBlockModel(model, getTexture());
}
);
}
@Override
default public void register() {
RegistrationHelper.register(getTexture().id, getBlock(), getItem());
}
@Override
default public void registerClient() {
RegistrationHelper.registerColorProvider(
getBlock(),
getItem(),
getResource()
);
}
@Override
default public void registerBiomeFeatures(Biome biome) {}
@Override
default public void registerItemGroup(List<ItemStack> stacks) {
stacks.add(new ItemStack(getBlock()));
}
}
|
3e09ac39baf57c55bcbab62bde099346f5c044c4 | 76,742 | java | Java | src/ml/Tree/AdaboostRandomForestClassifier.java | ledell/StackNet | c6ee1f5b7c21479be362c33f404debbbdc37aed6 | [
"MIT"
] | null | null | null | src/ml/Tree/AdaboostRandomForestClassifier.java | ledell/StackNet | c6ee1f5b7c21479be362c33f404debbbdc37aed6 | [
"MIT"
] | null | null | null | src/ml/Tree/AdaboostRandomForestClassifier.java | ledell/StackNet | c6ee1f5b7c21479be362c33f404debbbdc37aed6 | [
"MIT"
] | 1 | 2019-08-31T15:22:05.000Z | 2019-08-31T15:22:05.000Z | 30.213386 | 238 | 0.637591 | 4,082 | /*Copyright (c) 2017 Marios Michailidis
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 ml.Tree;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import preprocess.scaling.scaler;
import utilis.XorShift128PlusRandom;
import utilis.map.intint.StringIntMap4a;
import exceptions.DimensionMismatchException;
import exceptions.LessThanMinimum;
import matrix.fsmatrix;
import matrix.smatrix;
import ml.classifier;
import ml.estimator;
/**
* /**
*
* @author mariosm
*<p> This class will run the Adaboost algorithms on Random Forest classifiers . The idea behind the algorithm is that
*It is in initially run on a given data set-normally with replacement (bootstrapping) and then the weights are
*updated based on whether the classifications correct or not. Wrong classifiers will get higher weights , making the
*next model more focused onto these cases. With this logic every new model tries to explain a little bit more the
*areas where the previous model failed to do so, reducing the total error dramatically . </p>
* <p> AdaBoost is very prone to overfitting therefore one has to be careful with what parameters to choose.
* <p> This version of AdaBoost is specifically made to reduce the residual error as defined in :
* <pre>Log((1-error)/error)</pre>.
<p>
*ref : Freund, Y., & Schapire, R. E. (1995, March). A desicion-theoretic generalization of on-line learning and an application to boosting. In European conference on computational learning theory (pp. 23-37). Springer Berlin Heidelberg.
Chicago </p>
*/
public class AdaboostRandomForestClassifier implements estimator,classifier {
/**
* This keeps the sorted indices for each column
*/
private int sorted_indices [][];
public void set_sorted_indices (int indices [][]){
if (indices==null || indices.length !=this.columndimension) {
throw new IllegalStateException(" The sorted indices need to have the same dimension as the feature input ");
}
this.sorted_indices=indices;
}
/**
* This keeps the sorted indices ranks
*/
private int maximum_ranks;
public void set_ranked_scores (int indices){
this.maximum_ranks=indices;
}
/**
* This holds all the trees'nodes
*/
private RandomForestClassifier tree_body [] ;
/**
* Number of trees to build
*/
public int estimators=10;
/**
* threads to use
*/
public int threads=1;
/**
* use samples with replacement or not
*/
public boolean bootsrap=false;
/*************tree specific from here on *****************/
/**
* maximum number of nodes allowed
*/
public double max_tree_size=-1;
/**
* offset for divisions
*/
public double offset=0.00001;
/**
* maximum depth of the tree
*/
public double max_depth=3;
/**
* Minimum gain to allow for a node to split
*/
public double gamma=1E-30;
/**
* Minimum weighted sum to split a node
*/
public double min_split=2.0;
/**
* Minimum weighted sum to keep a splitted node
*/
public double min_leaf=1.0;
/**
* Proportions of columns (features) to consider
*/
public double max_features=1.0;
/**
* Proportions of columns (features) to consider
*/
public double feature_subselection=1.0;
/**
* Proportions of best cut offs to consider
*/
public double cut_off_subsample=1.0;
/**
* Trees in Random forest.
*/
public int trees=1;
/**
* weight on each estimator . Smaller values prevent overfitting.
*/
//public double shrinkage=0.1;
/**
* Proportions of best cut offs to consider
*/
public double row_subsample=1.0;
/**
* Rows to use
*/
private int rows [];
public RandomForestClassifier [] Get_tree(){
if (this.tree_body==null || this.tree_body.length<=0){
throw new IllegalStateException(" There is NO tree" );
}
return tree_body;
}
public double [] get_importances(){
if (this.feature_importances==null || feature_importances.length<=0){
throw new IllegalStateException(" There no importances (yet)" );
}
return feature_importances;
}
public void set_rows(int rows []){
if (rows==null || rows.length<=0){
throw new IllegalStateException(" The row indices are empty" );
}
this.rows=rows;
}
/**
* columns to use
*/
private int columns [];
public void set_columns(int columns []){
if (columns==null || columns.length<=0){
throw new IllegalStateException(" The columns indices are empty" );
}
this.columns=columns;
}
/**
* Holds the rank of the 'zero' (e.g. sparse) elements
*/
private int zero_rank_holder [];
public void set_zero_rank (int [] indices){
this.zero_rank_holder=indices;
}
/**
* The objective to optimise in split . It may be ENTROPY
* , GINI or AUC
*/
public String Objective="ENTROPY";
/**
* scale the copy the dataset
*/
public boolean copy=true;
/**
* digits of rounding to prevent overfitting
*/
public double rounding=6;
/**
* seed to use
*/
public int seed=1;
/**
* Random number generator to use
*/
private Random random;
/**
* weighst to used per row(sample)
*/
public double [] weights;
/**
* if true, it prints stuff
*/
public boolean verbose=true;
/**
* Target variable in double format
*/
public double target[];
/**
* The coefficients of each classifier
*/
private double coeffs [];
/**
* size of ensemble
*/
private int ensemble_size=0;
/**
* weight threshold to avoid early stopping
*/
public double weight_thresold=0.1;
/**
* Target variable in 2d double format
*/
public double target2d[][];
/**
* Target variable in fixed-size matrix format
*/
public int [] fstarget;
/**
* Target variable in sparse matrix format
*/
public smatrix starget;
/**
* Hold feature importance for the tree
*/
double feature_importances [];
/**
* How many predictors the model has
*/
private int columndimension=0;
//return number of predictors in the model
public int get_predictors(){
return columndimension;
}
/**
* Number of target-variable columns. The name is left as n_classes(same as classification for consistency)
*/
private int n_classes=0;
/**
* Name of the unique classes
*/
private String classes[];
/**
* Target variable in String format
*/
public String Starget[];
public int getnumber_of_classes(){
return n_classes;
}
/**
*
* @param classes : the classes to put
*/
public void setclasses(String[] classes ) {
if (classes==null || classes.length<=0){
throw new IllegalStateException (" No classes are found");
} else {
this.classes= classes;
}
}
@Override
public String[] getclasses() {
if (classes==null || classes.length<=0){
throw new IllegalStateException (" No classes are found, the model needs to be fitted first");
} else {
return classes;
}
}
@Override
public void AddClassnames(String[] names) {
String distinctnames[]=manipulate.distinct.distinct.getstringDistinctset(names);
if (distinctnames.length<2){
throw new LessThanMinimum(names.length,2);
}
if (distinctnames.length!=names.length){
throw new IllegalStateException (" There are duplicate values in the names of the addClasses method, dedupe before adding them");
}
classes=new String[names.length];
for (int j=0; j < names.length; j++){
classes[j]=names[j];
}
}
/**
* The object that holds the modelling data in double form in cases the user chooses this form
*/
private double dataset[][];
/**
* The object that holds the modelling data in fsmatrix form cases the user chooses this form
*/
private fsmatrix fsdataset;
/**
* The object that holds the modelling data in smatrix form cases the user chooses this form
*/
private smatrix sdataset;
/**
* Default constructor for AdaboostRandomForestClassifier with no data
*/
public AdaboostRandomForestClassifier(){
}
/**
* Default constructor for AdaboostRandomForestClassifier with double data
*/
public AdaboostRandomForestClassifier(double data [][]){
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
dataset=data;
}
/**
* Default constructor for AdaboostRandomForestClassifier with fsmatrx data
*/
public AdaboostRandomForestClassifier(fsmatrix data){
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
fsdataset=data;
}
/**
* Default constructor for AdaboostRandomForestClassifier with smatrx data
*/
public AdaboostRandomForestClassifier(smatrix data){
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
sdataset=data;
}
public void setdata(double data [][]){
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
dataset=data;
}
public void setdata(fsmatrix data){
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
fsdataset=data;
}
public void setdata(smatrix data){
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
sdataset=data;
}
@Override
public void run() {
// check which object was chosen to train on
if (dataset!=null){
this.fit(dataset);
} else if (fsdataset!=null){
this.fit(fsdataset);
} else if (sdataset!=null){
this.fit(sdataset);
} else {
throw new IllegalStateException(" No data structure specifed in the constructor" );
}
}
/**
* default Serial id
*/
private static final long serialVersionUID = -8611561535854392960L;
@Override
public double[][] predict_proba(double[][] data) {
/* check if the Create_Logic method is run properly
*/
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data[0].length!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data[0].length);
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
double predictions[][]= new double [data.length][this.n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.length,this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(predictions, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[][] predict_proba(fsmatrix data) {
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
double predictions[][]= new double [data.GetRowDimension()][this.n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.GetRowDimension(),this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(predictions, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[][] predict_proba(smatrix data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
if (!data.IsSortedByRow()){
data.convert_type();
}
double predictions[][]= new double [data.GetRowDimension()][this.n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.GetRowDimension(),this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(predictions, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[] predict_probaRow(double[] data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.length!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as the trained one: " + columndimension + " <> " + data.length);
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions[]= new double [this.n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data);
append_predictions_score(predictions, newpredictions,this.coeffs[j]);
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[] predict_probaRow(fsmatrix data, int rows) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions[]= new double [this.n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data,rows);
append_predictions_score(predictions, newpredictions,this.coeffs[j]);
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[] predict_probaRow(smatrix data, int start, int end) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions[]= new double [this.n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data,start,end);
append_predictions_score(predictions, newpredictions,this.coeffs[j]);
}
scale_scores(predictions);
// return the 1st prediction
return predictions;
}
@Override
public double[] predict(fsmatrix data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
double predictions[]= new double [data.GetRowDimension()];
double prediction_probas[][]= new double [data.GetRowDimension()][n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.GetRowDimension(),this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(prediction_probas, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
// return the 1st prediction
for (int i=0; i < predictions.length; i++) {
double temp[]=prediction_probas[i];
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions[i]=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions[i]=maxi;
}
}
prediction_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public double[] predict(smatrix data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
if (!data.IsSortedByRow()){
data.convert_type();
}
double predictions[]= new double [data.GetRowDimension()];
double prediction_probas[][]= new double [data.GetRowDimension()][n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.GetRowDimension(),this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(prediction_probas, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
// return the 1st prediction
for (int i=0; i < predictions.length; i++) {
double temp[]=prediction_probas[i];
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions[i]=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions[i]=maxi;
}
}
prediction_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public double[] predict(double[][] data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 ||this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data[0].length!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data[0].length);
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
double predictions[]= new double [data.length];
double prediction_probas[][]= new double [data.length][n_classes];
double shrinks[]= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
Thread[] thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads]; // generate threads' array
fsmatrix arrays []= new fsmatrix[(this.ensemble_size <this.threads)?this.ensemble_size:this.threads];
int count_of_live_threads=0;
for (int tree =0; tree <this.ensemble_size;tree++ ){
shrinks[count_of_live_threads]=this.coeffs[tree];
arrays[count_of_live_threads]=new fsmatrix(data.length,this.n_classes);
thread_array[count_of_live_threads]= new Thread(new scoringhelpercatfv2 (data, arrays[count_of_live_threads], tree_body[tree])); ;
thread_array[count_of_live_threads].start();
count_of_live_threads++;
if (count_of_live_threads==threads || tree==tree_body.length-1){
for (int s=0; s <count_of_live_threads;s++ ){
try {
thread_array[s].join();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new IllegalStateException(" algorithm was terminated due to multithreading error");
}
}
//extract the values and see if we got a gamma better than required one
for (int s=0; s <count_of_live_threads;s++ ){
append_predictions_score(prediction_probas, arrays[s],shrinks[s]);
}
count_of_live_threads=0;
thread_array= new Thread[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
arrays = new fsmatrix[(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
shrinks= new double [(this.ensemble_size<this.threads)?this.ensemble_size:this.threads];
}
}
// return the 1st prediction
for (int i=0; i < predictions.length; i++) {
double temp[]=prediction_probas[i];
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions[i]=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions[i]=maxi;
}
}
prediction_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public double predict_Row(double[] data) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<1 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.length!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as the trained one: " + columndimension + " <> " + data.length);
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions= 0.0;
double predictions_probas[]= new double [n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data);
append_predictions_score(predictions_probas, newpredictions,this.coeffs[j]);
}
double temp[]=predictions_probas;
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions=maxi;
}
predictions_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public double predict_Row(fsmatrix data, int rows) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<2 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions= 0.0;
double predictions_probas[]= new double [n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data,rows);
append_predictions_score(predictions_probas, newpredictions,this.coeffs[j]);
}
double temp[]=predictions_probas;
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions=maxi;
}
predictions_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public double predict_Row(smatrix data, int start, int end) {
/*
* check if the Create_Logic method is run properly
*/
if (n_classes<1 || this.tree_body==null || this.tree_body.length<=0 ){
throw new IllegalStateException("The fit method needs to be run successfully in " +
"order to create the logic before attempting scoring a new set");}
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" There is nothing to score" );
}
if (data.GetColumnDimension()!=columndimension){
throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " + columndimension + " <> " + data.GetColumnDimension());
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
}
double predictions= 0.0;
double predictions_probas[]= new double [n_classes];
for (int j=0; j < tree_body.length; j++){
double newpredictions[]=tree_body[j].predict_probaRow(data,start,end);
append_predictions_score(predictions_probas, newpredictions,this.coeffs[j]);
}
double temp[]=predictions_probas;
int maxi=0;
double max=temp[0];
for (int k=1; k<n_classes; k++) {
if (temp[k]>max){
max=temp[k];
maxi=k;
}
}
try{
predictions=Double.parseDouble(classes[maxi]);
} catch (Exception e){
predictions=maxi;
}
predictions_probas=null;
// return the 1st prediction
return predictions;
}
@Override
public void fit(double[][] data) {
// make sensible checks
if (data==null || data.length<=0){
throw new IllegalStateException(" Main data object is null or has too few cases" );
}
dataset=data;
if (max_tree_size<=0){
max_tree_size=Double.MAX_VALUE;
}
if (min_split<2){
min_split=2;
}
if (min_leaf<1){
min_leaf=1;
}
if (max_features<=0){
max_features=1;
}
if (feature_subselection<=0){
feature_subselection=1;
}
if (this.offset<=0){
this.offset=0.0000001;
}
if (cut_off_subsample<=0){
cut_off_subsample=1;
}
if (row_subsample<=0){
row_subsample=1;
}
if (weight_thresold<=0 || weight_thresold>=1){
weight_thresold=0.1;
}
if (this.estimators<1){
estimators=1;
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
// make sensible checks on the target data
if ( (target==null || target.length!=data.length) && (Starget==null || Starget.length!=data.length) ){
throw new IllegalStateException(" target array needs to be provided with the same length as the data" );
} else if (target!=null ){
// check if values only 1 and zero
HashSet<Double> has= new HashSet<Double> ();
for (int i=0; i < target.length; i++){
has.add(target[i]);
}
if (has.size()<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
double uniquevalues[]= new double[has.size()];
int k=0;
for (Iterator<Double> it = has.iterator(); it.hasNext(); ) {
uniquevalues[k]= it.next();
k++;
}
// sort values
Arrays.sort(uniquevalues);
classes= new String[uniquevalues.length];
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < uniquevalues.length; j++){
classes[j]=uniquevalues[j]+"";
mapper.put(classes[j], index);
index++;
}
fstarget=new int[target.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(target[i] + "");
}
} else if (Starget!=null && (classes==null || classes.length<=1)){
classes=manipulate.distinct.distinct.getstringDistinctset(Starget);
if (classes.length<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
Arrays.sort(classes);
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < classes.length; j++){
mapper.put(classes[j], index);
index++;
}
fstarget=new int[Starget.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(Starget[i]);
}
}
if (weights==null) {
weights=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weights[i]=1.0;
}
} else {
if (weights.length!=data.length){
throw new DimensionMismatchException(weights.length,data.length);
}
weights=manipulate.transforms.transforms.scaleweight(weights);
for (int i=0; i < weights.length; i++){
weights[i]*= weights.length;
}
}
//hard copy
if (copy){
data= manipulate.copies.copies.Copy( data);
}
// Initialise randomiser
fsdataset=new fsmatrix(data);
this.random = new XorShift128PlusRandom(this.seed);
this.n_classes=classes.length;
if (this.Objective.equals("AUC") && (this.n_classes!=2)){
throw new IllegalStateException("The 'AUC' Metric can only be used when n_classes=2" );
}
/**
* generate rows required by the algorithm
*/
/*
if (data.optional_rows==null){
data.void_update_indice();
}
*/
columndimension=data[0].length;
feature_importances= new double [columndimension];
if (this.sorted_indices==null){
this.sorted_indices=new int [3] [];
this.maximum_ranks= 0;
this.zero_rank_holder= new int [this.columndimension];
// create indices
sortcolumnsnomap sorty= new sortcolumnsnomap (this.fsdataset,
this.rows,
this.sorted_indices,
this.zero_rank_holder,
this.rounding );
sorty.verbose=this.verbose;
sorty.merge_thresold=this.gamma;
sorty.target_vales=fstarget;
sorty.run();
this.maximum_ranks= sorty.getmaxrank();
}
if (this.verbose){
System.out.println("Sorting is done");
}
//calculate initial estimates
// Initialise the tree structure
this.coeffs=new double [this.estimators];
tree_body= new RandomForestClassifier[this.estimators];
// start the loop to find the support vectors
int targetcolumns=n_classes;
fsmatrix predictions=new fsmatrix(fstarget.length, targetcolumns);
double classification[]=new double [fstarget.length];
double weight[]=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weight[i]= weights[i];
}
ensemble_size=0;
//fsmatrix fstarget_model=new fsmatrix(residuals);
for (int n=0; n <this.estimators; n++ ){
RandomForestClassifier model = new RandomForestClassifier(fsdataset);
//general
model.set_sorted_indices(this.sorted_indices);
model.set_ranked_scores(this.maximum_ranks);
model.set_zero_rank(this.zero_rank_holder);
model.internal_threads=this.threads;
model.verbose=false;
model.rounding=this.rounding;
model.estimators=this.trees;
model.copy=false;
model.cut_off_subsample=this.cut_off_subsample;
model.feature_subselection=this.feature_subselection;
model.setclasses(this.classes);
if (this.rows!=null){
model.set_rows(this.rows);
}
if (this.columns!=null){
model.set_columns(this.columns);
}
model.offset=this.offset;
model.gamma=this.gamma;
model.bootsrap=this.bootsrap;
model.max_depth=this.max_depth;
model.max_features=this.max_features;
model.max_tree_size=-1;
model.min_leaf=this.min_leaf;
model.min_split=this.min_split;
model.Objective=this.Objective;
model.row_subsample=this.row_subsample;
model.seed=this.seed+ n;
model.weights=weight; // add the weights
model.fstarget=this.fstarget;
tree_body[n]=model;
model.fit(fsdataset);
ensemble_size+=1;
predictions=tree_body[n].predict_probafs(fsdataset);
double error=0.0;
double correct=0.0;
double max=Double.MIN_VALUE;
//iterate through predictions
for (int m=0; m <predictions.GetRowDimension(); m++ ){
max=Double.MIN_VALUE;
classification[m]=0;
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
error+=(1.0-predictions.GetElement(m, j));
correct+=predictions.GetElement(m, j);
}
if (predictions.GetElement(m, j)>max){
max=predictions.GetElement(m, j);
classification[m]=j;
}
}}
weight=new double[this.weights.length];
for (int m=0; m <predictions.GetRowDimension(); m++ ){
weight[m]=this.weight_thresold;
}
double adjust=correct/error;
for (int m=0; m <predictions.GetRowDimension(); m++ ){
if (fstarget[m]!=classification[m]){
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
weight[m]+= predictions.GetElement(m, j)*adjust ;
}
}
}
}
// if error too big or too small , stop.
if((error>=correct || error==0.0) && n!=1){
if(this.verbose){
System.err.println(" Process stopped pre-maturely with error: " + error);
System.err.println(" Process stopped pre-maturely with correct: " + correct);
System.err.println(" Process stopped pre-maturely with adjestment: " + adjust);
}
break;
}
//Assign new coefficient
coeffs[n] = Math.log((correct) / error);//*shrinkage;
if (verbose) {
System.out.println(" Iteration: "+ n+ " with error: " + error + " and correct: " + correct);
}
}
for (int i=0; i <ensemble_size; i++){
double importances[]=tree_body[i].get_importances();
for (int j=0; j < importances.length; j++){
feature_importances[j]+=importances[j];
}
}
double sum_importances=get_sum(this.feature_importances);
for (int i=0; i <feature_importances.length; i++ ){
feature_importances[i]/=sum_importances;
}
dataset=null;
fsdataset=null;
sdataset=null;
System.gc();
}
@Override
public void fit(fsmatrix data) {
// make sensible checks
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" Main data object is null or has too few cases" );
}
fsdataset=data;
if (max_tree_size<=0){
max_tree_size=Double.MAX_VALUE;
}
if (min_split<2){
min_split=2;
}
if (min_leaf<1){
min_leaf=1;
}
if (max_features<=0){
max_features=1;
}
if (feature_subselection<=0){
feature_subselection=1;
}
if (this.offset<=0){
this.offset=0.0000001;
}
if (cut_off_subsample<=0){
cut_off_subsample=1;
}
if (row_subsample<=0){
row_subsample=1;
}
if (weight_thresold<=0 || weight_thresold>=1){
weight_thresold=0.1;
}
if (this.estimators<1){
estimators=1;
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
// make sensible checks on the target data
if ( (target==null || target.length!=data.GetRowDimension()) && (Starget==null || Starget.length!=data.GetRowDimension()) ){
throw new IllegalStateException(" target array needs to be provided with the same length as the data" );
} else if (target!=null ){
// check if values only 1 and zero
HashSet<Double> has= new HashSet<Double> ();
for (int i=0; i < target.length; i++){
has.add(target[i]);
}
if (has.size()<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
double uniquevalues[]= new double[has.size()];
int k=0;
for (Iterator<Double> it = has.iterator(); it.hasNext(); ) {
uniquevalues[k]= it.next();
k++;
}
// sort values
Arrays.sort(uniquevalues);
classes= new String[uniquevalues.length];
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < uniquevalues.length; j++){
classes[j]=uniquevalues[j]+"";
mapper.put(classes[j], index);
index++;
}
fstarget=new int[target.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(target[i] + "");
}
} else if (Starget!=null && (classes==null || classes.length<=1)){
classes=manipulate.distinct.distinct.getstringDistinctset(Starget);
if (classes.length<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
Arrays.sort(classes);
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < classes.length; j++){
mapper.put(classes[j], index);
index++;
}
fstarget=new int[Starget.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(Starget[i]);
}
}
if (weights==null) {
weights=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weights[i]=1.0;
}
} else {
if (weights.length!=data.GetRowDimension()){
throw new DimensionMismatchException(weights.length,data.GetRowDimension());
}
weights=manipulate.transforms.transforms.scaleweight(weights);
for (int i=0; i < weights.length; i++){
weights[i]*= weights.length;
}
}
//hard copy
if (copy){
data= (fsmatrix) data.Copy();
}
// Initialise randomiser
this.random = new XorShift128PlusRandom(this.seed);
this.n_classes=classes.length;
if (this.Objective.equals("AUC") && (this.n_classes!=2)){
throw new IllegalStateException("The 'AUC' Metric can only be used when n_classes=2" );
}
/**
* generate rows required by the algorithm
*/
/*
if (data.optional_rows==null){
data.void_update_indice();
}
*/
columndimension=data.GetColumnDimension();
feature_importances= new double [columndimension];
if (this.sorted_indices==null){
this.sorted_indices=new int [3] [];
this.maximum_ranks= 0;
this.zero_rank_holder= new int [this.columndimension];
// create indices
sortcolumnsnomap sorty= new sortcolumnsnomap (this.fsdataset,
this.rows,
this.sorted_indices,
this.zero_rank_holder,
this.rounding );
sorty.verbose=this.verbose;
sorty.merge_thresold=this.gamma;
sorty.target_vales=fstarget;
sorty.run();
this.maximum_ranks= sorty.getmaxrank();
}
if (this.verbose){
System.out.println("Sorting is done");
}
//calculate initial estimates
// Initialise the tree structure
this.coeffs=new double [this.estimators];
tree_body= new RandomForestClassifier[this.estimators];
// start the loop to find the support vectors
int targetcolumns=n_classes;
fsmatrix predictions=new fsmatrix(fstarget.length, targetcolumns);
double classification[]=new double [fstarget.length];
double weight[]=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weight[i]= weights[i];
}
ensemble_size=0;
//fsmatrix fstarget_model=new fsmatrix(residuals);
for (int n=0; n <this.estimators; n++ ){
RandomForestClassifier model = new RandomForestClassifier(fsdataset);
//general
model.set_sorted_indices(this.sorted_indices);
model.set_ranked_scores(this.maximum_ranks);
model.set_zero_rank(this.zero_rank_holder);
model.internal_threads=this.threads;
model.verbose=false;
model.estimators=this.trees;
model.copy=false;
model.cut_off_subsample=this.cut_off_subsample;
model.feature_subselection=this.feature_subselection;
if (this.rows!=null){
model.set_rows(this.rows);
}
if (this.columns!=null){
model.set_columns(this.columns);
}
model.AddClassnames(this.classes);
model.offset=this.offset;
model.gamma=this.gamma;
model.max_depth=this.max_depth;
model.max_features=this.max_features;
model.max_tree_size=-1;
model.min_leaf=this.min_leaf;
model.bootsrap=this.bootsrap;
model.min_split=this.min_split;
model.Objective=this.Objective;
model.row_subsample=this.row_subsample;
model.seed=this.seed+ n;
model.weights=weight;
model.rounding=this.rounding;
model.fstarget=this.fstarget;
tree_body[n]=model;
model.fit(fsdataset);
ensemble_size+=1;
predictions=tree_body[n].predict_probafs(fsdataset);
double error=0.0;
double correct=0.0;
double max=Double.MIN_VALUE;
//iterate through predictions
for (int m=0; m <predictions.GetRowDimension(); m++ ){
max=Double.MIN_VALUE;
classification[m]=0;
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
error+=(1.0-predictions.GetElement(m, j));
correct+=predictions.GetElement(m, j);
}
if (predictions.GetElement(m, j)>max){
max=predictions.GetElement(m, j);
classification[m]=j;
}
}}
weight=new double[this.weights.length];
for (int m=0; m <predictions.GetRowDimension(); m++ ){
weight[m]=this.weight_thresold;
}
double adjust=correct/error;
for (int m=0; m <predictions.GetRowDimension(); m++ ){
if (fstarget[m]!=classification[m]){
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
weight[m]+= predictions.GetElement(m, j)*adjust ;
}
}
}
}
// if error too big or too small , stop.
//Assign new coefficient
coeffs[n] = Math.log((correct) / error);//*shrinkage;
if((error>=correct || error==0.0) && n!=1){
if(this.verbose){
System.err.println(" Process stopped pre-maturely with error: " + error);
System.err.println(" Process stopped pre-maturely with correct: " + correct);
System.err.println(" Process stopped pre-maturely with adjestment: " + adjust);
}
break;
}
if (verbose) {
System.out.println(" Iteration: "+ n+ " with error: " + error + " and correct: " + correct);
}
}
for (int i=0; i <ensemble_size; i++){
double importances[]=tree_body[i].get_importances();
for (int j=0; j < importances.length; j++){
feature_importances[j]+=importances[j];
}
}
double sum_importances=get_sum(this.feature_importances);
for (int i=0; i < feature_importances.length; i++ ){
feature_importances[i]/=sum_importances;
}
fsdataset=null;
sdataset=null;
System.gc();
}
@Override
public void fit(smatrix data) {
// make sensible checks
if (data==null || data.GetRowDimension()<=0){
throw new IllegalStateException(" Main data object is null or has too few cases" );
}
sdataset=data;
if (max_tree_size<=0){
max_tree_size=Double.MAX_VALUE;
}
if (min_split<2){
min_split=2;
}
if (min_leaf<1){
min_leaf=1;
}
if (max_features<=0){
max_features=1;
}
if (feature_subselection<=0){
feature_subselection=1;
}
if (this.offset<=0){
this.offset=0.0000001;
}
if (cut_off_subsample<=0){
cut_off_subsample=1;
}
if (row_subsample<=0){
row_subsample=1;
}
if (weight_thresold<=0 || weight_thresold>=1){
weight_thresold=0.1;
}
if (this.estimators<1){
estimators=1;
}
if (this.threads<=0){
this.threads=Runtime.getRuntime().availableProcessors();
if (this.threads<1){
this.threads=1;
}
}
// make sensible checks on the target data
if ( (target==null || target.length!=data.GetRowDimension()) && (Starget==null || Starget.length!=data.GetRowDimension()) ){
throw new IllegalStateException(" target array needs to be provided with the same length as the data" );
} else if (target!=null ){
// check if values only 1 and zero
HashSet<Double> has= new HashSet<Double> ();
for (int i=0; i < target.length; i++){
has.add(target[i]);
}
if (has.size()<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
double uniquevalues[]= new double[has.size()];
int k=0;
for (Iterator<Double> it = has.iterator(); it.hasNext(); ) {
uniquevalues[k]= it.next();
k++;
}
// sort values
Arrays.sort(uniquevalues);
classes= new String[uniquevalues.length];
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < uniquevalues.length; j++){
classes[j]=uniquevalues[j]+"";
mapper.put(classes[j], index);
index++;
}
fstarget=new int[target.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(target[i] + "");
}
} else if (Starget!=null && (classes==null || classes.length<=1)){
classes=manipulate.distinct.distinct.getstringDistinctset(Starget);
if (classes.length<=1){
throw new IllegalStateException(" target array needs to have more 2 or more classes" );
}
Arrays.sort(classes);
StringIntMap4a mapper = new StringIntMap4a(classes.length,0.5F);
int index=0;
for (int j=0; j < classes.length; j++){
mapper.put(classes[j], index);
index++;
}
fstarget=new int[Starget.length];
for (int i=0; i < fstarget.length; i++){
fstarget[i]=mapper.get(Starget[i]);
}
}
if (weights==null) {
weights=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weights[i]=1.0;
}
} else {
if (weights.length!=data.GetRowDimension()){
throw new DimensionMismatchException(weights.length,data.GetRowDimension());
}
weights=manipulate.transforms.transforms.scaleweight(weights);
for (int i=0; i < weights.length; i++){
weights[i]*= weights.length;
}
}
//hard copy
if (copy){
data= (smatrix) data.Copy();
}
// Initialise randomiser
sdataset.trim();
if (!this.sdataset.IsSortedByRow()){
this.sdataset.convert_type();
//System.out.println("built sort");
}
this.random = new XorShift128PlusRandom(this.seed);
this.n_classes=classes.length;
if (this.Objective.equals("AUC") && (this.n_classes!=2)){
throw new IllegalStateException("The 'AUC' Metric can only be used when n_classes=2" );
}
/**
* generate rows required by the algorithm
*/
/*
if (data.optional_rows==null){
data.void_update_indice();
}
*/
columndimension=data.GetColumnDimension();
feature_importances= new double [columndimension];
if (this.sorted_indices==null){
this.sorted_indices=new int [3] [];
this.maximum_ranks= 0;
this.zero_rank_holder= new int [this.columndimension];
// create indices
sortcolumnsnomap sorty= new sortcolumnsnomap (this.sdataset,
this.rows,
this.sorted_indices,
this.zero_rank_holder,
this.rounding );
sorty.verbose=this.verbose;
sorty.merge_thresold=this.gamma;
sorty.target_vales=fstarget;
sorty.run();
this.maximum_ranks= sorty.getmaxrank();
}
if (this.verbose){
System.out.println("Sorting is done");
}
//calculate initial estimates
// Initialise the tree structure
this.coeffs=new double [this.estimators];
tree_body= new RandomForestClassifier[this.estimators];
// start the loop to find the support vectors
int targetcolumns=n_classes;
fsmatrix predictions=new fsmatrix(fstarget.length, targetcolumns);
double classification[]=new double [fstarget.length];
double weight[]=new double [fstarget.length];
for (int i=0; i < weights.length; i++){
weight[i]= weights[i];
}
ensemble_size=0;
//fsmatrix fstarget_model=new fsmatrix(residuals);
for (int n=0; n <this.estimators; n++ ){
RandomForestClassifier model = new RandomForestClassifier(sdataset);
//general
model.set_sorted_indices(this.sorted_indices);
model.set_ranked_scores(this.maximum_ranks);
model.set_zero_rank(this.zero_rank_holder);
model.internal_threads=this.threads;
model.verbose=false;
model.rounding=this.rounding;
model.estimators=this.trees;
model.copy=false;
model.cut_off_subsample=this.cut_off_subsample;
model.feature_subselection=this.feature_subselection;
if (this.rows!=null){
model.set_rows(this.rows);
}
if (this.columns!=null){
model.set_columns(this.columns);
}
model.AddClassnames(this.classes);
model.offset=this.offset;
model.gamma=this.gamma;
model.max_depth=this.max_depth;
model.max_features=this.max_features;
model.max_tree_size=-1;
model.bootsrap=this.bootsrap;
model.min_leaf=this.min_leaf;
model.min_split=this.min_split;
model.Objective=this.Objective;
model.row_subsample=this.row_subsample;
model.seed=this.seed+ n;
model.weights=weight; // add the weights
model.fstarget=this.fstarget;
tree_body[n]=model;
model.fit(sdataset);
ensemble_size+=1;
predictions=tree_body[n].predict_probafs(sdataset);
double error=0.0;
double correct=0.0;
double max=Double.MIN_VALUE;
//iterate through predictions
for (int m=0; m <predictions.GetRowDimension(); m++ ){
max=Double.MIN_VALUE;
classification[m]=0;
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
error+=(1.0-predictions.GetElement(m, j));
correct+=predictions.GetElement(m, j);
}
if (predictions.GetElement(m, j)>max){
max=predictions.GetElement(m, j);
classification[m]=j;
}
}}
weight=new double[this.weights.length];
for (int m=0; m <predictions.GetRowDimension(); m++ ){
weight[m]=this.weight_thresold;
}
double adjust=correct/error;
for (int m=0; m <predictions.GetRowDimension(); m++ ){
if (fstarget[m]!=classification[m]){
for (int j=0; j<targetcolumns; j++ ){
if (fstarget[m]==j){
weight[m]+= predictions.GetElement(m, j)*adjust ;
}
}
}
}
// if error too big or too small , stop.
if((error>=correct || error==0.0) && n!=1){
if(this.verbose){
System.err.println(" Process stopped pre-maturely with error: " + error);
System.err.println(" Process stopped pre-maturely with correct: " + correct);
System.err.println(" Process stopped pre-maturely with adjestment: " + adjust);
}
break;
}
//Assign new coefficient
coeffs[n] = Math.log((correct) / error);//*shrinkage;
if (verbose) {
System.out.println(" Iteration: "+ n+ " with error: " + error + " and correct: " + correct);
}
}
for (int i=0; i <ensemble_size; i++){
double importances[]=tree_body[i].get_importances();
for (int j=0; j < importances.length; j++){
feature_importances[j]+=importances[j];
}
}
double sum_importances=get_sum(this.feature_importances);
for (int i=0; i <feature_importances.length; i++ ){
feature_importances[i]/=sum_importances;
}
sdataset=null;
System.gc();
// calculate first node
}
/**
* Retrieve the number of target variables
*/
public int getnumber_of_targets(){
return n_classes;
}
public double get_sum(double array []){
double a=0.0;
for (int i=0; i <array.length; i++ ){
a+=array[i];
}
return a;
}
/**
*
* @returns the closest integer that reflects this percentage!
* <p> it may sound strange, random.nextint can be significantly faster than nextdouble()
*/
public int get_random_integer(double percentage){
double per= Math.min(Math.max(0, percentage),1.0);
double difference=2147483647.0+(2147483648.0);
int point=(int)(-2147483648.0 + (per*difference ));
return point;
}
@Override
public String GetType() {
return "classifier";
}
@Override
public boolean SupportsWeights() {
return true;
}
@Override
public String GetName() {
return "AdaboostRandomForestClassifier";
}
@Override
public void PrintInformation() {
System.out.println("Classifier: AdaboostRandomForestClassifier");
System.out.println("Classes: " + n_classes);
System.out.println("Supports Weights: True");
System.out.println("Column dimension: " + columndimension);
System.out.println("Estimators: " + this.estimators);
System.out.println("Bootsrapping: " + this.bootsrap);
System.out.println("cut_off_subsample: "+ this.cut_off_subsample);
System.out.println("Objective: "+ this.Objective);
System.out.println("feature_subselection: "+ this.feature_subselection);
System.out.println("gamma: "+ this.gamma);
//System.out.println("Shrinkage: "+ this.shrinkage);
System.out.println("max_depth: "+ this.max_depth);
System.out.println("weight thresold: "+ this.weight_thresold);
System.out.println("offset: "+ this.offset);
System.out.println("rounding: "+ this.rounding);
System.out.println("trees: "+ this.trees);
System.out.println("max_features : "+ this.max_features);
System.out.println("max_tree_size : "+ this.max_tree_size);
System.out.println("min_leaf : "+ this.min_leaf);
System.out.println("min_leaf : "+ this.min_split);
System.out.println("row_subsample : "+ this.row_subsample);
System.out.println("threads : "+ this.threads);
System.out.println("Seed: "+ seed);
System.out.println("Verbality: "+ verbose);
if (this.tree_body==null){
System.out.println("Trained: False");
} else {
System.out.println("Trained: True");
}
}
@Override
public boolean HasTheSametype(estimator a) {
if (a.GetType().equals(this.GetType())){
return true;
} else {
return false;
}
}
@Override
public boolean isfitted() {
if (this.tree_body!=null || tree_body.length>0){
return true;
} else {
return false;
}
}
@Override
public boolean IsRegressor() {
return false ;
}
@Override
public boolean IsClassifier() {
return true;
}
@Override
public void reset() {
this.tree_body= null;
n_classes=0;
Objective="ENTROPY";
threads=1;
this.estimators=10;
this.bootsrap=false;
this.columns=null;
this.random=null;
this.cut_off_subsample=1.0;
this.feature_importances.clone();
this.feature_subselection=1.0;
this.gamma=1E-30;
this.max_depth=3;
this.max_features=1.0;
this.max_tree_size=-1;
this.min_leaf=1.0;
this.min_split=2.0;
this.row_subsample=1.0;
this.weight_thresold=0.1;
columndimension=0;
this.classes=null;
copy=true;
seed=1;
this.rounding=30;
this.offset=0.0001;
this.trees=1;
random=null;
target=null;
fstarget=null;
target=null;
fstarget=null;
starget=null;
weights=null;
verbose=true;
coeffs=null;
}
@Override
public estimator copy() {
AdaboostRandomForestClassifier br = new AdaboostRandomForestClassifier();
RandomForestClassifier[] tree_bodys= new RandomForestClassifier[this.tree_body.length];
for (int i=0; i <tree_bodys.length; i++ ){
tree_bodys[i]=(RandomForestClassifier) tree_body[i].copy();
}
br.tree_body=tree_bodys;
br.estimators=this.estimators;
br.bootsrap=this.bootsrap;
//br.shrinkage=this.shrinkage;
br.trees=this.trees;
br.n_classes=this.n_classes;
br.rounding=this.rounding;
br.offset=this.offset;
br.trees=this.trees;
br.columns=this.columns.clone();
br.cut_off_subsample=this.cut_off_subsample;
br.feature_importances=this.feature_importances.clone();
br.feature_subselection=this.feature_subselection;
br.gamma=this.gamma;
br.max_depth=this.max_depth;
br.weight_thresold=this.weight_thresold;
br.max_features=this.max_features;
br.max_tree_size=this.max_tree_size;
br.Objective=this.Objective;
br.min_leaf=this.min_leaf;
br.min_split=this.min_split;
br.row_subsample=this.row_subsample;
br.threads=this.threads;
br.columndimension=this.columndimension;
br.copy=this.copy;
br.seed=this.seed;
br.random=this.random;
br.ensemble_size=this.ensemble_size;
br.coeffs=manipulate.copies.copies.Copy(this.coeffs.clone());
br.target=manipulate.copies.copies.Copy(this.target.clone());
br.target2d=manipulate.copies.copies.Copy(this.target2d.clone());
br.fstarget=(this.fstarget.clone());
br.starget=(smatrix) this.starget.Copy();
br.weights=manipulate.copies.copies.Copy(this.weights.clone());
br.verbose=this.verbose;
return br;
}
@Override
public void set_params(String params){
String splitted_params []=params.split(" " + "+");
for (int j=0; j<splitted_params.length; j++ ){
String mini_split []=splitted_params[j].split(":");
if (mini_split.length>=2){
String metric=mini_split[0];
String value=mini_split[1];
if (metric.equals("cut_off_subsample")) {this.cut_off_subsample=Double.parseDouble(value);}
else if (metric.equals("feature_subselection")) {this.feature_subselection=Double.parseDouble(value);}
else if (metric.equals("row_subsample")) {this.row_subsample=Double.parseDouble(value);}
else if (metric.equals("weight_thresold")) {this.weight_thresold=Double.parseDouble(value);}
else if (metric.equals("estimators")) {this.estimators=Integer.parseInt(value);}
else if (metric.equals("min_leaf")) {this.min_leaf=Double.parseDouble(value);}
else if (metric.equals("trees")) {this.trees=Integer.parseInt(value);}
else if (metric.equals("max_depth")) {this.max_depth=Integer.parseInt(value);}
else if (metric.equals("Objective")) {this.Objective=value;}
else if (metric.equals("threads")) {this.threads=Integer.parseInt(value);}
else if (metric.equals("rounding")) {this.rounding=Double.parseDouble(value);}
else if (metric.equals("offset")) {this.offset=Double.parseDouble(value);}
else if (metric.equals("max_tree_size")) {this.max_tree_size=Integer.parseInt(value);}
else if (metric.equals("gamma")) {this.gamma=Double.parseDouble(value);}
else if (metric.equals("max_features")) {this.max_features=Double.parseDouble(value);}
else if (metric.equals("bootsrap")) {this.bootsrap=(value.toLowerCase().equals("true")?true:false);}
else if (metric.equals("min_split")) {this.min_split=Double.parseDouble(value);}
else if (metric.equals("copy")) {this.copy=(value.toLowerCase().equals("true")?true:false);}
else if (metric.equals("seed")) {this.seed=Integer.parseInt(value);}
else if (metric.equals("verbose")) {this.verbose=(value.toLowerCase().equals("true")?true:false) ;}
}
}
}
@Override
public scaler ReturnScaler() {
return null;
}
@Override
public void setScaler(scaler sc) {
}
@Override
public void setSeed(int seed) {
this.seed=seed;}
@Override
public void set_target(double data []){
if (data==null || data.length<=0){
throw new IllegalStateException(" There is nothing to train on" );
}
this.target=data;
}
/**
*
* @param previous_predictions : Previous predictions
* @param new_predictions : New predictions to be added to the new ones
*/
public void append_predictions_score(double previous_predictions [][], fsmatrix new_predictions , double shrink){
if (new_predictions.GetColumnDimension()==1){
for (int i=0; i <previous_predictions.length; i++ ){
previous_predictions[i][0]+= new_predictions.GetElement(i, 0)*shrink;
}
}else {
for (int i=0; i <previous_predictions.length; i++ ){
for (int j=0; j <previous_predictions[0].length; j++ ){
previous_predictions[i][j]+= new_predictions.GetElement(i, j)*shrink;
}
}
}
}
/**
*
* @param previous_predictions : Previous predictions
* @param new_predictions : New predictions to be added to the new ones
*/
public void append_predictions(double previous_predictions [][], double new_predictions [][], double shrink){
if (previous_predictions.length==1){
for (int i=0; i <previous_predictions[0].length; i++ ){
previous_predictions[0][i]+= new_predictions[i][0]*shrink;
}
}else {
for (int i=0; i <previous_predictions[0].length; i++ ){
for (int j=0; j <previous_predictions.length; j++ ){
previous_predictions[j][i]+= new_predictions[i][j]*shrink;
}
}
}
}
/**
*
* @param previous_predictions : Previous predictions
* @param new_predictions : New predictions to be added to the new ones
*/
public void append_predictions_score(double previous_predictions [][], double new_predictions [][], double shrink){
if (new_predictions[0].length==1){
for (int i=0; i <previous_predictions.length; i++ ){
for (int j=0; j <previous_predictions[0].length; j++ ){
previous_predictions[i][0]+= new_predictions[i][0]*shrink;
}
}
}else {
for (int i=0; i <previous_predictions.length; i++ ){
for (int j=0; j <previous_predictions[0].length; j++ ){
previous_predictions[i][j]+= new_predictions[i][j]*shrink;
}
}
}
}
/**
*
* @param previous_predictions : Previous predictions
* @param new_predictions : New predictions to be added to the new ones
*/
public void append_predictions_score(double previous_predictions [], double new_predictions [], double shrink){
if (new_predictions.length==1){
for (int j=0; j <previous_predictions.length; j++ ){
previous_predictions[0]+= new_predictions[0]*shrink;
}
}else {
for (int j=0; j <previous_predictions.length; j++ ){
previous_predictions[j]+= new_predictions[j]*shrink;
}
}
}
/**
*
* @param previous_predictions : raw scores output to be transformed into probabilities
*/
public void scale_scores(double previous_predictions [][]){
for (int i=0; i <previous_predictions.length; i++ ){
double sum=0.0;
for (int j = 0; j < previous_predictions[0].length; j++) {
sum += previous_predictions[i][j];
}
for (int j = 0; j < previous_predictions[0].length; j++) {
previous_predictions[i][j] /= sum;
}
}
}
/**
*
* @param previous_predictions : raw scores output to be transformed into probabilities
*/
public int scale_scores(double previous_predictions []){
double sum=0.0;
double max=Double.MIN_VALUE;
int cla=-1;
for (int j = 0; j < previous_predictions.length; j++) {
if (previous_predictions[j]>max ){
max=previous_predictions[j];
cla=j;
}
}
for (int j = 0; j < previous_predictions.length; j++) {
previous_predictions[j] = Math.exp(previous_predictions[j] - max);
sum += previous_predictions[j];
}
for (int j = 0; j < previous_predictions.length; j++) {
previous_predictions[j] /= sum;
}
return cla;
}
@Override
public int getSeed() {
return this.seed;}
}
|
3e09ae5d7ccc76ffbb6ecf91a891f65fed2d87eb | 2,842 | java | Java | lab9/code/app/src/main/java/com/example/getwebpagesourcecode/MainActivity.java | Wuruoyu1/IntelligentMobileDevelopment | ada01f961fe343950b0ca4564826278cf299242f | [
"BSD-3-Clause"
] | null | null | null | lab9/code/app/src/main/java/com/example/getwebpagesourcecode/MainActivity.java | Wuruoyu1/IntelligentMobileDevelopment | ada01f961fe343950b0ca4564826278cf299242f | [
"BSD-3-Clause"
] | null | null | null | lab9/code/app/src/main/java/com/example/getwebpagesourcecode/MainActivity.java | Wuruoyu1/IntelligentMobileDevelopment | ada01f961fe343950b0ca4564826278cf299242f | [
"BSD-3-Clause"
] | null | null | null | 33.833333 | 89 | 0.679451 | 4,083 | package com.example.getwebpagesourcecode;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
private String prefix = "http://";
private EditText mWebLocation;
private EditText mScrollTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebLocation = (EditText) findViewById(R.id.web_location_text);
mScrollTextView = (EditText) findViewById(R.id.scroll_edittext);
// Spinner
Spinner spinner = (Spinner) findViewById(R.id.http_spinner);
if (spinner != null) {
spinner.setOnItemSelectedListener(this);
}
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.http_or_https, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
if (spinner != null) {
spinner.setAdapter(adapter);
}
}
private String getWebString() {
return prefix + mWebLocation.getText().toString();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefix = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void getWebSource(View view) {
String queryString = getWebString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null ) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
NetworkInfo networkInfo = null;
if (connMgr != null) {
networkInfo = connMgr.getActiveNetworkInfo();
}
if (networkInfo != null && networkInfo.isConnected()
&& queryString.length() != 0) {
new FetchSource(mScrollTextView).execute(queryString);
mScrollTextView.setText(R.string.loading);
} else {
mScrollTextView.setText(R.string.no_network);
}
}
} |
3e09aee1d3db78e851067f4b8057b085e9efffe8 | 1,766 | java | Java | src/main/java/com/miscitems/MiscItemsAndBlocks/Gui/Machines/GuiTrashBin.java | tm1990/MiscItemsAndBlocks-Source-Code | 5cbaa12f507cc4f56b5ba9ac238cbe99fb02eb30 | [
"MIT"
] | null | null | null | src/main/java/com/miscitems/MiscItemsAndBlocks/Gui/Machines/GuiTrashBin.java | tm1990/MiscItemsAndBlocks-Source-Code | 5cbaa12f507cc4f56b5ba9ac238cbe99fb02eb30 | [
"MIT"
] | 1 | 2015-01-06T16:27:39.000Z | 2015-01-06T17:50:13.000Z | src/main/java/com/miscitems/MiscItemsAndBlocks/Gui/Machines/GuiTrashBin.java | tm1990/MiscItemsAndBlocks-Source-Code | 5cbaa12f507cc4f56b5ba9ac238cbe99fb02eb30 | [
"MIT"
] | null | null | null | 29.932203 | 122 | 0.741223 | 4,084 | package com.miscitems.MiscItemsAndBlocks.Gui.Machines;
import MiscUtils.GuiObjects.GuiTipButton;
import com.miscitems.MiscItemsAndBlocks.Container.ContainerBin;
import com.miscitems.MiscItemsAndBlocks.TileEntity.Machines.TileEntityTrashBin;
import com.miscitems.MiscItemsAndBlocks.Utils.References.Messages;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
public class GuiTrashBin extends GuiContainer{
TileEntityTrashBin tile = new TileEntityTrashBin();
private final ResourceLocation Texture = new ResourceLocation("miscitems" , "textures/gui/BinGui.png");
public GuiTrashBin(InventoryPlayer InvPlayer, TileEntityTrashBin tile) {
super(new ContainerBin(InvPlayer, tile));
xSize = 197;
ySize = 166;
}
@Override
protected void drawGuiContainerForegroundLayer(int param1, int param2) {
fontRendererObj.drawString(StatCollector.translateToLocal("container.inventory"), 8, ySize - 96 + 2, 4210752);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.trashbin"), 7, 3, 4210752);
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int X, int Y)
{
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
Minecraft.getMinecraft().renderEngine.bindTexture(Texture);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
}
@Override
public void initGui(){
super.initGui();
buttonList.clear();
buttonList.add(new GuiTipButton(1, guiLeft, guiTop, "?", Messages.TrashBinTips));
}
}
|
3e09af3a620e6392cc201f861520abc7201acc9d | 1,234 | java | Java | src/main/java/com/supyuan/util/ImageTools.java | MichardChen/jadmin | 052dee802541d8d943bc1af982ce928f46f1ecc5 | [
"MIT"
] | 1 | 2018-02-16T00:29:38.000Z | 2018-02-16T00:29:38.000Z | src/main/java/com/supyuan/util/ImageTools.java | MichardChen/jadmin | 052dee802541d8d943bc1af982ce928f46f1ecc5 | [
"MIT"
] | null | null | null | src/main/java/com/supyuan/util/ImageTools.java | MichardChen/jadmin | 052dee802541d8d943bc1af982ce928f46f1ecc5 | [
"MIT"
] | null | null | null | 24.196078 | 51 | 0.487034 | 4,085 | package com.supyuan.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class ImageTools {
/**
* 获取图片宽度
* @param file 图片文件
* @return 宽度
*/
public static int getImgWidth(File file) {
InputStream is = null;
BufferedImage src = null;
int ret = -1;
try {
is = new FileInputStream(file);
src = javax.imageio.ImageIO.read(is);
ret = src.getWidth(null); // 得到源图宽
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* 获取图片高度
* @param file 图片文件
* @return 高度
*/
public static int getImgHeight(File file) {
InputStream is = null;
BufferedImage src = null;
int ret = -1;
try {
is = new FileInputStream(file);
src = javax.imageio.ImageIO.read(is);
ret = src.getHeight(null); // 得到源图高
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
|
3e09af7c306116c6702944022fa03cd602cfc984 | 2,040 | java | Java | src/test/java/com/deemkeen/quarkus/DynamoDBClientIT.java | devk-insurance/quarkus-amazon-lambda | 9f0dae294fef6287601493d5aa4b5722cb0bc49b | [
"Apache-2.0"
] | 5 | 2019-07-18T09:04:42.000Z | 2021-07-27T03:26:53.000Z | src/test/java/com/deemkeen/quarkus/DynamoDBClientIT.java | devk-insurance/quarkus-amazon-lambda | 9f0dae294fef6287601493d5aa4b5722cb0bc49b | [
"Apache-2.0"
] | 2 | 2019-07-15T14:35:52.000Z | 2019-07-15T14:39:43.000Z | src/test/java/com/deemkeen/quarkus/DynamoDBClientIT.java | devk-insurance/quarkus-amazon-lambda | 9f0dae294fef6287601493d5aa4b5722cb0bc49b | [
"Apache-2.0"
] | 1 | 2020-01-23T05:04:00.000Z | 2020-01-23T05:04:00.000Z | 25.5 | 92 | 0.690686 | 4,086 | package com.deemkeen.quarkus;
import com.deemkeen.quarkus.handler.DynamoDao;
import com.deemkeen.quarkus.lambda.*;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.wildfly.common.Assert;
import javax.inject.Inject;
import javax.json.bind.Jsonb;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
@QuarkusTest
class DynamoDBClientIT {
private static final Logger LOGGER = Logger.getLogger(DynamoDBClientIT.class.getName());
@Inject
HelloSaveLambda helloSaveFunction;
//@Inject
//HelloDeleteLambda helloDeleteFunction;
@Inject
HelloFindLambda helloFindFunction;
@Inject
Jsonb jsonb;
@Inject
DynamoDao dynamoDao;
@Test
void testDynamoHelloSave() throws Exception{
HelloSaveRequest testRequest = new HelloSaveRequest();
testRequest.setFirstName("John");
testRequest.setLastName("Doh");
String message = jsonb.toJson(testRequest);
String process = helloSaveFunction.process(message);
Assert.assertNotNull(process);
LOGGER.info(process);
}
/*@Test
void testDynamoHelloDelete() {
HelloDeleteRequest testRequest = new HelloDeleteRequest();
testRequest.setId("fakeId");
String message = jsonb.toJson(testRequest);
helloDeleteFunction.process(message);
}*/
@Test
void testGetDao(){
List<HelloDynamoResponse> byLimit = dynamoDao.findByLimit(10);
LOGGER.info(byLimit.toString());
String singleId = byLimit.get(0).getId();
HelloDynamoResponse single = dynamoDao.find(singleId);
LOGGER.info(single.toString());
}
@Test
void testDynamoHelloFind() throws Exception{
Map<String,String> testMap = new HashMap<>();
testMap.put("id", "9bd90583-8e39-47df-ad78-3c053a760035");
String json = jsonb.toJson(testMap);
String process = helloFindFunction.process(json);
LOGGER.info(process);
}
} |
3e09b000e9a48713a18d915d9b5cd8f51596d678 | 558 | java | Java | git-agent/src/jetbrains/buildServer/buildTriggers/vcs/git/agent/command/RevParseCommand.java | JetBrains/teamcity- | 407af42b9d6544bfde1d9a457486cd80829336fc | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 6 | 2020-07-23T12:21:45.000Z | 2021-11-08T09:50:23.000Z | git-agent/src/jetbrains/buildServer/buildTriggers/vcs/git/agent/command/RevParseCommand.java | JetBrains/teamcity- | 407af42b9d6544bfde1d9a457486cd80829336fc | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | git-agent/src/jetbrains/buildServer/buildTriggers/vcs/git/agent/command/RevParseCommand.java | JetBrains/teamcity- | 407af42b9d6544bfde1d9a457486cd80829336fc | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 3 | 2021-06-01T14:02:06.000Z | 2022-03-18T10:16:27.000Z | 26.571429 | 71 | 0.793907 | 4,087 | package jetbrains.buildServer.buildTriggers.vcs.git.agent.command;
import jetbrains.buildServer.buildTriggers.vcs.git.command.BaseCommand;
import jetbrains.buildServer.vcs.VcsException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface RevParseCommand extends BaseCommand {
@NotNull
RevParseCommand setRef(String ref);
@NotNull
RevParseCommand setShallow(boolean isShallow);
@NotNull
RevParseCommand verify(String param);
@Nullable
String call() throws VcsException;
}
|
3e09b00cd2b1e84dc687022665cb3cec9b754f7b | 2,483 | java | Java | dspace-api/src/main/java/org/dspace/app/orcid/service/impl/OrcidProfileSectionFactoryServiceImpl.java | steph-ieffam/DSpace | fdcd064f7de8d39859f267b681e3aa9cd06f6d91 | [
"BSD-3-Clause"
] | 35 | 2016-09-27T14:34:43.000Z | 2021-12-15T11:20:31.000Z | dspace-api/src/main/java/org/dspace/app/orcid/service/impl/OrcidProfileSectionFactoryServiceImpl.java | steph-ieffam/DSpace | fdcd064f7de8d39859f267b681e3aa9cd06f6d91 | [
"BSD-3-Clause"
] | 110 | 2016-09-15T13:49:39.000Z | 2022-02-01T07:00:17.000Z | dspace-api/src/main/java/org/dspace/app/orcid/service/impl/OrcidProfileSectionFactoryServiceImpl.java | steph-ieffam/DSpace | fdcd064f7de8d39859f267b681e3aa9cd06f6d91 | [
"BSD-3-Clause"
] | 81 | 2016-11-28T12:52:20.000Z | 2022-03-07T16:12:20.000Z | 40.048387 | 120 | 0.786549 | 4,088 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.orcid.service.impl;
import static java.util.stream.Collectors.toMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.dspace.app.orcid.model.OrcidProfileSectionType;
import org.dspace.app.orcid.model.factory.OrcidProfileSectionFactory;
import org.dspace.app.orcid.service.OrcidProfileSectionFactoryService;
import org.dspace.app.profile.OrcidProfileSyncPreference;
import org.dspace.content.MetadataValue;
import org.dspace.core.Context;
/**
* Implementation of {@link OrcidProfileSectionFactoryService}.
*
* @author Luca Giamminonni (luca.giamminonni at 4science.it)
*
*/
public class OrcidProfileSectionFactoryServiceImpl implements OrcidProfileSectionFactoryService {
private final Map<OrcidProfileSectionType, OrcidProfileSectionFactory> sectionFactories;
private OrcidProfileSectionFactoryServiceImpl(List<OrcidProfileSectionFactory> sectionFactories) {
this.sectionFactories = sectionFactories.stream()
.collect(toMap(OrcidProfileSectionFactory::getProfileSectionType, Function.identity()));
}
@Override
public Optional<OrcidProfileSectionFactory> findBySectionType(OrcidProfileSectionType type) {
return Optional.ofNullable(this.sectionFactories.get(type));
}
@Override
public List<OrcidProfileSectionFactory> findByPreferences(List<OrcidProfileSyncPreference> preferences) {
return filterBy(configuration -> preferences.contains(configuration.getSynchronizationPreference()));
}
@Override
public Object createOrcidObject(Context context, List<MetadataValue> metadataValues, OrcidProfileSectionType type) {
OrcidProfileSectionFactory profileSectionFactory = findBySectionType(type)
.orElseThrow(() -> new IllegalArgumentException("No ORCID profile section factory configured for " + type));
return profileSectionFactory.create(context, metadataValues);
}
private List<OrcidProfileSectionFactory> filterBy(Predicate<OrcidProfileSectionFactory> predicate) {
return sectionFactories.values().stream().filter(predicate).collect(Collectors.toList());
}
}
|
3e09b066bdc10c1cc4b8b0a0a73c37b72bbbbfc8 | 848 | java | Java | flow-tests/test-root-context/src/main/java/com/vaadin/flow/uitest/ui/PushWSUpdateDivView.java | mortensen/flow | c0b2ffb0c5d35df46cf416e195201450c1de9e8a | [
"Apache-2.0"
] | null | null | null | flow-tests/test-root-context/src/main/java/com/vaadin/flow/uitest/ui/PushWSUpdateDivView.java | mortensen/flow | c0b2ffb0c5d35df46cf416e195201450c1de9e8a | [
"Apache-2.0"
] | 10 | 2021-11-16T09:33:53.000Z | 2022-02-26T08:46:21.000Z | flow-tests/test-root-context/src/main/java/com/vaadin/flow/uitest/ui/PushWSUpdateDivView.java | mortensen/flow | c0b2ffb0c5d35df46cf416e195201450c1de9e8a | [
"Apache-2.0"
] | null | null | null | 32.615385 | 80 | 0.762972 | 4,089 | /*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.uitest.ui;
import com.vaadin.flow.component.page.Push;
import com.vaadin.flow.router.Route;
@Push
@Route("com.vaadin.flow.uitest.ui.PushWSUpdateDivView")
public class PushWSUpdateDivView extends AbstractPushUpdateDivView {
}
|
3e09b198bd83b7622bcd2ffacca3c72e302248f5 | 2,726 | java | Java | generated-sources/java-pkmst/mojang-api/src/main/java/com/github/asyncmc/mojang/api/java/pkmst/model/NameChange.java | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/java-pkmst/mojang-api/src/main/java/com/github/asyncmc/mojang/api/java/pkmst/model/NameChange.java | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/java-pkmst/mojang-api/src/main/java/com/github/asyncmc/mojang/api/java/pkmst/model/NameChange.java | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | 25.961905 | 165 | 0.678283 | 4,090 | package com.github.asyncmc.mojang.api.java.pkmst.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Response class to be returned by Api
* @author pkmst
*
*/
/**
* A registered name change.
*/
@ApiModel(description = "A registered name change.")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPKMSTServerCodegen", date = "2020-06-06T04:59:25.087174700-03:00[America/Sao_Paulo]")
public class NameChange {
@JsonProperty("name")
private String name;
@JsonProperty("changedToAt")
private Long changedToAt;
public NameChange name(String name) {
this.name = name;
return this;
}
/**
* The new player name
* @return name
**/
@ApiModelProperty(example = "LordofMC_Playerz", required = true, value = "The new player name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public NameChange changedToAt(Long changedToAt) {
this.changedToAt = changedToAt;
return this;
}
/**
* Time which the name was changed in UNIX Timestamp without milliseconds. Usually absent for the first entry.
* @return changedToAt
**/
@ApiModelProperty(example = "1448677333000", value = "Time which the name was changed in UNIX Timestamp without milliseconds. Usually absent for the first entry.")
public Long getChangedToAt() {
return changedToAt;
}
public void setChangedToAt(Long changedToAt) {
this.changedToAt = changedToAt;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NameChange nameChange = (NameChange) o;
return Objects.equals(this.name, nameChange.name) &&
Objects.equals(this.changedToAt, nameChange.changedToAt);
}
@Override
public int hashCode() {
return Objects.hash(name, changedToAt);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class NameChange {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" changedToAt: ").append(toIndentedString(changedToAt)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e09b26bf971d49029aa6254e7a240ba1c144246 | 508 | java | Java | b2c-parent/b2c-test/src/test/java/org/javamaster/b2c/test/java8/DefaultMethodTest.java | jufeng98/Java-master | 27fc0f39822084bd9ebd7103aaf5a72dfd16e37d | [
"Apache-2.0"
] | 100 | 2019-07-09T05:07:36.000Z | 2022-03-25T10:41:20.000Z | b2c-parent/b2c-test/src/test/java/org/javamaster/b2c/test/java8/DefaultMethodTest.java | yuankang134/java-master | 5884b1582faeefddb8f0cc0a3d7d565bf2090e1d | [
"Apache-2.0"
] | 15 | 2020-03-04T22:58:26.000Z | 2022-03-31T20:57:17.000Z | b2c-parent/b2c-test/src/test/java/org/javamaster/b2c/test/java8/DefaultMethodTest.java | yuankang134/java-master | 5884b1582faeefddb8f0cc0a3d7d565bf2090e1d | [
"Apache-2.0"
] | 54 | 2019-08-31T12:46:56.000Z | 2022-03-29T10:20:16.000Z | 22.086957 | 57 | 0.647638 | 4,091 | package org.javamaster.b2c.test.java8;
import static java.util.stream.Collectors.toList;
import org.javamaster.b2c.test.model.Apple;
import org.junit.Test;
import java.util.List;
/**
* @author yudong
* @date 2019/6/11
*/
public class DefaultMethodTest extends CommonCode {
@Test
public void test() {
List<Apple> heavyApples = apples.stream()
.filter((Apple a) -> a.getWeight() > 150)
.collect(toList());
System.out.println(heavyApples);
}
}
|
3e09b29871c47682b5a93e8128d6e2480908c967 | 1,316 | java | Java | app/models/nanda/Bepalendkenmerk_Diagnose.java | jochumdg/nandanicnoc | 3e1a60ddf3c6ea9c38cc09e81e45a251c11cb869 | [
"Apache-2.0"
] | null | null | null | app/models/nanda/Bepalendkenmerk_Diagnose.java | jochumdg/nandanicnoc | 3e1a60ddf3c6ea9c38cc09e81e45a251c11cb869 | [
"Apache-2.0"
] | null | null | null | app/models/nanda/Bepalendkenmerk_Diagnose.java | jochumdg/nandanicnoc | 3e1a60ddf3c6ea9c38cc09e81e45a251c11cb869 | [
"Apache-2.0"
] | null | null | null | 27.416667 | 162 | 0.672492 | 4,092 | package models.nanda;
import java.util.*;
import javax.persistence.*;
import com.avaje.ebean.Page;
import play.db.ebean.*;
import play.data.format.Formats;
/**
* Company entity managed by Ebean
*/
@Entity
public class Bepalendkenmerk_Diagnose extends Model {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name="bepalendkenmerk_id")
public Bepalendkenmerk bepalendkenmerk;
@ManyToOne
@JoinColumn(name="diagnose_id")
public Diagnose diagnose;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date diagnose_bepalendkenmerk_releasestatus_datum;
public String diagnose_bepalendkenmerk_releasestatus_omschrijving;
/**
* Generic query helper for entity Company with id Long
*/
public static Model.Finder<Long,Bepalendkenmerk_Diagnose> find = new Model.Finder<Long,Bepalendkenmerk_Diagnose>(Long.class, Bepalendkenmerk_Diagnose.class);
public static Page<Bepalendkenmerk_Diagnose> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("diagnose_id", filter)
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
}
|
3e09b36183a13a927ceaf09d1a8e87a667bc8e46 | 1,274 | java | Java | test-forum/src/main/java/com/dranawhite/forum/domain/BoardPO.java | dranawhite/test-java | b911e4afb1eaa40815333bd4aeb4209e21446068 | [
"MIT"
] | null | null | null | test-forum/src/main/java/com/dranawhite/forum/domain/BoardPO.java | dranawhite/test-java | b911e4afb1eaa40815333bd4aeb4209e21446068 | [
"MIT"
] | null | null | null | test-forum/src/main/java/com/dranawhite/forum/domain/BoardPO.java | dranawhite/test-java | b911e4afb1eaa40815333bd4aeb4209e21446068 | [
"MIT"
] | null | null | null | 21.965517 | 90 | 0.67033 | 4,093 | package com.dranawhite.forum.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* @author dranawhite
* @version 1.0.0
*/
public class BoardPO extends BaseDomain {
private static final long serialVersionUID = -155105317432182282L;
private Integer boardId;
private String boardName;
private String boardDesc;
private Integer topicNum;
public Integer getBoardId() {
return boardId;
}
public void setBoardId(Integer boardId) {
this.boardId = boardId;
}
public String getBoardName() {
return boardName;
}
public void setBoardName(String boardName) {
this.boardName = boardName == null ? null : boardName.trim();
}
public String getBoardDesc() {
return boardDesc;
}
public void setBoardDesc(String boardDesc) {
this.boardDesc = boardDesc == null ? null : boardDesc.trim();
}
public Integer getTopicNum() {
return topicNum;
}
public void setTopicNum(Integer topicNum) {
this.topicNum = topicNum;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
} |
3e09b38899435971afd76b34f20a5d11383a71a1 | 5,318 | java | Java | src/main/java/com/yunnex/ops/erp/modules/store/basic/entity/ErpStoreCredentials.java | 13802706376/wxapp-web-erp | b3f04eb147611f8e0913954f43f9757412efb423 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yunnex/ops/erp/modules/store/basic/entity/ErpStoreCredentials.java | 13802706376/wxapp-web-erp | b3f04eb147611f8e0913954f43f9757412efb423 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yunnex/ops/erp/modules/store/basic/entity/ErpStoreCredentials.java | 13802706376/wxapp-web-erp | b3f04eb147611f8e0913954f43f9757412efb423 | [
"Apache-2.0"
] | null | null | null | 30.739884 | 596 | 0.68522 | 4,094 | package com.yunnex.ops.erp.modules.store.basic.entity;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yunnex.ops.erp.common.persistence.DataEntity;
/**
* 商户营业资质信息Entity
*
* @author yunnex
* @version 2017-12-09
*/
public class ErpStoreCredentials extends DataEntity<ErpStoreCredentials> {
private static final long serialVersionUID = 1L;
private String registerName; // 注册名称
private String registerNo; // 注册号
private String registerCity; // 注册城市
private String registerAddress; // 注册地址
private Integer businessScope; // 经营范围
private Date startDate; // 资质有效期起始日期
private Date endDate; // 资质有效期结束日期
private Integer isLongTime = 0; // 资质是否是长期有效,0:否,1:是,默认0
private String organizationCodeCertificateNo; // 组织机构代码证号
private String organizationCodeCertificate; // 组织机构代码证
private String businessLicence; // 营业执照
private String specialCertificate; // 特殊资质
private String erpStoreInfoId;// 门店基本信息ID
private String finishStatus;// 资料完成状态,1:未进行,2:未完成,3:当前页面,4:已完成
public ErpStoreCredentials() {
super();
}
public ErpStoreCredentials(String id) {
super(id);
}
@Length(min = 0, max = 64, message = "注册名称长度必须介于 0 和 64 之间")
public String getRegisterName() {
return registerName;
}
public void setRegisterName(String registerName) {
this.registerName = registerName;
}
@Length(min = 0, max = 30, message = "注册号长度必须介于 0 和 30 之间")
public String getRegisterNo() {
return registerNo;
}
public void setRegisterNo(String registerNo) {
this.registerNo = registerNo;
}
@Length(min = 0, max = 30, message = "注册城市长度必须介于 0 和 30 之间")
public String getRegisterCity() {
return registerCity;
}
public void setRegisterCity(String registerCity) {
this.registerCity = registerCity;
}
@Length(min = 0, max = 64, message = "注册地址长度必须介于 0 和 64 之间")
public String getRegisterAddress() {
return registerAddress;
}
public void setRegisterAddress(String registerAddress) {
this.registerAddress = registerAddress;
}
public Integer getBusinessScope() {
return businessScope;
}
public void setBusinessScope(Integer businessScope) {
this.businessScope = businessScope;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@NotNull(message = "资质是否是长期有效,0:否,1:是,默认0不能为空")
public Integer getIsLongTime() {
return isLongTime;
}
public void setIsLongTime(Integer isLongTime) {
this.isLongTime = isLongTime;
}
@Length(min = 0, max = 64, message = "组织机构代码证号长度必须介于 0 和 64 之间")
public String getOrganizationCodeCertificateNo() {
return organizationCodeCertificateNo;
}
public void setOrganizationCodeCertificateNo(String organizationCodeCertificateNo) {
this.organizationCodeCertificateNo = organizationCodeCertificateNo;
}
@Length(min = 0, max = 128, message = "组织机构代码证长度必须介于 0 和 128 之间")
public String getOrganizationCodeCertificate() {
return organizationCodeCertificate;
}
public void setOrganizationCodeCertificate(String organizationCodeCertificate) {
this.organizationCodeCertificate = organizationCodeCertificate;
}
@Length(min = 0, max = 512, message = "营业执照长度必须介于 0 和 512 之间")
public String getBusinessLicence() {
return businessLicence;
}
public void setBusinessLicence(String businessLicence) {
this.businessLicence = businessLicence;
}
@Length(min = 0, max = 1024, message = "特殊资质长度必须介于 0 和 1024 之间")
public String getSpecialCertificate() {
return specialCertificate;
}
public void setSpecialCertificate(String specialCertificate) {
this.specialCertificate = specialCertificate;
}
public String getErpStoreInfoId() {
return erpStoreInfoId;
}
public void setErpStoreInfoId(String storeInfoId) {
this.erpStoreInfoId = storeInfoId;
}
public String getFinishStatus() {
return finishStatus;
}
public void setFinishStatus(String finishStatus) {
this.finishStatus = finishStatus;
}
@Override
public String toString() {
return "ErpStoreCredentials [registerName=" + registerName + ", registerNo=" + registerNo + ", registerCity=" + registerCity + ", registerAddress=" + registerAddress + ", businessScope=" + businessScope + ", startDate=" + startDate + ", endDate=" + endDate + ", isLongTime=" + isLongTime + ", organizationCodeCertificateNo=" + organizationCodeCertificateNo + ", organizationCodeCertificate=" + organizationCodeCertificate + ", businessLicence=" + businessLicence + ", specialCertificate=" + specialCertificate + ",erpStoreInfoId=" + erpStoreInfoId + ",finishStatus=" + finishStatus + "]";
}
}
|
3e09b451dedd01713961c66be01518cc02f69cbe | 854 | java | Java | src/cc/purplepopo/character/CharacterTree.java | aylqs/Stroke-Chinese-Character-System | 721234baf757a1f2646366e23ee87473f9695f82 | [
"MIT"
] | null | null | null | src/cc/purplepopo/character/CharacterTree.java | aylqs/Stroke-Chinese-Character-System | 721234baf757a1f2646366e23ee87473f9695f82 | [
"MIT"
] | null | null | null | src/cc/purplepopo/character/CharacterTree.java | aylqs/Stroke-Chinese-Character-System | 721234baf757a1f2646366e23ee87473f9695f82 | [
"MIT"
] | null | null | null | 24.4 | 88 | 0.730679 | 4,095 | package cc.purplepopo.character;
import java.util.ArrayList;
public class CharacterTree {
String characterTreeName;
ArrayList<CharacterGlyph> characterGlyphArrayList = new ArrayList<CharacterGlyph>();
public CharacterTree() {
characterTreeName="New group";
}
public CharacterTree(String characterTreeName) {
this.characterTreeName=characterTreeName;
}
public String getcharacterTreeName() {
return characterTreeName;
}
public void setcharacterTreeName(String characterTreeName) {
this.characterTreeName=characterTreeName;
}
public ArrayList<CharacterGlyph> getCharacterGlyphArrayList() {
return characterGlyphArrayList;
}
public void addCharacterStroke(CharacterGlyph characterGlyph) {
this.characterGlyphArrayList.add(characterGlyph);
}
}
|
3e09b46b73d4361f37da440f0dd0e2d795a8fd74 | 367 | java | Java | gmall-pms/src/main/java/com/atguigu/gmall/pms/dao/AttrGroupDao.java | xzw1116/yun | 49fd55bf3d8b92945e5c7d59405d671331b1a370 | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/dao/AttrGroupDao.java | xzw1116/yun | 49fd55bf3d8b92945e5c7d59405d671331b1a370 | [
"Apache-2.0"
] | 3 | 2020-07-21T05:17:45.000Z | 2021-09-20T20:59:52.000Z | gmall-pms/src/main/java/com/atguigu/gmall/pms/dao/AttrGroupDao.java | xzw1116/yun | 49fd55bf3d8b92945e5c7d59405d671331b1a370 | [
"Apache-2.0"
] | null | null | null | 20.277778 | 67 | 0.758904 | 4,096 | package com.atguigu.gmall.pms.dao;
import com.atguigu.gmall.pms.entity.AttrGroupEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 属性分组
*
* @author xzw1116
* @email upchh@example.com
* @date 2020-06-15 15:04:04
*/
@Mapper
public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> {
}
|
3e09b608943cbdf8fc780b091b21b49e0803dec1 | 843 | java | Java | src/main/java/org/dailywork/ui/menu/MenuButtonFactory.java | piotr-sobczyk/daily-work | 1d69c66ed4151c60733b30eef25cd75a34962c03 | [
"Apache-2.0"
] | 1 | 2016-03-09T14:12:03.000Z | 2016-03-09T14:12:03.000Z | src/main/java/org/dailywork/ui/menu/MenuButtonFactory.java | piotr-sobczyk/daily-work | 1d69c66ed4151c60733b30eef25cd75a34962c03 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/dailywork/ui/menu/MenuButtonFactory.java | piotr-sobczyk/daily-work | 1d69c66ed4151c60733b30eef25cd75a34962c03 | [
"Apache-2.0"
] | null | null | null | 24.085714 | 57 | 0.678529 | 4,097 | package org.dailywork.ui.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.inject.Inject;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import org.dailywork.ui.PopupMenu;
import org.dailywork.ui.swing.laf.SexyArrowButtonUI;
public class MenuButtonFactory {
@Inject
private PopupMenu popupMenu;
@Inject
private SexyArrowButtonUI arrowButtonUI;
public JButton create() {
final JPopupMenu menu = popupMenu.getPopupMenu();
final JButton button = new JButton();
button.setUI(arrowButtonUI);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
menu.show(button, 0, button.getHeight());
}
});
return button;
}
}
|
3e09b6c700af07abf083483828558eca7ff64343 | 2,142 | java | Java | renderer/mil-sym-renderer/src/main/java/org/gavaghan/geodesy/GeodeticCurve.java | jtharp/mil-sym-java | 85901ae3b64d01583e55c3e416225c45ac715824 | [
"Apache-2.0"
] | 36 | 2015-01-15T08:38:39.000Z | 2020-06-19T18:34:56.000Z | renderer/mil-sym-renderer/src/main/java/org/gavaghan/geodesy/GeodeticCurve.java | jtharp/mil-sym-java | 85901ae3b64d01583e55c3e416225c45ac715824 | [
"Apache-2.0"
] | 90 | 2015-01-13T16:03:37.000Z | 2021-09-20T14:50:55.000Z | renderer/mil-sym-renderer/src/main/java/org/gavaghan/geodesy/GeodeticCurve.java | jtharp/mil-sym-java | 85901ae3b64d01583e55c3e416225c45ac715824 | [
"Apache-2.0"
] | 36 | 2015-07-02T19:11:46.000Z | 2022-03-31T06:54:11.000Z | 23.8 | 90 | 0.669001 | 4,098 | /* Geodesy by Mike Gavaghan
*
* http://www.gavaghan.org/blog/free-source-code/geodesy-library-vincentys-formula/
*
* This code may be freely used and modified on any personal or professional
* project. It comes with no warranty.
*/
package org.gavaghan.geodesy;
import java.io.Serializable;
/**
* This is the outcome of a geodetic calculation. It represents the path and
* ellipsoidal distance between two GlobalCoordinates for a specified reference
* ellipsoid.
*
* @author Mike Gavaghan
*/
public class GeodeticCurve implements Serializable
{
/** Ellipsoidal distance (in meters). */
private final double mEllipsoidalDistance;
/** Azimuth (degrees from north). */
private final double mAzimuth;
/** Reverse azimuth (degrees from north). */
private final double mReverseAzimuth;
/**
* Create a new GeodeticCurve.
* @param ellipsoidalDistance ellipsoidal distance in meters
* @param azimuth azimuth in degrees
* @param reverseAzimuth reverse azimuth in degrees
*/
public GeodeticCurve(double ellipsoidalDistance, double azimuth, double reverseAzimuth)
{
mEllipsoidalDistance = ellipsoidalDistance;
mAzimuth = azimuth;
mReverseAzimuth = reverseAzimuth;
}
/**
* Get the ellipsoidal distance.
* @return ellipsoidal distance in meters
*/
public double getEllipsoidalDistance()
{
return mEllipsoidalDistance;
}
/**
* Get the azimuth.
* @return azimuth in degrees
*/
public double getAzimuth()
{
return mAzimuth;
}
/**
* Get the reverse azimuth.
* @return reverse azimuth in degrees
*/
public double getReverseAzimuth()
{
return mReverseAzimuth;
}
/**
* Get curve as a string.
* @return
*/
@Override
public String toString()
{
StringBuffer buffer = new StringBuffer();
buffer.append("s=");
buffer.append(mEllipsoidalDistance);
buffer.append(";a12=");
buffer.append(mAzimuth);
buffer.append(";a21=");
buffer.append(mReverseAzimuth);
buffer.append(";");
return buffer.toString();
}
}
|
3e09b71a6cb80ea1ba634cb1a3b887cd20205081 | 149 | java | Java | src/main/java/Main.java | momokinou/ipi-java-220-ex | 463a3fd1cce98c6ad546bc13fed35a99d7328c36 | [
"MIT"
] | null | null | null | src/main/java/Main.java | momokinou/ipi-java-220-ex | 463a3fd1cce98c6ad546bc13fed35a99d7328c36 | [
"MIT"
] | null | null | null | src/main/java/Main.java | momokinou/ipi-java-220-ex | 463a3fd1cce98c6ad546bc13fed35a99d7328c36 | [
"MIT"
] | null | null | null | 24.833333 | 44 | 0.597315 | 4,099 | public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
System.out.print("test");
}
} |
3e09b731bf0fc290484d8f7e847693f1460ff1ee | 391 | java | Java | Sorter.java | BrianGrammer/Sorting-Algorithms-Comparisons | ba322b910be85c1a94e79474b5e860653ffd1f79 | [
"MIT"
] | null | null | null | Sorter.java | BrianGrammer/Sorting-Algorithms-Comparisons | ba322b910be85c1a94e79474b5e860653ffd1f79 | [
"MIT"
] | null | null | null | Sorter.java | BrianGrammer/Sorting-Algorithms-Comparisons | ba322b910be85c1a94e79474b5e860653ffd1f79 | [
"MIT"
] | null | null | null | 39.1 | 77 | 0.73913 | 4,100 | // CS 0445 Spring 2020
// Code for various versions of QuickSort (much taken from the Carrano text)
// Note that this code is designed for readability and modularity. It is
// not necessarily the most efficient way of implementing these algorithms.
public interface Sorter<T extends Comparable<? super T>>
{
public void sort(T[] a, int size);
public void setMin(int minSize);
} |
3e09b8223ccca314552392532e2982ade969494d | 6,934 | java | Java | opensrp-register/src/test/java/org/opensrp/register/repository/it/FormDataRepositoryIntegrationTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | opensrp-register/src/test/java/org/opensrp/register/repository/it/FormDataRepositoryIntegrationTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | opensrp-register/src/test/java/org/opensrp/register/repository/it/FormDataRepositoryIntegrationTest.java | proshantokuet/data-coorection | 88f5653d606b06001776a0530be0c6c62c9f805f | [
"Apache-2.0"
] | null | null | null | 44.448718 | 127 | 0.598067 | 4,101 | package org.opensrp.register.repository.it;
import com.google.gson.Gson;
import org.opensrp.register.domain.EligibleCouple;
import org.opensrp.register.domain.Mother;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opensrp.register.repository.AllEligibleCouples;
import org.opensrp.register.repository.AllMothers;
import org.opensrp.register.repository.FormDataRepositoryImpl;
import org.opensrp.repository.FormDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Map;
import static org.opensrp.common.util.EasyMap.create;
import static org.opensrp.common.util.EasyMap.mapOf;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:test-applicationContext-opensrp-register.xml")
public class FormDataRepositoryIntegrationTest {
@Autowired
private FormDataRepository repository;
@Autowired
private AllEligibleCouples eligibleCouples;
@Autowired
private AllMothers mothers;
@Before
public void setUp() throws Exception {
eligibleCouples.removeAll();
mothers.removeAll();
}
@Test
public void shouldSaveNewEntityAsEligibleCouple() throws Exception {
Map<String, String> fields =
create("id", "entity id 1")
.put("husbandName", "raja")
.put("wifeName", "asha")
.put("ecNumber", "ec 123")
//.put("village", "") TODO needs to change to test for expected location too
//.put("phc", "phc")
//.put("subCenter", "sub center")
.put("currentMethod", "ocp")
.put("isHighPriority", "no")
.put("isClosed", "false")
.put("isOutOfArea", "false")
.map();
String fieldsJSON = new Gson().toJson(fields);
String entityId = repository.saveEntity("eligible_couple", fieldsJSON);
assertEquals(entityId, "entity id 1");
EligibleCouple savedEC = eligibleCouples.findByCaseId(entityId);
Map<String, String> expectedDetails = create("currentMethod", "ocp")
.put("isHighPriority", "no")
.map();
EligibleCouple expectedEligibleCouple = new EligibleCouple("entity id 1", "ec 123")
.withCouple("asha", "raja").withDetails(expectedDetails);
assertEquals(expectedEligibleCouple, savedEC);
}
@Test
public void shouldSaveNewEntityWhenThereIsAnDifferentExistingEntityOfSameType() throws Exception {
EligibleCouple existingEligibleCouple = new EligibleCouple("entity id 0", "ec 123").withDetails(mapOf("key", "value"));
eligibleCouples.add(existingEligibleCouple);
Map<String, String> fields =
create("id", "entity id 1")
.put("husbandName", "raja")
.put("wifeName", "asha")
.put("ecNumber", "ec 123")
//.put("village", "") TODO needs to be changed to compare location vars too
// .put("phc", "phc")
// .put("subCenter", "sub center")
.put("currentMethod", "ocp")
.put("isHighPriority", "no")
.put("isClosed", "false")
.put("isOutOfArea", "false")
.map();
String fieldsJSON = new Gson().toJson(fields);
String entityId = repository.saveEntity("eligible_couple", fieldsJSON);
assertEquals(entityId, "entity id 1");
EligibleCouple savedEC = eligibleCouples.findByCaseId(entityId);
EligibleCouple existingEC = eligibleCouples.findByCaseId("entity id 0");
Map<String, String> expectedDetails = create("currentMethod", "ocp")
.put("isHighPriority", "no")
.map();
EligibleCouple expectedEligibleCouple = new EligibleCouple("entity id 1", "ec 123")
.withCouple("asha", "raja").withDetails(expectedDetails);
assertEquals(expectedEligibleCouple, savedEC);
assertEquals(existingEligibleCouple, existingEC);
}
@Test
public void shouldUpdateExistingEntityAsEligibleCouple() throws Exception {
Map<String, String> fields =
create("id", "entity id 1")
.put("husbandName", "raja")
.put("ecNumber", "ec 123")
.put("wifeName", "asha")
//.put("village", "") //TODO check for location tooo
.put("currentMethod", "ocp")
.put("isHighPriority", "no")
.map();
String fieldsJSON = new Gson().toJson(fields);
Map<String, String> oldDetails = create("currentMethod", "condom")
.put("isHighPriority", "yes")
.put("bloodGroup", "o-ve")
.map();
EligibleCouple oldEC = new EligibleCouple("entity id 1", "ec 123")
.withCouple("old wife name", "old husband name").withDetails(oldDetails);
eligibleCouples.add(oldEC);
String entityId = repository.saveEntity("eligible_couple", fieldsJSON);
assertEquals(entityId, "entity id 1");
EligibleCouple savedEC = eligibleCouples.findByCaseId(entityId);
Map<String, String> expectedDetails = create("currentMethod", "ocp")
.put("isHighPriority", "no")
.put("bloodGroup", "o-ve")
.map();
EligibleCouple expectedEligibleCouple = new EligibleCouple("entity id 1", "ec 123")
.withCouple("asha", "raja").withDetails(expectedDetails);
assertEquals(expectedEligibleCouple, savedEC);
}
@Test
public void shouldUpdateMotherEntity() throws Exception {
Map<String, String> fields =
create("id", "entity id 1")
.put("thayiCardNumber", "thayi1")
.put("ecCaseId", "ec 123")
.put("isHighPriority", "no")
.map();
String fieldsJSON = new Gson().toJson(fields);
Mother oldMother = new Mother("entity id 1", "ec 123", "thayi2");
mothers.add(oldMother);
String entityId = repository.saveEntity("mother", fieldsJSON);
Mother savedMother = mothers.findByCaseId(entityId);
Map<String, String> expectedDetails = mapOf("isHighPriority", "no");
Mother expectedMother = new Mother("entity id 1", "ec 123", "thayi1").withDetails(expectedDetails);
assertEquals(expectedMother, savedMother);
}
}
|
3e09b8323801f16925362ae7a67a3baea23e034b | 1,252 | java | Java | qualification-round/b_nesting_depth.java | demin13/GoogleCodeJam2020 | fb9497565f3c6b321b9f20699e2a6c8a30008f49 | [
"MIT"
] | 12 | 2020-04-04T14:13:41.000Z | 2021-02-20T07:24:31.000Z | qualification-round/b_nesting_depth.java | ShivamGoyal1899/GoogleCodeJam2020 | 98c6b2c9f3742bf3ad70271b69126d89de65ea9f | [
"MIT"
] | null | null | null | qualification-round/b_nesting_depth.java | ShivamGoyal1899/GoogleCodeJam2020 | 98c6b2c9f3742bf3ad70271b69126d89de65ea9f | [
"MIT"
] | 11 | 2020-04-04T13:14:56.000Z | 2020-07-14T10:27:27.000Z | 26.083333 | 81 | 0.605431 | 4,102 | import java.util.*;
import java.io.*;
import java.lang.Math;
public class Solution {
public static void main (String[] args) {
boolean debug = false;
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
String tString = in.nextLine();
int t = Integer.parseInt(tString);
for (int i = 1; i <= t; ++i) {
String string = in.nextLine();
char[] cArr = string.toCharArray();
int currentStack = 0;
String answer = "";
for (char currentChar: cArr) {
int currentInt = Character.getNumericValue(currentChar);
if (currentInt > currentStack) {
while (currentInt > currentStack) {
answer += "(";
currentStack++;
}
answer += Integer.toString(currentInt);
} else if (currentInt == currentStack) {
answer += currentInt;
} else if (currentInt < currentStack) {
while (currentInt < currentStack) {
answer += ")";
currentStack--;
}
answer += Integer.toString(currentInt);
}
}
while (currentStack > 0) {
answer += ")";
currentStack--;
}
if (debug) {
System.out.println("Case #" + i + ": " + Arrays.toString(cArr));
System.out.println(answer);
}
System.out.println("Case #" + i + ": " + answer);
}
}
} |
3e09b87bd22f9eef89ffce23b33e9c4c06f527eb | 605 | java | Java | src/Uygulama/validator.java | ramazanisik/CariHesap-JavaSwing | 3bf1064f66bed63d836529f2cf4756111c2edb62 | [
"MIT"
] | null | null | null | src/Uygulama/validator.java | ramazanisik/CariHesap-JavaSwing | 3bf1064f66bed63d836529f2cf4756111c2edb62 | [
"MIT"
] | null | null | null | src/Uygulama/validator.java | ramazanisik/CariHesap-JavaSwing | 3bf1064f66bed63d836529f2cf4756111c2edb62 | [
"MIT"
] | null | null | null | 14.404762 | 45 | 0.520661 | 4,103 |
package Uygulama;
public class validator {
public boolean harfkontrol(String gelen)
{
boolean kontrol=true;
for(Character harf:gelen.toCharArray())
{
if(!(Character.isAlphabetic(harf)))
{
kontrol=false;
break;
}
}
return kontrol;
}
public boolean rakamkontrol(String gelen)
{
boolean kontrol=true;
for(Character harf:gelen.toCharArray())
{
if(!(Character.isDigit(harf)))
{
kontrol=false;
break;
}
}
return kontrol;
}
}
|
3e09b87d9fe8399a1af2849b43081701b3c74ccb | 8,395 | java | Java | src/main/java/org/statemach/db/sql/postgres/PostgresSQLBuilder.java | YuriyGorvitovskiy/statemach-data | b43114a7245a2fe7e859b218192b538d7ca17165 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/statemach/db/sql/postgres/PostgresSQLBuilder.java | YuriyGorvitovskiy/statemach-data | b43114a7245a2fe7e859b218192b538d7ca17165 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/statemach/db/sql/postgres/PostgresSQLBuilder.java | YuriyGorvitovskiy/statemach-data | b43114a7245a2fe7e859b218192b538d7ca17165 | [
"Apache-2.0"
] | null | null | null | 34.834025 | 122 | 0.587731 | 4,104 | package org.statemach.db.sql.postgres;
import org.statemach.db.jdbc.Extract;
import org.statemach.db.jdbc.Inject;
import org.statemach.db.jdbc.Vendor;
import org.statemach.db.schema.ColumnInfo;
import org.statemach.db.schema.DataType;
import org.statemach.db.sql.Condition;
import org.statemach.db.sql.From;
import org.statemach.db.sql.Join;
import org.statemach.db.sql.SQL;
import org.statemach.db.sql.SQLBuilder;
import org.statemach.db.sql.Select;
import org.statemach.db.sql.TableLike;
import org.statemach.db.sql.View;
import org.statemach.util.Java;
import org.statemach.util.Json;
import org.statemach.util.NodeLinkTree;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Set;
import io.vavr.collection.Traversable;
public class PostgresSQLBuilder implements SQLBuilder {
final String schema;
public PostgresSQLBuilder(String schema) {
this.schema = schema;
}
@Override
public Vendor getVendor() {
return Vendor.POSTGRES;
}
@Override
public Condition and(Traversable<Condition> child) {
if (child.isEmpty()) {
return Condition.NONE;
}
if (1 == child.size()) {
return child.get();
}
return new Condition(
child.map(c -> SQL.OPEN + c.sql + SQL.CLOSE).mkString(SQL.AND),
Inject.fold(child.map(c -> c.inject)));
}
@Override
public Condition or(Traversable<Condition> child) {
if (child.isEmpty()) {
return Condition.NONE;
}
if (1 == child.size()) {
return child.get();
}
return new Condition(
child.map(c -> SQL.OPEN + c.sql + SQL.CLOSE).mkString(SQL.OR),
Inject.fold(child.map(c -> c.inject)));
}
@Override
public Condition not(Condition child) {
return new Condition(SQL.NOT_OPEN + child.sql + SQL.CLOSE, child.inject);
}
@Override
public Condition isNull(Select<?> column) {
return new Condition(column.sql() + SQL.IS_NULL, Inject.NOTHING);
}
@Override
public Condition isNotNull(Select<?> column) {
return new Condition(column.sql() + SQL.NOT_NULL, Inject.NOTHING);
}
@Override
public Condition equal(Select<?> column, Inject value) {
return new Condition(column.sql() + SQL.EQUAL + SQL.PARAM, value);
}
@Override
public Condition equal(Select<?> left, Select<?> right) {
return new Condition(left.sql() + SQL.EQUAL + right.sql(), Inject.NOTHING);
}
@Override
public Condition in(Select<?> column, Traversable<Inject> values) {
return new Condition(column.sql() + SQL.IN_OPEN + Java.repeat(SQL.PARAM, SQL.COMMA, values.size()) + SQL.CLOSE,
Inject.fold(values));
}
@Override
public Condition inJsonArray(Select<?> column, DataType elementType, Traversable<?> array) {
return new Condition(column.sql() + SQL.IN_OPEN + SQL.SELECT +
SQL.UNNEST_PARAM_OPEN + elementType.name + SQL.ARRAY + SQL.CLOSE +
SQL.CLOSE,
elementType.injectJsonArray.prepare(array));
}
@Override
public Condition inStringArray(Select<?> column, DataType elementType, Traversable<String> array) {
return new Condition(column.sql() + SQL.IN_OPEN + SQL.SELECT +
SQL.UNNEST_PARAM_OPEN + elementType.name + SQL.ARRAY + SQL.CLOSE +
SQL.CLOSE,
elementType.injectStringArray.prepare(array));
}
@Override
public Condition textSearch(Select<?> column, Traversable<String> values) {
return new Condition(SQL.WEB_SEARCH + column.sql(),
PostgresDataType.TSVECTOR.injectStringValue.prepare(values.mkString(" ")));
}
String querySql(List<View<String>> commonTableExpressions, View<Tuple2<String, Extract<?>>> query) {
StringBuilder sb = new StringBuilder();
int indent = 0;
Set<String> cteNames = commonTableExpressions.map(c -> c.name).toSet();
if (!commonTableExpressions.isEmpty()) {
sb.append(SQL.WITH);
sb.append(commonTableExpressions.map(v -> commonTableExrpressionSql(v, cteNames, 1)).mkString(SQL.COMMA));
sb.append(SQL.NEXT_LINE);
indent = 1;
}
sb.append(viewSql(query, cteNames, indent));
return sb.toString();
}
String commonTableExrpressionSql(View<String> v, Set<String> cteNames, int indentLength) {
return v.name +
SQL.SPACE +
v.select.map(c -> c._1).mkString(SQL.OPEN, SQL.COMMA, SQL.CLOSE) +
SQL.AS_OPEN + SQL.NEXT_LINE +
viewSql(v, cteNames, indentLength + 1) +
Java.repeat(SQL.INDENT, indentLength) +
SQL.CLOSE;
}
String viewSql(View<?> v, Set<String> cteNames, int indentLength) {
String indent = Java.repeat(SQL.INDENT, indentLength);
StringBuilder sb = new StringBuilder()
.append(indent)
.append(SQL.SELECT);
if (v.distinct) {
sb.append(SQL.DISTINCT);
}
sb.append(v.select.map(c -> c.from + SQL.DOT + c.column).mkString(SQL.COMMA))
.append(SQL.NEXT_LINE);
indent = indent + SQL.INDENT;
joinSql(v.joins, cteNames, sb, indent);
if (Condition.NONE != v.where) {
sb.append(indent)
.append(SQL.WHERE)
.append(v.where.sql)
.append(SQL.NEXT_LINE);
}
if (!v.order.isEmpty()) {
sb.append(indent)
.append(SQL.ORDER_BY)
.append(v.order.map(c -> c.from + SQL.DOT + c.column + (c._1 ? SQL.ASC : SQL.DESC)).mkString(SQL.COMMA))
.append(SQL.NEXT_LINE);
}
if (null != v.limit) {
sb.append(indent)
.append(SQL.LIMIT)
.append(v.limit)
.append(SQL.NEXT_LINE);
}
if (null != v.skip) {
sb.append(indent)
.append(SQL.OFFSET)
.append(v.skip)
.append(SQL.NEXT_LINE);
}
return sb.toString();
}
StringBuilder joinSql(NodeLinkTree<String, From, Join> joins, Set<String> cteNames, StringBuilder sb, String indent) {
sb.append(indent)
.append(SQL.FROM)
.append(joins.getNode().table.sql)
.append(SQL.SPACE)
.append(joins.getNode().alias)
.append(SQL.NEXT_LINE);
return joins.links
.values()
.foldLeft(sb, (s, c) -> joinSql(c._1, c._2, cteNames, s, indent));
}
StringBuilder joinSql(Join join,
NodeLinkTree<String, From, Join> right,
Set<String> cteNames,
StringBuilder sb,
String indent) {
sb.append(indent)
.append(join.kind.sql)
.append(right.getNode().table.sql)
.append(SQL.SPACE)
.append(right.getNode().alias)
.append(SQL.ON)
.append(join.condition.sql)
.append(SQL.NEXT_LINE);
return right.links
.values()
.foldLeft(sb, (s, c) -> joinSql(c._1, c._2, cteNames, sb, indent));
}
@Override
public TableLike arrayAsTable(DataType type, List<ColumnInfo> columns, Traversable<Map<String, Object>> values) {
// JSON_POPULATE_RECORDSET(null::scm.type, ?::JSON)
String sql = SQL.JSON_POPULATE_RS_OPEN + schema + SQL.DOT + type.name
+ SQL.COMMA + SQL.PARAM + SQL.JSON_CAST
+ SQL.CLOSE;
String json = Java.soft(() -> Json.MAPPER.writeValueAsString(values));
Inject inject = PostgresDataType.TEXT.injectStringValue.prepare(json);
return TableLike.of(sql, inject);
}
@Override
public TableLike arrayAsTable(ColumnInfo column, Traversable<Object> values) {
// (SELECT UNNEST((?)::type) AS col)
String sql = SQL.OPEN
+ SQL.SELECT + SQL.UNNEST_PARAM_OPEN + column.type.name + SQL.ARRAY + SQL.CLOSE
+ SQL.AS + column.name
+ SQL.CLOSE;
return TableLike.of(sql, column.type.injectJsonArray.prepare(values));
}
}
|
3e09b956d59e5c64fa2a8ceaeab10eaf1bfeb1fd | 1,409 | java | Java | chapter04/bean-init-method/src/main/java/com/isaac/ch4/config/SingerConfigDemo.java | baocaixue/spring-dk | 9fc5ac437751f81ae1c4c4065e12c51be77c831f | [
"Apache-2.0"
] | 5 | 2019-07-26T06:17:10.000Z | 2020-04-28T05:39:25.000Z | chapter04/bean-init-method/src/main/java/com/isaac/ch4/config/SingerConfigDemo.java | baocaixue/spring-dk | 9fc5ac437751f81ae1c4c4065e12c51be77c831f | [
"Apache-2.0"
] | 1 | 2019-08-27T14:25:49.000Z | 2019-08-27T14:26:30.000Z | chapter04/bean-init-method/src/main/java/com/isaac/ch4/config/SingerConfigDemo.java | baocaixue/spring-dk | 9fc5ac437751f81ae1c4c4065e12c51be77c831f | [
"Apache-2.0"
] | 1 | 2019-07-26T08:04:25.000Z | 2019-07-26T08:04:25.000Z | 28.755102 | 92 | 0.637331 | 4,105 | package com.isaac.ch4.config;
import com.isaac.ch4.Singer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import static com.isaac.ch4.Singer.getBean;
public class SingerConfigDemo {
@Configuration
static class SingerConfig {
@Lazy
@Bean(initMethod = "init")
Singer singerOne() {
Singer singerOne = new Singer();
singerOne.setName("John Mayer");
singerOne.setAge(39);
return singerOne;
}
@Lazy
@Bean(initMethod = "init")
Singer singerTwo() {
Singer singerTwo = new Singer();
singerTwo.setAge(31);
return singerTwo;
}
@Lazy
@Bean(initMethod = "init")
Singer singerThree() {
Singer singerThree = new Singer();
singerThree.setName("John Mayer");
return singerThree;
}
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SingerConfig.class);
getBean("singerOne", ctx);
getBean("singerTwo", ctx);
getBean("singerThree", ctx);
}
}
|
3e09b9a159c4330da1afd500dcbbf2cacd15042a | 1,265 | java | Java | aws-java-sdk-kafkaconnect/src/main/java/com/amazonaws/services/kafkaconnect/model/UnauthorizedException.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-kafkaconnect/src/main/java/com/amazonaws/services/kafkaconnect/model/UnauthorizedException.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-kafkaconnect/src/main/java/com/amazonaws/services/kafkaconnect/model/UnauthorizedException.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 34.189189 | 119 | 0.727273 | 4,106 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kafkaconnect.model;
import javax.annotation.Generated;
/**
* <p>
* HTTP Status Code 401: Unauthorized request. The provided credentials couldn't be validated.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UnauthorizedException extends com.amazonaws.services.kafkaconnect.model.AWSKafkaConnectException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new UnauthorizedException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public UnauthorizedException(String message) {
super(message);
}
}
|
3e09b9a23f5729e8d13f0baf240298523e8c32f0 | 30,385 | java | Java | Mage.Client/src/main/java/mage/client/cards/CardsList.java | Emigara/mage | 2783199b735b35c718db3bff85a3505793920ca9 | [
"MIT"
] | 2 | 2020-04-04T22:36:47.000Z | 2020-04-04T22:57:35.000Z | Mage.Client/src/main/java/mage/client/cards/CardsList.java | Emigara/mage | 2783199b735b35c718db3bff85a3505793920ca9 | [
"MIT"
] | 43 | 2020-07-27T06:53:24.000Z | 2022-03-28T23:03:21.000Z | Mage.Client/src/main/java/mage/client/cards/CardsList.java | Emigara/mage | 2783199b735b35c718db3bff85a3505793920ca9 | [
"MIT"
] | 2 | 2020-01-30T01:09:39.000Z | 2020-02-20T02:08:24.000Z | 42.795775 | 190 | 0.608721 | 4,107 |
/*
* CardsList.java
*
* Created on Dec 18, 2009, 10:40:12 AM
*/
package mage.client.cards;
import mage.cards.MageCard;
import mage.client.constants.Constants.DeckEditorMode;
import mage.client.constants.Constants.SortBy;
import mage.client.deckeditor.SortSetting;
import mage.client.deckeditor.table.TableModel;
import mage.client.deckeditor.table.UpdateCountsCallback;
import mage.client.dialog.PreferencesDialog;
import mage.client.plugins.impl.Plugins;
import mage.client.util.Event;
import mage.client.util.*;
import mage.client.util.gui.TableSpinnerEditor;
import mage.view.CardView;
import mage.view.CardsView;
import mage.view.SimpleCardView;
import org.mage.card.arcane.CardPanel;
import org.mage.card.arcane.ManaSymbolsCellRenderer;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.Beans;
import java.util.List;
import java.util.*;
/**
* @author BetaSteward_at_googlemail.com
*/
public class CardsList extends javax.swing.JPanel implements MouseListener, ICardGrid {
protected final CardEventSource cardEventSource = new CardEventSource();
private Dimension cardDimension;
private int rowHeight;
private CardsView cards;
private Map<UUID, MageCard> mageCards = new LinkedHashMap<>();
protected BigCard bigCard;
protected UUID gameId;
private SortSetting sortSetting;
private TableModel mainModel;
private JTable mainTable;
private ICardGrid currentView;
/**
* Creates new form Cards
*/
public CardsList() {
initComponents();
makeTransparent();
initListViewComponents();
setGUISize();
}
public void cleanUp() {
this.clearCardEventListeners();
if (cards != null) {
cards.clear();
}
if (mainModel != null) {
mainModel.removeTableModelListener(mainTable);
mainModel.clear();
}
if (cardArea != null) {
for (MouseListener ml : cardArea.getMouseListeners()) {
cardArea.removeMouseListener(ml);
}
for (Component comp : cardArea.getComponents()) {
if (comp instanceof CardPanel) {
((CardPanel) comp).cleanUp();
}
}
cardArea.removeAll();
}
if (mainTable != null) {
for (MouseListener ml : mainTable.getMouseListeners()) {
mainTable.removeMouseListener(ml);
}
}
if (currentView != null) {
currentView.clearCardEventListeners();
}
mageCards.clear();
this.bigCard = null;
}
public void changeGUISize() {
setGUISize();
redrawCards();
}
private void setGUISize() {
mainTable.getTableHeader().setFont(GUISizeHelper.tableFont);
mainTable.setFont(GUISizeHelper.tableFont);
mainTable.setRowHeight(GUISizeHelper.getTableRowHeight());
cardDimension = GUISizeHelper.editorCardDimension;
rowHeight = GUISizeHelper.editorCardOffsetSize;
}
private void makeTransparent() {
panelCardArea.setOpaque(false);
cardArea.setOpaque(false);
panelCardArea.getViewport().setOpaque(false);
panelControl.setBackground(new Color(250, 250, 250, 150));
panelControl.setOpaque(true);
cbSortBy.setModel(new DefaultComboBoxModel<>(SortBy.values()));
}
private void initListViewComponents() {
mainTable = new JTable();
mainModel = new TableModel();
mainModel.addListeners(mainTable);
mainTable.setModel(mainModel);
mainTable.setForeground(Color.white);
DefaultTableCellRenderer myRenderer = (DefaultTableCellRenderer) mainTable.getDefaultRenderer(String.class);
myRenderer.setBackground(new Color(0, 0, 0, 100));
mainTable.getColumnModel().getColumn(0).setMaxWidth(25);
mainTable.getColumnModel().getColumn(0).setPreferredWidth(25);
mainTable.getColumnModel().getColumn(1).setPreferredWidth(110);
mainTable.getColumnModel().getColumn(2).setPreferredWidth(90);
mainTable.getColumnModel().getColumn(3).setPreferredWidth(50);
mainTable.getColumnModel().getColumn(4).setPreferredWidth(170);
mainTable.getColumnModel().getColumn(5).setPreferredWidth(30);
mainTable.getColumnModel().getColumn(6).setPreferredWidth(15);
mainTable.getColumnModel().getColumn(7).setPreferredWidth(15);
// new mana render (svg support)
mainTable.getColumnModel().getColumn(mainModel.COLUMN_INDEX_COST).setCellRenderer(new ManaSymbolsCellRenderer());
if (PreferencesDialog.getCachedValue(PreferencesDialog.KEY_DRAFT_VIEW, "cardView").equals("listView")) {
jToggleListView.setSelected(true);
panelCardArea.setViewportView(mainTable);
currentView = mainModel;
cbSortBy.setEnabled(false);
chkPiles.setEnabled(false);
} else {
jToggleCardView.setSelected(true);
currentView = this;
panelCardArea.setViewportView(cardArea);
cbSortBy.setEnabled(true);
chkPiles.setEnabled(true);
}
cardArea.addMouseListener(this);
mainTable.setOpaque(false);
mainTable.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if ((e.getClickCount() & 1) == 0 && (e.getClickCount() > 0) && !e.isConsumed()) { // double clicks and repeated double clicks
e.consume();
if (e.isAltDown()) {
handleAltDoubleClick();
} else {
handleDoubleClick();
}
}
}
});
mainModel.setUpdateCountsCallback(new UpdateCountsCallback(lblCount, lblCreatureCount, lblLandCount, null, null, null, null));
}
// if you use the deck ediot to build a free deck, numbers can be set directly in deck and sideboard
public void setDeckEditorMode(DeckEditorMode mode) {
if (mode == DeckEditorMode.FREE_BUILDING) {
// activate spinner for card number change
mainModel.setNumberEditable(true);
TableColumnModel tcm = mainTable.getColumnModel();
TableColumn tc = tcm.getColumn(0);
tc.setMaxWidth(55);
tc.setMinWidth(55);
tc.setPreferredWidth(55);
tc.setCellEditor(new TableSpinnerEditor(this));
}
}
public void handleSetNumber(int number) {
if (mainTable.getSelectedRowCount() == 1) {
mainModel.setNumber(mainTable.getSelectedRow(), number);
}
}
public void handleDoubleClick() {
if (mainTable.getSelectedRowCount() > 0) {
int[] n = mainTable.getSelectedRows();
List<Integer> indexes = asList(n);
Collections.reverse(indexes);
for (Integer index : indexes) {
mainModel.doubleClick(index);
}
}
}
public void handleAltDoubleClick() {
if (mainTable.getSelectedRowCount() > 0) {
int[] n = mainTable.getSelectedRows();
List<Integer> indexes = asList(n);
Collections.reverse(indexes);
for (Integer index : indexes) {
mainModel.altDoubleClick(index);
}
}
}
public ICardGrid getMainModel() {
return mainModel;
}
public List<Integer> asList(final int[] is) {
List<Integer> list = new ArrayList<>();
for (int i : is) {
list.add(i);
}
return list;
}
public void loadCards(CardsView showCards, BigCard bigCard, UUID gameId) {
int selectedRow = -1;
if (currentView.equals(mainModel)) {
selectedRow = mainTable.getSelectedRow();
}
this.cards = showCards;
this.bigCard = bigCard;
this.gameId = gameId;
cbSortBy.setSelectedItem(sortSetting.getSortBy());
chkPiles.setSelected(sortSetting.isPilesToggle());
currentView.loadCards(showCards, sortSetting, bigCard, gameId);
if (selectedRow >= 0) {
selectedRow = Math.min(selectedRow, mainTable.getRowCount() - 1);
if (selectedRow >= 0) {
mainTable.setRowSelectionInterval(selectedRow, selectedRow);
}
}
}
private void redrawCards() {
if (cards == null) {
cards = new CardsView();
}
currentView.loadCards(cards, sortSetting, bigCard, gameId);
}
@Override
public void drawCards(SortSetting sortSetting) {
int maxWidth = this.getParent().getWidth();
int numColumns = maxWidth / cardDimension.width;
int curColumn = 0;
int curRow = 0;
int maxRow = 0;
int maxColumn = 0;
Comparator<CardView> comparator = null;
Map<UUID, MageCard> oldMageCards = mageCards;
mageCards = new LinkedHashMap<>();
//Find card view
for (Map.Entry<UUID, CardView> view : cards.entrySet()) {
UUID uuid = view.getKey();
CardView cardView = view.getValue();
if (oldMageCards.containsKey(uuid)) {
mageCards.put(uuid, oldMageCards.get(uuid));
oldMageCards.remove(uuid);
} else {
mageCards.put(uuid, addCard(cardView, bigCard, gameId));
}
}
//Remove unused cards
for (MageCard card : oldMageCards.values()) {
cardArea.remove(card);
}
if (cards != null && !cards.isEmpty()) {
Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height);
List<CardView> sortedCards = new ArrayList<>(cards.values());
switch (sortSetting.getSortBy()) {
case NAME:
comparator = new CardViewNameComparator();
break;
case RARITY:
comparator = new CardViewRarityComparator();
break;
case CARD_TYPE:
comparator = new CardViewCardTypeComparator();
break;
case COLOR:
comparator = new CardViewColorComparator();
break;
case COLOR_IDENTITY:
comparator = new CardViewColorIdentityComparator();
break;
case CASTING_COST:
comparator = new CardViewCostComparator();
break;
}
if (comparator != null) {
sortedCards.sort(new CardViewNameComparator());
sortedCards.sort(comparator);
}
CardView lastCard = null;
for (CardView card : sortedCards) {
if (sortSetting.isPilesToggle()) {
if (lastCard == null) {
lastCard = card;
}
if (comparator != null) {
if (comparator.compare(card, lastCard) > 0) {
curColumn++;
maxRow = Math.max(maxRow, curRow);
curRow = 0;
}
}
rectangle.setLocation(curColumn * cardDimension.width, curRow * rowHeight);
setCardBounds(mageCards.get(card.getId()), rectangle);
curRow++;
lastCard = card;
} else {
rectangle.setLocation(curColumn * cardDimension.width, curRow * rowHeight);
setCardBounds(mageCards.get(card.getId()), rectangle);
curColumn++;
if (curColumn == numColumns) {
maxColumn = Math.max(maxColumn, curColumn);
curColumn = 0;
curRow++;
}
}
}
}
maxRow = Math.max(maxRow, curRow);
maxColumn = Math.max(maxColumn, curColumn);
updateCounts();
cardArea.setPreferredSize(new Dimension((maxColumn + 1) * cardDimension.width, cardDimension.height + maxRow * rowHeight));
cardArea.revalidate();
this.revalidate();
this.repaint();
this.setVisible(true);
}
private void updateCounts() {
int landCount = 0;
int creatureCount = 0;
int sorceryCount = 0;
int instantCount = 0;
int enchantmentCount = 0;
int artifactCount = 0;
for (CardView card : cards.values()) {
if (card.isLand()) {
landCount++;
}
if (card.isCreature()) {
creatureCount++;
}
if (card.isSorcery()) {
sorceryCount++;
}
if (card.isInstant()) {
instantCount++;
}
if (card.isEnchantment()) {
enchantmentCount++;
}
if (card.isArtifact()) {
artifactCount++;
}
}
int count = cards != null ? cards.size() : 0;
this.lblCount.setText(Integer.toString(count));
this.lblCreatureCount.setText(Integer.toString(creatureCount));
this.lblLandCount.setText(Integer.toString(landCount));
}
private MageCard addCard(CardView card, BigCard bigCard, UUID gameId) {
MageCard cardImg = Plugins.instance.getMageCard(card, bigCard, cardDimension, gameId, true, true, PreferencesDialog.getRenderMode(), true);
cardArea.add(cardImg);
cardImg.update(card);
cardImg.addMouseListener(this);
return cardImg;
}
private void setCardBounds(MageCard card, Rectangle rectangle) {
card.setBounds(rectangle);
card.setCardBounds(rectangle.x, rectangle.y, cardDimension.width, cardDimension.height);
cardArea.moveToFront(card);
}
@Override
public void addCardEventListener(Listener<Event> listener) {
cardEventSource.addListener(listener);
mainModel.addCardEventListener(listener);
}
@Override
public void loadCards(CardsView showCards, SortSetting sortSetting, BigCard bigCard, UUID gameId) {
this.loadCards(showCards, sortSetting, bigCard, gameId, true);
}
@Override
public void loadCards(CardsView showCards, SortSetting sortSetting, BigCard bigCard, UUID gameId, boolean merge) {
cards = showCards;
this.bigCard = bigCard;
this.gameId = gameId;
drawCards(sortSetting);
}
@Override
public void refresh() {
redrawCards();
}
@Override
public void clearCardEventListeners() {
cardEventSource.clearListeners();
mainModel.clearCardEventListeners();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bgView = new javax.swing.ButtonGroup();
panelControl = new javax.swing.JPanel();
lblCount = new javax.swing.JLabel();
lblLandCount = new javax.swing.JLabel();
lblCreatureCount = new javax.swing.JLabel();
chkPiles = new javax.swing.JCheckBox();
cbSortBy = new javax.swing.JComboBox();
jToggleListView = new javax.swing.JToggleButton();
jToggleCardView = new javax.swing.JToggleButton();
panelCardArea = new javax.swing.JScrollPane();
cardArea = new javax.swing.JLayeredPane();
setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
setMinimumSize(new java.awt.Dimension(30, 30));
setPreferredSize((!Beans.isDesignTime()) ?
(GUISizeHelper.editorCardDimension)
: (new Dimension(600, 600)));
setRequestFocusEnabled(false);
panelControl.setMaximumSize(new java.awt.Dimension(32767, 23));
panelControl.setMinimumSize(new java.awt.Dimension(616, 23));
panelControl.setName(""); // NOI18N
panelControl.setPreferredSize(new java.awt.Dimension(616, 23));
panelControl.setRequestFocusEnabled(false);
lblCount.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/deck_pack.png"))); // NOI18N
lblCount.setText("999");
lblCount.setToolTipText("Number of all cards in this area.");
lblCount.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
lblCount.setFocusable(false);
lblCount.setInheritsPopupMenu(false);
lblCount.setRequestFocusEnabled(false);
lblCount.setVerifyInputWhenFocusTarget(false);
lblLandCount.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
lblLandCount.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_land.png"))); // NOI18N
lblLandCount.setText("999");
lblLandCount.setToolTipText("Number of lands.");
lblLandCount.setVerticalAlignment(javax.swing.SwingConstants.TOP);
lblLandCount.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
lblLandCount.setFocusable(false);
lblLandCount.setInheritsPopupMenu(false);
lblLandCount.setRequestFocusEnabled(false);
lblLandCount.setVerifyInputWhenFocusTarget(false);
lblCreatureCount.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
lblCreatureCount.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/type_creatures.png"))); // NOI18N
lblCreatureCount.setText("999");
lblCreatureCount.setToolTipText("Number of creatures.");
lblCreatureCount.setVerticalAlignment(javax.swing.SwingConstants.TOP);
lblCreatureCount.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
lblCreatureCount.setFocusable(false);
lblCreatureCount.setInheritsPopupMenu(false);
lblCreatureCount.setRequestFocusEnabled(false);
lblCreatureCount.setVerifyInputWhenFocusTarget(false);
chkPiles.setText("Piles");
chkPiles.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
chkPiles.setMargin(new java.awt.Insets(3, 2, 2, 2));
chkPiles.addActionListener(evt -> chkPilesActionPerformed(evt));
cbSortBy.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"SortBy"}));
cbSortBy.setToolTipText("Sort the cards if card view is active.");
cbSortBy.setMaximumSize(new java.awt.Dimension(120, 20));
cbSortBy.setMinimumSize(new java.awt.Dimension(120, 20));
cbSortBy.setName("SortBy"); // NOI18N
cbSortBy.setOpaque(false);
cbSortBy.setPreferredSize(new java.awt.Dimension(120, 20));
cbSortBy.addActionListener(evt -> cbSortByActionPerformed(evt));
bgView.add(jToggleListView);
jToggleListView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/list_panel.png"))); // NOI18N
jToggleListView.setToolTipText("Shows the cards as a list.");
jToggleListView.setBorder(null);
jToggleListView.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jToggleListView.setMargin(new java.awt.Insets(2, 6, 2, 6));
jToggleListView.setMaximumSize(new java.awt.Dimension(37, 25));
jToggleListView.setMinimumSize(new java.awt.Dimension(37, 25));
jToggleListView.setPreferredSize(new java.awt.Dimension(44, 22));
jToggleListView.addActionListener(evt -> jToggleListViewActionPerformed(evt));
bgView.add(jToggleCardView);
jToggleCardView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/buttons/card_panel.png"))); // NOI18N
jToggleCardView.setToolTipText("Shows the card as images.");
jToggleCardView.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jToggleCardView.setMargin(new java.awt.Insets(2, 6, 2, 6));
jToggleCardView.setPreferredSize(new java.awt.Dimension(40, 22));
jToggleCardView.addActionListener(evt -> jToggleCardViewActionPerformed(evt));
javax.swing.GroupLayout panelControlLayout = new javax.swing.GroupLayout(panelControl);
panelControl.setLayout(panelControlLayout);
panelControlLayout.setHorizontalGroup(
panelControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelControlLayout.createSequentialGroup()
.addComponent(lblCount)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblLandCount)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblCreatureCount)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chkPiles)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cbSortBy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jToggleListView, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleCardView, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelControlLayout.setVerticalGroup(
panelControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelControlLayout.createSequentialGroup()
.addGroup(panelControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCount)
.addComponent(lblLandCount)
.addComponent(lblCreatureCount)
.addComponent(chkPiles))
.addComponent(cbSortBy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleListView, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jToggleCardView, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
jToggleListView.getAccessibleContext().setAccessibleDescription("Switch between image and table view.");
panelCardArea.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
panelCardArea.setViewportView(cardArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelControl, javax.swing.GroupLayout.PREFERRED_SIZE, 467, Short.MAX_VALUE)
.addComponent(panelCardArea)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(panelControl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(panelCardArea, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void jToggleCardViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleCardViewActionPerformed
currentView = this;
panelCardArea.setViewportView(cardArea);
cbSortBy.setEnabled(true);
chkPiles.setEnabled(true);
PreferencesDialog.saveValue(PreferencesDialog.KEY_DRAFT_VIEW, "cardView");
redrawCards();
}//GEN-LAST:event_jToggleCardViewActionPerformed
private void jToggleListViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleListViewActionPerformed
currentView = mainModel;
panelCardArea.setViewportView(mainTable);
cbSortBy.setEnabled(false);
chkPiles.setEnabled(false);
PreferencesDialog.saveValue(PreferencesDialog.KEY_DRAFT_VIEW, "listView");
redrawCards();
}//GEN-LAST:event_jToggleListViewActionPerformed
private void cbSortByActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSortByActionPerformed
sortSetting.setSortBy((SortBy) cbSortBy.getSelectedItem());
drawCards(sortSetting);
}//GEN-LAST:event_cbSortByActionPerformed
private void chkPilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkPilesActionPerformed
sortSetting.setPilesToggle(chkPiles.isSelected());
drawCards(sortSetting);
}//GEN-LAST:event_chkPilesActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgView;
private javax.swing.JLayeredPane cardArea;
private javax.swing.JComboBox cbSortBy;
private javax.swing.JCheckBox chkPiles;
private javax.swing.JToggleButton jToggleCardView;
private javax.swing.JToggleButton jToggleListView;
private javax.swing.JLabel lblCount;
private javax.swing.JLabel lblCreatureCount;
private javax.swing.JLabel lblLandCount;
private javax.swing.JScrollPane panelCardArea;
private javax.swing.JPanel panelControl;
// End of variables declaration//GEN-END:variables
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() >= 1 && !e.isConsumed()) {
Object obj = e.getSource();
if ((e.getClickCount() & 1) == 0 && (e.getClickCount() > 0)) { // double clicks and repeated double clicks
e.consume();
if (obj instanceof Card) {
if (e.isAltDown()) {
cardEventSource.fireEvent(((Card) obj).getOriginal(), ClientEventType.ALT_DOUBLE_CLICK);
} else {
cardEventSource.fireEvent(((Card) obj).getOriginal(), ClientEventType.DOUBLE_CLICK);
}
} else if (obj instanceof MageCard) {
if (e.isAltDown()) {
cardEventSource.fireEvent(((MageCard) obj).getOriginal(), ClientEventType.ALT_DOUBLE_CLICK);
} else {
cardEventSource.fireEvent(((MageCard) obj).getOriginal(), ClientEventType.DOUBLE_CLICK);
}
}
}
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (!e.isConsumed()) {
Object obj = e.getSource();
if (obj instanceof MageCard) {
checkMenu(e, ((MageCard) obj).getOriginal());
} else {
checkMenu(e, null);
}
}
}
private void checkMenu(MouseEvent Me, SimpleCardView card) {
if (Me.isPopupTrigger()) {
Me.consume();
cardEventSource.fireEvent(card, Me.getComponent(), Me.getX(), Me.getY(), ClientEventType.SHOW_POP_UP_MENU);
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public void setDisplayNoCopies(boolean value) {
mainModel.setDisplayNoCopies(value);
}
@Override
public int cardsSize() {
return cards.size();
}
public void setSortBy(SortBy sortBy) {
if (sortBy != null) {
cbSortBy.setSelectedIndex(sortBy.ordinal());
}
}
public void setSortSetting(SortSetting sortSetting) {
this.sortSetting = sortSetting;
}
}
|
3e09ba883a6eb326ed66f9909043089a5df533d8 | 328 | java | Java | client/src/main/java/de/sebsprenger/grpc/helloworld/ClientApplication.java | sebsprenger/grpc-hello-world | 33e27d0dd62847246d4c22f064be2e912a413199 | [
"MIT"
] | null | null | null | client/src/main/java/de/sebsprenger/grpc/helloworld/ClientApplication.java | sebsprenger/grpc-hello-world | 33e27d0dd62847246d4c22f064be2e912a413199 | [
"MIT"
] | null | null | null | client/src/main/java/de/sebsprenger/grpc/helloworld/ClientApplication.java | sebsprenger/grpc-hello-world | 33e27d0dd62847246d4c22f064be2e912a413199 | [
"MIT"
] | null | null | null | 23.428571 | 68 | 0.792683 | 4,108 | package de.sebsprenger.grpc.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
|
3e09bab5c19edab6c77cec3e41a15847a7440a02 | 9,778 | java | Java | geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteFunction.java | monkeyherder/geode | 1d9e34cb7e9f8f87736e091ed98da62a91b5e6c2 | [
"Apache-2.0"
] | null | null | null | geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteFunction.java | monkeyherder/geode | 1d9e34cb7e9f8f87736e091ed98da62a91b5e6c2 | [
"Apache-2.0"
] | 2 | 2022-02-12T02:10:43.000Z | 2022-03-31T01:53:43.000Z | geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ExecuteFunction.java | s0/geode | a49e03a4b8c2e289a0cc3e17bde1043e5f2a669c | [
"Apache-2.0"
] | 1 | 2019-11-14T09:24:34.000Z | 2019-11-14T09:24:34.000Z | 44.853211 | 100 | 0.726018 | 4,109 | /*
* 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.geode.internal.cache.tier.sockets.command;
import java.io.IOException;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.execute.ResultSender;
import org.apache.geode.cache.operations.ExecuteFunctionOperationContext;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.execute.FunctionContextImpl;
import org.apache.geode.internal.cache.execute.FunctionStats;
import org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException;
import org.apache.geode.internal.cache.execute.MemberMappedArgument;
import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender;
import org.apache.geode.internal.cache.tier.Command;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.ServerSideHandshake;
import org.apache.geode.internal.cache.tier.sockets.BaseCommand;
import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage;
import org.apache.geode.internal.cache.tier.sockets.Message;
import org.apache.geode.internal.cache.tier.sockets.Part;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.security.AuthorizeRequest;
import org.apache.geode.internal.security.SecurityService;
/**
* This is the base command which read the parts for the MessageType.EXECUTE_FUNCTION.<br>
* If the hasResult byte is 1, then this command send back the result after the execution to the
* client else do not send the reply back to the client
*
* @since GemFire 5.8Beta
*/
public class ExecuteFunction extends BaseCommand {
private static final ExecuteFunction singleton = new ExecuteFunction();
public static Command getCommand() {
return singleton;
}
@Override
public void cmdExecute(final Message clientMessage, final ServerConnection serverConnection,
final SecurityService securityService, long start) throws IOException {
Object function = null;
Object args = null;
MemberMappedArgument memberMappedArg = null;
byte hasResult = 0;
try {
hasResult = clientMessage.getPart(0).getSerializedForm()[0];
if (hasResult == 1) {
serverConnection.setAsTrue(REQUIRES_RESPONSE);
serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
}
function = clientMessage.getPart(1).getStringOrObject();
args = clientMessage.getPart(2).getObject();
Part part = clientMessage.getPart(3);
if (part != null) {
memberMappedArg = (MemberMappedArgument) part.getObject();
}
} catch (ClassNotFoundException exception) {
logger.warn(String.format("Exception on server while executing function: %s",
function),
exception);
if (hasResult == 1) {
writeChunkedException(clientMessage, exception, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
}
if (function == null) {
final String message =
"The input function for the execute function request is null";
logger.warn("{}: {}", serverConnection.getName(), message);
sendError(hasResult, clientMessage, message, serverConnection);
return;
}
// Execute function on the cache
try {
Function<?> functionObject = null;
if (function instanceof String) {
functionObject = FunctionService.getFunction((String) function);
if (functionObject == null) {
final String message =
String.format("Function named %s is not registered to FunctionService",
function);
logger.warn("{}: {}", serverConnection.getName(), message);
sendError(hasResult, clientMessage, message, serverConnection);
return;
}
} else {
functionObject = (Function) function;
}
FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
// check if the caller is authorized to do this operation on server
functionObject.getRequiredPermissions(null, args).forEach(securityService::authorize);
AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
ExecuteFunctionOperationContext executeContext = null;
if (authzRequest != null) {
executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null,
args, functionObject.optimizeForWrite());
}
ChunkedMessage m = serverConnection.getFunctionResponseMessage();
m.setTransactionId(clientMessage.getTransactionId());
ResultSender resultSender = new ServerToClientFunctionResultSender(m,
MessageType.EXECUTE_FUNCTION_RESULT, serverConnection, functionObject, executeContext);
FunctionContext context = null;
InternalCache cache = serverConnection.getCache();
InternalDistributedMember localVM =
(InternalDistributedMember) cache.getDistributedSystem().getDistributedMember();
if (memberMappedArg != null) {
context = new FunctionContextImpl(cache, functionObject.getId(),
memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender);
} else {
context = new FunctionContextImpl(cache, functionObject.getId(), args, resultSender);
}
ServerSideHandshake handshake = serverConnection.getHandshake();
int earlierClientReadTimeout = handshake.getClientReadTimeout();
handshake.setClientReadTimeout(0);
try {
long startExecution = stats.startTime();
stats.startFunctionExecution(functionObject.hasResult());
if (logger.isDebugEnabled()) {
logger.debug("Executing Function on Server: " + serverConnection.toString()
+ "with context :" + context.toString());
}
cache.getInternalResourceManager().getHeapMonitor().checkForLowMemory(functionObject,
cache.getMyId());
functionObject.execute(context);
stats.endFunctionExecution(startExecution, functionObject.hasResult());
} catch (FunctionException functionException) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw functionException;
} catch (Exception exception) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw new FunctionException(exception);
} finally {
handshake.setClientReadTimeout(earlierClientReadTimeout);
}
} catch (IOException ioException) {
logger.warn(String.format("Exception on server while executing function: %s",
function),
ioException);
String message =
"Server could not send the reply";
sendException(hasResult, clientMessage, message, serverConnection, ioException);
} catch (InternalFunctionInvocationTargetException internalfunctionException) {
// Fix for #44709: User should not be aware of
// InternalFunctionInvocationTargetException. No instance of
// InternalFunctionInvocationTargetException is giving useful
// information to user to take any corrective action hence logging
// this at fine level logging
// 1> When bucket is moved
// 2> Incase of HA FucntionInvocationTargetException thrown. Since
// it is HA, fucntion will be reexecuted on right node
// 3> Multiple target nodes found for single hop operation
// 4> in case of HA member departed
if (logger.isDebugEnabled()) {
logger.debug(String.format("Exception on server while executing function: %s",
new Object[] {function}),
internalfunctionException);
}
final String message = internalfunctionException.getMessage();
sendException(hasResult, clientMessage, message, serverConnection, internalfunctionException);
} catch (Exception e) {
logger.warn(String.format("Exception on server while executing function: %s",
function),
e);
final String message = e.getMessage();
sendException(hasResult, clientMessage, message, serverConnection, e);
}
}
private void sendException(byte hasResult, Message msg, String message,
ServerConnection serverConnection, Throwable e) throws IOException {
if (hasResult == 1) {
writeFunctionResponseException(msg, MessageType.EXCEPTION, serverConnection, e);
serverConnection.setAsTrue(RESPONDED);
}
}
private void sendError(byte hasResult, Message msg, String message,
ServerConnection serverConnection) throws IOException {
if (hasResult == 1) {
writeFunctionResponseError(msg, MessageType.EXECUTE_FUNCTION_ERROR, message,
serverConnection);
serverConnection.setAsTrue(RESPONDED);
}
}
}
|
3e09baf8a6d9cf26c3d91dfc3aec27483d29af64 | 12,608 | java | Java | src/core/src/main/java/org/locationtech/geogig/repository/Repository.java | jodygarnett/geogig | ee4a94b28ecb65cc5822bd84b629ae6eaccefde6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/core/src/main/java/org/locationtech/geogig/repository/Repository.java | jodygarnett/geogig | ee4a94b28ecb65cc5822bd84b629ae6eaccefde6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/core/src/main/java/org/locationtech/geogig/repository/Repository.java | jodygarnett/geogig | ee4a94b28ecb65cc5822bd84b629ae6eaccefde6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 31.758186 | 99 | 0.653791 | 4,110 | /* Copyright (c) 2012-2014 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.repository;
import java.io.Closeable;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import org.locationtech.geogig.api.AbstractGeoGigOp;
import org.locationtech.geogig.api.Context;
import org.locationtech.geogig.api.Node;
import org.locationtech.geogig.api.NodeRef;
import org.locationtech.geogig.api.ObjectId;
import org.locationtech.geogig.api.Platform;
import org.locationtech.geogig.api.Ref;
import org.locationtech.geogig.api.RevCommit;
import org.locationtech.geogig.api.RevFeature;
import org.locationtech.geogig.api.RevObject;
import org.locationtech.geogig.api.RevTree;
import org.locationtech.geogig.api.plumbing.FindTreeChild;
import org.locationtech.geogig.api.plumbing.RefParse;
import org.locationtech.geogig.api.plumbing.ResolveGeogigURI;
import org.locationtech.geogig.api.plumbing.ResolveTreeish;
import org.locationtech.geogig.api.plumbing.RevObjectParse;
import org.locationtech.geogig.api.plumbing.RevParse;
import org.locationtech.geogig.api.porcelain.ConfigOp;
import org.locationtech.geogig.api.porcelain.ConfigOp.ConfigAction;
import org.locationtech.geogig.di.Singleton;
import org.locationtech.geogig.storage.BlobStore;
import org.locationtech.geogig.storage.ConfigDatabase;
import org.locationtech.geogig.storage.ConflictsDatabase;
import org.locationtech.geogig.storage.DeduplicationService;
import org.locationtech.geogig.storage.GraphDatabase;
import org.locationtech.geogig.storage.ObjectDatabase;
import org.locationtech.geogig.storage.ObjectInserter;
import org.locationtech.geogig.storage.RefDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
/**
* A repository is a collection of commits, each of which is an archive of what the project's
* working tree looked like at a past date, whether on your machine or someone else's.
* <p>
* It also defines HEAD (see below), which identifies the branch or commit the current working tree
* stemmed from. Lastly, it contains a set of branches and tags, to identify certain commits by
* name.
* </p>
*
* @see WorkingTree
*/
@Singleton
public class Repository {
private static Logger LOGGER = LoggerFactory.getLogger(Repository.class);
public static interface RepositoryListener {
public void opened(Repository repo);
public void closed();
}
private List<RepositoryListener> listeners = Lists.newCopyOnWriteArrayList();
private Context context;
private URI repositoryLocation;
public static final String DEPTH_CONFIG_KEY = "core.depth";
private ExecutorService executor;
@Inject
public Repository(Context context, ExecutorService executor) {
this.context = context;
this.executor = executor;
}
public void addListener(RepositoryListener listener) {
if (!this.listeners.contains(listener)) {
this.listeners.add(listener);
}
}
public void configure() throws RepositoryConnectionException {
context.refDatabase().configure();
context.objectDatabase().configure();
context.graphDatabase().configure();
}
public void open() throws RepositoryConnectionException {
Optional<URI> repoUrl = command(ResolveGeogigURI.class).call();
Preconditions.checkState(repoUrl.isPresent(), "Repository URL can't be located");
this.repositoryLocation = repoUrl.get();
context.refDatabase().checkConfig();
context.objectDatabase().checkConfig();
context.graphDatabase().checkConfig();
context.refDatabase().create();
context.objectDatabase().open();
context.graphDatabase().open();
for (RepositoryListener l : listeners) {
l.opened(this);
}
}
/**
* Closes the repository.
*/
public synchronized void close() {
close(context.refDatabase());
close(context.objectDatabase());
close(context.graphDatabase());
for (RepositoryListener l : listeners) {
l.closed();
}
executor.shutdownNow();
close(context.configDatabase());
}
private void close(Closeable db) {
try {
db.close();
} catch (Exception e) {
LOGGER.error("Error closing database " + db, e);
}
}
public URI getLocation() {
return repositoryLocation;
}
/**
* Finds and returns an instance of a command of the specified class.
*
* @param commandClass the kind of command to locate and instantiate
* @return a new instance of the requested command class, with its dependencies resolved
*/
public <T extends AbstractGeoGigOp<?>> T command(Class<T> commandClass) {
return context.command(commandClass);
}
/**
* Test if a blob exists in the object database
*
* @param id the ID of the blob in the object database
* @return true if the blob exists with the parameter ID, false otherwise
*/
public boolean blobExists(final ObjectId id) {
return context().objectDatabase().exists(id);
}
/**
* @param revStr the string to parse
* @return the parsed {@link Ref}, or {@link Optional#absent()} if it did not parse.
*/
public Optional<Ref> getRef(final String revStr) {
Optional<Ref> ref = command(RefParse.class).setName(revStr).call();
return ref;
}
/**
* @return the {@link Ref} pointed to by HEAD, or {@link Optional#absent()} if it could not be
* resolved.
*/
public Optional<Ref> getHead() {
return getRef(Ref.HEAD);
}
/**
* Determines if a commit with the given {@link ObjectId} exists in the object database.
*
* @param id the id to look for
* @return true if the object was found, false otherwise
*/
public boolean commitExists(final ObjectId id) {
try {
RevObject revObject = context().objectDatabase().get(id);
return revObject instanceof RevCommit;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Gets the {@link RevCommit} with the given {@link ObjectId} from the object database.
*
* @param commitId the {@code ObjectId} for the commit
* @return the {@code RevCommit}
*/
public RevCommit getCommit(final ObjectId commitId) {
RevCommit commit = context().objectDatabase().getCommit(commitId);
return commit;
}
/**
* Test if a tree exists in the object database
*
* @param id the ID of the tree in the object database
* @return true if the tree exists with the parameter ID, false otherwise
*/
public boolean treeExists(final ObjectId id) {
try {
context().objectDatabase().getTree(id);
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
/**
* @return the {@link ObjectId} of the root tree
*/
public ObjectId getRootTreeId() {
// find the root tree
ObjectId commitId = command(RevParse.class).setRefSpec(Ref.HEAD).call().get();
if (commitId.isNull()) {
return commitId;
}
RevCommit commit = command(RevObjectParse.class).setRefSpec(commitId.toString())
.call(RevCommit.class).get();
ObjectId treeId = commit.getTreeId();
return treeId;
}
/**
* @return an {@link ObjectInserter} to insert objects into the object database
*/
@Deprecated
public ObjectInserter newObjectInserter() {
return context().objectDatabase().newObjectInserter();
}
/**
* @param contentId the {@link ObjectId} of the feature to get
* @return the {@link RevFeature} that was found in the object database
*/
public RevFeature getFeature(final ObjectId contentId) {
RevFeature revFeature = context().objectDatabase().getFeature(contentId);
return revFeature;
}
/**
* @return the existing {@link RevTree} pointed to by HEAD, or a new {@code RevTree} if it did
* not exist
*/
public RevTree getOrCreateHeadTree() {
Optional<ObjectId> headTreeId = command(ResolveTreeish.class).setTreeish(Ref.HEAD).call();
if (!headTreeId.isPresent()) {
return RevTree.EMPTY;
}
return getTree(headTreeId.get());
}
/**
* @param treeId the tree to retrieve
* @return the {@link RevTree} referred to by the given {@link ObjectId}
*/
public RevTree getTree(ObjectId treeId) {
return command(RevObjectParse.class).setObjectId(treeId).call(RevTree.class).get();
}
/**
* @param path the path to search for
* @return an {@link Optional} of the {@link Node} for the child, or {@link Optional#absent()}
* if it wasn't found
*/
public Optional<Node> getRootTreeChild(String path) {
Optional<NodeRef> nodeRef = command(FindTreeChild.class).setChildPath(path).call();
if (nodeRef.isPresent()) {
return Optional.of(nodeRef.get().getNode());
} else {
return Optional.absent();
}
}
/**
* Search the given tree for the child path.
*
* @param tree the tree to search
* @param childPath the path to search for
* @return an {@link Optional} of the {@link Node} for the child path, or
* {@link Optional#absent()} if it wasn't found
*/
public Optional<Node> getTreeChild(RevTree tree, String childPath) {
Optional<NodeRef> nodeRef = command(FindTreeChild.class).setParent(tree)
.setChildPath(childPath).call();
if (nodeRef.isPresent()) {
return Optional.of(nodeRef.get().getNode());
} else {
return Optional.absent();
}
}
/**
* Gets the depth of the repository, or {@link Optional#absent} if this is not a shallow clone.
*
* @return the depth
*/
public Optional<Integer> getDepth() {
int repoDepth = 0;
Optional<Map<String, String>> depthResult = command(ConfigOp.class)
.setAction(ConfigAction.CONFIG_GET).setName(DEPTH_CONFIG_KEY).call();
if (depthResult.isPresent()) {
String depthString = depthResult.get().get(DEPTH_CONFIG_KEY);
if (depthString != null) {
repoDepth = Integer.parseInt(depthString);
}
}
if (repoDepth == 0) {
return Optional.absent();
}
return Optional.of(repoDepth);
}
/**
* @return true if this is a sparse (mapped) clone.
*/
public boolean isSparse() {
Optional<Map<String, String>> sparseResult = command(ConfigOp.class)
.setAction(ConfigAction.CONFIG_GET).setName("sparse.filter").call();
return sparseResult.isPresent();
}
public Context context() {
return context;
}
// @Override
public WorkingTree workingTree() {
return context.workingTree();
}
// @Override
public StagingArea index() {
return context.index();
}
// @Override
public RefDatabase refDatabase() {
return context.refDatabase();
}
// @Override
public Platform platform() {
return context.platform();
}
// @Override
public ObjectDatabase objectDatabase() {
return context.objectDatabase();
}
// @Override
public ConflictsDatabase conflictsDatabase() {
return context.conflictsDatabase();
}
// @Override
public ConfigDatabase configDatabase() {
return context.configDatabase();
}
// @Override
public GraphDatabase graphDatabase() {
return context.graphDatabase();
}
// @Override
public DeduplicationService deduplicationService() {
return context.deduplicationService();
}
public BlobStore blobStore() {
return context().blobStore();
}
}
|
3e09bb49c24b0d4a72dd4626833a93bfac1c7e9d | 676 | java | Java | src/main/com/java/example/effectivejava/OperationUsingLambda.java | kpunith8/java-samples | 1e1853d6fad0a7a76ac14a6b1ad310d6aff21567 | [
"MIT"
] | 2 | 2018-10-30T18:43:14.000Z | 2019-08-21T08:22:22.000Z | src/main/com/java/example/effectivejava/OperationUsingLambda.java | kpunith8/java-samples | 1e1853d6fad0a7a76ac14a6b1ad310d6aff21567 | [
"MIT"
] | 1 | 2022-03-27T07:55:42.000Z | 2022-03-27T07:55:42.000Z | src/main/com/java/example/effectivejava/OperationUsingLambda.java | kpunith8/java-samples | 1e1853d6fad0a7a76ac14a6b1ad310d6aff21567 | [
"MIT"
] | null | null | null | 21.125 | 70 | 0.600592 | 4,111 | package main.com.java.example.effectivejava;
import java.util.function.DoubleBinaryOperator;
public enum OperationUsingLambda
{
PLUS("+", (x, y) -> x + y),
MINUS("-", (x, y) -> x - y),
TIMES("*", (x, y) -> x * y),
DEVIDE("/", (x, y) -> x / y);
private final String symbol;
private final DoubleBinaryOperator operator;
OperationUsingLambda(String symbol, DoubleBinaryOperator operator)
{
this.symbol = symbol;
this.operator = operator;
}
@Override
public String toString()
{
return symbol;
}
public double apply(double x, double y)
{
return operator.applyAsDouble(x, y);
}
}
|
3e09bb5a249a8efb8cd90408bc57d7849b1ab327 | 1,958 | java | Java | app/src/main/java/com/jl/libjpeg/MainActivity.java | chinagzitbeyond/libjpeg | 01edb0cd9f6ce53eda2cacdfc7edf55396fcd067 | [
"Apache-2.0"
] | 1 | 2021-09-10T09:15:47.000Z | 2021-09-10T09:15:47.000Z | app/src/main/java/com/jl/libjpeg/MainActivity.java | chinagzitbeyond/libjpeg | 01edb0cd9f6ce53eda2cacdfc7edf55396fcd067 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/jl/libjpeg/MainActivity.java | chinagzitbeyond/libjpeg | 01edb0cd9f6ce53eda2cacdfc7edf55396fcd067 | [
"Apache-2.0"
] | null | null | null | 34.964286 | 88 | 0.554137 | 4,112 | package com.jl.libjpeg;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import net.bither.util.NativeUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testJpeg();
}
private void testJpeg() {
new Thread(new Runnable() {
public void run() {
try {
int quality = 90;
InputStream in = getResources().getAssets()
.open("test.jpg");
Bitmap bit = BitmapFactory.decodeStream(in);
File dirFile = getExternalCacheDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
File originalFile = new File(dirFile, "original.jpg");
FileOutputStream fileOutputStream = new FileOutputStream(
originalFile);
bit.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);
File jpegTrueFile = new File(dirFile, "jpegtrue.jpg");
File jpegFalseFile = new File(dirFile, "jpegfalse.jpg");
NativeUtil.compressBitmap(bit, quality,
jpegTrueFile.getAbsolutePath(), true);
NativeUtil.compressBitmap(bit, quality,
jpegFalseFile.getAbsolutePath(), false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
} |
3e09bbfdc22bc3b7cf250aa36c297d066c19caa7 | 3,997 | java | Java | src/main/java/com/rest/demo/model/Usuario.java | JDogeStyle/spring-rest-demo | f73d8a19a0966983028e5a999f0f8d7c59b4f5c2 | [
"MIT"
] | null | null | null | src/main/java/com/rest/demo/model/Usuario.java | JDogeStyle/spring-rest-demo | f73d8a19a0966983028e5a999f0f8d7c59b4f5c2 | [
"MIT"
] | null | null | null | src/main/java/com/rest/demo/model/Usuario.java | JDogeStyle/spring-rest-demo | f73d8a19a0966983028e5a999f0f8d7c59b4f5c2 | [
"MIT"
] | null | null | null | 22.455056 | 88 | 0.717788 | 4,113 | package com.rest.demo.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Entity
@Table(name="usuario")
@JsonIgnoreProperties(ignoreUnknown=true)
@NamedQuery(name="Usuario.findAll", query="SELECT u FROM Usuario u")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
private static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(11);
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private Long idusuario;
@NotNull
@Size(min=3, max=45)
@Column(nullable=false, length=45, unique=true)
private String username;
@NotNull
@JsonProperty(access = Access.WRITE_ONLY)
@Size(min=60, max=60)
@Column(nullable=false, length=60)
private String password;
@NotNull
@Size(min=3, max=45)
@Column(nullable=false, length=45)
private String nombre;
@NotNull
@Size(min=3, max=45)
@Column(nullable=false, length=45)
private String paterno;
@NotNull
@Size(min=3, max=45)
@Column(nullable=false, length=45)
private String materno;
@NotNull
@Size(min=3, max=45)
@Column(nullable=false, length=45, unique=true)
private String telefono;
@NotNull
@Pattern(regexp="^\\d{8}$")
@Column(nullable=false, length=8, unique=true)
private String dni;
@NotNull
@Column(nullable=false)
private boolean estado = true;
//bi-directional many-to-many association to Role
@JsonIgnore
@ManyToMany
@JoinTable(
name="user_roles"
, joinColumns={
@JoinColumn(name="idusuario", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="idrol", nullable=false)
}
)
private List<Role> roles;
public Usuario() {
}
public Long getIdusuario() {
return this.idusuario;
}
public void setIdusuario(Long idusuario) {
this.idusuario = idusuario;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = PASSWORD_ENCODER.encode(password);
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPaterno() {
return this.paterno;
}
public void setPaterno(String paterno) {
this.paterno = paterno;
}
public String getMaterno() {
return this.materno;
}
public void setMaterno(String materno) {
this.materno = materno;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getDni() {
return this.dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public boolean isEstado() {
return estado;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
public List<Role> getRoles() {
return this.roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
} |
3e09bcac6c0d963b0ff6f107837abbc7e8845689 | 322 | java | Java | src/main/java/eu/lucaventuri/common/ConcurrentHashSet.java | lucav76/Fibry | bd033fddfcb24ec437eea1f38c5b82513868aacd | [
"MIT"
] | 177 | 2019-08-10T07:58:06.000Z | 2022-03-25T13:49:12.000Z | src/main/java/eu/lucaventuri/common/ConcurrentHashSet.java | psycho-ir/Fibry | b5f12a40782da6ee42807c1b9ffa5a1edfc968d6 | [
"MIT"
] | 7 | 2019-09-19T00:38:58.000Z | 2021-04-27T06:04:32.000Z | src/main/java/eu/lucaventuri/common/ConcurrentHashSet.java | lucav76/Fibry | bd033fddfcb24ec437eea1f38c5b82513868aacd | [
"MIT"
] | 22 | 2019-07-08T06:41:41.000Z | 2022-03-26T15:32:58.000Z | 24.769231 | 68 | 0.73913 | 4,114 | package eu.lucaventuri.common;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class ConcurrentHashSet {
private ConcurrentHashSet() {}
public static <K> Set<K> build() {
return Collections.newSetFromMap(new ConcurrentHashMap<>());
}
}
|
3e09bcc7492e83feab888b659460108aa1e01875 | 6,416 | java | Java | src/plantuml-asl/src/net/sourceforge/plantuml/cucadiagram/Member.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 174 | 2016-03-02T20:22:19.000Z | 2022-03-18T09:28:05.000Z | src/plantuml-asl/src/net/sourceforge/plantuml/cucadiagram/Member.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 314 | 2016-03-01T06:59:04.000Z | 2022-03-21T19:59:08.000Z | src/plantuml-asl/src/net/sourceforge/plantuml/cucadiagram/Member.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 29 | 2017-04-29T06:52:27.000Z | 2022-02-22T01:52:16.000Z | 28.7713 | 107 | 0.710411 | 4,115 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.cucadiagram;
import net.sourceforge.plantuml.Guillemet;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.UrlBuilder;
import net.sourceforge.plantuml.UrlBuilder.ModeUrl;
import net.sourceforge.plantuml.command.regex.Matcher2;
import net.sourceforge.plantuml.command.regex.MyPattern;
import net.sourceforge.plantuml.command.regex.Pattern2;
import net.sourceforge.plantuml.skin.VisibilityModifier;
public class Member implements CharSequence {
private final String display;
private final CharSequence raw;
private final boolean staticModifier;
private final boolean abstractModifier;
private final Url url;
private final boolean hasUrl;
private final VisibilityModifier visibilityModifier;
@Override
public String toString() {
return raw.toString();
}
public char charAt(int index) {
return raw.charAt(index);
}
public int length() {
return raw.length();
}
public CharSequence subSequence(int start, int end) {
return raw.subSequence(start, end);
}
public static Member method(CharSequence tmpDisplay) {
return new Member(true, tmpDisplay, true);
}
public static Member field(CharSequence tmpDisplay) {
return new Member(true, tmpDisplay, false);
}
public static Member method(CharSequence tmpDisplay, boolean manageModifier) {
return new Member(manageModifier, tmpDisplay, true);
}
public static Member field(CharSequence tmpDisplay, boolean manageModifier) {
return new Member(manageModifier, tmpDisplay, false);
}
private Member(boolean manageModifier, CharSequence tmpDisplay, boolean isMethod) {
this.raw = tmpDisplay;
tmpDisplay = tmpDisplay.toString().replaceAll("(?i)\\{(method|field)\\}\\s*", "");
if (manageModifier) {
final Pattern2 finalUrl = MyPattern.cmpile("^(.*?)(?:\\[(" + UrlBuilder.getRegexp() + ")\\])?$");
final Matcher2 matcher = finalUrl.matcher(tmpDisplay);
if (matcher.matches() == false) {
throw new IllegalStateException();
}
tmpDisplay = matcher.group(1);
final String urlString = matcher.group(2);
if (urlString == null) {
this.url = null;
} else {
this.url = new UrlBuilder(null, ModeUrl.STRICT).getUrl(urlString);
}
} else {
this.url = null;
}
this.hasUrl = this.url != null;
final String lower = StringUtils.goLowerCase(tmpDisplay.toString());
if (manageModifier) {
this.staticModifier = lower.contains("{static}") || lower.contains("{classifier}");
this.abstractModifier = lower.contains("{abstract}");
String displayClean = tmpDisplay.toString().replaceAll("(?i)\\{(static|classifier|abstract)\\}\\s*", "")
.trim();
if (displayClean.length() == 0) {
displayClean = " ";
}
if (VisibilityModifier.isVisibilityCharacter(displayClean)) {
visibilityModifier = VisibilityModifier.getVisibilityModifier(displayClean, isMethod == false);
this.display = StringUtils.trin(Guillemet.GUILLEMET.manageGuillemet(displayClean.substring(1)));
} else {
this.display = Guillemet.GUILLEMET.manageGuillemet(displayClean);
visibilityModifier = null;
}
} else {
this.staticModifier = false;
this.visibilityModifier = null;
this.abstractModifier = false;
tmpDisplay = StringUtils.trin(tmpDisplay.toString());
this.display = tmpDisplay.length() == 0 ? " "
: Guillemet.GUILLEMET.manageGuillemet(StringUtils.trin(tmpDisplay.toString()));
}
}
public String getDisplay(boolean withVisibilityChar) {
if (withVisibilityChar) {
return getDisplayWithVisibilityChar();
}
return getDisplayWithoutVisibilityChar();
}
private String getDisplayWithoutVisibilityChar() {
return display;
}
private String getDisplayWithVisibilityChar() {
if (isPrivate()) {
return "-" + display;
}
if (isPublic()) {
return "+" + display;
}
if (isPackagePrivate()) {
return "~" + display;
}
if (isProtected()) {
return "#" + display;
}
if (isIEMandatory()) {
return "*" + display;
}
return display;
}
@Override
public boolean equals(Object obj) {
final Member other = (Member) obj;
return this.display.equals(other.display);
}
@Override
public int hashCode() {
return display.hashCode();
}
public final boolean isStatic() {
return staticModifier;
}
public final boolean isAbstract() {
return abstractModifier;
}
private boolean isPrivate() {
return visibilityModifier == VisibilityModifier.PRIVATE_FIELD
|| visibilityModifier == VisibilityModifier.PRIVATE_METHOD;
}
private boolean isProtected() {
return visibilityModifier == VisibilityModifier.PROTECTED_FIELD
|| visibilityModifier == VisibilityModifier.PROTECTED_METHOD;
}
private boolean isPublic() {
return visibilityModifier == VisibilityModifier.PUBLIC_FIELD
|| visibilityModifier == VisibilityModifier.PUBLIC_METHOD;
}
private boolean isPackagePrivate() {
return visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_FIELD
|| visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_METHOD;
}
private boolean isIEMandatory() {
return visibilityModifier == VisibilityModifier.IE_MANDATORY;
}
public final VisibilityModifier getVisibilityModifier() {
return visibilityModifier;
}
public final Url getUrl() {
return url;
}
public boolean hasUrl() {
return hasUrl;
}
}
|
3e09bcdcca970aeb2b958f35b2d1b01fbe941497 | 775 | java | Java | server-common/src/main/java/com/data2/easybuild/server/common/aop/AbstractRestAop.java | data2/easybuild-framework | bc7a5bdd983a87dc4347a1f87be8ad83d62e3185 | [
"Apache-2.0"
] | 2 | 2021-09-17T12:49:33.000Z | 2021-09-17T13:45:04.000Z | server-common/src/main/java/com/data2/easybuild/server/common/aop/AbstractRestAop.java | data2/easybuild-framework | bc7a5bdd983a87dc4347a1f87be8ad83d62e3185 | [
"Apache-2.0"
] | null | null | null | server-common/src/main/java/com/data2/easybuild/server/common/aop/AbstractRestAop.java | data2/easybuild-framework | bc7a5bdd983a87dc4347a1f87be8ad83d62e3185 | [
"Apache-2.0"
] | 1 | 2021-11-19T08:38:40.000Z | 2021-11-19T08:38:40.000Z | 23.484848 | 69 | 0.629677 | 4,116 | package com.data2.easybuild.server.common.aop;
import com.data2.easybuild.api.common.dto.Input;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.Objects;
/**
* @author data2
* @description
* @date 2020/11/27 下午9:30
*/
public abstract class AbstractRestAop extends AbstractOpenApiAop {
public Object doRestApi(ProceedingJoinPoint proceedingJoinPoint){
Object[] args = proceedingJoinPoint.getArgs();
if (!Objects.isNull(args) && args.length > 0){
for(Object arg : args){
if (arg instanceof Input){
this.writeParam((Input)arg);
}
}
}
return super.doApi(proceedingJoinPoint);
}
// 预留功能
private void writeParam(Input arg) {
}
}
|
3e09be4c0719c5feb21d3f831ad0faa667be628b | 857 | java | Java | mymall-mbg/src/main/java/com/macro/mymall/mbg/mapper/UmsRoleMapper.java | zewei0920/bigfoot | 4e0320871273579424479a1e585d587871cb4928 | [
"Apache-2.0"
] | 1 | 2020-04-12T08:42:56.000Z | 2020-04-12T08:42:56.000Z | mymall-mbg/src/main/java/com/macro/mymall/mbg/mapper/UmsRoleMapper.java | zewei0920/mymall | 4e0320871273579424479a1e585d587871cb4928 | [
"Apache-2.0"
] | 4 | 2020-03-24T17:02:20.000Z | 2020-03-31T03:05:11.000Z | mymall-mbg/src/main/java/com/macro/mymall/mbg/mapper/UmsRoleMapper.java | zewei0920/bigfoot | 4e0320871273579424479a1e585d587871cb4928 | [
"Apache-2.0"
] | null | null | null | 28.566667 | 108 | 0.772462 | 4,117 | package com.macro.mymall.mbg.mapper;
import com.macro.mymall.mbg.model.UmsRole;
import com.macro.mymall.mbg.model.UmsRoleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UmsRoleMapper {
long countByExample(UmsRoleExample example);
int deleteByExample(UmsRoleExample example);
int deleteByPrimaryKey(Long id);
int insert(UmsRole record);
int insertSelective(UmsRole record);
List<UmsRole> selectByExample(UmsRoleExample example);
UmsRole selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UmsRole record, @Param("example") UmsRoleExample example);
int updateByExample(@Param("record") UmsRole record, @Param("example") UmsRoleExample example);
int updateByPrimaryKeySelective(UmsRole record);
int updateByPrimaryKey(UmsRole record);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.