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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1b7a13cc09c8639f69504576178810c21e50ec | 1,172 | java | Java | src/main/java/org/semsys/helper/Utility.java | fekaputra/course-tutorial | 7a382a6381f44bebd534434d4f436e6a981818a2 | [
"MIT"
] | 1 | 2021-12-02T20:38:39.000Z | 2021-12-02T20:38:39.000Z | src/main/java/org/semsys/helper/Utility.java | fekaputra/course-tutorial | 7a382a6381f44bebd534434d4f436e6a981818a2 | [
"MIT"
] | null | null | null | src/main/java/org/semsys/helper/Utility.java | fekaputra/course-tutorial | 7a382a6381f44bebd534434d4f436e6a981818a2 | [
"MIT"
] | 1 | 2020-08-06T22:00:49.000Z | 2020-08-06T22:00:49.000Z | 40.413793 | 89 | 0.738908 | 11,646 | package org.semsys.helper;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Utility {
public static final String REMOTE_SPARQL_ENDPOINT = "http://128.131.169.17:7200";
public static final String REMOTE_REPO_ID = "course";
public static final String NS_EXAMPLE = "http://semantics.id/ns/example/";
public static final String NS_MOVIE = "http://semantics.id/ns/example/movie#";
public static final String INPUT_FILE = "./input/graph/movie.ttl";
public static final String INSTANCE_FILE = "./input/graph/movie-instances.ttl";
public static final String Q1_SELECT = "./input/query/Q1_SELECT_allmovies.sparql";
public static final String Q2_SELECT = "./input/query/Q2_SELECT_oldeststudio.sparql";
public static final String Q3_CONSTRUCT = "./input/query/Q3_CONSTRUCT_family.sparql";
public static final String OUTPUT_FILE = "./output/output.ttl";
public static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
|
3e1b7a6bb305d1a9c6b7f262d9bb9f74224fc553 | 234 | java | Java | ex2/src/AST/AST_CLASS_DECLER.java | galtoubul/compilation | f614e2e7a00928a664d65a9de4429c2e3222fc52 | [
"MIT"
] | null | null | null | ex2/src/AST/AST_CLASS_DECLER.java | galtoubul/compilation | f614e2e7a00928a664d65a9de4429c2e3222fc52 | [
"MIT"
] | null | null | null | ex2/src/AST/AST_CLASS_DECLER.java | galtoubul/compilation | f614e2e7a00928a664d65a9de4429c2e3222fc52 | [
"MIT"
] | null | null | null | 19.5 | 60 | 0.67094 | 11,647 | package AST;
public class AST_CLASS_DECLER extends AST_CLASS_DEC{
public String id;
public AST_CFIELD_LIST cf;
public AST_CLASS_DECLER(String id, AST_CFIELD_LIST cf) {
this.id = id;
this.cf = cf;
}
}
|
3e1b7bc7395c6898b672df16238b9e0a78a21383 | 1,170 | java | Java | relish-core/src/main/java/uk/co/blackpepper/relish/core/Widget.java | davidgriffithsbp/relish | 2db2fa5e1446af201a382d5d833248471628cc5f | [
"MIT"
] | 1 | 2018-05-14T16:44:30.000Z | 2018-05-14T16:44:30.000Z | relish-core/src/main/java/uk/co/blackpepper/relish/core/Widget.java | BlackPepperSoftware/relish | 2db2fa5e1446af201a382d5d833248471628cc5f | [
"MIT"
] | null | null | null | relish-core/src/main/java/uk/co/blackpepper/relish/core/Widget.java | BlackPepperSoftware/relish | 2db2fa5e1446af201a382d5d833248471628cc5f | [
"MIT"
] | null | null | null | 17.205882 | 72 | 0.52906 | 11,648 | package uk.co.blackpepper.relish.core;
/**
* The type Widget.
*
* @param <T> the type parameter
*/
public abstract class Widget<T> extends Component {
private T peer;
/**
* Instantiates a new Widget.
*
* @param peer the peer
* @param parent the parent
*/
public Widget(T peer, Component parent) {
super(parent);
if (parent == null) {
throw new IllegalArgumentException("Parent cannot be null");
}
parent.assertVisible();
this.peer = peer;
}
/**
* Get t.
*
* @return the t
*/
public T get() {
return peer;
}
/**
* Click.
*/
public abstract void click();
/**
* Assert invisible.
*/
public abstract void assertInvisible();
/**
* Assert invisible.
*/
public abstract void assertVisible();
/**
* Assert disabled.
*/
public abstract void assertDisabled();
/**
* Assert enabled.
*/
public abstract void assertEnabled();
/**
* Scroll to widget.
*
* @return the widget
*/
public abstract Widget<T> scrollTo();
}
|
3e1b7becaba624d6aa6d83e28d82e9ae97edf329 | 2,570 | java | Java | src/main/java/com/ibm/cusp/graph/errors/CuspExecutionError.java | IBM/cusp | 1599b326f4686c81e238e17e0b7e80b723965793 | [
"MIT"
] | 1 | 2021-06-06T23:33:08.000Z | 2021-06-06T23:33:08.000Z | src/main/java/com/ibm/cusp/graph/errors/CuspExecutionError.java | IBM/cusp | 1599b326f4686c81e238e17e0b7e80b723965793 | [
"MIT"
] | 6 | 2020-11-16T15:01:53.000Z | 2021-12-16T13:55:54.000Z | src/main/java/com/ibm/cusp/graph/errors/CuspExecutionError.java | IBM/cusp | 1599b326f4686c81e238e17e0b7e80b723965793 | [
"MIT"
] | 3 | 2021-01-07T18:24:15.000Z | 2021-09-17T21:27:54.000Z | 35.205479 | 100 | 0.703502 | 11,649 | /**
* Copyright (c) 2020 International Business Machines
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.ibm.cusp.graph.errors;
import java.text.MessageFormat;
public class CuspExecutionError extends Exception implements CuspError<CuspErrorCode> {
private final String description;
private final CuspErrorCode code;
public CuspExecutionError(Throwable t, CuspErrorCode code, String description) {
super(code + ": " + description, t);
this.code = code;
this.description = description;
}
public CuspExecutionError(CuspErrorCode code, String description) {
super(code + ": " + description);
this.code = code;
this.description = description;
}
public CuspExecutionError(CuspErrorCode code, String description, Object... args) {
super(code + ": " + MessageFormat.format(description, args));
this.code = code;
this.description = description;
}
public CuspExecutionError(Throwable t, CuspErrorCode code, String description, Object... args) {
super(code + ": " + MessageFormat.format(description, args), t);
this.code = code;
this.description = MessageFormat.format(description, args);
}
@Override
public CuspErrorCode getCode() {
return code;
}
@Override
public String getDescription() {
return description;
}
@Override
public String toString() {
return MessageFormat.format("Error {0}: {1}", code.name(), description);
}
}
|
3e1b7c06298678af59f66264a8e57998a373fe78 | 3,792 | java | Java | tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 945 | 2018-12-13T00:39:04.000Z | 2020-10-01T04:17:02.000Z | tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 923 | 2019-01-18T01:12:04.000Z | 2020-10-01T02:17:11.000Z | tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 375 | 2018-12-23T06:40:33.000Z | 2020-10-01T02:49:20.000Z | 27.678832 | 99 | 0.718882 | 11,650 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.tsfile.read.filter;
import org.apache.iotdb.tsfile.read.filter.basic.Filter;
import org.apache.iotdb.tsfile.read.filter.factory.FilterType;
import org.apache.iotdb.tsfile.read.filter.operator.Eq;
import org.apache.iotdb.tsfile.read.filter.operator.Gt;
import org.apache.iotdb.tsfile.read.filter.operator.GtEq;
import org.apache.iotdb.tsfile.read.filter.operator.In;
import org.apache.iotdb.tsfile.read.filter.operator.Lt;
import org.apache.iotdb.tsfile.read.filter.operator.LtEq;
import org.apache.iotdb.tsfile.read.filter.operator.NotEq;
import org.apache.iotdb.tsfile.read.filter.operator.NotFilter;
import java.util.Set;
public class TimeFilter {
private TimeFilter() {}
public static TimeEq eq(long value) {
return new TimeEq(value);
}
public static TimeGt gt(long value) {
return new TimeGt(value);
}
public static TimeGtEq gtEq(long value) {
return new TimeGtEq(value);
}
public static TimeLt lt(long value) {
return new TimeLt(value);
}
public static TimeLtEq ltEq(long value) {
return new TimeLtEq(value);
}
public static TimeNotFilter not(Filter filter) {
return new TimeNotFilter(filter);
}
public static TimeNotEq notEq(long value) {
return new TimeNotEq(value);
}
public static TimeIn in(Set<Long> values, boolean not) {
return new TimeIn(values, not);
}
public static class TimeIn extends In {
private TimeIn(Set<Long> values, boolean not) {
super(values, FilterType.TIME_FILTER, not);
}
}
public static class TimeEq extends Eq {
private TimeEq(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeNotEq extends NotEq {
private TimeNotEq(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeGt extends Gt {
private TimeGt(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeGtEq extends GtEq {
private TimeGtEq(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeLt extends Lt {
private TimeLt(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeLtEq extends LtEq {
private TimeLtEq(long value) {
super(value, FilterType.TIME_FILTER);
}
}
public static class TimeNotFilter extends NotFilter {
private TimeNotFilter(Filter filter) {
super(filter);
}
}
/**
* returns a default time filter by whether it's an ascending query.
*
* <p>If the data is read in descending order, we use the largest timestamp to set to the filter,
* so the filter should be TimeLtEq. If the data is read in ascending order, we use the smallest
* timestamp to set to the filter, so the filter should be TimeGtEq.
*/
public static Filter defaultTimeFilter(boolean ascending) {
return ascending ? TimeFilter.gtEq(Long.MIN_VALUE) : TimeFilter.ltEq(Long.MAX_VALUE);
}
}
|
3e1b7cd1d9af2d1a8aeada8922080023af335a2c | 1,773 | java | Java | src/main/java/adventurers/cards/starter/DefendRogue.java | Residualshade/Sts-AdventurersMod | eb4cd96c7b14941a4509bfa0070d04fe7fc8571e | [
"MIT"
] | null | null | null | src/main/java/adventurers/cards/starter/DefendRogue.java | Residualshade/Sts-AdventurersMod | eb4cd96c7b14941a4509bfa0070d04fe7fc8571e | [
"MIT"
] | null | null | null | src/main/java/adventurers/cards/starter/DefendRogue.java | Residualshade/Sts-AdventurersMod | eb4cd96c7b14941a4509bfa0070d04fe7fc8571e | [
"MIT"
] | null | null | null | 32.236364 | 113 | 0.705584 | 11,651 | package adventurers.cards.starter;
import adventurers.patches.AbstractCardEnum;
import basemod.abstracts.CustomCard;
import basemod.helpers.BaseModCardTags;
import com.megacrit.cardcrawl.actions.common.GainBlockAction;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
public class DefendRogue extends CustomCard {
public static final String ID = "adventurers:DefendRogue";
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
private static final int COST = 1;
private static final int BLOCK = 5;
private static final int UPGRADE_BLOCK_BONUS = 3;
//TODO: CARD IMAGE
public DefendRogue() {
super(
ID
,NAME
,null
,COST
,DESCRIPTION
, CardType.SKILL
, AbstractCardEnum.ADVENTURERS_GOLD
, CardRarity.BASIC
, CardTarget.SELF
);
this.baseBlock = this.block = BLOCK;
this.tags.add(BaseModCardTags.BASIC_DEFEND);
}
@Override
public void upgrade() {
if(!this.upgraded) {
this.upgradeName();
this.upgradeBlock(UPGRADE_BLOCK_BONUS);
}
}
@Override
public void use(AbstractPlayer abstractPlayer, AbstractMonster abstractMonster) {
AbstractDungeon.actionManager.addToBottom(new GainBlockAction(abstractPlayer,abstractPlayer,this.block));
}
}
|
3e1b7d08dba771c53f8f351d30fb3abefa745d98 | 180 | java | Java | src/main/java/com/grocerystore/service/UserPaymentService.java | jasmeettuteja/e-kiranastore-userend | 632838f1730ac5126fcb1756a3f94d9b68eebbf4 | [
"MIT"
] | null | null | null | src/main/java/com/grocerystore/service/UserPaymentService.java | jasmeettuteja/e-kiranastore-userend | 632838f1730ac5126fcb1756a3f94d9b68eebbf4 | [
"MIT"
] | null | null | null | src/main/java/com/grocerystore/service/UserPaymentService.java | jasmeettuteja/e-kiranastore-userend | 632838f1730ac5126fcb1756a3f94d9b68eebbf4 | [
"MIT"
] | null | null | null | 18 | 43 | 0.805556 | 11,652 | package com.grocerystore.service;
import com.grocerystore.domain.UserPayment;
public interface UserPaymentService {
UserPayment findById(Long id);
void removeById(Long id);
}
|
3e1b7d093f69fc6eb6111d9d3c9a9562955f38b6 | 978 | java | Java | app/src/main/java/com/lineargs/watchnext/utils/retrofit/series/seasondetails/Crew.java | mrh419/MyFirstProject | 89bf0538133aebc56130dc92c8d17acf1f165583 | [
"MIT"
] | 3 | 2018-01-22T23:06:10.000Z | 2018-08-09T20:42:13.000Z | app/src/main/java/com/lineargs/watchnext/utils/retrofit/series/seasondetails/Crew.java | mrh419/MyFirstProject | 89bf0538133aebc56130dc92c8d17acf1f165583 | [
"MIT"
] | 29 | 2018-01-08T21:40:05.000Z | 2019-08-26T21:29:07.000Z | app/src/main/java/com/lineargs/watchnext/utils/retrofit/series/seasondetails/Crew.java | mrh419/MyFirstProject | 89bf0538133aebc56130dc92c8d17acf1f165583 | [
"MIT"
] | 2 | 2019-01-10T09:01:11.000Z | 2020-03-24T21:33:45.000Z | 18.111111 | 80 | 0.648262 | 11,653 | package com.lineargs.watchnext.utils.retrofit.series.seasondetails;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by goranminov on 28/11/2017.
* <p>
* JSON POJO class for our {@link retrofit2.converter.gson.GsonConverterFactory}
*/
public class Crew {
@SerializedName("department")
@Expose
private String department;
@SerializedName("id")
@Expose
private int id;
@SerializedName("job")
@Expose
private String job;
@SerializedName("name")
@Expose
private String name;
@SerializedName("profile_path")
@Expose
private String profilePath;
public String getDepartment() {
return department;
}
public int getId() {
return id;
}
public String getJob() {
return job;
}
public String getName() {
return name;
}
public String getProfilePath() {
return profilePath;
}
}
|
3e1b7d43297a37c655ea214872b48e13b7629b66 | 16,368 | java | Java | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunction.java | karreiro/drools | fdb7c4d2486224312483d00aa0e3df3f345d5840 | [
"Apache-2.0"
] | 1 | 2021-03-04T09:11:57.000Z | 2021-03-04T09:11:57.000Z | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunction.java | karreiro/drools | fdb7c4d2486224312483d00aa0e3df3f345d5840 | [
"Apache-2.0"
] | null | null | null | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunction.java | karreiro/drools | fdb7c4d2486224312483d00aa0e3df3f345d5840 | [
"Apache-2.0"
] | null | null | null | 43.531915 | 245 | 0.497434 | 11,654 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.kie.dmn.feel.runtime.functions;
import org.kie.dmn.api.feel.runtime.events.FEELEvent;
import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity;
import org.kie.dmn.feel.lang.EvaluationContext;
import org.kie.dmn.feel.lang.Symbol;
import org.kie.dmn.feel.lang.impl.FEELEventListenersManager;
import org.kie.dmn.feel.lang.impl.NamedParameter;
import org.kie.dmn.feel.lang.types.FunctionSymbol;
import org.kie.dmn.feel.runtime.FEELFunction;
import org.kie.dmn.feel.runtime.events.FEELEventBase;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
import org.kie.dmn.feel.util.Either;
import org.kie.dmn.feel.util.EvalHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public abstract class BaseFEELFunction
implements FEELFunction {
private final Logger logger = LoggerFactory.getLogger( getClass() );
private String name;
private Symbol symbol;
public BaseFEELFunction(String name) {
this.name = name;
this.symbol = new FunctionSymbol( name, this );
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
((FunctionSymbol) this.symbol).setId( name );
}
@Override
public Symbol getSymbol() {
return symbol;
}
@Override
public Object invokeReflectively(EvaluationContext ctx, Object[] params) {
// use reflection to call the appropriate invoke method
try {
boolean isNamedParams = params.length > 0 && params[0] instanceof NamedParameter;
if ( !isCustomFunction() ) {
List<String> available = null;
if ( isNamedParams ) {
available = Stream.of( params ).map( p -> ((NamedParameter) p).getName() ).collect( Collectors.toList() );
}
Class[] classes = Stream.of( params ).map( p -> p != null ? p.getClass() : null ).toArray( Class[]::new );
CandidateMethod cm = getCandidateMethod( ctx, params, isNamedParams, available, classes );
if ( cm != null ) {
Object result = cm.apply.invoke( this, cm.actualParams );
if ( result instanceof Either ) {
@SuppressWarnings("unchecked")
Either<FEELEvent, Object> either = (Either<FEELEvent, Object>) result;
Object eitherResult = either.cata( (left) -> {
FEELEventListenersManager.notifyListeners( ctx.getEventsManager(), () -> {
if ( left instanceof InvalidParametersEvent ) {
InvalidParametersEvent invalidParametersEvent = (InvalidParametersEvent) left;
invalidParametersEvent.setNodeName( getName() );
invalidParametersEvent.setActualParameters(
Stream.of( cm.apply.getParameters() ).map( p -> p.getAnnotation( ParameterName.class ).value() ).collect( Collectors.toList() ),
Arrays.asList( cm.actualParams )
);
}
return left;
}
);
return null;
}, Function.identity() );
return eitherResult;
}
return result;
} else {
String ps = Arrays.toString( classes );
logger.error( "Unable to find function '" + getName() + "( " + ps.substring( 1, ps.length() - 1 ) + " )'" );
FEELEventListenersManager.notifyListeners( ctx.getEventsManager(), () -> {
return new FEELEventBase( Severity.ERROR, "Unable to find function '" + getName() + "( " + ps.substring( 1, ps.length() - 1 ) + " )'", null );
}
);
}
} else {
if ( isNamedParams ) {
params = rearrangeParameters( params, this.getParameterNames().get( 0 ) );
}
Object result = invoke( ctx, params );
if ( result instanceof Either ) {
@SuppressWarnings("unchecked")
Either<FEELEvent, Object> either = (Either<FEELEvent, Object>) result;
final Object[] usedParams = params;
Object eitherResult = either.cata( (left) -> {
FEELEventListenersManager.notifyListeners( ctx.getEventsManager(), () -> {
if ( left instanceof InvalidParametersEvent ) {
InvalidParametersEvent invalidParametersEvent = (InvalidParametersEvent) left;
invalidParametersEvent.setNodeName( getName() );
invalidParametersEvent.setActualParameters( IntStream.of( 0, usedParams.length ).mapToObj( i -> "arg" + i ).collect( Collectors.toList() ), Arrays.asList( usedParams ) );
}
return left;
}
);
return null;
}, Function.identity() );
return normalizeResult( eitherResult );
}
return normalizeResult( result );
}
} catch ( Exception e ) {
logger.error( "Error trying to call function " + getName() + ".", e );
FEELEventListenersManager.notifyListeners( ctx.getEventsManager(), () -> {
return new FEELEventBase( Severity.ERROR, "Error trying to call function " + getName() + ".", e );
}
);
}
return null;
}
/**
* this method should be overriden by custom function implementations that should be invoked reflectively
* @param ctx
* @param params
* @return
*/
public Object invoke(EvaluationContext ctx, Object[] params) {
throw new RuntimeException( "This method should be overriden by classes that implement custom feel functions" );
}
private Object[] rearrangeParameters(Object[] params, List<String> pnames) {
if ( pnames.size() > 0 ) {
Object[] actualParams = new Object[pnames.size()];
for ( int i = 0; i < actualParams.length; i++ ) {
for ( int j = 0; j < params.length; j++ ) {
if ( ((NamedParameter) params[j]).getName().equals( pnames.get( i ) ) ) {
actualParams[i] = ((NamedParameter) params[j]).getValue();
break;
}
}
}
params = actualParams;
}
return params;
}
private CandidateMethod getCandidateMethod(EvaluationContext ctx, Object[] params, boolean isNamedParams, List<String> available, Class[] classes) {
CandidateMethod candidate = null;
// first, look for exact matches
for ( Method m : getClass().getDeclaredMethods() ) {
if ( !m.getName().equals( "invoke" ) ) {
continue;
}
Object[] actualParams = null;
boolean injectCtx = Arrays.stream( m.getParameterTypes() ).anyMatch( p -> EvaluationContext.class.isAssignableFrom( p ) );
if( injectCtx ) {
actualParams = new Object[ params.length + 1 ];
int j = 0;
for( int i = 0; i < m.getParameterCount() && j < params.length; i++ ) {
if( EvaluationContext.class.isAssignableFrom( m.getParameterTypes()[i] ) ) {
if( isNamedParams ) {
actualParams[i] = new NamedParameter( "ctx", ctx );
} else {
actualParams[i] = ctx;
}
// if( available != null ) {
// // if there is a list of available parameter names, add the injected context parameter into the list
// Annotation[][] annotations = m.getParameterAnnotations();
// boolean foundName = false;
// for( int k = 0; k < annotations[i].length; k++ ) {
// if( annotations[i][k] instanceof NamedParameter ) {
// available = new ArrayList<>( available );
// available.add( ((NamedParameter)annotations[i][k]).getName() );
// foundName = true;
// break;
// }
// }
// if( ! foundName ) {
// // use default name
// available.add( "ctx" );
// }
// }
} else {
actualParams[i] = params[j];
j++;
}
}
} else {
actualParams = params;
}
if( isNamedParams ) {
actualParams = calculateActualParams( ctx, m, actualParams, available );
if( actualParams == null ) {
// incompatible method
continue;
}
}
CandidateMethod cm = new CandidateMethod( actualParams );
Class<?>[] parameterTypes = m.getParameterTypes();
adjustForVariableParameters( cm, parameterTypes );
if ( parameterTypes.length != cm.getActualParams().length ) {
continue;
}
boolean found = true;
for ( int i = 0; i < parameterTypes.length; i++ ) {
if ( cm.getActualClasses()[i] != null && !parameterTypes[i].isAssignableFrom( cm.getActualClasses()[i] ) ) {
found = false;
break;
}
}
if ( found ) {
cm.setApply( m );
if ( candidate == null || cm.getScore() > candidate.getScore() ) {
candidate = cm;
}
}
}
return candidate;
}
@Override
public List<List<String>> getParameterNames() {
// TODO: we could implement this method using reflection, just for consistency,
// but it is not used at the moment
return Collections.emptyList();
}
private void adjustForVariableParameters(CandidateMethod cm, Class<?>[] parameterTypes) {
if ( parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].isArray() ) {
// then it is a variable parameters function call
Object[] newParams = new Object[parameterTypes.length];
if ( newParams.length > 1 ) {
System.arraycopy( cm.getActualParams(), 0, newParams, 0, newParams.length - 1 );
}
Object[] remaining = new Object[cm.getActualParams().length - parameterTypes.length + 1];
newParams[newParams.length - 1] = remaining;
System.arraycopy( cm.getActualParams(), parameterTypes.length - 1, remaining, 0, remaining.length );
cm.setActualParams( newParams );
}
}
private Object[] calculateActualParams(EvaluationContext ctx, Method m, Object[] params, List<String> available) {
Annotation[][] pas = m.getParameterAnnotations();
List<String> names = new ArrayList<>( m.getParameterCount() );
for ( int i = 0; i < m.getParameterCount(); i++ ) {
for ( int p = 0; p < pas[i].length; i++ ) {
if ( pas[i][p] instanceof ParameterName ) {
names.add( ((ParameterName) pas[i][p]).value() );
break;
}
}
if ( names.get( i ) == null ) {
// no name found
return null;
}
}
if ( names.containsAll( available ) ) {
Object[] actualParams = new Object[names.size()];
for ( Object o : params ) {
NamedParameter np = (NamedParameter) o;
actualParams[names.indexOf( np.getName() )] = np.getValue();
}
return actualParams;
} else {
// method is not compatible
return null;
}
}
private Object normalizeResult(Object result) {
// this is to normalize types returned by external functions
return result != null && result instanceof Number && !(result instanceof BigDecimal) ? EvalHelper.getBigDecimalOrNull( result.toString() ) : result;
}
protected boolean isCustomFunction() {
return false;
}
private static class CandidateMethod {
private Method apply = null;
private Object[] actualParams = null;
private Class[] actualClasses = null;
private int score;
public CandidateMethod(Object[] actualParams) {
this.actualParams = actualParams;
populateActualClasses();
}
private void calculateScore() {
if ( actualClasses.length > 0 && actualClasses[actualClasses.length - 1] != null && actualClasses[actualClasses.length - 1].isArray() ) {
score = 1;
} else {
score = 10;
}
}
public Method getApply() {
return apply;
}
public void setApply(Method apply) {
this.apply = apply;
calculateScore();
}
public Object[] getActualParams() {
return actualParams;
}
public void setActualParams(Object[] actualParams) {
this.actualParams = actualParams;
populateActualClasses();
}
private void populateActualClasses() {
this.actualClasses = Stream.of( this.actualParams ).map( p -> p != null ? p.getClass() : null ).toArray( Class[]::new );
}
public Class[] getActualClasses() {
return actualClasses;
}
public int getScore() {
return score;
}
}
}
|
3e1b7d911e4c82432f9b2c042861e69a72511199 | 2,669 | java | Java | core/src/test/java/google/registry/tools/params/DateParameterTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 1,644 | 2016-10-18T15:05:43.000Z | 2022-03-19T21:45:23.000Z | core/src/test/java/google/registry/tools/params/DateParameterTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 332 | 2016-10-18T15:33:58.000Z | 2022-03-30T12:48:37.000Z | core/src/test/java/google/registry/tools/params/DateParameterTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 270 | 2016-10-18T14:56:43.000Z | 2022-03-27T17:54:07.000Z | 31.4 | 96 | 0.739228 | 11,655 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools.params;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link DateParameter}. */
class DateParameterTest {
private final DateParameter instance = new DateParameter();
@Test
void testConvert_onlyDate() {
String exampleDate = "2014-01-01";
assertThat(instance.convert(exampleDate)).isEqualTo(DateTime.parse("2014-01-01T00:00:00Z"));
}
@Test
void testConvert_numeric_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("1234"));
}
@Test
void testConvert_validDateAndTime_throwsException() {
assertThrows(
IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02:03.004Z"));
}
@Test
void testConvert_invalidDate_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-13-33"));
}
@Test
void testConvert_null_throwsException() {
assertThrows(NullPointerException.class, () -> instance.convert(null));
}
@Test
void testConvert_empty_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert(""));
}
@Test
void testConvert_sillyString_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("foo"));
}
@Test
void testConvert_partialDate_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01"));
}
@Test
void testConvert_onlyTime_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02:03"));
}
@Test
void testConvert_partialDateAndPartialTime_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("9T9"));
}
@Test
void testConvert_dateAndPartialTime_throwsException() {
assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02"));
}
}
|
3e1b7db9d521d980827b6968640f61cbdd337e11 | 4,694 | java | Java | src/com/lupcode/Utilities/others/UTF8String.java | luca-vogels/java-utilities | 062fe6a7f535bc96b71c3fa8b981ee74c4d02bef | [
"MIT"
] | 1 | 2020-12-31T12:15:34.000Z | 2020-12-31T12:15:34.000Z | src/com/lupcode/Utilities/others/UTF8String.java | LupCode/java-utilities | 062fe6a7f535bc96b71c3fa8b981ee74c4d02bef | [
"MIT"
] | null | null | null | src/com/lupcode/Utilities/others/UTF8String.java | LupCode/java-utilities | 062fe6a7f535bc96b71c3fa8b981ee74c4d02bef | [
"MIT"
] | null | null | null | 26.822857 | 125 | 0.711121 | 11,656 | package com.lupcode.Utilities.others;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Queue;
import com.lupcode.Utilities.streams.UTF8CharInputStream;
/**
* UTF-8 String holds UTF-8 characters
* @author LupCode.com (Luca Vogels)
* @since 2020-12-23
*/
public class UTF8String extends ArrayList<String> implements Queue<String> {
private static final long serialVersionUID = 1L;
/**
* Creates an empty UTF-8 string
*/
public UTF8String() {
super();
}
/**
* Creates an UTF-8 string based on a normal string
* @param utf8String String that should be used for initialization
*/
public UTF8String(String utf8String) {
super();
if(utf8String!=null) appendString(utf8String);
}
/**
* Creates an empty UTF-8 string with an initial capacity
* @param initialCapacity Initial capacity
*/
public UTF8String(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates an UTF-8 string based on a given list of UTF-8 characters (not further proofed)
* @param chars UTF-8 characters
*/
protected UTF8String(Collection<String> chars) {
super(chars);
}
/**
* How many characters the UTF-8 string holds
* @return Amount of characters
*/
public int length() {
return size();
}
/**
* Returns a single UTF-8 character at a given index
* @param index Index of UTF-8 character that should be returned
* @return UTF-8 character
* @throws IndexOutOfBoundsException if index is out of bounds
*/
public String charAt(int index) throws IndexOutOfBoundsException {
return get(index);
}
/**
* Returns a substring
* @param beginIndex Index where substring should begin (inclusive)
* @return Substring
* @throws IndexOutOfBoundsException if beginIndex is out of bounds
*/
public UTF8String substring(int beginIndex) throws IndexOutOfBoundsException {
return new UTF8String(subList(beginIndex, size()));
}
/**
* Returns a substring
* @param beginIndex Index where substring should begin (inclusive)
* @param endIndex Index where substring should end (exclusive)
* @return Substring
* @throws IndexOutOfBoundsException if beginIndex or endIndex is out of bounds
*/
public UTF8String substring(int beginIndex, int endIndex) {
return new UTF8String(subList(beginIndex, endIndex));
}
@Override
public boolean equals(Object o) {
if(o==null || !(o instanceof Collection)) return false;
try {
@SuppressWarnings("unchecked")
Collection<String> c = (Collection<String>) o;
if(c.size() != super.size()) return false;
int index = 0;
for(String str : c) {
if(str==null || !Arrays.equals(
str.getBytes(StandardCharsets.UTF_8),
super.get(index++).getBytes(StandardCharsets.UTF_8)
)) return false;
}
return true;
} catch (ClassCastException ex) { return false; }
}
/**
* Sets the content of this UTF-8 string from a given normal String
* @param utf8String String that should be read
*/
public void setString(String utf8String) {
if(utf8String==null) throw new NullPointerException("String cannot be null");
clear();
appendString(utf8String);
}
/**
* Appends a normal string to this UTF-8 string
* @param utf8String String that should be appended
*/
public void appendString(String utf8String) {
if(utf8String==null) throw new NullPointerException("String cannot be null");
UTF8CharInputStream input = new UTF8CharInputStream(new ByteArrayInputStream(utf8String.getBytes(StandardCharsets.UTF_8)));
String c;
try {
while((c = input.readChar())!=null) add(c);
} catch (IOException e) {}
}
/**
* Returns byte array containing the UTF-8 bytes of the UTF-8 string
* @return UTF-8 byte array
*/
public byte[] getBytes() {
return toString().getBytes(StandardCharsets.UTF_8);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(String c : this) {
sb.append(c);
} return sb.toString();
}
@Override
public boolean offer(String e) {
if(e==null) throw new NullPointerException("Char cannot be null");
return super.add(e);
}
@Override
public String remove() {
if(isEmpty()) throw new NoSuchElementException("UTF8String is empty");
return super.remove(0);
}
@Override
public String poll() {
return isEmpty() ? null : super.remove(0);
}
@Override
public String element() {
if(isEmpty()) throw new NoSuchElementException("UTF8String is empty");
return super.get(0);
}
@Override
public String peek() {
return isEmpty() ? null : super.get(0);
}
}
|
3e1b7e90149246e90711d9ee60981f3e0cd97437 | 3,189 | java | Java | src/main/java/com/mediafire/sdk/response_models/data_models/UserInfoModel.java | MediaFire/mediafire-java-sdk | aa538d0a551f6ba4c22f3f6ed7c9865dbab4c958 | [
"Apache-2.0"
] | 11 | 2015-10-30T19:43:13.000Z | 2021-04-06T17:30:08.000Z | src/main/java/com/mediafire/sdk/response_models/data_models/UserInfoModel.java | MediaFire/mediafire-java-sdk | aa538d0a551f6ba4c22f3f6ed7c9865dbab4c958 | [
"Apache-2.0"
] | 3 | 2016-04-10T15:16:04.000Z | 2016-12-06T11:17:45.000Z | src/main/java/com/mediafire/sdk/response_models/data_models/UserInfoModel.java | MediaFire/mediafire-java-sdk | aa538d0a551f6ba4c22f3f6ed7c9865dbab4c958 | [
"Apache-2.0"
] | 9 | 2015-03-02T15:15:33.000Z | 2019-12-29T08:25:20.000Z | 22.145833 | 54 | 0.541549 | 11,657 | package com.mediafire.sdk.response_models.data_models;
/**
* Created by Chris on 5/14/2015.
*/
public class UserInfoModel {
private String first_name;
private String last_name;
private String display_name;
private String birth_date;
private String max_instant_upload_size;
private String storage_limit;
private String storage_limit_exceeded;
private String used_storage_size;
private String email;
private String gender;
private String location;
private String website;
private String premium;
private String options;
private String ekey;
private FacebookInfoModel facebook;
private TwitterInfoModel twitter;
public FacebookInfoModel getFacebookInfo() {
if (facebook == null) {
facebook = new FacebookInfoModel();
}
return facebook;
}
public TwitterInfoModel getTwitterInfo() {
if (twitter == null) {
twitter = new TwitterInfoModel();
}
return twitter;
}
public String getEKey() {
if (ekey == null) {
ekey = "";
}
return ekey;
}
public String getFirstName() {
if (first_name == null) {
first_name = "";
}
return first_name;
}
public String getLastName() {
if (last_name == null) {
last_name = "";
}
return last_name;
}
public String getDisplayName() {
if (display_name == null) {
display_name = "";
}
return display_name;
}
public String getBirthDate() {
if (birth_date == null) {
birth_date = "";
}
return birth_date;
}
public String getMaxInstantUploadSize() {
if (max_instant_upload_size == null) {
max_instant_upload_size = "";
}
return max_instant_upload_size;
}
public String getStorageLimit() {
if (storage_limit == null) {
storage_limit = "";
}
return storage_limit;
}
public String getUsedStorageSize() {
if (used_storage_size == null) {
used_storage_size = "";
}
return used_storage_size;
}
public String getStorageLimitExceeded() {
if (storage_limit_exceeded == null) {
storage_limit_exceeded = "";
}
return storage_limit_exceeded;
}
public String getEmail() {
if (email == null) {
email = "";
}
return email;
}
public String getGender() {
if (gender == null) {
gender = "";
}
return gender;
}
public String getLocation() {
if (location == null) {
location = "";
}
return location;
}
public String getWebsite() {
if (website == null) {
website = "";
}
return website;
}
public String getPremium() {
if (premium == null) {
premium = "";
}
return premium;
}
public String getOptions() {
if (options == null) {
options = "";
}
return options;
}
}
|
3e1b81310fee392cdc2f1b7a0f322b8d284a65bb | 29,780 | java | Java | flink-table-store-connector/src/test/java/org/apache/flink/table/store/connector/ReadWriteTableTestUtil.java | SteNicholas/flink-table-store | d0576e1bbd7f798d68db398593c8368376743203 | [
"Apache-2.0"
] | 74 | 2022-01-12T06:02:22.000Z | 2022-03-31T02:59:23.000Z | flink-table-store-connector/src/test/java/org/apache/flink/table/store/connector/ReadWriteTableTestUtil.java | SteNicholas/flink-table-store | d0576e1bbd7f798d68db398593c8368376743203 | [
"Apache-2.0"
] | 15 | 2022-01-12T07:10:32.000Z | 2022-03-30T08:01:35.000Z | flink-table-store-connector/src/test/java/org/apache/flink/table/store/connector/ReadWriteTableTestUtil.java | SteNicholas/flink-table-store | d0576e1bbd7f798d68db398593c8368376743203 | [
"Apache-2.0"
] | 20 | 2022-01-12T05:59:51.000Z | 2022-03-24T14:43:55.000Z | 51.256454 | 99 | 0.504735 | 11,658 | /*
* 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.flink.table.store.connector;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.catalog.Column;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.catalog.ResolvedCatalogTable;
import org.apache.flink.table.planner.factories.TestValuesTableFactory;
import org.apache.flink.types.Row;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.flink.table.api.DataTypes.BIGINT;
import static org.apache.flink.table.api.DataTypes.DOUBLE;
import static org.apache.flink.table.api.DataTypes.STRING;
import static org.apache.flink.table.api.DataTypes.TIMESTAMP;
import static org.apache.flink.table.planner.factories.TestValuesTableFactory.changelogRow;
import static org.apache.flink.table.planner.factories.TestValuesTableFactory.registerData;
import static org.apache.flink.table.store.connector.ShowCreateUtil.buildShowCreateTable;
import static org.apache.flink.table.store.connector.TableStoreTestBase.createResolvedTable;
/** Data util for {@link ReadWriteTableITCase}. */
public class ReadWriteTableTestUtil {
public static String prepareHelperSourceWithInsertOnlyRecords(
String sourceTable,
List<String> partitionKeys,
List<String> primaryKeys,
boolean assignWatermark) {
return prepareHelperSourceRecords(
RuntimeExecutionMode.BATCH,
sourceTable,
partitionKeys,
primaryKeys,
assignWatermark);
}
public static String prepareHelperSourceWithChangelogRecords(
String sourceTable,
List<String> partitionKeys,
List<String> primaryKeys,
boolean assignWatermark) {
return prepareHelperSourceRecords(
RuntimeExecutionMode.STREAMING,
sourceTable,
partitionKeys,
primaryKeys,
assignWatermark);
}
/**
* Prepare helper source table ddl according to different input parameter.
*
* <pre> E.g. pk with partition
* {@code
* CREATE TABLE source_table (
* currency STRING,
* rate BIGINT,
* dt STRING) PARTITIONED BY (dt)
* WITH (
* 'connector' = 'values',
* 'bounded' = executionMode == RuntimeExecutionMode.BATCH,
* 'partition-list' = '...'
* )
* }
* </pre>
*
* @param executionMode is used to calculate {@code bounded}
* @param sourceTable source table name
* @param partitionKeys is used to calculate {@code partition-list}
* @param primaryKeys
* @param assignWatermark
* @return helper source ddl
*/
private static String prepareHelperSourceRecords(
RuntimeExecutionMode executionMode,
String sourceTable,
List<String> partitionKeys,
List<String> primaryKeys,
boolean assignWatermark) {
Map<String, String> tableOptions = new HashMap<>();
boolean bounded = executionMode == RuntimeExecutionMode.BATCH;
String changelogMode = bounded ? "I" : primaryKeys.size() > 0 ? "I,UA,D" : "I,UA,UB,D";
List<String> exclusivePk = new ArrayList<>(primaryKeys);
exclusivePk.removeAll(partitionKeys);
Tuple2<List<Row>, String> tuple =
prepareHelperSource(
bounded, exclusivePk.size(), partitionKeys.size(), assignWatermark);
String dataId = registerData(tuple.f0);
String partitionList = tuple.f1;
tableOptions.put("connector", TestValuesTableFactory.IDENTIFIER);
tableOptions.put("bounded", String.valueOf(bounded));
tableOptions.put("disable-lookup", String.valueOf(true));
tableOptions.put("changelog-mode", changelogMode);
tableOptions.put("data-id", dataId);
if (partitionList != null) {
tableOptions.put("partition-list", partitionList);
}
ResolvedCatalogTable table;
if (assignWatermark) {
table = prepareRateSourceWithTimestamp(tableOptions);
} else {
if (exclusivePk.size() > 1) {
table = prepareExchangeRateSource(partitionKeys, primaryKeys, tableOptions);
} else {
table = prepareRateSource(partitionKeys, primaryKeys, tableOptions);
}
}
return buildShowCreateTable(
table,
ObjectIdentifier.of("default_catalog", "default_database", sourceTable),
true);
}
private static Tuple2<List<Row>, String> prepareHelperSource(
boolean bounded, int pkSize, int partitionSize, boolean assignWatermark) {
List<Row> input;
String partitionList = null;
if (assignWatermark) {
return Tuple2.of(ratesWithTimestamp(), null);
}
if (pkSize == 2) {
if (bounded) {
if (partitionSize == 0) {
// multi-pk, non-partitioned
input = exchangeRates();
} else if (partitionSize == 1) {
// multi-pk, single-partitioned
input = dailyExchangeRates().f0;
partitionList = dailyExchangeRates().f1;
} else {
// multi-pk, multi-partitioned
input = hourlyExchangeRates().f0;
partitionList = hourlyExchangeRates().f1;
}
} else {
if (partitionSize == 0) {
// multi-pk, non-partitioned
input = exchangeRatesChangelogWithoutUB();
} else if (partitionSize == 1) {
// multi-pk, single-partitioned
input = dailyExchangeRatesChangelogWithoutUB().f0;
partitionList = dailyExchangeRatesChangelogWithoutUB().f1;
} else {
// multi-pk, multi-partitioned
input = hourlyExchangeRatesChangelogWithoutUB().f0;
partitionList = hourlyExchangeRatesChangelogWithoutUB().f1;
}
}
} else if (pkSize == 1) {
if (bounded) {
if (partitionSize == 0) {
// single-pk, non-partitioned
input = rates();
} else if (partitionSize == 1) {
// single-pk, single-partitioned
input = dailyRates().f0;
partitionList = dailyRates().f1;
} else {
// single-pk, multi-partitioned
input = hourlyRates().f0;
partitionList = hourlyRates().f1;
}
} else {
if (partitionSize == 0) {
// single-pk, non-partitioned
input = ratesChangelogWithoutUB();
} else if (partitionSize == 1) {
// single-pk, single-partitioned
input = dailyRatesChangelogWithoutUB().f0;
partitionList = dailyRatesChangelogWithoutUB().f1;
} else {
// single-pk, multi-partitioned
input = hourlyRatesChangelogWithoutUB().f0;
partitionList = hourlyRatesChangelogWithoutUB().f1;
}
}
} else {
if (bounded) {
if (partitionSize == 0) {
// without pk, non-partitioned
input = rates();
} else if (partitionSize == 1) {
// without, single-partitioned
input = dailyRates().f0;
partitionList = dailyRates().f1;
} else {
// without pk, multi-partitioned
input = hourlyRates().f0;
partitionList = hourlyRates().f1;
}
} else {
if (partitionSize == 0) {
// without pk, non-partitioned
input = ratesChangelogWithUB();
} else if (partitionSize == 1) {
// without pk, single-partitioned
input = dailyRatesChangelogWithUB().f0;
partitionList = dailyRatesChangelogWithUB().f1;
} else {
// without pk, multi-partitioned
input = hourlyRatesChangelogWithUB().f0;
partitionList = hourlyRatesChangelogWithUB().f1;
}
}
}
return Tuple2.of(input, partitionList);
}
private static ResolvedCatalogTable prepareRateSource(
List<String> partitionKeys,
List<String> primaryKeys,
Map<String, String> tableOptions) {
List<Column> resolvedColumns = new ArrayList<>();
resolvedColumns.add(Column.physical("currency", STRING()));
resolvedColumns.add(Column.physical("rate", BIGINT()));
if (partitionKeys.size() > 0) {
resolvedColumns.add(Column.physical("dt", STRING()));
}
if (partitionKeys.size() == 2) {
resolvedColumns.add(Column.physical("hh", STRING()));
}
return createResolvedTable(tableOptions, resolvedColumns, partitionKeys, primaryKeys);
}
private static ResolvedCatalogTable prepareRateSourceWithTimestamp(
Map<String, String> tableOptions) {
List<Column> resolvedColumns = new ArrayList<>();
resolvedColumns.add(Column.physical("currency", STRING()));
resolvedColumns.add(Column.physical("rate", BIGINT()));
resolvedColumns.add(Column.physical("ts", TIMESTAMP(3)));
return createResolvedTable(
tableOptions, resolvedColumns, Collections.emptyList(), Collections.emptyList());
}
private static ResolvedCatalogTable prepareExchangeRateSource(
List<String> partitionKeys,
List<String> primaryKeys,
Map<String, String> tableOptions) {
List<Column> resolvedColumns = new ArrayList<>();
resolvedColumns.add(Column.physical("from_currency", STRING()));
resolvedColumns.add(Column.physical("to_currency", STRING()));
resolvedColumns.add(Column.physical("rate_by_to_currency", DOUBLE()));
if (partitionKeys.size() > 0) {
resolvedColumns.add(Column.physical("dt", STRING()));
}
if (partitionKeys.size() == 2) {
resolvedColumns.add(Column.physical("hh", STRING()));
}
return createResolvedTable(tableOptions, resolvedColumns, partitionKeys, primaryKeys);
}
public static List<Row> rates() {
// currency, rate
return Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Euro", 119L));
}
public static List<Row> ratesWithTimestamp() {
// currency, rate, timestamp
return Arrays.asList(
changelogRow(
"+I", "US Dollar", 102L, LocalDateTime.parse("1990-04-07T10:00:11.120")),
changelogRow("+I", "Euro", 119L, LocalDateTime.parse("2020-04-07T10:10:11.120")),
changelogRow("+I", "Yen", 1L, LocalDateTime.parse("2022-04-07T09:54:11.120")));
}
public static List<Row> exchangeRates() {
// from_currency, to_currency, rate_by_to_currency
return Arrays.asList(
// to_currency is USD
changelogRow("+I", "US Dollar", "US Dollar", 1.0d),
changelogRow("+I", "Euro", "US Dollar", 1.11d),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d),
changelogRow("+I", "Yen", "US Dollar", 0.0082d),
changelogRow("+I", "Singapore Dollar", "US Dollar", 0.74d),
changelogRow("+I", "Yen", "US Dollar", 0.0081d),
changelogRow("+I", "US Dollar", "US Dollar", 1.0d),
// to_currency is Euro
changelogRow("+I", "US Dollar", "Euro", 0.9d),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d),
// to_currency is Yen
changelogRow("+I", "Yen", "Yen", 1.0d),
changelogRow("+I", "Chinese Yuan", "Yen", 19.25d),
changelogRow("+I", "Singapore Dollar", "Yen", 90.32d),
changelogRow("+I", "Singapore Dollar", "Yen", 122.46d));
}
public static Tuple2<List<Row>, String> dailyRates() {
// currency, rate, dt
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "US Dollar", 114L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 119L, "2022-01-02")),
"dt:2022-01-01;dt:2022-01-02");
}
public static Tuple2<List<Row>, String> dailyExchangeRates() {
// from_currency, to_currency, rate_by_to_currency, dt
return Tuple2.of(
Arrays.asList(
// to_currency is USD
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-01"),
changelogRow("+I", "Euro", "US Dollar", 1.11d, "2022-01-01"),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d, "2022-01-01"),
changelogRow("+I", "Yen", "US Dollar", 0.0082d, "2022-01-01"),
changelogRow("+I", "Singapore Dollar", "US Dollar", 0.74d, "2022-01-01"),
changelogRow("+I", "Yen", "US Dollar", 0.0081d, "2022-01-02"),
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-02"),
// to_currency is Euro
changelogRow("+I", "US Dollar", "Euro", 0.9d, "2022-01-01"),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d, "2022-01-01"),
// to_currency is Yen
changelogRow("+I", "Yen", "Yen", 1.0d, "2022-01-01"),
changelogRow("+I", "Chinese Yuan", "Yen", 19.25d, "2022-01-01"),
changelogRow("+I", "Singapore Dollar", "Yen", 90.32d, "2022-01-01"),
changelogRow("+I", "Singapore Dollar", "Yen", 122.46d, "2022-01-01")),
"dt:2022-01-01;dt:2022-01-02");
}
public static Tuple2<List<Row>, String> hourlyRates() {
// currency, rate, dt, hh
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01, hh = 00
changelogRow("+I", "US Dollar", 102L, "2022-01-01", "00"),
changelogRow("+I", "Euro", 114L, "2022-01-01", "00"),
changelogRow("+I", "Yen", 1L, "2022-01-01", "00"),
changelogRow("+I", "Euro", 114L, "2022-01-01", "00"),
changelogRow("+I", "US Dollar", 114L, "2022-01-01", "00"),
// dt = 2022-01-01, hh = 20
changelogRow("+I", "US Dollar", 102L, "2022-01-01", "20"),
changelogRow("+I", "Euro", 114L, "2022-01-01", "20"),
changelogRow("+I", "Yen", 1L, "2022-01-01", "20"),
changelogRow("+I", "Euro", 114L, "2022-01-01", "20"),
changelogRow("+I", "US Dollar", 114L, "2022-01-01", "20"),
// dt = 2022-01-02, hh = 12
changelogRow("+I", "Euro", 119L, "2022-01-02", "12")),
"dt:2022-01-01,hh:00;dt:2022-01-01,hh:20;dt:2022-01-02,hh:12");
}
public static Tuple2<List<Row>, String> hourlyExchangeRates() {
// from_currency, to_currency, rate_by_to_currency, dt, hh
return Tuple2.of(
Arrays.asList(
// to_currency is USD, dt = 2022-01-01, hh = 11
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-01", "11"),
changelogRow("+I", "Euro", "US Dollar", 1.11d, "2022-01-01", "11"),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d, "2022-01-01", "11"),
changelogRow("+I", "Yen", "US Dollar", 0.0082d, "2022-01-01", "11"),
changelogRow(
"+I", "Singapore Dollar", "US Dollar", 0.74d, "2022-01-01", "11"),
changelogRow("+I", "Yen", "US Dollar", 0.0081d, "2022-01-01", "11"),
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-01", "11"),
// to_currency is USD, dt = 2022-01-01, hh = 12
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-01", "12"),
changelogRow("+I", "Euro", "US Dollar", 1.12d, "2022-01-01", "12"),
changelogRow("+I", "HK Dollar", "US Dollar", 0.129d, "2022-01-01", "12"),
changelogRow("+I", "Yen", "US Dollar", 0.0081d, "2022-01-01", "12"),
changelogRow(
"+I", "Singapore Dollar", "US Dollar", 0.741d, "2022-01-01", "12"),
changelogRow("+I", "Yen", "US Dollar", 0.00812d, "2022-01-01", "12"),
// to_currency is Euro, dt = 2022-01-02, hh = 23
changelogRow("+I", "US Dollar", "Euro", 0.918d, "2022-01-02", "23"),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d, "2022-01-02", "23")),
"dt:2022-01-01,hh:11;dt:2022-01-01,hh:12;dt:2022-01-02,hh:23");
}
public static List<Row> ratesChangelogWithoutUB() {
return Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L),
changelogRow("+U", "Euro", 119L),
changelogRow("-D", "Yen", 1L));
}
public static List<Row> exchangeRatesChangelogWithoutUB() {
// from_currency, to_currency, rate_by_to_currency
return Arrays.asList(
// to_currency is USD
changelogRow("+I", "US Dollar", "US Dollar", 1.0d),
changelogRow("+I", "Euro", "US Dollar", 1.11d),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d),
changelogRow("+U", "Euro", "US Dollar", 1.12d),
changelogRow("+I", "Yen", "US Dollar", 0.0082d),
changelogRow("+I", "Singapore Dollar", "US Dollar", 0.74d),
changelogRow("+U", "Yen", "US Dollar", 0.0081d),
changelogRow("-D", "US Dollar", "US Dollar", 1.0d),
changelogRow("-D", "Yen", "US Dollar", 0.0081d),
// to_currency is Euro
changelogRow("+I", "US Dollar", "Euro", 0.9d),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d),
changelogRow("+U", "Singapore Dollar", "Euro", 0.69d),
// to_currency is Yen
changelogRow("+I", "Yen", "Yen", 1.0d),
changelogRow("+I", "Chinese Yuan", "Yen", 19.25d),
changelogRow("+I", "Singapore Dollar", "Yen", 90.32d),
changelogRow("-D", "Yen", "Yen", 1.0d),
changelogRow("+U", "Singapore Dollar", "Yen", 122.46d),
changelogRow("+U", "Singapore Dollar", "Yen", 122d));
}
public static Tuple2<List<Row>, String> dailyRatesChangelogWithoutUB() {
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+U", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 119L, "2022-01-02"),
changelogRow("+U", "Euro", 119L, "2022-01-02")),
"dt:2022-01-01;dt:2022-01-02");
}
public static Tuple2<List<Row>, String> dailyExchangeRatesChangelogWithoutUB() {
// from_currency, to_currency, rate_by_to_currency, dt
return Tuple2.of(
Arrays.asList(
// to_currency is USD
changelogRow("+I", "US Dollar", "US Dollar", null, "2022-01-01"),
changelogRow("+I", "Euro", "US Dollar", null, "2022-01-01"),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d, "2022-01-01"),
changelogRow("+I", "Yen", "US Dollar", 0.0082d, "2022-01-01"),
changelogRow("-D", "Yen", "US Dollar", 0.0082d, "2022-01-01"),
changelogRow("+I", "Singapore Dollar", "US Dollar", 0.74d, "2022-01-01"),
changelogRow("+I", "Yen", "US Dollar", 0.0081d, "2022-01-01"),
changelogRow("+U", "Euro", "US Dollar", 1.11d, "2022-01-01"),
changelogRow("+U", "US Dollar", "US Dollar", 1.0d, "2022-01-01"),
// to_currency is Euro
changelogRow("+I", "US Dollar", "Euro", 0.9d, "2022-01-02"),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d, "2022-01-02"),
changelogRow("-D", "Singapore Dollar", "Euro", 0.67d, "2022-01-02"),
// to_currency is Yen
changelogRow("+I", "Yen", "Yen", 1.0d, "2022-01-02"),
changelogRow("+I", "Chinese Yuan", "Yen", 19.25d, "2022-01-02"),
changelogRow("+I", "Singapore Dollar", "Yen", 90.32d, "2022-01-02"),
changelogRow("+U", "Singapore Dollar", "Yen", 122.46d, "2022-01-02")),
"dt:2022-01-01;dt:2022-01-02");
}
public static Tuple2<List<Row>, String> hourlyRatesChangelogWithoutUB() {
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01, hh = "15"
changelogRow("+I", "US Dollar", 102L, "2022-01-01", "15"),
changelogRow("+I", "Euro", 114L, "2022-01-01", "15"),
changelogRow("+I", "Yen", 1L, "2022-01-01", "15"),
changelogRow("+U", "Euro", 116L, "2022-01-01", "15"),
changelogRow("-D", "Yen", 1L, "2022-01-01", "15"),
changelogRow("-D", "Euro", 116L, "2022-01-01", "15"),
// dt = 2022-01-02, hh = "23"
changelogRow("+I", "Euro", 119L, "2022-01-02", "23"),
changelogRow("+U", "Euro", 119L, "2022-01-02", "23")),
"dt:2022-01-01,hh:15;dt:2022-01-02,hh:23");
}
public static Tuple2<List<Row>, String> hourlyExchangeRatesChangelogWithoutUB() {
// from_currency, to_currency, rate_by_to_currency, dt, hh
return Tuple2.of(
Arrays.asList(
// to_currency is USD
changelogRow("+I", "US Dollar", "US Dollar", 1.0d, "2022-01-02", "20"),
changelogRow("+I", "Euro", "US Dollar", null, "2022-01-02", "20"),
changelogRow("+I", "HK Dollar", "US Dollar", 0.13d, "2022-01-02", "20"),
changelogRow("+I", "Yen", "US Dollar", 0.0082d, "2022-01-02", "20"),
changelogRow(
"+I", "Singapore Dollar", "US Dollar", 0.74d, "2022-01-02", "20"),
changelogRow("+U", "Yen", "US Dollar", 0.0081d, "2022-01-02", "20"),
changelogRow("-D", "US Dollar", "US Dollar", 1.0d, "2022-01-02", "20"),
changelogRow("-D", "Euro", "US Dollar", null, "2022-01-02", "20"),
changelogRow(
"+U", "Singapore Dollar", "US Dollar", 0.76d, "2022-01-02", "20"),
// to_currency is Euro
changelogRow("+I", "US Dollar", "Euro", 0.9d, "2022-01-02", "20"),
changelogRow("+I", "Singapore Dollar", "Euro", 0.67d, "2022-01-02", "20"),
changelogRow("+U", "Singapore Dollar", "Euro", null, "2022-01-02", "20"),
// to_currency is Yen
changelogRow("+I", "Yen", "Yen", 1.0d, "2022-01-02", "20"),
changelogRow("+I", "Chinese Yuan", "Yen", 19.25d, "2022-01-02", "20"),
changelogRow("+U", "Chinese Yuan", "Yen", 25.6d, "2022-01-02", "20"),
changelogRow("+I", "Singapore Dollar", "Yen", 90.32d, "2022-01-02", "20"),
changelogRow("+I", "US Dollar", "Yen", 122.46d, "2022-01-02", "21"),
changelogRow("+U", "Singapore Dollar", "Yen", 90.1d, "2022-01-02", "20")),
"dt:2022-01-02,hh:20;dt:2022-01-02,hh:21");
}
public static List<Row> ratesChangelogWithUB() {
return Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("-U", "Euro", 114L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L),
changelogRow("-U", "Euro", 119L),
changelogRow("+U", "Euro", 119L),
changelogRow("-D", "Yen", 1L),
changelogRow("+I", null, 100L),
changelogRow("+I", "HK Dollar", null));
}
public static Tuple2<List<Row>, String> dailyRatesChangelogWithUB() {
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 114L, "2022-01-02"),
changelogRow("-U", "Euro", 114L, "2022-01-02"),
changelogRow("+U", "Euro", 119L, "2022-01-02"),
changelogRow("-D", "Euro", 119L, "2022-01-02"),
changelogRow("+I", "Euro", 115L, "2022-01-02")),
"dt:2022-01-01;dt:2022-01-02");
}
public static Tuple2<List<Row>, String> hourlyRatesChangelogWithUB() {
return Tuple2.of(
Arrays.asList(
// dt = 2022-01-01, hh = 15
changelogRow("+I", "US Dollar", 102L, "2022-01-01", "15"),
changelogRow("+I", "Euro", 116L, "2022-01-01", "15"),
changelogRow("-D", "Euro", 116L, "2022-01-01", "15"),
changelogRow("+I", "Yen", 1L, "2022-01-01", "15"),
changelogRow("-D", "Yen", 1L, "2022-01-01", "15"),
// dt = 2022-01-02, hh = 20
changelogRow("+I", "Euro", 114L, "2022-01-02", "20"),
changelogRow("-U", "Euro", 114L, "2022-01-02", "20"),
changelogRow("+U", "Euro", 119L, "2022-01-02", "20"),
changelogRow("-D", "Euro", 119L, "2022-01-02", "20"),
changelogRow("+I", "Euro", 115L, "2022-01-02", "20")),
"dt:2022-01-01,hh:15;dt:2022-01-02,hh:20");
}
}
|
3e1b815c48c2623ecc9d2cf90abb80b39a0a760b | 391 | java | Java | library/src/main/java/com/hololo/tutorial/library/StepView.java | smhdk/tutorial-view | eff330476789ec92334aa8157a154a6753d6ac22 | [
"MIT"
] | 255 | 2017-05-09T08:49:34.000Z | 2022-03-04T17:57:44.000Z | library/src/main/java/com/hololo/tutorial/library/StepView.java | smhdk/tutorial-view | eff330476789ec92334aa8157a154a6753d6ac22 | [
"MIT"
] | 15 | 2017-09-27T20:43:20.000Z | 2020-09-15T14:31:27.000Z | library/src/main/java/com/hololo/tutorial/library/StepView.java | smhdk/tutorial-view | eff330476789ec92334aa8157a154a6753d6ac22 | [
"MIT"
] | 61 | 2017-09-25T13:23:24.000Z | 2020-12-01T08:45:56.000Z | 21.722222 | 63 | 0.734015 | 11,659 | package com.hololo.tutorial.library;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public class StepView extends Fragment {
Step step;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
step = getArguments().getParcelable("step");
}
}
|
3e1b82345c4c78c27112f2b7039d4cbd70e8326b | 705 | java | Java | src/main/java/ca/ulaval/glo4003/users/domain/exceptions/InvalidBirthDateException.java | ExiledNarwal28/glo-4003-spamdul | 5d7484d754f23a3579bedbb6800e8adf464c3491 | [
"MIT"
] | 1 | 2021-02-09T01:46:59.000Z | 2021-02-09T01:46:59.000Z | src/main/java/ca/ulaval/glo4003/users/domain/exceptions/InvalidBirthDateException.java | ExiledNarwal28/glo-4003-spamdul | 5d7484d754f23a3579bedbb6800e8adf464c3491 | [
"MIT"
] | null | null | null | src/main/java/ca/ulaval/glo4003/users/domain/exceptions/InvalidBirthDateException.java | ExiledNarwal28/glo-4003-spamdul | 5d7484d754f23a3579bedbb6800e8adf464c3491 | [
"MIT"
] | 2 | 2021-02-09T01:46:37.000Z | 2021-04-14T03:54:22.000Z | 32.045455 | 80 | 0.775887 | 11,660 | package ca.ulaval.glo4003.users.domain.exceptions;
import ca.ulaval.glo4003.errors.domain.ErrorCode;
import ca.ulaval.glo4003.errors.domain.exceptions.ApplicationException;
public class InvalidBirthDateException extends ApplicationException {
private static final String ERROR = "Invalid birth date";
private static final String DESCRIPTION = "Birth date must be of format : %s";
private static final ErrorCode CODE = ErrorCode.INVALID_REQUEST;
private final String format;
public InvalidBirthDateException(String format) {
super(ERROR, DESCRIPTION, CODE);
this.format = format;
}
@Override
public String getDescription() {
return String.format(DESCRIPTION, format);
}
}
|
3e1b82601826960051f5a0d55ad544bf42089c7b | 510 | java | Java | springcloud-config-eureka-client-7001/src/main/java/com/lx/spring/springcloud/Config_Eureka_Client_7001.java | lx106/springcloud | d749a53c09a3a24ac4e6901252274bfb39afd3d0 | [
"Apache-2.0"
] | null | null | null | springcloud-config-eureka-client-7001/src/main/java/com/lx/spring/springcloud/Config_Eureka_Client_7001.java | lx106/springcloud | d749a53c09a3a24ac4e6901252274bfb39afd3d0 | [
"Apache-2.0"
] | null | null | null | springcloud-config-eureka-client-7001/src/main/java/com/lx/spring/springcloud/Config_Eureka_Client_7001.java | lx106/springcloud | d749a53c09a3a24ac4e6901252274bfb39afd3d0 | [
"Apache-2.0"
] | null | null | null | 25.5 | 74 | 0.792157 | 11,661 | package com.lx.spring.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* Created with liuxun
* Description:
* Date: 2018-07-11-9:30
*/
@SpringBootApplication
@EnableEurekaServer
public class Config_Eureka_Client_7001 {
public static void main(String[] args){
SpringApplication.run(Config_Eureka_Client_7001.class,args);
}
}
|
3e1b8298eb4b07f772156785071d39d2ad02ed32 | 348 | java | Java | springboot-thymeleaf/src/main/java/zam/hzh/thymeleaf/SpringbootThymeleafApplication.java | hzhxzqs/SpringBootDemo | e1036662b08a70d2403e6e81794e35e1cf3667f3 | [
"Apache-2.0"
] | null | null | null | springboot-thymeleaf/src/main/java/zam/hzh/thymeleaf/SpringbootThymeleafApplication.java | hzhxzqs/SpringBootDemo | e1036662b08a70d2403e6e81794e35e1cf3667f3 | [
"Apache-2.0"
] | null | null | null | springboot-thymeleaf/src/main/java/zam/hzh/thymeleaf/SpringbootThymeleafApplication.java | hzhxzqs/SpringBootDemo | e1036662b08a70d2403e6e81794e35e1cf3667f3 | [
"Apache-2.0"
] | null | null | null | 24.857143 | 74 | 0.804598 | 11,662 | package zam.hzh.thymeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootThymeleafApplication.class, args);
}
}
|
3e1b8384b61fe78bf917fd023ba5d729ba639d33 | 2,120 | java | Java | app/src/main/java/com/android/simpletodo/EditItemActivity.java | QuangMuop/TodoApp | 0b8bf937fd8b3ee34dbc4433559cf5ed8e928044 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/simpletodo/EditItemActivity.java | QuangMuop/TodoApp | 0b8bf937fd8b3ee34dbc4433559cf5ed8e928044 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/simpletodo/EditItemActivity.java | QuangMuop/TodoApp | 0b8bf937fd8b3ee34dbc4433559cf5ed8e928044 | [
"Apache-2.0"
] | null | null | null | 31.176471 | 86 | 0.591509 | 11,663 | package com.android.simpletodo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.ArrayList;
public class EditItemActivity extends AppCompatActivity {
ArrayList<String> items;
ImageButton btnEdit, btnSave, btnDelete, btnClose;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
editText = (EditText) findViewById(R.id.edtEdit);
btnSave = (ImageButton)findViewById(R.id.btnSave);
btnDelete = (ImageButton)findViewById(R.id.btnDelete);
btnClose = (ImageButton)findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(EditItemActivity.this, MainActivity.class);
startActivity(intent);
}
}
);
Bundle bd = getIntent().getExtras();
if(bd!=null){
String text = bd.getString("item");
editText.setText(text);
}
else {
editText.setText("");
}
btnSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
String newTxt = editText.getText().toString();
Intent intent = new Intent();
intent.putExtra("newText", newTxt);
setResult(10, intent);
finish();
}
}
);
btnDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
String newTxt = editText.getText().toString();
Intent intent = new Intent();
intent.putExtra("newText", newTxt);
setResult(20, intent);
finish();
}
}
);
}
}
|
3e1b838e403d6c6861603cfcf7ec7d1fd8cd4eac | 4,987 | java | Java | src/main/java/eu/datex/v220/VmsUnitTable.java | svvsaga/datex-client | f4f65e7ae2250ed6db8590783a0825dcedd785f2 | [
"MIT"
] | 2 | 2020-05-06T20:38:49.000Z | 2020-07-19T20:44:02.000Z | src/main/java/eu/datex/v220/VmsUnitTable.java | svvsaga/datex-client | f4f65e7ae2250ed6db8590783a0825dcedd785f2 | [
"MIT"
] | null | null | null | src/main/java/eu/datex/v220/VmsUnitTable.java | svvsaga/datex-client | f4f65e7ae2250ed6db8590783a0825dcedd785f2 | [
"MIT"
] | 4 | 2020-02-07T09:43:27.000Z | 2021-08-02T12:46:45.000Z | 27.552486 | 123 | 0.605173 | 11,664 |
package eu.datex.v220;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for VmsUnitTable complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="VmsUnitTable">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="vmsUnitTableIdentification" type="{http://datex2.eu/schema/2/2_0}String" minOccurs="0"/>
* <element name="vmsUnitRecord" type="{http://datex2.eu/schema/2/2_0}VmsUnitRecord" maxOccurs="unbounded"/>
* <element name="vmsUnitTableExtension" type="{http://datex2.eu/schema/2/2_0}_ExtensionType" minOccurs="0"/>
* </sequence>
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VmsUnitTable", namespace = "http://datex2.eu/schema/2/2_0", propOrder = {
"vmsUnitTableIdentification",
"vmsUnitRecord",
"vmsUnitTableExtension"
})
public class VmsUnitTable {
@XmlElement(namespace = "http://datex2.eu/schema/2/2_0")
protected String vmsUnitTableIdentification;
@XmlElement(namespace = "http://datex2.eu/schema/2/2_0", required = true)
protected List<VmsUnitRecord> vmsUnitRecord;
@XmlElement(namespace = "http://datex2.eu/schema/2/2_0")
protected ExtensionType vmsUnitTableExtension;
@XmlAttribute(name = "id", required = true)
protected String id;
@XmlAttribute(name = "version", required = true)
protected String version;
/**
* Gets the value of the vmsUnitTableIdentification property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVmsUnitTableIdentification() {
return vmsUnitTableIdentification;
}
/**
* Sets the value of the vmsUnitTableIdentification property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVmsUnitTableIdentification(String value) {
this.vmsUnitTableIdentification = value;
}
/**
* Gets the value of the vmsUnitRecord property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the vmsUnitRecord property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVmsUnitRecord().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link VmsUnitRecord }
*
*
*/
public List<VmsUnitRecord> getVmsUnitRecord() {
if (vmsUnitRecord == null) {
vmsUnitRecord = new ArrayList<VmsUnitRecord>();
}
return this.vmsUnitRecord;
}
/**
* Gets the value of the vmsUnitTableExtension property.
*
* @return
* possible object is
* {@link ExtensionType }
*
*/
public ExtensionType getVmsUnitTableExtension() {
return vmsUnitTableExtension;
}
/**
* Sets the value of the vmsUnitTableExtension property.
*
* @param value
* allowed object is
* {@link ExtensionType }
*
*/
public void setVmsUnitTableExtension(ExtensionType value) {
this.vmsUnitTableExtension = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
|
3e1b849bf84bf3faf010a71c1e0b39ffb0ac6ac9 | 1,263 | java | Java | src/main/java/org/hzero/platform/infra/mapper/LovMapper.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | 7 | 2020-09-27T09:09:27.000Z | 2021-06-11T12:48:32.000Z | src/main/java/org/hzero/platform/infra/mapper/LovMapper.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | null | null | null | src/main/java/org/hzero/platform/infra/mapper/LovMapper.java | yang-zhang99/hzero-platform | e3ad6091c1292a43443461e02428cb380f4ed9db | [
"Apache-2.0"
] | 17 | 2020-09-23T07:51:40.000Z | 2021-11-23T13:52:08.000Z | 23.109091 | 142 | 0.638867 | 11,665 | package org.hzero.platform.infra.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.hzero.platform.domain.entity.Lov;
import io.choerodon.mybatis.common.BaseMapper;
/**
* <p><b>name</b> LovMapper</p>
* <p><b>description</b> 值集头Mapper</p>
* @author envkt@example.com 2018年6月5日下午7:45:46
* @version 1.0
*/
public interface LovMapper extends BaseMapper<Lov> {
/**
* 条件查询Lov头
* @param queryParam 查询条件
* @return Lov头
*/
List<Lov> selectLovHeaders(Lov queryParam);
/**
* 查询与给定代码重复的数据库记录数
* @param queryParam 查询条件
* @return 重复的数据库记录数
*/
int selectRepeatCodeCount(Lov queryParam);
/**
* 根据值集ID查询值集
* @param lovId
* @return
*/
Lov selectLovHeaderByLovId(@Param("lovId") Long lovId, @Param("tenantId") Long tenantId, @Param("sqlTypeControl") boolean sqlTypeControl);
/**
* 数据组维度查询
* @param queryParam
* @return
*/
List<Lov> listLovForDataGroupDimension(Lov queryParam);
/**
* 查询0租户下的父级值集
*
* @param lovCode 查询code
* @param tenantId 租户Id
* @return Lov
*/
Lov selectLovHeaderByCodeAndTenant(@Param("lovCode") String lovCode, @Param("tenantId") Long tenantId);
}
|
3e1b8700100f8314b590e611ab4c5dc0fe6c6e00 | 674 | java | Java | src/main/java/KnowledgeableReview201901/designPatterns/abstractFactory/ShapeFactory.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | null | null | null | src/main/java/KnowledgeableReview201901/designPatterns/abstractFactory/ShapeFactory.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | 1 | 2020-06-15T20:06:08.000Z | 2020-06-15T20:06:08.000Z | src/main/java/KnowledgeableReview201901/designPatterns/abstractFactory/ShapeFactory.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | null | null | null | 16.85 | 65 | 0.560831 | 11,666 | package KnowledgeableReview201901.designPatterns.abstractFactory;
/**
* Created with IntelliJ IDEA.
* Author: Abbot
* Date: 2018-03-19
* Time: 15:44:38
* Description:
*/
public class ShapeFactory extends AbstractFactory
{
@Override
Color getColor(String color)
{
return null;
}
@Override
Shape getShape(String shape)
{
if(shape== null)
{
return null;
}
if(shape.equalsIgnoreCase("car"))
{
return new CarFactory();
}
if(shape.equalsIgnoreCase("computer"))
{
return new ComputerFactory();
}
return null;
}
}
|
3e1b8721aae96e88c0dece8b4d0cecfe1dff5979 | 606 | java | Java | core/src/de/longri/cachebox3/gui/menu/menuBtn1/Action_Share.java | Longri/cachebox3.0 | 517e6c35f58a1636f00ff96cf99ffbf229597125 | [
"Apache-2.0"
] | 10 | 2016-07-13T22:10:32.000Z | 2022-03-20T17:08:01.000Z | core/src/de/longri/cachebox3/gui/menu/menuBtn1/Action_Share.java | Longri/cachebox3.0 | 517e6c35f58a1636f00ff96cf99ffbf229597125 | [
"Apache-2.0"
] | 257 | 2016-06-28T20:17:45.000Z | 2020-06-15T18:44:47.000Z | core/src/de/longri/cachebox3/gui/menu/menuBtn1/Action_Share.java | Longri/cachebox3.0 | 517e6c35f58a1636f00ff96cf99ffbf229597125 | [
"Apache-2.0"
] | 6 | 2016-08-15T07:35:46.000Z | 2020-01-29T10:18:39.000Z | 23.307692 | 63 | 0.721122 | 11,667 | package de.longri.cachebox3.gui.menu.menuBtn1;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import de.longri.cachebox3.CB;
import de.longri.cachebox3.gui.menu.MenuID;
import de.longri.cachebox3.gui.stages.AbstractAction;
import static de.longri.cachebox3.PlatformConnector.shareInfos;
public class Action_Share extends AbstractAction {
public Action_Share() {
super("Share", MenuID.SHARE_INFOS);
}
@Override
public void execute() {
shareInfos();
}
@Override
public Drawable getIcon() {
return CB.getSkin().menuIcon.me1ShareInfos;
}
}
|
3e1b875feb4bc27144c80fd9564f95385c2b3ccd | 188 | java | Java | src/com/example/exceptions/DAOException.java | collegboi/MotorSpy-Software-Engineering- | b0989919a4715c73845f856831f7a465ab43cf32 | [
"MIT"
] | null | null | null | src/com/example/exceptions/DAOException.java | collegboi/MotorSpy-Software-Engineering- | b0989919a4715c73845f856831f7a465ab43cf32 | [
"MIT"
] | null | null | null | src/com/example/exceptions/DAOException.java | collegboi/MotorSpy-Software-Engineering- | b0989919a4715c73845f856831f7a465ab43cf32 | [
"MIT"
] | null | null | null | 15.666667 | 45 | 0.68617 | 11,668 | package com.example.exceptions;
public class DAOException extends Exception {
public DAOException() {
}
public DAOException(String aMessage) {
super(aMessage);
}
}
|
3e1b8772d78ac5601fc43dea1d275146a0973485 | 2,590 | java | Java | Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/response/PassThruMode.java | connect-cgi/CONNECT | 5f71b77155ac2c68a323eb8ea1549bc8a356e78c | [
"BSD-3-Clause"
] | 37 | 2015-02-11T15:26:13.000Z | 2021-12-08T06:48:47.000Z | Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/response/PassThruMode.java | connect-cgi/CONNECT | 5f71b77155ac2c68a323eb8ea1549bc8a356e78c | [
"BSD-3-Clause"
] | 519 | 2015-01-06T18:06:52.000Z | 2019-09-04T18:25:11.000Z | Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/response/PassThruMode.java | connect-cgi/CONNECT | 5f71b77155ac2c68a323eb8ea1549bc8a356e78c | [
"BSD-3-Clause"
] | 63 | 2015-01-04T07:35:46.000Z | 2021-06-24T19:40:38.000Z | 43.166667 | 116 | 0.746718 | 11,669 | /*
* Copyright (c) 2009-2019, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.patientdiscovery.response;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import org.hl7.v3.II;
import org.hl7.v3.PRPAIN201306UV02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author dunnek
*/
public class PassThruMode implements ResponseMode {
private static final Logger LOG = LoggerFactory.getLogger(PassThruMode.class);
public PassThruMode() {
super();
}
@Override
public PRPAIN201306UV02 processResponse(ResponseParams params) {
// In pass through mode, no additional processing is done by the Entity.
// 201306 is returned directly to the agency.
LOG.trace("begin processResponse");
return params.response;
}
@Override
public PRPAIN201306UV02 processResponse(PRPAIN201306UV02 response, AssertionType assertion, II localPatientId) {
return response;
}
}
|
3e1b888f21999e4b3cee232cd40e71d4840d253f | 1,827 | java | Java | amazon/java/cut_off_trees_golf_event_675.java | Xiaoyu-Xing/algorithms | 93936aeeef64487285db360b5884e844e0662b8e | [
"MIT"
] | null | null | null | amazon/java/cut_off_trees_golf_event_675.java | Xiaoyu-Xing/algorithms | 93936aeeef64487285db360b5884e844e0662b8e | [
"MIT"
] | null | null | null | amazon/java/cut_off_trees_golf_event_675.java | Xiaoyu-Xing/algorithms | 93936aeeef64487285db360b5884e844e0662b8e | [
"MIT"
] | null | null | null | 35.823529 | 109 | 0.417625 | 11,670 | // BFS, map, time O((r*c)^2) space O(r*c)
class Solution {
public int cutOffTree(List<List<Integer>> forest) {
List<int[]> trees = new ArrayList();
for (int r = 0; r < forest.size(); r++) {
for (int c = 0; c < forest.get(r).size(); c++) {
int value = forest.get(r).get(c);
if (value > 1) {
trees.add(new int[] {value, r, c});
}
}
}
Collections.sort(trees, (a, b) -> Integer.compare(a[0], b[0]));
int ans = 0, sr = 0, sc = 0;
for (int[] tree: trees) {
int dis = dist(forest, sr, sc, tree[1], tree[2]);
if (dis < 0) return -1;
ans += dis;
sr = tree[1];
sc = tree[2];
}
return ans;
}
public int dist(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {
int[] dr = {-1, 1, 0, 0};
int[] dc = {0, 0, -1, 1};
int height = forest.size();
int width = forest.get(0).size();
Queue<int[]> queue = new LinkedList();
// Queue includes the array of row#, column#, and distance to source
queue.offer(new int[] {sr, sc, 0});
boolean[][] seen = new boolean[height][width];
seen[sr][sc] = true;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
if (cur[0] == tr && cur[1] == tc) return cur[2];
for (int di = 0; di < 4; di++) {
int r = cur[0] + dr[di];
int c = cur[1] + dc[di];
if (0 <= r && r < height && 0 <= c && c < width && !seen[r][c] && forest.get(r).get(c) > 0) {
seen[r][c] = true;
queue.offer(new int[] {r, c, cur[2]+1});
}
}
}
return -1;
}
} |
3e1b88de32ec76cefe65079be8c85bc84b7fa201 | 676 | java | Java | spring-demo/src/main/java/com/xinyu/proxyDemo/CglibProxy/BeforeAdvice.java | xinyu894235025/spring-framework | 297a50c9cb854bfedfad47d0e89800cae43d85bb | [
"Apache-2.0"
] | null | null | null | spring-demo/src/main/java/com/xinyu/proxyDemo/CglibProxy/BeforeAdvice.java | xinyu894235025/spring-framework | 297a50c9cb854bfedfad47d0e89800cae43d85bb | [
"Apache-2.0"
] | null | null | null | spring-demo/src/main/java/com/xinyu/proxyDemo/CglibProxy/BeforeAdvice.java | xinyu894235025/spring-framework | 297a50c9cb854bfedfad47d0e89800cae43d85bb | [
"Apache-2.0"
] | null | null | null | 21.806452 | 108 | 0.717456 | 11,671 | package com.xinyu.proxyDemo.CglibProxy;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* @Description
* @Author xinyu4
* @Date 2021/3/10/0010 17:45
*/
public class BeforeAdvice implements MethodInterceptor {
/**
* 代理方法, 每次调用目标方法时都会进到这里
*/
@Override
public Object intercept(Object o, Method method, Object[] objs, MethodProxy methodProxy) throws Throwable {
before();
return methodProxy.invokeSuper(o, objs);
// return method.invoke(obj, args); 这种也行
}
/**
* 前置增强
*/
private void before() {
System.out.println("The before Enhancer!");
}
}
|
3e1b8944b773aa1d7dcef1364fedb0df75f9d7e3 | 860 | java | Java | src/main/java/frc/robot/commands/Drive_Joystick_command.java | zumrutsarp/2021-frc | 768983a38b8e52791c51449f70314671436055fd | [
"BSD-3-Clause"
] | 1 | 2021-06-15T17:24:56.000Z | 2021-06-15T17:24:56.000Z | src/main/java/frc/robot/commands/Drive_Joystick_command.java | zumrutsarp/2021-frc | 768983a38b8e52791c51449f70314671436055fd | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/Drive_Joystick_command.java | zumrutsarp/2021-frc | 768983a38b8e52791c51449f70314671436055fd | [
"BSD-3-Clause"
] | null | null | null | 19.545455 | 123 | 0.772093 | 11,672 |
package frc.robot.commands;
import java.util.function.DoubleSupplier;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.Drive_Train_Subsystem;
public class Drive_Joystick_command extends CommandBase {
Drive_Train_Subsystem m_drive;
DoubleSupplier m_rotation;
DoubleSupplier m_forward;
public Drive_Joystick_command( Drive_Train_Subsystem drive_Subsystem,DoubleSupplier rotation,DoubleSupplier forward ) {
this.m_drive=drive_Subsystem;
this.m_forward=forward;
this.m_rotation=rotation;
addRequirements(m_drive);
}
@Override
public void initialize() {}
@Override
public void execute() {
m_drive.arcade_Drive(m_forward.getAsDouble(), m_rotation.getAsDouble());
}
@Override
public void end(boolean interrupted) {}
@Override
public boolean isFinished() {
return false;
}
}
|
3e1b89b1ab5244e4a0610f90424f5296cc93ab44 | 2,427 | java | Java | src/myfaces-impl-2.1.10-sources/org/apache/myfaces/view/facelets/compiler/NamespaceHandler.java | JavaQualitasCorpus/myfaces_core-2.1.10 | 10c9f2d038dd91c0b4f78ba9ad9ed44b20fb55c3 | [
"Apache-2.0"
] | null | null | null | src/myfaces-impl-2.1.10-sources/org/apache/myfaces/view/facelets/compiler/NamespaceHandler.java | JavaQualitasCorpus/myfaces_core-2.1.10 | 10c9f2d038dd91c0b4f78ba9ad9ed44b20fb55c3 | [
"Apache-2.0"
] | null | null | null | src/myfaces-impl-2.1.10-sources/org/apache/myfaces/view/facelets/compiler/NamespaceHandler.java | JavaQualitasCorpus/myfaces_core-2.1.10 | 10c9f2d038dd91c0b4f78ba9ad9ed44b20fb55c3 | [
"Apache-2.0"
] | null | null | null | 31.934211 | 115 | 0.713226 | 11,673 | /*
* 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.myfaces.view.facelets.compiler;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import javax.el.ELException;
import javax.el.FunctionMapper;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.view.facelets.FaceletContext;
import javax.faces.view.facelets.FaceletException;
import javax.faces.view.facelets.FaceletHandler;
import org.apache.myfaces.view.facelets.el.CompositeFunctionMapper;
import org.apache.myfaces.view.facelets.tag.TagLibrary;
final class NamespaceHandler extends FunctionMapper implements FaceletHandler
{
private final TagLibrary library;
private final Map<String, String> ns;
private FaceletHandler next;
public NamespaceHandler(FaceletHandler next, TagLibrary library, Map<String, String> ns)
{
this.library = library;
this.ns = ns;
this.next = next;
}
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException,
ELException
{
FunctionMapper orig = ctx.getFunctionMapper();
ctx.setFunctionMapper(new CompositeFunctionMapper(this, orig));
try
{
next.apply(ctx, parent);
}
finally
{
ctx.setFunctionMapper(orig);
}
}
public Method resolveFunction(String prefix, String localName)
{
String uri = (String) this.ns.get(prefix);
if (uri != null)
{
return this.library.createFunction(uri, localName);
}
return null;
}
}
|
3e1b8a67bfa57b2ceb7355c5c1ce141871c6aee9 | 10,836 | java | Java | src/integrationTest/java/uk/gov/hmcts/reform/bulkscan/orchestrator/client/transformation/TransformationClientTest.java | hmcts/bulk-scan-orchestrator | 38ab93befeddf9c583d042dbcc8170a37452586c | [
"MIT"
] | 1 | 2020-07-13T05:50:54.000Z | 2020-07-13T05:50:54.000Z | src/integrationTest/java/uk/gov/hmcts/reform/bulkscan/orchestrator/client/transformation/TransformationClientTest.java | hmcts/bulk-scan-orchestrator | 38ab93befeddf9c583d042dbcc8170a37452586c | [
"MIT"
] | 1,121 | 2018-08-23T10:14:13.000Z | 2022-03-30T07:18:10.000Z | src/integrationTest/java/uk/gov/hmcts/reform/bulkscan/orchestrator/client/transformation/TransformationClientTest.java | hmcts/bulk-scan-orchestrator | 38ab93befeddf9c583d042dbcc8170a37452586c | [
"MIT"
] | 3 | 2019-01-24T07:01:49.000Z | 2021-04-10T22:36:32.000Z | 42 | 129 | 0.699982 | 11,674 | package uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException.BadRequest;
import org.springframework.web.client.HttpClientErrorException.Forbidden;
import org.springframework.web.client.HttpClientErrorException.Unauthorized;
import org.springframework.web.client.HttpClientErrorException.UnprocessableEntity;
import org.springframework.web.client.HttpServerErrorException.InternalServerError;
import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.DocumentType;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.DocumentUrl;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.OcrDataField;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.ScannedDocument;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.model.request.TransformationRequest;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.model.response.CaseCreationDetails;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.model.response.SuccessfulTransformationResponse;
import uk.gov.hmcts.reform.bulkscan.orchestrator.config.IntegrationTest;
import uk.gov.hmcts.reform.bulkscan.orchestrator.services.servicebus.domains.envelopes.model.Classification;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.forbidden;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.serverError;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.unauthorized;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static java.time.LocalDateTime.now;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.UUID.randomUUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.BDDMockito.given;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
import static uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.TransformationResponseTestData.errorResponse;
import static uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.TransformationResponseTestData.invalidDataResponse;
import static uk.gov.hmcts.reform.bulkscan.orchestrator.client.transformation.TransformationResponseTestData.successResponse;
@AutoConfigureWireMock(port = 0)
@IntegrationTest
public class TransformationClientTest {
private static final String TRANSFORMATION_URL = "/transform-exception-record";
@MockBean
private AuthTokenGenerator s2sTokenGenerator;
@Autowired
private TransformationClient client;
@Value("${service-config.services[0].transformation-url}")
private String transformationUrl;
@Test
public void should_return_case_details_for_successful_transformation() throws Exception {
// given
String s2sToken = setupS2sTokenGeneratorToReturnOneToken();
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.withHeader("ServiceAuthorization", equalTo(s2sToken))
.withRequestBody(matchingJsonPath("scanned_documents[0].type", matching("[a-z]+")))
.willReturn(okJson(successResponse().toString()))
);
// when
SuccessfulTransformationResponse response = client.transformCaseData(
transformationUrl,
sampleTransformationRequest()
);
// then
assertThat(response).isNotNull();
assertThat(response.warnings).isEmpty();
CaseCreationDetails caseCreationDetails = response.caseCreationDetails;
assertThat(caseCreationDetails).isNotNull();
assertThat(caseCreationDetails.caseTypeId).isEqualTo("some_case_type");
assertThat(caseCreationDetails.eventId).isEqualTo("createCase");
assertThat(caseCreationDetails.caseData).isNotNull();
}
@Test
public void should_throw_unprocessable_entity_exception_for_unprocessable_entity_response() throws Exception {
// given
String s2sToken = setupS2sTokenGeneratorToReturnOneToken();
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.withHeader("ServiceAuthorization", equalTo(s2sToken))
.willReturn(aResponse().withBody(errorResponse().toString()).withStatus(UNPROCESSABLE_ENTITY.value())));
// when
UnprocessableEntity exception = catchThrowableOfType(
() -> client.transformCaseData(transformationUrl, sampleTransformationRequest()),
UnprocessableEntity.class
);
// then
assertThat(exception.getStatusCode()).isEqualTo(UNPROCESSABLE_ENTITY);
assertThat(exception.getStatusText()).isEqualTo("Unprocessable Entity");
assertThat(exception.getResponseBodyAsString())
.isEqualTo("{\"warnings\":[\"field2 is missing\"],\"errors\":[\"field1 is missing\"]}");
}
@Test
public void should_throw_invalid_case_data_exception_for_bad_request() throws Exception {
// given
String s2sToken = setupS2sTokenGeneratorToReturnOneToken();
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.withHeader("ServiceAuthorization", equalTo(s2sToken))
.willReturn(aResponse().withBody(invalidDataResponse().toString()).withStatus(BAD_REQUEST.value())));
// when
BadRequest exception = catchThrowableOfType(
() -> client.transformCaseData(transformationUrl, sampleTransformationRequest()),
BadRequest.class
);
// then
assertThat(exception.getStatusCode()).isEqualTo(BAD_REQUEST);
assertThat(exception.getResponseBodyAsString()).isEqualTo("{\"errors\":[\"field1 is missing\"]}");
}
@Test
public void should_throw_case_client_service_exception_when_unable_to_process_body() {
// given
String s2sToken = setupS2sTokenGeneratorToReturnOneToken();
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.withHeader("ServiceAuthorization", equalTo(s2sToken))
.willReturn(aResponse().withBody(new byte[]{}).withStatus(BAD_REQUEST.value())));
// when
BadRequest exception = catchThrowableOfType(
() -> client.transformCaseData(transformationUrl, sampleTransformationRequest()),
BadRequest.class
);
// then
assertThat(exception.getStatusCode()).isEqualTo(BAD_REQUEST);
assertThat(exception.getResponseBodyAsString()).isEqualTo(""); // because byte[]{}
}
@Test
public void should_throw_exception_for_unauthorised_service_auth_header() {
// given
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.willReturn(forbidden().withBody("Calling service is not authorised")));
// when
Forbidden exception = catchThrowableOfType(
() -> client.transformCaseData(
transformationUrl,
sampleTransformationRequest()
),
Forbidden.class
);
// then
assertThat(exception.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exception.getResponseBodyAsString()).contains("Calling service is not authorised");
}
@Test
public void should_throw_exception_for_invalid_service_auth_header() {
// given
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.willReturn(unauthorized().withBody("Invalid S2S token")));
// when
Unauthorized exception = catchThrowableOfType(
() -> client.transformCaseData(
transformationUrl,
sampleTransformationRequest()
),
Unauthorized.class
);
// then
assertThat(exception.getResponseBodyAsString()).isEqualTo("Invalid S2S token");
}
@Test
public void should_throw_exception_for_server_exception() {
// given
stubFor(
post(urlPathMatching(TRANSFORMATION_URL))
.willReturn(serverError().withBody("Internal Server error")));
// when
InternalServerError exception = catchThrowableOfType(
() -> client.transformCaseData(
transformationUrl,
sampleTransformationRequest()
),
InternalServerError.class
);
// then
assertThat(exception.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(exception.getResponseBodyAsString()).contains("Internal Server error");
}
private TransformationRequest sampleTransformationRequest() {
return new TransformationRequest(
"id",
"some_case_type",
"envelope_id",
false,
"poBox",
"BULKSCAN",
Classification.NEW_APPLICATION,
"D8",
now(),
now(),
singletonList(new ScannedDocument(
DocumentType.CHERISHED,
"D8",
new DocumentUrl(
"http://locahost",
"http://locahost/binary",
"file1.pdf"
),
"1234",
"file1.pdf",
now(),
now()
)),
asList(
new OcrDataField("name1", "value1"),
new OcrDataField("name2", "value2")
),
false
);
}
private String setupS2sTokenGeneratorToReturnOneToken() {
String s2sToken = randomUUID().toString();
given(s2sTokenGenerator.generate()).willReturn(s2sToken);
return s2sToken;
}
}
|
3e1b8b346ec46e0cb08bec6d42492cdec961e34c | 2,722 | java | Java | src/main/java/net/imglib2/ops/condition/AbstractFunctionCondition.java | bnorthan/imagej-ops | defeee0eecc113b05685dcc6f0f475060ea1d943 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/net/imglib2/ops/condition/AbstractFunctionCondition.java | bnorthan/imagej-ops | defeee0eecc113b05685dcc6f0f475060ea1d943 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/net/imglib2/ops/condition/AbstractFunctionCondition.java | bnorthan/imagej-ops | defeee0eecc113b05685dcc6f0f475060ea1d943 | [
"BSD-2-Clause"
] | null | null | null | 29.586957 | 79 | 0.735489 | 11,675 | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 Board of Regents of the University of
* Wisconsin-Madison and University of Konstanz.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imglib2.ops.condition;
import net.imglib2.ops.function.Function;
import net.imglib2.type.numeric.RealType;
/**
* Base class for some simple conditions based upon values of functions.
*
* @author Barry DeZonia
* @deprecated Use net.imagej.ops instead.
*/
@Deprecated
public abstract class AbstractFunctionCondition<T extends RealType<T>>
implements Condition<long[]>
{
// -- instance variables --
protected Function<long[], T> func;
protected double value;
private final T var;
// -- abstract methods --
abstract boolean relationTrue(double fVal);
// -- constructor --
public AbstractFunctionCondition(Function<long[], T> func, double value) {
this.func = func;
this.value = value;
var = func.createOutput();
}
// -- Condition methods --
@Override
public boolean isTrue(long[] val) {
func.compute(val, var);
return relationTrue(var.getRealDouble());
}
// -- AbstractFunctionCondition methods --
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public Function<long[], T> getFunction() {
return func;
}
public void setFunction(Function<long[], T> func) {
this.func = func;
}
}
|
3e1b8c7a67031e2cafb120ad2171e7dfc4b67d0b | 3,309 | java | Java | odata2-lib/odata-core/src/test/java/org/apache/olingo/odata2/core/edm/provider/EdmAssociationSetEndImplProvTest.java | Infosys/olingo-odata2 | daa83f4d80f3eb8019ae2cb6729486d1821b8c89 | [
"Apache-2.0"
] | 41 | 2015-01-22T21:14:18.000Z | 2021-11-08T13:15:49.000Z | odata2-lib/odata-core/src/test/java/org/apache/olingo/odata2/core/edm/provider/EdmAssociationSetEndImplProvTest.java | Infosys/olingo-odata2 | daa83f4d80f3eb8019ae2cb6729486d1821b8c89 | [
"Apache-2.0"
] | 14 | 2015-02-26T12:15:04.000Z | 2022-03-12T16:52:28.000Z | odata2-lib/odata-core/src/test/java/org/apache/olingo/odata2/core/edm/provider/EdmAssociationSetEndImplProvTest.java | Infosys/olingo-odata2 | daa83f4d80f3eb8019ae2cb6729486d1821b8c89 | [
"Apache-2.0"
] | 88 | 2015-01-26T16:51:42.000Z | 2022-03-11T13:49:53.000Z | 44.12 | 117 | 0.754306 | 11,676 | /*******************************************************************************
* 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.olingo.odata2.core.edm.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.olingo.odata2.api.edm.EdmAnnotatable;
import org.apache.olingo.odata2.api.edm.EdmAnnotations;
import org.apache.olingo.odata2.api.edm.EdmAssociationSetEnd;
import org.apache.olingo.odata2.api.edm.EdmEntityContainer;
import org.apache.olingo.odata2.api.edm.provider.AssociationSetEnd;
import org.apache.olingo.odata2.api.edm.provider.EdmProvider;
import org.apache.olingo.odata2.api.edm.provider.EntityContainerInfo;
import org.apache.olingo.odata2.api.edm.provider.EntitySet;
import org.apache.olingo.odata2.testutil.fit.BaseTest;
import org.junit.BeforeClass;
import org.junit.Test;
public class EdmAssociationSetEndImplProvTest extends BaseTest {
private static EdmAssociationSetEnd edmAssociationSetEnd;
private static EdmProvider edmProvider;
@BeforeClass
public static void getEdmEntityContainerImpl() throws Exception {
edmProvider = mock(EdmProvider.class);
EdmImplProv edmImplProv = new EdmImplProv(edmProvider);
EntityContainerInfo entityContainer = new EntityContainerInfo().setName("Container");
EdmEntityContainer edmEntityContainer = new EdmEntityContainerImplProv(edmImplProv, entityContainer);
AssociationSetEnd associationSetEnd = new AssociationSetEnd().setRole("end1Role").setEntitySet("entitySetRole1");
EntitySet entitySet = new EntitySet().setName("entitySetRole1");
when(edmProvider.getEntitySet("Container", "entitySetRole1")).thenReturn(entitySet);
edmAssociationSetEnd =
new EdmAssociationSetEndImplProv(associationSetEnd, edmEntityContainer.getEntitySet("entitySetRole1"));
}
@Test
public void testAssociationSetEnd() throws Exception {
EdmAssociationSetEnd setEnd = edmAssociationSetEnd;
assertEquals("end1Role", setEnd.getRole());
assertEquals("entitySetRole1", setEnd.getEntitySet().getName());
}
@Test
public void getAnnotations() throws Exception {
EdmAnnotatable annotatable = (EdmAnnotatable) edmAssociationSetEnd;
EdmAnnotations annotations = annotatable.getAnnotations();
assertNull(annotations.getAnnotationAttributes());
assertNull(annotations.getAnnotationElements());
}
}
|
3e1b8c8388402771dad46986773ebf7aa8f09585 | 9,546 | java | Java | lib-translation-tool/src/main/java/eu/smesec/cysec/translationtool/Merger.java | cysec-platform/cysec-translation-tool | eec5c53ffa1ed638fac8452bfa9df8803e32a144 | [
"Apache-2.0"
] | null | null | null | lib-translation-tool/src/main/java/eu/smesec/cysec/translationtool/Merger.java | cysec-platform/cysec-translation-tool | eec5c53ffa1ed638fac8452bfa9df8803e32a144 | [
"Apache-2.0"
] | null | null | null | lib-translation-tool/src/main/java/eu/smesec/cysec/translationtool/Merger.java | cysec-platform/cysec-translation-tool | eec5c53ffa1ed638fac8452bfa9df8803e32a144 | [
"Apache-2.0"
] | null | null | null | 42.426667 | 150 | 0.631259 | 11,677 | /*-
* #%L
* CYSEC Translation Tool Library
* %%
* Copyright (C) 2021 - 2022 FHNW (University of Applied Sciences and Arts Northwestern Switzerland)
* %%
* 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.
* #L%
*/
package eu.smesec.cysec.translationtool;
import eu.smesec.cysec.platform.bridge.generated.DictionaryEntry;
import eu.smesec.cysec.platform.bridge.generated.Option;
import eu.smesec.cysec.platform.bridge.generated.Question;
import eu.smesec.cysec.platform.bridge.generated.Questionnaire;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.filters.IFilter;
import net.sf.okapi.common.resource.ITextUnit;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.filters.xliff.XLIFFFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* Merges an original coach with translations in XLIFF format.
*
* @author Matthias Luppi
*/
public class Merger {
private static final Logger log = LoggerFactory.getLogger(Merger.class);
private final Path inputFile;
private final Path xlfFile;
private final Path outputFile;
private final LocaleId trgLocale;
public Merger(final Path inputFile, final Path xlfFile, final String targetLang, final Path outputFile) {
this.inputFile = inputFile;
this.xlfFile = xlfFile;
this.trgLocale = new LocaleId(targetLang);
this.outputFile = outputFile;
}
/**
* Executes the merge operation.
*
* @return true if all translations found, false if there were missing translations
* @throws IOException if an I/O error occurs
* @throws JAXBException if an error occurred while handling the XML files
*/
public boolean merge() throws IOException, JAXBException {
if (inputFile == null) {
throw new IllegalArgumentException("Invalid input file");
}
if (xlfFile == null) {
throw new IllegalArgumentException("Invalid XLF file");
}
if (outputFile == null) {
throw new IllegalArgumentException("Invalid output file");
}
if (Files.notExists(outputFile.getParent())) {
Files.createDirectories(outputFile.getParent());
}
log.info("Base coach for translations is '{}'", inputFile);
final JAXBContext context = JAXBContext.newInstance(Questionnaire.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
final Questionnaire questionnaire = (Questionnaire) unmarshaller.unmarshal(inputFile.toFile());
// get source language from XML or use English as fallback
final LocaleId srcLocale;
if (StringUtils.isNotBlank(questionnaire.getLanguage())) {
srcLocale = new LocaleId(questionnaire.getLanguage());
log.info("Detected source language is '{}'", srcLocale.getLanguage());
} else {
srcLocale = new LocaleId("en");
log.info("No source language set, falling back to '{}'", srcLocale.getLanguage());
}
final TranslationApplier ta = new TranslationApplier(trgLocale);
// load all available translations
log.info("Reading translation entries from '{}'", xlfFile);
try (IFilter filter = new XLIFFFilter()) {
filter.open(new RawDocument(xlfFile.toUri(), StandardCharsets.UTF_8.name(), srcLocale, trgLocale));
while (filter.hasNext()) {
Event event = filter.next();
if (event.getEventType() == EventType.TEXT_UNIT) {
final ITextUnit textUnit = event.getTextUnit();
if (!textUnit.getTargetLocales().isEmpty()) {
if (textUnit.getTargetLocales().size() > 1) {
throw new IllegalArgumentException("More than one target language in XLIFF file for id=" + textUnit.getId());
}
final LocaleId localeId = textUnit.getTargetLocales().iterator().next();
if (trgLocale != localeId) {
throw new IllegalArgumentException("Requested target languages does not match translation (id=" + textUnit.getId() + ")");
}
} else {
log.debug("Translation entry contains no target element -> {}", textUnit.getId());
}
ta.learn(textUnit);
}
}
}
log.info("Loaded {} translation entries", ta.memoryCount());
// update general attributes with translations
ta.apply(TextUnitId.attr(TextUnitId.COACH_READABLE_NAME), questionnaire::setReadableName);
ta.apply(TextUnitId.attr(TextUnitId.COACH_DESCRIPTION), questionnaire::setDescription);
// update content of questions with translations
if (questionnaire.getQuestions() != null) {
for (Question question : questionnaire.getQuestions().getQuestion()) {
ta.apply(TextUnitId.attr(TextUnitId.QST_TEXT).qst(question), question::setText);
ta.apply(TextUnitId.attr(TextUnitId.QST_INTRODUCTION).qst(question), question::setIntroduction);
if (question.getOptions() != null) {
for (Option option : question.getOptions().getOption()) {
if (StringUtils.isNotBlank(option.getText())) {
ta.apply(TextUnitId.attr(TextUnitId.OPT_TEXT).qst(question).opt(option), option::setText);
}
if (StringUtils.isNotBlank(option.getComment())) {
ta.apply(TextUnitId.attr(TextUnitId.OPT_COMMENT).qst(question).opt(option), option::setComment);
}
}
}
if (StringUtils.isNotBlank(question.getInfotext())) {
ta.apply(TextUnitId.attr(TextUnitId.QST_INFOTEXT).qst(question), question::setInfotext);
}
if (StringUtils.isNotBlank(question.getReadMore())) {
ta.apply(TextUnitId.attr(TextUnitId.QST_READ_MORE).qst(question), question::setReadMore);
}
if (question.getInstruction() != null && StringUtils.isNotBlank(question.getInstruction().getText())) {
ta.apply(TextUnitId.attr(TextUnitId.QST_INSTRUCTION).qst(question), s -> question.getInstruction().setText(s));
}
}
}
// update dictionary with translations
if (questionnaire.getDictionary() != null) {
for (DictionaryEntry entry : questionnaire.getDictionary().getEntry()) {
ta.apply(TextUnitId.attr(TextUnitId.DK_TEXT).dkey(entry.getKey()), entry::setValue);
}
}
log.info("Applied {} translations", ta.getApplyCount());
log.warn("Could not find {} translations", ta.getNotFoundCount());
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(questionnaire, outputFile.toFile());
log.info("Translated coach written to '{}'", outputFile);
return (ta.getNotFoundCount() == 0);
}
private static class TranslationApplier {
private final LocaleId trgLocale;
private final Map<TextUnitId, ITextUnit> textUnitById = new HashMap<>();
private long applyCount = 0;
private long notFoundCount = 0;
public TranslationApplier(final LocaleId trgLocale) {
this.trgLocale = trgLocale;
}
public void learn(ITextUnit textUnit) {
textUnitById.put(TextUnitId.parse(textUnit.getId()), textUnit);
}
public void apply(TextUnitId id, Consumer<String> fieldSetter) {
ITextUnit textUnit = textUnitById.get(id);
if (textUnit != null && textUnit.getTarget(trgLocale) != null && !textUnit.getTarget(trgLocale).isEmpty()) {
fieldSetter.accept(textUnit.getTarget(trgLocale).toString());
log.info("Translation applied -> {} ", id);
applyCount++;
} else {
log.warn("Translation not found -> {}", id);
notFoundCount++;
}
}
public int memoryCount() {
return textUnitById.size();
}
public long getApplyCount() {
return applyCount;
}
public long getNotFoundCount() {
return notFoundCount;
}
}
}
|
3e1b8ce1763c28f3ed7cbc68b669ece63acd672e | 160 | java | Java | src/app/models/Set.java | TangZuqin/CDE3API | b0458f89352724bb60aac6c85baa8f11ccac28d5 | [
"MIT"
] | null | null | null | src/app/models/Set.java | TangZuqin/CDE3API | b0458f89352724bb60aac6c85baa8f11ccac28d5 | [
"MIT"
] | null | null | null | src/app/models/Set.java | TangZuqin/CDE3API | b0458f89352724bb60aac6c85baa8f11ccac28d5 | [
"MIT"
] | null | null | null | 17.777778 | 49 | 0.7875 | 11,678 | package app.models;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
@Table("sets")
public class Set extends Model {
}
|
3e1b8dba9ebd87cf232137447fcecdcf8494f305 | 275 | java | Java | spring-data-rest-angular/src/main/java/com/programmingfree/springservice/HomeController.java | marhan/spring-boot-sandbox | fa8930740dbce68f4724a8ff5f6cc62f44b1b531 | [
"Apache-2.0"
] | null | null | null | spring-data-rest-angular/src/main/java/com/programmingfree/springservice/HomeController.java | marhan/spring-boot-sandbox | fa8930740dbce68f4724a8ff5f6cc62f44b1b531 | [
"Apache-2.0"
] | null | null | null | spring-data-rest-angular/src/main/java/com/programmingfree/springservice/HomeController.java | marhan/spring-boot-sandbox | fa8930740dbce68f4724a8ff5f6cc62f44b1b531 | [
"Apache-2.0"
] | null | null | null | 18.333333 | 62 | 0.789091 | 11,679 | package com.programmingfree.springservice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/home")
public String home() {
return "index";
}
}
|
3e1b8ec1e82fee4af064f78d04c6789a5b31bf1d | 1,112 | java | Java | src/biovis/hackebeil/server/worker/motifWorker/MotifWorkerInterface.java | sierraplatinum/masakari | c86a2f7661a47d6541dd9b11c817b350e2aacb33 | [
"Apache-2.0"
] | null | null | null | src/biovis/hackebeil/server/worker/motifWorker/MotifWorkerInterface.java | sierraplatinum/masakari | c86a2f7661a47d6541dd9b11c817b350e2aacb33 | [
"Apache-2.0"
] | 1 | 2018-01-14T11:03:33.000Z | 2018-01-15T16:20:35.000Z | src/biovis/hackebeil/server/worker/motifWorker/MotifWorkerInterface.java | sierraplatinum/masakari | c86a2f7661a47d6541dd9b11c817b350e2aacb33 | [
"Apache-2.0"
] | null | null | null | 32.705882 | 80 | 0.639388 | 11,680 | /**
* *****************************************************************************
* Copyright 2015 Dirk Zeckzer, Lydia Müller, Daniel Gerighausen
*
* 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 biovis.hackebeil.server.worker.motifWorker;
import biovis.hackebeil.common.data.Motif;
import java.util.List;
import java.util.Map;
/**
*
* @author zeckzer
*/
public interface MotifWorkerInterface {
public void setMotifList(List<Motif> motifList);
public Map<String, List<Double>> getMotifValues();
}
|
3e1b8ed261dbb94ad6770ff5610c25920e32eced | 157 | java | Java | chapter_002/src/main/java/by/vorokhobko/inheritance/package-info.java | EvgenyVorohobko/java-a-to-z | cfce43406af66d25551f5d57194a741ec15a73c0 | [
"Apache-2.0"
] | 1 | 2017-08-02T00:46:49.000Z | 2017-08-02T00:46:49.000Z | chapter_002/src/main/java/by/vorokhobko/inheritance/package-info.java | EvgenyVorohobko/java-a-to-z | cfce43406af66d25551f5d57194a741ec15a73c0 | [
"Apache-2.0"
] | 5 | 2021-01-20T23:08:28.000Z | 2021-12-14T21:16:55.000Z | chapter_002/src/main/java/by/vorokhobko/inheritance/package-info.java | 1Evgeny/java-a-to-z | cfce43406af66d25551f5d57194a741ec15a73c0 | [
"Apache-2.0"
] | null | null | null | 20.5 | 56 | 0.670732 | 11,681 | /**
* //TODO add comments.
*
* @author Evgeny Vorokhobko (lyhxr@example.com).
* @version 1.
* @since 16.01.2017.
*/
package by.vorokhobko.inheritance; |
3e1b8ed593398668ee39dc4e0f9c6247f40538ec | 3,678 | java | Java | forest-rpc/src/main/java/com/zhizus/forest/ForestRouter.java | dempeZheng/yysrv | 2f6cd1f6a72a541bf7c6440a91713a33895be2ff | [
"Apache-2.0"
] | 450 | 2016-02-18T14:06:14.000Z | 2022-03-04T02:58:01.000Z | forest-rpc/src/main/java/com/zhizus/forest/ForestRouter.java | houxudong01/forest | 2f6cd1f6a72a541bf7c6440a91713a33895be2ff | [
"Apache-2.0"
] | 6 | 2016-06-08T06:40:38.000Z | 2018-08-28T03:30:43.000Z | forest-rpc/src/main/java/com/zhizus/forest/ForestRouter.java | houxudong01/forest | 2f6cd1f6a72a541bf7c6440a91713a33895be2ff | [
"Apache-2.0"
] | 213 | 2016-04-19T08:29:40.000Z | 2022-02-25T02:16:16.000Z | 37.530612 | 145 | 0.626427 | 11,682 | package com.zhizus.forest;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.zhizus.forest.common.annotation.Interceptor;
import com.zhizus.forest.common.annotation.MethodExport;
import com.zhizus.forest.common.annotation.Rate;
import com.zhizus.forest.common.config.ServiceExportConfig;
import com.zhizus.forest.common.util.ForestUtil;
import com.zhizus.forest.common.interceptor.InvokerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Created by Dempe on 2016/12/9.
*/
public class ForestRouter implements IRouter {
private final static Logger LOGGER = LoggerFactory.getLogger(ForestRouter.class);
private Map<String, ActionMethod> routerMapping = Maps.newConcurrentMap();
private ApplicationContext context;
public ForestRouter(ApplicationContext context) {
this.context = context;
}
public void init(Object bean, ServiceExportConfig config) {
for (Method method : bean.getClass().getMethods()) {
MethodExport methodExport = method.getAnnotation(MethodExport.class);
if (methodExport == null) {
continue;
}
if (Strings.isNullOrEmpty(config.getServiceName()) || Strings.isNullOrEmpty(config.getMethodName(method))) {
LOGGER.warn("methodName or service is null.methodName:{},serviceName:{}", config.getMethodName(method), config.getServiceName());
}
String uri = ForestUtil.buildUri(config.getServiceName(), config.getMethodName(method));
ActionMethod actionMethod = new ActionMethod(bean, method);
routerMapping.put(uri, actionMethod);
initInterceptor(actionMethod, context);
initRate(actionMethod);
}
}
public void initRate(ActionMethod actionMethod) {
Rate rate = actionMethod.getMethod().getAnnotation(Rate.class);
if (rate != null) {
int value = rate.value();
if (value > 0) {
actionMethod.setRateLimiter(RateLimiter.create(value));
} else {
LOGGER.warn("Rate value < 0 !");
}
}
}
public void initInterceptor(ActionMethod actionMethod, ApplicationContext context) {
Interceptor interceptor = actionMethod.getMethod().getAnnotation(Interceptor.class);
if (interceptor != null) {
String id = interceptor.value();
if (Strings.isNullOrEmpty(id) && context != null) {
Class<?> clazz = interceptor.clazz();
if (clazz == Object.class) {
LOGGER.warn("Interceptor id is empty !");
} else {
Object bean = context.getBean(clazz);
if (bean != null && bean instanceof InvokerInterceptor) {
actionMethod.addInterceptorList((InvokerInterceptor) bean);
}
}
} else {
for (String beanId : id.split(",")) {
Object bean = context.getBean(beanId);
if (bean != null && bean instanceof InvokerInterceptor) {
InvokerInterceptor invokerInterceptor = (InvokerInterceptor) bean;
actionMethod.addInterceptorList(invokerInterceptor);
}
}
}
}
}
@Override
public ActionMethod router(String uri) {
return routerMapping.get(uri);
}
}
|
3e1b8f027726f3817792509bff54d85a36634aab | 1,382 | java | Java | community/server/src/test/java/org/neo4j/server/configuration/validation/DatabaseLocationMustBeSpecifiedRuleTest.java | jexp/neo4j | fcc121f9f0456e21f609f3f8e895255052242ff1 | [
"CNRI-Python",
"Apache-1.1"
] | 1 | 2015-12-14T07:35:29.000Z | 2015-12-14T07:35:29.000Z | community/server/src/test/java/org/neo4j/server/configuration/validation/DatabaseLocationMustBeSpecifiedRuleTest.java | jexp/neo4j | fcc121f9f0456e21f609f3f8e895255052242ff1 | [
"CNRI-Python",
"Apache-1.1"
] | null | null | null | community/server/src/test/java/org/neo4j/server/configuration/validation/DatabaseLocationMustBeSpecifiedRuleTest.java | jexp/neo4j | fcc121f9f0456e21f609f3f8e895255052242ff1 | [
"CNRI-Python",
"Apache-1.1"
] | null | null | null | 38.388889 | 96 | 0.747467 | 11,683 | /**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.configuration.validation;
import org.apache.commons.configuration.BaseConfiguration;
import org.junit.Test;
public class DatabaseLocationMustBeSpecifiedRuleTest
{
@Test( expected = RuleFailedException.class )
public void shouldFailWhenDatabaseLocationIsAbsentFromConfig() throws RuleFailedException
{
DatabaseLocationMustBeSpecifiedRule theRule = new DatabaseLocationMustBeSpecifiedRule();
BaseConfiguration config = new BaseConfiguration();
config.addProperty( "foo", "bar" );
theRule.validate( config );
}
}
|
3e1b8f6127d379d37e7e5724b3ff3b1580800765 | 757 | java | Java | S1/TAA/TP2/src/main/java/TP2/jpa/JpaTest.java | Yberion/M2-IL | 10ed305f3aae2b7142cf409839faac11d6a41b12 | [
"MIT"
] | 2 | 2020-09-09T16:26:17.000Z | 2020-10-27T18:42:49.000Z | S1/TAA/TP2/src/main/java/TP2/jpa/JpaTest.java | Yberion/M2-IL | 10ed305f3aae2b7142cf409839faac11d6a41b12 | [
"MIT"
] | null | null | null | S1/TAA/TP2/src/main/java/TP2/jpa/JpaTest.java | Yberion/M2-IL | 10ed305f3aae2b7142cf409839faac11d6a41b12 | [
"MIT"
] | 1 | 2021-01-27T09:04:12.000Z | 2021-01-27T09:04:12.000Z | 21.628571 | 61 | 0.569353 | 11,684 | package TP2.jpa;
import java.util.List;
import TP2.jpa.kanban.dao.KanbanDAO;
import TP2.jpa.kanban.dao.SectionDAO;
public class JpaTest
{
public static void main(String[] args)
{
KanbanDAO kanbanDAO = new KanbanDAO();
SectionDAO sectionDAO = new SectionDAO();
try
{
List<Long> kanbanIds = kanbanDAO.createKanbans();
for (Long id : kanbanIds)
{
sectionDAO.createDefaultSections(id);
}
}
catch (Exception e)
{
e.printStackTrace();
}
kanbanDAO.displayKanbans();
EntityManagerHelper.closeEntityManager();
EntityManagerHelper.closeEntityManagerFactory();
}
}
|
3e1b8f644ffbe14eb7180fe456981ded7d751a70 | 393 | java | Java | Backend/src/test/java/com/mexbo/Controller/UserControllerTest.java | awfssv/Springboot_muxin | 05820f6f2eb0ce0d8480588243ad42721609cd4f | [
"Apache-2.0"
] | 26 | 2019-01-31T13:14:26.000Z | 2022-03-18T13:38:50.000Z | Backend/src/test/java/com/mexbo/Controller/UserControllerTest.java | awfssv/Springboot_muxin | 05820f6f2eb0ce0d8480588243ad42721609cd4f | [
"Apache-2.0"
] | null | null | null | Backend/src/test/java/com/mexbo/Controller/UserControllerTest.java | awfssv/Springboot_muxin | 05820f6f2eb0ce0d8480588243ad42721609cd4f | [
"Apache-2.0"
] | 21 | 2019-06-15T05:17:14.000Z | 2020-10-19T13:36:47.000Z | 21.833333 | 62 | 0.768448 | 11,685 | package com.mexbo.Controller;
import com.mexbo.controller.UserController;
import com.mexbo.pojo.Users;
import com.mexbo.utils.MD5Utils;
import org.junit.Test;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
public class UserControllerTest {
@Autowired
private Sid sid;
@Test
public void registOrlogin() throws Exception {
}
} |
3e1b90b7180068b828eb3ab65654b64d630f52a1 | 65,311 | java | Java | core/src/main/java/tech/tablesaw/api/Table.java | jbsooter/tablesaw | 8c03426f73cfa432ac563d5a6cb69bebdfea056a | [
"Apache-2.0"
] | null | null | null | core/src/main/java/tech/tablesaw/api/Table.java | jbsooter/tablesaw | 8c03426f73cfa432ac563d5a6cb69bebdfea056a | [
"Apache-2.0"
] | null | null | null | core/src/main/java/tech/tablesaw/api/Table.java | jbsooter/tablesaw | 8c03426f73cfa432ac563d5a6cb69bebdfea056a | [
"Apache-2.0"
] | null | null | null | 35.43733 | 134 | 0.670454 | 11,686 | /*
* 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 tech.tablesaw.api;
import static java.util.stream.Collectors.toList;
import static tech.tablesaw.aggregate.AggregateFunctions.count;
import static tech.tablesaw.aggregate.AggregateFunctions.countMissing;
import static tech.tablesaw.api.QuerySupport.not;
import static tech.tablesaw.selection.Selection.selectNRowsAtRandom;
import com.google.common.base.Preconditions;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import it.unimi.dsi.fastutil.ints.*;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.roaringbitmap.RoaringBitmap;
import tech.tablesaw.aggregate.AggregateFunction;
import tech.tablesaw.aggregate.CrossTab;
import tech.tablesaw.aggregate.PivotTable;
import tech.tablesaw.aggregate.Summarizer;
import tech.tablesaw.columns.Column;
import tech.tablesaw.io.DataFrameReader;
import tech.tablesaw.io.DataFrameWriter;
import tech.tablesaw.io.DataReader;
import tech.tablesaw.io.DataWriter;
import tech.tablesaw.io.ReaderRegistry;
import tech.tablesaw.io.WriterRegistry;
import tech.tablesaw.joining.DataFrameJoiner;
import tech.tablesaw.selection.BitmapBackedSelection;
import tech.tablesaw.selection.Selection;
import tech.tablesaw.sorting.Sort;
import tech.tablesaw.sorting.SortUtils;
import tech.tablesaw.sorting.comparators.IntComparatorChain;
import tech.tablesaw.table.*;
/**
* A table of data, consisting of some number of columns, each of which has the same number of rows.
* All the data in a column has the same type: integer, float, category, etc., but a table may
* contain an arbitrary number of columns of any type.
*
* <p>Tables are the main data-type and primary focus of Tablesaw.
*/
public class Table extends Relation implements Iterable<Row> {
public static final ReaderRegistry defaultReaderRegistry = new ReaderRegistry();
public static final WriterRegistry defaultWriterRegistry = new WriterRegistry();
static {
autoRegisterReadersAndWriters();
}
/** The columns that hold the data in this table */
private final List<Column<?>> columnList = new ArrayList<>();
/** The name of the table */
private String name;
// standard column names for melt and cast operations
public static final String MELT_VARIABLE_COLUMN_NAME = "variable";
public static final String MELT_VALUE_COLUMN_NAME = "value";
/** Returns a new table */
private Table() {}
/** Returns a new table initialized with the given name */
private Table(String name) {
this.name = name;
}
/**
* Returns a new Table initialized with the given names and columns
*
* @param name The name of the table
* @param columns One or more columns, all of which must have either the same length or size 0
*/
protected Table(String name, Column<?>... columns) {
this(name);
for (final Column<?> column : columns) {
this.addColumns(column);
}
}
/**
* Returns a new Table initialized with the given names and columns
*
* @param name The name of the table
* @param columns One or more columns, all of which must have either the same length or size 0
*/
protected Table(String name, Collection<Column<?>> columns) {
this(name);
for (final Column<?> column : columns) {
this.addColumns(column);
}
}
/** TODO: Add documentation */
private static void autoRegisterReadersAndWriters() {
try (ScanResult scanResult =
new ClassGraph().enableAllInfo().whitelistPackages("tech.tablesaw.io").scan()) {
List<String> classes = new ArrayList<>();
classes.addAll(scanResult.getClassesImplementing(DataWriter.class.getName()).getNames());
classes.addAll(scanResult.getClassesImplementing(DataReader.class.getName()).getNames());
for (String clazz : classes) {
try {
Class.forName(clazz);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
}
/** Returns a new, empty table (without rows or columns) */
public static Table create() {
return new Table();
}
/** Returns a new, empty table (without rows or columns) with the given name */
public static Table create(String tableName) {
return new Table(tableName);
}
/**
* Returns a new table with the given columns
*
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(Column<?>... columns) {
return new Table(null, columns);
}
/**
* Returns a new table with the given columns
*
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(Collection<Column<?>> columns) {
return new Table(null, columns);
}
/**
* Returns a new table with the given columns
*
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(Stream<Column<?>> columns) {
return new Table(null, columns.collect(Collectors.toList()));
}
/**
* Returns a new table with the given columns and given name
*
* @param name the name for this table
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(String name, Column<?>... columns) {
return new Table(name, columns);
}
/**
* Returns a new table with the given columns and given name
*
* @param name the name for this table
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(String name, Collection<Column<?>> columns) {
return new Table(name, columns);
}
/**
* Returns a new table with the given columns and given name
*
* @param name the name for this table
* @param columns one or more columns, all of the same @code{column.size()}
*/
public static Table create(String name, Stream<Column<?>> columns) {
return new Table(name, columns.collect(Collectors.toList()));
}
/**
* Returns a sort Key that can be used for simple or chained comparator sorting
*
* <p>You can extend the sort key by using .next() to fill more columns to the sort order
*/
private static Sort first(String columnName, Sort.Order order) {
return Sort.on(columnName, order);
}
/**
* Returns an object that can be used to sort this table in the order specified for by the given
* column names
*/
private static Sort getSort(String... columnNames) {
Sort key = null;
for (String s : columnNames) {
if (key == null) {
key = first(s, Sort.Order.DESCEND);
} else {
key.next(s, Sort.Order.DESCEND);
}
}
return key;
}
/** Returns an object that can be used to read data from a file into a new Table */
public static DataFrameReader read() {
return new DataFrameReader(defaultReaderRegistry);
}
/**
* Returns an object that an be used to write data from a Table into a file. If the file exists,
* it is over-written
*/
public DataFrameWriter write() {
return new DataFrameWriter(defaultWriterRegistry, this);
}
/**
* Adds the given column to this table. Column must either be empty or have size() == the
* rowCount() of the table they're being added to. Column names in the table must remain unique.
*/
@Override
public Table addColumns(final Column<?>... cols) {
for (final Column<?> c : cols) {
validateColumn(c);
columnList.add(c);
}
return this;
}
/**
* For internal Tablesaw use only
*
* <p>Adds the given column to this table without performing duplicate-name or column size checks
*/
public void internalAddWithoutValidation(final Column<?> c) {
columnList.add(c);
}
/**
* Throws an IllegalArgumentException if a column with the given name is already in the table, or
* if the number of rows in the column does not match the number of rows in the table. Regarding
* the latter rule, however, if the column is completely empty (size == 0), then it is filled with
* missing values to match the rowSize() as a convenience.
*/
private void validateColumn(final Column<?> newColumn) {
Preconditions.checkNotNull(
newColumn, "Attempted to add a null to the columns in table " + name);
List<String> stringList = new ArrayList<>();
for (String name : columnNames()) {
stringList.add(name.toLowerCase());
}
if (stringList.contains(newColumn.name().toLowerCase())) {
String message =
String.format(
"Cannot add column with duplicate name %s to table %s", newColumn.name(), name);
throw new IllegalArgumentException(message);
}
checkColumnSize(newColumn);
}
/**
* Throws an IllegalArgumentException if the column size doesn't match the rowCount() for the
* table. Columns that are completely empty, however, are initialized to match rowcount by filling
* with missing values
*/
private void checkColumnSize(Column<?> newColumn) {
if (columnCount() != 0) {
if (!isEmpty()) {
if (newColumn.isEmpty()) {
while (newColumn.size() < rowCount()) {
newColumn.appendMissing();
}
}
}
Preconditions.checkArgument(
newColumn.size() == rowCount(),
"Column "
+ newColumn.name()
+ " does not have the same number of rows as the other columns in the table.");
}
}
/**
* Adds the given column to this table at the given position in the column list. Columns must
* either be empty or have size() == the rowCount() of the table they're being added to. Column
* names in the table must remain unique.
*
* @param index Zero-based index into the column list
* @param column Column to be added
*/
public Table insertColumn(int index, Column<?> column) {
validateColumn(column);
columnList.add(index, column);
return this;
}
/**
* Return a new table (shallow copy) that contains all the columns in this table, in the order
* given in the argument. Throw an IllegalArgument exception if the number of names given does not
* match the number of columns in this table. NOTE: This does not make a copy of the columns, so
* they are shared between the two tables.
*
* @param columnNames a column name or array of names
*/
public Table reorderColumns(String... columnNames) {
Preconditions.checkArgument(columnNames.length == columnCount());
Table table = Table.create(name);
for (String name : columnNames) {
table.addColumns(column(name));
}
return table;
}
/**
* Replaces an existing column (by index) in this table with the given new column
*
* @param colIndex Zero-based index of the column to be replaced
* @param newColumn Column to be added
*/
public Table replaceColumn(final int colIndex, final Column<?> newColumn) {
removeColumns(column(colIndex));
return insertColumn(colIndex, newColumn);
}
/**
* Replaces an existing column (by name) in this table with the given new column
*
* @param columnName String name of the column to be replaced
* @param newColumn Column to be added
*/
public Table replaceColumn(final String columnName, final Column<?> newColumn) {
int colIndex = columnIndex(columnName);
return replaceColumn(colIndex, newColumn);
}
/**
* Replaces an existing column having the same name of the given column with the given column
*
* @param newColumn Column to be added
*/
public Table replaceColumn(Column<?> newColumn) {
return replaceColumn(newColumn.name(), newColumn);
}
/** Sets the name of the table */
@Override
public Table setName(String name) {
this.name = name;
return this;
}
/**
* Returns the column at the given index in the column list
*
* @param columnIndex an integer at least 0 and less than number of columns in the table
*/
@Override
public Column<?> column(int columnIndex) {
return columnList.get(columnIndex);
}
/** Returns the number of columns in the table */
@Override
public int columnCount() {
return columnList.size();
}
/** Returns the number of rows in the table */
@Override
public int rowCount() {
int result = 0;
if (!columnList.isEmpty()) {
// all the columns have the same number of elements, so we can check any of them
result = columnList.get(0).size();
}
return result;
}
/** Returns the list of columns */
@Override
public List<Column<?>> columns() {
return columnList;
}
/** Returns the columns in this table as an array */
public Column<?>[] columnArray() {
return columnList.toArray(new Column<?>[columnCount()]);
}
/** Returns only the columns whose names are given in the input array */
@Override
public List<CategoricalColumn<?>> categoricalColumns(String... columnNames) {
List<CategoricalColumn<?>> columns = new ArrayList<>();
for (String columnName : columnNames) {
columns.add(categoricalColumn(columnName));
}
return columns;
}
/**
* Returns the index of the column with the given name
*
* @throws IllegalArgumentException if the input string is not the name of any column in the table
*/
@Override
public int columnIndex(String columnName) {
int columnIndex = -1;
for (int i = 0; i < columnList.size(); i++) {
if (columnList.get(i).name().equalsIgnoreCase(columnName)) {
columnIndex = i;
break;
}
}
if (columnIndex == -1) {
throw new IllegalArgumentException(
String.format("Column %s is not present in table %s", columnName, name));
}
return columnIndex;
}
/**
* Returns the index of the given column (its position in the list of columns)
*
* @throws IllegalArgumentException if the column is not present in this table
*/
public int columnIndex(Column<?> column) {
int columnIndex = -1;
for (int i = 0; i < columnList.size(); i++) {
if (columnList.get(i).equals(column)) {
columnIndex = i;
break;
}
}
if (columnIndex == -1) {
throw new IllegalArgumentException(
String.format("Column %s is not present in table %s", column.name(), name));
}
return columnIndex;
}
/** Returns the name of the table */
@Override
public String name() {
return name;
}
/** Returns a List of the names of all the columns in this table */
public List<String> columnNames() {
return columnList.stream().map(Column::name).collect(toList());
}
/** Returns a table with the same columns and data as this table */
public Table copy() {
return inRange(0, this.rowCount());
}
/** Returns a table with the same columns as this table, but no data */
public Table emptyCopy() {
Table copy = new Table(name);
for (Column<?> column : columnList) {
copy.addColumns(column.emptyCopy());
}
return copy;
}
/**
* Returns a table with the same columns as this table, but no data, initialized to the given row
* size
*/
public Table emptyCopy(int rowSize) {
Table copy = new Table(name);
for (Column<?> column : columnList) {
copy.addColumns(column.emptyCopy(rowSize));
}
return copy;
}
/**
* Copies the rows specified by Selection into newTable
*
* @param rows A Selection defining the rows to copy
* @param newTable The table to copy the rows into
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public void copyRowsToTable(Selection rows, Table newTable) {
for (int columnIndex = 0; columnIndex < this.columnCount(); columnIndex++) {
Column oldColumn = this.column(columnIndex);
int r = 0;
for (int i : rows) {
newTable.column(columnIndex).set(r, oldColumn, i);
r++;
}
}
}
/**
* Copies the rows indicated by the row index values in the given array from oldTable to newTable
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public void copyRowsToTable(int[] rows, Table newTable) {
for (int columnIndex = 0; columnIndex < columnCount(); columnIndex++) {
Column oldColumn = column(columnIndex);
int r = 0;
for (int i : rows) {
newTable.column(columnIndex).set(r, oldColumn, i);
r++;
}
}
}
/**
* Returns {@code true} if the row @rowNumber in table1 holds the same data as the row at
* rowNumber in table2
*/
public static boolean compareRows(int rowNumber, Table table1, Table table2) {
int columnCount = table1.columnCount();
boolean result;
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
ColumnType columnType = table1.column(columnIndex).type();
result =
columnType.compare(rowNumber, table2.column(columnIndex), table1.column(columnIndex));
if (!result) {
return false;
}
}
return true;
}
/**
* Returns true if every value in row1 is equal to the same value in row2, where row1 and row2 are
* both rows from this table
*/
private boolean duplicateRows(Row row1, Row row2) {
if (row1.columnCount() != row2.columnCount()) {
return false;
}
boolean result;
for (int columnIndex = 0; columnIndex < row1.columnCount(); columnIndex++) {
Column<?> c = column(columnIndex);
result = c.equals(row1.getRowNumber(), row2.getRowNumber());
if (!result) {
return false;
}
}
return true;
}
public Table[] sampleSplit(double table1Proportion) {
Table[] tables = new Table[2];
int table1Count = (int) Math.round(rowCount() * table1Proportion);
Selection table2Selection = new BitmapBackedSelection();
for (int i = 0; i < rowCount(); i++) {
table2Selection.add(i);
}
Selection table1Selection = new BitmapBackedSelection();
Selection table1Records = selectNRowsAtRandom(table1Count, rowCount());
for (int table1Record : table1Records) {
table1Selection.add(table1Record);
}
table2Selection.andNot(table1Selection);
tables[0] = where(table1Selection);
tables[1] = where(table2Selection);
return tables;
}
/**
* Splits the table into two stratified samples, this uses the specified column to divide the
* table into groups, randomly assigning records to each according to the proportion given in
* trainingProportion.
*
* @param column the column to be used for the stratified sampling
* @param table1Proportion The proportion to go in the first table
* @return An array two tables, with the first table having the proportion specified in the method
* parameter, and the second table having the balance of the rows
*/
public Table[] stratifiedSampleSplit(CategoricalColumn<?> column, double table1Proportion) {
Preconditions.checkArgument(
containsColumn(column),
"The categorical column must be part of the table, you can create a string column and add it to this table before sampling.");
final Table first = emptyCopy();
final Table second = emptyCopy();
splitOn(column)
.asTableList()
.forEach(
tab -> {
Table[] splits = tab.sampleSplit(table1Proportion);
first.append(splits[0]);
second.append(splits[1]);
});
return new Table[] {first, second};
}
/**
* Returns a table consisting of randomly selected records from this table. The sample size is
* based on the given proportion
*
* @param proportion The proportion to go in the sample
*/
public Table sampleX(double proportion) {
Preconditions.checkArgument(
proportion <= 1 && proportion >= 0, "The sample proportion must be between 0 and 1");
int tableSize = (int) Math.round(rowCount() * proportion);
return where(selectNRowsAtRandom(tableSize, rowCount()));
}
/**
* Returns a table consisting of randomly selected records from this table
*
* @param nRows The number of rows to go in the sample
*/
public Table sampleN(int nRows) {
Preconditions.checkArgument(
nRows > 0 && nRows < rowCount(),
"The number of rows sampled must be greater than 0 and less than the number of rows in the table.");
return where(selectNRowsAtRandom(nRows, rowCount()));
}
/** Clears all the data from this table */
@Override
public void clear() {
columnList.forEach(Column::clear);
}
/** Returns a new table containing the first {@code nrows} of data in this table */
public Table first(int nRows) {
int newRowCount = Math.min(nRows, rowCount());
return inRange(0, newRowCount);
}
/** Returns a new table containing the last {@code nrows} of data in this table */
public Table last(int nRows) {
int newRowCount = Math.min(nRows, rowCount());
return inRange(rowCount() - newRowCount, rowCount());
}
/**
* Sorts this table into a new table on the columns indexed
*
* <p>if index is negative then sort that column in descending order otherwise sort ascending
*/
public Table sortOn(int... columnIndexes) {
List<String> names = new ArrayList<>();
for (int i : columnIndexes) {
if (i >= 0) {
names.add(columnList.get(i).name());
} else {
names.add("-" + columnList.get(-i).name());
}
}
return sortOn(names.toArray(new String[names.size()]));
}
/**
* Returns a copy of this table sorted on the given column names, applied in order,
*
* <p>if column name starts with - then sort that column descending otherwise sort ascending
*/
public Table sortOn(String... columnNames) {
return this.sortOn(Sort.create(this, columnNames));
}
/**
* Returns a copy of this table sorted in the order of the given column names, in ascending order
*/
public Table sortAscendingOn(String... columnNames) {
return this.sortOn(columnNames);
}
/**
* Returns a copy of this table sorted on the given column names, applied in order, descending
* TODO: Provide equivalent methods naming columns by index
*/
public Table sortDescendingOn(String... columnNames) {
Sort key = getSort(columnNames);
return sortOn(key);
}
/**
* Returns a copy of this table sorted using the given sort key.
*
* @param key to sort on.
* @return a sorted copy of this table.
*/
public Table sortOn(Sort key) {
Preconditions.checkArgument(!key.isEmpty());
if (key.size() == 1) {
IntComparator comparator = SortUtils.getComparator(this, key);
return parallelSortOn(comparator);
}
IntComparatorChain chain = SortUtils.getChain(this, key);
return parallelSortOn(chain);
}
/**
* Returns a copy of this table sorted using the given comparator. This method sorts in a single
* thread, as is required for using Comparator<Row>
*/
private Table sortOn(IntComparator rowComparator) {
Table newTable = emptyCopy(rowCount());
int[] newRows = rows();
IntArrays.mergeSort(newRows, rowComparator);
copyRowsToTable(newRows, newTable);
return newTable;
}
/** Returns a copy of this table sorted in parallel using the given comparator */
private Table parallelSortOn(IntComparator rowComparator) {
Table newTable = emptyCopy(rowCount());
int[] newRows = rows();
IntArrays.parallelQuickSort(newRows, rowComparator);
copyRowsToTable(newRows, newTable);
return newTable;
}
/** Returns a copy of this table sorted using the given comparator */
public Table sortOn(Comparator<Row> rowComparator) {
Row row1 = new Row(this);
Row row2 = new Row(this);
return sortOn( // Note: Never user parallel sort here as Row isn't remotely thread-safe
(IntComparator)
(k1, k2) -> {
row1.at(k1);
row2.at(k2);
return rowComparator.compare(row1, row2);
});
}
/** Returns an array of ints of the same number of rows as the table */
private int[] rows() {
int[] rowIndexes = new int[rowCount()];
for (int i = 0; i < rowCount(); i++) {
rowIndexes[i] = i;
}
return rowIndexes;
}
/**
* Adds a single row to this table from sourceTable, copying every column in sourceTable
*
* @param rowIndex The row in sourceTable to add to this table
* @param sourceTable A table with the same column structure as this table
*/
public void addRow(int rowIndex, Table sourceTable) {
for (int i = 0; i < columnCount(); i++) {
column(i).appendObj(sourceTable.column(i).get(rowIndex));
}
}
/** Returns a new Row object with its position set to the given zero-based row index. */
public Row row(int rowIndex) {
Row row = new Row(Table.this);
row.at(rowIndex);
return row;
}
/** Returns a table containing the rows contained in the given array of row indices */
public Table rows(int... rowNumbers) {
Preconditions.checkArgument(Ints.max(rowNumbers) <= rowCount());
return where(Selection.with(rowNumbers));
}
/** Returns a table EXCLUDING the rows contained in the given array of row indices */
public Table dropRows(int... rowNumbers) {
Preconditions.checkArgument(Ints.max(rowNumbers) <= rowCount());
Selection selection = Selection.withRange(0, rowCount()).andNot(Selection.with(rowNumbers));
return where(selection);
}
/**
* Returns a new table containing the first rowCount rows if rowCount positive. Returns the last
* rowCount rows if rowCount negative.
*/
public Table inRange(int rowCount) {
Preconditions.checkArgument(rowCount <= rowCount());
int rowStart = rowCount >= 0 ? 0 : rowCount() + rowCount;
int rowEnd = rowCount >= 0 ? rowCount : rowCount();
return where(Selection.withRange(rowStart, rowEnd));
}
/**
* Returns a new table containing the rows contained in the range from rowStart inclusive to
* rowEnd exclusive
*/
public Table inRange(int rowStart, int rowEnd) {
Preconditions.checkArgument(rowEnd <= rowCount());
return where(Selection.withRange(rowStart, rowEnd));
}
/**
* Returns a new table EXCLUDING the first rowCount rows if rowCount positive. Drops the last
* rowCount rows if rowCount negative.
*/
public Table dropRange(int rowCount) {
Preconditions.checkArgument(rowCount <= rowCount());
int rowStart = rowCount >= 0 ? rowCount : 0;
int rowEnd = rowCount >= 0 ? rowCount() : rowCount() + rowCount;
return where(Selection.withRange(rowStart, rowEnd));
}
/**
* Returns a table EXCLUDING the rows contained in the range from rowStart inclusive to rowEnd
* exclusive
*/
public Table dropRange(int rowStart, int rowEnd) {
Preconditions.checkArgument(rowEnd <= rowCount());
return where(Selection.withoutRange(0, rowCount(), rowStart, rowEnd));
}
/** Returns a table containing the rows contained in the given Selection */
public Table where(Selection selection) {
Table newTable = this.emptyCopy(selection.size());
copyRowsToTable(selection, newTable);
return newTable;
}
/** Returns a new Table made by applying the given function to this table */
public Table where(Function<Table, Selection> selection) {
return where(selection.apply(this));
}
/**
* Returns a new Table made by EXCLUDING any rows returned when the given function is applied to
* this table
*/
public Table dropWhere(Function<Table, Selection> selection) {
return where(not(selection));
}
/** Returns a table EXCLUDING the rows contained in the given Selection */
public Table dropWhere(Selection selection) {
Selection opposite = new BitmapBackedSelection();
opposite.addRange(0, rowCount());
opposite.andNot(selection);
Table newTable = this.emptyCopy(opposite.size());
copyRowsToTable(opposite, newTable);
return newTable;
}
/**
* Returns a pivot on this table, where: The first column contains unique values from the index
* column1 There are n additional columns, one for each unique value in column2 The values in each
* of the cells in these new columns are the result of applying the given AggregateFunction to the
* data in column3, grouped by the values of column1 and column2
*/
public Table pivot(
CategoricalColumn<?> column1,
CategoricalColumn<?> column2,
NumericColumn<?> column3,
AggregateFunction<?, ?> aggregateFunction) {
return PivotTable.pivot(this, column1, column2, column3, aggregateFunction);
}
/**
* Returns a pivot on this table, where: The first column contains unique values from the index
* column1 There are n additional columns, one for each unique value in column2 The values in each
* of the cells in these new columns are the result of applying the given AggregateFunction to the
* data in column3, grouped by the values of column1 and column2
*/
public Table pivot(
String column1Name,
String column2Name,
String column3Name,
AggregateFunction<?, ?> aggregateFunction) {
return pivot(
categoricalColumn(column1Name),
categoricalColumn(column2Name),
numberColumn(column3Name),
aggregateFunction);
}
/**
* Returns a non-overlapping and exhaustive collection of "slices" over this table. Each slice is
* like a virtual table containing a subset of the records in this table
*
* <p>This method is intended for advanced or unusual operations on the subtables. If you want to
* calculate summary statistics for each subtable, the summarize methods (e.g)
*
* <p>table.summarize(myColumn, mean, median).by(columns)
*
* <p>are preferred
*/
public TableSliceGroup splitOn(String... columns) {
return splitOn(categoricalColumns(columns).toArray(new CategoricalColumn<?>[columns.length]));
}
/**
* Returns a non-overlapping and exhaustive collection of "slices" over this table. Each slice is
* like a virtual table containing a subset of the records in this table
*
* <p>This method is intended for advanced or unusual operations on the subtables. If you want to
* calculate summary statistics for each subtable, the summarize methods (e.g)
*
* <p>table.summarize(myColumn, mean, median).by(columns)
*
* <p>are preferred
*/
public TableSliceGroup splitOn(CategoricalColumn<?>... columns) {
return StandardTableSliceGroup.create(this, columns);
}
/**
* Returns the unique records in this table, such that any record that appears more than once in
* this table, appears only once in the returned table.
*/
public Table dropDuplicateRows() {
Table temp = emptyCopy();
Int2ObjectMap<IntArrayList> uniqueHashes = new Int2ObjectOpenHashMap<>();
// ListMultimap<Integer, Integer> uniqueHashes = ArrayListMultimap.create();
for (Row row : this) {
if (!isDuplicate(row, uniqueHashes)) {
temp.append(row);
}
}
return temp;
}
/**
* Returns true if all the values in row are identical to those in another row previously seen and
* recorded in the list.
*
* @param row the row to evaluate
* @param uniqueHashes a map of row hashes to the id of an exemplar row that produces that hash.
* If two different rows produce the same hash, then the row number for each is placed in the
* list, so that there are exemplars for both
* @return true if the row's values exactly match a row that was previously seen
*/
private boolean isDuplicate(Row row, Int2ObjectMap<IntArrayList> uniqueHashes) {
int hash = row.rowHash();
if (!uniqueHashes.containsKey(hash)) {
IntArrayList rowNumbers = new IntArrayList();
rowNumbers.add(row.getRowNumber());
uniqueHashes.put(hash, rowNumbers);
return false;
}
// the hashmap contains the hash, make sure the actual row values match
IntArrayList matchingKeys = uniqueHashes.get(hash);
for (int key : matchingKeys) {
Row oldRow = this.row(key);
if (duplicateRows(row, oldRow)) {
return true;
} else {
uniqueHashes.get(hash).add(row.getRowNumber());
return false;
}
}
return true;
}
/** Returns only those records in this table that have no columns with missing values */
public Table dropRowsWithMissingValues() {
Selection missing = new BitmapBackedSelection();
for (int row = 0; row < rowCount(); row++) {
for (int col = 0; col < columnCount(); col++) {
Column<?> c = column(col);
if (c.isMissing(row)) {
missing.add(row);
break;
}
}
}
Selection notMissing = Selection.withRange(0, rowCount());
notMissing.andNot(missing);
Table temp = emptyCopy(notMissing.size());
copyRowsToTable(notMissing, temp);
return temp;
}
/**
* Returns a new table containing copies of the selected columns from this table
*
* @param columns The columns to copy into the new table
* @see #retainColumns(Column[])
*/
public Table selectColumns(Column<?>... columns) {
Table t = Table.create(this.name);
for (Column<?> c : columns) {
t.addColumns(c.copy());
}
return t;
}
/**
* Returns a new table containing copies of the selected columns from this table
*
* @param columnNames The names of the columns to include
* @see #retainColumns(String[])
*/
public Table selectColumns(String... columnNames) {
Table t = Table.create(this.name);
for (String s : columnNames) {
t.addColumns(column(s).copy());
}
return t;
}
/**
* Returns a new table containing copies of all the columns from this table, except those at the
* given indexes
*
* @param columnIndexes The indexes of the columns to exclude
* @see #removeColumns(int[])
*/
public Table rejectColumns(int... columnIndexes) {
Table t = Table.create(this.name);
RoaringBitmap bm = new RoaringBitmap();
bm.add((long) 0, columnCount());
RoaringBitmap excluded = new RoaringBitmap();
excluded.add(columnIndexes);
bm.andNot(excluded);
for (int i : bm) {
t.addColumns(column(i).copy());
}
return t;
}
/**
* Returns a new table containing copies of all the columns from this table, except those named in
* the argument
*
* @param columnNames The names of the columns to exclude
* @see #removeColumns(int[])
*/
public Table rejectColumns(String... columnNames) {
IntArrayList indices = new IntArrayList();
for (String s : columnNames) {
indices.add(columnIndex(s));
}
return rejectColumns(indices.toIntArray());
}
/**
* Returns a new table containing copies of all the columns from this table, except those named in
* the argument
*
* @param columns The names of the columns to exclude
* @see #removeColumns(int[])
*/
public Table rejectColumns(Column<?>... columns) {
IntArrayList indices = new IntArrayList();
for (Column<?> c : columns) {
indices.add(columnIndex(c));
}
return rejectColumns(indices.toIntArray());
}
/**
* Returns a new table containing copies of the columns at the given indexes
*
* @param columnIndexes The indexes of the columns to include
* @see #retainColumns(int[])
*/
public Table selectColumns(int... columnIndexes) {
Table t = Table.create(this.name);
RoaringBitmap bm = new RoaringBitmap();
bm.add(columnIndexes);
for (int i : bm) {
t.addColumns(column(i).copy());
}
return t;
}
/** Removes the given columns from this table and returns this table */
@Override
public Table removeColumns(Column<?>... columns) {
columnList.removeAll(Arrays.asList(columns));
return this;
}
/** Removes all columns with missing values from this table, and returns this table. */
public Table removeColumnsWithMissingValues() {
removeColumns(columnList.stream().filter(x -> x.countMissing() > 0).toArray(Column<?>[]::new));
return this;
}
/**
* Removes all columns except for those given in the argument from this table and returns this
* table
*/
public Table retainColumns(Column<?>... columns) {
List<Column<?>> retained = Arrays.asList(columns);
columnList.clear();
columnList.addAll(retained);
return this;
}
/**
* Removes all columns except for those given in the argument from this table and returns this
* table
*/
public Table retainColumns(int... columnIndexes) {
List<Column<?>> retained = columns(columnIndexes);
columnList.clear();
columnList.addAll(retained);
return this;
}
/**
* Removes all columns except for those given in the argument from this table and returns this
* table
*/
public Table retainColumns(String... columnNames) {
List<Column<?>> retained = columns(columnNames);
columnList.clear();
columnList.addAll(retained);
return this;
}
/** Returns this table after adding the data from the argument */
@SuppressWarnings({"rawtypes", "unchecked"})
public Table append(Relation tableToAppend) {
for (final Column column : columnList) {
final Column columnToAppend = tableToAppend.column(column.name());
column.append(columnToAppend);
}
return this;
}
/**
* Appends the given row to this table and returns the table.
*
* <p>Note: The table is modified in-place TODO: Performance
*/
public Table append(Row row) {
for (int i = 0; i < row.columnCount(); i++) {
column(i).appendObj(row.getObject(i));
}
return this;
}
/** Removes the columns with the given names from this table and returns this table */
@Override
public Table removeColumns(String... columns) {
return (Table) super.removeColumns(columns);
}
/** Removes the columns at the given indices from this table and returns this table */
@Override
public Table removeColumns(int... columnIndexes) {
return (Table) super.removeColumns(columnIndexes);
}
/**
* Appends an empty row and returns a Row object indexed to the newly added row so values can be
* set.
*
* <p>Intended usage:
*
* <p>for (int i = 0; ...) { Row row = table.appendRow(); row.setString("name", "Bob");
* row.setFloat("IQ", 123.4f); ...etc. }
*/
public Row appendRow() {
for (final Column<?> column : columnList) {
column.appendMissing();
}
return row(rowCount() - 1);
}
/**
* Add all the columns of tableToConcatenate to this table Note: The columns in the result must
* have unique names, when compared case insensitive Note: Both tables must have the same number
* of rows
*
* @param tableToConcatenate The table containing the columns to be added
* @return This table
*/
public Table concat(Table tableToConcatenate) {
Preconditions.checkArgument(
tableToConcatenate.rowCount() == this.rowCount(),
"Both tables must have the same number of rows to concatenate them.");
for (Column<?> column : tableToConcatenate.columns()) {
this.addColumns(column);
}
return this;
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(String columName, AggregateFunction<?, ?>... functions) {
return summarize(column(columName), functions);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(List<String> columnNames, AggregateFunction<?, ?>... functions) {
return new Summarizer(this, columnNames, functions);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
String numericColumn1Name, String numericColumn2Name, AggregateFunction<?, ?>... functions) {
return summarize(column(numericColumn1Name), column(numericColumn2Name), functions);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
String col1Name, String col2Name, String col3Name, AggregateFunction<?, ?>... functions) {
return summarize(column(col1Name), column(col2Name), column(col3Name), functions);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
String col1Name,
String col2Name,
String col3Name,
String col4Name,
AggregateFunction<?, ?>... functions) {
return summarize(
column(col1Name), column(col2Name), column(col3Name), column(col4Name), functions);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(Column<?> numberColumn, AggregateFunction<?, ?>... function) {
return new Summarizer(this, numberColumn, function);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
Column<?> column1, Column<?> column2, AggregateFunction<?, ?>... function) {
return new Summarizer(this, column1, column2, function);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
Column<?> column1,
Column<?> column2,
Column<?> column3,
AggregateFunction<?, ?>... function) {
return new Summarizer(this, column1, column2, column3, function);
}
/**
* Returns a {@link Summarizer} that can be used to summarize the column with the given name(s)
* using the given functions. This object implements reduce/aggregation operations on a table.
*
* <p>Summarizer can return the results as a table using the Summarizer:apply() method. Summarizer
* can compute sub-totals using the Summarizer:by() method.
*/
public Summarizer summarize(
Column<?> column1,
Column<?> column2,
Column<?> column3,
Column<?> column4,
AggregateFunction<?, ?>... function) {
return new Summarizer(this, column1, column2, column3, column4, function);
}
/**
* Returns a table with n by m + 1 cells. The first column contains labels, the other cells
* contains the counts for every unique combination of values from the two specified columns in
* this table.
*/
public Table xTabCounts(String column1Name, String column2Name) {
return CrossTab.counts(this, categoricalColumn(column1Name), categoricalColumn(column2Name));
}
/**
* Returns a table with n by m + 1 cells. The first column contains labels, the other cells
* contains the row percents for every unique combination of values from the two specified columns
* in this table. Row percents total to 100% in every row.
*/
public Table xTabRowPercents(String column1Name, String column2Name) {
return CrossTab.rowPercents(this, column1Name, column2Name);
}
/**
* Returns a table with n by m + 1 cells. The first column contains labels, the other cells
* contains the column percents for every unique combination of values from the two specified
* columns in this table. Column percents total to 100% in every column.
*/
public Table xTabColumnPercents(String column1Name, String column2Name) {
return CrossTab.columnPercents(this, column1Name, column2Name);
}
/**
* Returns a table with n by m + 1 cells. The first column contains labels, the other cells
* contains the proportion for a unique combination of values from the two specified columns in
* this table
*/
public Table xTabTablePercents(String column1Name, String column2Name) {
return CrossTab.tablePercents(this, column1Name, column2Name);
}
/**
* TODO: Rename the method to xTabProportions, deprecating this version Returns a table with two
* columns, the first contains a value each unique value in the argument, and the second contains
* the proportion of observations having that value
*/
public Table xTabPercents(String column1Name) {
return CrossTab.percents(this, column1Name);
}
/**
* Returns a table with two columns, the first contains a value each unique value in the argument,
* and the second contains the number of observations of each value
*/
public Table xTabCounts(String column1Name) {
return CrossTab.counts(this, column1Name);
}
/**
* Returns a table containing two columns, the grouping column, and a column named "Count" that
* contains the counts for each grouping column value
*/
public Table countBy(CategoricalColumn<?>... groupingColumns) {
String[] names = new String[groupingColumns.length];
for (int i = 0; i < groupingColumns.length; i++) {
names[i] = groupingColumns[i].name();
}
return countBy(names);
}
/**
* Returns a table containing a column for each grouping column, and a column named "Count" that
* contains the counts for each combination of grouping column values
*
* @param categoricalColumnNames The name(s) of one or more CategoricalColumns in this table
* @return A table containing counts of rows grouped by the categorical columns
* @throws ClassCastException if the categoricalColumnName parameter is the name of a column that
* does not * implement categorical
*/
public Table countBy(String... categoricalColumnNames) {
Table t = summarize(column(0).name(), count).by(categoricalColumnNames);
t.column(t.columnCount() - 1).setName("Count");
t.replaceColumn("Count", (t.doubleColumn("Count").asIntColumn()));
return t;
}
/**
* Returns a new DataFrameJoiner initialized with multiple {@code columnNames}
*
* @param columnNames Name of the columns to join on.
* @return The new DataFrameJoiner
*/
public DataFrameJoiner joinOn(String... columnNames) {
return new DataFrameJoiner(this, columnNames);
}
/** Returns a table containing the number of missing values in each column in this table */
public Table missingValueCounts() {
return summarize(columnNames(), countMissing).apply();
}
@Override
public Iterator<Row> iterator() {
return new Iterator<Row>() {
private final Row row = new Row(Table.this);
@Override
public Row next() {
return row.next();
}
@Override
public boolean hasNext() {
return row.hasNext();
}
};
}
/**
* Iterates over rolling sets of rows. I.e. 0 to n-1, 1 to n, 2 to n+1, etc.
*
* @param n the number of rows to return for each iteration
*/
public Iterator<Row[]> rollingIterator(int n) {
return new Iterator<Row[]>() {
private int currRow = 0;
@Override
public Row[] next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Row[] rows = new Row[n];
for (int i = 0; i < n; i++) {
rows[i] = new Row(Table.this, currRow + i);
}
currRow++;
return rows;
}
@Override
public boolean hasNext() {
return currRow + n <= rowCount();
}
};
}
/**
* Streams over stepped sets of rows. I.e. 0 to n-1, n to 2n-1, 2n to 3n-1, etc. Only returns full
* sets of rows.
*
* @param n the number of rows to return for each iteration
*/
public Iterator<Row[]> steppingIterator(int n) {
return new Iterator<Row[]>() {
private int currRow = 0;
@Override
public Row[] next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Row[] rows = new Row[n];
for (int i = 0; i < n; i++) {
rows[i] = new Row(Table.this, currRow + i);
}
currRow += n;
return rows;
}
@Override
public boolean hasNext() {
return currRow + n <= rowCount();
}
};
}
/** Returns the rows in this table as a Stream */
public Stream<Row> stream() {
return Streams.stream(iterator());
}
/**
* Streams over stepped sets of rows. I.e. 0 to n-1, n to 2n-1, 2n to 3n-1, etc. Only returns full
* sets of rows.
*
* @param n the number of rows to return for each iteration
*/
public Stream<Row[]> steppingStream(int n) {
return Streams.stream(steppingIterator(n));
}
/**
* Streams over rolling sets of rows. I.e. 0 to n-1, 1 to n, 2 to n+1, etc.
*
* @param n the number of rows to return for each iteration
*/
public Stream<Row[]> rollingStream(int n) {
return Streams.stream(rollingIterator(n));
}
/**
* Transposes data in the table, switching rows for columns. For example, a table like this.<br>
* value1 | value2 |<br>
* -------------------------------<br>
* 1 | 2 |<br>
* 1.1 | 2.1 |<br>
* 1.2 | 2.2 |<br>
*
* <p>Is transposed into the following<br>
* 0 | 1 | 2 |<br>
* -------------------------------------<br>
* 1 | 1.1 | 1.2 |<br>
* 2 | 2.1 | 2.2 |<br>
*
* @see Table#transpose(boolean,boolean)
* @return transposed table
*/
public Table transpose() {
return transpose(false, false);
}
/**
* Transposes data in the table, switching rows for columns. For example, a table like this.<br>
* label | value1 | value2 |<br>
* -------------------------------<br>
* row1 | 1 | 2 |<br>
* row2 | 1.1 | 2.1 |<br>
* row3 | 1.2 | 2.2 |<br>
*
* <p>Is transposed into the following<br>
* label | row1 | row2 | row3 |<br>
* -------------------------------------<br>
* value1 | 1 | 1.1 | 1.2 |<br>
* value2 | 2 | 2.1 | 2.2 |<br>
*
* @param includeColumnHeadingsAsFirstColumn Toggle whether to include the column headings as
* first column in result
* @param useFirstColumnForHeadings Use the first column as the column headings in the result.
* Useful if the data set already has a first column which contains a set of labels
* @return The transposed table
*/
public Table transpose(
boolean includeColumnHeadingsAsFirstColumn, boolean useFirstColumnForHeadings) {
if (this.columnCount() == 0) {
return this;
}
// Validate first
int columnOffset = useFirstColumnForHeadings ? 1 : 0;
ColumnType resultColumnType = validateTableHasSingleColumnType(columnOffset);
Table transposed = Table.create(this.name);
if (includeColumnHeadingsAsFirstColumn) {
String columnName = useFirstColumnForHeadings ? this.column(0).name() : "0";
StringColumn labelColumn = StringColumn.create(columnName);
for (int i = columnOffset; i < this.columnCount(); i++) {
Column<?> columnToTranspose = this.column(i);
labelColumn.append(columnToTranspose.name());
}
transposed.addColumns(labelColumn);
}
if (useFirstColumnForHeadings) {
transpose(transposed, resultColumnType, row -> String.valueOf(this.get(row, 0)), 1);
} else {
// default column labelling
return transpose(
transposed, resultColumnType, row -> String.valueOf(transposed.columnCount()), 0);
}
return transposed;
}
private ColumnType validateTableHasSingleColumnType(int startingColumn) {
// If all columns are of the same type
ColumnType[] columnTypes = this.typeArray();
long distinctColumnTypesCount =
Arrays.stream(columnTypes).skip(startingColumn).distinct().count();
if (distinctColumnTypesCount > 1) {
throw new IllegalArgumentException(
"This operation currently only supports tables where value columns are of the same type");
}
return columnTypes[startingColumn];
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Table transpose(
Table transposed,
ColumnType resultColumnType,
IntFunction<String> columnNameExtractor,
int startingColumn) {
for (int row = 0; row < this.rowCount(); row++) {
String columnName = columnNameExtractor.apply(row);
Column column = resultColumnType.create(columnName);
for (int col = startingColumn; col < this.columnCount(); col++) {
column.append(this.column(col), row);
}
transposed.addColumns(column);
}
return transposed;
}
/**
* Melt implements the 'tidy' melt operation as described in these papers by Hadley Wickham.
*
* <p>Tidy concepts: see https://www.jstatsoft.org/article/view/v059i10
*
* <p>Cast function details: see https://www.jstatsoft.org/article/view/v021i12
*
* <p>In short, melt turns columns into rows, but in a particular way. Used with the cast method,
* it can help make data tidy. In a tidy dataset, every variable is a column and every observation
* a row.
*
* <p>This method returns a table that contains all the data in this table, but organized such
* that there is a set of identifier variables (columns) and a single measured variable (column).
* For example, given a table with columns:
*
* <p>patient_id, gender, age, weight, temperature,
*
* <p>it returns a table with the columns:
*
* <p>patient_id, variable, value
*
* <p>In the new format, the strings age, weight, and temperature have become cells in the
* measurement table, such that a single row in the source table might look like this in the
* result table:
*
* <p>1234, gender, male 1234, age, 42 1234, weight, 186 1234, temperature, 97.4
*
* <p>This kind of structure often makes for a good intermediate format for performing subsequent
* transformations. It is especially useful when combined with the {@link #cast()} operation
*
* @param idVariables A list of column names intended to be used as identifiers. In he example,
* only patient_id would be an identifier
* @param measuredVariables A list of columns intended to be used as measured variables. All
* columns must have the same type
* @param dropMissing drop any row where the value is missing
*/
public Table melt(
List<String> idVariables, List<NumericColumn<?>> measuredVariables, Boolean dropMissing) {
Table result = Table.create(name);
for (String idColName : idVariables) {
result.addColumns(column(idColName).type().create(idColName));
}
result.addColumns(
StringColumn.create(MELT_VARIABLE_COLUMN_NAME),
DoubleColumn.create(MELT_VALUE_COLUMN_NAME));
List<String> measureColumnNames =
measuredVariables.stream().map(Column::name).collect(Collectors.toList());
TableSliceGroup slices = splitOn(idVariables.toArray(new String[0]));
for (TableSlice slice : slices) {
for (Row row : slice) {
for (String colName : measureColumnNames) {
if (!dropMissing || !row.isMissing(colName)) {
writeIdVariables(idVariables, result, row);
result.stringColumn(MELT_VARIABLE_COLUMN_NAME).append(colName);
double value = row.getNumber(colName);
result.doubleColumn(MELT_VALUE_COLUMN_NAME).append(value);
}
}
}
}
return result;
}
/** Writes one row of id variables into the result table */
private void writeIdVariables(List<String> idVariables, Table result, Row row) {
for (String id : idVariables) {
Column<?> resultColumn = result.column(id);
final ColumnType columnType = resultColumn.type();
if (columnType.equals(ColumnType.STRING)) {
StringColumn sc = (StringColumn) resultColumn;
sc.append(row.getString(resultColumn.name()));
} else if (columnType.equals(ColumnType.TEXT)) {
TextColumn sc = (TextColumn) resultColumn;
sc.append(row.getString(resultColumn.name()));
} else if (columnType.equals(ColumnType.INTEGER)) {
IntColumn ic = (IntColumn) resultColumn;
ic.append(row.getInt(resultColumn.name()));
} else if (columnType.equals(ColumnType.LONG)) {
LongColumn ic = (LongColumn) resultColumn;
ic.append(row.getLong(resultColumn.name()));
} else if (columnType.equals(ColumnType.SHORT)) {
ShortColumn ic = (ShortColumn) resultColumn;
ic.append(row.getShort(resultColumn.name()));
} else if (columnType.equals(ColumnType.LOCAL_DATE)) {
DateColumn ic = (DateColumn) resultColumn;
ic.appendInternal(row.getPackedDate(resultColumn.name()));
} else if (columnType.equals(ColumnType.LOCAL_DATE_TIME)) {
DateTimeColumn ic = (DateTimeColumn) resultColumn;
ic.appendInternal(row.getPackedDateTime(resultColumn.name()));
} else if (columnType.equals(ColumnType.LOCAL_TIME)) {
TimeColumn ic = (TimeColumn) resultColumn;
ic.appendInternal(row.getPackedTime(resultColumn.name()));
} else if (columnType.equals(ColumnType.INSTANT)) {
InstantColumn ic = (InstantColumn) resultColumn;
ic.appendInternal(row.getPackedInstant(resultColumn.name()));
} else if (columnType.equals(ColumnType.BOOLEAN)) {
BooleanColumn ic = (BooleanColumn) resultColumn;
ic.append(row.getBooleanAsByte(resultColumn.name()));
} else if (columnType.equals(ColumnType.DOUBLE)) {
DoubleColumn ic = (DoubleColumn) resultColumn;
ic.append(row.getDouble(resultColumn.name()));
} else if (columnType.equals(ColumnType.FLOAT)) {
FloatColumn ic = (FloatColumn) resultColumn;
ic.append(row.getFloat(resultColumn.name()));
} else {
throw new IllegalArgumentException("melt() does not support column type " + columnType);
}
}
}
/**
* Cast implements the 'tidy' cast operation as described in these papers by Hadley Wickham:
*
* <p>Cast takes a table in 'molten' format, such as is produced by the {@link #melt(List, List,
* Boolean)} t} method, and returns a version in standard tidy format.
*
* <p>The molten table should have a StringColumn called "variable" and a column called "value"
* Every unique variable name will become a column in the output table.
*
* <p>All other columns in this table are considered identifier variable. Each combination of
* identifier variables specifies an observation, so there will be one row for each, with the
* other variables added.
*
* <p>Variable columns are returned in an arbitrary order. Use {@link #reorderColumns(String...)}
* if column order is important.
*
* <p>Tidy concepts: see https://www.jstatsoft.org/article/view/v059i10
*
* <p>Cast function details: see https://www.jstatsoft.org/article/view/v021i12
*/
public Table cast() {
StringColumn variableNames = stringColumn(MELT_VARIABLE_COLUMN_NAME);
List<Column<?>> idColumns =
columnList.stream()
.filter(
column ->
!column.name().equals(MELT_VARIABLE_COLUMN_NAME)
&& !column.name().equals(MELT_VALUE_COLUMN_NAME))
.collect(toList());
Table result = Table.create(name);
for (Column<?> idColumn : idColumns) {
result.addColumns(idColumn.type().create(idColumn.name()));
}
StringColumn uniqueVariableNames = variableNames.unique();
for (String varName : uniqueVariableNames) {
result.addColumns(DoubleColumn.create(varName));
}
TableSliceGroup slices = splitOn(idColumns.stream().map(Column::name).toArray(String[]::new));
for (TableSlice slice : slices) {
Table sliceTable = slice.asTable();
for (Column<?> idColumn : idColumns) {
final ColumnType columnType = idColumn.type();
if (columnType.equals(ColumnType.STRING)) {
StringColumn source = (StringColumn) sliceTable.column(idColumn.name());
StringColumn dest = (StringColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.TEXT)) {
TextColumn source = (TextColumn) sliceTable.column(idColumn.name());
TextColumn dest = (TextColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.INTEGER)) {
IntColumn source = (IntColumn) sliceTable.column(idColumn.name());
IntColumn dest = (IntColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.LONG)) {
LongColumn source = (LongColumn) sliceTable.column(idColumn.name());
LongColumn dest = (LongColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.SHORT)) {
ShortColumn source = (ShortColumn) sliceTable.column(idColumn.name());
ShortColumn dest = (ShortColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.BOOLEAN)) {
BooleanColumn source = (BooleanColumn) sliceTable.column(idColumn.name());
BooleanColumn dest = (BooleanColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.LOCAL_DATE)) {
DateColumn source = (DateColumn) sliceTable.column(idColumn.name());
DateColumn dest = (DateColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.LOCAL_DATE_TIME)) {
DateTimeColumn source = (DateTimeColumn) sliceTable.column(idColumn.name());
DateTimeColumn dest = (DateTimeColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.INSTANT)) {
InstantColumn source = (InstantColumn) sliceTable.column(idColumn.name());
InstantColumn dest = (InstantColumn) result.column(idColumn.name());
dest.append(source.get(0));
} else if (columnType.equals(ColumnType.LOCAL_TIME)) {
TimeColumn source = (TimeColumn) sliceTable.column(idColumn.name());
TimeColumn dest = (TimeColumn) result.column(idColumn.name());
dest.append(source.get(0));
}
}
for (String varName : uniqueVariableNames) {
DoubleColumn dest = (DoubleColumn) result.column(varName);
Table sliceRow =
sliceTable.where(sliceTable.stringColumn(MELT_VARIABLE_COLUMN_NAME).isEqualTo(varName));
if (!sliceRow.isEmpty()) {
dest.append(sliceRow.doubleColumn(MELT_VALUE_COLUMN_NAME).get(0));
} else {
dest.appendMissing();
}
}
}
return result;
}
}
|
3e1b9108bcb3b243dd34b4a0643f1e8e45adf583 | 465 | java | Java | netty-im/src/main/java/com/sanshengshui/im/codec/PacketDecoder.java | 1604559744/netty-learning-example | 5be11db9a01e38d9e17ac2d906c55e8d0366b93d | [
"Apache-2.0"
] | 2,462 | 2018-09-26T01:14:58.000Z | 2022-03-31T15:02:58.000Z | netty-im/src/main/java/com/sanshengshui/im/codec/PacketDecoder.java | 1604559744/netty-learning-example | 5be11db9a01e38d9e17ac2d906c55e8d0366b93d | [
"Apache-2.0"
] | 9 | 2018-12-24T03:53:34.000Z | 2019-09-19T10:00:03.000Z | netty-im/src/main/java/com/sanshengshui/im/codec/PacketDecoder.java | 1604559744/netty-learning-example | 5be11db9a01e38d9e17ac2d906c55e8d0366b93d | [
"Apache-2.0"
] | 683 | 2018-09-27T03:11:49.000Z | 2022-03-29T09:22:56.000Z | 25.833333 | 76 | 0.784946 | 11,687 | package com.sanshengshui.im.codec;
import com.sanshengshui.im.protocol.PacketCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
public class PacketDecoder extends MessageToMessageDecoder<ByteBuf> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) {
out.add(PacketCodec.INSTANCE.decode(in));
}
}
|
3e1b91372d7dc8367ea1cf6baa75b04dd58b11fc | 270 | java | Java | src/main/java/com/jgb/designpatterns/decorator/SimplyVegPizza.java | jgb11/design-patterns-tutorial | 0de88b168a3b08ef969122ffa444b4ab4a5065ca | [
"MIT"
] | null | null | null | src/main/java/com/jgb/designpatterns/decorator/SimplyVegPizza.java | jgb11/design-patterns-tutorial | 0de88b168a3b08ef969122ffa444b4ab4a5065ca | [
"MIT"
] | null | null | null | src/main/java/com/jgb/designpatterns/decorator/SimplyVegPizza.java | jgb11/design-patterns-tutorial | 0de88b168a3b08ef969122ffa444b4ab4a5065ca | [
"MIT"
] | null | null | null | 16.875 | 47 | 0.603704 | 11,688 | package com.jgb.designpatterns.decorator;
public class SimplyVegPizza implements Pizza {
@Override
public String getDesc() {
return "SimplyVegPizza (230)";
}
@Override
public double getPrice() {
return 230;
}
}
|
3e1b92364e05f61fe923f230b41068279ac7e08c | 10,326 | java | Java | chi-maven-plugin/src/main/java/ca/infoway/messagebuilder/generator/DataType.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | 1 | 2022-03-09T12:17:41.000Z | 2022-03-09T12:17:41.000Z | chi-maven-plugin/src/main/java/ca/infoway/messagebuilder/generator/DataType.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | chi-maven-plugin/src/main/java/ca/infoway/messagebuilder/generator/DataType.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | 33.855738 | 144 | 0.761282 | 11,689 | /**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy$
* Last modified: $LastChangedDate$
* Revision: $LastChangedRevision$
*/
package ca.infoway.messagebuilder.generator;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.ClassUtils;
import ca.infoway.messagebuilder.datatype.StandardDataType;
import ca.infoway.messagebuilder.generator.util.ProgrammingLanguage;
import ca.infoway.messagebuilder.xml.Hl7TypeName;
public class DataType {
private final String qualifier;
private final DataType[] parameters;
private final DataTypeGenerationDetails type;
private final ParameterAppenderRegistry parameterAppenderRegistry;
private final boolean isR2;
DataType(DataTypeGenerationDetails type, String qualifier, boolean isR2, DataType... parameters) {
this.qualifier = qualifier;
this.isR2 = isR2;
if (DataTypeGenerationDetails.IVL_TS_R2 == type) {
this.parameters = new DataType[0];
} else {
this.parameters = parameters;
}
this.type = type;
this.parameterAppenderRegistry = new ParameterAppenderRegistryFactory().create(isR2);
}
public boolean isR2() {
return isR2;
}
DataType(DataTypeGenerationDetails type, String typeName, boolean isR2, List<DataType> parameters) {
this(type, typeName, isR2, parameters == null ? new DataType[0] : parameters.toArray(new DataType[parameters.size()]));
}
public String getShortName(ProgrammingLanguage language) {
StringBuilder builder = new StringBuilder();
getShortName(builder, language);
return builder.toString();
}
void getShortName(StringBuilder builder, ProgrammingLanguage language) {
builder.append(getUnparameterizedShortName(language));
appendParameters(builder, language);
}
public void appendParameters(StringBuilder builder, ProgrammingLanguage language) {
getWrappedParameterAppender().append(builder, this, Arrays.asList(this.parameters), language);
}
public String getUnparameterizedShortName(ProgrammingLanguage language) {
if (this.type.isCoded()) {
return ClassUtils.getShortClassName(this.qualifier);
} else {
return ClassUtils.getShortClassName(this.type.getLanguageSpecificTypeName(language));
}
}
public String getUnparameterizedShortWrappedName() {
return ClassUtils.getShortClassName(this.type.getHl7TypeName());
}
public String getTypeParameters(ProgrammingLanguage language) {
StringBuilder builder = new StringBuilder();
appendParameters(builder, language);
return builder.toString();
}
public String getCollectionParameterWrappedTypeImpl() {
String collectionWrappedParameter = "Object";
if (this.parameters.length>0) {
collectionWrappedParameter = this.parameters[0].getUnparameterizedShortWrappedNameImpl();
}
return collectionWrappedParameter;
}
/**
* @return <b>true</b> if the underlying HL7 type is a LIST or a SET.
*/
public boolean isWrappedTypeListOrSet() {
boolean isListOrSet = false;
if (getShortWrappedName()!=null) {
Hl7TypeName typeName = Hl7TypeName.parse(getShortWrappedName());
isListOrSet = StandardDataType.isSetOrList(typeName!=null ? typeName.getRootName() : null) ;
}
return isListOrSet;
}
/**
* @return <b>true</b> if the underlying HL7 type is a LIST or a SET.
*/
public boolean isWrappedTypeSet() {
boolean isSet = false;
if (getShortWrappedName()!=null) {
Hl7TypeName typeName = Hl7TypeName.parse(getShortWrappedName());
isSet = StandardDataType.isSet(typeName!=null ? typeName.getRootName() : null) ;
}
return isSet;
}
/**
* @return <b>true</b> if the java type used to represent this data type is a collection.
*/
public boolean isTypeCollection() {
return "Set".equals(getUnparameterizedShortName(ProgrammingLanguage.JAVA)) ||
"List".equals(getUnparameterizedShortName(ProgrammingLanguage.JAVA)) ||
"Collection".equals(getUnparameterizedShortName(ProgrammingLanguage.JAVA));
}
private boolean isTypeNotRequiringUnparameterizedImplTypeImports() {
String rootType = this.type.getRootType();
return "IVL".equals(rootType) || "URG".equals(rootType) || "RTO".equals(rootType) || "PIVL".equals(rootType);
}
public Set<String> getImportTypes() {
return getImportTypes(true);
}
private Set<String> getImportTypes(boolean addUnparameterizedImplType) {
Set<String> result = new HashSet<String>();
result.add(this.qualifier);
addWrappedTypeIfNecessary(result, addUnparameterizedImplType);
for (DataType dataType : this.parameters) {
result.addAll(dataType.getImportTypes(!isTypeNotRequiringUnparameterizedImplTypeImports()));
}
return result;
}
private void addWrappedTypeIfNecessary(Set<String> result, boolean addUnparameterizedImplType) {
if (getHl7ClassName() != null) {
result.add(getHl7ClassName());
if (addUnparameterizedImplType) {
result.add(getUnparameterizedImplementationType());
}
}
}
public String getTypeName(ProgrammingLanguage language) {
if (this.type.isCoded()) {
return this.qualifier;
} else {
return this.type.getLanguageSpecificTypeName(language);
}
}
public String getTypeName() {
return this.qualifier;
}
public String getShortWrappedName() {
return getShortWrappedName(ProgrammingLanguage.JAVA);
}
public String getShortWrappedName(ProgrammingLanguage language) {
StringBuilder builder = new StringBuilder();
getShortWrappedName(builder, language);
return builder.toString();
}
public String getShortWrappedNameImpl(ProgrammingLanguage language) {
StringBuilder builder = new StringBuilder();
getShortWrappedNameImpl(builder, language);
return builder.toString();
}
public String getShortWrappedNameImpl() {
return getShortWrappedNameImpl(ProgrammingLanguage.JAVA);
}
public String getUnparameterizedShortWrappedNameImpl() {
StringBuilder builder = new StringBuilder();
getUnparameterizedShortImplementationType(builder);
return builder.toString();
}
/**
* <p>Returns the name of the Java class that defines the interface for the
* HL7 type. Examples might include "ca.infoway.messagebuilder.datatype.ST".
* @return - the Java class name of the HL7 interface type
*/
public String getHl7ClassName() {
return this.type.getHl7TypeName();
}
private void getShortWrappedName(StringBuilder builder, ProgrammingLanguage language) {
builder.append(getUnparameterizedShortWrappedName());
getWrappedParameterAppender().appendWrapped(builder, this, Arrays.asList(this.parameters), language);
}
private ParameterAppender getWrappedParameterAppender() {
ParameterAppender appender = this.parameterAppenderRegistry.getAppender(StandardDataType.getByTypeName(getUnparameterizedShortWrappedName()));
return appender;
}
private void getShortWrappedNameImpl(StringBuilder builder, ProgrammingLanguage language) {
getUnparameterizedShortImplementationType(builder);
getWrappedParameterAppender().appendWrapped(builder, this, Arrays.asList(this.parameters), language);
}
protected String getUnparameterizedImplementationType() {
String packageName = ClassUtils.getPackageName(this.type.getHl7TypeName());
String implementationPackageName = packageName + ".impl";
return implementationPackageName + "." + getUnparameterizedShortImplementationType(null);
}
/**
* <p>Returns the type used for a field definition initializer. Examples might
* include "STImpl", "LISTImpl" or ANYImpl".
*
* @param builder
* @return
*/
private String getUnparameterizedShortImplementationType(StringBuilder builder) {
StringBuilder stringBuilder = new StringBuilder();
if (isBasicCollection()) {
stringBuilder.append(ClassUtils.getShortClassName(DataTypeGenerationDetails.LIST.getHl7TypeName()));
} else {
stringBuilder.append(getUnparameterizedShortWrappedName());
}
stringBuilder.append("Impl");
String result = stringBuilder.toString();
if (builder != null) {
builder.append(result);
}
return result;
}
/**
* <p>BAG and COLLECTION types are not really supported by the pan-Canadian standards,
* and yet we've seen instances where we need to support them. For all intents
* and purposes, we'll treat them like LISTs.
* @return
*/
private boolean isBasicCollection() {
return this.type == DataTypeGenerationDetails.COLLECTION ||
this.type == DataTypeGenerationDetails.BAG;
}
@Override
public String toString() {
return getShortWrappedName() + "/" + getShortName(ProgrammingLanguage.JAVA);
}
public DataTypeGenerationDetails getType() {
return this.type;
}
public boolean isCodedType() {
return getType().isCoded();
}
public DataType[] getParameters() {
return this.parameters;
}
/**
* <p>Provide a parameterized version of the implementation type. The result includes
* all generic parameters, but none of the classes are qualified with package names.
*
* <p>Examples:
*
* <p>The implementation type of a ST field is STImpl;
*
* <p>The implementation type of a LIST<II> field is LISTImpl<II, Identifier>
*
* @param language
* @return
*/
public String getParameterizedImplementationType(ProgrammingLanguage language) {
StringBuilder builder = new StringBuilder();
getUnparameterizedShortImplementationType(builder);
ParameterAppender appender = getImplementationParameterAppender();
appender.appendWrapped(builder, this, Arrays.asList(this.parameters), language);
return builder.toString();
}
private ParameterAppender getImplementationParameterAppender() {
if (isBasicCollection()) {
return parameterAppenderRegistry.getAppender(StandardDataType.LIST);
} else {
return parameterAppenderRegistry.getAppender(StandardDataType.getByTypeName(getUnparameterizedShortWrappedName()));
}
}
}
|
3e1b937d6d17282280107d2db11b007ed4b19b26 | 982 | java | Java | ciat-bim-rule/src/test/java/IntTbActorMsg.java | zjtyxy/bimServer | 7b8d199c9ca5c1627397b937ed7334c6468b8c4f | [
"MIT"
] | 1 | 2022-02-28T02:04:47.000Z | 2022-02-28T02:04:47.000Z | ciat-bim-rule/src/test/java/IntTbActorMsg.java | zjtyxy/bimServer | 7b8d199c9ca5c1627397b937ed7334c6468b8c4f | [
"MIT"
] | null | null | null | ciat-bim-rule/src/test/java/IntTbActorMsg.java | zjtyxy/bimServer | 7b8d199c9ca5c1627397b937ed7334c6468b8c4f | [
"MIT"
] | null | null | null | 26.540541 | 75 | 0.718941 | 11,690 | import com.ciat.bim.msg.MsgType;
import com.ciat.bim.msg.TbActorMsg;
import lombok.Getter;
/**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class IntTbActorMsg implements TbActorMsg {
@Getter
private final int value;
public IntTbActorMsg(int value) {
this.value = value;
}
@Override
public MsgType getMsgType() {
return MsgType.QUEUE_TO_RULE_ENGINE_MSG;
}
}
|
3e1b942cd0d70a5a190a1785c02aa3958118802b | 182 | java | Java | hprof-heap/src/test/java/org/netbeans/lib/profiler/heap/DummyP.java | AppSecAI-TEST/jvm-tools | 45b120e12a031f04c1db6f96e0c16cbe58e9f87c | [
"Apache-2.0"
] | 2 | 2018-01-08T04:21:57.000Z | 2018-01-08T04:22:14.000Z | hprof-heap/src/test/java/org/netbeans/lib/profiler/heap/DummyP.java | AppSecAI-TEST/jvm-tools | 45b120e12a031f04c1db6f96e0c16cbe58e9f87c | [
"Apache-2.0"
] | 2 | 2020-05-21T19:21:24.000Z | 2021-03-19T20:29:05.000Z | hprof-heap/src/test/java/org/netbeans/lib/profiler/heap/DummyP.java | AppSecAI-TEST/jvm-tools | 45b120e12a031f04c1db6f96e0c16cbe58e9f87c | [
"Apache-2.0"
] | 7 | 2018-12-21T00:13:41.000Z | 2021-09-03T21:13:31.000Z | 14 | 42 | 0.692308 | 11,691 | package org.netbeans.lib.profiler.heap;
public class DummyP {
String key;
Object value;
public DummyP(String key, Object value) {
this.key = key;
this.value = value;
}
}
|
3e1b954bf826a157fc94fda51f38afb98b7f355b | 483 | java | Java | panda-core/src/main/java/panda/dao/sql/expert/MariadbSqlExpert.java | foolite/panda | fc1ee07315554b264ae2c5776a2ca016a2e1c975 | [
"Apache-2.0"
] | 8 | 2017-07-07T11:22:31.000Z | 2022-03-17T15:50:12.000Z | panda-core/src/main/java/panda/dao/sql/expert/MariadbSqlExpert.java | foolite/panda | fc1ee07315554b264ae2c5776a2ca016a2e1c975 | [
"Apache-2.0"
] | 2 | 2022-02-02T02:55:37.000Z | 2022-02-02T06:52:15.000Z | panda-core/src/main/java/panda/dao/sql/expert/MariadbSqlExpert.java | foolite/panda | fc1ee07315554b264ae2c5776a2ca016a2e1c975 | [
"Apache-2.0"
] | 1 | 2019-06-18T03:57:19.000Z | 2019-06-18T03:57:19.000Z | 23 | 78 | 0.73499 | 11,692 | package panda.dao.sql.expert;
import panda.dao.DB;
import panda.dao.entity.Entity;
import panda.lang.Strings;
public class MariadbSqlExpert extends MysqlSqlExpert {
@Override
public DB getDatabaseType() {
return DB.MARIADB;
}
protected String getTableOption(Entity<?> entity, String name, String defv) {
String v = getEntityOptionString(entity, "mariadb-" + name, defv);
if (Strings.isEmpty(v)) {
return super.getTableOption(entity, name, defv);
}
return v;
}
}
|
3e1b95e68bd84958f6e54c4cd4f96f6330248927 | 6,851 | java | Java | src/test/java/com/example/service/DeviceServiceTest.java | Engin-Boot/alert-to-care-s3b8 | d6b01cc3dd9343d5119605f504754131d6aeb217 | [
"MIT"
] | null | null | null | src/test/java/com/example/service/DeviceServiceTest.java | Engin-Boot/alert-to-care-s3b8 | d6b01cc3dd9343d5119605f504754131d6aeb217 | [
"MIT"
] | 5 | 2021-12-14T20:57:10.000Z | 2022-01-04T16:48:17.000Z | src/test/java/com/example/service/DeviceServiceTest.java | Engin-Boot/alert-to-care-s3b8 | d6b01cc3dd9343d5119605f504754131d6aeb217 | [
"MIT"
] | null | null | null | 45.370861 | 198 | 0.73887 | 11,693 | package com.example.service;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.example.entities.Device;
import com.example.entities.DeviceStatus;
import com.example.exceptions.DeviceDoesNotExistException;
import com.example.exceptions.DeviceNotAssociatedWithBedException;
import com.example.mapper.DeviceMapper;
import com.example.repository.DeviceRepository;
@RunWith(MockitoJUnitRunner.class)
public class DeviceServiceTest {
@Mock
DeviceRepository deviceRepository;
@Mock
DeviceMapper deviceMapper;
DeviceService deviceService;
@Captor
ArgumentCaptor<Device> deviceArgumentCaptor;
@Before
public void setUp() {
deviceService = new DeviceService(deviceRepository, deviceMapper);
}
@Test
public void given_Existing_DeviceId_When_Get_Device_By_Id_Then_Throw_No_Exception() throws DeviceNotAssociatedWithBedException, DeviceDoesNotExistException {
String bed_id = UUID.randomUUID().toString();
String existing_device_id = UUID.randomUUID().toString();
Device existing_device = new Device( existing_device_id,"type1", DeviceStatus.NOTINUSE.toString(), bed_id);
when(deviceRepository.findById(any())).thenReturn(Optional.of(existing_device));
Device device = deviceService.getDeviceHavingAssocationWithBed(existing_device_id);
Assert.assertNotNull(device.getBedId());
Assert.assertNotNull(device.getDeviceStatus());
Assert.assertNotNull(device.getDeviceType());
Assert.assertNotNull(device.getDeviceId());
}
@Test(expected = DeviceDoesNotExistException.class)
public void given_Non_Existing_DeviceId_When_Get_Device_By_Id_Then_Throw_Exception() throws DeviceNotAssociatedWithBedException, DeviceDoesNotExistException {
String non_existing_device_id = UUID.randomUUID().toString();
when(deviceRepository.findById(non_existing_device_id)).thenReturn(Optional.empty());
deviceService.getDeviceHavingAssocationWithBed(non_existing_device_id);
}
@Test(expected = DeviceNotAssociatedWithBedException.class)
public void given_Existing_DeviceId_When_Get_Device_By_Id_But_Device_Not_Associated_With_Any_Bed_Then_Throw_Exception() throws DeviceNotAssociatedWithBedException, DeviceDoesNotExistException {
String existing_device_id = UUID.randomUUID().toString();
Device existing_device = new Device( existing_device_id,"type1", DeviceStatus.NOTINUSE.toString(), null);
when(deviceRepository.findById(existing_device_id)).thenReturn(Optional.of(existing_device));
deviceService.getDeviceHavingAssocationWithBed(existing_device_id);
}
@Test
public void given_Devices_When_Created_Then_Throw_No_Exception() {
int no_of_beds = 3;
Device device1 = new Device(UUID.randomUUID().toString(),"type1", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
Device device2 = new Device(UUID.randomUUID().toString(),"type2", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
Device device3 = new Device(UUID.randomUUID().toString(),"type3", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
when(deviceMapper.mapDeviceDTOtoDeviceEntity(any()))
.thenReturn(device1)
.thenReturn(device2)
.thenReturn(device3);
deviceService.createDevices(no_of_beds);
verify(deviceRepository, times(3)).save(deviceArgumentCaptor.capture());
for(Device device: deviceArgumentCaptor.getAllValues()) {
Assert.assertEquals(DeviceStatus.NOTINUSE.toString(), device.getDeviceStatus());
}
}
@Test
public void given_Device_When_Associating_Device_With_Bed_Then_Throw_No_Exception(){
String bed_id = UUID.randomUUID().toString();
Device device1 = new Device(UUID.randomUUID().toString(),"type1", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
Device device2 = new Device(UUID.randomUUID().toString(),"type2", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
List<Device> deviceList = new ArrayList<>();
deviceList.add(device1);
deviceList.add(device2);
when(deviceRepository.findByDeviceStatus(any())).thenReturn(deviceList);
deviceService.associateDeviceToBed(bed_id);
verify(deviceRepository, times(1)).save(deviceArgumentCaptor.capture());
Assert.assertEquals(bed_id, deviceArgumentCaptor.getValue().getBedId());
Assert.assertEquals("type1", deviceArgumentCaptor.getValue().getDeviceType());
Assert.assertEquals(DeviceStatus.INUSE.toString(), deviceArgumentCaptor.getValue().getDeviceStatus());
}
@Test
public void given_Device_When_Updating_Device_After_Patient_Discharge_Then_Throw_No_Exception() throws DeviceDoesNotExistException {
String valid_bed_id = UUID.randomUUID().toString();
String device_id = UUID.randomUUID().toString();
Device existing_device = new Device(device_id,"type1", DeviceStatus.NOTINUSE.toString(), valid_bed_id);
when(deviceRepository.findByBedId(valid_bed_id)).thenReturn(existing_device);
deviceService.updateDeviceAfterPatientDischarge(valid_bed_id);
verify(deviceRepository, times(1)).save(deviceArgumentCaptor.capture());
Assert.assertNull(deviceArgumentCaptor.getValue().getBedId());
Assert.assertEquals("type1", deviceArgumentCaptor.getValue().getDeviceType());
Assert.assertEquals(DeviceStatus.NOTINUSE.toString(), deviceArgumentCaptor.getValue().getDeviceStatus());
}
@Test(expected = DeviceDoesNotExistException.class)
public void given_Device_With_Invalid_Bed_Id_When_Updating_Device_After_Patient_Discharge_Then_Throw_Exception() throws DeviceDoesNotExistException {
String invalid_bed_id = UUID.randomUUID().toString();
String device_id = UUID.randomUUID().toString();
Device existing_device = new Device(device_id,"type1", DeviceStatus.NOTINUSE.toString(), UUID.randomUUID().toString());
when(deviceRepository.findByBedId(invalid_bed_id)).thenReturn(null);
deviceService.updateDeviceAfterPatientDischarge(invalid_bed_id);
}
}
|
3e1b96effdd06c92c36b1b1d9e0c41305409680c | 151 | java | Java | src/main/java/com/michalkowol/article/package-info.java | michalkowol/spring-boot-template | 1e3fecff63d7a15cd86f0cc3ff4bca2b201c4f02 | [
"0BSD"
] | 2 | 2016-02-12T22:17:30.000Z | 2020-04-22T16:24:30.000Z | src/main/java/com/michalkowol/article/package-info.java | michalkowol/spring-boot-template | 1e3fecff63d7a15cd86f0cc3ff4bca2b201c4f02 | [
"0BSD"
] | null | null | null | src/main/java/com/michalkowol/article/package-info.java | michalkowol/spring-boot-template | 1e3fecff63d7a15cd86f0cc3ff4bca2b201c4f02 | [
"0BSD"
] | null | null | null | 18.875 | 43 | 0.854305 | 11,694 | @CheckReturnValue
@NonNullApi
package com.michalkowol.article;
import org.springframework.lang.NonNullApi;
import javax.annotation.CheckReturnValue;
|
3e1b9a679ac9aa9a3d6591b0ac95a539c8975cdb | 832 | java | Java | src/main/java/com/company/app/application/usecases/FindBooksUseCase.java | JonasHavers/archunit-examples | d60b8cea830d9298cb98d51ad82078002950f9fc | [
"MIT"
] | 30 | 2019-05-15T13:32:35.000Z | 2022-03-01T11:23:10.000Z | src/main/java/com/company/app/application/usecases/FindBooksUseCase.java | JonasHavers/archunit-examples | d60b8cea830d9298cb98d51ad82078002950f9fc | [
"MIT"
] | null | null | null | src/main/java/com/company/app/application/usecases/FindBooksUseCase.java | JonasHavers/archunit-examples | d60b8cea830d9298cb98d51ad82078002950f9fc | [
"MIT"
] | 6 | 2019-07-01T09:37:03.000Z | 2020-12-10T05:58:18.000Z | 20.8 | 58 | 0.72476 | 11,695 | package com.company.app.application.usecases;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
@Service
public class FindBooksUseCase {
private final FindBooksPort findBooksPort;
public FindBooksUseCase(FindBooksPort findBooksPort) {
this.findBooksPort = findBooksPort;
}
public Response invoke(Request request) {
Flux<BookDto> allBooks = findBooksPort.findAllBooks();
return new Response(allBooks);
}
public interface FindBooksPort {
Flux<BookDto> findAllBooks();
}
public static class Request {
}
public static class Response {
public final Flux<BookDto> books;
Response(Flux<BookDto> books) {
this.books = books;
}
}
public static class BookDto {
public String isbn;
public String title;
public String author;
}
}
|
3e1b9a75b83d8cecbf83b1edff0677667b51a72f | 624 | java | Java | src/main/java/com/kapresoft/parkingapp/repositories/ReservationRepository.java | nkapre/parkinglot | 791829389a38ddd8fdd6f2286e8893216c61593a | [
"Unlicense"
] | null | null | null | src/main/java/com/kapresoft/parkingapp/repositories/ReservationRepository.java | nkapre/parkinglot | 791829389a38ddd8fdd6f2286e8893216c61593a | [
"Unlicense"
] | null | null | null | src/main/java/com/kapresoft/parkingapp/repositories/ReservationRepository.java | nkapre/parkinglot | 791829389a38ddd8fdd6f2286e8893216c61593a | [
"Unlicense"
] | null | null | null | 39 | 116 | 0.850962 | 11,696 | package com.kapresoft.parkingapp.repositories;
import com.kapresoft.parkingapp.cbo.reservation.ParkingReservation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
public interface ReservationRepository extends MongoRepository<ParkingReservation, String> {
public ParkingReservation findReservationByReservationConfirmationNumber (final String confirmationNumber);
@Query ("{'reservationConfirmationNumber': ?0}")
public ParkingReservation findReservationByReservationConfirmationNumberQuery (final String confirmationNumber);
}
|
3e1b9aaaf11fc730fba1ee3608bf4dcd83bc79e8 | 306 | java | Java | activity-service/src/main/java/com/springboot/cloud/dto/FlashPromotionParams.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | 1 | 2022-03-29T15:04:58.000Z | 2022-03-29T15:04:58.000Z | activity-service/src/main/java/com/springboot/cloud/dto/FlashPromotionParams.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | null | null | null | activity-service/src/main/java/com/springboot/cloud/dto/FlashPromotionParams.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | null | null | null | 13.304348 | 35 | 0.683007 | 11,697 | package com.springboot.cloud.dto;
import lombok.Data;
import java.util.Date;
/**
* @Author: lirisheng
* @Date: 2021/3/31 21:43
* @Version 1.0
*/
@Data
public class FlashPromotionParams {
private String name;
private Date nowTime;
private Date endTime;
private Integer status;
}
|
3e1b9d3c19da401a38d0565b11e347f4f89897bb | 41,839 | java | Java | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/coretext/c/CoreText.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/coretext/c/CoreText.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/coretext/c/CoreText.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | 30.696258 | 190 | 0.752623 | 11,698 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.coretext.c;
import apple.corefoundation.opaque.CFArrayRef;
import apple.corefoundation.opaque.CFAttributedStringRef;
import apple.corefoundation.opaque.CFCharacterSetRef;
import apple.corefoundation.opaque.CFDataRef;
import apple.corefoundation.opaque.CFDictionaryRef;
import apple.corefoundation.opaque.CFErrorRef;
import apple.corefoundation.opaque.CFNumberRef;
import apple.corefoundation.opaque.CFSetRef;
import apple.corefoundation.opaque.CFStringRef;
import apple.corefoundation.opaque.CFURLRef;
import apple.corefoundation.struct.CFRange;
import apple.coregraphics.opaque.CGContextRef;
import apple.coregraphics.opaque.CGFontRef;
import apple.coregraphics.opaque.CGPathRef;
import apple.coregraphics.struct.CGAffineTransform;
import apple.coregraphics.struct.CGPoint;
import apple.coregraphics.struct.CGRect;
import apple.coregraphics.struct.CGSize;
import apple.coretext.opaque.CTFontCollectionRef;
import apple.coretext.opaque.CTFontDescriptorRef;
import apple.coretext.opaque.CTFontRef;
import apple.coretext.opaque.CTFrameRef;
import apple.coretext.opaque.CTFramesetterRef;
import apple.coretext.opaque.CTGlyphInfoRef;
import apple.coretext.opaque.CTLineRef;
import apple.coretext.opaque.CTParagraphStyleRef;
import apple.coretext.opaque.CTRubyAnnotationRef;
import apple.coretext.opaque.CTRunDelegateRef;
import apple.coretext.opaque.CTRunRef;
import apple.coretext.opaque.CTTextTabRef;
import apple.coretext.opaque.CTTypesetterRef;
import apple.coretext.struct.CTParagraphStyleSetting;
import apple.coretext.struct.CTRunDelegateCallbacks;
import org.moe.natj.c.CRuntime;
import org.moe.natj.c.ann.CFunction;
import org.moe.natj.c.ann.CVariable;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.NFloat;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ann.UncertainArgument;
import org.moe.natj.general.ann.UncertainReturn;
import org.moe.natj.general.ptr.BoolPtr;
import org.moe.natj.general.ptr.CharPtr;
import org.moe.natj.general.ptr.ConstCharPtr;
import org.moe.natj.general.ptr.ConstNIntPtr;
import org.moe.natj.general.ptr.ConstVoidPtr;
import org.moe.natj.general.ptr.NFloatPtr;
import org.moe.natj.general.ptr.NIntPtr;
import org.moe.natj.general.ptr.Ptr;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.ann.ObjCBlock;
@Generated
@Library("CoreText")
@Runtime(CRuntime.class)
public final class CoreText {
static {
NatJ.register();
}
@Generated
private CoreText() {
}
@Generated
@CFunction
@NUInt
public static native long CTParagraphStyleGetTypeID();
@Generated
@CFunction
public static native CTParagraphStyleRef CTParagraphStyleCreate(
@UncertainArgument("Options: reference, array Fallback: reference") CTParagraphStyleSetting settings,
@NUInt long settingCount);
@Generated
@CFunction
public static native CTParagraphStyleRef CTParagraphStyleCreateCopy(CTParagraphStyleRef paragraphStyle);
@Generated
@CFunction
public static native boolean CTParagraphStyleGetValueForSpecifier(CTParagraphStyleRef paragraphStyle, int spec,
@NUInt long valueBufferSize, VoidPtr valueBuffer);
@Generated
@CFunction
@NUInt
public static native long CTFontDescriptorGetTypeID();
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateWithNameAndSize(CFStringRef name,
@NFloat double size);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateWithAttributes(CFDictionaryRef attributes);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateCopyWithAttributes(CTFontDescriptorRef original,
CFDictionaryRef attributes);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateCopyWithFamily(CTFontDescriptorRef original,
CFStringRef family);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateCopyWithSymbolicTraits(CTFontDescriptorRef original,
int symTraitValue, int symTraitMask);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateCopyWithVariation(CTFontDescriptorRef original,
CFNumberRef variationIdentifier, @NFloat double variationValue);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateCopyWithFeature(CTFontDescriptorRef original,
CFNumberRef featureTypeIdentifier, CFNumberRef featureSelectorIdentifier);
@Generated
@CFunction
public static native CFArrayRef CTFontDescriptorCreateMatchingFontDescriptors(CTFontDescriptorRef descriptor,
CFSetRef mandatoryAttributes);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontDescriptorCreateMatchingFontDescriptor(
CTFontDescriptorRef descriptor, CFSetRef mandatoryAttributes);
@Generated
@CFunction
public static native boolean CTFontDescriptorMatchFontDescriptorsWithProgressHandler(CFArrayRef descriptors,
CFSetRef mandatoryAttributes,
@ObjCBlock(name = "call_CTFontDescriptorMatchFontDescriptorsWithProgressHandler") Block_CTFontDescriptorMatchFontDescriptorsWithProgressHandler progressBlock);
@Generated
@CFunction
public static native CFDictionaryRef CTFontDescriptorCopyAttributes(CTFontDescriptorRef descriptor);
@Generated
@CFunction
public static native ConstVoidPtr CTFontDescriptorCopyAttribute(CTFontDescriptorRef descriptor,
CFStringRef attribute);
@Generated
@CFunction
public static native ConstVoidPtr CTFontDescriptorCopyLocalizedAttribute(CTFontDescriptorRef descriptor,
CFStringRef attribute, Ptr<CFStringRef> language);
@Generated
@CFunction
@NUInt
public static native long CTFontGetTypeID();
@Generated
@CFunction
public static native CTFontRef CTFontCreateWithName(CFStringRef name, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix);
@Generated
@CFunction
public static native CTFontRef CTFontCreateWithFontDescriptor(CTFontDescriptorRef descriptor, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix);
@Generated
@CFunction
public static native CTFontRef CTFontCreateWithNameAndOptions(CFStringRef name, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
@NUInt long options);
@Generated
@CFunction
public static native CTFontRef CTFontCreateWithFontDescriptorAndOptions(CTFontDescriptorRef descriptor,
@NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
@NUInt long options);
@Generated
@CFunction
public static native CTFontRef CTFontCreateUIFontForLanguage(int uiType, @NFloat double size, CFStringRef language);
@Generated
@CFunction
public static native CTFontRef CTFontCreateCopyWithAttributes(CTFontRef font, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
CTFontDescriptorRef attributes);
@Generated
@CFunction
public static native CTFontRef CTFontCreateCopyWithSymbolicTraits(CTFontRef font, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
int symTraitValue, int symTraitMask);
@Generated
@CFunction
public static native CTFontRef CTFontCreateCopyWithFamily(CTFontRef font, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
CFStringRef family);
@Generated
@CFunction
public static native CTFontRef CTFontCreateForString(CTFontRef currentFont, CFStringRef string,
@ByValue CFRange range);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontCopyFontDescriptor(CTFontRef font);
@Generated
@CFunction
public static native ConstVoidPtr CTFontCopyAttribute(CTFontRef font, CFStringRef attribute);
@Generated
@CFunction
@NFloat
public static native double CTFontGetSize(CTFontRef font);
@Generated
@CFunction
@ByValue
public static native CGAffineTransform CTFontGetMatrix(CTFontRef font);
@Generated
@CFunction
public static native int CTFontGetSymbolicTraits(CTFontRef font);
@Generated
@CFunction
public static native CFDictionaryRef CTFontCopyTraits(CTFontRef font);
@Generated
@CFunction
public static native CFStringRef CTFontCopyPostScriptName(CTFontRef font);
@Generated
@CFunction
public static native CFStringRef CTFontCopyFamilyName(CTFontRef font);
@Generated
@CFunction
public static native CFStringRef CTFontCopyFullName(CTFontRef font);
@Generated
@CFunction
public static native CFStringRef CTFontCopyDisplayName(CTFontRef font);
@Generated
@CFunction
public static native CFStringRef CTFontCopyName(CTFontRef font, CFStringRef nameKey);
@Generated
@CFunction
public static native CFStringRef CTFontCopyLocalizedName(CTFontRef font, CFStringRef nameKey,
Ptr<CFStringRef> actualLanguage);
@Generated
@CFunction
public static native CFCharacterSetRef CTFontCopyCharacterSet(CTFontRef font);
@Generated
@CFunction
public static native int CTFontGetStringEncoding(CTFontRef font);
@Generated
@CFunction
public static native CFArrayRef CTFontCopySupportedLanguages(CTFontRef font);
@Generated
@CFunction
public static native boolean CTFontGetGlyphsForCharacters(CTFontRef font, ConstCharPtr characters, CharPtr glyphs,
@NInt long count);
@Generated
@CFunction
@NFloat
public static native double CTFontGetAscent(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetDescent(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetLeading(CTFontRef font);
@Generated
@CFunction
public static native int CTFontGetUnitsPerEm(CTFontRef font);
@Generated
@CFunction
@NInt
public static native long CTFontGetGlyphCount(CTFontRef font);
@Generated
@CFunction
@ByValue
public static native CGRect CTFontGetBoundingBox(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetUnderlinePosition(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetUnderlineThickness(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetSlantAngle(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetCapHeight(CTFontRef font);
@Generated
@CFunction
@NFloat
public static native double CTFontGetXHeight(CTFontRef font);
@Generated
@CFunction
public static native char CTFontGetGlyphWithName(CTFontRef font, CFStringRef glyphName);
@Generated
@CFunction
@ByValue
public static native CGRect CTFontGetBoundingRectsForGlyphs(CTFontRef font, int orientation, ConstCharPtr glyphs,
@UncertainArgument("Options: reference, array Fallback: reference") CGRect boundingRects, @NInt long count);
@Generated
@CFunction
@ByValue
public static native CGRect CTFontGetOpticalBoundsForGlyphs(CTFontRef font, ConstCharPtr glyphs,
@UncertainArgument("Options: reference, array Fallback: reference") CGRect boundingRects, @NInt long count,
@NUInt long options);
@Generated
@CFunction
public static native double CTFontGetAdvancesForGlyphs(CTFontRef font, int orientation, ConstCharPtr glyphs,
@UncertainArgument("Options: reference, array Fallback: reference") CGSize advances, @NInt long count);
@Generated
@CFunction
public static native void CTFontGetVerticalTranslationsForGlyphs(CTFontRef font, ConstCharPtr glyphs,
@UncertainArgument("Options: reference, array Fallback: reference") CGSize translations, @NInt long count);
@Generated
@CFunction
public static native CGPathRef CTFontCreatePathForGlyph(CTFontRef font, char glyph,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix);
@Generated
@CFunction
public static native CFArrayRef CTFontCopyVariationAxes(CTFontRef font);
@Generated
@CFunction
public static native CFDictionaryRef CTFontCopyVariation(CTFontRef font);
@Generated
@CFunction
public static native CFArrayRef CTFontCopyFeatures(CTFontRef font);
@Generated
@CFunction
public static native CFArrayRef CTFontCopyFeatureSettings(CTFontRef font);
@Generated
@CFunction
public static native CGFontRef CTFontCopyGraphicsFont(CTFontRef font, Ptr<CTFontDescriptorRef> attributes);
@Generated
@CFunction
public static native CTFontRef CTFontCreateWithGraphicsFont(CGFontRef graphicsFont, @NFloat double size,
@UncertainArgument("Options: reference, array Fallback: reference") CGAffineTransform matrix,
CTFontDescriptorRef attributes);
@Generated
@CFunction
public static native CFArrayRef CTFontCopyAvailableTables(CTFontRef font, int options);
@Generated
@CFunction
public static native CFDataRef CTFontCopyTable(CTFontRef font, int table, int options);
@Generated
@CFunction
public static native void CTFontDrawGlyphs(CTFontRef font, ConstCharPtr glyphs,
@UncertainArgument("Options: reference, array Fallback: reference") CGPoint positions, @NUInt long count,
CGContextRef context);
@Generated
@CFunction
@NInt
public static native long CTFontGetLigatureCaretPositions(CTFontRef font, char glyph, NFloatPtr positions,
@NInt long maxPositions);
@Generated
@CFunction
public static native CFArrayRef CTFontCopyDefaultCascadeListForLanguages(CTFontRef font,
CFArrayRef languagePrefList);
@Generated
@CFunction
@NUInt
public static native long CTFontCollectionGetTypeID();
@Generated
@CFunction
public static native CTFontCollectionRef CTFontCollectionCreateFromAvailableFonts(CFDictionaryRef options);
@Generated
@CFunction
public static native CTFontCollectionRef CTFontCollectionCreateWithFontDescriptors(CFArrayRef queryDescriptors,
CFDictionaryRef options);
@Generated
@CFunction
public static native CTFontCollectionRef CTFontCollectionCreateCopyWithFontDescriptors(CTFontCollectionRef original,
CFArrayRef queryDescriptors, CFDictionaryRef options);
@Generated
@CFunction
public static native CFArrayRef CTFontCollectionCreateMatchingFontDescriptors(CTFontCollectionRef collection);
@Generated
@CFunction
public static native CFArrayRef CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback(
CTFontCollectionRef collection,
@FunctionPtr(name = "call_CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback") Function_CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback sortCallback,
VoidPtr refCon);
@Generated
@CFunction
public static native CFArrayRef CTFontManagerCopyAvailablePostScriptNames();
@Generated
@CFunction
public static native CFArrayRef CTFontManagerCopyAvailableFontFamilyNames();
@Generated
@CFunction
public static native CFArrayRef CTFontManagerCreateFontDescriptorsFromURL(CFURLRef fileURL);
@Generated
@CFunction
public static native CTFontDescriptorRef CTFontManagerCreateFontDescriptorFromData(CFDataRef data);
@Generated
@CFunction
public static native boolean CTFontManagerRegisterFontsForURL(CFURLRef fontURL, int scope, Ptr<CFErrorRef> error);
@Generated
@CFunction
public static native boolean CTFontManagerUnregisterFontsForURL(CFURLRef fontURL, int scope, Ptr<CFErrorRef> error);
@Generated
@CFunction
public static native boolean CTFontManagerRegisterGraphicsFont(CGFontRef font, Ptr<CFErrorRef> error);
@Generated
@CFunction
public static native boolean CTFontManagerUnregisterGraphicsFont(CGFontRef font, Ptr<CFErrorRef> error);
@Generated
@CFunction
public static native boolean CTFontManagerRegisterFontsForURLs(CFArrayRef fontURLs, int scope,
Ptr<CFArrayRef> errors);
@Generated
@CFunction
public static native boolean CTFontManagerUnregisterFontsForURLs(CFArrayRef fontURLs, int scope,
Ptr<CFArrayRef> errors);
@Generated
@CFunction
@NUInt
public static native long CTFrameGetTypeID();
@Generated
@CFunction
@ByValue
public static native CFRange CTFrameGetStringRange(CTFrameRef frame);
@Generated
@CFunction
@ByValue
public static native CFRange CTFrameGetVisibleStringRange(CTFrameRef frame);
@Generated
@CFunction
public static native CGPathRef CTFrameGetPath(CTFrameRef frame);
@Generated
@CFunction
public static native CFDictionaryRef CTFrameGetFrameAttributes(CTFrameRef frame);
@Generated
@CFunction
public static native CFArrayRef CTFrameGetLines(CTFrameRef frame);
@Generated
@CFunction
public static native void CTFrameGetLineOrigins(CTFrameRef frame, @ByValue CFRange range,
@UncertainArgument("Options: reference, array Fallback: reference") CGPoint origins);
@Generated
@CFunction
public static native void CTFrameDraw(CTFrameRef frame, CGContextRef context);
@Generated
@CFunction
@NUInt
public static native long CTLineGetTypeID();
@Generated
@CFunction
public static native CTLineRef CTLineCreateWithAttributedString(CFAttributedStringRef attrString);
@Generated
@CFunction
public static native CTLineRef CTLineCreateTruncatedLine(CTLineRef line, double width, int truncationType,
CTLineRef truncationToken);
@Generated
@CFunction
public static native CTLineRef CTLineCreateJustifiedLine(CTLineRef line, @NFloat double justificationFactor,
double justificationWidth);
@Generated
@CFunction
@NInt
public static native long CTLineGetGlyphCount(CTLineRef line);
@Generated
@CFunction
public static native CFArrayRef CTLineGetGlyphRuns(CTLineRef line);
@Generated
@CFunction
@ByValue
public static native CFRange CTLineGetStringRange(CTLineRef line);
@Generated
@CFunction
public static native double CTLineGetPenOffsetForFlush(CTLineRef line, @NFloat double flushFactor,
double flushWidth);
@Generated
@CFunction
public static native void CTLineDraw(CTLineRef line, CGContextRef context);
@Generated
@CFunction
public static native double CTLineGetTypographicBounds(CTLineRef line, NFloatPtr ascent, NFloatPtr descent,
NFloatPtr leading);
@Generated
@CFunction
@ByValue
public static native CGRect CTLineGetBoundsWithOptions(CTLineRef line, @NUInt long options);
@Generated
@CFunction
public static native double CTLineGetTrailingWhitespaceWidth(CTLineRef line);
@Generated
@CFunction
@ByValue
public static native CGRect CTLineGetImageBounds(CTLineRef line, CGContextRef context);
@Generated
@CFunction
@NInt
public static native long CTLineGetStringIndexForPosition(CTLineRef line, @ByValue CGPoint position);
@Generated
@CFunction
@NFloat
public static native double CTLineGetOffsetForStringIndex(CTLineRef line, @NInt long charIndex,
NFloatPtr secondaryOffset);
@Generated
@CFunction
public static native void CTLineEnumerateCaretOffsets(CTLineRef line,
@ObjCBlock(name = "call_CTLineEnumerateCaretOffsets") Block_CTLineEnumerateCaretOffsets block);
@Generated
@CFunction
@NUInt
public static native long CTTypesetterGetTypeID();
@Generated
@CFunction
public static native CTTypesetterRef CTTypesetterCreateWithAttributedString(CFAttributedStringRef string);
@Generated
@CFunction
public static native CTTypesetterRef CTTypesetterCreateWithAttributedStringAndOptions(CFAttributedStringRef string,
CFDictionaryRef options);
@Generated
@CFunction
public static native CTLineRef CTTypesetterCreateLineWithOffset(CTTypesetterRef typesetter,
@ByValue CFRange stringRange, double offset);
@Generated
@CFunction
public static native CTLineRef CTTypesetterCreateLine(CTTypesetterRef typesetter, @ByValue CFRange stringRange);
@Generated
@CFunction
@NInt
public static native long CTTypesetterSuggestLineBreakWithOffset(CTTypesetterRef typesetter, @NInt long startIndex,
double width, double offset);
@Generated
@CFunction
@NInt
public static native long CTTypesetterSuggestLineBreak(CTTypesetterRef typesetter, @NInt long startIndex,
double width);
@Generated
@CFunction
@NInt
public static native long CTTypesetterSuggestClusterBreakWithOffset(CTTypesetterRef typesetter,
@NInt long startIndex, double width, double offset);
@Generated
@CFunction
@NInt
public static native long CTTypesetterSuggestClusterBreak(CTTypesetterRef typesetter, @NInt long startIndex,
double width);
@Generated
@CFunction
@NUInt
public static native long CTFramesetterGetTypeID();
@Generated
@CFunction
public static native CTFramesetterRef CTFramesetterCreateWithAttributedString(CFAttributedStringRef string);
@Generated
@CFunction
public static native CTFrameRef CTFramesetterCreateFrame(CTFramesetterRef framesetter, @ByValue CFRange stringRange,
CGPathRef path, CFDictionaryRef frameAttributes);
@Generated
@CFunction
public static native CTTypesetterRef CTFramesetterGetTypesetter(CTFramesetterRef framesetter);
@Generated
@CFunction
@ByValue
public static native CGSize CTFramesetterSuggestFrameSizeWithConstraints(CTFramesetterRef framesetter,
@ByValue CFRange stringRange, CFDictionaryRef frameAttributes, @ByValue CGSize constraints,
@UncertainArgument("Options: reference, array Fallback: reference") CFRange fitRange);
@Generated
@CFunction
@NUInt
public static native long CTGlyphInfoGetTypeID();
@Generated
@CFunction
public static native CTGlyphInfoRef CTGlyphInfoCreateWithGlyphName(CFStringRef glyphName, CTFontRef font,
CFStringRef baseString);
@Generated
@CFunction
public static native CTGlyphInfoRef CTGlyphInfoCreateWithGlyph(char glyph, CTFontRef font, CFStringRef baseString);
@Generated
@CFunction
public static native CTGlyphInfoRef CTGlyphInfoCreateWithCharacterIdentifier(char cid, short collection,
CFStringRef baseString);
@Generated
@CFunction
public static native CFStringRef CTGlyphInfoGetGlyphName(CTGlyphInfoRef glyphInfo);
@Generated
@CFunction
public static native char CTGlyphInfoGetCharacterIdentifier(CTGlyphInfoRef glyphInfo);
@Generated
@CFunction
public static native short CTGlyphInfoGetCharacterCollection(CTGlyphInfoRef glyphInfo);
@Generated
@CFunction
@NUInt
public static native long CTRubyAnnotationGetTypeID();
@Generated
@CFunction
public static native CTRubyAnnotationRef CTRubyAnnotationCreateWithAttributes(byte alignment, byte overhang,
byte position, CFStringRef string, CFDictionaryRef attributes);
@Generated
@CFunction
public static native CTRubyAnnotationRef CTRubyAnnotationCreateCopy(CTRubyAnnotationRef rubyAnnotation);
@Generated
@CFunction
public static native byte CTRubyAnnotationGetAlignment(CTRubyAnnotationRef rubyAnnotation);
@Generated
@CFunction
public static native byte CTRubyAnnotationGetOverhang(CTRubyAnnotationRef rubyAnnotation);
@Generated
@CFunction
@NFloat
public static native double CTRubyAnnotationGetSizeFactor(CTRubyAnnotationRef rubyAnnotation);
@Generated
@CFunction
public static native CFStringRef CTRubyAnnotationGetTextForPosition(CTRubyAnnotationRef rubyAnnotation,
byte position);
@Generated
@CFunction
@NUInt
public static native long CTRunGetTypeID();
@Generated
@CFunction
@NInt
public static native long CTRunGetGlyphCount(CTRunRef run);
@Generated
@CFunction
public static native CFDictionaryRef CTRunGetAttributes(CTRunRef run);
@Generated
@CFunction
public static native int CTRunGetStatus(CTRunRef run);
@Generated
@CFunction
public static native ConstCharPtr CTRunGetGlyphsPtr(CTRunRef run);
@Generated
@CFunction
public static native void CTRunGetGlyphs(CTRunRef run, @ByValue CFRange range, CharPtr buffer);
@Generated
@CFunction
@UncertainReturn("Options: reference, array Fallback: reference")
public static native CGPoint CTRunGetPositionsPtr(CTRunRef run);
@Generated
@CFunction
public static native void CTRunGetPositions(CTRunRef run, @ByValue CFRange range,
@UncertainArgument("Options: reference, array Fallback: reference") CGPoint buffer);
@Generated
@CFunction
@UncertainReturn("Options: reference, array Fallback: reference")
public static native CGSize CTRunGetAdvancesPtr(CTRunRef run);
@Generated
@CFunction
public static native void CTRunGetAdvances(CTRunRef run, @ByValue CFRange range,
@UncertainArgument("Options: reference, array Fallback: reference") CGSize buffer);
@Generated
@CFunction
public static native ConstNIntPtr CTRunGetStringIndicesPtr(CTRunRef run);
@Generated
@CFunction
public static native void CTRunGetStringIndices(CTRunRef run, @ByValue CFRange range, NIntPtr buffer);
@Generated
@CFunction
@ByValue
public static native CFRange CTRunGetStringRange(CTRunRef run);
@Generated
@CFunction
public static native double CTRunGetTypographicBounds(CTRunRef run, @ByValue CFRange range, NFloatPtr ascent,
NFloatPtr descent, NFloatPtr leading);
@Generated
@CFunction
@ByValue
public static native CGRect CTRunGetImageBounds(CTRunRef run, CGContextRef context, @ByValue CFRange range);
@Generated
@CFunction
@ByValue
public static native CGAffineTransform CTRunGetTextMatrix(CTRunRef run);
@Generated
@CFunction
public static native void CTRunDraw(CTRunRef run, CGContextRef context, @ByValue CFRange range);
@Generated
@CFunction
@NUInt
public static native long CTRunDelegateGetTypeID();
@Generated
@CFunction
public static native CTRunDelegateRef CTRunDelegateCreate(
@UncertainArgument("Options: reference, array Fallback: reference") CTRunDelegateCallbacks callbacks,
VoidPtr refCon);
@Generated
@CFunction
public static native VoidPtr CTRunDelegateGetRefCon(CTRunDelegateRef runDelegate);
@Generated
@CFunction
@NUInt
public static native long CTTextTabGetTypeID();
@Generated
@CFunction
public static native CTTextTabRef CTTextTabCreate(byte alignment, double location, CFDictionaryRef options);
@Generated
@CFunction
public static native byte CTTextTabGetAlignment(CTTextTabRef tab);
@Generated
@CFunction
public static native double CTTextTabGetLocation(CTTextTabRef tab);
@Generated
@CFunction
public static native CFDictionaryRef CTTextTabGetOptions(CTTextTabRef tab);
@Generated
@CFunction
public static native int CTGetCoreTextVersion();
@Generated
@CVariable()
public static native CFStringRef kCTFontSymbolicTrait();
@Generated
@CVariable()
public static native CFStringRef kCTFontWeightTrait();
@Generated
@CVariable()
public static native CFStringRef kCTFontWidthTrait();
@Generated
@CVariable()
public static native CFStringRef kCTFontSlantTrait();
@Generated
@CVariable()
public static native CFStringRef kCTFontURLAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontNameAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontDisplayNameAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontFamilyNameAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontStyleNameAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontTraitsAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontSizeAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontMatrixAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontCascadeListAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontCharacterSetAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontLanguagesAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontBaselineAdjustAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontMacintoshEncodingsAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeaturesAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureSettingsAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontFixedAdvanceAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontOrientationAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontFormatAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontRegistrationScopeAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontPriorityAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontEnabledAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontDownloadableAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontDownloadedAttribute();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingSourceDescriptor();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingDescriptors();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingResult();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingPercentage();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingCurrentAssetSize();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingTotalDownloadedSize();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingTotalAssetSize();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptorMatchingError();
@Generated
@CVariable()
public static native CFStringRef kCTFontCopyrightNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFamilyNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontSubFamilyNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontStyleNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontUniqueNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFullNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVersionNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontPostScriptNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontTrademarkNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontManufacturerNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontDesignerNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontDescriptionNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVendorURLNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontDesignerURLNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontLicenseNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontLicenseURLNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontSampleTextNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontPostScriptCIDNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisIdentifierKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisMinimumValueKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisMaximumValueKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisDefaultValueKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontOpenTypeFeatureTag();
@Generated
@CVariable()
public static native CFStringRef kCTFontOpenTypeFeatureValue();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureTypeIdentifierKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureTypeNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureTypeExclusiveKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureTypeSelectorsKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureSelectorIdentifierKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureSelectorNameKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureSelectorDefaultKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontFeatureSelectorSettingKey();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassRoman();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassIdeographicCentered();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassIdeographicLow();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassIdeographicHigh();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassHanging();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassMath();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineReferenceFont();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineOriginalFont();
@Generated
@CVariable()
public static native CFStringRef kCTFontCollectionRemoveDuplicatesOption();
@Generated
@CVariable()
public static native CFStringRef kCTFontManagerErrorDomain();
@Generated
@CVariable()
public static native CFStringRef kCTFontManagerErrorFontURLsKey();
@Generated
@CVariable()
public static native CFStringRef kCTFontManagerRegisteredFontsChangedNotification();
@Generated
@CVariable()
public static native CFStringRef kCTFrameProgressionAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTFramePathFillRuleAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTFramePathWidthAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTFrameClippingPathsAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTFramePathClippingPathAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTTypesetterOptionDisableBidiProcessing();
@Generated
@CVariable()
public static native CFStringRef kCTTypesetterOptionForcedEmbeddingLevel();
@Generated
@CVariable()
public static native CFStringRef kCTRubyAnnotationSizeFactorAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTRubyAnnotationScaleToFitAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTFontAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTForegroundColorFromContextAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTKernAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTLigatureAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTForegroundColorAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTBackgroundColorAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTParagraphStyleAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTStrokeWidthAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTStrokeColorAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTUnderlineStyleAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTSuperscriptAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTUnderlineColorAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTVerticalFormsAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTHorizontalInVerticalFormsAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTGlyphInfoAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTCharacterShapeAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTLanguageAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTRunDelegateAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineClassAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineInfoAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineReferenceInfoAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTWritingDirectionAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTRubyAnnotationAttributeName();
@Generated
@CVariable()
public static native CFStringRef kCTTabColumnTerminatorsAttributeName();
@Runtime(CRuntime.class)
@Generated
public interface Block_CTFontDescriptorMatchFontDescriptorsWithProgressHandler {
@Generated
boolean call_CTFontDescriptorMatchFontDescriptorsWithProgressHandler(int arg0, CFDictionaryRef arg1);
}
@Runtime(CRuntime.class)
@Generated
public interface Function_CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback {
@Generated
@NInt
long call_CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback(CTFontDescriptorRef arg0,
CTFontDescriptorRef arg1, VoidPtr arg2);
}
@Runtime(CRuntime.class)
@Generated
public interface Block_CTLineEnumerateCaretOffsets {
@Generated
void call_CTLineEnumerateCaretOffsets(double arg0, @NInt long arg1, boolean arg2, BoolPtr arg3);
}
@Generated
@CVariable()
public static native CFStringRef kCTFontVariationAxisHiddenKey();
@Generated
@CVariable()
public static native CFStringRef kCTBaselineOffsetAttributeName();
}
|
3e1b9ee06d41738a7d469918320e2f485451127b | 4,693 | java | Java | src/main/java/za/co/sindi/jsonweb/jose/jws/JWSSignatureCryptographicAlgorithm.java | TheEliteGentleman/sindi-jsonweb | e0c79b5897f8362b6af1941978be83def366bed1 | [
"Apache-2.0"
] | null | null | null | src/main/java/za/co/sindi/jsonweb/jose/jws/JWSSignatureCryptographicAlgorithm.java | TheEliteGentleman/sindi-jsonweb | e0c79b5897f8362b6af1941978be83def366bed1 | [
"Apache-2.0"
] | null | null | null | src/main/java/za/co/sindi/jsonweb/jose/jws/JWSSignatureCryptographicAlgorithm.java | TheEliteGentleman/sindi-jsonweb | e0c79b5897f8362b6af1941978be83def366bed1 | [
"Apache-2.0"
] | null | null | null | 30.875 | 155 | 0.759642 | 11,699 | /**
*
*/
package za.co.sindi.jsonweb.jose.jws;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import za.co.sindi.common.utils.PreConditions;
/**
* @author Bienfait Sindi
* @since 12 June 2017
*
*/
public abstract class JWSSignatureCryptographicAlgorithm extends AbstractJWSCryptographicAlgorithm {
private final Signature SIGNATURE;
/**
* @param algorithm
* @param provider
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
protected JWSSignatureCryptographicAlgorithm(JWSAlgorithm algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
this(algorithm, (String)null);
}
/**
* @param algorithm
* @param provider
* @param miminumKeyLength
* @throws NoSuchAlgorithmException
*/
protected JWSSignatureCryptographicAlgorithm(JWSAlgorithm algorithm, final String provider) throws NoSuchAlgorithmException {
this(algorithm, Security.getProvider(provider));
}
/**
* @param algorithm
* @param provider
* @throws NoSuchAlgorithmException
*/
protected JWSSignatureCryptographicAlgorithm(JWSAlgorithm algorithm, Provider provider) throws NoSuchAlgorithmException {
super(algorithm);
SIGNATURE = provider != null ? Signature.getInstance(algorithm.getJcaAlgorithmName(), provider) : Signature.getInstance(algorithm.getJcaAlgorithmName());
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jws.JWSCryptographicAlgorithm#validateSignatureKey(java.security.Key)
*/
// @Override
protected void validateSignatureKey(Key key) {
// TODO Auto-generated method stub
PreConditions.checkArgument(key != null, "A Signature key is required.");
PreConditions.checkArgument(key instanceof PrivateKey, "A Private Key Signature is required.");
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jws.JWSCryptographicAlgorithm#validateVerificationKey(java.security.Key)
*/
// @Override
protected void validateVerificationKey(Key key) {
// TODO Auto-generated method stub
PreConditions.checkArgument(key != null, "A Signature key is required.");
PreConditions.checkArgument(key instanceof PublicKey, "A Public Key Signature key is required.");
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jwa.CryptographicAlgorithm#initSign(java.security.Key)
*/
@Override
public void initSign(Key key) throws GeneralSecurityException {
// TODO Auto-generated method stub
validateSignatureKey(key);
SIGNATURE.initSign((PrivateKey) key);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jws.JWSSignatureAlgorithm#initVerify(java.security.Key)
*/
@Override
public void initVerify(Key key) throws GeneralSecurityException {
// TODO Auto-generated method stub
validateVerificationKey(key);
SIGNATURE.initVerify((PublicKey) key);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jwa.CryptographicAlgorithm#update(byte[])
*/
@Override
public void update(byte[] input) throws GeneralSecurityException {
// TODO Auto-generated method stub
SIGNATURE.update(input);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jwa.CryptographicAlgorithm#update(byte[], int, int)
*/
@Override
public void update(byte[] input, int offset, int length) throws GeneralSecurityException {
// TODO Auto-generated method stub
SIGNATURE.update(input, offset, length);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jwa.CryptographicAlgorithm#update(java.nio.ByteBuffer)
*/
@Override
public void update(ByteBuffer input) throws GeneralSecurityException {
// TODO Auto-generated method stub
SIGNATURE.update(input);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jwa.CryptographicAlgorithm#compute()
*/
@Override
public byte[] compute() throws GeneralSecurityException {
// TODO Auto-generated method stub
return SIGNATURE.sign();
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jws.JWSSignatureVerificationAlgorithm#verify(byte[])
*/
@Override
public boolean verify(byte[] signature) throws GeneralSecurityException {
// TODO Auto-generated method stub
return SIGNATURE.verify(signature);
}
/* (non-Javadoc)
* @see za.co.sindi.jsonweb.jose.jws.JWSSignatureVerificationAlgorithm#verify(byte[], int, int)
*/
@Override
public boolean verify(byte[] signature, int offset, int length) throws GeneralSecurityException {
// TODO Auto-generated method stub
return SIGNATURE.verify(signature, offset, length);
}
}
|
3e1b9ef4efbcc3e482b5e53f0a32eb0387839f36 | 4,711 | java | Java | PicoCore/src/main/java/org/picojs/PacketReceiver.java | tonywestonuk/picowf | 6a32db126e92b26b1fc22f107b5e252509e8a5cb | [
"Apache-2.0"
] | null | null | null | PicoCore/src/main/java/org/picojs/PacketReceiver.java | tonywestonuk/picowf | 6a32db126e92b26b1fc22f107b5e252509e8a5cb | [
"Apache-2.0"
] | null | null | null | PicoCore/src/main/java/org/picojs/PacketReceiver.java | tonywestonuk/picowf | 6a32db126e92b26b1fc22f107b5e252509e8a5cb | [
"Apache-2.0"
] | null | null | null | 29.816456 | 104 | 0.706644 | 11,700 | package org.picojs;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.picojs.nanojson.JsonObject;
import org.picojs.nanojson.JsonParser;
import org.picojs.nanojson.JsonParserException;
@WebListener
public class PacketReceiver implements ServletContextListener {
private MulticastSocket mcastSocket;
private String picoServiceGroup;
private boolean debugMode=false;
public ConcurrentSkipListMap<String, Map<String, String>> getPacketCache() {
return packetCache;
}
private ConcurrentSkipListMap<String, Map<String,String>> packetCache = new ConcurrentSkipListMap<>();
private ScheduledExecutorService timeOutExecutor;
public void receivePacket() {
byte[] buf = new byte[1500];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
try {
mcastSocket.receive(recv); // if this times out, the loop exits.
JsonObject jp=null;
try {
if (debugMode)
System.out.println(new String(recv.getData(), 0, recv.getLength()));
jp = JsonParser.object().from(new ByteArrayInputStream(recv.getData(), 0, recv.getLength()));
} catch (JsonParserException e) {
throw new RuntimeException(e);
}
ConcurrentHashMap<String, String> packet = new ConcurrentHashMap<>();
for (String key:jp.keySet()){
packet.put(key, jp.getString(key));
}
packet.put("lastSeen", Long.toString(System.currentTimeMillis()));
String packetServiceGroup = packet.get("serviceGroup");
if ((packetServiceGroup==null && picoServiceGroup==null)
|| picoServiceGroup.equals(packet.get("serviceGroup"))){
if ("true".equals(packet.get("shutdown"))){
packetCache.remove(packet.get("uuid"));
} else{
packetCache.put(packet.get("uuid"), packet);
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException e) {
//**** at this point.... the while true loop ends...
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Removed old services who've we've not heard from in 30 seconds.
public void timeOut(){
Long timeOut=System.currentTimeMillis()-30000; // 30 seconds time out.
Iterator<Entry<String, Map<String,String>>> it= packetCache.entrySet().iterator();
while (it.hasNext()) {
Entry<String,Map<String,String>> entry=it.next();
long lastSeen = Long.parseLong(entry.getValue().get("lastSeen"));
if (lastSeen<timeOut){
System.out.println("removed "+entry.getValue().get("uuid"));
it.remove();
}
}
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
timeOutExecutor.shutdown();
try {
timeOutExecutor.awaitTermination(10,TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mcastSocket.close();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
arg0.getServletContext().setAttribute("packetReceiver", this);
ServletContext servletContext = arg0.getServletContext();
debugMode=servletContext.getInitParameter("pico_debug")!=null;
this.picoServiceGroup = servletContext.getInitParameter("pico_serviceGroup");
try {
mcastSocket = new MulticastSocket(MulticastEnabler.port);
//mcastSocket.setInterface(InetAddress.getLocalHost());
System.out.println(MulticastEnabler.mCastAddress);
mcastSocket.joinGroup(MulticastEnabler.mCastAddress);
mcastSocket.setSoTimeout(100);
} catch (IOException e) {
throw new RuntimeException(e);
}
timeOutExecutor = Executors.newSingleThreadScheduledExecutor();
timeOutExecutor.scheduleWithFixedDelay(()->{timeOut();}, 1, 1, TimeUnit.SECONDS);
timeOutExecutor.scheduleWithFixedDelay(()->{receivePacket();}, 1, 1, TimeUnit.MILLISECONDS);
}
}
|
3e1b9ef7b00bec00940c72ed512a0620e5c2c30f | 148 | java | Java | java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 5 | 2015-12-19T15:27:30.000Z | 2019-08-17T10:07:23.000Z | java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 18.5 | 45 | 0.608108 | 11,701 | public class A {
private static final class Inner {
public Inner(Integer param) {
String s<caret>tr = param.toString();
}
}
}
|
3e1b9f831a7bd90fa8b8753a61cb3ec4239d09a5 | 1,292 | java | Java | kawwa2-tapestry/src/test/java/net/atos/kawwaportal/components/test/data/User.java | got5/KAWWA | d2a8ee49eaf61fb672135709a009c20d8aa17fad | [
"MIT"
] | 7 | 2015-04-24T07:29:45.000Z | 2019-02-19T17:00:58.000Z | kawwa2-tapestry/src/test/java/net/atos/kawwaportal/components/test/data/User.java | got5/KAWWA | d2a8ee49eaf61fb672135709a009c20d8aa17fad | [
"MIT"
] | 48 | 2015-01-20T16:21:47.000Z | 2018-08-23T14:40:26.000Z | kawwa2-tapestry/src/test/java/net/atos/kawwaportal/components/test/data/User.java | got5/KAWWA | d2a8ee49eaf61fb672135709a009c20d8aa17fad | [
"MIT"
] | 11 | 2015-01-14T11:55:31.000Z | 2021-03-26T07:59:46.000Z | 17.944444 | 73 | 0.660217 | 11,702 | package net.atos.kawwaportal.components.test.data;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import java.util.List;
import java.util.UUID;
public class User {
public final String uuid = UUID.randomUUID().toString();
private String nom;
public final List<User> children = CollectionFactory.newList();
public User(String nom) {
super();
this.nom = nom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public static final User ROOT = new User("<root>");
public User addChildrenNamed(String... names){
for(String name : names){
children.add(new User(name));
}
return this;
}
public User addChild(User user){
children.add(user);
return this;
}
public User seek(String uuid){
if(this.uuid.equals(uuid)) return this;
for(User child : children){
User match = child.seek(uuid);
if(match != null) return match;
}
return null;
}
static {
ROOT.addChild(new User("Renault")
.addChild(new User("Mégane"))
.addChild(new User("Clio")
.addChildrenNamed("Clio Campus", "Clio Sport")
)
)
.addChild(new User("Ferarri").addChildrenNamed("F430", "California"));
}
}
|
3e1ba05125597a10e46cc1e3ffd98378f78bce93 | 2,690 | java | Java | src/main/java/cat/yoink/dream/impl/module/exploit/NoBreakAnimation.java | PlutoSolutions/moneymodplus2-src | f83ffa3df1cc8ba8b55dbc555dd174114f914327 | [
"WTFPL"
] | 12 | 2021-05-07T15:09:35.000Z | 2021-11-09T11:10:01.000Z | src/main/java/cat/yoink/dream/impl/module/exploit/NoBreakAnimation.java | PlutoSolutions/moneymodplus2-src | f83ffa3df1cc8ba8b55dbc555dd174114f914327 | [
"WTFPL"
] | 2 | 2021-05-07T15:06:43.000Z | 2021-08-12T05:45:37.000Z | src/main/java/cat/yoink/dream/impl/module/exploit/NoBreakAnimation.java | PlutoSolutions/moneymodplus2-src | f83ffa3df1cc8ba8b55dbc555dd174114f914327 | [
"WTFPL"
] | 4 | 2021-05-07T17:05:10.000Z | 2021-11-18T20:08:38.000Z | 32.409639 | 107 | 0.760223 | 11,703 | package cat.yoink.dream.impl.module.exploit;
import cat.yoink.dream.api.module.Category;
import cat.yoink.dream.api.module.Module;
import cat.yoink.dream.impl.event.PacketReceiveEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class NoBreakAnimation extends Module {
private boolean isMining;
private BlockPos lastPos;
private EnumFacing lastFacing;
public NoBreakAnimation(String name, String description, Category category) {
super(name, description, category);
this.isMining = false;
this.lastPos = null;
this.lastFacing = null;
// TODO Auto-generated constructor stub
}
@SubscribeEvent
public void recp(PacketReceiveEvent event) {
if (event.getPacket() instanceof CPacketPlayerDigging) {
final CPacketPlayerDigging cPacketPlayerDigging = (CPacketPlayerDigging) event.getPacket();
for (final Entity entity : mc.world.getEntitiesWithinAABBExcludingEntity((Entity) null,
new AxisAlignedBB(cPacketPlayerDigging.getPosition()))) {
if (entity instanceof EntityEnderCrystal) {
this.resetMining();
return;
}
if (entity instanceof EntityLivingBase) {
this.resetMining();
return;
}
}
if (cPacketPlayerDigging.getAction().equals((Object) CPacketPlayerDigging.Action.START_DESTROY_BLOCK)) {
this.isMining = true;
this.setMiningInfo(cPacketPlayerDigging.getPosition(), cPacketPlayerDigging.getFacing());
}
if (cPacketPlayerDigging.getAction().equals((Object) CPacketPlayerDigging.Action.STOP_DESTROY_BLOCK)) {
this.resetMining();
}
}
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (mc == null || mc.player == null)
return;
if (!mc.gameSettings.keyBindAttack.isKeyDown()) {
this.resetMining();
return;
}
if (this.isMining && this.lastPos != null && this.lastFacing != null) {
mc.player.connection
.sendPacket((Packet) new CPacketPlayerDigging(CPacketPlayerDigging.Action.ABORT_DESTROY_BLOCK,
this.lastPos, this.lastFacing));
}
}
private void setMiningInfo(final BlockPos lastPos, final EnumFacing lastFacing) {
this.lastPos = lastPos;
this.lastFacing = lastFacing;
}
public void resetMining() {
this.isMining = false;
this.lastPos = null;
this.lastFacing = null;
}
}
|
3e1ba17f978026f65ee6a3612493311eb2c08594 | 5,413 | java | Java | sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TemplateLink.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TemplateLink.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/TemplateLink.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 32.220238 | 120 | 0.662294 | 11,704 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.resources.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Entity representing the reference to the template. */
@Fluent
public final class TemplateLink {
@JsonIgnore private final ClientLogger logger = new ClientLogger(TemplateLink.class);
/*
* The URI of the template to deploy. Use either the uri or id property,
* but not both.
*/
@JsonProperty(value = "uri")
private String uri;
/*
* The resource id of a Template Spec. Use either the id or uri property,
* but not both.
*/
@JsonProperty(value = "id")
private String id;
/*
* The relativePath property can be used to deploy a linked template at a
* location relative to the parent. If the parent template was linked with
* a TemplateSpec, this will reference an artifact in the TemplateSpec. If
* the parent was linked with a URI, the child deployment will be a
* combination of the parent and relativePath URIs
*/
@JsonProperty(value = "relativePath")
private String relativePath;
/*
* If included, must match the ContentVersion in the template.
*/
@JsonProperty(value = "contentVersion")
private String contentVersion;
/*
* The query string (for example, a SAS token) to be used with the
* templateLink URI.
*/
@JsonProperty(value = "queryString")
private String queryString;
/**
* Get the uri property: The URI of the template to deploy. Use either the uri or id property, but not both.
*
* @return the uri value.
*/
public String uri() {
return this.uri;
}
/**
* Set the uri property: The URI of the template to deploy. Use either the uri or id property, but not both.
*
* @param uri the uri value to set.
* @return the TemplateLink object itself.
*/
public TemplateLink withUri(String uri) {
this.uri = uri;
return this;
}
/**
* Get the id property: The resource id of a Template Spec. Use either the id or uri property, but not both.
*
* @return the id value.
*/
public String id() {
return this.id;
}
/**
* Set the id property: The resource id of a Template Spec. Use either the id or uri property, but not both.
*
* @param id the id value to set.
* @return the TemplateLink object itself.
*/
public TemplateLink withId(String id) {
this.id = id;
return this;
}
/**
* Get the relativePath property: The relativePath property can be used to deploy a linked template at a location
* relative to the parent. If the parent template was linked with a TemplateSpec, this will reference an artifact in
* the TemplateSpec. If the parent was linked with a URI, the child deployment will be a combination of the parent
* and relativePath URIs.
*
* @return the relativePath value.
*/
public String relativePath() {
return this.relativePath;
}
/**
* Set the relativePath property: The relativePath property can be used to deploy a linked template at a location
* relative to the parent. If the parent template was linked with a TemplateSpec, this will reference an artifact in
* the TemplateSpec. If the parent was linked with a URI, the child deployment will be a combination of the parent
* and relativePath URIs.
*
* @param relativePath the relativePath value to set.
* @return the TemplateLink object itself.
*/
public TemplateLink withRelativePath(String relativePath) {
this.relativePath = relativePath;
return this;
}
/**
* Get the contentVersion property: If included, must match the ContentVersion in the template.
*
* @return the contentVersion value.
*/
public String contentVersion() {
return this.contentVersion;
}
/**
* Set the contentVersion property: If included, must match the ContentVersion in the template.
*
* @param contentVersion the contentVersion value to set.
* @return the TemplateLink object itself.
*/
public TemplateLink withContentVersion(String contentVersion) {
this.contentVersion = contentVersion;
return this;
}
/**
* Get the queryString property: The query string (for example, a SAS token) to be used with the templateLink URI.
*
* @return the queryString value.
*/
public String queryString() {
return this.queryString;
}
/**
* Set the queryString property: The query string (for example, a SAS token) to be used with the templateLink URI.
*
* @param queryString the queryString value to set.
* @return the TemplateLink object itself.
*/
public TemplateLink withQueryString(String queryString) {
this.queryString = queryString;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
3e1ba182a6c2a7d7f3c2c98e90b88405540506ae | 1,227 | java | Java | Students/Bologa M. Marius - Vasile/Zoowsome/src/javasmmr/zoowsome/controllers/AddController.java | JavaSummer/JavaMainRepo | 262a3299b0135ba40ea4018a184dd3fdbf468d2e | [
"Apache-2.0"
] | 31 | 2015-06-22T08:12:05.000Z | 2021-01-09T08:39:16.000Z | Students/Bologa M. Marius - Vasile/Zoowsome/src/javasmmr/zoowsome/controllers/AddController.java | souravsingpardeshi/JavaMainRepo | 262a3299b0135ba40ea4018a184dd3fdbf468d2e | [
"Apache-2.0"
] | 77 | 2015-06-24T05:40:30.000Z | 2020-08-25T09:00:11.000Z | Students/Bologa M. Marius - Vasile/Zoowsome/src/javasmmr/zoowsome/controllers/AddController.java | souravsingpardeshi/JavaMainRepo | 262a3299b0135ba40ea4018a184dd3fdbf468d2e | [
"Apache-2.0"
] | 68 | 2015-06-22T08:19:35.000Z | 2021-08-17T09:29:39.000Z | 22.309091 | 77 | 0.726161 | 11,705 | package javasmmr.zoowsome.controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javasmmr.zoowsome.views.AddFrame;
import javasmmr.zoowsome.views.AnimalFrame;
import javasmmr.zoowsome.views.EmployeeFrame;
/**
*
* @author Marius Bologa
*
*/
public class AddController extends AbstractController {
/**
*
* @param addFrame
* If we need to add a new frame.
* @param hasBackButton
* If the back button was pushed.
*/
public AddController(final AddFrame addFrame, final boolean hasBackButton) {
super(addFrame, hasBackButton);
addFrame.setAnimal(new AnimalButtonActionListener());
addFrame.setEmployee(new EmployeeButtonActionListener());
}
/**
*
* @author Marius Bologa
*
*/
public class AnimalButtonActionListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
new AnimalController(new AnimalFrame("Animal"), true);
}
}
/**
*
* @author Marius Bologa
*
*/
public class EmployeeButtonActionListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
new EmployeeController(new EmployeeFrame("Employee"), true);
}
}
} |
3e1ba200042f261703531d0386d43c3ac1e439b1 | 11,774 | java | Java | Demo/app/src/main/java/com/example/hakeem/demo/utilities/ImageProcess.java | mhakeem531/my_graduation_project | 26c5ea963e233a3433e2ad8c5e9625f4f3d11d13 | [
"Apache-2.0"
] | null | null | null | Demo/app/src/main/java/com/example/hakeem/demo/utilities/ImageProcess.java | mhakeem531/my_graduation_project | 26c5ea963e233a3433e2ad8c5e9625f4f3d11d13 | [
"Apache-2.0"
] | null | null | null | Demo/app/src/main/java/com/example/hakeem/demo/utilities/ImageProcess.java | mhakeem531/my_graduation_project | 26c5ea963e233a3433e2ad8c5e9625f4f3d11d13 | [
"Apache-2.0"
] | null | null | null | 33.73639 | 170 | 0.636912 | 11,706 | package com.example.hakeem.demo.utilities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public final class ImageProcess {
/**
* this method to name image file uploaded as feedback
* name will be
* username + current datetime
*
* @return String filename
*/
public static String getPhotoUploadedName(String userid) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
return "JPEG_" + timeStamp + "_" + userid + ".jpg";
}
/**
* Resamples the captured photo to fit the screen for better memory usage.
*
* @param context The application context.
* @param imagePath The path of the photo to be resampled.
* @return The resampled bitmap
*/
public static Bitmap resamplePic(Context context, String imagePath) {
// Get device screen size information
DisplayMetrics metrics = new DisplayMetrics();
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert manager != null;
manager.getDefaultDisplay().getMetrics(metrics);
int targetH = metrics.heightPixels;
int targetW = metrics.widthPixels;
// Get the dimensions of the original bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
return BitmapFactory.decodeFile(imagePath);
}
/**
* Deletes image file for a given path.
*
* @param context The application context.
* @param imagePath The path of the photo to be deleted.
*/
public static boolean deleteImageFile(Context context, String imagePath) {
// Get the file
File imageFile = new File(imagePath);
// Delete the image
boolean deleted = imageFile.delete();
// If there is an error deleting the file, show a Toast
if (!deleted) {
String errorMessage = "error";
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
}
return deleted;
}
/**
* Creates the temporary image file in the cache directory.
*
* @return The temporary image file.
* @throws IOException Thrown if there is an error creating the file
*/
public static File createTempImageFile(Context context) throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getExternalCacheDir();
Log.e("storageDir.toString()", storageDir.toString());
return File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
}
// And to convert the image URI to the direct file system path of the image file
public static String getRealPathFromURI(Context context, Uri contentUri) {
// can post image
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public static Bitmap rotateBy90Degree(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
return Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
}
public static void uploadImage(final Context context, Bitmap imageAsBitmap, final String imageFileName, final String userId) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageAsBitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
@SuppressLint("StaticFieldLeak")
class AsyncTaskUploadClass extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog = ProgressDialog.show(context,"It posting...","Please Wait",false,false);
}
@Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
Toast.makeText(context, string1, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String, String> HashMapParams = new HashMap<>();
HashMapParams.put("file", ConvertImage);
HashMapParams.put("file_name", imageFileName);
HashMapParams.put("user_id", userId);
String FinalData = imageProcessClass.ImageHttpRequest(Variables.UPLOAD_FEEDBACK_PHOTO_ONLY, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
public static class ImageProcessClass {
public String ImageHttpRequest(String requestURL, HashMap<String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(requestURL);
HttpURLConnection httpURLConnection;
OutputStream outputStream;
BufferedWriter bufferedWriter;
BufferedReader bufferedReader;
int RC;
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(bufferedWriterDataFN(PData));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
RC = httpURLConnection.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReader.readLine()) != null) {
stringBuilder.append(RC2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {
StringBuilder stringBuilder = new StringBuilder();
boolean check = true;
for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
if (check)
check = false;
else
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilder.toString();
}
}
public static void uploadCompleteFeedback(final Context context, final String feedbackText, Bitmap imageAsBitmap, final String imageFileName, final String userId) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageAsBitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
@SuppressLint("StaticFieldLeak")
class AsyncTaskUploadClass extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog = ProgressDialog.show(context,"It posting...","Please Wait",false,false);
}
@Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
Toast.makeText(context, string1, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String, String> HashMapParams = new HashMap<>();
HashMapParams.put("user_id", userId);
HashMapParams.put("file_name", imageFileName);
HashMapParams.put("file", ConvertImage);
HashMapParams.put("feedback_text", feedbackText);
// String FinalData = imageProcessClass.ImageHttpRequest("http://192.168.1.4/guidak_files/feedback_scripts/upload_feedback_photo_text.php", HashMapParams);
String FinalData = imageProcessClass.ImageHttpRequest(Variables.UPLOAD_FEEDBACK_TEXT_PHOTO, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
} |
3e1ba32b8a9741b026dac7a4ea284eef23eb7f04 | 9,223 | java | Java | python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAssignmentStatementImpl.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAssignmentStatementImpl.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2022-02-19T09:45:05.000Z | 2022-02-27T20:32:55.000Z | python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAssignmentStatementImpl.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-03-10T02:53:51.000Z | 2020-03-10T02:53:51.000Z | 35.88716 | 140 | 0.693267 | 11,707 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.impl;
import com.google.common.collect.Lists;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.*;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author yole
*/
public class PyAssignmentStatementImpl extends PyElementImpl implements PyAssignmentStatement {
private volatile PyExpression @Nullable [] myTargets;
public PyAssignmentStatementImpl(ASTNode astNode) {
super(astNode);
}
@Override
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyAssignmentStatement(this);
}
@Override
public PyExpression @NotNull [] getTargets() {
PyExpression[] result = myTargets;
if (result == null) {
myTargets = result = calcTargets(false);
}
return result;
}
@Override
public PyExpression @NotNull [] getRawTargets() {
return calcTargets(true);
}
private PyExpression @NotNull [] calcTargets(boolean raw) {
final ASTNode[] eqSigns = getNode().getChildren(TokenSet.create(PyTokenTypes.EQ));
if (eqSigns.length == 0) {
return PyExpression.EMPTY_ARRAY;
}
final ASTNode lastEq = eqSigns[eqSigns.length - 1];
List<PyExpression> candidates = new ArrayList<>();
ASTNode node = getNode().getFirstChildNode();
while (node != null && node != lastEq) {
final PsiElement psi = node.getPsi();
if (psi instanceof PyExpression) {
if (raw) {
candidates.add((PyExpression) psi);
}
else {
addCandidate(candidates, (PyExpression)psi);
}
}
node = node.getTreeNext();
}
List<PyExpression> targets = new ArrayList<>();
for (PyExpression expr : candidates) { // only filter out targets
if (raw ||
expr instanceof PyTargetExpression ||
expr instanceof PyReferenceExpression ||
expr instanceof PySubscriptionExpression ||
expr instanceof PySliceExpression) {
targets.add(expr);
}
}
return targets.toArray(PyExpression.EMPTY_ARRAY);
}
@Nullable
@Override
public PyAnnotation getAnnotation() {
return findChildByClass(PyAnnotation.class);
}
@Nullable
@Override
public String getAnnotationValue() {
return getAnnotationContentFromPsi(this);
}
private static void addCandidate(List<PyExpression> candidates, PyExpression psi) {
if (psi instanceof PyParenthesizedExpression) {
addCandidate(candidates, ((PyParenthesizedExpression)psi).getContainedExpression());
}
else if (psi instanceof PySequenceExpression) {
final PyExpression[] pyExpressions = ((PySequenceExpression)psi).getElements();
for (PyExpression pyExpression : pyExpressions) {
addCandidate(candidates, pyExpression);
}
}
else if (psi instanceof PyStarExpression) {
final PyExpression expression = ((PyStarExpression)psi).getExpression();
if (expression != null) {
addCandidate(candidates, expression);
}
}
else {
candidates.add(psi);
}
}
/**
* @return rightmost expression in statement, which is supposedly the assigned value, or null.
*/
@Override
@Nullable
public PyExpression getAssignedValue() {
PsiElement child = getLastChild();
while (child != null && !(child instanceof PyExpression)) {
if (child instanceof PsiErrorElement) return null; // incomplete assignment operator can't be analyzed properly, bail out.
child = child.getPrevSibling();
}
return (PyExpression)child;
}
@Override
@NotNull
public List<Pair<PyExpression, PyExpression>> getTargetsToValuesMapping() {
List<Pair<PyExpression, PyExpression>> ret = new SmartList<>();
if (!PsiTreeUtil.hasErrorElements(this)) { // no parse errors
PyExpression[] constituents = PsiTreeUtil.getChildrenOfType(this, PyExpression.class); // "a = b = c" -> [a, b, c]
if (constituents != null && constituents.length > 1) {
PyExpression rhs = constituents[constituents.length - 1]; // last
List<PyExpression> lhses = Lists.newArrayList(constituents);
if (lhses.size()>0) lhses.remove(lhses.size()-1); // copy all but last; most often it's one element.
for (PyExpression lhs : lhses) mapToValues(lhs, rhs, ret);
}
}
return ret;
}
@Override
@Nullable
public PyExpression getLeftHandSideExpression() {
PsiElement child = getFirstChild();
while (child != null && !(child instanceof PyExpression)) {
if (child instanceof PsiErrorElement) return null; // incomplete assignment operator can't be analyzed properly, bail out.
child = child.getPrevSibling();
}
return (PyExpression)child;
}
@Override
public boolean isAssignmentTo(@NotNull String name) {
PyExpression lhs = getLeftHandSideExpression();
return lhs instanceof PyTargetExpression && name.equals(lhs.getName());
}
private static void mapToValues(PyExpression lhs, PyExpression rhs, List<Pair<PyExpression, PyExpression>> map) {
// cast for convenience
PySequenceExpression lhs_tuple = null;
PyExpression lhs_one = null;
if (lhs instanceof PySequenceExpression) lhs_tuple = (PySequenceExpression)lhs;
else if (lhs != null) lhs_one = lhs;
PySequenceExpression rhs_tuple = null;
PyExpression rhs_one = null;
if (rhs instanceof PyParenthesizedExpression) {
PyExpression exp = ((PyParenthesizedExpression)rhs).getContainedExpression();
if (exp instanceof PyTupleExpression)
rhs_tuple = (PySequenceExpression)exp;
else
rhs_one = rhs;
}
else if (rhs instanceof PySequenceExpression) rhs_tuple = (PySequenceExpression)rhs;
else if (rhs != null) rhs_one = rhs;
//
if (lhs_one != null) { // single LHS, single RHS (direct mapping) or multiple RHS (packing)
map.add(Pair.create(lhs_one, rhs));
}
else if (lhs_tuple != null && rhs_one != null) { // multiple LHS, single RHS: unpacking
// PY-2648, PY-2649
PyElementGenerator elementGenerator = PyElementGenerator.getInstance(rhs_one.getProject());
final LanguageLevel languageLevel = LanguageLevel.forElement(lhs);
int counter = 0;
for (PyExpression tuple_elt : lhs_tuple.getElements()) {
try {
final PyExpression expression =
elementGenerator.createExpressionFromText(languageLevel, "(" + rhs_one.getText() + ")[" + counter + "]");
map.add(Pair.create(tuple_elt, expression));
}
catch (IncorrectOperationException e) {
// not parsed, no problem
}
++counter;
}
}
else if (lhs_tuple != null && rhs_tuple != null) { // multiple both sides: piecewise mapping
final List<PyExpression> lhsTupleElements = Arrays.asList(lhs_tuple.getElements());
final List<PyExpression> rhsTupleElements = Arrays.asList(rhs_tuple.getElements());
final int size = Math.max(lhsTupleElements.size(), rhsTupleElements.size());
map.addAll(StreamEx.zip(alignToSize(lhsTupleElements, size), alignToSize(rhsTupleElements, size), Pair::create).toList());
}
}
@NotNull
private static <T> List<T> alignToSize(@NotNull List<T> list, int size) {
return list.size() == size
? list
: IntStreamEx.range(size).mapToObj(index -> ContainerUtil.getOrElse(list, index, null)).toList();
}
@Override
@NotNull
public List<PsiNamedElement> getNamedElements() {
final List<PyExpression> expressions = PyUtil.flattenedParensAndStars(getTargets());
List<PsiNamedElement> result = new ArrayList<>();
for (PyExpression expression : expressions) {
if (expression instanceof PyQualifiedExpression && ((PyQualifiedExpression)expression).isQualified()) {
continue;
}
if (expression instanceof PsiNamedElement) {
result.add((PsiNamedElement)expression);
}
}
return result;
}
@Nullable
public PsiNamedElement getNamedElement(@NotNull final String the_name) {
// performance: check simple case first
PyExpression[] targets = getTargets();
if (targets.length == 1 && targets[0] instanceof PyTargetExpression) {
PyTargetExpression target = (PyTargetExpression)targets[0];
return !target.isQualified() && the_name.equals(target.getName()) ? target : null;
}
return PyUtil.IterHelper.findName(getNamedElements(), the_name);
}
@Override
public void subtreeChanged() {
super.subtreeChanged();
myTargets = null;
}
}
|
3e1ba37f457973290a29d7ca52c968c273b62d10 | 438 | java | Java | src/org/aikodi/chameleon/support/statement/DefaultLabel.java | markovandooren/chameleon | c93d794bdba38bd27529055a1e71aa381000ec42 | [
"MIT"
] | 1 | 2015-06-11T11:23:15.000Z | 2015-06-11T11:23:15.000Z | src/org/aikodi/chameleon/support/statement/DefaultLabel.java | markovandooren/chameleon | c93d794bdba38bd27529055a1e71aa381000ec42 | [
"MIT"
] | 2 | 2015-04-16T14:42:23.000Z | 2016-10-07T10:14:09.000Z | src/org/aikodi/chameleon/support/statement/DefaultLabel.java | markovandooren/chameleon | c93d794bdba38bd27529055a1e71aa381000ec42 | [
"MIT"
] | 1 | 2015-11-19T17:44:59.000Z | 2015-11-19T17:44:59.000Z | 18.25 | 57 | 0.742009 | 11,708 | package org.aikodi.chameleon.support.statement;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
/**
* @author Marko van Dooren
*/
public class DefaultLabel extends SwitchLabel {
public DefaultLabel() {
}
@Override
protected DefaultLabel cloneSelf() {
return new DefaultLabel();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
}
|
3e1ba38ed74afe36753ebef4b3c8b15108fed642 | 212 | java | Java | src/test/java/wing/api/user/UserApplicationTests.java | multicampus-msa/wing-user | 110b5d5ae84807a3d0d371bb3ec034432ebe0198 | [
"MIT"
] | null | null | null | src/test/java/wing/api/user/UserApplicationTests.java | multicampus-msa/wing-user | 110b5d5ae84807a3d0d371bb3ec034432ebe0198 | [
"MIT"
] | null | null | null | src/test/java/wing/api/user/UserApplicationTests.java | multicampus-msa/wing-user | 110b5d5ae84807a3d0d371bb3ec034432ebe0198 | [
"MIT"
] | null | null | null | 15.142857 | 60 | 0.745283 | 11,709 | package wing.api.user;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserApplicationTests {
@Test
void contextLoads() {
}
}
|
3e1ba3e5e5c6f21d01864cc80c4cacf2c386e52b | 1,060 | java | Java | Android/doraemonkit-no-op/src/main/java/com/didichuxing/doraemonkit/ui/base/TouchProxy.java | ghbhaha/DoraemonKit | e7977e7b56d65bab5f49940e1b5a89e1bb8506be | [
"Apache-2.0"
] | 1 | 2021-01-29T02:24:22.000Z | 2021-01-29T02:24:22.000Z | Android/doraemonkit-no-op/src/main/java/com/didichuxing/doraemonkit/ui/base/TouchProxy.java | wangfeng19930909/DoraemonKit | 231dd7f6a5a946ad12b8a1a442c24d53f07115fd | [
"Apache-2.0"
] | null | null | null | Android/doraemonkit-no-op/src/main/java/com/didichuxing/doraemonkit/ui/base/TouchProxy.java | wangfeng19930909/DoraemonKit | 231dd7f6a5a946ad12b8a1a442c24d53f07115fd | [
"Apache-2.0"
] | 1 | 2019-11-29T11:42:15.000Z | 2019-11-29T11:42:15.000Z | 21.632653 | 70 | 0.684906 | 11,710 | package com.didichuxing.doraemonkit.ui.base;
import android.view.MotionEvent;
import android.view.View;
/**
* @author wanglikun
* touch 事件代理 解决点击和触摸事件的冲突
*/
public class TouchProxy {
private static final int MIN_DISTANCE_MOVE = 4;
private static final int MIN_TAP_TIME = 1000;
private OnTouchEventListener mEventListener;
private int mLastX;
private int mLastY;
private int mStartX;
private int mStartY;
private TouchState mState = TouchState.STATE_STOP;
public TouchProxy(OnTouchEventListener eventListener) {
mEventListener = eventListener;
}
public void setEventListener(OnTouchEventListener eventListener) {
mEventListener = eventListener;
}
private enum TouchState {
STATE_MOVE,
STATE_STOP
}
public boolean onTouchEvent(View v, MotionEvent event) {
return true;
}
public interface OnTouchEventListener {
void onMove(int x, int y, int dx, int dy);
void onUp(int x, int y);
void onDown(int x, int y);
}
}
|
3e1ba3ea2c554654b2c176444d755abad314dded | 358 | java | Java | spring-chu-beans/src/main/java/com/chu/beans/factory/BeanFactoryAware.java | chudichen/spring-source-code | afe7c3561c23eb29cc058385af054ac6cedf5bd9 | [
"Apache-2.0"
] | null | null | null | spring-chu-beans/src/main/java/com/chu/beans/factory/BeanFactoryAware.java | chudichen/spring-source-code | afe7c3561c23eb29cc058385af054ac6cedf5bd9 | [
"Apache-2.0"
] | null | null | null | spring-chu-beans/src/main/java/com/chu/beans/factory/BeanFactoryAware.java | chudichen/spring-source-code | afe7c3561c23eb29cc058385af054ac6cedf5bd9 | [
"Apache-2.0"
] | null | null | null | 17.047619 | 68 | 0.726257 | 11,711 | package com.chu.beans.factory;
import com.chu.beans.BeansException;
/**
* 实现该接口,能感知所属BeanFactory
*
* @author chudichen
* @date 2021-04-01
*/
public interface BeanFactoryAware extends Aware {
/**
* 设置bean工厂
*
* @param beanFactory 工厂
* @throws BeansException 未找到bean
*/
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
|
3e1ba4065161a8ebeb220732b26f2faae3d13bc7 | 433 | java | Java | references/bcb_chosen_clones/selected#2245750#230#237.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 23 | 2018-10-03T15:02:53.000Z | 2021-09-16T11:07:36.000Z | references/bcb_chosen_clones/selected#2245750#230#237.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 18 | 2019-02-10T04:52:54.000Z | 2022-01-25T02:14:40.000Z | references/bcb_chosen_clones/selected#2245750#230#237.java | cragkhit/Siamese | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 19 | 2018-11-16T13:39:05.000Z | 2021-09-05T23:59:30.000Z | 48.111111 | 82 | 0.706697 | 11,712 | public static void copyFile(File file, String pathExport) throws IOException {
File out = new File(pathExport);
FileChannel sourceChannel = new FileInputStream(file).getChannel();
FileChannel destinationChannel = new FileOutputStream(out).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close();
destinationChannel.close();
}
|
3e1ba464f7bdf13aa14aab52409af6e43d122acf | 4,666 | java | Java | corpus/class/tomcat70/1692.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/tomcat70/1692.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/tomcat70/1692.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 32.859155 | 77 | 0.640377 | 11,713 | /*
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.jasper.xmlparser;
/**
* This class is used as a structure to pass text contained in the underlying
* character buffer of the scanner. The offset and length fields allow the
* buffer to be re-used without creating new character arrays.
* <p>
* <strong>Note:</strong> Methods that are passed an XMLString structure
* should consider the contents read-only and not make any modifications
* to the contents of the buffer. The method receiving this structure
* should also not modify the offset and length if this structure (or
* the values of this structure) are passed to another method.
* <p>
* <strong>Note:</strong> Methods that are passed an XMLString structure
* are required to copy the information out of the buffer if it is to be
* saved for use beyond the scope of the method. The contents of the
* structure are volatile and the contents of the character buffer cannot
* be assured once the method that is passed this structure returns.
* Therefore, methods passed this structure should not save any reference
* to the structure or the character array contained in the structure.
*
* @author Eric Ye, IBM
* @author Andy Clark, IBM
*/
public class XMLString {
//
// Data
//
/** The character array. */
public char[] ch;
/** The offset into the character array. */
public int offset;
/** The length of characters from the offset. */
public int length;
/** Default constructor. */
public XMLString() {
}
// <init>()
//
// Public methods
//
/**
* Initializes the contents of the XMLString structure with the
* specified values.
*
* @param ch The character array.
* @param offset The offset into the character array.
* @param length The length of characters from the offset.
*/
public void setValues(char[] ch, int offset, int length) {
this.ch = ch;
this.offset = offset;
this.length = length;
}
// setValues(char[],int,int)
/**
* Initializes the contents of the XMLString structure with copies
* of the given string structure.
* <p>
* <strong>Note:</strong> This does not copy the character array;
* only the reference to the array is copied.
*
* @param s
*/
public void setValues(XMLString s) {
setValues(s.ch, s.offset, s.length);
}
// setValues(XMLString)
/** Resets all of the values to their defaults. */
public void clear() {
this.ch = null;
this.offset = 0;
this.length = -1;
}
// clear()
/**
* Returns true if the contents of this XMLString structure and
* the specified string are equal.
*
* @param s The string to compare.
*/
public boolean equals(String s) {
if (s == null) {
return false;
}
if (length != s.length()) {
return false;
}
// new char array object.
for (int i = 0; i < length; i++) {
if (ch[offset + i] != s.charAt(i)) {
return false;
}
}
return true;
}
// equals(String):boolean
//
// Object methods
//
/** Returns a string representation of this object. */
@Override
public String toString() {
return length > 0 ? new String(ch, offset, length) : "";
}
// toString():String
}
// class XMLString
|
3e1ba54c9b54e19aee23e91926aa1289d6e24794 | 459 | java | Java | compiler/src/main/java/de/tub/dima/babelfish/ir/lqp/relational/KeyGroup.java | TU-Berlin-DIMA/babelfish | 4926384d994ab4ab324a056d69be64d9b52ed7a0 | [
"Apache-2.0"
] | 2 | 2022-01-28T00:55:18.000Z | 2022-02-08T16:43:41.000Z | compiler/src/main/java/de/tub/dima/babelfish/ir/lqp/relational/KeyGroup.java | TU-Berlin-DIMA/babelfish | 4926384d994ab4ab324a056d69be64d9b52ed7a0 | [
"Apache-2.0"
] | null | null | null | compiler/src/main/java/de/tub/dima/babelfish/ir/lqp/relational/KeyGroup.java | TU-Berlin-DIMA/babelfish | 4926384d994ab4ab324a056d69be64d9b52ed7a0 | [
"Apache-2.0"
] | null | null | null | 21.857143 | 58 | 0.727669 | 11,714 | package de.tub.dima.babelfish.ir.lqp.relational;
import de.tub.dima.babelfish.ir.lqp.schema.FieldReference;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
public class KeyGroup implements Serializable {
private List<FieldReference> keys;
public KeyGroup(FieldReference... fieldReference) {
keys = Arrays.asList(fieldReference);
}
public List<FieldReference> getKeys() {
return keys;
}
}
|
3e1ba58d0e6648bdf4ca72683d6f8a1a44232784 | 12,003 | java | Java | produsupsys-admin/src/main/java/com/ruoyi/service/impl/SortingMatchingServiceImpl.java | guoruijun07/produsupsys | 70023f43f9bb90a7c4e5214e5f7af10239281b1c | [
"MIT"
] | 1 | 2020-07-24T10:44:20.000Z | 2020-07-24T10:44:20.000Z | produsupsys-admin/src/main/java/com/ruoyi/service/impl/SortingMatchingServiceImpl.java | guoruijun07/produsupsys | 70023f43f9bb90a7c4e5214e5f7af10239281b1c | [
"MIT"
] | 1 | 2021-09-20T21:01:04.000Z | 2021-09-20T21:01:04.000Z | produsupsys-admin/src/main/java/com/ruoyi/service/impl/SortingMatchingServiceImpl.java | guoruijun07/produsupsys | 70023f43f9bb90a7c4e5214e5f7af10239281b1c | [
"MIT"
] | null | null | null | 51.943723 | 216 | 0.660888 | 11,715 | package com.ruoyi.service.impl;
import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.bean.bo.Address;
import com.ruoyi.common.bean.bo.SingleRouteInfoRequest;
import com.ruoyi.common.bean.po.PostPscAddressMatchingResult;
import com.ruoyi.common.bean.po.PostPscAddressOriginal;
import com.ruoyi.common.bean.po.PostPscBaseSorting;
import com.ruoyi.common.mapper.PostPscAddressMatchingResultMapper;
import com.ruoyi.common.mapper.PostPscAddressOriginalMapper;
import com.ruoyi.common.mapper.PostPscBaseSortingMapper;
import com.ruoyi.service.SortingMatchingService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author GuoRJ
* @date 2020/7/4 13:35
*/
/*四级分拣码 通过CSB调用*/
@Service
public class SortingMatchingServiceImpl implements SortingMatchingService {
private static final Logger logger = LoggerFactory.getLogger(SortingMatchingService.class);
@Autowired(required = false)
private PostPscAddressOriginalMapper postPscAddressOriginalMapper;
@Autowired(required = false)
private PostPscAddressMatchingResultMapper postPscAddressMatchingResultMapper;
@Autowired(required = false)
private PostPscBaseSortingMapper postPscBaseSortingMapper;
@Override
public void sortingMatchingInfoByPc(String batchNo) throws HttpCallerException {
//batchNo="1";
final List<PostPscAddressOriginal> postPscAddressOriginalList = postPscAddressOriginalMapper.selectByBatchNo(batchNo);
final List<PostPscAddressMatchingResult> postPscAddressMatchingResults = postPscAddressMatchingResultMapper.selectByBatch(batchNo);
logger.info("查询完毕");
if (postPscAddressMatchingResults == null || postPscAddressMatchingResults.size() == 0) {
//新增操作
postPscAddressMatchingResultMapper.batchInsert(postPscAddressOriginalList);
} else {
//修改操作
}
List<SingleRouteInfoRequest> logisticsInterfaces = new ArrayList<>();
List<PostPscAddressMatchingResult> sortingMatchingInfos = new ArrayList<>();
List<PostPscAddressOriginal> orderOriginalInfos = new ArrayList<>();
for (PostPscAddressOriginal postPscAddressOriginal : postPscAddressOriginalList) {
SingleRouteInfoRequest singleRouteInfoRequest = new SingleRouteInfoRequest();
Address senderAddress = new Address();
Address receiverAddress = new Address();
singleRouteInfoRequest.setObjectId(parseString(postPscAddressOriginal.getOrderNo()));
senderAddress.setTown(null);
senderAddress.setCity(postPscAddressOriginal.getSenderCity());
senderAddress.setArea(postPscAddressOriginal.getSenderCounty());
senderAddress.setDetail(postPscAddressOriginal.getSenderAddress());
senderAddress.setProvince(postPscAddressOriginal.getSenderProvince());
senderAddress.setZip(null);
singleRouteInfoRequest.setSenderAddress(senderAddress);
receiverAddress.setTown(null);
receiverAddress.setCity(postPscAddressOriginal.getReciverCity());
receiverAddress.setArea(postPscAddressOriginal.getReciverCounty());
receiverAddress.setDetail(postPscAddressOriginal.getReciverAddress());
receiverAddress.setProvince(postPscAddressOriginal.getReciverProvince());
receiverAddress.setZip(null);
singleRouteInfoRequest.setReceiverAddress(receiverAddress);
logisticsInterfaces.add(singleRouteInfoRequest);
}
getMatchingData(logisticsInterfaces, sortingMatchingInfos, orderOriginalInfos);
// for (TbSortingMatchingInfo sortingMatchingInfo : sortingMatchingInfos) {
// postPscAddressMatchingResultMapper.updateByOrderNo(sortingMatchingInfo);
// }
// for (TbOrderOriginalInfo orderOriginalInfo : orderOriginalInfos) {
// postPscAddressOriginalMapper.updateByOrderNo(orderOriginalInfo);
// }
if (sortingMatchingInfos.size() > 0) {
postPscAddressMatchingResultMapper.batchUpdateByOrderNo(sortingMatchingInfos);
postPscAddressOriginalMapper.batchUpdateByOrderNo(orderOriginalInfos);
}
}
@Override
public PostPscAddressMatchingResult sortingMatchingByApp(PostPscAddressOriginal tbOrderOriginalInfo) throws HttpCallerException {
List<SingleRouteInfoRequest> logisticsInterfaces = new ArrayList<>();
List<PostPscAddressMatchingResult> sortingMatchingInfos = new ArrayList<>();
List<PostPscAddressOriginal> orderOriginalInfos = new ArrayList<>();
SingleRouteInfoRequest singleRouteInfoRequest = new SingleRouteInfoRequest();
Address senderAddress = new Address();
Address receiverAddress = new Address();
singleRouteInfoRequest.setObjectId(parseString(tbOrderOriginalInfo.getOrderNo()));
senderAddress.setTown(null);
senderAddress.setCity(tbOrderOriginalInfo.getSenderCity());
senderAddress.setArea(tbOrderOriginalInfo.getSenderCounty());
senderAddress.setDetail(tbOrderOriginalInfo.getSenderAddress());
senderAddress.setProvince(tbOrderOriginalInfo.getSenderProvince());
senderAddress.setZip(null);
singleRouteInfoRequest.setSenderAddress(senderAddress);
receiverAddress.setTown(null);
receiverAddress.setCity(tbOrderOriginalInfo.getReciverCity());
receiverAddress.setArea(tbOrderOriginalInfo.getReciverCounty());
receiverAddress.setDetail(tbOrderOriginalInfo.getReciverAddress());
receiverAddress.setProvince(tbOrderOriginalInfo.getReciverProvince());
receiverAddress.setZip(null);
singleRouteInfoRequest.setReceiverAddress(receiverAddress);
logisticsInterfaces.add(singleRouteInfoRequest);
getMatchingData(logisticsInterfaces, sortingMatchingInfos, orderOriginalInfos);
return sortingMatchingInfos.get(0);
}
private void getMatchingData(List<SingleRouteInfoRequest> logisticsInterface, List<PostPscAddressMatchingResult> sortingMatchingInfos, List<PostPscAddressOriginal> orderOriginalInfos) throws HttpCallerException {
//获取基础信息
List<PostPscBaseSorting> tbSortingBaseInfos = postPscBaseSortingMapper.selectAllData();
Map<String, PostPscBaseSorting> mapBasesSortingInfos = new HashMap<>();
for (PostPscBaseSorting postPscBaseSorting : tbSortingBaseInfos) {
mapBasesSortingInfos.put(postPscBaseSorting.getSortingName(), postPscBaseSorting);
}
Map<String, String> params = new HashMap<String, String>();
params.put("logisticsInterface", JSON.toJSONString(logisticsInterface));
params.put("dataDigest", "bb");
params.put("wpCode", "DNMN-EMS");
String requestURL = "https://211.156.195.14:443/csb_jidi1_1";
String API_NAME = "routInfoQueryForPDD"; // CSB发布服务定义的服务名
String version = "1.0.0";
String ak = "caf86f4uutaoxfysmf7anj01xl6sv3ps";//
String sk = "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"; // 用户安全校验的签名密钥对
String result = HttpCaller.doPost(requestURL, API_NAME, version, params, ak, sk);
if (result != null) {
logger.info("四级分拣码匹配成功,result:" + result);
Map<String, Object> mapPc = JSONObject.parseObject(result);
Map<String, Object> body = (Map<String, Object>) mapPc.get("body");
if ("true".equals(body.get("success"))) {
List<Map<String, Object>> list = (List<Map<String, Object>>) body.get("result");
for (Map<String, Object> resultMap : list) {
if ("true".equals(resultMap.get("success"))) {
if (!"".equals(parseString(resultMap.get("objectId")))) {
PostPscAddressMatchingResult tbSortingMatchingInfo = new PostPscAddressMatchingResult();
tbSortingMatchingInfo.setOrderNo(parseString(resultMap.get("objectId")));
tbSortingMatchingInfo.setSortingStatus(1);
tbSortingMatchingInfo.setDatoubi(parseString(resultMap.get("datoubi")));
tbSortingMatchingInfo.setDatoubiCode(parseString(resultMap.get("datoubiCode")));
//四级分拣码,得到分拣码
String levelFourSortingName = parseString(resultMap.get("routeCode"));
if (StringUtils.isNotBlank(levelFourSortingName)) {
String substringTmp = levelFourSortingName.substring(0, levelFourSortingName.lastIndexOf("-"));
String sortingName = substringTmp.substring(substringTmp.lastIndexOf("-") + 1);
// String[] split = levelFourSortingName.split("-");
// if (split.length > 3) {
// String sortingName = split[3];
tbSortingMatchingInfo.setSortingName(sortingName);
PostPscBaseSorting tbSortingInfo = mapBasesSortingInfos.get(sortingName);
if (tbSortingInfo != null) {
tbSortingMatchingInfo.setDistribuCenter(tbSortingInfo.getDistribuCenter());
tbSortingMatchingInfo.setMarking(tbSortingInfo.getMarking());
tbSortingMatchingInfo.setOrgNo(tbSortingInfo.getOrgNo());
tbSortingMatchingInfo.setOrgName(tbSortingInfo.getOrgName());
tbSortingMatchingInfo.setDlvName(tbSortingInfo.getDlvName());
tbSortingMatchingInfo.setDlvNo(tbSortingInfo.getAreaNum());
}
// }
}
tbSortingMatchingInfo.setLevelFourSortingName(levelFourSortingName);
if (resultMap.get("consolidationList") != null) {
List<Map<String, Object>> conList = (List<Map<String, Object>>) resultMap.get("consolidationList");
if (conList != null && conList.size() > 0) {
tbSortingMatchingInfo.setConsolidationCode(parseString(conList.get(0).get("code")));
tbSortingMatchingInfo.setConsolidationName(parseString(conList.get(0).get("name")));
}
}
// postPscAddressMatchingResultMapper.updateByOrderNo(tbSortingMatchingInfo);
PostPscAddressOriginal updateOrderOriginalInfo = new PostPscAddressOriginal();
updateOrderOriginalInfo.setOrderNo(parseString(resultMap.get("objectId")));
updateOrderOriginalInfo.setSortingStatus(1);
updateOrderOriginalInfo.setModifyTime(new Date());
// postPscAddressOriginalMapper.updateByOrderNo(updateOrderOriginalInfo);
sortingMatchingInfos.add(tbSortingMatchingInfo);
orderOriginalInfos.add(updateOrderOriginalInfo);
}
}
}
} else {
logger.info("errorCode:" + body.get("errorCode"));
logger.info("errorMsg:" + body.get("errorMsg"));
}
} else {
logger.info("没有任何数据。");
}
}
public String parseString(Object obj) {
if (obj == null) {
return "";
} else {
return obj.toString();
}
}
}
|
3e1ba63cb22369e31cf039c22b5b6dc27dd2ae87 | 2,365 | java | Java | anywhere-fitness/src/main/java/com/anywhere/fitness/controllers/UserController.java | BW-AnytimeFitness-072020/Backend | 02a5b5130e11b84e0097eeb2fdea46f3984f1e80 | [
"MIT"
] | null | null | null | anywhere-fitness/src/main/java/com/anywhere/fitness/controllers/UserController.java | BW-AnytimeFitness-072020/Backend | 02a5b5130e11b84e0097eeb2fdea46f3984f1e80 | [
"MIT"
] | null | null | null | anywhere-fitness/src/main/java/com/anywhere/fitness/controllers/UserController.java | BW-AnytimeFitness-072020/Backend | 02a5b5130e11b84e0097eeb2fdea46f3984f1e80 | [
"MIT"
] | 1 | 2021-01-21T16:17:42.000Z | 2021-01-21T16:17:42.000Z | 34.275362 | 112 | 0.684144 | 11,716 | package com.anywhere.fitness.controllers;
import com.anywhere.fitness.models.User;
import com.anywhere.fitness.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/user/addcourse/{courseid}", produces = {"application/json"})
public ResponseEntity<?> addCourse(@PathVariable long courseid){
User u = userService.findUserByName(SecurityContextHolder.getContext().getAuthentication().getName());
User nu = userService.addUserCourse(courseid, u.getUsername());
return new ResponseEntity<>(nu, HttpStatus.OK);
}
@PutMapping(value = "/user/{id}", consumes = {"application/json"})
public ResponseEntity<?> updateUser(@Valid @RequestBody User user,
@PathVariable long id){
user.setUserid(id);
userService.save(user);
return new ResponseEntity<>(HttpStatus.OK);
}
@DeleteMapping(value = "/user/{id}")
public ResponseEntity<?> deleteUser(@PathVariable long id){
userService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
@GetMapping(value = "/users", produces = {"application/json"})
public ResponseEntity<?> listAllUsers(){
List<User> rtn = userService.findAllUsers();
return new ResponseEntity<>(rtn, HttpStatus.OK);
}
@PatchMapping(value = "/user/{id}", produces = {"application/json"})
public ResponseEntity<?> patchUser(@RequestBody User user, @PathVariable long id){
userService.update(user, id);
return new ResponseEntity<>(HttpStatus.OK);
}
// @GetMapping(value = "/getuserinfo",
// produces = {"application/json"})
// public ResponseEntity<?> getCurrentUserInfo()
// {
// User u = userService.findUserByName(SecurityContextHolder.getContext().getAuthentication().getName());
// return new ResponseEntity<>(u,
// HttpStatus.OK);
// }
}
|
3e1ba73f8766aa725e9be7b67854a8d8b7bbe3fa | 1,033 | java | Java | leetcode/src/test/java/com/github/vvv1559/algorithms/leetcode/math/ReverseIntegerTest.java | vvv1559/algorytms_and_data_structures | e2b5842b004ba443d6271c90cec7187100fd0a95 | [
"Apache-2.0"
] | null | null | null | leetcode/src/test/java/com/github/vvv1559/algorithms/leetcode/math/ReverseIntegerTest.java | vvv1559/algorytms_and_data_structures | e2b5842b004ba443d6271c90cec7187100fd0a95 | [
"Apache-2.0"
] | null | null | null | leetcode/src/test/java/com/github/vvv1559/algorithms/leetcode/math/ReverseIntegerTest.java | vvv1559/algorytms_and_data_structures | e2b5842b004ba443d6271c90cec7187100fd0a95 | [
"Apache-2.0"
] | null | null | null | 31.30303 | 71 | 0.693127 | 11,717 | package com.github.vvv1559.algorithms.leetcode.math;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReverseIntegerTest {
private final ReverseInteger reverseInteger = new ReverseInteger();
@Test
public void testExamples() {
assertEquals(321, reverseInteger.reverse(123));
assertEquals(-321, reverseInteger.reverse(-123));
assertEquals(-1, reverseInteger.reverse(-10));
assertEquals(-101, reverseInteger.reverse(-101));
}
@Test
public void testNotes() {
assertEquals(1, reverseInteger.reverse(10));
assertEquals(1, reverseInteger.reverse(100));
assertEquals(-1, reverseInteger.reverse(-100));
}
@Test
public void testOverflow() {
assertEquals(0, reverseInteger.reverse(1000000003));
assertEquals(0, reverseInteger.reverse(-1000000003));
assertEquals(0, reverseInteger.reverse(1534236469));
assertEquals(0, reverseInteger.reverse(0));
}
} |
3e1ba7f08029bf748ecc1a501691b73649378317 | 14,243 | java | Java | fui.core/src/main/java/com/hundsun/jres/fui/core/resource/FResourceManager.java | fuhp/fui | 2299fcc96f92e0e6f715ccb3a6e27a4fafd51f8c | [
"MIT"
] | 1 | 2021-04-09T16:14:02.000Z | 2021-04-09T16:14:02.000Z | fui.core/src/main/java/com/hundsun/jres/fui/core/resource/FResourceManager.java | fuhp/fui | 2299fcc96f92e0e6f715ccb3a6e27a4fafd51f8c | [
"MIT"
] | null | null | null | fui.core/src/main/java/com/hundsun/jres/fui/core/resource/FResourceManager.java | fuhp/fui | 2299fcc96f92e0e6f715ccb3a6e27a4fafd51f8c | [
"MIT"
] | null | null | null | 25.119929 | 101 | 0.654848 | 11,718 | /*
* 系统名称: JRES 应用快速开发企业套件
* 模块名称: JRES内核
* 文件名称: FResourceManager.java
* 软件版权: 恒生电子股份有限公司
* 修改记录:
* 修改日期 修改人员 修改说明 <br>
* ======== ======= ============================================
*
* ======== ======= ============================================
*/
package com.hundsun.jres.fui.core.resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hundsun.jres.fui.core.FContext;
import com.hundsun.jres.fui.core.FEnvironment;
import com.hundsun.jres.fui.core.FLOG;
import com.hundsun.jres.fui.core.ResourceCallback;
import com.hundsun.jres.fui.core.util.ResourceUtils;
import com.hundsun.jres.fui.core.xml.Tag;
/**
* 功能说明: 资源管理的实现类
* <p>
* 系统版本: v1.0<br>
* 开发人员: hanyin <br>
* 开发时间: 2012-3-31 <br>
*/
public class FResourceManager
{
/** 静态资源URI */
private Map<String, String> resUri = new HashMap<String, String>();
/** 回调资源URI */
private Map<String, ResourceCallback> resCallback = new HashMap<String, ResourceCallback>();
/** 日志实例 */
private Logger LOG = LoggerFactory.getLogger(FEnvironment.LOG_NAME);
/** 组件路径列表 */
private ArrayList<ResJsModule> componentDirs;
/** 国际化资源管理器 */
private ResI18n i18nResource;
/** 主题资源 */
private ArrayList<ResThemes> themeResources;
/** 其他新注册的资源 */
private ArrayList<RefreshableResource> otherResources = new ArrayList<RefreshableResource>();
/** 资源刷新线程 */
private ResourceRefreshThread refreshThread;
/** 工程根目录"/",绝对路径 */
private static final String ROOT_PATH = ResourceUtils.getWebRootAbsolutePath();
public void init()
{
if (LOG.isInfoEnabled()) {
LOG.info("ROOT_PATH: " + ROOT_PATH);
} else {
FLOG.info("ROOT_PATH[" + ROOT_PATH + "]");
}
// 在环境变量中设置当前工程更目录的绝对路径
FEnvironment.get().setProperty(FEnvironment.F_ROOT_PATH, ROOT_PATH);
// 刷新路径设置
initResources();
// 根据当前的启动模式,选择是否开启刷新线程
if (FEnvironment.get().isDevMode()) {
refreshThread = new ResourceRefreshThread();
refreshThread.setDaemon(true);
refreshThread.start();
}
}
synchronized public void destroy()
{
resUri.clear();
resCallback.clear();
List<ResJsModule> componentDirs = this.componentDirs;
ArrayList<ResThemes> themeResources = this.themeResources;
if (componentDirs != null) {
for (ResJsModule jsModule : componentDirs) {
jsModule.release();
}
}
if (themeResources != null) {
for (ResThemes resThemes : themeResources) {
resThemes.release();
}
}
if (refreshThread != null) {
refreshThread.maskStop();
}
}
/**
* 刷新所有资源文件
*/
public synchronized void initResources()
{
FEnvironment env = FEnvironment.get();
// 初始化国际化资源文件路径
String i18nPaths = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_i18n_RESOURCES);
initI18nPaths(i18nPaths);
// 初始化组件JS路径
String customComps = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_COMPONENTS);
initCustomCompsPath(customComps);
// 初始化主题theme路径
String themePaths = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_THEMES);
initThemePaths(themePaths);
// 初始化JQuery路径
String jqueryPath = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_JS_JQUERY);
initJQueryPath(jqueryPath);
// 初始化FUI核心js路径
String corejsPath = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_JS_CORE);
initCoreJsPath(corejsPath);
// 初始化核心css路径
String coreCssPath = (String) env.getProperty(FEnvironment.CONSTANT_CUSTOM_CSS_CORE);
initCoreCssPath(coreCssPath);
// 初始化运行时主题管理器
boolean runtimeThemeEnable = (Boolean) env.getProperty(FEnvironment.CONSTANT_RUNTIME_THEME_ENABLE);
String runtimeTheme = (String) env.getProperty(FEnvironment.CONSTANT_RUNTIME_THEME);
initRuntimeTheme(runtimeThemeEnable, runtimeTheme);
// 初始化运行时国际化管理器
boolean runtimeI18nEnable = (Boolean) env.getProperty(FEnvironment.CONSTANT_RUNTIME_I18N_ENABLE);
String runtimeI18n = (String) env.getProperty(FEnvironment.CONSTANT_RUNTIME_I18N);
initRuntimeI18n(runtimeI18nEnable, runtimeI18n);
}
private String formatPath(String path)
{
path = path.trim();
path = path.replace('\\', '/');
if (!path.startsWith("/")) {
path = "/" + path;
}
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
/**
* method comments here
* @param customComps
*/
private void initCustomCompsPath(String customComps)
{
String[] compPaths = customComps.split(",");
ArrayList<ResJsModule> parserList = new ArrayList<ResJsModule>();
for (String compPath : compPaths) {
if (compPath != null && compPath.trim().length() != 0) {
try {
compPath = formatPath(compPath);
ResJsModule resComponentJSDir = new ResJsModule(compPath);
parserList.add(resComponentJSDir);
} catch (Exception e) {
LOG.warn("invalid component path[" + compPath + "]", e);
}
}
}
componentDirs = parserList;
}
/**
* method comments here
* @param i18nPaths
*/
private void initI18nPaths(String customI18nPaths)
{
ResI18n i18nResource = new ResI18n(customI18nPaths);
this.i18nResource = i18nResource;
}
/**
* method comments here
* @param themePaths
*/
private void initThemePaths(String customThemePaths)
{
themeResources = new ArrayList<ResThemes>();
String[] themePaths = customThemePaths.split(",");
for (String themePath : themePaths) {
themePath = formatPath(themePath);
themeResources.add(new ResThemes(themePath));
}
}
/**
* method comments here
* @param jqueryPath
*/
private void initJQueryPath(String jqueryPath)
{
// TODO Auto-generated method stub
}
/**
* method comments here
* @param corejsPath
*/
private void initCoreJsPath(String corejsPath)
{
// TODO Auto-generated method stub
}
/**
* method comments here
* @param coreCssPath
*/
private void initCoreCssPath(String coreCssPath)
{
// TODO Auto-generated method stub
}
/**
* method comments here
* @param runtimeThemeEnable
* @param runtimeTheme
*/
private void initRuntimeTheme(boolean runtimeThemeEnable, String runtimeTheme)
{
// TODO Auto-generated method stub
}
/**
* method comments here
* @param runtimeI18nEnable
* @param runtimeI18n
*/
private void initRuntimeI18n(boolean runtimeI18nEnable, String runtimeI18n)
{
// TODO Auto-generated method stub
}
/**
* 初始化FUI默认的资源路径
*/
// private void initDefaultUri()
// {
// resUri.put(F_Root, "/FUI");
// resUri.put(F_Css, "{f_root}/css");
// resUri.put(F_Js, "{f_root}/js");
// resUri.put(F_JsSrc, "{f_js}/src");
// resUri.put(F_Themes, "{f_root}/themes");
// resUri.put(F_Ex_Root, "/FUI-extend");
// resUri.put(F_Ex_JsSrc, "{f_ex_root}/js/src");
// resUri.put(F_Ex_Themes, "{f_ex_root}/themes");
// resUri.put(F_Ex_Templates, "classpath:templates");
//
// resUri.put(F_DATA_MODEL, "classpath*:dm/dataModel.xml");
// }
/**
* 从FUI-config.xml中读取配置的URI,并初始化
*/
private void initConfig(ArrayList<Tag> arrayList)
{
ArrayList<Tag> resources = arrayList;
for (Tag res : resources) {
String name = res.getProperty("name");
if (name == null) {
continue;
} else {
name = name.trim();
if (name.length() == 0) {
LOG.warn("init resource [" + res.toString() + "] has error and skip it");
continue;
}
}
// 初始化单个资源配置
initConfigUri(name, res);
}
}
private void initConfigUri(String name, Tag res)
{
String callback = res.getProperty("callback");
String uri = res.getProperty("uri");
if (callback != null) { // 动态URI回调
ResourceCallback resCallback = null;
try {
Class<?> clz = Class.forName(callback);
resCallback = (ResourceCallback) clz.newInstance();
} catch (Exception e) {
LOG.warn("init resource [" + res.toString() + "] has error and skip it", e);
return;
}
// 读取初始化参数
// Map<String, String> parameters = new HashMap<String, String>();
// ArrayList<Tag> params = res.getSubListByName("param");
// for (Tag param : params) {
// String key = param.getProperty("key");
// String value = param.getProperty("value");
// if ((key != null) && (value != null) && (key.trim().length() !=
// 0)) {
// key = key.trim();
// parameters.put(key, value);
// }
// }
// try {
// resCallback.init(parameters);
// } catch (Exception e) {
// LOG.warn("init resource [" + res.toString() +
// "] has error and skip it", e);
// return;
// }
// 放入容器
this.resCallback.put(name, resCallback);
LOG.debug("loaded resource[" + res.toString() + "]");
} else { // 静态URI
if ((uri != null) && (uri.trim().length() != 0)) {
resUri.put(name, uri.trim());
LOG.debug("loaded resource[" + res.toString() + "]");
} else {
LOG.warn("init resource [" + res.toString() + "] has error and skip it");
}
}
}
/*
* (non-Javadoc)
* @see com.hundsun.jres.fui.core.IResources#getContextPath()
*/
public String getContextPath()
{
return FEnvironment.get().getContextPath();
}
/*
* (non-Javadoc)
* @see
* com.hundsun.jres.fui.core.IResources#getResourcePath(java.lang.String)
*/
public String getResourcePath(String resAlias, FContext context)
{
String uri = null;
ResourceCallback callback = resCallback.get(resAlias);
if (callback != null) {
uri = callback.getResource(context);
}
if (uri == null) {
uri = resUri.get(resAlias);
}
return parse2RealPath(uri, context);
}
/*
* (non-Javadoc)
* @see
* com.hundsun.jres.fui.core.IResources#getResourcePathCtx(java.lang.String,
* com.hundsun.jres.fui.core.FContext)
*/
public String getResourcePathCtx(String resAlias, FContext context)
{
String uri = getResourcePath(resAlias, context);
if (uri != null) {
try {
URI u = new URI(uri);
if (u.getScheme() == null) {
String realPart = u.getSchemeSpecificPart();
realPart = realPart.replace('\\', '/');
if (realPart.length() > 0) {
if (realPart.charAt(0) != '/') {
realPart = "/" + realPart;
}
}
return getContextPath() + realPart;
}
} catch (URISyntaxException e) {
// 解析错误
return null;
}
}
return uri;
}
// 将类似于 {xxx}/src 翻译成真正的路径,不允许表达式嵌套
private String parse2RealPath(String uri, FContext context)
{
if (uri == null) {
return null;
}
int size = uri.length();
StringBuilder sb = new StringBuilder(size * 2);
for (int i = 0; i < size; i++) {
char c = uri.charAt(i);
if (c == '{') {
int index = uri.indexOf('}', i);
if (i + 1 > index) { // 格式不正确
return null;
} else {
sb.append(getResourcePath(uri.substring(i + 1, index), context));
}
i = index;
} else {
sb.append(c);
}
}
return sb.toString();
}
public ArrayList<ResJsModule> getComponentModules()
{
return componentDirs;
}
public ResI18n getI18nResource()
{
return i18nResource;
}
public ArrayList<ResThemes> getThemeResources()
{
return themeResources;
}
public void addRefreshableResource(RefreshableResource res)
{
synchronized (otherResources) {
otherResources.add(res);
}
}
public void removeRefreshableResource(RefreshableResource res)
{
synchronized (otherResources) {
otherResources.remove(res);
}
}
private class ResourceRefreshThread extends Thread
{
private boolean canRefresh = true;
/*
* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run()
{
while (canRefresh) {
boolean noRefresh = true;
ArrayList<ResJsModule> modules = FResourceManager.this.componentDirs;
for (ResJsModule module : modules) {
if (module != null) {
noRefresh = module.refresh() && noRefresh;
}
if (!canRefresh) {
return;
}
}
ArrayList<ResThemes> themeResources = FResourceManager.this.themeResources;
for (ResThemes theme : themeResources) {
if (theme != null) {
noRefresh = theme.refresh() && noRefresh;
}
if (!canRefresh) {
return;
}
}
// 其他资源
synchronized (otherResources) {
for (RefreshableResource resouce : otherResources) {
noRefresh = resouce.refresh() && noRefresh;
}
if (!canRefresh) {
return;
}
}
if (!noRefresh) {
LOG.info("Resource refreshed.");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
canRefresh = false;
return;
}
}
}
public void maskStop()
{
canRefresh = false;
}
}
public static void main(String[] args)
{
// FResourceManager manager = new FResourceManager();
// manager.init(null);
// manager.resUri.put("testuri", "/ddd/{def}");
// manager.resUri.put("abc", "/中文");
// manager.resUri.put("def", "英文");
//
// System.out.println(manager.getExJsSrcPath(null));
// System.out.println(manager.getFJsSrcPath(null));
// System.out.println(manager.getExTemplatesPath(null));
// System.out.println(manager.getResourcePath("testuri", null));
// System.out.println(manager.getResourcePathCtx(F_Ex_Templates, null));
// try {
// System.out.println(new URI(
// "http://localhost:8080/FUI/layout.ftl?key1=value1&key2=value2")
// .getSchemeSpecificPart());
//
// String uri =
// "http://localhost:8080/FUI/layout.ftl?key1=value1&key2=value2";
// System.out.println(new URI(uri).getAuthority());
// System.out.println(new URI(uri).getFragment());
// System.out.println(new URI(uri).getHost());
// System.out.println(new URI(uri).getPath());
// System.out.println(new URI(uri).getPort());
// System.out.println(new URI(uri).getQuery());
// System.out.println(new URI(uri).getRawAuthority());
// System.out.println(new URI(uri).getRawFragment());
// System.out.println(new URI(uri).getRawPath());
// System.out.println(new URI(uri).getRawQuery());
// System.out.println(new URI(uri).getRawSchemeSpecificPart());
// System.out.println(new URI(uri).getRawUserInfo());
// System.out.println(new URI(uri).getScheme());
// System.out.println(new URI(uri).getSchemeSpecificPart());
// System.out.println(new URI(uri).getUserInfo());
// } catch (URISyntaxException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
|
3e1ba9b61739c00bacef5214b83f3d85c5042585 | 4,230 | java | Java | src/main/java/bbound/NetworkTopologyMeasuresCalculator.java | kleinmind/bridge-bounding | 5fe8e06891c175a9a855c6abf64aac9653554520 | [
"Apache-2.0"
] | 2 | 2020-03-02T00:10:57.000Z | 2021-08-13T12:31:51.000Z | src/main/java/bbound/NetworkTopologyMeasuresCalculator.java | kleinmind/bridge-bounding | 5fe8e06891c175a9a855c6abf64aac9653554520 | [
"Apache-2.0"
] | null | null | null | src/main/java/bbound/NetworkTopologyMeasuresCalculator.java | kleinmind/bridge-bounding | 5fe8e06891c175a9a855c6abf64aac9653554520 | [
"Apache-2.0"
] | null | null | null | 30.875912 | 102 | 0.726478 | 11,719 | /*
@(#) NetworkTopologyMeasuresCalculator.java 1.0, 08/07/2013
Bridge Bounding, https://github.com/kleinmind/bridge-bounding
Copyright 2013 Symeon Papadopoulos
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 bbound;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.uci.ics.jung.graph.util.Pair;
import jung.WalkableWeightedEdge;
import jung.IndexableUndirectedSparseGraph;
import jung.StringIndexableVertex;
/**
* This class calculates a series of predefined network topology measures
* around a given edge or node.
*
* @author Symeon Papadopoulos
*
*/
public class NetworkTopologyMeasuresCalculator<V extends StringIndexableVertex, E> {
private final NetworkTopologyMeasures measure;
private IndexableUndirectedSparseGraph<V, E> referenceGraph = null;
private final double alpha = 0.5;
public NetworkTopologyMeasuresCalculator(
IndexableUndirectedSparseGraph<V,E> g, NetworkTopologyMeasures measure){
this.referenceGraph = g;
this.measure = measure;
}
public double calculateMeasure(E edge){
if (NetworkTopologyMeasures.ELB.equals(measure)){
return calculateElb(edge);
} else if (NetworkTopologyMeasures.ELB2.equals(measure)) {
return calculateElb2(edge);
} else {
throw new IllegalArgumentException("Unsupported network measure!");
}
}
/**
* Calculate edge local bridging (equivalent to: 1.0-edge clustering coefficient)
*
* @param edge
* @return
*/
private double calculateElb(E edge){
if (edge instanceof WalkableWeightedEdge){
Double elb = ((WalkableWeightedEdge)edge).getNetworkTopologyMeasure(NetworkTopologyMeasures.ELB);
if (elb != null){
return elb;
}
}
Pair<V> endpoints = referenceGraph.getEndpoints(edge);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
int deg1 = referenceGraph.degree(v1);
int deg2 = referenceGraph.degree(v2);
int denominator = Math.min(deg1-1, deg2-1);
if (denominator == 1){
return 1.0;
}
Set<V> neighborhood1Set = new HashSet<V>(referenceGraph.getNeighbors(v1));
List<V> neighborhood2 = new ArrayList<V>(referenceGraph.getNeighbors(v2));
int countCommon = 0;
for (int i = 0; i < neighborhood2.size(); i++) {
if (neighborhood1Set.contains(neighborhood2.get(i))){
countCommon++;
}
}
double elb = (1.0-(double)countCommon / (double)denominator);
if (edge instanceof WalkableWeightedEdge){
((WalkableWeightedEdge)edge).setNetworkTopologyMeasure(NetworkTopologyMeasures.ELB, elb);
}
return elb;
}
/**
* Calculate 2nd order edge local bridging (average between the local bridging of
* the edge and the bridging values of the surrounding edges)
*
* @param edge
* @return
*/
private double calculateElb2(E edge){
if (edge instanceof WalkableWeightedEdge){
Double elb2 = ((WalkableWeightedEdge)edge).getNetworkTopologyMeasure(NetworkTopologyMeasures.ELB2);
if (elb2 != null){
return elb2;
}
}
Pair<V> endpoints = referenceGraph.getEndpoints(edge);
double thisElb = calculateElb(edge);
V v1 = endpoints.getFirst();
V v2 = endpoints.getSecond();
List<E> edges1 = new ArrayList<E>(referenceGraph.getIncidentEdges(v1));
List<E> edges2 = new ArrayList<E>(referenceGraph.getIncidentEdges(v2));
double sum = 0.0;
for (int i = 0; i < edges1.size(); i++){
sum += calculateElb(edges1.get(i));
}
for (int i = 0; i < edges2.size(); i++){
sum += calculateElb(edges2.get(i));
}
double elb2 = alpha*thisElb + (1.0-alpha)*sum/(edges1.size()+edges2.size());
if (edge instanceof WalkableWeightedEdge){
((WalkableWeightedEdge)edge).setNetworkTopologyMeasure(NetworkTopologyMeasures.ELB2, elb2);
}
return elb2;
}
}
|
3e1ba9e0be5cf821cd4c3b131c414b1612d7b4e3 | 259 | java | Java | app/src/main/java/io/mvpstarter/sample/data/local/DbManager.java | shisheng-1/android-starter | a77488ccb337f3d08737259a2d17349fe783ac62 | [
"Unlicense"
] | 372 | 2016-08-08T14:19:04.000Z | 2017-06-04T23:09:36.000Z | app/src/main/java/io/mvpstarter/sample/data/local/DbManager.java | ravidsrk/Android-Mvp-Starter | a77488ccb337f3d08737259a2d17349fe783ac62 | [
"Unlicense"
] | 14 | 2017-08-29T18:34:56.000Z | 2019-06-01T09:55:20.000Z | app/src/main/java/io/mvpstarter/sample/data/local/DbManager.java | ravidsrk/Android-Mvp-Starter | a77488ccb337f3d08737259a2d17349fe783ac62 | [
"Unlicense"
] | 54 | 2016-07-29T17:48:07.000Z | 2017-06-08T13:28:17.000Z | 13.631579 | 40 | 0.69112 | 11,720 | package io.mvpstarter.sample.data.local;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Created by shivam on 29/5/17.
*/
// To be implemented with Realm
@Singleton
public class DbManager {
@Inject
public DbManager() {
}
}
|
3e1baa54042bcdb41e9231b9b30b5e0a440eaa80 | 1,616 | java | Java | ds-stack/src/test/java/johnny/dsa/ds/StackMergeSortTest.java | jojozhuang/DataStructure | 8328972a041c6676cade88c3e47c5769c3bd870e | [
"MIT"
] | 2 | 2021-01-13T08:06:48.000Z | 2021-04-13T19:32:01.000Z | ds-stack/src/test/java/johnny/dsa/ds/StackMergeSortTest.java | jojozhuang/DataStructure | 8328972a041c6676cade88c3e47c5769c3bd870e | [
"MIT"
] | null | null | null | ds-stack/src/test/java/johnny/dsa/ds/StackMergeSortTest.java | jojozhuang/DataStructure | 8328972a041c6676cade88c3e47c5769c3bd870e | [
"MIT"
] | 3 | 2021-08-25T16:27:46.000Z | 2022-01-20T20:53:45.000Z | 30.490566 | 78 | 0.561262 | 11,721 | package johnny.dsa.ds;
import org.junit.jupiter.api.Test;
import java.util.Stack;
import static org.junit.jupiter.api.Assertions.*;
public class StackMergeSortTest {
@Test
public void testStackMergeSort() {
System.out.println("testStackMergeSort");
StackMergeSort instance = new StackMergeSort();
Stack<Integer> result1 = instance.sort(null);
Stack<Integer> expect1 = null;
assertEquals(expect1, result1);
Stack<Integer> result2 = instance.sort(new int[] {7,2});
Stack<Integer> expect2 = new Stack<Integer>();
int[] nums2 = new int[] {2,7};
for (int i : nums2) {
expect2.push(i);
}
assertEquals(expect2, result2);
Stack<Integer> result3 = instance.sort(new int[] {5,1,4});
Stack<Integer> expect3 = new Stack<Integer>();
int[] nums3 = new int[] {1,4,5};
for (int i : nums3) {
expect3.push(i);
}
assertEquals(expect3, result3);
Stack<Integer> result4 = instance.sort(new int[] {2,4,5,7,1,2,3,6});
Stack<Integer> expect4 = new Stack<Integer>();
int[] nums4 = new int[] {1,2,2,3,4,5,6,7};
for (int i : nums4) {
expect4.push(i);
}
assertEquals(expect4, result4);
Stack<Integer> result5 = instance.sort(new int[] {2,4,5,7,1,2,3,6,9});
Stack<Integer> expect5 = new Stack<Integer>();
int[] nums5 = new int[] {1,2,2,3,4,5,6,7,9};
for (int i : nums5) {
expect5.push(i);
}
assertEquals(expect5, result5);
}
}
|
3e1baa9309d352c7d8e4d32bf9d26a7ebced0cf2 | 292 | java | Java | primeira-api/algafood-api/src/main/java/com/algaworks/algafoodapi/core/validation/ValidacaoException.java | georgealan/Especialista-Spring-REST-Algaworks | c1666830ba79c3ebd74a643ee28c55e2288e549c | [
"MIT"
] | 1 | 2020-07-22T21:38:03.000Z | 2020-07-22T21:38:03.000Z | primeira-api/algafood-api/src/main/java/com/algaworks/algafoodapi/core/validation/ValidacaoException.java | georgealan/Especialista-Spring-REST-Algaworks | c1666830ba79c3ebd74a643ee28c55e2288e549c | [
"MIT"
] | null | null | null | primeira-api/algafood-api/src/main/java/com/algaworks/algafoodapi/core/validation/ValidacaoException.java | georgealan/Especialista-Spring-REST-Algaworks | c1666830ba79c3ebd74a643ee28c55e2288e549c | [
"MIT"
] | null | null | null | 24.333333 | 58 | 0.849315 | 11,722 | package com.algaworks.algafoodapi.core.validation;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.validation.BindingResult;
@AllArgsConstructor
@Getter
public class ValidacaoException extends RuntimeException {
private BindingResult bindingResult;
}
|
3e1bab202c2c99a6d9d089e2e8d4a4605edfeb53 | 1,200 | java | Java | mapstruct-lookup-entity-with-id/src/main/java/org/mapstruct/jpa/ComposedKey.java | eaz/mapstruct-examples | b138453c35e24a6269c34813a1b5669b75d6d36e | [
"Apache-2.0"
] | 1 | 2020-08-28T18:46:20.000Z | 2020-08-28T18:46:20.000Z | mapstruct-lookup-entity-with-id/src/main/java/org/mapstruct/jpa/ComposedKey.java | eaz/mapstruct-examples | b138453c35e24a6269c34813a1b5669b75d6d36e | [
"Apache-2.0"
] | null | null | null | mapstruct-lookup-entity-with-id/src/main/java/org/mapstruct/jpa/ComposedKey.java | eaz/mapstruct-examples | b138453c35e24a6269c34813a1b5669b75d6d36e | [
"Apache-2.0"
] | null | null | null | 26.666667 | 76 | 0.686667 | 11,723 | /**
* Copyright 2012-2017 Gunnar Morling (http://www.gunnarmorling.de/)
* and/or other contributors as indicated by the @authors tag. See the
* copyright.txt file in the distribution for a full listing of all
* contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapstruct.jpa;
/**
*
* @author Sjaak Derksen
*/
public class ComposedKey {
private final String name1;
private final String name2;
public ComposedKey(String name1, String name2) {
this.name1 = name1;
this.name2 = name2;
}
public String getName1() {
return name1;
}
public String getName2() {
return name2;
}
}
|
3e1bab92da9c250ffc79ff6dc5477e33c260f799 | 19,230 | java | Java | src/main/java/org/tinymediamanager/ui/tvshows/TvShowTreeDataProvider.java | SoapCanFly/tinyPornhubManager | d53b0ada8d0211f5d52a887945ce0428f5a65591 | [
"Apache-2.0"
] | 1 | 2022-03-15T14:00:38.000Z | 2022-03-15T14:00:38.000Z | src/main/java/org/tinymediamanager/ui/tvshows/TvShowTreeDataProvider.java | SoapCanFly/tinyPornhubManager | d53b0ada8d0211f5d52a887945ce0428f5a65591 | [
"Apache-2.0"
] | 1 | 2022-02-12T18:24:52.000Z | 2022-02-12T18:24:52.000Z | src/main/java/org/tinymediamanager/ui/tvshows/TvShowTreeDataProvider.java | LemonGo97/TinyMediaManager | fe6ec2b0105d4fc5b9523059dde86d105c8720f9 | [
"Apache-2.0"
] | null | null | null | 30.379147 | 146 | 0.656994 | 11,724 | /*
* Copyright 2012 - 2020 Manuel Laggner
*
* 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.tinymediamanager.ui.tvshows;
import java.beans.PropertyChangeListener;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.lang3.StringUtils;
import org.tinymediamanager.core.Constants;
import org.tinymediamanager.core.UTF8Control;
import org.tinymediamanager.core.tvshow.TvShowList;
import org.tinymediamanager.core.tvshow.TvShowModuleManager;
import org.tinymediamanager.core.tvshow.entities.TvShow;
import org.tinymediamanager.core.tvshow.entities.TvShowEpisode;
import org.tinymediamanager.core.tvshow.entities.TvShowSeason;
import org.tinymediamanager.ui.components.tree.TmmTreeDataProvider;
import org.tinymediamanager.ui.components.tree.TmmTreeNode;
/**
* The class TvShowTreeDataProvider is used for providing and managing the data for the TV show tree
*
* @author Manuel Laggner
*/
public class TvShowTreeDataProvider extends TmmTreeDataProvider<TmmTreeNode> {
protected static final ResourceBundle BUNDLE = ResourceBundle.getBundle("messages", new UTF8Control());
private TmmTreeNode root = new TmmTreeNode(new Object(), this);
private RuleBasedCollator stringCollator = (RuleBasedCollator) RuleBasedCollator.getInstance();
private final PropertyChangeListener tvShowListPropertyChangeListener;
private final PropertyChangeListener tvShowPropertyChangeListener;
private final PropertyChangeListener episodePropertyChangeListener;
private final TvShowList tvShowList = TvShowList.getInstance();
public TvShowTreeDataProvider() {
tvShowListPropertyChangeListener = evt -> {
TvShow tvShow;
switch (evt.getPropertyName()) {
case Constants.ADDED_TV_SHOW:
tvShow = (TvShow) evt.getNewValue();
addTvShow(tvShow);
break;
case Constants.REMOVED_TV_SHOW:
tvShow = (TvShow) evt.getNewValue();
removeTvShow(tvShow);
break;
default:
// do not react on other events of the tvShowList
if (evt.getSource() instanceof TvShowList) {
break;
}
nodeChanged(evt.getSource());
break;
}
};
tvShowList.addPropertyChangeListener(tvShowListPropertyChangeListener);
tvShowPropertyChangeListener = evt -> {
TvShowSeason season;
TvShowEpisode episode;
// only process events from the TV show itself
if (!(evt.getSource() instanceof TvShow)) {
return;
}
switch (evt.getPropertyName()) {
case Constants.ADDED_SEASON:
season = (TvShowSeason) evt.getNewValue();
addTvShowSeason(season);
break;
case Constants.ADDED_EPISODE:
episode = (TvShowEpisode) evt.getNewValue();
addTvShowEpisode(episode);
break;
case Constants.REMOVED_EPISODE:
episode = (TvShowEpisode) evt.getNewValue();
removeTvShowEpisode(episode);
break;
case Constants.EPISODE_COUNT:
case Constants.SEASON_COUNT:
// do not react on change of the episode count
break;
default:
nodeChanged(evt.getSource());
break;
}
};
episodePropertyChangeListener = evt -> {
TvShowEpisode episode;
switch (evt.getPropertyName()) {
// changed the season/episode nr of an episode
case Constants.SEASON:
case Constants.EPISODE:
// simply remove it from the tree and readd it
episode = (TvShowEpisode) evt.getSource();
removeTvShowEpisode(episode);
addTvShowEpisode(episode);
break;
case Constants.TV_SHOW:
// do not react on change of the TV show itself
break;
default:
nodeChanged(evt.getSource());
break;
}
};
setTreeComparator(new TvShowComparator());
TvShowModuleManager.SETTINGS.addPropertyChangeListener(evt -> {
switch (evt.getPropertyName()) {
case "displayMissingEpisodes":
if (TvShowModuleManager.SETTINGS.isDisplayMissingEpisodes()) {
addDummyEpisodes();
}
else {
removeDummyEpisodes();
}
break;
case "displayMissingSpecials":
if (TvShowModuleManager.SETTINGS.isDisplayMissingSpecials()) {
addDummySpecials();
}
else {
removeDummySpecials();
}
break;
}
});
}
/**
* add the dummy episodes to the tree is the setting has been activated
*/
private void addDummyEpisodes() {
for (TvShow tvShow : tvShowList.getTvShows()) {
for (TvShowEpisode episode : tvShow.getEpisodesForDisplay()) {
if (episode.isDummy()) {
addTvShowEpisode(episode);
}
}
}
}
/**
* remove the dummy episodes from the tree is the setting has been deactivated
*/
private void removeDummyEpisodes() {
for (TvShow tvShow : tvShowList.getTvShows()) {
for (TvShowEpisode episode : tvShow.getDummyEpisodes()) {
if (episode.isDummy()) {
removeTvShowEpisode(episode);
}
}
// last but not least remove all empty seasons
for (TvShowSeason season : tvShow.getSeasons()) {
if (season.isDummy()) {
removeTvShowSeason(season);
}
}
}
}
/**
* add the dummy specials to the tree is the setting has been activated
*/
private void addDummySpecials() {
for (TvShow tvShow : tvShowList.getTvShows()) {
for (TvShowEpisode episode : tvShow.getEpisodesForDisplay()) {
if (episode.isDummy() && episode.getSeason() == 0) {
addTvShowEpisode(episode);
}
}
}
}
/**
* remove the dummy specials from the tree is the setting has been deactivated
*/
private void removeDummySpecials() {
for (TvShow tvShow : tvShowList.getTvShows()) {
for (TvShowEpisode episode : tvShow.getDummyEpisodes()) {
if (episode.isDummy() && episode.getSeason() == 0) {
removeTvShowEpisode(episode);
}
}
// last but not least remove all empty seasons
for (TvShowSeason season : tvShow.getSeasons()) {
if (season.getSeason() == 0 && season.isDummy()) {
removeTvShowSeason(season);
}
}
}
}
/**
* trigger a node changed event for all other events
*
* @param source
*/
private void nodeChanged(Object source) {
TmmTreeNode node = getNodeFromCache(source);
if (node != null) {
firePropertyChange(NODE_CHANGED, null, node);
}
}
@Override
public TmmTreeNode getRoot() {
return root;
}
@Override
public TmmTreeNode getParent(TmmTreeNode child) {
if (child.getUserObject() instanceof TvShow) {
return root;
}
else if (child.getUserObject() instanceof TvShowSeason) {
TvShowSeason season = (TvShowSeason) child.getUserObject();
TmmTreeNode node = getNodeFromCache(season.getTvShow());
// parent TV show not yet added? add it
if (node == null) {
node = addTvShow(season.getTvShow());
}
return node;
}
else if (child.getUserObject() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) child.getUserObject();
TmmTreeNode node = getNodeFromCache(episode.getTvShowSeason());
if (node == null) {
node = addTvShowSeason(episode.getTvShowSeason());
}
// also check if the TV show has already been added
if (getNodeFromCache(episode.getTvShow()) == null) {
addTvShow(episode.getTvShow());
}
return node;
}
return null;
}
@Override
public List<TmmTreeNode> getChildren(TmmTreeNode parent) {
if (parent == root) {
ArrayList<TmmTreeNode> nodes = new ArrayList<>();
for (TvShow tvShow : new ArrayList<>(tvShowList.getTvShows())) {
TmmTreeNode node = new TvShowTreeNode(tvShow, this);
putNodeToCache(tvShow, node);
nodes.add(node);
// add a propertychangelistener for this tv show
tvShow.addPropertyChangeListener(tvShowPropertyChangeListener);
}
return nodes;
}
else if (parent.getUserObject() instanceof TvShow) {
TvShow tvShow = (TvShow) parent.getUserObject();
ArrayList<TmmTreeNode> nodes = new ArrayList<>();
for (TvShowSeason season : tvShow.getSeasons()) {
TmmTreeNode node = new TvShowSeasonTreeNode(season, this);
putNodeToCache(season, node);
nodes.add(node);
}
return nodes;
}
else if (parent.getUserObject() instanceof TvShowSeason) {
TvShowSeason season = (TvShowSeason) parent.getUserObject();
ArrayList<TmmTreeNode> nodes = new ArrayList<>();
for (TvShowEpisode episode : season.getEpisodesForDisplay()) {
// look if a node of this episode already exist
TmmTreeNode node = getNodeFromCache(episode);
if (node == null) {
// create a new one
node = new TvShowEpisodeTreeNode(episode, this);
putNodeToCache(episode, node);
}
nodes.add(node);
// add a propertychangelistener for this episode
episode.addPropertyChangeListener(episodePropertyChangeListener);
}
return nodes;
}
return null;
}
@Override
public boolean isLeaf(TmmTreeNode node) {
return node.getUserObject() instanceof TvShowEpisode;
}
@Override
public Comparator<TmmTreeNode> getTreeComparator() {
return super.getTreeComparator();
}
private TmmTreeNode addTvShow(TvShow tvShow) {
// check if this tv show has already been added
TmmTreeNode cachedNode = getNodeFromCache(tvShow);
if (cachedNode != null) {
return cachedNode;
}
// add a new node
TmmTreeNode node = new TvShowTreeNode(tvShow, this);
putNodeToCache(tvShow, node);
firePropertyChange(NODE_INSERTED, null, node);
// and also add a propertychangelistener to react on changes inside the tv show
tvShow.addPropertyChangeListener(tvShowPropertyChangeListener);
return node;
}
private void removeTvShow(TvShow tvShow) {
// remove the propertychangelistener from this tv show
tvShow.removePropertyChangeListener(tvShowPropertyChangeListener);
TmmTreeNode cachedNode = removeNodeFromCache(tvShow);
if (cachedNode == null) {
return;
}
// remove all children from the map (the nodes will be removed by the treemodel)
for (TvShowSeason season : tvShow.getSeasons()) {
removeNodeFromCache(season);
}
for (TvShowEpisode episode : tvShow.getEpisodesForDisplay()) {
removeNodeFromCache(episode);
}
firePropertyChange(NODE_REMOVED, null, cachedNode);
}
private TmmTreeNode addTvShowSeason(TvShowSeason season) {
// check if this season has already been added
TmmTreeNode cachedNode = getNodeFromCache(season);
if (cachedNode != null) {
return cachedNode;
}
// add a new node
TmmTreeNode node = new TvShowSeasonTreeNode(season, this);
putNodeToCache(season, node);
firePropertyChange(NODE_INSERTED, null, node);
return node;
}
private TmmTreeNode addTvShowEpisode(TvShowEpisode episode) {
// check if this episode has already been added
TmmTreeNode cachedNode = getNodeFromCache(episode);
if (cachedNode != null) {
return cachedNode;
}
// add a new node
TmmTreeNode node = new TvShowEpisodeTreeNode(episode, this);
putNodeToCache(episode, node);
firePropertyChange(NODE_INSERTED, null, node);
// and also add a propertychangelistener to react on changes inside the episode
episode.addPropertyChangeListener(episodePropertyChangeListener);
return node;
}
private void removeTvShowEpisode(TvShowEpisode episode) {
// remove the propertychangelistener from this episode
episode.removePropertyChangeListener(episodePropertyChangeListener);
TmmTreeNode cachedNode = removeNodeFromCache(episode);
if (cachedNode == null) {
return;
}
firePropertyChange(NODE_REMOVED, null, cachedNode);
// okay, we've removed the episode; now check which seasons we have to remove too
for (TvShowSeason season : episode.getTvShow().getSeasons()) {
if (season.getEpisodes().isEmpty()) {
removeTvShowSeason(season);
}
}
}
private void removeTvShowSeason(TvShowSeason season) {
// remove the propertychangelistener from this episode
season.removePropertyChangeListener(episodePropertyChangeListener);
TmmTreeNode cachedNode = removeNodeFromCache(season);
if (cachedNode == null) {
return;
}
firePropertyChange(NODE_REMOVED, null, cachedNode);
}
/*
* helper classes
*/
class TvShowComparator implements Comparator<TmmTreeNode> {
@Override
public int compare(TmmTreeNode o1, TmmTreeNode o2) {
Object userObject1 = o1.getUserObject();
Object userObject2 = o2.getUserObject();
if (userObject1 instanceof TvShow && userObject2 instanceof TvShow) {
TvShow tvShow1 = (TvShow) userObject1;
TvShow tvShow2 = (TvShow) userObject2;
if (stringCollator != null) {
return stringCollator.compare(tvShow1.getTitleSortable().toLowerCase(Locale.ROOT), tvShow2.getTitleSortable().toLowerCase(Locale.ROOT));
}
return tvShow1.getTitleSortable().compareToIgnoreCase(tvShow2.getTitleSortable());
}
if (userObject1 instanceof TvShowSeason && userObject2 instanceof TvShowSeason) {
TvShowSeason tvShowSeason1 = (TvShowSeason) userObject1;
TvShowSeason tvShowSeason2 = (TvShowSeason) userObject2;
return tvShowSeason1.getSeason() - tvShowSeason2.getSeason();
}
if (userObject1 instanceof TvShowEpisode && userObject2 instanceof TvShowEpisode) {
TvShowEpisode tvShowEpisode1 = (TvShowEpisode) userObject1;
TvShowEpisode tvShowEpisode2 = (TvShowEpisode) userObject2;
return tvShowEpisode1.getEpisode() - tvShowEpisode2.getEpisode();
}
return o1.toString().compareToIgnoreCase(o2.toString());
}
}
abstract static class AbstractTvShowTreeNode extends TmmTreeNode {
AbstractTvShowTreeNode(Object userObject, TmmTreeDataProvider dataProvider) {
super(userObject, dataProvider);
}
abstract String getTitle();
abstract String getOriginalTitle();
}
public static class TvShowTreeNode extends AbstractTvShowTreeNode {
private static final long serialVersionUID = -1316609340104597133L;
/**
* Instantiates a new tv show tree node.
*
* @param userObject
* the user object
*/
TvShowTreeNode(Object userObject, TmmTreeDataProvider dataProvider) {
super(userObject, dataProvider);
}
/**
* provides the right name of the node for display.
*
* @return the string
*/
@Override
public String toString() {
// return TV show name
if (getUserObject() instanceof TvShow) {
TvShow tvShow = (TvShow) getUserObject();
return tvShow.getTitleSortable();
}
// fallback: call super
return super.toString();
}
@Override
public String getTitle() {
if (getUserObject() instanceof TvShow) {
TvShow tvShow = (TvShow) getUserObject();
return tvShow.getTitle();
}
return toString();
}
@Override
public String getOriginalTitle() {
if (getUserObject() instanceof TvShow) {
TvShow tvShow = (TvShow) getUserObject();
return tvShow.getOriginalTitle();
}
return toString();
}
}
public static class TvShowSeasonTreeNode extends AbstractTvShowTreeNode {
private static final long serialVersionUID = -5734830011018805194L;
/**
* Instantiates a new tv show season tree node.
*
* @param userObject
* the user object
*/
public TvShowSeasonTreeNode(Object userObject, TmmTreeDataProvider dataProvider) {
super(userObject, dataProvider);
}
/**
* provides the right name of the node for display
*/
@Override
public String toString() {
// return movieSet name
if (getUserObject() instanceof TvShowSeason) {
TvShowSeason season = (TvShowSeason) getUserObject();
if (StringUtils.isNotBlank(season.getTitle())) {
return season.getTitle();
}
else {
if (season.getSeason() == -1) {
return BUNDLE.getString("tvshow.uncategorized");
}
if (season.getSeason() == 0) {
return BUNDLE.getString("metatag.specials");
}
return BUNDLE.getString("metatag.season") + " " + season.getSeason();
}
}
// fallback: call super
return super.toString();
}
@Override
public String getTitle() {
return toString();
}
@Override
public String getOriginalTitle() {
return toString();
}
}
public static class TvShowEpisodeTreeNode extends AbstractTvShowTreeNode {
private static final long serialVersionUID = -7108614568808831980L;
/**
* Instantiates a new tv show episode tree node.
*
* @param userObject
* the user object
*/
public TvShowEpisodeTreeNode(Object userObject, TmmTreeDataProvider dataProvider) {
super(userObject, dataProvider);
}
/**
* provides the right name of the node for display.
*
* @return the string
*/
@Override
public String toString() {
// return episode name and number
if (getUserObject() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) getUserObject();
if (episode.getEpisode() >= 0) {
return episode.getEpisode() + ". " + episode.getTitle();
}
else {
return episode.getTitleSortable();
}
}
// fallback: call super
return super.toString();
}
@Override
public String getTitle() {
if (getUserObject() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) getUserObject();
return episode.getTitle();
}
return toString();
}
@Override
public String getOriginalTitle() {
if (getUserObject() instanceof TvShowEpisode) {
TvShowEpisode episode = (TvShowEpisode) getUserObject();
return episode.getOriginalTitle();
}
return toString();
}
}
}
|
3e1bac171072cdf5574c046d0e0b4bf4f03cc94d | 1,341 | java | Java | src/main/java/com/geccocrawler/gecco/spider/render/RenderFactory.java | joro88/gecco | 9227c917f62bb39bd5853f8cccd93c7b67e7c691 | [
"MIT"
] | null | null | null | src/main/java/com/geccocrawler/gecco/spider/render/RenderFactory.java | joro88/gecco | 9227c917f62bb39bd5853f8cccd93c7b67e7c691 | [
"MIT"
] | null | null | null | src/main/java/com/geccocrawler/gecco/spider/render/RenderFactory.java | joro88/gecco | 9227c917f62bb39bd5853f8cccd93c7b67e7c691 | [
"MIT"
] | null | null | null | 29.152174 | 112 | 0.786726 | 11,725 | package com.geccocrawler.gecco.spider.render;
import com.geccocrawler.gecco.GeccoFactory;
import com.geccocrawler.gecco.GeccoContext;
import java.util.HashMap;
import java.util.Map;
import org.reflections.Reflections;
import com.geccocrawler.gecco.spider.render.html.HtmlRender;
import com.geccocrawler.gecco.spider.render.json.JsonRender;
public abstract class RenderFactory {
protected Map<RenderType, Render> renders;
protected GeccoContext context;
protected GeccoFactory factory;
public RenderFactory(Reflections reflections, GeccoContext context) {
this.context = context;
this.factory = context.getFactory();
CustomFieldRenderFactory customFieldRenderFactory = factory.createCustomFieldRenderFactory(reflections, this);
renders = new HashMap<RenderType, Render>();
AbstractRender htmlRender = createHtmlRender();
htmlRender.setCustomFieldRenderFactory(customFieldRenderFactory);
AbstractRender jsonRender = createJsonRender();
jsonRender.setCustomFieldRenderFactory(customFieldRenderFactory);
renders.put(RenderType.HTML, htmlRender);
renders.put(RenderType.JSON, jsonRender);
}
public Render getRender(RenderType type) {
return renders.get(type);
}
public abstract HtmlRender createHtmlRender();
public abstract JsonRender createJsonRender();
}
|
3e1bac40b4c84898657ed6308666868aa47ff639 | 2,341 | java | Java | src/main/java/com/tjs/common/aop/AuthorizationAspect.java | tjscreator/londonapp | 29a342a680e9ea10d0d4478c33dfd34400434595 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tjs/common/aop/AuthorizationAspect.java | tjscreator/londonapp | 29a342a680e9ea10d0d4478c33dfd34400434595 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tjs/common/aop/AuthorizationAspect.java | tjscreator/londonapp | 29a342a680e9ea10d0d4478c33dfd34400434595 | [
"Apache-2.0"
] | null | null | null | 43.351852 | 105 | 0.770611 | 11,726 | package com.tjs.common.aop;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.tjs.common.enums.ResponseCode;
import com.tjs.common.logger.LoggerService;
import com.tjs.common.threadlocal.Auditor;
import com.tjs.common.user.enums.ModuleEnum;
import com.tjs.common.user.enums.RightsEnum;
import com.tjs.common.user.model.UserModel;
import com.tjs.harbor.exception.HarborException;
/**
* This will be used to perform access control validation. This aspect will be
* applied when method has been annotated with Authorization Annotation.
*
* @version 1.0
*/
@Component
@Aspect
public class AuthorizationAspect {
@Before("@annotation(authorization)")
public void authorized(JoinPoint joinPoint, Authorization authorization) throws Exception {
UserModel userModel = Auditor.getAuditor();
if (userModel == null) {
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes()).getRequest();
LoggerService.info(joinPoint.getSignature().getName().toUpperCase(),
" Unauthorized access, " + httpServletRequest.getRequestURI(), "");
throw new HarborException(ResponseCode.UNAUTHORIZED_ACCESS.getCode(),
ResponseCode.UNAUTHORIZED_ACCESS.getMessage());
}
RightsEnum rightsEnum = authorization.rights();
ModuleEnum moduleEnum = authorization.modules();
if (!userModel.hasAccess(userModel.getUserRequestedRoleModel().getId(),
Integer.valueOf(moduleEnum.getId()).longValue(), Integer.valueOf(rightsEnum.getId()).longValue())) {
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes()).getRequest();
LoggerService.info(joinPoint.getSignature().getName().toUpperCase(),
" Unauthorized access of, " + httpServletRequest.getRequestURI(), " by " + userModel.getMobile());
throw new HarborException(ResponseCode.UNAUTHORIZED_ACCESS.getCode(),
ResponseCode.UNAUTHORIZED_ACCESS.getMessage());
}
}
}
|
3e1bac916a076e257e45f81e0c642c6fe433a9a8 | 407 | java | Java | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/digester/RuleSetBase.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/digester/RuleSetBase.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/digester/RuleSetBase.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | 19.380952 | 61 | 0.675676 | 11,727 | //
// Decompiled by Procyon v0.5.36
//
package org.mudebug.prapr.reloc.commons.digester;
public abstract class RuleSetBase implements RuleSet
{
protected String namespaceURI;
public RuleSetBase() {
this.namespaceURI = null;
}
public String getNamespaceURI() {
return this.namespaceURI;
}
public abstract void addRuleInstances(final Digester p0);
}
|
3e1bac9307f90398f3d31072f085b8e71a9e58cc | 23,494 | java | Java | optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/result/PlannerBenchmarkResult.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 2,400 | 2017-03-14T14:16:18.000Z | 2022-03-31T09:18:47.000Z | optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/result/PlannerBenchmarkResult.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 1,312 | 2017-03-13T14:57:10.000Z | 2022-03-30T14:50:37.000Z | optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/result/PlannerBenchmarkResult.java | artysidorenko/optaplanner | 6557c2599260f6673feed4aab9f2958befe13daf | [
"Apache-2.0"
] | 635 | 2017-03-16T13:17:14.000Z | 2022-03-25T01:12:38.000Z | 44.412098 | 125 | 0.657189 | 11,728 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.benchmark.impl.result;
import java.io.File;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.optaplanner.benchmark.impl.report.BenchmarkReport;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the benchmarks on multiple {@link Solver} configurations on multiple problem instances (data sets).
*/
@XmlRootElement(name = "plannerBenchmarkResult")
public class PlannerBenchmarkResult {
private String name;
private Boolean aggregation;
@XmlTransient // Moving or renaming a report directory after creation is allowed
private File benchmarkReportDirectory;
// If it is an aggregation, many properties can stay null
private Integer availableProcessors = null;
private String loggingLevelOptaPlannerCore = null;
private String loggingLevelDroolsCore = null;
private Long maxMemory = null;
private String optaPlannerVersion = null;
private String javaVersion = null;
private String javaVM = null;
private String operatingSystem = null;
private Integer parallelBenchmarkCount = null;
private Long warmUpTimeMillisSpentLimit = null;
private EnvironmentMode environmentMode = null;
@XmlElement(name = "solverBenchmarkResult")
private List<SolverBenchmarkResult> solverBenchmarkResultList = null;
@XmlElement(name = "unifiedProblemBenchmarkResult")
private List<ProblemBenchmarkResult> unifiedProblemBenchmarkResultList = null;
private OffsetDateTime startingTimestamp = null;
private Long benchmarkTimeMillisSpent = null;
// ************************************************************************
// Report accumulates
// ************************************************************************
private Integer failureCount = null;
private Long averageProblemScale = null;
private Score averageScore = null;
private SolverBenchmarkResult favoriteSolverBenchmarkResult = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getAggregation() {
return aggregation;
}
public void setAggregation(Boolean aggregation) {
this.aggregation = aggregation;
}
public File getBenchmarkReportDirectory() {
return benchmarkReportDirectory;
}
public void setBenchmarkReportDirectory(File benchmarkReportDirectory) {
this.benchmarkReportDirectory = benchmarkReportDirectory;
}
public Integer getAvailableProcessors() {
return availableProcessors;
}
public String getLoggingLevelOptaPlannerCore() {
return loggingLevelOptaPlannerCore;
}
public String getLoggingLevelDroolsCore() {
return loggingLevelDroolsCore;
}
public Long getMaxMemory() {
return maxMemory;
}
public String getJavaVersion() {
return javaVersion;
}
public String getJavaVM() {
return javaVM;
}
public String getOperatingSystem() {
return operatingSystem;
}
public String getOptaPlannerVersion() {
return optaPlannerVersion;
}
public Integer getParallelBenchmarkCount() {
return parallelBenchmarkCount;
}
public void setParallelBenchmarkCount(Integer parallelBenchmarkCount) {
this.parallelBenchmarkCount = parallelBenchmarkCount;
}
public Long getWarmUpTimeMillisSpentLimit() {
return warmUpTimeMillisSpentLimit;
}
public void setWarmUpTimeMillisSpentLimit(Long warmUpTimeMillisSpentLimit) {
this.warmUpTimeMillisSpentLimit = warmUpTimeMillisSpentLimit;
}
public EnvironmentMode getEnvironmentMode() {
return environmentMode;
}
public List<SolverBenchmarkResult> getSolverBenchmarkResultList() {
return solverBenchmarkResultList;
}
public void setSolverBenchmarkResultList(List<SolverBenchmarkResult> solverBenchmarkResultList) {
this.solverBenchmarkResultList = solverBenchmarkResultList;
}
public List<ProblemBenchmarkResult> getUnifiedProblemBenchmarkResultList() {
return unifiedProblemBenchmarkResultList;
}
public void setUnifiedProblemBenchmarkResultList(List<ProblemBenchmarkResult> unifiedProblemBenchmarkResultList) {
this.unifiedProblemBenchmarkResultList = unifiedProblemBenchmarkResultList;
}
public OffsetDateTime getStartingTimestamp() {
return startingTimestamp;
}
public void setStartingTimestamp(OffsetDateTime startingTimestamp) {
this.startingTimestamp = startingTimestamp;
}
public Long getBenchmarkTimeMillisSpent() {
return benchmarkTimeMillisSpent;
}
public void setBenchmarkTimeMillisSpent(Long benchmarkTimeMillisSpent) {
this.benchmarkTimeMillisSpent = benchmarkTimeMillisSpent;
}
public Integer getFailureCount() {
return failureCount;
}
public Long getAverageProblemScale() {
return averageProblemScale;
}
public Score getAverageScore() {
return averageScore;
}
public SolverBenchmarkResult getFavoriteSolverBenchmarkResult() {
return favoriteSolverBenchmarkResult;
}
// ************************************************************************
// Smart getters
// ************************************************************************
public boolean hasMultipleParallelBenchmarks() {
return parallelBenchmarkCount == null || parallelBenchmarkCount > 1;
}
public boolean hasAnyFailure() {
return failureCount > 0;
}
public int getMaximumSubSingleCount() {
int maximumSubSingleCount = 0;
for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
int problemMaximumSubSingleCount = problemBenchmarkResult.getMaximumSubSingleCount();
if (problemMaximumSubSingleCount > maximumSubSingleCount) {
maximumSubSingleCount = problemMaximumSubSingleCount;
}
}
return maximumSubSingleCount;
}
public String findScoreLevelLabel(int scoreLevel) {
String[] levelLabels = solverBenchmarkResultList.get(0).getScoreDefinition().getLevelLabels();
if (scoreLevel >= levelLabels.length) {
// Occurs when mixing multiple examples in the same benchmark run, such as GeneralOptaPlannerBenchmarkApp
return "unknown-" + (scoreLevel - levelLabels.length);
}
return levelLabels[scoreLevel];
}
public String getStartingTimestampAsMediumString() {
return startingTimestamp == null ? null
: startingTimestamp.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
}
// ************************************************************************
// Accumulate methods
// ************************************************************************
public void initBenchmarkReportDirectory(File benchmarkDirectory) {
String timestampString = startingTimestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss"));
if (name == null || name.isEmpty()) {
name = timestampString;
}
if (!benchmarkDirectory.mkdirs()) {
if (!benchmarkDirectory.isDirectory()) {
throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory
+ ") already exists, but is not a directory.");
}
if (!benchmarkDirectory.canWrite()) {
throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory
+ ") already exists, but is not writable.");
}
}
int duplicationIndex = 0;
do {
String directoryName = timestampString + (duplicationIndex == 0 ? "" : "_" + duplicationIndex);
duplicationIndex++;
benchmarkReportDirectory = new File(benchmarkDirectory,
(aggregation != null && !aggregation) ? directoryName : directoryName + "_aggregation");
} while (!benchmarkReportDirectory.mkdir());
for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
problemBenchmarkResult.makeDirs();
}
}
public void initSystemProperties() {
availableProcessors = Runtime.getRuntime().availableProcessors();
loggingLevelOptaPlannerCore = resolveLoggingLevel("org.optaplanner.core");
loggingLevelDroolsCore = resolveLoggingLevel("org.drools.core");
maxMemory = Runtime.getRuntime().maxMemory();
optaPlannerVersion = SolverFactory.class.getPackage().getImplementationVersion();
if (optaPlannerVersion == null) {
optaPlannerVersion = "Unjarred development snapshot";
}
javaVersion = "Java " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")";
javaVM = "Java " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version")
+ " (" + System.getProperty("java.vm.vendor") + ")";
operatingSystem = System.getProperty("os.name") + " " + System.getProperty("os.arch")
+ " " + System.getProperty("os.version");
}
private String resolveLoggingLevel(String loggerName) {
Logger logger = LoggerFactory.getLogger(loggerName);
if (logger.isTraceEnabled()) {
return "trace";
} else if (logger.isDebugEnabled()) {
return "debug";
} else if (logger.isInfoEnabled()) {
return "info";
} else if (logger.isWarnEnabled()) {
return "warn";
} else if (logger.isErrorEnabled()) {
return "error";
} else {
throw new IllegalStateException("Logging level for loggerName (" + loggerName + ") cannot be determined.");
}
}
public int getTotalSubSingleCount() {
int totalSubSingleCount = 0;
for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
totalSubSingleCount += problemBenchmarkResult.getTotalSubSingleCount();
}
return totalSubSingleCount;
}
public void accumulateResults(BenchmarkReport benchmarkReport) {
for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
problemBenchmarkResult.accumulateResults(benchmarkReport);
}
for (SolverBenchmarkResult solverBenchmarkResult : solverBenchmarkResultList) {
solverBenchmarkResult.accumulateResults(benchmarkReport);
}
determineTotalsAndAverages();
determineSolverRanking(benchmarkReport);
}
private void determineTotalsAndAverages() {
failureCount = 0;
long totalProblemScale = 0L;
int problemScaleCount = 0;
for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
Long problemScale = problemBenchmarkResult.getProblemScale();
if (problemScale != null && problemScale >= 0L) {
totalProblemScale += problemScale;
problemScaleCount++;
}
failureCount += problemBenchmarkResult.getFailureCount();
}
averageProblemScale = problemScaleCount == 0 ? null : totalProblemScale / problemScaleCount;
Score totalScore = null;
int solverBenchmarkCount = 0;
boolean firstSolverBenchmarkResult = true;
for (SolverBenchmarkResult solverBenchmarkResult : solverBenchmarkResultList) {
EnvironmentMode solverEnvironmentMode = solverBenchmarkResult.getEnvironmentMode();
if (firstSolverBenchmarkResult && solverEnvironmentMode != null) {
environmentMode = solverEnvironmentMode;
firstSolverBenchmarkResult = false;
} else if (!firstSolverBenchmarkResult && solverEnvironmentMode != environmentMode) {
environmentMode = null;
}
Score score = solverBenchmarkResult.getAverageScore();
if (score != null) {
ScoreDefinition scoreDefinition = solverBenchmarkResult.getScoreDefinition();
if (totalScore != null && !scoreDefinition.isCompatibleArithmeticArgument(totalScore)) {
// Mixing different use cases with different score definitions.
totalScore = null;
break;
}
totalScore = (totalScore == null) ? score : totalScore.add(score);
solverBenchmarkCount++;
}
}
if (totalScore != null) {
averageScore = totalScore.divide(solverBenchmarkCount);
}
}
private void determineSolverRanking(BenchmarkReport benchmarkReport) {
List<SolverBenchmarkResult> rankableSolverBenchmarkResultList = new ArrayList<>(solverBenchmarkResultList);
// Do not rank a SolverBenchmarkResult that has a failure
rankableSolverBenchmarkResultList.removeIf(SolverBenchmarkResult::hasAnyFailure);
List<List<SolverBenchmarkResult>> sameRankingListList = createSameRankingListList(
benchmarkReport, rankableSolverBenchmarkResultList);
int ranking = 0;
for (List<SolverBenchmarkResult> sameRankingList : sameRankingListList) {
for (SolverBenchmarkResult solverBenchmarkResult : sameRankingList) {
solverBenchmarkResult.setRanking(ranking);
}
ranking += sameRankingList.size();
}
favoriteSolverBenchmarkResult = sameRankingListList.isEmpty() ? null
: sameRankingListList.get(0).get(0);
}
private List<List<SolverBenchmarkResult>> createSameRankingListList(
BenchmarkReport benchmarkReport, List<SolverBenchmarkResult> rankableSolverBenchmarkResultList) {
List<List<SolverBenchmarkResult>> sameRankingListList = new ArrayList<>(
rankableSolverBenchmarkResultList.size());
if (benchmarkReport.getSolverRankingComparator() != null) {
Comparator<SolverBenchmarkResult> comparator = Collections.reverseOrder(
benchmarkReport.getSolverRankingComparator());
rankableSolverBenchmarkResultList.sort(comparator);
List<SolverBenchmarkResult> sameRankingList = null;
SolverBenchmarkResult previousSolverBenchmarkResult = null;
for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) {
if (previousSolverBenchmarkResult == null
|| comparator.compare(previousSolverBenchmarkResult, solverBenchmarkResult) != 0) {
// New rank
sameRankingList = new ArrayList<>();
sameRankingListList.add(sameRankingList);
}
sameRankingList.add(solverBenchmarkResult);
previousSolverBenchmarkResult = solverBenchmarkResult;
}
} else if (benchmarkReport.getSolverRankingWeightFactory() != null) {
SortedMap<Comparable, List<SolverBenchmarkResult>> rankedMap = new TreeMap<>(Collections.reverseOrder());
for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) {
Comparable rankingWeight = benchmarkReport.getSolverRankingWeightFactory()
.createRankingWeight(rankableSolverBenchmarkResultList, solverBenchmarkResult);
List<SolverBenchmarkResult> sameRankingList = rankedMap.computeIfAbsent(rankingWeight,
k -> new ArrayList<>());
sameRankingList.add(solverBenchmarkResult);
}
for (Map.Entry<Comparable, List<SolverBenchmarkResult>> entry : rankedMap.entrySet()) {
sameRankingListList.add(entry.getValue());
}
} else {
throw new IllegalStateException("Ranking is impossible" +
" because solverRankingComparator and solverRankingWeightFactory are null.");
}
return sameRankingListList;
}
// ************************************************************************
// Merger methods
// ************************************************************************
public static PlannerBenchmarkResult createMergedResult(
List<SingleBenchmarkResult> singleBenchmarkResultList) {
PlannerBenchmarkResult mergedResult = createMergeSingleton(singleBenchmarkResultList);
Map<SolverBenchmarkResult, SolverBenchmarkResult> solverMergeMap = SolverBenchmarkResult.createMergeMap(mergedResult,
singleBenchmarkResultList);
Map<ProblemBenchmarkResult, ProblemBenchmarkResult> problemMergeMap = ProblemBenchmarkResult
.createMergeMap(mergedResult, singleBenchmarkResultList);
for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) {
SolverBenchmarkResult solverBenchmarkResult = solverMergeMap.get(
singleBenchmarkResult.getSolverBenchmarkResult());
ProblemBenchmarkResult problemBenchmarkResult = problemMergeMap.get(
singleBenchmarkResult.getProblemBenchmarkResult());
SingleBenchmarkResult.createMerge(
solverBenchmarkResult, problemBenchmarkResult, singleBenchmarkResult);
}
return mergedResult;
}
protected static PlannerBenchmarkResult createMergeSingleton(List<SingleBenchmarkResult> singleBenchmarkResultList) {
PlannerBenchmarkResult newResult = null;
Map<PlannerBenchmarkResult, PlannerBenchmarkResult> mergeMap = new IdentityHashMap<>();
for (SingleBenchmarkResult singleBenchmarkResult : singleBenchmarkResultList) {
PlannerBenchmarkResult oldResult = singleBenchmarkResult
.getSolverBenchmarkResult().getPlannerBenchmarkResult();
if (!mergeMap.containsKey(oldResult)) {
if (newResult == null) {
newResult = new PlannerBenchmarkResult();
newResult.setAggregation(true);
newResult.availableProcessors = oldResult.availableProcessors;
newResult.loggingLevelOptaPlannerCore = oldResult.loggingLevelOptaPlannerCore;
newResult.loggingLevelDroolsCore = oldResult.loggingLevelDroolsCore;
newResult.maxMemory = oldResult.maxMemory;
newResult.optaPlannerVersion = oldResult.optaPlannerVersion;
newResult.javaVersion = oldResult.javaVersion;
newResult.javaVM = oldResult.javaVM;
newResult.operatingSystem = oldResult.operatingSystem;
newResult.parallelBenchmarkCount = oldResult.parallelBenchmarkCount;
newResult.warmUpTimeMillisSpentLimit = oldResult.warmUpTimeMillisSpentLimit;
newResult.environmentMode = oldResult.environmentMode;
newResult.solverBenchmarkResultList = new ArrayList<>();
newResult.unifiedProblemBenchmarkResultList = new ArrayList<>();
newResult.startingTimestamp = null;
newResult.benchmarkTimeMillisSpent = null;
} else {
newResult.availableProcessors = ConfigUtils.mergeProperty(
newResult.availableProcessors, oldResult.availableProcessors);
newResult.loggingLevelOptaPlannerCore = ConfigUtils.mergeProperty(
newResult.loggingLevelOptaPlannerCore, oldResult.loggingLevelOptaPlannerCore);
newResult.loggingLevelDroolsCore = ConfigUtils.mergeProperty(
newResult.loggingLevelDroolsCore, oldResult.loggingLevelDroolsCore);
newResult.maxMemory = ConfigUtils.mergeProperty(
newResult.maxMemory, oldResult.maxMemory);
newResult.optaPlannerVersion = ConfigUtils.mergeProperty(
newResult.optaPlannerVersion, oldResult.optaPlannerVersion);
newResult.javaVersion = ConfigUtils.mergeProperty(
newResult.javaVersion, oldResult.javaVersion);
newResult.javaVM = ConfigUtils.mergeProperty(
newResult.javaVM, oldResult.javaVM);
newResult.operatingSystem = ConfigUtils.mergeProperty(
newResult.operatingSystem, oldResult.operatingSystem);
newResult.parallelBenchmarkCount = ConfigUtils.mergeProperty(
newResult.parallelBenchmarkCount, oldResult.parallelBenchmarkCount);
newResult.warmUpTimeMillisSpentLimit = ConfigUtils.mergeProperty(
newResult.warmUpTimeMillisSpentLimit, oldResult.warmUpTimeMillisSpentLimit);
newResult.environmentMode = ConfigUtils.mergeProperty(
newResult.environmentMode, oldResult.environmentMode);
}
mergeMap.put(oldResult, newResult);
}
}
return newResult;
}
public static PlannerBenchmarkResult createUnmarshallingFailedResult(String benchmarkReportDirectoryName) {
PlannerBenchmarkResult result = new PlannerBenchmarkResult();
result.setName("Failed unmarshalling " + benchmarkReportDirectoryName);
result.setSolverBenchmarkResultList(Collections.emptyList());
result.setUnifiedProblemBenchmarkResultList(Collections.emptyList());
return result;
}
@Override
public String toString() {
return getName();
}
}
|
3e1bad6a70cb59437ed61d29ecb4a870f767f775 | 11,093 | java | Java | src/main/java/com/github/drbookings/cli/PayoutCommand.java | DrBookings/drbookings-cli | 4986ed60ae8ef59fbb83eb164192a95deec8e173 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/drbookings/cli/PayoutCommand.java | DrBookings/drbookings-cli | 4986ed60ae8ef59fbb83eb164192a95deec8e173 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/drbookings/cli/PayoutCommand.java | DrBookings/drbookings-cli | 4986ed60ae8ef59fbb83eb164192a95deec8e173 | [
"Apache-2.0"
] | null | null | null | 51.119816 | 117 | 0.712251 | 11,729 | package com.github.drbookings.cli;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import org.javamoney.moneta.Money;
import com.github.drbookings.BookingOrigin;
import com.github.drbookings.CleaningBeanFactory;
import com.github.drbookings.CleaningEntriesByOrigin;
import com.github.drbookings.CleaningExpensesFactory2;
import com.github.drbookings.DefaultGrossPaymentsSupplier2;
import com.github.drbookings.DefaultServiceFeesSupplier2;
import com.github.drbookings.Payments2;
import com.github.drbookings.SettingsManager;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
@Command(name = "payout", descriptionHeading = "..", description = { "..", ".." })
public class PayoutCommand extends AbstractFilterableByOriginCommand implements Runnable {
@Option(names = { "-c", "--cheat" }, description = "Put Other's costs to Booking and Airbnb.")
boolean cheat;
@Override
public void run() {
super.run();
try {
final MonetaryAmount grossPaymentsTotal = new DefaultGrossPaymentsSupplier2(getDateRange())
.apply(getBookings());
final MonetaryAmount grossPaymentsBooking = new DefaultGrossPaymentsSupplier2(getDateRange())
.apply(getBookingsInRange().getBookingElements());
final MonetaryAmount grossPaymentsAirbnb = new DefaultGrossPaymentsSupplier2(getDateRange())
.apply(getBookingsInRange().getAirbnbElements());
final MonetaryAmount grossPaymentsOther = new DefaultGrossPaymentsSupplier2(getDateRange())
.apply(getBookingsInRange().getOtherElements());
System.out.println();
System.out.println(
"Payout Chain " + getDateRange().lowerEndpoint() + " -> " + getDateRange().upperEndpoint() + ":");
System.out.println();
System.out.println("Total Gross Payments: " + String.format("%8.2f",
grossPaymentsTotal.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
// System.out.println("----------------------------------------------------");
System.out.println("Booking Gross Payments: " + String.format("%8.2f",
grossPaymentsBooking.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Airbnb Gross Payments: " + String.format("%8.2f",
grossPaymentsAirbnb.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Other Gross Payments: " + String.format("%8.2f",
grossPaymentsOther.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
final MonetaryAmount serviceFeesAll = new DefaultServiceFeesSupplier2(getDateRange()).apply(getBookings());
final MonetaryAmount serviceFeesBooking = new DefaultServiceFeesSupplier2(getDateRange())
.apply(getBookingsInRange().getBookingElements());
final MonetaryAmount serviceFeesAirbnb = new DefaultServiceFeesSupplier2(getDateRange())
.apply(getBookingsInRange().getAirbnbElements());
final MonetaryAmount serviceFeesOther = new DefaultServiceFeesSupplier2(getDateRange())
.apply(getBookingsInRange().getOtherElements());
System.out.println(StatisticsCommand.getServiceFeesString("Total", serviceFeesAll));
System.out.println(StatisticsCommand.getServiceFeesString("Booking", serviceFeesBooking));
System.out.println("Airbnb Service Fees: " + String.format("%8.2f",
serviceFeesAirbnb.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Other Service Fees: " + String.format("%8.2f",
serviceFeesOther.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
final double allNights = new NightsCounter(getDateRange()).apply();
final double allBookedNights = new SimpleNumberOfNightsCounter(getDateRange(), getBookings()).apply();
double allBookedNightsCheat = 0;
final double bookingNights = new SimpleNumberOfNightsCounter(getDateRange(), getBookings())
.setOrigin(new BookingOrigin("Booking")).apply();
final double airbnbNights = new SimpleNumberOfNightsCounter(getDateRange(), getBookings())
.setOrigin(new BookingOrigin("Airbnb")).apply();
final double otherNights = new SimpleNumberOfNightsCounter(getDateRange(), getBookings())
.setOrigin(new BookingOrigin("")).apply();
if (cheat) {
allBookedNightsCheat = allBookedNights - otherNights;
} else {
}
final double occupancyRateAll = (allBookedNights
/ (allNights * SettingsManager.getInstance().getNumberOfRooms())) * 100;
double occupancyRateAllCheat = 0;
final double occupancyRateBooking = (bookingNights / (cheat ? allBookedNightsCheat : allBookedNights))
* 100;
final double occupancyRateAirbnb = (airbnbNights / (cheat ? allBookedNightsCheat : allBookedNights)) * 100;
double occupancyRateOther = (otherNights / allBookedNights) * 100;
if (cheat) {
occupancyRateAllCheat = (allBookedNightsCheat
/ (allNights * SettingsManager.getInstance().getNumberOfRooms())) * 100;
occupancyRateOther = 0;
}
System.out.println("Total occupancy rate: " + String.format("%6.2f", occupancyRateAll) + "% ("
+ String.format("%3.0f", allBookedNights) + "/"
+ String.format("%3.0f", (allNights * SettingsManager.getInstance().getNumberOfRooms()))
+ " room nights busy)");
System.out.println("Cheat Tot. occup. rate: " + String.format("%6.2f", occupancyRateAllCheat) + "% ("
+ String.format("%3.0f", allBookedNightsCheat) + "/"
+ String.format("%3.0f", (allNights * SettingsManager.getInstance().getNumberOfRooms()))
+ " room nights busy)");
System.out.println("Booking occupancy rate: " + String.format("%6.2f", occupancyRateBooking) + "% ("
+ String.format("%3.0f", bookingNights) + "/"
+ String.format("%3.0f", cheat ? allBookedNightsCheat : allBookedNights) + " room nights busy)");
System.out.println("Airbnb occupancy rate: " + String.format("%6.2f", occupancyRateAirbnb) + "% ("
+ String.format("%3.0f", airbnbNights) + "/"
+ String.format("%3.0f", cheat ? allBookedNightsCheat : allBookedNights) + " room nights busy)");
System.out.println("Other occupancy rate: " + String.format("%6.2f", occupancyRateOther) + "% ("
+ String.format("%3.0f", otherNights) + "/" + String.format("%3.0f", cheat ? 0 : allBookedNights)
+ " room nights busy)");
final MonetaryAmount commonExpenses = Payments2.getSum(getExpensesInRange());
final MonetaryAmount commonExpensesBooking = (Double.isNaN(occupancyRateBooking)
|| Double.isInfinite(occupancyRateBooking) || (occupancyRateBooking == 0)) ? Money.of(0, "EUR")
: commonExpenses.multiply(occupancyRateBooking / 100);
final MonetaryAmount commonExpensesAirbnb = (Double.isNaN(occupancyRateAirbnb)
|| Double.isInfinite(occupancyRateAirbnb) || (occupancyRateAirbnb == 0)) ? Money.of(0, "EUR")
: commonExpenses.multiply(occupancyRateAirbnb / 100);
final MonetaryAmount commonExpensesOther = (Double.isNaN(occupancyRateOther)
|| Double.isInfinite(occupancyRateOther) || (occupancyRateOther == 0)) ? Money.of(0, "EUR")
: commonExpenses.multiply(occupancyRateOther / 100);
if (cheat) {
}
System.out.println("Total Common Expenses: " + String.format("%8.2f",
commonExpenses.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Booking Common Expenses: " + String.format("%8.2f",
commonExpensesBooking.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Airbnb Common Expenses: " + String.format("%8.2f",
commonExpensesAirbnb.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
System.out.println("Other Common Expenses: " + String.format("%8.2f",
commonExpensesOther.with(Monetary.getDefaultRounding()).getNumber().doubleValue()));
final CleaningEntriesByOrigin cbo = new CleaningEntriesByOrigin(new CleaningBeanFactory()
.setBookings(getAllBookings().getAllElements()).build(getCleaningsInRange()));
final MonetaryAmount totalCleanings = Payments2
.getSum(CleaningExpensesFactory2.build(cbo.getAllElements(), true));
final MonetaryAmount bookingCleanings = Payments2
.getSum(CleaningExpensesFactory2.build(cbo.getBookingElements(), true));
final MonetaryAmount airbnbCleanings = Payments2
.getSum(CleaningExpensesFactory2.build(cbo.getAirbnbElements(), true));
final double otherCleanings = Payments2.getSum(CleaningExpensesFactory2.build(cbo.getOtherElements(), true))
.getNumber().doubleValue();
System.out.println(
"Total Cleanings: " + String.format("%8.2f", totalCleanings.getNumber().doubleValue()));
System.out.println(
"Booking Cleanings: " + String.format("%8.2f", bookingCleanings.getNumber().doubleValue()));
System.out.println(
"Airbnb Cleanings: " + String.format("%8.2f", airbnbCleanings.getNumber().doubleValue()));
System.out.println("Other Cleanings: " + String.format("%8.2f", otherCleanings));
if (cheat) {
final double additionalBookingCleanings = otherCleanings * occupancyRateBooking;
final double additionalAirbnbCleanings = otherCleanings * occupancyRateAirbnb;
}
System.out.println();
System.out.println(
"Total profit: " + String.format("%8.2f", grossPaymentsTotal.subtract(serviceFeesAll)
.subtract(commonExpenses).subtract(totalCleanings).getNumber().doubleValue()));
System.out.println("----------------------------------------------------");
System.out.println(getPayoutString("Booking", grossPaymentsBooking, serviceFeesBooking,
commonExpensesBooking, bookingCleanings, 1f));
System.out.println(getPayoutString("Airbnb", grossPaymentsAirbnb, serviceFeesAirbnb, commonExpensesAirbnb,
airbnbCleanings, 1f));
System.out.println(getPayoutString("Sum", grossPaymentsAirbnb.add(grossPaymentsBooking),
serviceFeesAirbnb.add(serviceFeesBooking), commonExpensesAirbnb.add(commonExpensesBooking),
airbnbCleanings.add(bookingCleanings), 1f));
} catch (final Exception e) {
e.printStackTrace();
}
}
String getPayoutString(final String origin, final MonetaryAmount grossPayments, final MonetaryAmount serviceFees,
final MonetaryAmount commonExpenses, final MonetaryAmount cleaningExpenses, final float payoutFactor) {
final StringBuilder sb = new StringBuilder();
final MonetaryAmount payout = grossPayments.subtract(serviceFees).subtract(commonExpenses)
.subtract(cleaningExpenses);
sb.append(getPayoutString(origin, payout, payoutFactor));
return sb.toString();
}
private String getPayoutString(final String origin, final MonetaryAmount payout, final float f) {
final StringBuilder sb = new StringBuilder();
sb.append("Payout");
sb.append(String.format("%9s", origin));
sb.append(" (");
sb.append(String.format("%3.0f", f * 100));
sb.append("%): ");
sb.append(String.format("%7.2f", payout.multiply(f).getNumber().doubleValue()));
return sb.toString();
}
}
|
3e1badebf7df16c32d7774a6d3028f039d26a924 | 845 | java | Java | src/com/geekdigging/day040/Solution.java | meteor1993/LeetCode | 5c9932795cbed00cbc4f2adec0b61792d1a844c8 | [
"Apache-2.0"
] | 10 | 2020-07-28T02:03:28.000Z | 2021-03-08T02:24:21.000Z | src/com/geekdigging/day040/Solution.java | meteor1993/LeetCode | 5c9932795cbed00cbc4f2adec0b61792d1a844c8 | [
"Apache-2.0"
] | null | null | null | src/com/geekdigging/day040/Solution.java | meteor1993/LeetCode | 5c9932795cbed00cbc4f2adec0b61792d1a844c8 | [
"Apache-2.0"
] | 1 | 2021-01-20T09:07:11.000Z | 2021-01-20T09:07:11.000Z | 15.648148 | 78 | 0.465089 | 11,730 | package com.geekdigging.day040;
/**
* Created with IntelliJ IDEA.
*
* Excel表列序号
*
* 给定一个Excel表格中的列名称,返回其相应的列序号。
*
* 例如,
*
* A -> 1
* B -> 2
* C -> 3
* ...
* Z -> 26
* AA -> 27
* AB -> 28
* ...
* 示例 1:
*
* 输入: "A"
* 输出: 1
*
* 示例 2:
*
* 输入: "AB"
* 输出: 28
*
* 示例 3:
*
* 输入: "ZY"
* 输出: 701
*
* @Date: 2020/9/4
* @Time: 19:15
* @email: dycjh@example.com
* Description:
*/
public class Solution {
public int titleToNumber(String s) {
int sum = 0;
for (int i = s.length() - 1; i >= 0; i--) {
sum += (s.charAt(i) - 'A' + 1) * Math.pow(26, s.length() - i - 1);
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.titleToNumber("ZY"));
}
}
|
3e1baed961b70703e4c425376b8fb17402918bde | 1,222 | java | Java | AirVisualApiNetwork/app/src/main/java/kr/co/woobi/imyeon/airvisualapinetwork/Service.java | yeonyang9421/BroadCastExam | 182c4fbf09239b76ad056f9db780009a4b1e6b52 | [
"CC-BY-4.0"
] | null | null | null | AirVisualApiNetwork/app/src/main/java/kr/co/woobi/imyeon/airvisualapinetwork/Service.java | yeonyang9421/BroadCastExam | 182c4fbf09239b76ad056f9db780009a4b1e6b52 | [
"CC-BY-4.0"
] | null | null | null | AirVisualApiNetwork/app/src/main/java/kr/co/woobi/imyeon/airvisualapinetwork/Service.java | yeonyang9421/BroadCastExam | 182c4fbf09239b76ad056f9db780009a4b1e6b52 | [
"CC-BY-4.0"
] | null | null | null | 34.914286 | 158 | 0.731588 | 11,731 | package kr.co.woobi.imyeon.airvisualapinetwork;
import kr.co.woobi.imyeon.airvisualapinetwork.cityModel.CityLocationInfo;
import kr.co.woobi.imyeon.airvisualapinetwork.stateModel.StateLocationInfo;
import kr.co.woobi.imyeon.airvisualapinetwork.dustInfoModel.Example;
import kr.co.woobi.imyeon.airvisualapinetwork.countryModel.LocationDustInfo;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Service {
@GET("v2/nearest_city")
Call<Example> keyValue(@Query("key") String key);
@GET("v2/countries")
Call<LocationDustInfo> keyCountry (@Query("key") String key);
@GET("v2/states")
Call<StateLocationInfo> keyState (@Query("country") String country, @Query("key") String key);
@GET("v2/cities")
Call<CityLocationInfo> keyCity (@Query("state") String state, @Query("country") String country, @Query("key") String key );
@GET("v2/city")
Call<Example> keyCityStateCountry (@Query("city") String city, @Query("state") String state, @Query("country") String country, @Query("key") String key );
@GET("v2/nearest_city")
Call<Example> keylatLon(@Query("lat") Double lat, @Query("lon") Double lon, @Query("key") String key);
}
|
3e1baeeeb97be5030b4cc28b2de913c5a8089ede | 6,327 | java | Java | handlers/src/main/java/kendal/handlers/TypescriptFieldsHandler.java | projectkendal/handlers | 0d46218e268b7df9e0374642fca7ccb814f945c4 | [
"MIT"
] | 1 | 2019-01-02T16:49:38.000Z | 2019-01-02T16:49:38.000Z | handlers/src/main/java/kendal/handlers/TypescriptFieldsHandler.java | projectkendal/handlers | 0d46218e268b7df9e0374642fca7ccb814f945c4 | [
"MIT"
] | null | null | null | handlers/src/main/java/kendal/handlers/TypescriptFieldsHandler.java | projectkendal/handlers | 0d46218e268b7df9e0374642fca7ccb814f945c4 | [
"MIT"
] | null | null | null | 40.819355 | 160 | 0.714399 | 11,732 | package kendal.handlers;
import static kendal.utils.AnnotationUtils.isPutOnAnnotation;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Name;
import kendal.annotations.PackagePrivate;
import kendal.annotations.Private;
import kendal.annotations.Protected;
import kendal.annotations.Public;
import kendal.api.AstHelper;
import kendal.api.AstHelper.Mode;
import kendal.api.AstNodeBuilder;
import kendal.api.KendalHandler;
import kendal.api.Modifier;
import kendal.api.exceptions.DuplicatedElementsException;
import kendal.api.exceptions.ImproperNodeTypeException;
import kendal.api.exceptions.InvalidAnnotationException;
import kendal.api.exceptions.KendalException;
import kendal.model.Node;
/**
* Performs field generation for classes with constructors having parameters annotated with one of "TypeScript Fields" feature annotations.
* These are {@link Private}, {@link PackagePrivate}, {@link Protected} and {@link Public}.
*
* @param <T> parameter specifying which exact annotation is handled by a given handler.
*/
public abstract class TypescriptFieldsHandler<T extends Annotation> implements KendalHandler<T> {
private AstHelper helper;
private AstNodeBuilder astNodeBuilder;
/**
* This method assumes that all passed annotatedNodes are annotated with one of the following annotations:
* {@link Private}, {@link PackagePrivate}, {@link Protected}, {@link Public}.
*/
@Override
public void handle(Collection<Node> handledNodes, AstHelper helper) throws KendalException {
this.helper = helper;
astNodeBuilder = helper.getAstNodeBuilder();
for (Node annotationNode : handledNodes) {
handleNode(annotationNode);
}
}
private void handleNode(Node<JCAnnotation> annotationNode) throws KendalException {
if (isPutOnAnnotation(annotationNode)) {
return; // because there is nothing to handle in such case
}
Node<JCMethodDecl> constructor = (Node<JCMethodDecl>) annotationNode.getParent().getParent();
if (!helper.getAstValidator().isConstructor(constructor)) {
throw new InvalidAnnotationException(
String.format("%s Annotated element must be parameter of a constructor!", annotationNode.getObject().toString()));
}
List<Modifier> modifiers = getModifiers(getFinalParamValue(annotationNode));
Node<JCClassDecl> clazz = (Node<JCClassDecl>) constructor.getParent();
Name name = ((JCVariableDecl)annotationNode.getParent().getObject()).name;
Node<JCVariableDecl> existingField = helper.findFieldByNameAndType(clazz, name);
Node<JCVariableDecl> newVariable = astNodeBuilder.variableDecl().build(modifiers,
((JCVariableDecl) annotationNode.getParent().getObject()).vartype, name, annotationNode);
if (existingField == null) {
helper.addElementToClass(clazz, newVariable, Mode.APPEND, 0);
} else {
if (!existingField.isAddedByHandler()) {
throw new DuplicatedElementsException("Auto generated field was already defined manually in this class!");
}
if (existingField.getObject().getModifiers().flags != newVariable.getObject().getModifiers().flags
|| !existingField.getObject().vartype.type.equals(newVariable.getObject().vartype.type)) {
throw new InvalidAnnotationException(String.format("Auto generated field %s in class %s occurred more than once, with inconsistent definition!",
existingField.getObject().name.toString(), clazz.getObject().name.toString()));
}
// here we have the case of identical field defined in more than one constructor. Let it be, skip field creation and just assign the value
}
addVariableAssignmentStatementToConstructor(constructor, newVariable);
}
private void addVariableAssignmentStatementToConstructor(Node<JCMethodDecl> constructor, Node<JCVariableDecl> variable)
throws ImproperNodeTypeException {
Node<JCIdent> objectRef = astNodeBuilder.identifier().build("this");
Node<JCFieldAccess> fieldAccess = astNodeBuilder.fieldAccess().build(objectRef, variable.getObject().name);
Node<JCIdent> newVariableRef = astNodeBuilder.identifier().build(variable.getObject().name);
Node<JCExpressionStatement> assignment = astNodeBuilder.buildAssignmentStatement(fieldAccess, newVariableRef);
helper.addExpressionStatementToConstructor(constructor, assignment, Mode.PREPEND, 0);
}
private List<Modifier> getModifiers(boolean finalParamValue) {
List<Modifier> list = new ArrayList<>();
list.add(getModifier());
if (finalParamValue) {
list.add(Modifier.FINAL);
}
return list;
}
private boolean getFinalParamValue(Node<JCAnnotation> sourceAnnotationNode) {
return (boolean) helper.getAnnotationValues(sourceAnnotationNode).get("makeFinal");
}
abstract Modifier getModifier();
public static class PrivateHandler extends TypescriptFieldsHandler<Private> {
@Override
Modifier getModifier() {
return Modifier.PRIVATE;
}
}
public static class ProtectedHandler extends TypescriptFieldsHandler<Protected> {
@Override
Modifier getModifier() {
return Modifier.PROTECTED;
}
}
public static class PackagePrivateHandler extends TypescriptFieldsHandler<PackagePrivate> {
@Override
Modifier getModifier() {
return Modifier.PACKAGE_PRIVATE;
}
}
public static class PublicHandler extends TypescriptFieldsHandler<Public> {
@Override
Modifier getModifier() {
return Modifier.PUBLIC;
}
}
}
|
3e1baf5f50bb0882be7bb7695a3fc8da5f9d974d | 3,374 | java | Java | app/src/main/java/com/tool/horizontalrecyclerview/PageIndicatorView.java | Xingzuo888/tool | 41f76b16ed3d5fdbc50f92634cf63859be12dd4e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tool/horizontalrecyclerview/PageIndicatorView.java | Xingzuo888/tool | 41f76b16ed3d5fdbc50f92634cf63859be12dd4e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tool/horizontalrecyclerview/PageIndicatorView.java | Xingzuo888/tool | 41f76b16ed3d5fdbc50f92634cf63859be12dd4e | [
"Apache-2.0"
] | null | null | null | 29.086207 | 109 | 0.590694 | 11,733 | package com.tool.horizontalrecyclerview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import com.nextclass.ai.nxfastinstall.R;
import java.util.ArrayList;
import java.util.List;
/**
* <p/>
* 页码指示器类,获得此类实例后,可通过{@link com.nextclass.ai.nxfastinstall.view.PageIndicatorView#initIndicator(int)}方法初始化指示器
* </P>
*/
public class PageIndicatorView extends LinearLayout {
private Context mContext = null;
private int dotSize = 17; // 指示器的大小(dp)
private int margins = 15; // 指示器间距(dp)
private List<View> indicatorViews = null; // 存放指示器
private PageOnClickLisener mListener = null;
public PageIndicatorView(Context context) {
this(context, null);
}
public PageIndicatorView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PageIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
this.mContext = context;
setGravity(Gravity.CENTER);
setOrientation(HORIZONTAL);
//dotSize = Utils.dip2px(context, dotSize);
//margins = Utils.dip2px(context, margins);
}
/**
* 初始化指示器,默认选中第一页
*
* @param count 指示器数量,即页数
*/
public void initIndicator(int count) {
if (indicatorViews == null) {
indicatorViews = new ArrayList<>();
} else {
indicatorViews.clear();
removeAllViews();
}
//只有一页时不显示
if (count < 2) {
return;
}
View view;
LayoutParams params = new LayoutParams(dotSize, dotSize);
params.setMargins(margins, margins, margins, margins);
for (int i = 0; i < count; i++) {
view = new View(mContext);
view.setBackgroundResource(R.drawable.page_indicator_new_unselect);
view.setTag(i);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
int pos = (int) view.getTag();
if (mListener != null) {
mListener.onClicked(pos);
}
}
});
addView(view, params);
indicatorViews.add(view);
}
if (indicatorViews.size() > 0) {
indicatorViews.get(0).setBackgroundResource(R.drawable.page_indicator_new_selected);
}
}
/**
* 设置选中页
*
* @param selected 页下标,从0开始
*/
public void setSelectedPage(int selected) {
if (indicatorViews != null && indicatorViews.size() > 0) {
for (int i = 0; i < indicatorViews.size(); i++) {
if (i == selected) {
indicatorViews.get(i).setBackgroundResource(R.drawable.page_indicator_new_selected);
} else {
indicatorViews.get(i).setBackgroundResource(R.drawable.page_indicator_new_unselect);
}
}
}
}
public void setOnPageClickListener(PageOnClickLisener lisener) {
mListener = lisener;
}
public interface PageOnClickLisener {
public void onClicked(int position);
}
} |
3e1bb153be62264b7cd840eb05de28075b4051ba | 19,698 | java | Java | animated-icons/src/main/java/tarek360/animated/icons/drawables/Like.java | anoop44/Animated-Icons | f8acb3250244e815fb3354313d84e88073aab3f9 | [
"Apache-2.0"
] | 249 | 2016-11-19T23:17:42.000Z | 2022-01-31T14:36:25.000Z | animated-icons/src/main/java/tarek360/animated/icons/drawables/Like.java | anoop44/Animated-Icons | f8acb3250244e815fb3354313d84e88073aab3f9 | [
"Apache-2.0"
] | 4 | 2016-11-26T07:15:47.000Z | 2017-10-16T12:06:57.000Z | animated-icons/src/main/java/tarek360/animated/icons/drawables/Like.java | anoop44/Animated-Icons | f8acb3250244e815fb3354313d84e88073aab3f9 | [
"Apache-2.0"
] | 51 | 2016-11-20T10:48:35.000Z | 2020-12-21T12:23:29.000Z | 59.87234 | 98 | 0.694284 | 11,734 | package tarek360.animated.icons.drawables;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.Log;
import android.view.animation.AccelerateDecelerateInterpolator;
public class Like extends AnimatedIcon {
private static final String TAG = Settings.class.getSimpleName();
private float viewBoxWidth = 1024;
private float viewBoxHeight = 1024;
private int animationDuration;
private int color;
private Path p = new Path();
private Paint paint = new Paint();
private float translateY;
private float scale = 1;
private float rotation;
public Like() {
animationDuration = 800;
color = Color.WHITE;
}
@Override public void draw(Canvas canvas) {
paint.setAntiAlias(true);
Rect bounds = getBounds();
if (viewBoxHeight <= 0 || viewBoxWidth <= 0 || bounds.width() <= 0 || bounds.height() <= 0) {
return;
}
canvas.save();
float viewBoxRatio = viewBoxWidth / (float) viewBoxHeight;
float boundsRatio = bounds.width() / (float) bounds.height();
float factorScale;
if (boundsRatio > viewBoxRatio) {
// canvas larger than viewbox
factorScale = bounds.height() / (float) viewBoxHeight;
} else {
// canvas higher (or equals) than viewbox
factorScale = bounds.width() / (float) viewBoxWidth;
}
int newViewBoxHeight = Math.round(factorScale * viewBoxHeight);
int newViewBoxWidth = Math.round(factorScale * viewBoxWidth);
int marginX = bounds.width() - newViewBoxWidth;
int marginY = bounds.height() - newViewBoxHeight;
canvas.translate(bounds.left, bounds.top);
canvas.translate(Math.round(marginX / 2f), Math.round(marginY / 2f));
canvas.clipRect(0, 0, newViewBoxWidth, newViewBoxHeight);
canvas.translate(0, factorScale * translateY);
canvas.scale(scale, scale, newViewBoxWidth / 2, newViewBoxHeight / 2);
canvas.rotate(rotation, newViewBoxWidth / 2, newViewBoxHeight / 2);
p.reset();
p.moveTo(factorScale * 824.710022f, factorScale * 482.136993f);
p.rCubicTo(factorScale * -29.694000f, factorScale * -7.792000f, factorScale * -99.510002f,
factorScale * -7.697000f, factorScale * -201.632996f, factorScale * -10.405000f);
p.rCubicTo(factorScale * 4.822000f, factorScale * -22.282000f, factorScale * 5.939000f,
factorScale * -42.379002f, factorScale * 5.939000f, factorScale * -78.058998f);
p.rCubicTo(factorScale * 0.000000f, factorScale * -85.233002f, factorScale * -62.096001f,
factorScale * -160.298996f, factorScale * -117.016998f, factorScale * -160.298996f);
p.rCubicTo(factorScale * -38.792000f, factorScale * 0.000000f, factorScale * -70.765999f,
factorScale * 31.712999f, factorScale * -71.264999f, factorScale * 70.719002f);
p.rCubicTo(factorScale * -0.523000f, factorScale * 47.842999f, factorScale * -15.322000f,
factorScale * 130.462997f, factorScale * -95.019997f, factorScale * 172.365997f);
p.rCubicTo(factorScale * -5.844000f, factorScale * 3.088000f, factorScale * -22.566999f,
factorScale * 11.331000f, factorScale * -25.014000f, factorScale * 12.400000f);
p.rLineTo(factorScale * 1.259000f, factorScale * 1.069000f);
p.rCubicTo(factorScale * -12.471000f, factorScale * -10.761000f, factorScale * -29.764999f,
factorScale * -19.004000f, factorScale * -47.509998f, factorScale * -19.004000f);
p.rLineTo(factorScale * -71.264999f, 0);
p.rCubicTo(factorScale * -39.291000f, factorScale * 0.000000f, factorScale * -71.264999f,
factorScale * 31.974001f, factorScale * -71.264999f, factorScale * 71.264999f);
p.rLineTo(0, factorScale * 380.079987f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 39.291000f, factorScale * 31.974001f,
factorScale * 71.264999f, factorScale * 71.264999f, factorScale * 71.264999f);
p.rLineTo(factorScale * 71.264999f, 0);
p.rCubicTo(factorScale * 28.268000f, factorScale * 0.000000f, factorScale * 51.928001f,
factorScale * -17.080000f, factorScale * 63.377998f, factorScale * -41.025002f);
p.rCubicTo(factorScale * 0.285000f, factorScale * 0.095000f, factorScale * 0.784000f,
factorScale * 0.238000f, factorScale * 1.116000f, factorScale * 0.285000f);
p.rCubicTo(factorScale * 1.568000f, factorScale * 0.428000f, factorScale * 3.421000f,
factorScale * 0.879000f, factorScale * 5.677000f, factorScale * 1.473000f);
p.rCubicTo(factorScale * 0.428000f, factorScale * 0.119000f, factorScale * 0.641000f,
factorScale * 0.166000f, factorScale * 1.093000f, factorScale * 0.285000f);
p.rCubicTo(factorScale * 13.683000f, factorScale * 3.397000f, factorScale * 40.027000f,
factorScale * 9.692000f, factorScale * 96.327003f, factorScale * 22.639000f);
p.rCubicTo(factorScale * 12.068000f, factorScale * 2.756000f, factorScale * 75.825996f,
factorScale * 16.343000f, factorScale * 141.865005f, factorScale * 16.343000f);
p.rLineTo(factorScale * 129.869003f, 0);
p.rCubicTo(factorScale * 39.576000f, factorScale * 0.000000f, factorScale * 68.106003f,
factorScale * -15.227000f, factorScale * 85.091003f, factorScale * -45.799999f);
p.rCubicTo(factorScale * 0.238000f, factorScale * -0.475000f, factorScale * 5.701000f,
factorScale * -11.141000f, factorScale * 10.167000f, factorScale * -25.559999f);
p.rCubicTo(factorScale * 3.349000f, factorScale * -10.856000f, factorScale * 4.585000f,
factorScale * -26.226000f, factorScale * 0.546000f, factorScale * -41.808998f);
p.rCubicTo(factorScale * 25.513000f, factorScale * -17.531000f, factorScale * 33.731998f,
factorScale * -44.042000f, factorScale * 39.077000f, factorScale * -61.287998f);
p.rCubicTo(factorScale * 8.956000f, factorScale * -28.292000f, factorScale * 6.271000f,
factorScale * -49.553001f, factorScale * 0.048000f, factorScale * -64.779999f);
p.rCubicTo(factorScale * 14.348000f, factorScale * -13.540000f, factorScale * 26.582001f,
factorScale * -34.182999f, factorScale * 31.737000f, factorScale * -65.706001f);
p.rCubicTo(factorScale * 3.207000f, factorScale * -19.527000f, factorScale * -0.238000f,
factorScale * -39.623001f, factorScale * -9.241000f, factorScale * -56.347000f);
p.rCubicTo(factorScale * 13.445000f, factorScale * -15.108000f, factorScale * 19.573999f,
factorScale * -34.112000f, factorScale * 20.287001f, factorScale * -51.691002f);
p.rLineTo(factorScale * 0.285000f, factorScale * -4.965000f);
p.rCubicTo(factorScale * 0.166000f, factorScale * -3.112000f, factorScale * 0.309000f,
factorScale * -5.036000f, factorScale * 0.309000f, factorScale * -11.878000f);
p.cubicTo(factorScale * 892.078979f, factorScale * 533.708984f, factorScale * 871.294006f,
factorScale * 495.440002f, factorScale * 824.710022f, factorScale * 482.136993f);
p.lineTo(factorScale * 824.710022f, factorScale * 482.136993f);
p.close();
p.moveTo(factorScale * 824.710022f, factorScale * 482.136993f);
p.moveTo(factorScale * 298.204010f, factorScale * 922.270020f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 13.136000f, factorScale * -10.618000f,
factorScale * 23.754999f, factorScale * -23.754999f, factorScale * 23.754999f);
p.rLineTo(factorScale * -71.264999f, 0);
p.rCubicTo(factorScale * -13.137000f, factorScale * 0.000000f, factorScale * -23.754999f,
factorScale * -10.619000f, factorScale * -23.754999f, factorScale * -23.754999f);
p.lineTo(factorScale * 179.429001f, factorScale * 542.190002f);
p.rCubicTo(factorScale * 0.000000f, factorScale * -13.137000f, factorScale * 10.618000f,
factorScale * -23.754999f, factorScale * 23.754999f, factorScale * -23.754999f);
p.rLineTo(factorScale * 71.264999f, 0);
p.rCubicTo(factorScale * 13.137000f, factorScale * 0.000000f, factorScale * 23.754999f,
factorScale * 10.618000f, factorScale * 23.754999f, factorScale * 23.754999f);
p.lineTo(factorScale * 298.204010f, factorScale * 922.270020f);
p.close();
p.moveTo(factorScale * 298.204010f, factorScale * 922.270020f);
p.moveTo(factorScale * 795.588013f, factorScale * 637.210022f);
p.rCubicTo(factorScale * 35.632000f, factorScale * -0.238000f, factorScale * 40.312000f,
factorScale * 29.551001f, factorScale * 38.007999f, factorScale * 43.804001f);
p.rCubicTo(factorScale * -2.946000f, factorScale * 17.721001f, factorScale * -11.260000f,
factorScale * 51.216000f, factorScale * -51.382000f, factorScale * 51.216000f);
p.rCubicTo(factorScale * -40.075001f, factorScale * 0.000000f, factorScale * -56.417999f,
factorScale * 0.000000f, factorScale * -56.417999f, factorScale * 0.000000f);
p.rCubicTo(factorScale * -6.580000f, factorScale * 0.000000f, factorScale * -38.230999f,
factorScale * 5.297000f, factorScale * -38.230999f, factorScale * 11.878000f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 6.533000f, factorScale * 31.650999f,
factorScale * 11.878000f, factorScale * 38.230999f, factorScale * 11.878000f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 0.000000f, factorScale * 28.221001f,
factorScale * 0.000000f, factorScale * 46.773998f, factorScale * 0.000000f);
p.rCubicTo(factorScale * 40.098000f, factorScale * 0.000000f, factorScale * 36.558998f,
factorScale * 30.573000f, factorScale * 30.809999f, factorScale * 48.817001f);
p.rCubicTo(factorScale * -7.578000f, factorScale * 23.969000f, factorScale * -12.210000f,
factorScale * 46.202999f, factorScale * -62.737000f, factorScale * 46.202999f);
p.rCubicTo(factorScale * -17.080000f, factorScale * 0.000000f, factorScale * -38.743999f,
factorScale * 0.000000f, factorScale * -38.743999f, factorScale * 0.000000f);
p.rCubicTo(factorScale * -6.580000f, factorScale * 0.000000f, factorScale * -38.831001f,
factorScale * 5.297000f, factorScale * -38.831001f, factorScale * 11.878000f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 6.533000f, factorScale * 32.250000f,
factorScale * 11.878000f, factorScale * 38.831001f, factorScale * 11.878000f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 0.000000f, factorScale * 16.462000f,
factorScale * 0.000000f, factorScale * 37.248001f, factorScale * 0.000000f);
p.rCubicTo(factorScale * 25.988001f, factorScale * 0.000000f, factorScale * 27.200001f,
factorScale * 24.586000f, factorScale * 24.490999f, factorScale * 33.400002f);
p.rCubicTo(factorScale * -2.969000f, factorScale * 9.645000f, factorScale * -6.485000f,
factorScale * 16.795000f, factorScale * -6.628000f, factorScale * 17.127001f);
p.rCubicTo(factorScale * -7.174000f, factorScale * 12.946000f, factorScale * -18.743000f,
factorScale * 20.738001f, factorScale * -43.234001f, factorScale * 20.738001f);
p.lineTo(factorScale * 583.906006f, factorScale * 946.027039f);
p.rCubicTo(factorScale * -65.231003f, factorScale * 0.000000f, factorScale * -129.940002f,
factorScale * -14.799000f, factorScale * -131.602997f, factorScale * -15.179000f);
p.rCubicTo(factorScale * -98.678001f, factorScale * -22.733999f, factorScale * -103.880997f,
factorScale * -24.490999f, factorScale * -110.081001f, factorScale * -26.249001f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 0.000000f, factorScale * -20.097000f,
factorScale * -3.397000f, factorScale * -20.097000f, factorScale * -20.927999f);
p.rLineTo(factorScale * -0.166000f, factorScale * -328.104004f);
p.rCubicTo(factorScale * 0.000000f, factorScale * -11.141000f, factorScale * 7.103000f,
factorScale * -21.212999f, factorScale * 18.861000f, factorScale * -24.753000f);
p.rCubicTo(factorScale * 1.473000f, factorScale * -0.570000f, factorScale * 3.468000f,
factorScale * -1.188000f, factorScale * 4.894000f, factorScale * -1.782000f);
p.rCubicTo(factorScale * 108.513000f, factorScale * -44.945000f, factorScale * 141.556000f,
factorScale * -143.479996f, factorScale * 142.529999f, factorScale * -224.389999f);
p.rCubicTo(factorScale * 0.143000f, factorScale * -11.379000f, factorScale * 8.908000f,
factorScale * -23.754999f, factorScale * 23.754999f, factorScale * -23.754999f);
p.rCubicTo(factorScale * 25.108999f, factorScale * 0.000000f, factorScale * 69.507004f,
factorScale * 50.408001f, factorScale * 69.507004f, factorScale * 112.789001f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 56.323002f, factorScale * -2.280000f,
factorScale * 66.063004f, factorScale * -21.997000f, factorScale * 124.761002f);
p.rCubicTo(factorScale * 237.550003f, factorScale * 0.000000f, factorScale * 235.886993f,
factorScale * 3.421000f, factorScale * 256.838989f, factorScale * 8.908000f);
p.rCubicTo(factorScale * 25.988001f, factorScale * 7.435000f, factorScale * 28.221001f,
factorScale * 28.957001f, factorScale * 28.221001f, factorScale * 36.368999f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 8.148000f, factorScale * -0.238000f,
factorScale * 6.960000f, factorScale * -0.546000f, factorScale * 14.942000f);
p.rCubicTo(factorScale * -0.475000f, factorScale * 11.735000f, factorScale * -5.392000f,
factorScale * 34.800999f, factorScale * -46.964001f, factorScale * 34.800999f);
p.rCubicTo(factorScale * -40.075001f, factorScale * 0.000000f, factorScale * -48.268002f,
factorScale * 0.000000f, factorScale * -48.268002f, factorScale * 0.000000f);
p.rCubicTo(factorScale * -6.580000f, factorScale * 0.000000f, factorScale * -38.230999f,
factorScale * 5.297000f, factorScale * -38.230999f, factorScale * 11.878000f);
p.rCubicTo(factorScale * 0.000000f, factorScale * 6.533000f, factorScale * 31.650999f,
factorScale * 11.878000f, factorScale * 38.230999f, factorScale * 11.878000f);
p.cubicTo(factorScale * 748.791992f, factorScale * 637.210022f, factorScale * 777.033997f,
factorScale * 637.210022f, factorScale * 795.588013f, factorScale * 637.210022f);
p.moveTo(factorScale * 238.815994f, factorScale * 851.005005f);
p.rCubicTo(factorScale * -19.669001f, factorScale * 0.000000f, factorScale * -35.632999f,
factorScale * 15.963000f, factorScale * -35.632999f, factorScale * 35.632999f);
p.cubicTo(factorScale * 203.182999f, factorScale * 906.307983f, factorScale * 219.145996f,
factorScale * 922.270996f, factorScale * 238.815994f, factorScale * 922.270996f);
p.cubicTo(factorScale * 258.485992f, factorScale * 922.270996f, factorScale * 274.449005f,
factorScale * 906.307983f, factorScale * 274.449005f, factorScale * 886.638000f);
p.cubicTo(factorScale * 274.449005f, factorScale * 866.968018f, factorScale * 258.485992f,
factorScale * 851.005005f, factorScale * 238.815994f, factorScale * 851.005005f);
p.close();
p.moveTo(factorScale * 238.815994f, factorScale * 851.005005f);
p.moveTo(factorScale * 238.815994f, factorScale * 898.515015f);
p.rCubicTo(factorScale * -6.533000f, factorScale * 0.000000f, factorScale * -11.878000f,
factorScale * -5.345000f, factorScale * -11.878000f, factorScale * -11.878000f);
p.cubicTo(factorScale * 226.937988f, factorScale * 880.104004f, factorScale * 232.282990f,
factorScale * 874.759033f, factorScale * 238.815994f, factorScale * 874.759033f);
p.cubicTo(factorScale * 245.348999f, factorScale * 874.759033f, factorScale * 250.694000f,
factorScale * 880.104004f, factorScale * 250.694000f, factorScale * 886.637024f);
p.cubicTo(factorScale * 250.694000f, factorScale * 893.170044f, factorScale * 245.348999f,
factorScale * 898.515015f, factorScale * 238.815994f, factorScale * 898.515015f);
p.close();
p.moveTo(factorScale * 238.815994f, factorScale * 898.515015f);
p.setFillType(Path.FillType.EVEN_ODD);
paint.setShader(null);
paint.setColor(color);
paint.setAlpha(255);
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(p, paint);
canvas.restore();
}
@Override public void setAlpha(int alpha) {
}
@Override public void setColorFilter(ColorFilter cf) {
}
@Override public int getOpacity() {
return 0;
}
@Override public int getMinimumHeight() {
return 10;
}
@Override public int getMinimumWidth() {
return 10;
}
@Override public void startAnimation() {
ValueAnimator scaleAnimator = ValueAnimator.ofFloat(1, 1.15f, 1);
// scaleAnimator.setRepeatMode(ValueAnimator.RESTART);
// scaleAnimator.setRepeatCount(1);
scaleAnimator.setDuration(400);
scaleAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
scaleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
Log.i("animation", "animatedValue " + animatedValue);
scale = animatedValue;
invalidateSelf();
}
});
ValueAnimator rotationAnimator = ValueAnimator.ofFloat(0, -15, 0);
// rotationAnimator.setRepeatMode(ValueAnimator.RESTART);
// rotationAnimator.setRepeatCount(1);
rotationAnimator.setDuration(400);
rotationAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
rotationAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
Log.i("animation", "animatedValue " + animatedValue);
rotation = animatedValue;
invalidateSelf();
}
});
ValueAnimator translatAnimator = ValueAnimator.ofFloat(0, -230, 0);
// translatAnimator.setRepeatMode(ValueAnimator.RESTART);
// translatAnimator.setRepeatCount(1);
translatAnimator.setDuration(400);
translatAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
translatAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
Log.i("animation", "animatedValue " + animatedValue);
translateY = animatedValue;
invalidateSelf();
}
});
ValueAnimator vibrateAnimator = ValueAnimator.ofFloat(0, -100, 0);
vibrateAnimator.setDuration(400);
vibrateAnimator.setStartDelay(400);
vibrateAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
vibrateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
Log.i("animation", "animatedValue " + animatedValue);
translateY = animatedValue;
invalidateSelf();
}
});
AnimatorSet set = new AnimatorSet();
set.playTogether(scaleAnimator, rotationAnimator, translatAnimator);
set.start();
}
}
|
3e1bb1b4891f9fe5403e696a68fd8a950db426f1 | 2,958 | java | Java | android-util-master/src/main/java/com/xjf/repository/utils/DES.java | zqh110110/base_http_rxjava_databing_commonutil | 8c37a80cce159eed2641d06b4a571af6162ba916 | [
"Apache-2.0"
] | null | null | null | android-util-master/src/main/java/com/xjf/repository/utils/DES.java | zqh110110/base_http_rxjava_databing_commonutil | 8c37a80cce159eed2641d06b4a571af6162ba916 | [
"Apache-2.0"
] | null | null | null | android-util-master/src/main/java/com/xjf/repository/utils/DES.java | zqh110110/base_http_rxjava_databing_commonutil | 8c37a80cce159eed2641d06b4a571af6162ba916 | [
"Apache-2.0"
] | null | null | null | 21.75 | 73 | 0.672752 | 11,735 | /*
* DES 20091106
*
* Copyright (c) 2009 北京数字政通科技股份有限公司
* 版权所有
*
* 文件功能描述:DES加密解密类
*
* 修改标识:史先方20091106
* 修改描述:创建
*/
package com.xjf.repository.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
* 将字符串进行DES加密解密
*
* @version 0.1 20091106
* @author 史先方
*/
public class DES {
/** 加密KEY */
private static final byte[] KEY = "7;9Ku7;:84VG*B78".getBytes();
/** 算法 */
private static final String ALGORITHM = "DES";
/** IV */
private static final byte[] IV = "sHjrydLq".getBytes();
/** TRANSFORMATION */
private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";
private int code = 0;
public DES() {
}
/**
* 构造函数
* @param code 加密方式:0-“ISO-8859-1”编码,1-base64编码,其它-默认编码(utf-8)
*/
public DES(int code) {
this.code = code;
}
/**
* 将字符串进行DES加密
* @param source 未加密源字符串
* @return 加密后字符串
*/
public String encrypt(String source) {
byte[] retByte = null;
// Create SecretKey object
DESKeySpec dks = null;
try {
dks = new DESKeySpec(KEY);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Create IvParameterSpec object with initialization vector
IvParameterSpec spec = new IvParameterSpec(IV);
// Create Cipter object
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// Initialize Cipher object
cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);
// Decrypting data
retByte = cipher.doFinal(source.getBytes());
String result = "";
if (code == 0) {
result = new String(retByte, "ISO-8859-1");
} else if (code == 1) {
result = Base64.encodeToString(retByte,false);
} else {
result = new String(retByte);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将DES加密的字符串解密
* @param encrypted 加密过的字符串
* @return 未加密源字符串
*/
public String decrypt(String encrypted) {
byte[] retByte = null;
// Create SecretKey object
DESKeySpec dks = null;
try {
dks = new DESKeySpec(KEY);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Create IvParameterSpec object with initialization vector
IvParameterSpec spec = new IvParameterSpec(IV);
// Create Cipter object
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// Initialize Cipher object
cipher.init(Cipher.DECRYPT_MODE, securekey, spec);
if (code == 0) {
retByte = encrypted.getBytes("ISO-8859-1");
} else if (code == 1) {
retByte = Base64.decode(encrypted);
} else {
retByte = encrypted.getBytes();
}
// Decrypting data
retByte = cipher.doFinal(retByte);
return new String(retByte, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
3e1bb1fe4c688aca266baff25fd692e0018d0cd0 | 11,970 | java | Java | integration-test/src/test/java/com/orange/cloud/servicebroker/filter/core/filters/AbstractServiceBrokerFilterTest.java | Orange-OpenSource/sec-group-brokerchain | ccc53a2d7edbb91ec0ba8cb50b9c0d933fa1106f | [
"Apache-2.0"
] | 14 | 2016-11-04T10:23:13.000Z | 2020-09-16T20:11:29.000Z | integration-test/src/test/java/com/orange/cloud/servicebroker/filter/core/filters/AbstractServiceBrokerFilterTest.java | Orange-OpenSource/sec-group-brokerchain | ccc53a2d7edbb91ec0ba8cb50b9c0d933fa1106f | [
"Apache-2.0"
] | 134 | 2016-09-12T08:46:49.000Z | 2021-07-01T04:50:21.000Z | integration-test/src/test/java/com/orange/cloud/servicebroker/filter/core/filters/AbstractServiceBrokerFilterTest.java | Orange-OpenSource/sec-group-brokerchain | ccc53a2d7edbb91ec0ba8cb50b9c0d933fa1106f | [
"Apache-2.0"
] | 1 | 2021-01-26T03:30:21.000Z | 2021-01-26T03:30:21.000Z | 44.007353 | 188 | 0.663826 | 11,736 | /*
* <!--
*
* Copyright (C) 2015 Orange
* 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.orange.cloud.servicebroker.filter.core.filters;
import com.orange.cloud.servicebroker.filter.core.RandomNameFactory;
import org.cloudfoundry.operations.CloudFoundryOperations;
import org.cloudfoundry.operations.applications.*;
import org.cloudfoundry.operations.serviceadmin.CreateServiceBrokerRequest;
import org.cloudfoundry.operations.serviceadmin.ServiceBroker;
import org.cloudfoundry.operations.services.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
/**
* credits to <a href="https://github.com/cloudfoundry/cf-java-client/tree/master/integration-test">cf-java-client IT</a>
*/
public abstract class AbstractServiceBrokerFilterTest extends AbstractIntegrationTest {
//service broker filter related properties
@Value("${test.domain}")
public String domainTest;
@Autowired
Mono<String> organizationId;
@Autowired
String userName;
@Autowired
RandomNameFactory nameFactory;
@Autowired
Mono<String> spaceId;
@Value("${broker.filter.url}")
private String brokerFilterUrl;
@Value("${broker.filter.user}")
private String brokerFilterUser;
@Value("${broker.filter.password}")
private String brokerFilterPassword;
@Autowired
private CloudFoundryOperations cloudFoundryOperations;
private static Mono<Void> pushApp(CloudFoundryOperations cloudFoundryOperations, Path applicationPath, String applicationName, String domain, Boolean noStart) {
logger.debug("pushing app {} ...", applicationName);
return cloudFoundryOperations.applications()
.push(PushApplicationRequest.builder()
.path(applicationPath)
.diskQuota(512)
.memory(512)
.name(applicationName)
.domain(domain)
.noStart(noStart)
.build());
}
private static Mono<Void> startApplication(CloudFoundryOperations cloudFoundryOperations, String applicationName) {
logger.debug("starting app {} ...", applicationName);
return cloudFoundryOperations.applications()
.start(StartApplicationRequest.builder()
.name(applicationName)
.build());
}
private static Mono<Void> setEnvironmentVariable(CloudFoundryOperations cloudFoundryOperations, String applicationName, String variableName, String variableValue) {
logger.debug("setting env {} with value {} for app {} ...", variableName, variableValue, applicationName);
return cloudFoundryOperations.applications()
.setEnvironmentVariable(SetEnvironmentVariableApplicationRequest.builder()
.name(applicationName)
.variableName(variableName)
.variableValue(variableValue)
.build());
}
private static Mono<Void> createPrivateServiceBroker(CloudFoundryOperations cloudFoundryOperations, String brokerName, String userName, String password, String url) {
logger.debug("creating service broker {} ...", brokerName);
return cloudFoundryOperations.serviceAdmin()
.create(CreateServiceBrokerRequest.builder()
.name(brokerName)
.username(userName)
.password(password)
.spaceScoped(true)
.url(url)
.build());
}
private static Mono<Void> createServiceInstance(CloudFoundryOperations cloudFoundryOperations, String serviceName, String planName, String serviceInstanceName) {
logger.debug("creating service instance {} ...", serviceInstanceName);
return cloudFoundryOperations.services()
.createInstance(CreateServiceInstanceRequest.builder()
.serviceName(serviceName)
.planName(planName)
.serviceInstanceName(serviceInstanceName)
.build());
}
protected static String buildHttpsUrl(String host, String domain) {
return String.format("https://%s.%s", host, domain);
}
private static Mono<Void> setEnvs(CloudFoundryOperations cloudFoundryOperations, String applicationName, Map<String, String> envs) {
return Optional.ofNullable(envs)
.map(Map::entrySet)
.orElse(Collections.emptySet())
.stream()
.map(env -> setEnvironmentVariable(cloudFoundryOperations, applicationName, env.getKey(), env.getValue()))
.reduce(Mono.empty().then(), (x, y) -> x.then(y));
}
public String getBrokerFilterUrl() {
return brokerFilterUrl;
}
public String getBrokerFilterUser() {
return brokerFilterUser;
}
public String getBrokerFilterPassword() {
return brokerFilterPassword;
}
private Path getApplicationPath() {
try {
return Paths.get(new ClassPathResource(serviceBrokerAppPath()).getURI());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected abstract String serviceBrokerAppPath();
protected abstract String getFilteredServiceBrokerOffering();
protected abstract String getFilteredServiceBrokerPlan();
protected abstract Map<String, String> serviceBrokerAppEnvironmentVariables();
@Test
public void push_service_broker_app() {
final String applicationName = getApplicationName();
final Map<String, String> environmentVariables = serviceBrokerAppEnvironmentVariables();
givenSpace()
.then(pushThenStartServiceBrokerApp(this.cloudFoundryOperations, applicationName, getApplicationPath(), domainTest, environmentVariables))
.then(this.cloudFoundryOperations.applications()
.get(GetApplicationRequest.builder()
.name(applicationName)
.build()))
.map(ApplicationDetail::getName)
.as(StepVerifier::create)
.expectNext(applicationName)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
private Mono<String> givenSpace() {
return spaceId;
}
@Test
public void create_service_broker() {
final String applicationName = getApplicationName();
final String brokerName = getBrokerName();
final String applicationUrl = getAppUrl(applicationName, domainTest);
final Map<String, String> environmentVariables = serviceBrokerAppEnvironmentVariables();
givenSpace()
.then(pushThenStartServiceBrokerApp(this.cloudFoundryOperations, applicationName, getApplicationPath(), domainTest, environmentVariables))
.then(createPrivateServiceBroker(this.cloudFoundryOperations, brokerName, brokerFilterUser, brokerFilterPassword, applicationUrl))
.thenMany(this.cloudFoundryOperations.serviceAdmin()
.list())
.filter(hasServiceBroker(brokerName))
.as(StepVerifier::create)
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void service_offering() {
final String applicationName = getApplicationName();
final String brokerName = getBrokerName();
final String applicationUrl = getAppUrl(applicationName, domainTest);
final Map<String, String> environmentVariables = serviceBrokerAppEnvironmentVariables();
givenSpace()
.then(pushThenStartServiceBrokerApp(this.cloudFoundryOperations, applicationName, getApplicationPath(), domainTest, environmentVariables))
.then(createPrivateServiceBroker(this.cloudFoundryOperations, brokerName, brokerFilterUser, brokerFilterPassword, applicationUrl))
.thenMany(this.cloudFoundryOperations.services()
.listServiceOfferings(ListServiceOfferingsRequest.builder()
.serviceName(getFilteredServiceBrokerOffering())
.build()))
.filter(hasService(getFilteredServiceBrokerOffering()))
.as(StepVerifier::create)
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void create_service_instance() {
final String applicationName = getApplicationName();
final String brokerName = getBrokerName();
final String applicationUrl = getAppUrl(applicationName, domainTest);
final Map<String, String> environmentVariables = serviceBrokerAppEnvironmentVariables();
String serviceInstanceName = getServiceInstanceName();
final String serviceName = getFilteredServiceBrokerOffering();
final String planName = getFilteredServiceBrokerPlan();
givenSpace()
.then(pushThenStartServiceBrokerApp(this.cloudFoundryOperations, applicationName, getApplicationPath(), domainTest, environmentVariables))
.then(createPrivateServiceBroker(this.cloudFoundryOperations, brokerName, brokerFilterUser, brokerFilterPassword, applicationUrl))
.then(createServiceInstance(this.cloudFoundryOperations, serviceName, planName, serviceInstanceName))
.then(this.cloudFoundryOperations.services()
.getInstance(GetServiceInstanceRequest.builder()
.name(serviceInstanceName)
.build()))
.map(ServiceInstance::getName)
.as(StepVerifier::create)
.expectNext(serviceInstanceName)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
private Predicate<? super ServiceOffering> hasService(String serviceName) {
return serviceOffering -> serviceName.equals(serviceOffering.getLabel());
}
private Predicate<ServiceBroker> hasServiceBroker(String brokerName) {
return serviceBroker -> brokerName.equals(serviceBroker.getName());
}
private Mono<Void> pushThenStartServiceBrokerApp(CloudFoundryOperations cloudFoundryOperations, String applicationName, Path applicationPath, String domain, Map<String, String> envs) {
return pushApp(cloudFoundryOperations, applicationPath, applicationName, domain, true)
.then(setEnvs(cloudFoundryOperations, applicationName, envs))
.then(startApplication(cloudFoundryOperations, applicationName));
}
protected final String getAppUrl(String host, String domain) {
return buildHttpsUrl(host, domain);
}
}
|
3e1bb3a440d53d8f72d4d2b5e175e4658faab10c | 5,620 | java | Java | open_bottle_common/jAOG/src/aog/app/sequence/SequenceContext.java | tdonca/OpenBottle | f03d80e7b3645232fb97f91cf7fc2dc02f101ac2 | [
"MIT"
] | null | null | null | open_bottle_common/jAOG/src/aog/app/sequence/SequenceContext.java | tdonca/OpenBottle | f03d80e7b3645232fb97f91cf7fc2dc02f101ac2 | [
"MIT"
] | null | null | null | open_bottle_common/jAOG/src/aog/app/sequence/SequenceContext.java | tdonca/OpenBottle | f03d80e7b3645232fb97f91cf7fc2dc02f101ac2 | [
"MIT"
] | null | null | null | 28.527919 | 90 | 0.641459 | 11,737 | package aog.app.sequence;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import aog.Pattern;
import aog.learn.bc.CompositionalContext;
import aog.learn.bc.Context;
import aog.sample.PatternInstance;
import aog.util.Pair;
/**
* Instances within a range from the position range of the center instance.
*
* @author Kewei Tu
*
*/
public class SequenceContext extends CompositionalContext {
public SequenceContext() {
super();
}
public SequenceContext(PatternInstance pi) {
super(pi);
signature = new Pair<ArrayList<Pattern>, ArrayList<Pattern>>(leftTypes,
rightTypes);
}
public SequenceContext(Context c) {
if (c instanceof SequenceContext) {
SequenceContext sc = (SequenceContext) c;
leftTypes = new ArrayList<>(sc.leftTypes);
rightTypes = new ArrayList<>(sc.rightTypes);
signature = new Pair<ArrayList<Pattern>, ArrayList<Pattern>>(
leftTypes, rightTypes);
} else {
System.err.println("[SequenceContext] type error.");
System.exit(1);
}
}
@Override
protected boolean isContainValidForCompositePI() {
return true;
}
@Override
protected boolean contains(PatternInstance query) {
if (centerParameters.isEmpty() || query.parameters.isEmpty()) {
System.out
.println("[Warning] SequenceContext: no parameter found in the pattern instances.");
return false;
}
double p0s = centerParameters.get(0);
double p0e = centerParameters.get(1);
double ps = query.parameters.get(0);
double pe = query.parameters.get(1);
return (p0s - pe <= range && p0s - pe > 0)
|| (ps - p0e <= range && ps - p0e > 0);
}
protected ArrayList<PatternInstance> leftElements;
protected ArrayList<PatternInstance> rightElements;
protected ArrayList<Pattern> leftTypes;
protected ArrayList<Pattern> rightTypes;
@Override
protected void constructSignature() {
ArrayList<PatternInstance> elementList = new ArrayList<>(elements);
Collections.sort(elementList, new Comparator<PatternInstance>() {
@Override
public int compare(PatternInstance o1, PatternInstance o2) {
int s1 = o1.parameters.get(0).intValue();
int s2 = o2.parameters.get(0).intValue();
return s1 - s2;
}
});
int s0 = centerParameters.get(0).intValue();
int firstRight = 0;
while (firstRight < elementList.size()
&& elementList.get(firstRight).parameters.get(0) < s0)
firstRight++;
leftElements = new ArrayList<>((int) range);
rightElements = new ArrayList<>((int) range);
leftTypes = new ArrayList<>((int) range);
rightTypes = new ArrayList<>((int) range);
signature = new Pair<ArrayList<Pattern>, ArrayList<Pattern>>(leftTypes,
rightTypes);
for (int i = 0; i < elementList.size(); i++) {
PatternInstance pi = elementList.get(i);
int relPos = i - firstRight;
if (relPos >= 0) {
rightElements.add(pi);
rightTypes.add(pi.type);
} else {
leftElements.add(0, pi);
leftTypes.add(0, pi.type);
}
}
}
@Override
public void updateWithBigramReduction(PatternInstance pia,
PatternInstance pib, PatternInstance newPI) {
boolean hasA = elements.remove(pia);
boolean hasB = elements.remove(pib);
if (!hasA && !hasB)
return;
elements.add(newPI);
PatternInstance pi = hasA ? pia : pib;
if (leftElements.contains(pi)) {
if (hasA && hasB) {
int posA = leftElements.indexOf(pia);
leftElements.set(posA, newPI);
leftTypes.set(posA, newPI.type);
int posB = leftElements.indexOf(pib);
leftElements.remove(posB);
leftTypes.remove(posB);
} else { // hasA ^ hasB
int pos = leftElements.size() - 1;
assert leftElements.get(pos) == pi;
leftElements.set(pos, newPI);
leftTypes.set(pos, newPI.type);
}
// try adding new elements into the context
int nToAdd = (int) (range - leftElements.size());
PatternInstance edge = leftElements.get(leftElements.size() - 1);
int pos = edge.parameters.get(0).intValue();
for (int i = 0; i < nToAdd; i++) {
boolean found = false;
for (PatternInstance pi2 : edge.containingSample.elements) {
int p = pi2.parameters.get(1).intValue();
if (p + 1 == pos) {
leftElements.add(pi2);
elements.add(pi2);
leftTypes.add(pi2.type);
pos = pi2.parameters.get(0).intValue();
found = true;
break;
}
}
if (!found)
break;
}
} else {
if (hasA && hasB) {
int posA = rightElements.indexOf(pia);
rightElements.set(posA, newPI);
rightTypes.set(posA, newPI.type);
int posB = rightElements.indexOf(pib);
rightElements.remove(posB);
rightTypes.remove(posB);
} else { // hasA ^ hasB
int pos = rightElements.size() - 1;
assert rightElements.get(pos) == pi;
rightElements.set(pos, newPI);
rightTypes.set(pos, newPI.type);
}
// try adding new elements into the context
int nToAdd = (int) (range - rightElements.size());
PatternInstance edge = rightElements.get(rightElements.size() - 1);
int pos = edge.parameters.get(1).intValue();
for (int i = 0; i < nToAdd; i++) {
boolean found = false;
for (PatternInstance pi2 : edge.containingSample.elements) {
int p = pi2.parameters.get(0).intValue();
if (p - 1 == pos) {
rightElements.add(pi2);
elements.add(pi2);
rightTypes.add(pi2.type);
pos = pi2.parameters.get(1).intValue();
found = true;
break;
}
}
if (!found)
break;
}
}
}
}
|
3e1bb46225f149b72dccea022110477fe1a00611 | 104 | java | Java | kata/6-kyu/pentabonacci/main/Pentanacci.java | Sophia-Okito/codewars-handbook | d896c766cf3347031dc3934ce18cd7a021ae2526 | [
"MIT"
] | 36 | 2020-04-16T17:53:05.000Z | 2022-03-15T06:59:04.000Z | kata/6-kyu/pentabonacci/main/Pentanacci.java | Sophia-Okito/codewars-handbook | d896c766cf3347031dc3934ce18cd7a021ae2526 | [
"MIT"
] | 8 | 2020-07-26T05:26:40.000Z | 2022-03-01T20:03:24.000Z | kata/6-kyu/pentabonacci/main/Pentanacci.java | ParanoidUser/codewars-handbook | 6e9f61b671bd379d8671f2ae1b134e3cbde62ff4 | [
"MIT"
] | 10 | 2020-04-10T12:07:02.000Z | 2022-01-21T12:29:39.000Z | 17.333333 | 40 | 0.586538 | 11,738 | interface Pentanacci {
static long countOddPentaFib(long n) {
return --n / 6 + --n / 6 + 1;
}
}
|
3e1bb59672245e19c53063abb4c2d2c462bdbcd2 | 3,492 | java | Java | src/main/java/com/github/yuebo/dyna/security/SecurityInterceptor.java | yuebo/dyna-starter | f11aeb58279af4062c32408b17e95a4e02fd4672 | [
"Apache-2.0"
] | 4 | 2018-10-11T09:13:04.000Z | 2021-09-06T07:01:09.000Z | src/main/java/com/github/yuebo/dyna/security/SecurityInterceptor.java | yuebo/dyna-starter | f11aeb58279af4062c32408b17e95a4e02fd4672 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/yuebo/dyna/security/SecurityInterceptor.java | yuebo/dyna-starter | f11aeb58279af4062c32408b17e95a4e02fd4672 | [
"Apache-2.0"
] | 2 | 2018-10-11T09:13:04.000Z | 2018-10-12T02:42:54.000Z | 36.757895 | 202 | 0.676117 | 11,739 | package com.github.yuebo.dyna.security;
import com.github.yuebo.dyna.core.PermissionProvider;
import com.github.yuebo.dyna.utils.FormViewUtils;
import com.github.yuebo.dyna.service.JDBCService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* User: yuebo
* Date: 12/30/14
* Time: 10:05 AM
*/
public class SecurityInterceptor extends HandlerInterceptorAdapter {
protected PermissionProvider permissionProvider;
protected JDBCService jdbcService;
protected FormViewUtils formViewUtils;
public PermissionProvider getPermissionProvider() {
return permissionProvider;
}
public void setPermissionProvider(PermissionProvider permissionProvider) {
this.permissionProvider = permissionProvider;
}
public JDBCService getJdbcService() {
return jdbcService;
}
public void setJdbcService(JDBCService jdbcService) {
this.jdbcService = jdbcService;
}
public FormViewUtils getFormViewUtils() {
return formViewUtils;
}
public void setFormViewUtils(FormViewUtils formViewUtils) {
this.formViewUtils = formViewUtils;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
PermissionCheck check = getPermissionCheck(handlerMethod);
Map pathVar = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (check != null && pathVar != null) {
String viewname = StringUtils.isEmpty(check.name()) ? (String) pathVar.get("viewname") : check.name();
if (StringUtils.isEmpty(viewname)) {
return true;
}
Map map = formViewUtils.getFormView(viewname);
if (map == null) {
response.sendError(404);
return false;
}
if (!permissionProvider.hasPermission((List) map.get("permission"))) {
response.sendError(401);
return false;
}
}
}
return true;
}
protected PermissionCheck getPermissionCheck(HandlerMethod handlerMethod) throws NoSuchMethodException {
PermissionCheck classCheck = null;
PermissionCheck check = null;
if (handlerMethod.getBean().getClass().getName().contains("$$EnhancerBySpringCGLIB$$")) {
classCheck = handlerMethod.getBean().getClass().getSuperclass().getAnnotation(PermissionCheck.class);
check = handlerMethod.getBean().getClass().getSuperclass().getMethod(handlerMethod.getMethod().getName(), handlerMethod.getMethod().getParameterTypes()).getAnnotation(PermissionCheck.class);
} else {
classCheck = handlerMethod.getBean().getClass().getAnnotation(PermissionCheck.class);
check = handlerMethod.getMethodAnnotation(PermissionCheck.class);
}
if (check == null) {
check = classCheck;
}
return classCheck;
}
}
|
3e1bb8079bc9ca99d352b98a32545466cc6c2937 | 3,005 | java | Java | app/src/main/java/com/bkromhout/minerva/D.java | bkromhout/Minerva | 49637785d01010424c46ab8cdd84faa6a2e68374 | [
"Apache-2.0"
] | 5 | 2016-08-07T13:43:22.000Z | 2018-01-31T12:45:47.000Z | app/src/main/java/com/bkromhout/minerva/D.java | bkromhout/Minerva | 49637785d01010424c46ab8cdd84faa6a2e68374 | [
"Apache-2.0"
] | 115 | 2016-01-05T20:28:51.000Z | 2016-10-08T00:29:31.000Z | app/src/main/java/com/bkromhout/minerva/D.java | bkromhout/Minerva | 49637785d01010424c46ab8cdd84faa6a2e68374 | [
"Apache-2.0"
] | null | null | null | 39.539474 | 103 | 0.616639 | 11,740 | package com.bkromhout.minerva;
import android.app.Application;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;
import android.view.View;
/**
* Similar to {@link C}, but for constants which we have to get from resources at runtime.
*/
public class D {
/**
* Default tag text color.
*/
@ColorInt
public final int DEFAULT_TAG_TEXT_COLOR;
/**
* Default tag background color.
*/
@ColorInt
public final int DEFAULT_TAG_BG_COLOR;
/**
* Color selector for card view backgrounds.
*/
public final ColorStateList CARD_BG_COLORS;
/**
* How much padding to use on the bottom of the tag.
*/
public final float TAG_BOTTOM_PADDING;
/**
* Radius to use for rounded tag corners.
*/
public final float TAG_CORNER_RADIUS;
/**
* Corner radii values for all corners.
*/
public final float[] ALL_CORNERS;
/**
* Corner radii values for start corners only.
*/
public final float[] START_CORNERS_ONLY;
/**
* Corner radii values for end corners only.
*/
public final float[] END_CORNERS_ONLY;
// Only Minerva should create an instance of this.
D(Application application) {
Resources resources = application.getResources();
DEFAULT_TAG_TEXT_COLOR = ContextCompat.getColor(application, R.color.grey200);
DEFAULT_TAG_BG_COLOR = ContextCompat.getColor(application, R.color.grey700);
CARD_BG_COLORS = ContextCompat.getColorStateList(application, R.color.card_bg_color);
TAG_BOTTOM_PADDING = resources.getDimension(R.dimen.tag_bottom_padding);
TAG_CORNER_RADIUS = resources.getDimension(R.dimen.tag_corner_radius);
ALL_CORNERS = new float[] {TAG_CORNER_RADIUS, TAG_CORNER_RADIUS, // Top left.
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS, // Top right.
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS, // Bottom right.
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS}; // Bottom left.
float[] leftCornersOnly = new float[] {TAG_CORNER_RADIUS, TAG_CORNER_RADIUS,
-1f, -1f,
-1f, -1f,
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS};
float[] rightCornersOnly = new float[] {0f, 0f,
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS,
TAG_CORNER_RADIUS, TAG_CORNER_RADIUS,
0f, 0f};
boolean isLtr = resources.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_LTR;
START_CORNERS_ONLY = isLtr ? leftCornersOnly : rightCornersOnly;
END_CORNERS_ONLY = isLtr ? rightCornersOnly : leftCornersOnly;
}
}
|
3e1bb85af4ed42d43f228b72045d80266a64b04c | 2,568 | java | Java | app/src/main/java/com/example/guest/myfirstapp/MainActivity.java | YHoP/myFirstApp_android | 178bc55b85a2304cf9e01d2341ad44fb4f6456dd | [
"Unlicense"
] | null | null | null | app/src/main/java/com/example/guest/myfirstapp/MainActivity.java | YHoP/myFirstApp_android | 178bc55b85a2304cf9e01d2341ad44fb4f6456dd | [
"Unlicense"
] | null | null | null | app/src/main/java/com/example/guest/myfirstapp/MainActivity.java | YHoP/myFirstApp_android | 178bc55b85a2304cf9e01d2341ad44fb4f6456dd | [
"Unlicense"
] | null | null | null | 32.506329 | 83 | 0.699377 | 11,741 | package com.example.guest.myfirstapp;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String KEY_FACT = "KEY_FACT";
private static final String KEY_COLOR = "KEY_COLOR";
public static final String TAG = MainActivity.class.getSimpleName();
private FactBook mFactBook = new FactBook();
private ColorWheel mColorWheel = new ColorWheel();
private TextView mFactLabel;
private Button mShowFactButton;
private RelativeLayout mRelativeLayout;
private String mFact = mFactBook.mFacts[0];
private int mColor = Color.parseColor(mColorWheel.mColor[13]);
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString(KEY_FACT, mFact);
outState.putInt(KEY_COLOR, mColor);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
mFact = savedInstanceState.getString(KEY_FACT);
mFactLabel.setText(mFact);
mColor = savedInstanceState.getInt(KEY_COLOR);
mRelativeLayout.setBackgroundColor(mColor);
mShowFactButton.setTextColor(mColor);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declare the View variables and assign the Views from the layout file
mFactLabel = (TextView) findViewById(R.id.factTextView);
mShowFactButton = (Button) findViewById(R.id.showFactButton);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String fact = mFactBook.getFact();
mFactLabel.setText(fact);
int color = mColorWheel.getColor();
mRelativeLayout.setBackgroundColor(color);
mShowFactButton.setTextColor(color);
}
};
mShowFactButton.setOnClickListener(listener);
// Toast.makeText(this, "Activity was created!", Toast.LENGTH_LONG).show();
Log.d(TAG, "Logging from the onCreate() method!");
}
}
|
3e1bb88432c6d7b388c6febfdb3489ad95667d8d | 931 | java | Java | src/main/java/com/github/tinosteinort/beanrepository/Factory.java | tinosteinort/beanrepository | 4131d1e380ebc511392f3bda9d0966997bb34a62 | [
"Apache-2.0"
] | 5 | 2016-12-03T11:39:02.000Z | 2019-05-06T17:49:11.000Z | src/main/java/com/github/tinosteinort/beanrepository/Factory.java | tinosteinort/beanrepository | 4131d1e380ebc511392f3bda9d0966997bb34a62 | [
"Apache-2.0"
] | 6 | 2017-02-08T21:18:44.000Z | 2018-12-21T19:33:12.000Z | src/main/java/com/github/tinosteinort/beanrepository/Factory.java | tinosteinort/beanrepository | 4131d1e380ebc511392f3bda9d0966997bb34a62 | [
"Apache-2.0"
] | null | null | null | 34.481481 | 111 | 0.686359 | 11,742 | package com.github.tinosteinort.beanrepository;
/**
* Creates an Instance of a Bean. Even if a Factory is registered in the {@link BeanRepository} it is by itself
* not a Bean. The created Object is the Bean. {@link PostConstructible#onPostConstruct(BeanRepository)} is
* executed for the Factory Object and for the returned Bean, if {@link PostConstructible} is implemented.
*
* @param <T> The Type of the Bean
*/
public interface Factory<T> {
/**
* Creates an Instance of a Bean. {@link PostConstructible#onPostConstruct(BeanRepository)} of the Bean
* must not executed from this Method. This Method may executed from the {@link BeanRepository} later.
*
* @return The created Instance of this Factory.
*/
T createInstance();
/**
* This method is needed to get the type of the bean.
*
* @return the {@code Class} of the bean
*/
Class<T> getBeanType();
}
|
3e1bb941579fd8e6935c870831d705a92eec3096 | 5,332 | java | Java | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DescribeStreamProcessorResultJsonUnmarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DescribeStreamProcessorResultJsonUnmarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DescribeStreamProcessorResultJsonUnmarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 48.036036 | 151 | 0.653976 | 11,743 | /*
* 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.rekognition.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.rekognition.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeStreamProcessorResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeStreamProcessorResultJsonUnmarshaller implements Unmarshaller<DescribeStreamProcessorResult, JsonUnmarshallerContext> {
public DescribeStreamProcessorResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeStreamProcessorResult describeStreamProcessorResult = new DescribeStreamProcessorResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeStreamProcessorResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("StreamProcessorArn", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setStreamProcessorArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("StatusMessage", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setStatusMessage(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreationTimestamp", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setCreationTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("LastUpdateTimestamp", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setLastUpdateTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("Input", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setInput(StreamProcessorInputJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("Output", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setOutput(StreamProcessorOutputJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("RoleArn", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setRoleArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Settings", targetDepth)) {
context.nextToken();
describeStreamProcessorResult.setSettings(StreamProcessorSettingsJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeStreamProcessorResult;
}
private static DescribeStreamProcessorResultJsonUnmarshaller instance;
public static DescribeStreamProcessorResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeStreamProcessorResultJsonUnmarshaller();
return instance;
}
}
|
3e1bbb4a8e9addbdf76be2d463c899c81d4cb2bb | 2,821 | java | Java | src/main/java/com/epam/digital/data/platform/registry/regulation/validation/cli/validator/mainliquibase/rules/ForeignKeyHasCapitalLetterRule.java | epam/edp-ddm-registry-regulations-validator-cli | b0559ddafaf5092f7ddac57b2ab8a136ee9af24f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/epam/digital/data/platform/registry/regulation/validation/cli/validator/mainliquibase/rules/ForeignKeyHasCapitalLetterRule.java | epam/edp-ddm-registry-regulations-validator-cli | b0559ddafaf5092f7ddac57b2ab8a136ee9af24f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/epam/digital/data/platform/registry/regulation/validation/cli/validator/mainliquibase/rules/ForeignKeyHasCapitalLetterRule.java | epam/edp-ddm-registry-regulations-validator-cli | b0559ddafaf5092f7ddac57b2ab8a136ee9af24f | [
"Apache-2.0"
] | null | null | null | 38.643836 | 108 | 0.726338 | 11,744 | /*
* Copyright 2022 EPAM Systems.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.digital.data.platform.registry.regulation.validation.cli.validator.mainliquibase.rules;
import com.deliveredtechnologies.rulebook.RuleState;
import com.deliveredtechnologies.rulebook.annotation.Rule;
import com.deliveredtechnologies.rulebook.annotation.Then;
import com.deliveredtechnologies.rulebook.annotation.When;
import com.deliveredtechnologies.rulebook.spring.RuleBean;
import com.epam.digital.data.platform.registry.regulation.validation.cli.validator.ValidationError;
import com.epam.digital.data.platform.registry.regulation.validation.cli.validator.mainliquibase.RulesOrder;
import liquibase.change.ColumnConfig;
import liquibase.change.ConstraintsConfig;
import liquibase.change.core.CreateTableChange;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@RuleBean
@Rule(order = RulesOrder.FOREIGN_KEY_HAS_CAPITAL_LETTER_RULE)
public class ForeignKeyHasCapitalLetterRule extends AbstractMainLiquibaseValidationRule {
private static final String HAS_UPPER_CASE_SYMBOL_PATTERN = "^.*\\p{javaUpperCase}.*$";
private List<String> foreignKeyIdentifiers;
@When
public boolean checkForeignKeys() {
foreignKeyIdentifiers = getForeignKeys(
getChangesByType(CreateTableChange.class))
.stream()
.filter(fk -> fk.matches(HAS_UPPER_CASE_SYMBOL_PATTERN))
.collect(Collectors.toList());
return !foreignKeyIdentifiers.isEmpty();
}
@Then
public RuleState then() {
errors.add(ValidationError.of(regulationFileType, regulationFile,
"The following foreign keys contain uppercase characters, "
+ "which is invalid: " + foreignKeyIdentifiers));
return RuleState.NEXT;
}
protected Set<String> getForeignKeys(List<CreateTableChange> changes) {
return changes.stream()
.flatMap(x -> x.getColumns().stream())
.map(ColumnConfig::getConstraints)
.filter(Objects::nonNull)
.map(ConstraintsConfig::getForeignKeyName)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
}
|
3e1bbc2e40cf4323206d1615f06ae4a712e086b8 | 2,051 | java | Java | base/src/main/java/adudecalledleo/tbsquared/data/DataTracker.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | base/src/main/java/adudecalledleo/tbsquared/data/DataTracker.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | base/src/main/java/adudecalledleo/tbsquared/data/DataTracker.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | 32.046875 | 118 | 0.551438 | 11,745 | package adudecalledleo.tbsquared.data;
import java.util.Map;
import java.util.Optional;
public interface DataTracker extends Iterable<DataTracker.Entry<?>> {
static DataTracker empty() {
return EmptyDataTracker.INSTANCE;
}
static DataTrackerBuilder builder() {
return new DataTrackerBuilder();
}
static <T1> DataTracker of(DataKey<T1> k1, T1 v1) {
return new DefaultDataTracker(Map.of(k1, v1));
}
static <T1, T2> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2));
}
static <T1, T2, T3> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2,
DataKey<T3> k3, T3 v3) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2, k3, v3));
}
static <T1, T2, T3, T4> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2,
DataKey<T3> k3, T3 v3,
DataKey<T4> k4, T4 v4) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2, k3, v3, k4, v4));
}
static DataTracker copyOf(DataTracker tracker) {
if (tracker.size() == 0) {
return empty();
} else if (tracker instanceof DefaultDataTracker) {
return tracker;
}
return builder().setAll(tracker).build();
}
record Entry<T>(DataKey<T> key, T value) { }
int size();
<T> Optional<T> get(DataKey<T> key);
boolean containsKey(DataKey<?> key);
default boolean isEmpty() {
return size() == 0;
}
/**
* Compares the specified object with this data tracker for equality.<p>
*
* This uses a similar contract to {@link java.util.Collection#equals(Object)}: data trackers are considered equal
* if they have the same size and the same contents.
*/
boolean equals(Object o);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.