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
923a528ee5c351f5307a1d590e483bfa3c1c45fe
202
java
Java
src/test/java/com/quizme/QuizmeApplicationTests.java
Erandana/Quiz-me-Backend
50e8cfebceb402c62e1192b9f7e9509e114c35ad
[ "MIT" ]
null
null
null
src/test/java/com/quizme/QuizmeApplicationTests.java
Erandana/Quiz-me-Backend
50e8cfebceb402c62e1192b9f7e9509e114c35ad
[ "MIT" ]
null
null
null
src/test/java/com/quizme/QuizmeApplicationTests.java
Erandana/Quiz-me-Backend
50e8cfebceb402c62e1192b9f7e9509e114c35ad
[ "MIT" ]
null
null
null
14.428571
60
0.782178
999,163
package com.quizme; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class QuizmeApplicationTests { @Test void contextLoads() { } }
923a529609ab7fb36791258b4b78c00032abaed1
12,208
java
Java
altass-ng-base/src/main/java/org/chim/altass/base/utils/type/NumberUtil.java
xuejiacore/altass-ng
4e54aa16b8d299904342383ceb0c7abe1aca9cfe
[ "Apache-2.0" ]
4
2018-11-11T16:00:04.000Z
2020-08-28T07:20:05.000Z
altass-ng-base/src/main/java/org/chim/altass/base/utils/type/NumberUtil.java
xuejiacore/altass-ng
4e54aa16b8d299904342383ceb0c7abe1aca9cfe
[ "Apache-2.0" ]
null
null
null
altass-ng-base/src/main/java/org/chim/altass/base/utils/type/NumberUtil.java
xuejiacore/altass-ng
4e54aa16b8d299904342383ceb0c7abe1aca9cfe
[ "Apache-2.0" ]
null
null
null
30.984772
147
0.390645
999,164
/** * Project: x-framework * Package Name: org.ike.utils * Author: Xuejia * Date Time: 2016/12/8 23:39 * Copyright: 2016 www.zigui.site. All rights reserved. **/ package org.chim.altass.base.utils.type; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; /** * Class Name: NumberUtil * Create Date: 2016/12/8 23:39 * Creator: Xuejia * Version: v1.0 * Updater: * Date Time: * Description: */ public class NumberUtil { public NumberUtil() { } public static String format(String format, int number) { return (new DecimalFormat(format).format(number)); } public static int stringToInt(String str) { return stringToInt(str, 0); } public static int stringToInt(String str, int defaultValue) { try { return Integer.parseInt(str); } catch (NumberFormatException var3) { return defaultValue; } } public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } else if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } else if (val.length() == 1 && !Character.isDigit(val.charAt(0))) { throw new NumberFormatException(val + " is not a valid number."); } else if (val.startsWith("--")) { return null; } else if (!val.startsWith("0x") && !val.startsWith("-0x")) { char lastChar = val.charAt(val.length() - 1); int decPos = val.indexOf(46); int expPos = val.indexOf(101) + val.indexOf(69) + 1; String mant; String dec; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } String exp; if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } String allZeros1 = val.substring(0, val.length() - 1); boolean nfe2 = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'D': case 'd': break; case 'F': case 'f': try { Float e = createFloat(allZeros1); if (e.isInfinite() || e.floatValue() == 0.0F && !nfe2) { break; } return e; } catch (NumberFormatException var15) { break; } case 'L': case 'l': if (dec == null && exp == null && (allZeros1.charAt(0) == 45 && isDigits(allZeros1.substring(1)) || isDigits(allZeros1))) { try { return createLong(allZeros1); } catch (NumberFormatException var11) { return createBigInteger(allZeros1); } } else { throw new NumberFormatException(val + " is not a valid number."); } default: throw new NumberFormatException(val + " is not a valid number."); } try { Double e1 = createDouble(allZeros1); if (!e1.isInfinite() && ((double) e1.floatValue() != 0.0D || nfe2)) { return e1; } } catch (NumberFormatException var14) { ; } try { return createBigDecimal(allZeros1); } catch (NumberFormatException var13) { throw new NumberFormatException(val + " is not a valid number."); } } else { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(val); } catch (NumberFormatException var12) { try { return createLong(val); } catch (NumberFormatException var10) { return createBigInteger(val); } } } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float nfe = createFloat(val); if (!nfe.isInfinite() && (nfe.floatValue() != 0.0F || allZeros)) { return nfe; } } catch (NumberFormatException var17) { ; } try { Double nfe1 = createDouble(val); if (!nfe1.isInfinite() && (nfe1.doubleValue() != 0.0D || allZeros)) { return nfe1; } } catch (NumberFormatException var16) { ; } return createBigDecimal(val); } } } else { return createInteger(val); } } private static boolean isAllZeros(String s) { if (s == null) { return true; } else { for (int i = s.length() - 1; i >= 0; --i) { if (s.charAt(i) != 48) { return false; } } return s.length() > 0; } } public static Float createFloat(String val) { return Float.valueOf(val); } public static Double createDouble(String val) { return Double.valueOf(val); } public static Integer createInteger(String val) { return Integer.decode(val); } public static Long createLong(String val) { return Long.valueOf(val); } public static BigInteger createBigInteger(String val) { BigInteger bi = new BigInteger(val); return bi; } public static BigDecimal createBigDecimal(String val) { BigDecimal bd = new BigDecimal(val); return bd; } public static long minimum(long a, long b, long c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } public static int minimum(int a, int b, int c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } public static long maximum(long a, long b, long c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } public static int maximum(int a, int b, int c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } public static int compare(double lhs, double rhs) { if (lhs < rhs) { return -1; } else if (lhs > rhs) { return 1; } else { long lhsBits = Double.doubleToLongBits(lhs); long rhsBits = Double.doubleToLongBits(rhs); return lhsBits == rhsBits ? 0 : (lhsBits < rhsBits ? -1 : 1); } } public static int compare(float lhs, float rhs) { if (lhs < rhs) { return -1; } else if (lhs > rhs) { return 1; } else { int lhsBits = Float.floatToIntBits(lhs); int rhsBits = Float.floatToIntBits(rhs); return lhsBits == rhsBits ? 0 : (lhsBits < rhsBits ? -1 : 1); } } public static boolean isDigits(String str) { if (str != null && str.length() != 0) { for (int i = 0; i < str.length(); ++i) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } else { return false; } } public static boolean isNumber(String str) { if (StringUtil.isEmpty(str)) { return false; } else { char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; int start = chars[0] == 45 ? 1 : 0; int i; if (sz > start + 1 && chars[start] == 48 && chars[start + 1] == 120) { i = start + 2; if (i == sz) { return false; } else { while (i < chars.length) { if ((chars[i] < 48 || chars[i] > 57) && (chars[i] < 97 || chars[i] > 102) && (chars[i] < 65 || chars[i] > 70)) { return false; } ++i; } return true; } } else { --sz; for (i = start; i < sz || i < sz + 1 && allowSigns && !foundDigit; ++i) { if (chars[i] >= 48 && chars[i] <= 57) { foundDigit = true; allowSigns = false; } else if (chars[i] == 46) { if (hasDecPoint || hasExp) { return false; } hasDecPoint = true; } else if (chars[i] != 101 && chars[i] != 69) { if (chars[i] != 43 && chars[i] != 45) { return false; } if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; } else { if (hasExp) { return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } } if (i < chars.length) { if (chars[i] >= 48 && chars[i] <= 57) { return true; } else if (chars[i] != 101 && chars[i] != 69) { if (!allowSigns && (chars[i] == 100 || chars[i] == 68 || chars[i] == 102 || chars[i] == 70)) { return foundDigit; } else if (chars[i] != 108 && chars[i] != 76) { return false; } else { return foundDigit && !hasExp; } } else { return false; } } else { return !allowSigns && foundDigit; } } } } }
923a534edf8ca6322a108fc232d29487a6ba6af5
1,067
java
Java
src/main/java/test/rss/TestArraylistDivision.java
project-recoin/googlenews
7b18b20e4de8405d4c5fc2d2ee8e0d9ed7eefaca
[ "MIT" ]
6
2016-06-18T22:40:11.000Z
2021-03-20T04:45:53.000Z
src/main/java/test/rss/TestArraylistDivision.java
enterstudio/googlenews
7b18b20e4de8405d4c5fc2d2ee8e0d9ed7eefaca
[ "MIT" ]
null
null
null
src/main/java/test/rss/TestArraylistDivision.java
enterstudio/googlenews
7b18b20e4de8405d4c5fc2d2ee8e0d9ed7eefaca
[ "MIT" ]
8
2016-04-22T10:06:09.000Z
2019-05-03T08:22:35.000Z
20.921569
75
0.642924
999,165
package test.rss; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class TestArraylistDivision { public static void main(String[] args) { Scanner s; ArrayList<String> list = null; int threadNo = 8; try { s = new Scanner( new File( "/Users/user/Eclipse/GoogleNews/Multithreading/allWorkingRSS.txt")); list = new ArrayList<String>(); while (s.hasNext()) { list.add(s.next()); } s.close(); System.out.println("size " + list.size()); int division = (list.size() / threadNo)+1; for (int i = 0; i < list.size(); i += division) { int end = division + i; if (i+division > list.size()) { insertArraylist(list.subList(i, list.size())); } else { insertArraylist(list.subList(i, end)); } } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public static void insertArraylist(List<String> urls) { System.out.println(urls.size()); } }
923a548ba942013c624c8ec5e9862da77e07b3da
1,622
java
Java
src/main/java/br/ufrn/imd/obd/commands/control/TimingAdvanceCommand.java
ccaronls-fisker/java-obd-api
7ec581206b30f17fc7587bc81f1f02c3ae157550
[ "ECL-2.0", "Apache-2.0" ]
32
2018-05-31T05:45:43.000Z
2021-07-05T08:38:20.000Z
src/main/java/br/ufrn/imd/obd/commands/control/TimingAdvanceCommand.java
ccaronls-fisker/java-obd-api
7ec581206b30f17fc7587bc81f1f02c3ae157550
[ "ECL-2.0", "Apache-2.0" ]
5
2020-05-26T15:20:49.000Z
2021-11-12T09:20:34.000Z
src/main/java/br/ufrn/imd/obd/commands/control/TimingAdvanceCommand.java
ccaronls-fisker/java-obd-api
7ec581206b30f17fc7587bc81f1f02c3ae157550
[ "ECL-2.0", "Apache-2.0" ]
13
2018-08-01T05:26:12.000Z
2021-06-19T01:18:34.000Z
25.746032
80
0.680641
999,166
/* * 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 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package br.ufrn.imd.obd.commands.control; import br.ufrn.imd.obd.commands.ObdCommand; import br.ufrn.imd.obd.enums.AvailableCommand; /** * Timing Advance */ public class TimingAdvanceCommand extends ObdCommand { private double timingAdvance = -65f; /** * <p>Constructor for TimingAdvanceCommand.</p> */ public TimingAdvanceCommand() { super(AvailableCommand.TIMING_ADVANCE); } /** * <p>Constructor for TimingAdvanceCommand.</p> * * @param other a {@link TimingAdvanceCommand} object. */ public TimingAdvanceCommand(TimingAdvanceCommand other) { super(other); } @Override protected void performCalculations() { timingAdvance = buffer.get(2) / 2f - 64; } @Override public String getFormattedResult() { return getCalculatedResult() + getResultUnit(); } @Override public String getCalculatedResult() { return String.valueOf(timingAdvance); } @Override public String getResultUnit() { return "°"; } }
923a5562acb18da3e65974109b9895b2fd959eeb
4,799
java
Java
compiler/src/main/ecj/org/eclipse/jdt/internal/compiler/ast/NameReference.java
salesforce/bazel-jdt-java-toolchain
785b2081a33426355692103f271f54f05b249d37
[ "Apache-2.0" ]
1
2021-11-29T19:47:46.000Z
2021-11-29T19:47:46.000Z
compiler/src/main/ecj/org/eclipse/jdt/internal/compiler/ast/NameReference.java
salesforce/bazel-jdt-java-toolchain
785b2081a33426355692103f271f54f05b249d37
[ "Apache-2.0" ]
3
2022-03-24T07:51:03.000Z
2022-03-24T08:03:18.000Z
compiler/src/main/ecj/org/eclipse/jdt/internal/compiler/ast/NameReference.java
salesforce/bazel-jdt-java-toolchain
785b2081a33426355692103f271f54f05b249d37
[ "Apache-2.0" ]
2
2021-11-16T12:52:35.000Z
2021-12-06T18:00:39.000Z
35.029197
119
0.725151
999,167
/******************************************************************************* * Copyright (c) 2000, 2021 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation * Stephan Herrmann - Contribution for * bug 331649 - [compiler][null] consider null annotations for fields * Bug 400874 - [1.8][compiler] Inference infrastructure should evolve to meet JLS8 18.x (Part G of JSR335 spec) * Bug 426996 - [1.8][inference] try to avoid method Expression.unresolve()? * Jesper S Moller - Contributions for * bug 382721 - [1.8][compiler] Effectively final variables needs special treatment *******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import java.util.function.Predicate; import org.eclipse.jdt.internal.compiler.lookup.*; import org.eclipse.jdt.internal.compiler.problem.AbortMethod; public abstract class NameReference extends Reference implements InvocationSite { public Binding binding; //may be aTypeBinding-aFieldBinding-aLocalVariableBinding public TypeBinding actualReceiverType; // modified receiver type - actual one according to namelookup //the error printing //some name reference are build as name reference but //only used as type reference. When it happens, instead of //creating a new object (aTypeReference) we just flag a boolean //This concesion is valuable while there are cases when the NameReference //will be a TypeReference (static message sends.....) and there is //no changeClass in java. public NameReference() { this.bits |= Binding.TYPE | Binding.VARIABLE; // restrictiveFlag } /** * Use this method only when sure that the current reference is <strong>not</strong> * a chain of several fields (QualifiedNameReference with more than one field). * Otherwise use {@link #lastFieldBinding()}. */ @Override public FieldBinding fieldBinding() { //this method should be sent ONLY after a check against isFieldReference() //check its use doing senders......... return (FieldBinding) this.binding ; } @Override public FieldBinding lastFieldBinding() { if ((this.bits & ASTNode.RestrictiveFlagMASK) == Binding.FIELD) return fieldBinding(); // most subclasses only refer to one field anyway return null; } @Override public InferenceContext18 freshInferenceContext(Scope scope) { return null; } @Override public boolean isSuperAccess() { return false; } @Override public boolean isTypeAccess() { // null is acceptable when we are resolving the first part of a reference return this.binding == null || (this.binding.kind() & Binding.TYPE) != 0; } @Override public boolean isTypeReference() { return this.binding instanceof ReferenceBinding; } @Override public void setActualReceiverType(ReferenceBinding receiverType) { if (receiverType == null) return; // error scenario only this.actualReceiverType = receiverType; } @Override public void setDepth(int depth) { this.bits &= ~DepthMASK; // flush previous depth if any if (depth > 0) { this.bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } } @Override public void setFieldIndex(int index){ // ignored } public abstract String unboundReferenceErrorName(); public abstract char[][] getName(); /* Called during code generation to ensure that outer locals's effectively finality is guaranteed. Aborts if constraints are violated. Due to various complexities, this check is not conveniently implementable in resolve/analyze phases. Another quirk here is this method tells the clients whether the below condition is true (this.bits & ASTNode.IsCapturedOuterLocal) != 0 */ public boolean checkEffectiveFinality(VariableBinding localBinding, Scope scope) { Predicate<VariableBinding> test = (local) -> { return (!localBinding.isFinal() && !localBinding.isEffectivelyFinal()); }; if ((this.bits & ASTNode.IsCapturedOuterLocal) != 0) { if (test.test(localBinding)) { scope.problemReporter().cannotReferToNonEffectivelyFinalOuterLocal(localBinding, this); throw new AbortMethod(scope.referenceCompilationUnit().compilationResult, null); } return true; } else if ((this.bits & ASTNode.IsUsedInPatternGuard) != 0) { if (test.test(localBinding)) { scope.problemReporter().cannotReferToNonFinalLocalInGuard(localBinding, this); throw new AbortMethod(scope.referenceCompilationUnit().compilationResult, null); } } return false; } @Override public boolean isType() { return (this.bits & Binding.TYPE) != 0; } }
923a5609c2f78f2ddec1c31023749bf815239a61
2,581
java
Java
jipipe-tables/src/main/java/org/hkijena/jipipe/extensions/tables/algorithms/DefineTablesAlgorithm.java
applied-systems-biology/acaq5
03e8001d2654db111ee95395ce651c281b0e9c5f
[ "BSD-2-Clause" ]
null
null
null
jipipe-tables/src/main/java/org/hkijena/jipipe/extensions/tables/algorithms/DefineTablesAlgorithm.java
applied-systems-biology/acaq5
03e8001d2654db111ee95395ce651c281b0e9c5f
[ "BSD-2-Clause" ]
null
null
null
jipipe-tables/src/main/java/org/hkijena/jipipe/extensions/tables/algorithms/DefineTablesAlgorithm.java
applied-systems-biology/acaq5
03e8001d2654db111ee95395ce651c281b0e9c5f
[ "BSD-2-Clause" ]
null
null
null
35.356164
102
0.742348
999,168
/* * Copyright by Zoltán Cseresnyés, Ruman Gerst * * Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Institute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * The project code is licensed under BSD 2-Clause. * See the LICENSE file provided with the code for the full license. */ package org.hkijena.jipipe.extensions.tables.algorithms; import org.hkijena.jipipe.api.JIPipeDocumentation; import org.hkijena.jipipe.api.JIPipeNode; import org.hkijena.jipipe.api.JIPipeProgressInfo; import org.hkijena.jipipe.api.nodes.JIPipeAlgorithm; import org.hkijena.jipipe.api.nodes.JIPipeNodeInfo; import org.hkijena.jipipe.api.nodes.JIPipeOutputSlot; import org.hkijena.jipipe.api.nodes.categories.DataSourceNodeTypeCategory; import org.hkijena.jipipe.api.parameters.JIPipeParameter; import org.hkijena.jipipe.extensions.tables.datatypes.ResultsTableData; import org.hkijena.jipipe.extensions.tables.parameters.collections.ResultsTableDataList; /** * Algorithm that annotates all data with the same annotation */ @JIPipeDocumentation(name = "Define tables", description = "Defines one or multiple tables.") @JIPipeNode(nodeTypeCategory = DataSourceNodeTypeCategory.class) @JIPipeOutputSlot(value = ResultsTableData.class, slotName = "Output", autoCreate = true) public class DefineTablesAlgorithm extends JIPipeAlgorithm { private ResultsTableDataList tables = new ResultsTableDataList(); /** * @param info the info */ public DefineTablesAlgorithm(JIPipeNodeInfo info) { super(info); tables.addNewInstance(); } /** * Copies the algorithm * * @param other the original */ public DefineTablesAlgorithm(DefineTablesAlgorithm other) { super(other); this.tables = new ResultsTableDataList(other.tables); } @Override public void run(JIPipeProgressInfo progressInfo) { for (ResultsTableData table : tables) { getFirstOutputSlot().addData(new ResultsTableData(table), progressInfo); } } @JIPipeDocumentation(name = "Tables", description = "The tables are stored into the output slot.") @JIPipeParameter("tables") public ResultsTableDataList getTables() { return tables; } @JIPipeParameter("tables") public void setTables(ResultsTableDataList tables) { this.tables = tables; } }
923a5633bfd7261473b3ee50a47751d9d0e52a6a
244
java
Java
shop-common/src/main/java/com/onnoa/shop/common/distributed/lock/zookeeper/generator/IdGenerator.java
onnoA/sample-collection
2ca7f240b4c2e78ebb59259de9723d6ab434b797
[ "Apache-2.0" ]
2
2020-10-21T07:30:19.000Z
2021-11-03T09:58:22.000Z
shop-common/src/main/java/com/onnoa/shop/common/distributed/lock/zookeeper/generator/IdGenerator.java
onnoA/sample-collection
2ca7f240b4c2e78ebb59259de9723d6ab434b797
[ "Apache-2.0" ]
5
2021-11-15T06:10:54.000Z
2022-02-01T01:14:17.000Z
shop-common/src/main/java/com/onnoa/shop/common/distributed/lock/zookeeper/generator/IdGenerator.java
onnoA/sample-collection
2ca7f240b4c2e78ebb59259de9723d6ab434b797
[ "Apache-2.0" ]
5
2020-09-15T03:10:59.000Z
2021-11-30T14:36:24.000Z
13.555556
67
0.647541
999,169
package com.onnoa.shop.common.distributed.lock.zookeeper.generator; /** * @Description: id生成接口 * @Author: onnoA * @Date: 2020/6/6 12:35 */ public interface IdGenerator { /** * 生成下一个ID * * @return the string */ Long nextId(); }
923a571b0b59aafdcf97bb30b3eb792b87b64ef1
1,090
java
Java
src/main/java/org/nfclabs/pojo/tagevent/GeoLocation.java
tagdyn/nfc-tag-event
dcdfab69427a23724d32a041cfcc14626ed8db82
[ "Apache-2.0" ]
null
null
null
src/main/java/org/nfclabs/pojo/tagevent/GeoLocation.java
tagdyn/nfc-tag-event
dcdfab69427a23724d32a041cfcc14626ed8db82
[ "Apache-2.0" ]
null
null
null
src/main/java/org/nfclabs/pojo/tagevent/GeoLocation.java
tagdyn/nfc-tag-event
dcdfab69427a23724d32a041cfcc14626ed8db82
[ "Apache-2.0" ]
null
null
null
24.222222
79
0.670642
999,170
/* * Copyright 2011-2012 NFC Labs * * 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.nfclabs.pojo.tagevent; import org.nfclabs.base.tagevent.IGeoLocation; public class GeoLocation implements IGeoLocation { protected double lat; protected double lon; protected double elev; @Override public double getLatitude() { return lat; } @Override public double getLongitude() { return lon; } @Override public double getElevation() { return elev; } }
923a576fc6d1c8e76ee0537f0edd6abc570c891a
697
java
Java
src/test/java/org/openstreetmap/atlas/geography/atlas/packed/PackedAtlasClonerTest.java
mertemin/atlas
d317950b3e4b92ca167b1e372c827c38b67b2463
[ "BSD-3-Clause" ]
1
2021-07-07T12:27:00.000Z
2021-07-07T12:27:00.000Z
src/test/java/org/openstreetmap/atlas/geography/atlas/packed/PackedAtlasClonerTest.java
mertemin/atlas
d317950b3e4b92ca167b1e372c827c38b67b2463
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/openstreetmap/atlas/geography/atlas/packed/PackedAtlasClonerTest.java
mertemin/atlas
d317950b3e4b92ca167b1e372c827c38b67b2463
[ "BSD-3-Clause" ]
null
null
null
27.88
97
0.671449
999,171
package org.openstreetmap.atlas.geography.atlas.packed; import org.junit.Assert; import org.junit.Test; import org.openstreetmap.atlas.geography.atlas.Atlas; import org.openstreetmap.atlas.geography.atlas.delta.AtlasDelta; /** * @author matthieun */ public class PackedAtlasClonerTest { @Test public void cloneTest() { for (int i = 0; i < 5; i++) { final Atlas atlas = RandomPackedAtlasBuilder.generate(50, 0); final PackedAtlasCloner cloner = new PackedAtlasCloner(); final Atlas copy = cloner.cloneFrom(atlas); Assert.assertTrue(new AtlasDelta(atlas, copy).generate().getDifferences().isEmpty()); } } }
923a580373d39ad69b0d2344c9403a04d1962423
788
java
Java
library/src/main/java/com/getbase/android/autoprovider/BaseContentUriHandler.java
fstech/sell-android-autoprovider
1fa2febf3b191563be9b9b31b4324fb8498b086a
[ "Apache-2.0" ]
21
2015-03-13T08:38:03.000Z
2017-04-08T12:09:02.000Z
library/src/main/java/com/getbase/android/autoprovider/BaseContentUriHandler.java
fstech/sell-android-autoprovider
1fa2febf3b191563be9b9b31b4324fb8498b086a
[ "Apache-2.0" ]
1
2021-02-04T15:01:13.000Z
2021-02-04T15:01:13.000Z
library/src/main/java/com/getbase/android/autoprovider/BaseContentUriHandler.java
fstech/sell-android-autoprovider
1fa2febf3b191563be9b9b31b4324fb8498b086a
[ "Apache-2.0" ]
3
2016-09-06T06:11:44.000Z
2018-01-16T21:16:07.000Z
28.142857
92
0.805838
999,172
package com.getbase.android.autoprovider; import android.content.ContentResolver; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public abstract class BaseContentUriHandler implements ContentUriHandler { private final SQLiteOpenHelper mDatabase; private final ContentResolver mContentResolver; public BaseContentUriHandler(SQLiteOpenHelper database, ContentResolver contentResolver) { mDatabase = database; mContentResolver = contentResolver; } protected ContentResolver getContentResolver() { return mContentResolver; } protected SQLiteDatabase getReadableDb() { return mDatabase.getReadableDatabase(); } protected SQLiteDatabase getWritableDb() { return mDatabase.getWritableDatabase(); } }
923a581eb8493d75abcf395c7a9224dc824b6518
2,779
java
Java
src/com/meilishuo/baselibrary/utils/BitmapChangeRound.java
JeffWangGithub/JeffBaseLibrary
6c8f4884ff1d10e6ad0e790aa3700ddb4e1c79b9
[ "Apache-2.0" ]
null
null
null
src/com/meilishuo/baselibrary/utils/BitmapChangeRound.java
JeffWangGithub/JeffBaseLibrary
6c8f4884ff1d10e6ad0e790aa3700ddb4e1c79b9
[ "Apache-2.0" ]
null
null
null
src/com/meilishuo/baselibrary/utils/BitmapChangeRound.java
JeffWangGithub/JeffBaseLibrary
6c8f4884ff1d10e6ad0e790aa3700ddb4e1c79b9
[ "Apache-2.0" ]
null
null
null
33.481928
125
0.583303
999,173
package com.meilishuo.baselibrary.utils; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; /** * 将一个Bitmap图形转换成圆形 * * @author Jeff */ public class BitmapChangeRound { /** * 转换图片成圆形 * 这个方法是根据传入的图片的高度(height)和宽度(width)决定的,如果是 width <= height 时,则会裁剪高度, * 裁剪的区域是宽度不变高度从顶部到宽度width的长度;如果 width > height,则会裁剪宽度,裁剪的区域是高度不变, * 宽度是取的图片宽度的中心区域,不过不同的业务需求,对裁剪图片要求不一样,可以根据业务的需求来调整裁剪的区域 * @param bitmap * 传入Bitmap对象 * @return 转换成圆形的Bitmap对象 */ public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; left = 0; top = 0; right = width; bottom = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true);// 设置画笔无锯齿 canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas paint.setColor(color); // 以下有两种方法画圆,drawRounRect和drawCircle // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形,第一个参数为图形显示区域,第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。 canvas.drawCircle(roundPx, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452 canvas.drawBitmap(bitmap, src, dst, paint); //以Mode.SRC_IN模式合并bitmap和已经draw了的Circle return output; } }
923a58e3ac0f85e0cebcda373a5b23bf5b07f826
408
java
Java
proFL-plugin-2.0.3/org/pitest/coverage/TestInfoNameComparator.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/pitest/coverage/TestInfoNameComparator.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/pitest/coverage/TestInfoNameComparator.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
21.473684
74
0.720588
999,174
// // Decompiled by Procyon v0.5.36 // package org.pitest.coverage; import java.io.Serializable; import java.util.Comparator; class TestInfoNameComparator implements Comparator<TestInfo>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(final TestInfo lhs, final TestInfo rhs) { return lhs.getName().compareTo(rhs.getName()); } }
923a58edeefe8e8ddd02e96d22b3a2e189fbbfaa
3,655
java
Java
Libraries/netty-3.9.4/src/main/java/org/jboss/netty/handler/codec/rtsp/RtspMessageDecoder.java
richmnus/sandbox
d58c8375a7b001eba3e11d77b74435d13b959635
[ "Apache-2.0" ]
null
null
null
Libraries/netty-3.9.4/src/main/java/org/jboss/netty/handler/codec/rtsp/RtspMessageDecoder.java
richmnus/sandbox
d58c8375a7b001eba3e11d77b74435d13b959635
[ "Apache-2.0" ]
null
null
null
Libraries/netty-3.9.4/src/main/java/org/jboss/netty/handler/codec/rtsp/RtspMessageDecoder.java
richmnus/sandbox
d58c8375a7b001eba3e11d77b74435d13b959635
[ "Apache-2.0" ]
null
null
null
35.833333
101
0.687004
999,175
/* * Copyright 2012 The Netty Project * * The Netty Project 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.jboss.netty.handler.codec.rtsp; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.embedder.DecoderEmbedder; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpMessage; import org.jboss.netty.handler.codec.http.HttpMessageDecoder; /** * Decodes {@link ChannelBuffer}s into RTSP messages represented in * {@link HttpMessage}s. * <p> * <h3>Parameters that prevents excessive memory consumption</h3> * <table border="1"> * <tr> * <th>Name</th><th>Meaning</th> * </tr> * <tr> * <td>{@code maxInitialLineLength}</td> * <td>The maximum length of the initial line * (e.g. {@code "SETUP / RTSP/1.0"} or {@code "RTSP/1.0 200 OK"}) * If the length of the initial line exceeds this value, a * {@link TooLongFrameException} will be raised.</td> * </tr> * <tr> * <td>{@code maxHeaderSize}</td> * <td>The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongFrameException} will be raised.</td> * </tr> * <tr> * <td>{@code maxContentLength}</td> * <td>The maximum length of the content. If the content length exceeds this * value, a {@link TooLongFrameException} will be raised.</td> * </tr> * </table> * @apiviz.landmark */ public abstract class RtspMessageDecoder extends HttpMessageDecoder { private final DecoderEmbedder<HttpMessage> aggregator; /** * Creates a new instance with the default * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (8192)}, and * {@code maxContentLength (8192)}. */ protected RtspMessageDecoder() { this(4096, 8192, 8192); } /** * Creates a new instance with the specified parameters. */ protected RtspMessageDecoder(int maxInitialLineLength, int maxHeaderSize, int maxContentLength) { super(maxInitialLineLength, maxHeaderSize, maxContentLength * 2); aggregator = new DecoderEmbedder<HttpMessage>(new HttpChunkAggregator(maxContentLength)); } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { Object o = super.decode(ctx, channel, buffer, state); if (o != null && aggregator.offer(o)) { return aggregator.poll(); } else { return null; } } @Override protected boolean isContentAlwaysEmpty(HttpMessage msg) { // Unlike HTTP, RTSP always assumes zero-length body if Content-Length // header is absent. boolean empty = super.isContentAlwaysEmpty(msg); if (empty) { return true; } if (!msg.headers().contains(RtspHeaders.Names.CONTENT_LENGTH)) { return true; } return empty; } }
923a59b4ab9a00137afc2e8513cedd3ee25d0146
7,836
java
Java
camera/camera-testing/src/main/java/androidx/camera/testing/CamcorderProfileUtil.java
LanderlYoung/androidx
d99c6ef82e67997b71b449840a8147f62f9537a8
[ "Apache-2.0" ]
3,799
2020-07-23T21:58:59.000Z
2022-03-31T17:07:19.000Z
camera/camera-testing/src/main/java/androidx/camera/testing/CamcorderProfileUtil.java
LanderlYoung/androidx
d99c6ef82e67997b71b449840a8147f62f9537a8
[ "Apache-2.0" ]
152
2020-07-24T00:19:02.000Z
2022-03-31T00:57:54.000Z
camera/camera-testing/src/main/java/androidx/camera/testing/CamcorderProfileUtil.java
LanderlYoung/androidx
d99c6ef82e67997b71b449840a8147f62f9537a8
[ "Apache-2.0" ]
582
2020-07-24T00:16:54.000Z
2022-03-30T23:32:45.000Z
38.22439
95
0.676876
999,176
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.testing; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.util.Size; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.camera.core.impl.CamcorderProfileProxy; /** * Utility methods for testing {@link CamcorderProfile} related classes, including predefined * resolutions, attributes and {@link CamcorderProfileProxy}, which can be used directly on the * unit tests. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java public final class CamcorderProfileUtil { private CamcorderProfileUtil() { } /** Resolution for QCIF. */ public static final Size RESOLUTION_QCIF = new Size(176, 144); /** Resolution for QVGA. */ public static final Size RESOLUTION_QVGA = new Size(320, 240); /** Resolution for CIF. */ public static final Size RESOLUTION_CIF = new Size(352, 288); /** Resolution for VGA. */ public static final Size RESOLUTION_VGA = new Size(640, 480); /** Resolution for 480P. */ public static final Size RESOLUTION_480P = new Size(720, 480); /* 640, 704 or 720 x 480 */ /** Resolution for 720P. */ public static final Size RESOLUTION_720P = new Size(1280, 720); /** Resolution for 1080P. */ public static final Size RESOLUTION_1080P = new Size(1920, 1080); /* 1920 x 1080 or 1088 */ /** Resolution for 2K. */ public static final Size RESOLUTION_2K = new Size(2048, 1080); /** Resolution for QHD. */ public static final Size RESOLUTION_QHD = new Size(2560, 1440); /** Resolution for 2160P. */ public static final Size RESOLUTION_2160P = new Size(3840, 2160); /** Resolution for 4KDCI. */ public static final Size RESOLUTION_4KDCI = new Size(4096, 2160); /** Default duration. */ public static final int DEFAULT_DURATION = 30; /** Default output format. */ public static final int DEFAULT_OUTPUT_FORMAT = MediaRecorder.OutputFormat.MPEG_4; /** Default video codec. */ public static final int DEFAULT_VIDEO_CODEC = MediaRecorder.VideoEncoder.H264; /** Default video bitrate. */ public static final int DEFAULT_VIDEO_BITRATE = 8 * 1024 * 1024; /** Default video frame rate. */ public static final int DEFAULT_VIDEO_FRAME_RATE = 30; /** Default audio codec. */ public static final int DEFAULT_AUDIO_CODEC = MediaRecorder.AudioEncoder.AAC; /** Default audio bitrate. */ public static final int DEFAULT_AUDIO_BITRATE = 192_000; /** Default audio sample rate. */ public static final int DEFAULT_AUDIO_SAMPLE_RATE = 48_000; /** Default channel count. */ public static final int DEFAULT_AUDIO_CHANNELS = 1; public static final CamcorderProfileProxy PROFILE_QCIF = createCamcorderProfileProxy( CamcorderProfile.QUALITY_QCIF, RESOLUTION_QCIF.getWidth(), RESOLUTION_QCIF.getHeight() ); public static final CamcorderProfileProxy PROFILE_QVGA = createCamcorderProfileProxy( CamcorderProfile.QUALITY_QVGA, RESOLUTION_QVGA.getWidth(), RESOLUTION_QVGA.getHeight() ); public static final CamcorderProfileProxy PROFILE_CIF = createCamcorderProfileProxy( CamcorderProfile.QUALITY_CIF, RESOLUTION_CIF.getWidth(), RESOLUTION_CIF.getHeight() ); public static final CamcorderProfileProxy PROFILE_VGA = createCamcorderProfileProxy( CamcorderProfile.QUALITY_VGA, RESOLUTION_VGA.getWidth(), RESOLUTION_VGA.getHeight() ); public static final CamcorderProfileProxy PROFILE_480P = createCamcorderProfileProxy( CamcorderProfile.QUALITY_480P, RESOLUTION_480P.getWidth(), RESOLUTION_480P.getHeight() ); public static final CamcorderProfileProxy PROFILE_720P = createCamcorderProfileProxy( CamcorderProfile.QUALITY_720P, RESOLUTION_720P.getWidth(), RESOLUTION_720P.getHeight() ); public static final CamcorderProfileProxy PROFILE_1080P = createCamcorderProfileProxy( CamcorderProfile.QUALITY_1080P, RESOLUTION_1080P.getWidth(), RESOLUTION_1080P.getHeight() ); public static final CamcorderProfileProxy PROFILE_2K = createCamcorderProfileProxy( CamcorderProfile.QUALITY_2K, RESOLUTION_2K.getWidth(), RESOLUTION_2K.getHeight() ); public static final CamcorderProfileProxy PROFILE_QHD = createCamcorderProfileProxy( CamcorderProfile.QUALITY_QHD, RESOLUTION_QHD.getWidth(), RESOLUTION_QHD.getHeight() ); public static final CamcorderProfileProxy PROFILE_2160P = createCamcorderProfileProxy( CamcorderProfile.QUALITY_2160P, RESOLUTION_2160P.getWidth(), RESOLUTION_2160P.getHeight() ); public static final CamcorderProfileProxy PROFILE_4KDCI = createCamcorderProfileProxy( CamcorderProfile.QUALITY_4KDCI, RESOLUTION_4KDCI.getWidth(), RESOLUTION_4KDCI.getHeight() ); /** A utility method to create a CamcorderProfileProxy with some default values. */ @NonNull public static CamcorderProfileProxy createCamcorderProfileProxy( int quality, int videoFrameWidth, int videoFrameHeight ) { return CamcorderProfileProxy.create( DEFAULT_DURATION, quality, DEFAULT_OUTPUT_FORMAT, DEFAULT_VIDEO_CODEC, DEFAULT_VIDEO_BITRATE, DEFAULT_VIDEO_FRAME_RATE, videoFrameWidth, videoFrameHeight, DEFAULT_AUDIO_CODEC, DEFAULT_AUDIO_BITRATE, DEFAULT_AUDIO_SAMPLE_RATE, DEFAULT_AUDIO_CHANNELS ); } /** * Copies a CamcorderProfileProxy and sets the quality to * {@link CamcorderProfile#QUALITY_HIGH}. */ @NonNull public static CamcorderProfileProxy asHighQuality(@NonNull CamcorderProfileProxy profile) { return asQuality(profile, CamcorderProfile.QUALITY_HIGH); } /** * Copies a CamcorderProfileProxy and sets the quality to * {@link CamcorderProfile#QUALITY_LOW}. */ @NonNull public static CamcorderProfileProxy asLowQuality(@NonNull CamcorderProfileProxy profile) { return asQuality(profile, CamcorderProfile.QUALITY_LOW); } private static CamcorderProfileProxy asQuality(@NonNull CamcorderProfileProxy profile, int quality) { return CamcorderProfileProxy.create( profile.getDuration(), quality, profile.getFileFormat(), profile.getVideoCodec(), profile.getVideoBitRate(), profile.getVideoFrameRate(), profile.getVideoFrameWidth(), profile.getVideoFrameHeight(), profile.getAudioCodec(), profile.getAudioBitRate(), profile.getAudioSampleRate(), profile.getAudioChannels() ); } }
923a5a12603bd2da05e7545e86d9235146436c9f
1,690
java
Java
elasticsearch-test-framework/src/test/java/org/elasticsearch/test/test/SuiteScopeClusterIT.java
jprante/elasticsearch-devkit
5dba5b5b77b538716d4a0a9578959f4e8417624e
[ "Apache-2.0" ]
1
2018-06-30T12:10:07.000Z
2018-06-30T12:10:07.000Z
elasticsearch-test-framework/src/test/java/org/elasticsearch/test/test/SuiteScopeClusterIT.java
jprante/elasticsearch-devkit
5dba5b5b77b538716d4a0a9578959f4e8417624e
[ "Apache-2.0" ]
null
null
null
elasticsearch-test-framework/src/test/java/org/elasticsearch/test/test/SuiteScopeClusterIT.java
jprante/elasticsearch-devkit
5dba5b5b77b538716d4a0a9578959f4e8417624e
[ "Apache-2.0" ]
null
null
null
33.8
87
0.657988
999,177
package org.elasticsearch.test.test; import com.carrotsearch.randomizedtesting.annotations.Repeat; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.TestCluster; import org.junit.Test; import java.io.IOException; import static org.hamcrest.Matchers.equalTo; /** * This test ensures that the cluster initializion for suite scope is not influencing * the tests random sequence due to initializtion using the same random instance. */ @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE) public class SuiteScopeClusterIT extends ESIntegTestCase { private static int ITER = 0; private static long[] SEQUENCE = new long[100]; private static Long CLUSTER_SEED = null; @Test @SuppressForbidden(reason = "repeat is a feature here") @Repeat(iterations = 10, useConstantSeed = true) public void testReproducible() throws IOException { if (ITER++ == 0) { CLUSTER_SEED = cluster().seed(); for (int i = 0; i < SEQUENCE.length; i++) { SEQUENCE[i] = randomLong(); } } else { assertEquals(CLUSTER_SEED, Long.valueOf(cluster().seed())); for (int i = 0; i < SEQUENCE.length; i++) { assertThat(SEQUENCE[i], equalTo(randomLong())); } } } @Override protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException { // produce some randomness int iters = between(1, 100); for (int i = 0; i < iters; i++) { randomLong(); } return super.buildTestCluster(scope, seed); } }
923a5adc57526c9f77945f1d456dc3740bcbf333
7,827
java
Java
jre_emul/android/platform/libcore/json/src/test/java/libcore/org/json/SelfUseTest.java
gaybro8777/j2objc
9234ca9bed5d16a2f9914d55001ce1ec2e84dc9d
[ "Apache-2.0" ]
4,901
2015-01-02T09:29:18.000Z
2022-03-29T06:51:04.000Z
jre_emul/android/platform/libcore/json/src/test/java/libcore/org/json/SelfUseTest.java
1Crazymoney/j2objc
444f387445b3f22fd807b7c72eca484ea8823c8e
[ "Apache-2.0" ]
853
2015-01-03T08:13:19.000Z
2022-03-22T18:51:24.000Z
jre_emul/android/platform/libcore/json/src/test/java/libcore/org/json/SelfUseTest.java
1Crazymoney/j2objc
444f387445b3f22fd807b7c72eca484ea8823c8e
[ "Apache-2.0" ]
964
2015-01-08T08:52:00.000Z
2022-03-23T16:36:47.000Z
33.306383
89
0.628466
999,178
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package libcore.org.json; import junit.framework.TestCase; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** * These tests checks self use calls. For the most part we doesn't attempt to * cover self-use, except in those cases where our clean room implementation * does it. * * <p>This black box test was written without inspecting the non-free org.json * sourcecode. */ public class SelfUseTest extends TestCase { private int objectPutCalls = 0; private int objectGetCalls = 0; private int objectOptCalls = 0; private int objectOptTypeCalls = 0; private int arrayPutCalls = 0; private int arrayGetCalls = 0; private int arrayOptCalls = 0; private int arrayOptTypeCalls = 0; private int tokenerNextCalls = 0; private int tokenerNextValueCalls = 0; private final JSONObject object = new JSONObject() { @Override public JSONObject put(String name, Object value) throws JSONException { objectPutCalls++; return super.put(name, value); } @Override public Object get(String name) throws JSONException { objectGetCalls++; return super.get(name); } @Override public Object opt(String name) { objectOptCalls++; return super.opt(name); } @Override public boolean optBoolean(String key, boolean defaultValue) { objectOptTypeCalls++; return super.optBoolean(key, defaultValue); } @Override public double optDouble(String key, double defaultValue) { objectOptTypeCalls++; return super.optDouble(key, defaultValue); } @Override public int optInt(String key, int defaultValue) { objectOptTypeCalls++; return super.optInt(key, defaultValue); } @Override public long optLong(String key, long defaultValue) { objectOptTypeCalls++; return super.optLong(key, defaultValue); } @Override public String optString(String key, String defaultValue) { objectOptTypeCalls++; return super.optString(key, defaultValue); } }; private final JSONArray array = new JSONArray() { @Override public JSONArray put(int index, Object value) throws JSONException { arrayPutCalls++; return super.put(index, value); } @Override public Object get(int index) throws JSONException { arrayGetCalls++; return super.get(index); } @Override public Object opt(int index) { arrayOptCalls++; return super.opt(index); } @Override public boolean optBoolean(int index, boolean fallback) { arrayOptTypeCalls++; return super.optBoolean(index, fallback); } @Override public double optDouble(int index, double fallback) { arrayOptTypeCalls++; return super.optDouble(index, fallback); } @Override public long optLong(int index, long fallback) { arrayOptTypeCalls++; return super.optLong(index, fallback); } @Override public String optString(int index, String fallback) { arrayOptTypeCalls++; return super.optString(index, fallback); } @Override public int optInt(int index, int fallback) { arrayOptTypeCalls++; return super.optInt(index, fallback); } }; private final JSONTokener tokener = new JSONTokener("{\"foo\": [true]}") { @Override public char next() { tokenerNextCalls++; return super.next(); } @Override public Object nextValue() throws JSONException { tokenerNextValueCalls++; return super.nextValue(); } }; public void testObjectPut() throws JSONException { object.putOpt("foo", "bar"); assertEquals(1, objectPutCalls); } public void testObjectAccumulate() throws JSONException { object.accumulate("foo", "bar"); assertEquals(1, objectPutCalls); } public void testObjectGetBoolean() throws JSONException { object.put("foo", "true"); object.getBoolean("foo"); assertEquals(1, objectGetCalls); } public void testObjectOptType() throws JSONException { object.optBoolean("foo"); assertEquals(1, objectOptCalls); assertEquals(1, objectOptTypeCalls); object.optDouble("foo"); assertEquals(2, objectOptCalls); assertEquals(2, objectOptTypeCalls); object.optInt("foo"); assertEquals(3, objectOptCalls); assertEquals(3, objectOptTypeCalls); object.optLong("foo"); assertEquals(4, objectOptCalls); assertEquals(4, objectOptTypeCalls); object.optString("foo"); assertEquals(5, objectOptCalls); assertEquals(5, objectOptTypeCalls); } public void testToJSONArray() throws JSONException { object.put("foo", 5); object.put("bar", 10); array.put("foo"); array.put("baz"); array.put("bar"); object.toJSONArray(array); assertEquals(3, arrayOptCalls); assertEquals(0, arrayOptTypeCalls); assertEquals(3, objectOptCalls); assertEquals(0, objectOptTypeCalls); } public void testPutAtIndex() throws JSONException { array.put(10, false); assertEquals(1, arrayPutCalls); } public void testIsNull() { array.isNull(5); assertEquals(1, arrayOptCalls); } public void testArrayGetType() throws JSONException { array.put(true); array.getBoolean(0); assertEquals(1, arrayGetCalls); } public void testArrayOptType() throws JSONException { array.optBoolean(3); assertEquals(1, arrayOptCalls); assertEquals(1, arrayOptTypeCalls); array.optDouble(3); assertEquals(2, arrayOptCalls); assertEquals(2, arrayOptTypeCalls); array.optInt(3); assertEquals(3, arrayOptCalls); assertEquals(3, arrayOptTypeCalls); array.optLong(3); assertEquals(4, arrayOptCalls); assertEquals(4, arrayOptTypeCalls); array.optString(3); assertEquals(5, arrayOptCalls); assertEquals(5, arrayOptTypeCalls); } public void testToJSONObject() throws JSONException { array.put("foo"); array.put("baz"); array.put("bar"); JSONArray values = new JSONArray(); values.put(5.5d); values.put(11d); values.put(30); values.toJSONObject(array); assertEquals(3, arrayOptCalls); assertEquals(0, arrayOptTypeCalls); } public void testNextExpecting() throws JSONException { tokener.next('{'); assertEquals(1, tokenerNextCalls); tokener.next('\"'); assertEquals(2, tokenerNextCalls); } public void testNextValue() throws JSONException { tokener.nextValue(); assertEquals(4, tokenerNextValueCalls); } }
923a5b8a3e3bc5b7e5f58d226561b674e907f318
470
java
Java
worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java
KleinCrafter/FastAsyncWorldEdit
7603dcd77e15a8f39e3c6dd7585bf31fa8f46178
[ "BSD-3-Clause" ]
6
2020-12-29T20:05:09.000Z
2021-01-27T21:31:42.000Z
worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java
KleinCrafter/FastAsyncWorldEdit
7603dcd77e15a8f39e3c6dd7585bf31fa8f46178
[ "BSD-3-Clause" ]
null
null
null
worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java
KleinCrafter/FastAsyncWorldEdit
7603dcd77e15a8f39e3c6dd7585bf31fa8f46178
[ "BSD-3-Clause" ]
1
2021-05-18T15:25:28.000Z
2021-05-18T15:25:28.000Z
16.206897
59
0.57234
999,179
package com.boydti.fawe.object.collection; import java.util.Map; public class MutablePair<K, V> implements Map.Entry<K, V> { private K key; private V value; @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { this.value = value; return value; } public void setKey(K key) { this.key = key; } }
923a5c724f598a3257811c07c56045b6bc2b3341
1,076
java
Java
maven-parent/b2c-cloud-test-learn-java/src/main/java/com/javamaster/b2c/cloud/test/learn/java/enums/EnumBase.java
jufeng98/b2c-master
5db75cea023c0f775a56b2a872e75e8f2fe4639f
[ "Unlicense" ]
null
null
null
maven-parent/b2c-cloud-test-learn-java/src/main/java/com/javamaster/b2c/cloud/test/learn/java/enums/EnumBase.java
jufeng98/b2c-master
5db75cea023c0f775a56b2a872e75e8f2fe4639f
[ "Unlicense" ]
null
null
null
maven-parent/b2c-cloud-test-learn-java/src/main/java/com/javamaster/b2c/cloud/test/learn/java/enums/EnumBase.java
jufeng98/b2c-master
5db75cea023c0f775a56b2a872e75e8f2fe4639f
[ "Unlicense" ]
null
null
null
21.098039
83
0.510223
999,180
package com.javamaster.b2c.cloud.test.learn.java.enums; /** * <p>枚举类的公共接口</p> * Created on 2019/1/8.<br/> * * @author yudong */ public interface EnumBase { int getCode(); String getMsg(); /** * 根据code获取对应的枚举对象 * * @param enumClass * @param code * @param <E> * @return 若无对应的枚举对象, 返回null */ static <E extends Enum<?> & EnumBase> E codeOf(Class<E> enumClass, int code) { E[] enumConstants = enumClass.getEnumConstants(); for (E e : enumConstants) { if (e.getCode() == code) { return e; } } return null; } /** * 根据msg获取对应的枚举对象 * * @param enumClass * @param msg * @param <E> * @return 若无对应的枚举对象, 返回null */ static <E extends Enum<?> & EnumBase> E msgOf(Class<E> enumClass, String msg) { E[] enumConstants = enumClass.getEnumConstants(); for (E e : enumConstants) { if (e.getMsg().equals(msg)) { return e; } } return null; } }
923a5c7b6579ab4f040fafbd9f2d6f355546baf3
61
java
Java
src/main/java/com/ukefu/util/UCKeFuIdGenerator.java
yeyu0415/kefu
2b56bb3e0023e4d579bca0f4665e32c608593574
[ "Apache-2.0" ]
56
2017-08-23T15:44:43.000Z
2021-11-16T07:45:43.000Z
ukefu(优客服)/src/main/java/com/ukefu/util/UCKeFuIdGenerator.java
15021904202/JavaEE-projects
66532dbc1a836f1d7d9bf79aa79a2be724c7748e
[ "MIT" ]
null
null
null
ukefu(优客服)/src/main/java/com/ukefu/util/UCKeFuIdGenerator.java
15021904202/JavaEE-projects
66532dbc1a836f1d7d9bf79aa79a2be724c7748e
[ "MIT" ]
45
2017-11-22T03:35:28.000Z
2021-11-27T05:47:27.000Z
10.166667
32
0.770492
999,181
package com.ukefu.util; public class UCKeFuIdGenerator { }
923a5debc051f13657bfe1507d2cac3d6fef6074
492
java
Java
swig/apps/oc/android_multi_device_server/MultiDeviceServer/app/src/main/java/org/iotivity/multideviceserver/Thermostat.java
wickimassoy/iotivity-lite
e140432a156d30c380dde29f219e682c59a087da
[ "BSD-2-Clause" ]
107
2019-02-28T02:09:01.000Z
2022-02-08T09:50:22.000Z
swig/apps/oc/android_multi_device_server/MultiDeviceServer/app/src/main/java/org/iotivity/multideviceserver/Thermostat.java
hongtianjun/iotivity-lite
6985a55497cea639f27827c116321ed671a778bb
[ "Apache-2.0" ]
134
2019-03-30T19:35:37.000Z
2022-03-29T17:47:17.000Z
swig/apps/oc/android_multi_device_server/MultiDeviceServer/app/src/main/java/org/iotivity/multideviceserver/Thermostat.java
hongtianjun/iotivity-lite
6985a55497cea639f27827c116321ed671a778bb
[ "Apache-2.0" ]
69
2019-02-25T12:41:02.000Z
2022-03-28T06:57:12.000Z
18.923077
63
0.656504
999,182
package org.iotivity.multideviceserver; public class Thermostat { static public final String TEMPERATURE_KEY = "temperature"; private String name; private double temperature; public Thermostat(String name) { this.name = name; } public String getName() { return name; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } }
923a5e39d27b75a9abcc86858ff7f168c707859b
1,026
java
Java
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/devconsole/DevQuteTemplateInfo.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
10,225
2019-03-07T11:55:54.000Z
2022-03-31T21:16:53.000Z
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/devconsole/DevQuteTemplateInfo.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
18,675
2019-03-07T11:56:33.000Z
2022-03-31T22:25:22.000Z
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/devconsole/DevQuteTemplateInfo.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
2,190
2019-03-07T12:07:18.000Z
2022-03-30T05:41:35.000Z
23.860465
92
0.658869
999,183
package io.quarkus.qute.deployment.devconsole; import java.util.Map; public class DevQuteTemplateInfo implements Comparable<DevQuteTemplateInfo> { private final String path; // variant -> source private final Map<String, String> variants; private final String methodInfo; private final Map<String, String> parameters; public DevQuteTemplateInfo(String path, Map<String, String> variants, String methodInfo, Map<String, String> parameters) { this.path = path; this.variants = variants; this.methodInfo = methodInfo; this.parameters = parameters; } public Map<String, String> getParameters() { return parameters; } public String getPath() { return path; } public Map<String, String> getVariants() { return variants; } public String getMethodInfo() { return methodInfo; } @Override public int compareTo(DevQuteTemplateInfo o) { return path.compareTo(o.path); } }
923a5f488f127f5bb2259acce12240ba6d7ea9fa
3,451
java
Java
src/com/sun/corba/se/PortableActivationIDL/LocatorPackage/ServerLocationPerTypeHelper.java
youyouwei/jdk-source
a83278572895f564c14d4fd52ee429f84b9c2ef8
[ "Apache-2.0" ]
null
null
null
src/com/sun/corba/se/PortableActivationIDL/LocatorPackage/ServerLocationPerTypeHelper.java
youyouwei/jdk-source
a83278572895f564c14d4fd52ee429f84b9c2ef8
[ "Apache-2.0" ]
null
null
null
src/com/sun/corba/se/PortableActivationIDL/LocatorPackage/ServerLocationPerTypeHelper.java
youyouwei/jdk-source
a83278572895f564c14d4fd52ee429f84b9c2ef8
[ "Apache-2.0" ]
null
null
null
40.6
192
0.707911
999,184
package com.sun.corba.se.PortableActivationIDL.LocatorPackage; /** * com/sun/corba/se/PortableActivationIDL/LocatorPackage/ServerLocationPerTypeHelper.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u191/11896/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl * Saturday, October 6, 2018 9:30:40 AM PDT */ abstract public class ServerLocationPerTypeHelper { private static String _id = "IDL:PortableActivationIDL/Locator/ServerLocationPerType:1.0"; public static void insert (org.omg.CORBA.Any a, com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType that) { org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); a.type (type ()); write (out, that); a.read_value (out.create_input_stream (), type ()); } public static com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType extract (org.omg.CORBA.Any a) { return read (a.create_input_stream ()); } private static org.omg.CORBA.TypeCode __typeCode = null; private static boolean __active = false; synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { synchronized (org.omg.CORBA.TypeCode.class) { if (__typeCode == null) { if (__active) { return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); } __active = true; org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; org.omg.CORBA.TypeCode _tcOf_members0 = null; _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); _members0[0] = new org.omg.CORBA.StructMember ( "hostname", _tcOf_members0, null); _tcOf_members0 = com.sun.corba.se.PortableActivationIDL.ORBPortInfoHelper.type (); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.corba.se.PortableActivationIDL.ORBPortInfoListHelper.id (), "ORBPortInfoList", _tcOf_members0); _members0[1] = new org.omg.CORBA.StructMember ( "ports", _tcOf_members0, null); __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerTypeHelper.id (), "ServerLocationPerType", _members0); __active = false; } } } return __typeCode; } public static String id () { return _id; } public static com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType read (org.omg.CORBA.portable.InputStream istream) { com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType value = new com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType (); value.hostname = istream.read_string (); value.ports = com.sun.corba.se.PortableActivationIDL.ORBPortInfoListHelper.read (istream); return value; } public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.corba.se.PortableActivationIDL.LocatorPackage.ServerLocationPerType value) { ostream.write_string (value.hostname); com.sun.corba.se.PortableActivationIDL.ORBPortInfoListHelper.write (ostream, value.ports); } }
923a5f9fe0a4bfe1be128d4db3169199359c9f1a
805
java
Java
app/src/main/java/com/room/db/entity/TradeDetail.java
BuleB/RoomOrmDemo
063b0dff64b623401db50670040c45e7a5c4b42c
[ "Apache-2.0" ]
2
2020-04-09T01:16:37.000Z
2021-06-17T01:21:14.000Z
app/src/main/java/com/room/db/entity/TradeDetail.java
BuleB/RoomOrmDemo
063b0dff64b623401db50670040c45e7a5c4b42c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/room/db/entity/TradeDetail.java
BuleB/RoomOrmDemo
063b0dff64b623401db50670040c45e7a5c4b42c
[ "Apache-2.0" ]
1
2019-01-11T09:59:32.000Z
2019-01-11T09:59:32.000Z
23
50
0.536646
999,185
package com.room.db.entity; import android.arch.persistence.room.ColumnInfo; import java.util.Date; public class TradeDetail { //订单id public String id; //用户姓名 @ColumnInfo(name = "user_name") public String userName; //书本名 @ColumnInfo(name = "book_name") public String bookName; //购买价格 @ColumnInfo(name = "trade_price") public double tradePrice; //订单时间 @ColumnInfo(name = "trade_time") public Date tradeTime; @Override public String toString() { return "TradeDetail{" + "id='" + id + '\'' + ", userName='" + userName + '\'' + ", bookName='" + bookName + '\'' + ", tradePrice=" + tradePrice + ", tradeTime=" + tradeTime + '}'; } }
923a5faa8351b29af9c1c4f6077cb51011fecfb8
10,708
java
Java
src/main/java/musee/musee_vue/AjoutPhoto.java
Yirou/Musee
c6370099f0c527efd53cde831fa26002632c39a9
[ "MIT" ]
null
null
null
src/main/java/musee/musee_vue/AjoutPhoto.java
Yirou/Musee
c6370099f0c527efd53cde831fa26002632c39a9
[ "MIT" ]
null
null
null
src/main/java/musee/musee_vue/AjoutPhoto.java
Yirou/Musee
c6370099f0c527efd53cde831fa26002632c39a9
[ "MIT" ]
null
null
null
46.759825
175
0.653343
999,186
package musee.musee_vue; import java.io.File; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import musee.Demande; import musee.Photo; import musee.Photographe; /** * * @author yirou */ public class AjoutPhoto extends javax.swing.JFrame { private FileChooser chooser; Photographe photographe; private String fileDirectory = new String("C:\\Users"); private FileNameExtensionFilter bothFilter = new FileNameExtensionFilter("JPEG and GIF Image Files", "jpg", "gif","JPG"); public AjoutPhoto(Photographe photographe) { initComponents(); this.photographe=photographe; jTextField1.setEditable(false); setResizable(false); setTitle("Ajout nouvelle photo"); remplirCombobox(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("..."); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Valider"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE) ); jLabel2.setText("Demande:"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jComboBox1, 0, 255, Short.MAX_VALUE) .addComponent(jTextField1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(63, 63, 63) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(17, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jLabel2) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(47, 47, 47) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(50, Short.MAX_VALUE)) ); jMenu1.setText("File"); jMenuItem1.setText("Quitter"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 8, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed chooser = new FileChooser(bothFilter) ; chooser.setCurrentDirectory(new File(fileDirectory)); int retval =chooser.showDialog(this, null); if (retval == JFileChooser.APPROVE_OPTION) { JOptionPane.showMessageDialog(this, chooser.getResultString()); String img = new String("file:///"+chooser.getResultString()); String imagesrc = new String("<html>" + "<center><img alt =\"\" src=\"" + img + "\" width=\"" + jLabel1.getWidth() + "\"" + "height=\"" + jLabel1.getHeight() + "\">" + "</center></html>"); fileDirectory = chooser.getCurrentDirectory().toString(); jTextField1.setText(chooser.getResultString()); jLabel1.setText(imagesrc); } else if (retval == JFileChooser.CANCEL_OPTION) { JOptionPane.showMessageDialog(this, "Operation annulé. Aucun fichier sélectionné."); } else if (retval == JFileChooser.ERROR_OPTION) { JOptionPane.showMessageDialog(this, "Erreur. Aucun fichier sélectionné"); } else { JOptionPane.showMessageDialog(this, "Unknown operation occured."); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed //Oeuvre oeuvre=new Oeuvre(dep.listeOeuvre.size()+2, "Image brute", jTextField1.getText().replace("\\" , "\\\\"), "", 0); Photo ph=new Photo(jTextField1.getText(), false); Demande d=chercherDemandeByName(photographe.demandePrisEnCharge, jComboBox1.getSelectedItem().toString()); d.setPhotoDeLaDemande(ph); d.changerEtatEnCoursDeValidation(); //dep.listeOeuvre.add(oeuvre); JOptionPane.showMessageDialog(null,"Image bien ajouté !"); this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed this.dispose(); }//GEN-LAST:event_jMenuItem1ActionPerformed public void remplirCombobox(){ jComboBox1.removeAllItems(); for(int i=0;i<photographe.demandePrisEnCharge.size();i++){ Demande d=photographe.demandePrisEnCharge.get(i); jComboBox1.addItem(d.getNomDemande()); } //desactive le bouton valider si la liste des demandes est vide if(photographe.demandePrisEnCharge.size()<1)jButton2.setEnabled(false); } public Demande chercherDemandeByName(ArrayList<Demande>listeD,String name){ for(int i=0;i<listeD.size();i++){ Demande d=listeD.get(i); if(d.getNomDemande().equals(name)){ return d; } } return null; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
923a5ffb3c9227660d77c6aeab9a0b69be947eb6
1,089
java
Java
app/src/main/java/com/davidpapazian/yokaiwatchmedals/views/SpaceItemDecoration.java
davidpapazian/YokaiWatchMedals
e2ea15f0841ce24bda1ab2dbd21dbb39c2c36abd
[ "blessing" ]
null
null
null
app/src/main/java/com/davidpapazian/yokaiwatchmedals/views/SpaceItemDecoration.java
davidpapazian/YokaiWatchMedals
e2ea15f0841ce24bda1ab2dbd21dbb39c2c36abd
[ "blessing" ]
null
null
null
app/src/main/java/com/davidpapazian/yokaiwatchmedals/views/SpaceItemDecoration.java
davidpapazian/YokaiWatchMedals
e2ea15f0841ce24bda1ab2dbd21dbb39c2c36abd
[ "blessing" ]
null
null
null
30.25
104
0.706152
999,187
package com.davidpapazian.yokaiwatchmedals.views; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; public class SpaceItemDecoration extends RecyclerView.ItemDecoration { private final int marginLeft; private final int marginTop; private final int marginRight; private final int marginBottom; public SpaceItemDecoration(int marginLeft, int marginTop, int marginRight, int marginBottom) { this.marginLeft = marginLeft; this.marginTop = marginTop; this.marginRight = marginRight; this.marginBottom = marginBottom; } public SpaceItemDecoration(int margin) { this.marginLeft = margin; this.marginTop = margin; this.marginRight = margin; this.marginBottom = margin; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = marginLeft; outRect.top = marginTop; outRect.right = marginRight; outRect.bottom = marginBottom; } }
923a6078f1591badef6d330c6c62fcbd5d498a89
5,857
java
Java
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/de/metas/letters/model/X_AD_BoilerPlate_Var.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/de/metas/letters/model/X_AD_BoilerPlate_Var.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/de/metas/letters/model/X_AD_BoilerPlate_Var.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
27.497653
129
0.670821
999,188
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via nnheo@example.com or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package de.metas.letters.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for AD_BoilerPlate_Var * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_AD_BoilerPlate_Var extends org.compiere.model.PO implements I_AD_BoilerPlate_Var, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -1279595309L; /** Standard Constructor */ public X_AD_BoilerPlate_Var (Properties ctx, int AD_BoilerPlate_Var_ID, String trxName) { super (ctx, AD_BoilerPlate_Var_ID, trxName); /** if (AD_BoilerPlate_Var_ID == 0) { setAD_BoilerPlate_Var_ID (0); setName (null); setType (null); // S setValue (null); } */ } /** Load Constructor */ public X_AD_BoilerPlate_Var (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_AD_BoilerPlate_Var[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Boiler Plate Variable. @param AD_BoilerPlate_Var_ID Boiler Plate Variable */ @Override public void setAD_BoilerPlate_Var_ID (int AD_BoilerPlate_Var_ID) { if (AD_BoilerPlate_Var_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_Var_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_Var_ID, Integer.valueOf(AD_BoilerPlate_Var_ID)); } /** Get Boiler Plate Variable. @return Boiler Plate Variable */ @Override public int getAD_BoilerPlate_Var_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_Var_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Rule getAD_Rule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class); } @Override public void setAD_Rule(org.compiere.model.I_AD_Rule AD_Rule) { set_ValueFromPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class, AD_Rule); } /** Set Rule. @param AD_Rule_ID Rule */ @Override public void setAD_Rule_ID (int AD_Rule_ID) { if (AD_Rule_ID < 1) set_Value (COLUMNNAME_AD_Rule_ID, null); else set_Value (COLUMNNAME_AD_Rule_ID, Integer.valueOf(AD_Rule_ID)); } /** Get Rule. @return Rule */ @Override public int getAD_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * Type AD_Reference_ID=540047 * Reference name: AD_BoilerPlate_VarType */ public static final int TYPE_AD_Reference_ID=540047; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Rule Engine = R */ public static final String TYPE_RuleEngine = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
923a608589a9b57ea0340448ba6b07a542aa3ce1
1,123
java
Java
gmall-ums-interface/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java
ShinmlyQiao/gmall
8d7cfd54fbeb7824d04f57d0b05d3ad6c4102545
[ "Apache-2.0" ]
1
2021-01-31T06:59:58.000Z
2021-01-31T06:59:58.000Z
gmall-ums-interface/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java
ShinmlyQiao/gmall
8d7cfd54fbeb7824d04f57d0b05d3ad6c4102545
[ "Apache-2.0" ]
5
2020-05-21T19:12:01.000Z
2022-03-31T22:25:13.000Z
gmall-ums-interface/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java
ShinmlyQiao/gmall
8d7cfd54fbeb7824d04f57d0b05d3ad6c4102545
[ "Apache-2.0" ]
2
2021-03-24T08:04:01.000Z
2021-07-19T00:25:18.000Z
21.557692
65
0.728814
999,189
package com.atguigu.gmall.ums.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 会员收藏的专题活动 * * @author Qiao * @email ychag@example.com * @date 2020-04-28 11:47:02 */ @ApiModel @Data @TableName("ums_member_collect_subject") public class MemberCollectSubjectEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * subject_id */ @ApiModelProperty(name = "subjectId",value = "subject_id") private Long subjectId; /** * subject_name */ @ApiModelProperty(name = "subjectName",value = "subject_name") private String subjectName; /** * subject_img */ @ApiModelProperty(name = "subjectImg",value = "subject_img") private String subjectImg; /** * 活动url */ @ApiModelProperty(name = "subjectUrll",value = "活动url") private String subjectUrll; }
923a608c769107cfb478ab61f76fac3e9b081c24
11,720
java
Java
src/main/java/com/lhjz/portal/controller/ProjectController.java
xiweicheng/tms
2152e77bebd393a0997b82468a394c4848df4504
[ "MIT" ]
296
2017-01-26T12:19:24.000Z
2022-03-18T00:50:30.000Z
src/main/java/com/lhjz/portal/controller/ProjectController.java
pgy866/tms
2152e77bebd393a0997b82468a394c4848df4504
[ "MIT" ]
9
2018-08-17T01:34:58.000Z
2022-03-26T13:25:44.000Z
src/main/java/com/lhjz/portal/controller/ProjectController.java
pgy866/tms
2152e77bebd393a0997b82468a394c4848df4504
[ "MIT" ]
89
2017-02-10T02:07:18.000Z
2022-03-30T10:10:54.000Z
27.383178
89
0.731058
999,190
/** * 版权所有 (TMS) */ package com.lhjz.portal.controller; import com.lhjz.portal.base.BaseController; import com.lhjz.portal.entity.Label; import com.lhjz.portal.entity.Language; import com.lhjz.portal.entity.Project; import com.lhjz.portal.entity.Translate; import com.lhjz.portal.entity.TranslateItem; import com.lhjz.portal.entity.TranslateItemHistory; import com.lhjz.portal.entity.security.User; import com.lhjz.portal.model.RespBody; import com.lhjz.portal.pojo.Enum.Action; import com.lhjz.portal.pojo.Enum.Status; import com.lhjz.portal.pojo.Enum.Target; import com.lhjz.portal.pojo.ProjectForm; import com.lhjz.portal.repository.AuthorityRepository; import com.lhjz.portal.repository.LabelRepository; import com.lhjz.portal.repository.LanguageRepository; import com.lhjz.portal.repository.ProjectRepository; import com.lhjz.portal.repository.TranslateItemHistoryRepository; import com.lhjz.portal.repository.TranslateItemRepository; import com.lhjz.portal.repository.TranslateRepository; import com.lhjz.portal.util.StringUtil; import com.lhjz.portal.util.WebUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.validation.Valid; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * * @author xi * * @date 2015年3月28日 下午1:19:05 * */ @Controller @RequestMapping("admin/project") public class ProjectController extends BaseController { static Logger logger = LoggerFactory.getLogger(ProjectController.class); @Autowired TranslateRepository translateRepository; @Autowired TranslateItemRepository translateItemRepository; @Autowired TranslateItemHistoryRepository translateItemHistoryRepository; @Autowired ProjectRepository projectRepository; @Autowired LanguageRepository languageRepository; @Autowired LabelRepository labelRepository; @Autowired AuthorityRepository authorityRepository; private boolean isContainsMainLanguage(ProjectForm projectForm) { String[] lngs = projectForm.getLanguages().split(","); for (String lng : lngs) { if (lng.equals(String.valueOf(projectForm.getLanguage()))) { return true; } } return false; } @RequestMapping(value = "create", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody create(@Valid ProjectForm projectForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream() .map(err -> err.getDefaultMessage()) .collect(Collectors.joining("<br/>"))); } Project project3 = projectRepository.findOneByName(projectForm .getName()); if (project3 != null) { return RespBody.failed("同名项目已经存在!"); } if (!isContainsMainLanguage(projectForm)) { return RespBody.failed("设置语言必须包含主语言!"); } Project project = new Project(); project.setCreateDate(new Date()); project.setCreator(WebUtil.getUsername()); project.setDescription(projectForm.getDesc()); project.setName(projectForm.getName()); project.setStatus(Status.New); project.setLanguage(languageRepository.findOne(projectForm .getLanguage())); // 项目语言保存 String[] lngArr = projectForm.getLanguages().split(","); List<Long> collect = Arrays.asList(lngArr).stream().map((lng) -> { return Long.valueOf(lng); }).collect(Collectors.toList()); List<Language> languages = languageRepository.findAll(collect); project.getLanguages().addAll(languages); // 项目关注者保存 List<User> watchers = null; if (StringUtil.isNotEmpty(projectForm.getWatchers())) { watchers = userRepository.findAll(Arrays.asList(projectForm .getWatchers().split(","))); project.getWatchers().addAll(watchers); } Project project2 = projectRepository.saveAndFlush(project); // 保存项目语言关系 for (Language language : languages) { language.getProjects().add(project2); } languageRepository.save(languages); languageRepository.flush(); // 保存项目关注者关系 if (watchers != null) { for (User user : watchers) { user.getWatcherProjects().add(project2); } userRepository.save(watchers); userRepository.flush(); } log(Action.Create, Target.Project, project2.getId()); return RespBody.succeed(project2); } private boolean isExistLanguage(Set<Language> lngs, Language lng) { for (Language language : lngs) { if (language.getId().equals(lng.getId())) { return true; } } return false; } private boolean isExistWatcher(Set<User> watchers, User user) { for (User watcher : watchers) { if (watcher.getUsername().equals(user.getUsername())) { return true; } } return false; } @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody update(@RequestParam("id") Long id, @Valid ProjectForm projectForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream() .map(err -> err.getDefaultMessage()) .collect(Collectors.joining("<br/>"))); } if (!isContainsMainLanguage(projectForm)) { return RespBody.failed("设置语言必须包含主语言!"); } Project project = projectRepository.findOne(id); project.setDescription(projectForm.getDesc()); Project project2 = projectRepository.findOneByName(projectForm .getName()); if (project2 == null) { project.setName(projectForm.getName()); } project.setStatus(Status.Updated); project.setUpdateDate(new Date()); project.setUpdater(WebUtil.getUsername()); // 主语言如果变化,则保存 if (!project.getLanguage().getId().equals(projectForm.getLanguage())) { project.setLanguage(languageRepository.findOne(projectForm .getLanguage())); } // 项目语言保存 String[] lngArr = projectForm.getLanguages().split(","); List<Long> collect = Arrays.asList(lngArr).stream().map((lng) -> { return Long.valueOf(lng); }).collect(Collectors.toList()); Set<Language> languages = project.getLanguages(); for (Language language : languages) { // 语言不存在,被删除了 if (!collect.contains(language.getId())) { language.getProjects().remove(project); } } HashSet<Language> languages2 = new HashSet<Language>( languageRepository.findAll(collect)); for (Language language : languages2) { // 新添加的语言 if (!isExistLanguage(languages, language)) { language.getProjects().add(project); } } languageRepository.save(languages); languageRepository.save(languages2); languageRepository.flush(); if (StringUtil.isNotEmpty(projectForm.getWatchers())) { List<String> watchers = Arrays.asList(projectForm.getWatchers() .split(",")); Set<User> watchers2 = project.getWatchers(); for (User user : watchers2) { if (!watchers.contains(user.getUsername())) { user.getWatcherProjects().remove(project); } } List<User> watcher3 = userRepository.findAll(watchers); for (User user : watcher3) { if (!isExistWatcher(watchers2, user)) { user.getWatcherProjects().add(project); } } userRepository.save(watchers2); userRepository.save(watcher3); languageRepository.flush(); project.setWatchers(new HashSet<User>(watcher3)); } else { // 删除全部关注者 project.getWatchers().stream().forEach((w) -> { w.getWatcherProjects().remove(project); }); userRepository.save(project.getWatchers()); userRepository.flush(); project.getWatchers().clear(); } project.setLanguages(languages2); projectRepository.saveAndFlush(project); log(Action.Update, Target.Project, project.getId()); return RespBody.succeed(project); } @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody delete(@RequestParam("id") Long id) { if (WebUtil.isRememberMeAuthenticated()) { return RespBody.failed("因为当前是通过[记住我]登录,为了安全需要,请退出重新登录再尝试删除项目!"); } Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed("删除项目不存在!"); } // 解除项目&语言关系 Set<Language> languages = project.getLanguages(); for (Language language : languages) { language.getProjects().remove(project); } languageRepository.save(languages); languageRepository.flush(); // 删除项目下全部翻译 Set<Translate> translates = project.getTranslates(); Set<TranslateItem> translateItems = new HashSet<TranslateItem>(); Set<TranslateItemHistory> translateItemHistories = new HashSet<TranslateItemHistory>(); Set<Label> labels = new HashSet<Label>(); translates.stream().forEach((t) -> { Set<TranslateItem> translateItems2 = t.getTranslateItems(); translateItems2.stream().forEach((ti) -> { ti.setTranslate(null); Set<TranslateItemHistory> translateItemHistories2 = ti.getTranslateItemHistories(); translateItemHistories2.stream().forEach((h -> { h.setTranslateItem(null); })); translateItemHistories.addAll(translateItemHistories2); }); translateItems.addAll(translateItems2); Set<Label> labels2 = t.getLabels(); labels2.stream().forEach((l) -> { l.setTranslate(null); }); labels.addAll(labels2); t.setProject(null); }); translateItemHistoryRepository.deleteInBatch(translateItemHistories); translateItemHistoryRepository.flush(); translateItemRepository.deleteInBatch(translateItems); translateItemRepository.flush(); labelRepository.deleteInBatch(labels); labelRepository.flush(); // 解除项目关注者和用户关系 Set<User> watchers = project.getWatchers(); for (User user : watchers) { user.getWatcherProjects().remove(project); } userRepository.save(watchers); userRepository.flush(); // 解除项目用户&项目关系 Set<User> users = project.getUsers(); users.stream().forEach((u) -> { u.getProjects().remove(project); }); userRepository.save(users); userRepository.flush(); translateRepository.deleteInBatch(translates); translateRepository.flush(); // 待关系都解除后,删除项目 projectRepository.delete(project); projectRepository.flush(); log(Action.Delete, Target.Project, id); return RespBody.succeed(id); } @RequestMapping(value = "deleteWatcher", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN", "ROLE_USER" }) public RespBody deleteWatcher(@RequestParam("id") Long id, @RequestParam("username") String username) { Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed("项目不存在!"); } User watcher = userRepository.findOne(username); if (watcher == null) { return RespBody.failed("关注者用户不存在!"); } watcher.getWatcherProjects().remove(project); project.getWatchers().remove(watcher); userRepository.saveAndFlush(watcher); projectRepository.saveAndFlush(project); log(Action.Update, Target.Project, project.getId()); return RespBody.succeed(id); } @RequestMapping(value = "get", method = RequestMethod.GET) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody get(@RequestParam("id") Long id) { Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed("获取项目不存在!"); } log(Action.Read, Target.Project, id); return RespBody.succeed(project); } }
923a6192e0941fef1fc79cbcf1613d5ca6af9ac9
419
java
Java
java/removeelement.java
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
12
2015-03-12T03:27:26.000Z
2021-03-11T09:26:16.000Z
java/removeelement.java
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
null
null
null
java/removeelement.java
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
11
2015-01-28T16:45:40.000Z
2017-03-28T20:01:38.000Z
23.277778
49
0.398568
999,191
public class Solution { public int removeElement(int[] A, int elem) { // Start typing your Java solution below // DO NOT write main() function int last = A.length-1; int i=0; while(i<=last){ if(A[i]==elem){ A[i]=A[last]; last--; } else{ i++; } } return i; } }
923a63236e0b7519464ca4672184db397c1da70a
105
java
Java
src/main/java/com/phicomm/product/manger/controller/package-info.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
null
null
null
src/main/java/com/phicomm/product/manger/controller/package-info.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
null
null
null
src/main/java/com/phicomm/product/manger/controller/package-info.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
4
2018-08-07T15:21:29.000Z
2021-07-06T07:35:52.000Z
17.5
46
0.657143
999,192
/** * 接口 * <p> * Created by yufei.liu on 2017/6/26. */ package com.phicomm.product.manger.controller;
923a635e48cfc2765d5cef113900258300c22c07
333
java
Java
src/tp/pr5/mv/traps/MVTrap.java
daxadal/programing-102
41d7c8de748587196789ef32ffa2c086e1ff587e
[ "MIT" ]
null
null
null
src/tp/pr5/mv/traps/MVTrap.java
daxadal/programing-102
41d7c8de748587196789ef32ffa2c086e1ff587e
[ "MIT" ]
null
null
null
src/tp/pr5/mv/traps/MVTrap.java
daxadal/programing-102
41d7c8de748587196789ef32ffa2c086e1ff587e
[ "MIT" ]
null
null
null
14.478261
47
0.624625
999,193
package tp.pr5.mv.traps; @SuppressWarnings("serial") public class MVTrap extends Exception { public MVTrap() { super(); } public MVTrap(String mensaje) { super(mensaje); } public MVTrap(Throwable th) { super(th); } public MVTrap(String mensaje, Throwable th) { super(mensaje, th); } }
923a63d196df0bf28bc18c234ee729666502e953
6,333
java
Java
src/CutRopeMaxProduct.java
lipsapatel/Algorithms
6f870a1b8fb4c9d576bee95730965a20a2657c7e
[ "MIT" ]
2
2018-05-02T22:07:32.000Z
2022-03-27T15:41:32.000Z
src/CutRopeMaxProduct.java
lipsapatel/Algorithms
6f870a1b8fb4c9d576bee95730965a20a2657c7e
[ "MIT" ]
null
null
null
src/CutRopeMaxProduct.java
lipsapatel/Algorithms
6f870a1b8fb4c9d576bee95730965a20a2657c7e
[ "MIT" ]
1
2020-10-22T15:01:13.000Z
2020-10-22T15:01:13.000Z
33.507937
134
0.591031
999,194
/** * Cut The Rope * Given a rope with length n, find the maximum value maxProduct, that can be achieved for product len[0] * len[1] * ... * len[m - 1], * where len[] is the array of lengths obtained by cutting the given rope into m parts. * * Note that * there should be atleast one cut, i.e. m >= 2. * All m parts obtained after cut should have non-zero integer valued lengths. * * For input n = 5, output will be: * 6 * * Constraints: * 2 <= n <= 111 * We have to cut at least once. (2 <= m). * Length of the rope, as well as the length of each part are in positive integer value. (i.e. can't do partial cuts.) * * Sample Input: * 4 * * Sample Output: * 4 * * Explanation: * For n = 4, there are two cuts possible: 1 + 3 and 2 + 2. * We'll pick 2 + 2, because their product 2 * 2 = 4 is greater than product of the first one 1 * 3 = 3. * (So our m = 2, n[0] = 2 and n[1] = 2 and product is n[0] * n[1] = 4.) * * resources/CutRopeMaxProductRecursion.jpg * resources/CutRopeMaxProductDp.jpg * resources/CutRopeMaxProductRecursion1.jpg * resources/CutRopeMaxProductTrickyApproach.jpg * * Recursion Solution * * Time Complexity: O(n^n) O(n!) * Space Complexity: O(n) * * Dp Solution: * * Time Complexity: O(n^2) * Space Complexity: O(n) * * Tricky Approach from observation * * For i >= 5, there's always one cut of length = 3 * * Time Complexity: O(n) * Space Complexity: O(n) * * Another tricky Approach * * 1) If the rope is multiple of 3, cut into 3 equal pieces. * 2) If rope is multiple of 3 + 1, cut one piece of len 4 and remaining of len 3 * 3) If rope is multiple of 3 + 2, cut one piece of length 2 and remaining of len 3 * * Power function: * Time complexity: O(logb) where b = n/3 * Space complexity: O(logb) where b = n/3 */ public class CutRopeMaxProduct { private static long maxProductFromCutPiecesRecursion(int n) { //Base Case if(n == 1) { return 1; } //At least one cut is required. //For all possible cuts long maxProduct = 1; for(int i = 1; i < n; i++) { //You don't have to do cut for 4, for example f(5) = max(1 * max (f(4), 4), 2 * max(f(3), 3), // 3 * max(f(2), 2), 4 * max(f(1), 1)) maxProduct = Math.max(maxProduct, i * Math.max(maxProductFromCutPiecesRecursion(n - i), n - i)); } return maxProduct; } private static long maxProductFromCutPiecesDp(int n) { //Identify the dp table //Recursion - one param changing n long[] dp = new long[n + 1]; //Initialize the dp table //Base case n == 0 return 1 dp[1] = 1; //Traversal direction. Recursion n to 0 // 1 to n for(int j = 2; j <= n; j++) { //Populate dp table long maxProduct = 1; //For all possible cuts for(int i = 1; i < j; i++) { maxProduct = Math.max(maxProduct, i * Math.max(dp[j - i], j - i)); } dp[j] = maxProduct; } return dp[n]; } private static long maxProductFromCutPiecesTrickyApproach(int n) { long[] maxProduct = new long[n + 1]; //Base Cases maxProduct[2] = 1; if(n >= 3) { maxProduct[3] = 2; } if(n >= 4) { maxProduct[4] = 4; } //There will be always one cut of length = 3 for(int i = 5; i <= n; i++) { maxProduct[i] = Math.max(i - 3, maxProduct[i - 3]) * 3; } return maxProduct[n]; } private static long maxProductFromCutPiecesAnotherTrickyApproach(int n) { if(n <= 3) { return n - 1; } if(n % 3 == 0) { //Cut all pieces of length 3 return power(3, n/3); } if(n % 3 == 1) { //Cut one piece of length 4 and all other pieces of length 3 return power(3, (n - 4)/3) * 4; } //Cut one piece of length 2 and all other pieces of length 3 return power(3, (n - 2)/3) * 2; } //k ^n //Time Complexity: O(logn) //Space Complexity: O(logn) private static long power(int k, int n) { if(n == 0) { return 1; } long halfResult = power(k, n/2); if(n % 2 == 0) { //even return halfResult * halfResult; } else { //odd return halfResult * halfResult * k; } } public static void main(String[] args) { int n = 3; System.out.println("Max Product for n = 3 Recursive " + maxProductFromCutPiecesRecursion(n)); System.out.println("Max Product for n = 3 Dp " + maxProductFromCutPiecesDp(n)); System.out.println("Max Product for n = 3 Tricky approach " + maxProductFromCutPiecesTrickyApproach(n)); System.out.println("Max Product for n = 3 Another Tricky approach " + maxProductFromCutPiecesAnotherTrickyApproach(n)); n = 4; System.out.println("Max Product for n = 4 Recursive " + maxProductFromCutPiecesRecursion(n)); System.out.println("Max Product for n = 4 Dp " + maxProductFromCutPiecesDp(n)); System.out.println("Max Product for n = 4 Tricky approach " + maxProductFromCutPiecesTrickyApproach(n)); System.out.println("Max Product for n = 4 Another Tricky approach " + maxProductFromCutPiecesAnotherTrickyApproach(n)); n = 5; System.out.println("Max Product for n = 5 Recursive " + maxProductFromCutPiecesRecursion(n)); System.out.println("Max Product for n = 5 Dp " + maxProductFromCutPiecesDp(n)); System.out.println("Max Product for n = 5 Tricky approach " + maxProductFromCutPiecesTrickyApproach(n)); System.out.println("Max Product for n = 5 Another Tricky approach " + maxProductFromCutPiecesAnotherTrickyApproach(n)); n = 8; System.out.println("Max Product for n = 8 Recursive " + maxProductFromCutPiecesRecursion(n)); System.out.println("Max Product for n = 8 Dp " + maxProductFromCutPiecesDp(n)); System.out.println("Max Product for n = 8 Tricky approach " + maxProductFromCutPiecesTrickyApproach(n)); System.out.println("Max Product for n = 8 Another Tricky approach " + maxProductFromCutPiecesAnotherTrickyApproach(n)); } }
923a6494d8b4cf5a9b5df24fa88b07e9f18e6b5e
5,670
java
Java
projects/integration/src/main/java/com/opengamma/integration/tool/hts/HistoricalTimeSeriesLoaderTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-18T09:32:40.000Z
2021-03-08T20:05:54.000Z
projects/integration/src/main/java/com/opengamma/integration/tool/hts/HistoricalTimeSeriesLoaderTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
10
2017-01-19T13:32:36.000Z
2021-09-20T20:41:48.000Z
projects/integration/src/main/java/com/opengamma/integration/tool/hts/HistoricalTimeSeriesLoaderTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-14T12:46:18.000Z
2020-12-11T19:52:37.000Z
42.313433
156
0.702646
999,195
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.integration.tool.hts; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.component.tool.AbstractTool; import com.opengamma.financial.tool.ToolContext; import com.opengamma.id.ExternalId; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesLoader; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesLoaderRequest; import com.opengamma.scripts.Scriptable; /** * A tool to load a list of historical timeseries from the system's hts loader (e.g. Quandl/Bloomberg). File contains only the ids you want to load, not the * data itself. For raw data loading, see TimeSeriesLoaderTool. */ @Scriptable public class HistoricalTimeSeriesLoaderTool extends AbstractTool<ToolContext> { private static final Logger LOGGER = LoggerFactory.getLogger(HistoricalTimeSeriesLoaderTool.class); /** File name option flag. */ public static final String FILE_NAME_OPT = "f"; /** Time series data source option flag. */ public static final String TIME_SERIES_DATASOURCE_OPT = "s"; /** Time series data provider option flag. */ public static final String TIME_SERIES_DATAPROVIDER_OPT = "p"; /** Time series data field option flag. */ public static final String TIME_SERIES_DATAFIELD_OPT = "d"; /** Time series ID scheme option flag. */ public static final String TIME_SERIES_IDSCHEME_OPT = "i"; /** Default value for the data provider */ private static final String DEFAULT_DATA_PROVIDER = "DEFAULT"; private static final String HELP_HEADER = "Tool to load time series from the system data source from a text file, one line per identifier."; private static final String HELP_FOOTER = null; // NOTE: jim 26-Jan-15 -- checked that printHelp code handles nulls okay. // ------------------------------------------------------------------------- /** * Main method to run the tool. * * @param args * the arguments, not null */ public static void main(final String[] args) { // CSIGNORE new HistoricalTimeSeriesLoaderTool().invokeAndTerminate(args); } // ------------------------------------------------------------------------- /** * Loads the test portfolio into the position master. */ @Override protected void doRun() { final String fileName = getCommandLine().getOptionValue(FILE_NAME_OPT); final String dataProvider = getCommandLine().hasOption(TIME_SERIES_DATAPROVIDER_OPT) ? getCommandLine().getOptionValue(TIME_SERIES_DATAPROVIDER_OPT) : DEFAULT_DATA_PROVIDER; final String dataField = getCommandLine().getOptionValue(TIME_SERIES_DATAFIELD_OPT); final HistoricalTimeSeriesLoader loader = getToolContext().getHistoricalTimeSeriesLoader(); try { final File file = new File(fileName); if (file.exists()) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; final Set<ExternalId> ids = new LinkedHashSet<>(); while ((line = reader.readLine()) != null) { if (line.contains("~")) { ids.add(ExternalId.parse(line.trim())); } else { if (getCommandLine().hasOption(TIME_SERIES_IDSCHEME_OPT)) { ids.add(ExternalId.of(getCommandLine().getOptionValue(TIME_SERIES_IDSCHEME_OPT), line.trim())); } else { LOGGER.error("Time series id {} does not have a scheme, and ID scheme option not set, so cannot be loaded, skipping.", line); } } } final HistoricalTimeSeriesLoaderRequest req = HistoricalTimeSeriesLoaderRequest.create(ids, dataProvider, dataField, null, null); loader.loadTimeSeries(req); } } else { LOGGER.error("File {} does not exist", fileName); } } catch (final Exception e) { } } @Override protected Options createOptions(final boolean contextProvided) { final Options options = super.createOptions(contextProvided); final Option filenameOption = new Option( FILE_NAME_OPT, "filename", true, "The path to the file containing data to import (CSV or ZIP)"); filenameOption.setRequired(true); options.addOption(filenameOption); final Option timeSeriesDataProviderOption = new Option( TIME_SERIES_DATAPROVIDER_OPT, "provider", true, "The name of the time series data provider (defaults to DEFAULT)"); timeSeriesDataProviderOption.setOptionalArg(true); options.addOption(timeSeriesDataProviderOption); final Option timeSeriesDataFieldOption = new Option( TIME_SERIES_DATAFIELD_OPT, "field", true, "The name of the time series data field"); options.addOption(timeSeriesDataFieldOption); final Option timeSeriesIdSchemeOption = new Option( TIME_SERIES_IDSCHEME_OPT, "scheme", true, "The time series ID scheme (e.g. RIC, if omitted, assumes included in file IDs)"); timeSeriesIdSchemeOption.setOptionalArg(true); options.addOption(timeSeriesIdSchemeOption); return options; } @Override protected void usage(final Options options) { final HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("historical-time-series-loader-tool.sh", HELP_HEADER, options, HELP_FOOTER, true); } }
923a6556b33bce58749cfc12b33079b17761ef78
7,859
java
Java
mockserver-core/src/test/java/org/mockserver/model/JsonBodyTest.java
acanda/mockserver
e9a36562e4d73c891da15da78eef7248b7f3c9e5
[ "Apache-2.0" ]
null
null
null
mockserver-core/src/test/java/org/mockserver/model/JsonBodyTest.java
acanda/mockserver
e9a36562e4d73c891da15da78eef7248b7f3c9e5
[ "Apache-2.0" ]
25
2020-12-09T07:05:01.000Z
2022-03-14T21:09:00.000Z
mockserver-core/src/test/java/org/mockserver/model/JsonBodyTest.java
acanda/mockserver
e9a36562e4d73c891da15da78eef7248b7f3c9e5
[ "Apache-2.0" ]
null
null
null
37.602871
199
0.65899
999,196
package org.mockserver.model; import org.junit.Test; import org.mockserver.matchers.MatchType; import java.nio.charset.StandardCharsets; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockserver.matchers.MatchType.ONLY_MATCHING_FIELDS; import static org.mockserver.matchers.MatchType.STRICT; import static org.mockserver.model.JsonBody.json; /** * @author jamesdbloom */ public class JsonBodyTest { @Test public void shouldReturnValuesSetInConstructor() { // when JsonBody jsonBody = new JsonBody("some_body"); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(MatchType.ONLY_MATCHING_FIELDS)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesSetInConstructorWithMatchType() { // when JsonBody jsonBody = new JsonBody("some_body", MatchType.STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(MatchType.STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesSetInConstructorWithMatchTypeAndCharset() { // when JsonBody jsonBody = new JsonBody("some_body", null, (StandardCharsets.UTF_16 != null ? MediaType.create("application", "json").withCharset(StandardCharsets.UTF_16) : null), MatchType.STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(MatchType.STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesSetInConstructorWithMatchTypeAndMediaType() { // when JsonBody jsonBody = new JsonBody("some_body", null, MediaType.JSON_UTF_8, MatchType.STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(MatchType.STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesFromStaticBuilder() { // when JsonBody jsonBody = json("some_body"); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(ONLY_MATCHING_FIELDS)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesFromStaticBuilderWithMatchType() { // when JsonBody jsonBody = json("some_body", STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesFromStaticBuilderWithCharsetAndMatchType() { // when JsonBody jsonBody = json("some_body", StandardCharsets.UTF_16, STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesFromStaticBuilderWithMediaTypeAndMatchType() { // when JsonBody jsonBody = json("some_body", MediaType.parse("application/json; charset=utf-16"), STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesFromStaticBuilderWithMatchTypeAndCharset() { // when JsonBody jsonBody = json("some_body", StandardCharsets.UTF_16, STRICT); // then assertThat(jsonBody.getValue(), is("some_body")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesFromStaticObjectBuilder() { // when JsonBody jsonBody = json(new TestObject()); // then assertThat(jsonBody.getValue(), is("{\"fieldOne\":\"valueOne\",\"fieldTwo\":\"valueTwo\"}")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(ONLY_MATCHING_FIELDS)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesFromStaticObjectBuilderWithMatchType() { // when JsonBody jsonBody = json(new TestObject(), STRICT); // then assertThat(jsonBody.getValue(), is("{\"fieldOne\":\"valueOne\",\"fieldTwo\":\"valueTwo\"}")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-8")); } @Test public void shouldReturnValuesFromStaticObjectBuilderWithCharsetAndMatchType() { // when JsonBody jsonBody = json(new TestObject(), StandardCharsets.UTF_16, STRICT); // then assertThat(jsonBody.getValue(), is("{\"fieldOne\":\"valueOne\",\"fieldTwo\":\"valueTwo\"}")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesFromStaticObjectBuilderWithMediaTypeAndMatchType() { // when JsonBody jsonBody = json(new TestObject(), MediaType.parse("application/json; charset=utf-16"), STRICT); // then assertThat(jsonBody.getValue(), is("{\"fieldOne\":\"valueOne\",\"fieldTwo\":\"valueTwo\"}")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } @Test public void shouldReturnValuesFromStaticObjectBuilderWithMatchTypeAndCharset() { // when JsonBody jsonBody = json(new TestObject(), StandardCharsets.UTF_16, STRICT); // then assertThat(jsonBody.getValue(), is("{\"fieldOne\":\"valueOne\",\"fieldTwo\":\"valueTwo\"}")); assertThat(jsonBody.getType(), is(Body.Type.JSON)); assertThat(jsonBody.getMatchType(), is(STRICT)); assertThat(jsonBody.getContentType(), is("application/json; charset=utf-16")); } public static class TestObject { private String fieldOne = "valueOne"; private String fieldTwo = "valueTwo"; public String getFieldOne() { return fieldOne; } public void setFieldOne(String fieldOne) { this.fieldOne = fieldOne; } public String getFieldTwo() { return fieldTwo; } public void setFieldTwo(String fieldTwo) { this.fieldTwo = fieldTwo; } } }
923a65b1e1f936cd05ff1a9674262f33d4577117
7,276
java
Java
src/main/java/com/blamejared/compat/chisel/Groups.java
Jorch72/ModTweaker
66d127582633b477df5dceeb6502d0f67ba4811a
[ "MIT" ]
null
null
null
src/main/java/com/blamejared/compat/chisel/Groups.java
Jorch72/ModTweaker
66d127582633b477df5dceeb6502d0f67ba4811a
[ "MIT" ]
null
null
null
src/main/java/com/blamejared/compat/chisel/Groups.java
Jorch72/ModTweaker
66d127582633b477df5dceeb6502d0f67ba4811a
[ "MIT" ]
null
null
null
29.45749
105
0.568582
999,197
package com.blamejared.compat.chisel; import com.blamejared.api.annotations.*; import minetweaker.*; import minetweaker.api.item.IItemStack; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import stanhebben.zenscript.annotations.*; import team.chisel.api.carving.*; import team.chisel.common.carving.GroupList; import static com.blamejared.mtlib.helpers.InputHelper.toStack; @ZenClass("mods.chisel.Groups") @Handler("chisel") public class Groups { @ZenMethod @Document({"groupName", "stack"}) public static void addVariation(String groupName, IItemStack stack) { ICarvingGroup group = CarvingUtils.getChiselRegistry().getGroup(groupName); Block block = Block.getBlockFromItem(toStack(stack).getItem()); IBlockState state = block.getStateFromMeta(toStack(stack).getItemDamage()); ICarvingVariation variation = CarvingUtils.getDefaultVariationFor(state, 0); if(group == null) { MineTweakerAPI.getLogger().logError("Cannot find group " + groupName); return; } if(variation == null) { MineTweakerAPI.getLogger().logError("Can't create variation from " + stack); return; } MineTweakerAPI.apply(new AddVariation(group, variation, stack.toString())); } @ZenMethod @Document({"groupName"}) public static void removeGroup(String groupName) { ICarvingGroup group = CarvingUtils.getChiselRegistry().getGroup(groupName); if(group == null) { MineTweakerAPI.getLogger().logError("Could not find group " + groupName); return; } MineTweakerAPI.apply(new RemoveGroup(group)); } @ZenMethod @Document({"stack"}) public static void removeVariation(IItemStack stack) { ICarvingVariation variation = null; ICarvingGroup g = CarvingUtils.getChiselRegistry().getGroup(toStack(stack)); if(g != null) { for(ICarvingVariation v : g.getVariations()) { if(v.getStack().isItemEqual(toStack(stack))) { variation = v; } } } if(variation == null) { MineTweakerAPI.getLogger().logError("Can't find variation from " + stack); return; } MineTweakerAPI.apply(new RemoveVariation(variation, stack.toString())); } @ZenMethod @Document({"groupName"}) public static void addGroup(String groupName) { ICarvingGroup group = CarvingUtils.getChiselRegistry().getGroup(groupName); if(group != null) { MineTweakerAPI.getLogger().logError("Group already exists " + groupName); return; } group = CarvingUtils.getDefaultGroupFor(groupName); MineTweakerAPI.apply(new AddGroup(group)); } private static class AddVariation implements IUndoableAction { ICarvingGroup group; ICarvingVariation variation; String variationName; AddVariation(ICarvingGroup group, ICarvingVariation variation, String variationName) { this.group = group; this.variation = variation; this.variationName = variationName; } @Override public void apply() { CarvingUtils.getChiselRegistry().addVariation(group.getName(), variation); } @Override public void undo() { CarvingUtils.getChiselRegistry().removeVariation(variation.getBlockState(), group.getName()); } @Override public boolean canUndo() { return group != null && variation != null; } @Override public String describe() { return "Adding Variation: " + variationName; } @Override public String describeUndo() { return "Removing Variation: " + variationName; } @Override public Object getOverrideKey() { return null; } } private static class RemoveVariation implements IUndoableAction { ICarvingVariation variation; String variationName; ICarvingGroup group; RemoveVariation(ICarvingVariation variation, String variationName) { this.variation = variation; this.variationName = variationName; } @Override public void apply() { group = CarvingUtils.getChiselRegistry().getGroup(variation.getStack()); CarvingUtils.getChiselRegistry().removeVariation(variation.getBlockState(), group.getName()); } @Override public boolean canUndo() { return group != null && variation != null; } @Override public String describe() { return "Removing Variation: " + variationName; } @Override public String describeUndo() { return "Adding Variation: " + variationName; } @Override public void undo() { CarvingUtils.getChiselRegistry().addVariation(group.getName(), variation); } @Override public Object getOverrideKey() { return null; } } static class AddGroup implements IUndoableAction { ICarvingGroup group; AddGroup(ICarvingGroup group) { this.group = group; } @Override public void apply() { CarvingUtils.getChiselRegistry().addGroup(group); } @Override public boolean canUndo() { return group != null; } @Override public String describe() { return "Adding Group: " + group.getName(); } @Override public String describeUndo() { return "Removing Group: " + group.getName(); } @Override public void undo() { CarvingUtils.getChiselRegistry().removeGroup(group.getName()); } @Override public Object getOverrideKey() { return null; } } private static class RemoveGroup implements IUndoableAction { ICarvingGroup group; RemoveGroup(ICarvingGroup group) { this.group = group; } @Override public void apply() { CarvingUtils.getChiselRegistry().removeGroup(group.getName()); } @Override public boolean canUndo() { return group != null; } @Override public String describe() { return "Removing Group: " + group.getName(); } @Override public String describeUndo() { return "Adding Group: " + group.getName(); } @Override public void undo() { CarvingUtils.getChiselRegistry().addGroup(group); } @Override public Object getOverrideKey() { return null; } } }
923a669e2a940225a89b304f5b3ac5863881cc46
2,520
java
Java
src/main/java/org/jasig/ssp/service/impl/PersonDemographicsServiceImpl.java
rodrigoords/SSP
eb190f7db9aca3b42dd7c85127a709efe4b27e15
[ "ECL-2.0", "Apache-2.0" ]
17
2015-05-24T09:52:11.000Z
2022-03-29T08:49:00.000Z
src/main/java/org/jasig/ssp/service/impl/PersonDemographicsServiceImpl.java
rodrigoords/SSP
eb190f7db9aca3b42dd7c85127a709efe4b27e15
[ "ECL-2.0", "Apache-2.0" ]
3
2016-03-05T18:11:10.000Z
2017-11-02T23:34:17.000Z
src/main/java/org/jasig/ssp/service/impl/PersonDemographicsServiceImpl.java
rodrigoords/SSP
eb190f7db9aca3b42dd7c85127a709efe4b27e15
[ "ECL-2.0", "Apache-2.0" ]
45
2015-02-02T01:06:27.000Z
2022-02-21T15:33:26.000Z
30.731707
81
0.78254
999,198
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.ssp.service.impl; import java.math.BigDecimal; import java.util.UUID; import org.jasig.ssp.dao.PersonDemographicsDao; import org.jasig.ssp.model.ObjectStatus; import org.jasig.ssp.model.Person; import org.jasig.ssp.model.PersonDemographics; import org.jasig.ssp.service.ObjectNotFoundException; import org.jasig.ssp.service.PersonDemographicsService; import org.jasig.ssp.util.sort.PagingWrapper; import org.jasig.ssp.util.sort.SortingAndPaging; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PersonDemographicsServiceImpl implements PersonDemographicsService { @Autowired private transient PersonDemographicsDao dao; @Override public PagingWrapper<PersonDemographics> getAll(final SortingAndPaging sAndP) { return dao.getAll(sAndP); } @Override public PersonDemographics get(final UUID id) throws ObjectNotFoundException { return dao.get(id); } @Override public PersonDemographics forPerson(final Person person) { return person.getDemographics(); } @Override public PersonDemographics create(final PersonDemographics obj) { return dao.save(obj); } @Override public PersonDemographics save(final PersonDemographics obj) throws ObjectNotFoundException { return dao.save(obj); } @Override public BigDecimal getBalancedOwed(UUID personId){ return dao.getBalanceOwed(personId); } @Override public void delete(final UUID id) throws ObjectNotFoundException { final PersonDemographics current = get(id); if ((null != current) && !ObjectStatus.INACTIVE.equals(current.getObjectStatus())) { current.setObjectStatus(ObjectStatus.INACTIVE); save(current); } } }
923a66cd5e7baff2282308f8971be41e5ac8c49e
1,322
java
Java
dl-on-flink-framework/src/test/java/org/flinkextended/flink/ml/util/it/MiniClusterIT.java
Sxnan/dl-on-flink
5151eed9bde850eb07062a084f72096ff7b07027
[ "Apache-2.0" ]
50
2021-12-14T11:01:18.000Z
2022-03-28T16:32:33.000Z
dl-on-flink-framework/src/test/java/org/flinkextended/flink/ml/util/it/MiniClusterIT.java
Sxnan/dl-on-flink
5151eed9bde850eb07062a084f72096ff7b07027
[ "Apache-2.0" ]
32
2021-12-14T20:57:48.000Z
2022-03-31T08:25:28.000Z
dl-on-flink-framework/src/test/java/org/flinkextended/flink/ml/util/it/MiniClusterIT.java
Sxnan/dl-on-flink
5151eed9bde850eb07062a084f72096ff7b07027
[ "Apache-2.0" ]
15
2021-12-20T09:45:37.000Z
2022-03-15T11:01:27.000Z
26.979592
75
0.698185
999,199
/* * Copyright 2022 Deep Learning on Flink Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flinkextended.flink.ml.util.it; import org.flinkextended.flink.ml.util.MiniCluster; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** Integration test for {@link MiniCluster}. */ @Ignore public class MiniClusterIT { private static MiniCluster miniCluster; private static final int numTMs = 3; @Before public void setUp() throws Exception { miniCluster = MiniCluster.start(numTMs); } @After public void tearDown() throws Exception { if (miniCluster != null) { miniCluster.stop(); } } @Test public void runSimpleCmd() { System.out.println("haha"); } }
923a67688e4768243ce545a35b4808f8e39abb66
122
java
Java
src/main/java/priv/mw/domain/Tag.java
MW530/tidy
82a1ecfbbed455d3d3cf012abf7165551c8fbd6a
[ "Apache-2.0" ]
null
null
null
src/main/java/priv/mw/domain/Tag.java
MW530/tidy
82a1ecfbbed455d3d3cf012abf7165551c8fbd6a
[ "Apache-2.0" ]
null
null
null
src/main/java/priv/mw/domain/Tag.java
MW530/tidy
82a1ecfbbed455d3d3cf012abf7165551c8fbd6a
[ "Apache-2.0" ]
null
null
null
12.2
24
0.704918
999,200
package priv.mw.domain; import lombok.Data; @Data public class Tag { private Integer id; private String name; }
923a67f66620dbdcaddc05d7939a6abaca3c4c68
558
java
Java
Spring_day01/src/test/java/com/yang/demo/HelloServiceTest.java
liuyang89116/Spring_Learning
1d668ad83d0f9e1bdfd27ff5eb80c55e2c73769f
[ "MIT" ]
null
null
null
Spring_day01/src/test/java/com/yang/demo/HelloServiceTest.java
liuyang89116/Spring_Learning
1d668ad83d0f9e1bdfd27ff5eb80c55e2c73769f
[ "MIT" ]
null
null
null
Spring_day01/src/test/java/com/yang/demo/HelloServiceTest.java
liuyang89116/Spring_Learning
1d668ad83d0f9e1bdfd27ff5eb80c55e2c73769f
[ "MIT" ]
null
null
null
29.368421
93
0.761649
999,201
package com.yang.demo; import com.yang.demo1.AppConfig; import com.yang.demo1.HelloService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class HelloServiceTest { @Test public void demo() { // 创建工厂类 ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); HelloService helloService = (HelloService) context.getBean("helloService"); helloService.sayHello(); } }
923a6aba1ec4a5ad817de5261bd8f0c42c4c8f89
1,322
java
Java
converter/src/main/java/gov/cms/qpp/conversion/model/error/AllErrors.java
REIctamke/qpp-conversion-tool
b88c3590d55dbb49176decf944e4210870846b59
[ "CC0-1.0" ]
33
2017-10-18T18:29:55.000Z
2022-03-03T19:43:39.000Z
converter/src/main/java/gov/cms/qpp/conversion/model/error/AllErrors.java
REIctamke/qpp-conversion-tool
b88c3590d55dbb49176decf944e4210870846b59
[ "CC0-1.0" ]
341
2017-10-18T22:17:31.000Z
2022-03-31T18:45:39.000Z
converter/src/main/java/gov/cms/qpp/conversion/model/error/AllErrors.java
REIctamke/qpp-conversion-tool
b88c3590d55dbb49176decf944e4210870846b59
[ "CC0-1.0" ]
56
2017-10-26T14:56:14.000Z
2022-03-27T16:17:50.000Z
19.15942
69
0.654312
999,202
package gov.cms.qpp.conversion.model.error; import com.google.common.base.MoreObjects; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Contains a list of error errors. */ public class AllErrors implements Serializable { private static final long serialVersionUID = -223805249639231357L; private List<Error> errors; /** * Constructs an {@code AllErrors} with no errors. */ public AllErrors() { //empty on purpose } /** * Constructs a {@code AllErrors} with the specified {@link Error}s. * * @param errors The list of {@code Error}s. */ public AllErrors(List<Error> errors) { this.errors = errors; } /** * Gets all the {@link Error}s. * * @return All the {@code Error}s. */ public List<Error> getErrors() { return errors; } /** * Sets all the {@link Error}. * * @param errors The {@code Error}s to use. */ public void setErrors(final List<Error> errors) { this.errors = errors; } /** * Adds a {@link Error} to the list. * * @param error The {@code Error} to add. */ public void addError(Error error) { if (null == errors) { errors = new ArrayList<>(); } errors.add(error); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("errors", errors) .toString(); } }
923a6b20cbd3c768e9abe2816480c94c46007ceb
3,809
java
Java
src/graphvisualizer/graph/HeapPriorityQueue.java
camli1803/Visualize-_Strongly_Connected_Graphs
d6d1a959ab2eb325026c8e26c7ce796b023ebfbc
[ "MIT" ]
6
2020-07-25T19:07:42.000Z
2021-05-06T16:37:37.000Z
src/graphvisualizer/graph/HeapPriorityQueue.java
camli1803/Visualize-_Strongly_Connected_Graphs
d6d1a959ab2eb325026c8e26c7ce796b023ebfbc
[ "MIT" ]
null
null
null
src/graphvisualizer/graph/HeapPriorityQueue.java
camli1803/Visualize-_Strongly_Connected_Graphs
d6d1a959ab2eb325026c8e26c7ce796b023ebfbc
[ "MIT" ]
1
2021-06-01T12:18:23.000Z
2021-06-01T12:18:23.000Z
38.474747
119
0.549226
999,203
package graphvisualizer.graph; import java.util.ArrayList; import java.util.Comparator; //An implementation of a priority queue using an array-based heap public class HeapPriorityQueue<K,V> extends AbstractPriorityQueue<K,V>{ //primary collection of priority queue entries protected ArrayList<Entry<K,V>> heap = new ArrayList<>(); //create an empty priority queue based on the natural ordering of its keys public HeapPriorityQueue(){super();} //create an empty priority queue using the given comparator to order keys public HeapPriorityQueue(Comparator<K> comp){super(comp);} //protected utilities protected int parent(int j){ return (j-1)/2; } //truncating division protected int left (int j){ return 2*j+1; } protected int right (int j){ return 2*j+2; } protected boolean hasLeft(int j){ return left(j) < heap.size(); } protected boolean hasRight(int j){ return right(j) < heap.size(); } //Exchanges the entries at indices i and j of the array list protected void swap(int i, int j){ Entry<K,V> temp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, temp); } //Moves the entry at index j higher, if necessary, to restore the heap property protected void upheap (int j){ while (j>0){ //continue until reaching root (or break statement) int p = parent(j); if (compare(heap.get(j), heap.get(p)) >= 0) break; //heap property verified swap(j, p); j = p; //continue from the parent's location } } //Moves the entry at index j lower, if necessary, to restore the heap property protected void downheap (int j){ while (hasLeft(j)){ //continue to bottom (or break statement) int leftIndex = left(j); int smallChildIndex = leftIndex; //although right may be smaller if (hasRight(j)){ int rightIndex = right(j); if (compare(heap.get(leftIndex), heap.get(rightIndex)) > 0) smallChildIndex = rightIndex; //right child is smaller } if (compare(heap.get(smallChildIndex), heap.get(j)) >= 0) break; //heap property has been restored swap(j, smallChildIndex); j = smallChildIndex; //continue at position of the child } } //Returns the number of items in the priority queue public int size(){ return heap.size(); } //Returns (but does not remove) an entry with minimal key (if any) public Entry<K, V> min() { if (heap.isEmpty()) return null; return heap.get(0); } //Inserts a key-value pair and returns the entry created public Entry<K, V> insert(K key, V value) throws IllegalArgumentException { checkKey(key); //auxiliary key-checking method (could throw exception) Entry<K,V> newest = new PQEntry<>(key, value); heap.add(newest); //add to the end of the list upheap(heap.size()-1); //upheap newly added entry return newest; } //Removes and returns an entry with minimal key (if any) public Entry<K, V> removeMin() { if (heap.isEmpty()) { return null; } Entry<K,V> answer = heap.get(0); swap(0,heap.size()-1); heap.remove(heap.size()-1); downheap(0); return answer; } }
923a6cb8668d71a0995924bb0e53ca8cb6b5869d
2,735
java
Java
aliyun-java-sdk-cms/src/main/java/com/aliyuncs/cms/model/v20190101/PutExporterRuleRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
3
2020-04-26T09:15:45.000Z
2020-05-09T03:10:26.000Z
aliyun-java-sdk-cms/src/main/java/com/aliyuncs/cms/model/v20190101/PutExporterRuleRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
27
2021-06-11T21:08:40.000Z
2022-03-11T21:25:09.000Z
aliyun-java-sdk-cms/src/main/java/com/aliyuncs/cms/model/v20190101/PutExporterRuleRequest.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
1
2020-03-05T07:30:16.000Z
2020-03-05T07:30:16.000Z
23.177966
84
0.702011
999,204
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.cms.model.v20190101; import com.aliyuncs.RpcAcsRequest; import java.util.List; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class PutExporterRuleRequest extends RpcAcsRequest<PutExporterRuleResponse> { private String ruleName; private List<String> dstNamess; private String namespace; private String targetWindows; private String describe; private String metricName; public PutExporterRuleRequest() { super("Cms", "2019-01-01", "PutExporterRule", "cms"); setMethod(MethodType.POST); } public String getRuleName() { return this.ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; if(ruleName != null){ putQueryParameter("RuleName", ruleName); } } public List<String> getDstNamess() { return this.dstNamess; } public void setDstNamess(List<String> dstNamess) { this.dstNamess = dstNamess; if (dstNamess != null) { for (int i = 0; i < dstNamess.size(); i++) { putQueryParameter("DstNames." + (i + 1) , dstNamess.get(i)); } } } public String getNamespace() { return this.namespace; } public void setNamespace(String namespace) { this.namespace = namespace; if(namespace != null){ putQueryParameter("Namespace", namespace); } } public String getTargetWindows() { return this.targetWindows; } public void setTargetWindows(String targetWindows) { this.targetWindows = targetWindows; if(targetWindows != null){ putQueryParameter("TargetWindows", targetWindows); } } public String getDescribe() { return this.describe; } public void setDescribe(String describe) { this.describe = describe; if(describe != null){ putQueryParameter("Describe", describe); } } public String getMetricName() { return this.metricName; } public void setMetricName(String metricName) { this.metricName = metricName; if(metricName != null){ putQueryParameter("MetricName", metricName); } } @Override public Class<PutExporterRuleResponse> getResponseClass() { return PutExporterRuleResponse.class; } }
923a6cd5e7df97b28c74a5668808cdb749ede114
1,620
java
Java
src/main/java/org/liveontologies/puli/pinpointing/HashIdMap.java
liveontologies/proof-utils
9dce2a3427a10cbc410b8c47170a4e02bbf810cc
[ "Apache-2.0" ]
null
null
null
src/main/java/org/liveontologies/puli/pinpointing/HashIdMap.java
liveontologies/proof-utils
9dce2a3427a10cbc410b8c47170a4e02bbf810cc
[ "Apache-2.0" ]
2
2017-03-23T09:31:47.000Z
2017-06-26T12:04:32.000Z
src/main/java/org/liveontologies/puli/pinpointing/HashIdMap.java
liveontologies/proof-utils
9dce2a3427a10cbc410b8c47170a4e02bbf810cc
[ "Apache-2.0" ]
1
2017-03-20T13:50:46.000Z
2017-03-20T13:50:46.000Z
22.5
75
0.7
999,205
package org.liveontologies.puli.pinpointing; /*- * #%L * Proof Utility Library * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2014 - 2017 Live Ontologies Project * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class HashIdMap<E> implements IdMap<E> { BiMap<E, Integer> baseBiMap_; int nextId_ = 0; private HashIdMap() { baseBiMap_ = HashBiMap.create(); } private HashIdMap(int expectedSize) { baseBiMap_ = HashBiMap.create(expectedSize); } public static <E> IdMap<E> create() { return new HashIdMap<E>(); } public static <E> IdMap<E> create(int expectedSize) { return new HashIdMap<E>(expectedSize); } @Override public int getId(E element) { Integer result = baseBiMap_.get(element); if (result != null) { return result; } // else baseBiMap_.put(element, nextId_); return (nextId_++); } @Override public E getElement(int id) { return baseBiMap_.inverse().get(id); } @Override public Integer contains(Object o) { return baseBiMap_.get(o); } }
923a6def64b23382abbe7c7a2a3366a7fd0d24f0
3,908
java
Java
HW2/src/gui/controllers/RegisterProductController.java
keremgure/CS202
adb12bdbea16caeff6671c04ad57ab06fae3f2eb
[ "MIT" ]
null
null
null
HW2/src/gui/controllers/RegisterProductController.java
keremgure/CS202
adb12bdbea16caeff6671c04ad57ab06fae3f2eb
[ "MIT" ]
null
null
null
HW2/src/gui/controllers/RegisterProductController.java
keremgure/CS202
adb12bdbea16caeff6671c04ad57ab06fae3f2eb
[ "MIT" ]
null
null
null
42.945055
180
0.657369
999,206
package gui.controllers; import javafx.fxml.Initializable; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.util.Duration; import tray.animations.AnimationType; import tray.notification.NotificationType; import tray.notification.TrayNotification; import utilities.SQLUtilities; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.StringJoiner; public class RegisterProductController implements Initializable { public ComboBox registerPro_farmerCBox; public ComboBox registerPro_productCBox; public TextField registerPro_qtyField; public TextField registerPro_priceField; public TextField registerPro_ibanField; private ArrayList<Integer> fids; private ArrayList<Integer> pids; @Override public void initialize(URL location, ResourceBundle resources) { ResultSet farmers = SQLUtilities.getTable(SQLUtilities.TYPE_FARMER); fids = new ArrayList<>(); ResultSet products = SQLUtilities.getTable(SQLUtilities.TYPE_PRODUCT); pids = new ArrayList<>(); try{ while(farmers.next()){ registerPro_farmerCBox.getItems().add(farmers.getString("name") + " " + farmers.getString("last_name")); fids.add(farmers.getInt("fid")); } while (products.next()){ registerPro_productCBox.getItems().add(products.getString("name")); pids.add(products.getInt("pid")); } }catch (SQLException e){ e.printStackTrace(); System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.err.println("Error adding to cbox"); } } public void registerProductAction(){ int findex = registerPro_farmerCBox.getSelectionModel().getSelectedIndex(); int pindex = registerPro_productCBox.getSelectionModel().getSelectedIndex(); int fid = fids.get(findex); int pid = pids.get(pindex); double amount; double price; String iban; try { amount = Double.parseDouble(registerPro_qtyField.getText()); price = Double.parseDouble(registerPro_priceField.getText()); iban = registerPro_ibanField.getText(); if(registerPro_qtyField.getText().length() == 0 || registerPro_priceField.getText().length() == 0 || registerPro_ibanField.getText().length() == 0)throw new Exception(); } catch (Exception e) { ControllerHelper.notifyParseError(); return; } StringJoiner sj = new StringJoiner(","); sj.add(""+amount).add(""+price).add(iban); int status = SQLUtilities.addEntry(SQLUtilities.TYPE_REGISTERS,sj.toString(),fid,pid); if(status == 1){ TrayNotification success = new TrayNotification(); success.setTitle("Registered to Website Successfully."); success.setMessage("Registering:" + registerPro_farmerCBox.getValue() + ", " + registerPro_productCBox.getValue() + ", " + amount +", " + price + "TL is added to DB."); success.setNotificationType(NotificationType.SUCCESS); success.setAnimationType(AnimationType.FADE); success.showAndDismiss(Duration.seconds(4)); } else{ TrayNotification failed = new TrayNotification(); failed.setTitle("Failed registering to Website."); failed.setMessage("Register failed:" + registerPro_farmerCBox.getValue() + ", " + registerPro_productCBox.getValue() + ", " + amount +", " + price + "TL to DB."); failed.setNotificationType(NotificationType.ERROR); failed.setAnimationType(AnimationType.FADE); failed.showAndDismiss(Duration.seconds(4)); } } }
923a6f05512a29456302d3b50c8282039267da7c
23,804
java
Java
UnitConverter.java
leweyccac/cit111_ccaclewey
7e07f187095e683586c75ba28370c4d06217b138
[ "Apache-2.0" ]
null
null
null
UnitConverter.java
leweyccac/cit111_ccaclewey
7e07f187095e683586c75ba28370c4d06217b138
[ "Apache-2.0" ]
null
null
null
UnitConverter.java
leweyccac/cit111_ccaclewey
7e07f187095e683586c75ba28370c4d06217b138
[ "Apache-2.0" ]
null
null
null
44.081481
103
0.42455
999,207
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package week7; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * Unit converter. Chunk 2, mod 2, mini-project * @author lewey */ public class UnitConverter { public static void main(String [] boo){ // assign variable for radius of earth measured in km final double RADIUS_E = 6367.0; // assign variable for radius of Jupiter measured in km final double RADIUS_J = 71492.0; // assign variable for radius of the Galaxy measured in ly final double RADIUS_G = 8.75E4; // assign variable for height of the Galaxy measured in ly final double HEIGHT_G = 1000.0; // assign variable for radius of the observable Universe measured in ly final double RADIUS_U = 4.4E10; // assign variable for radius of a penny measured in micrometers final double RADIUS_P = 8750.0; // assign variable for height of a penny measured in micrometers final double HEIGHT_P = 2000.0; // assign variable for radius of a Tardigrade measured in micrometers final double RADIUS_T = 0.0000016; // assign variable for height of a Tardigrade measured in micrometers final double HEIGHT_T = 0.00000152; // assign boolean for main loop control boolean loop = true; // assign boolean for response loop control boolean loopSwitch1 = true; // create scanner for user input Scanner scan = new Scanner(System.in); // create a do block for loop return do{ // greet user System.out.println("3 choices for conversions."); // slow text speed for user try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Would you like to try the Earths to " + "Jupiter coversion? If so press 1 and press enter."); // slow text speed for user try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Would you like to try the Milky Way Galaxy " + "to the observable Universe coversion? If so press 2 " + "and press enter."); // slow text speed for user try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // prompt user for input System.out.println("Would you like to try the penny " + "to Tardigrades conversion? If so Press 3 and press " + "enter."); // create a do block for loop return do{ // assign an int for user response int response = scan.nextInt(); // create a switch block for multiple reponses switch (response){ // Earths to Jupiter conversion case 1: // greet user System.out.println("You've chosen the Earths to " + "Jupiter conversion."); // slow text speed for user try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // prompt user for input System.out.println("Please enter the amount of Earths " + "you'd like to put inside of Jupiter."); // assign a double for users response double earthsIn = scan.nextDouble(); // print to user their input System.out.println("You have requested " + earthsIn + " Earths."); // assign a double for the calculated Earth volume double returnedEarthsVol = earthVol(RADIUS_E); // assign a double for the calculated Jupiter volume double returnedJupiterVol = jupiterVol(RADIUS_J); // multiply earths volume by users input returnedEarthsVol = returnedEarthsVol * earthsIn; // calculate the result double conversionEJ = returnedEarthsVol / returnedJupiterVol; // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("There are " + conversionEJ + "" + " Jupiters to requested Earths."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("To put this into perspective, the " + "unit used to measure this volume was " + "kilometers."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // inform user of the calculated Jupiter Volume System.out.println("The volume for Jupiter came out" + " being " + returnedJupiterVol + " " + "kilometers cubed."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Have you heard of the big red spot" + " on Jupiter? If you haven't, it's a big " + "hurricane on Jupiter."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("When I say big, I actually mean" + " ginormous. It is big enough to hold an " + "Earth and some change."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Imagine getting stuck in that " + "storm!"); // set loop to false to prevent looping loopSwitch1 = false; break; // Galaxy to Universe conversion case 2: // greet user System.out.println("You've chosen the Milky Way Galaxy" + " to Observable Universe conversion."); // slow text speed for user try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // prompt user for input System.out.println("Please enter the amount of " + "Milky Way Galaxies you'd like to put in the " + "Universe."); // assign a double for users response double galaxysIn = scan.nextDouble(); // print to user their input System.out.println("You have requested " + galaxysIn + " Galaxies."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // assign a double to calculate the Galaxy's volume double returnedGalaxyVol = galaxyVol(RADIUS_G , HEIGHT_G); // assign a double to calculate the universes volume double returnedUniverseVol = universeVol(RADIUS_U); // multiply returnedGalaxyVol by uses response returnedGalaxyVol = returnedGalaxyVol * galaxysIn; // assign a double to calculate the results double conversionGU = returnedGalaxyVol / returnedUniverseVol; // print to user the conversion result System.out.println("There are " + conversionGU + " Universes to requested Galaxies."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("To put it into perspective, the " + "unit of length used for this was " + "light years."); // slow text speed for user try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("The actual Universe volume is " + "unknown due to the light not reaching " + "us yet,"); // print to user the Universes volume System.out.println("but this approximation came out " + "to being " + returnedUniverseVol + " light " + "years cubed."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("One light year is equivalent to " + "9.5E12 kilometers. Do you feel small yet?"); // set loop to false to prevent loop loopSwitch1 = false; break; // pennys to Tardigrades conversion case 3: System.out.println("You've chosen the pennies to " + "Tardigrades conversion."); // slow text speed for user try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Please enter amount of pennies " + "you'd like to put Tardigrades in."); // assign a double for users response double penniesIn = scan.nextDouble(); // print to user what they inputted System.out.println("You have requested " + penniesIn + " pennies."); // assign a double to calculate Tardigrade volume double returnedTardigradesVol = tardigradesVol (RADIUS_T , HEIGHT_T); // assign a double to calculte penny volume double returnedPennyVol = pennyVol(RADIUS_P , HEIGHT_P); // multiply penny volume by users input returnedPennyVol = penniesIn * returnedPennyVol; // assign double to calcutlate the result double conversionTP = returnedPennyVol/ returnedTardigradesVol; // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // print to user the result System.out.println("There are " + conversionTP + " " + "Taridigrades to requested pennies."); // slow text speed for user try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("Putting this into perspective," + " the unit of length used for this was " + "micrometers."); // slow text speed for user try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} System.out.println("The volume measured for the " + "Tardigrades is " + returnedTardigradesVol + " micrometers cubed."); System.out.println("One micrometer is equivalent to " + "1E-6 meter. These creatures are tiny and " + "can live in the vacuum of space!"); // set loop to false to prevent loop loopSwitch1 = false; break; // loop activator default: System.out.println("That wasn't an option. Please " + "enter a number between 1 and 3."); // set loop to true to loop back to choice selector loopSwitch1 = true; } // close switch block }while(loopSwitch1 == true); // slow text speed for user try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(UnitConverter.class.getName()).log (Level.SEVERE, null, ex);} // ask user if they'd like to continue System.out.println("Would you like to try another conversion? " + "Enter 1 for yes, any other number for no."); // assign int for response to loop or not int loopResponse = scan.nextInt(); // compare answer if(loopResponse == 1){ // set loop to true if chosen loop = true; }else{ // set loop to false if 1 is not chosen loop = !loop; // send user on their merry way System.out.println("Thanks for playing! I hope I put something " + "into perspective."); } // close if/else block } while(loop == true); // close do/while block }//close main method /** * Method earthVol contains variables for volume and returns the equation * once the method is called with 1 parameter. * @param r * @return compute earth volume */ public static double earthVol(double r){ // assign double for pi final double PI = 3.1416; // assign double for 4/3 final double FRACTION = 4/3; // assign double for equation double earthVol = FRACTION * PI * Math.pow(r, 3); // return the equation return earthVol; } // close earthVol method /** * Method jupiterVol contains variables for volume and returns the equation * once the method is called with 1 parameter. * @param r * @return compute Jupiter volume */ public static double jupiterVol(double r){ // assign double for pi final double PI = 3.1416; // assign double for 4/3 final double FRACTION = 4/3; // assign double for equation double jupiterVol = FRACTION * PI * Math.pow(r, 3); // return equation return jupiterVol; } // close jupiterVol method /** * Method galaxyVol contains variables for volume and returns the equation * once the method is called with 2 parameters. * @param r * @param h * @return compute Galaxy volume */ public static double galaxyVol(double r, double h){ // assign double for pi final double PI = 3.1416; // assign double for equation double galaxyVol = PI * Math.pow(r , 2) * h; // return equation return galaxyVol; } // close galaxyVol /** * Method universeVol contains variables for volume and returns the equation * once the method is called with 1 parameter. * @param r * @return compute Universe volume */ public static double universeVol(double r){ // assign double for pi final double PI = 3.1416; // assign double for 4/3 final double FRACTION = 4/3; // assign double for equation double universeVol = FRACTION * PI * Math.pow(r , 3); // return equation return universeVol; } // close universeVol method /** * Method tardigradesVol contains variables for volume and returns the * equation once the method is called with 2 parameters. * @param r * @param h * @return computed Tardigrades volume */ public static double tardigradesVol(double r, double h){ // assign double for pi final double PI = 3.1416; // assign double for equation double tardigradesVol = PI * Math.pow(r , 2) * h; // return equation return tardigradesVol; } // close tardigradeVol method /** * Method pennyVol contains variables for volume and returns the equation * once the method is called with 2 parameters. * @param r * @param h * @return computed penny volume */ public static double pennyVol(double r , double h){ // assign double for pi final double PI = 3.1416; // assign double for equation double pennyVol = PI * Math.pow(r , 2) * h; // return equation return pennyVol; } // close pennyVol method } // close class UnitConverter
923a6f2046f013cd831139723a96c19c165529d7
12,351
java
Java
src/main/java/io/github/wufei/parse/XmlAsmConfigParser.java
wufei-limit/rebo-asm
99c044d9ecc9c6be7ee0e075a30f87e0d68327ea
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/wufei/parse/XmlAsmConfigParser.java
wufei-limit/rebo-asm
99c044d9ecc9c6be7ee0e075a30f87e0d68327ea
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/wufei/parse/XmlAsmConfigParser.java
wufei-limit/rebo-asm
99c044d9ecc9c6be7ee0e075a30f87e0d68327ea
[ "Apache-2.0" ]
1
2021-11-25T02:47:45.000Z
2021-11-25T02:47:45.000Z
43.797872
115
0.636305
999,208
package io.github.wufei.parse; import org.gradle.api.logging.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jetbrains.annotations.NotNull; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import io.github.wufei.config.AsmConfig; import io.github.wufei.config.ReplaceClassInvokeConfig; import io.github.wufei.config.ReplaceMethodCodeConfig; import io.github.wufei.config.ReplaceMethodInvokeConfig; import io.github.wufei.config.ReplaceSuperClassConfig; import io.github.wufei.config.TryCatchMethodConfig; public class XmlAsmConfigParser implements AsmConfigParser { private final Logger logger; public XmlAsmConfigParser(Logger logger) { this.logger = logger; } @Override @NotNull public AsmConfig parseAsmConfig(File asmConfigFile) throws IOException { AsmConfig result = new AsmConfig(); if (asmConfigFile.exists() && asmConfigFile.isFile()) { try { result.setReplaceMethodCodeConfig(parseReplaceMethodCode(asmConfigFile)); result.setReplaceMethodInvokeConfigs(parseReplaceMethodInvoke(asmConfigFile)); result.setSkipClassName(parseSkipClassName(asmConfigFile)); result.setTryCatchMethodConfigs(parseTryCatchMethod(asmConfigFile)); result.setReplaceClassInvokeConfigs(parseReplaceClassInvoke(asmConfigFile)); result.setReplaceSuperClassConfigs(parseReplaceSuperClass(asmConfigFile)); } catch (IOException | JDOMException e) { throw new IOException("RoboAsmConfig.xml parse error", e); } } else { logger.info("RoboAsmConfig.xml no exists, path=" + asmConfigFile.getAbsolutePath()); } return result; } private List<ReplaceSuperClassConfig> parseReplaceSuperClass(File file) throws IOException, JDOMException { List<ReplaceSuperClassConfig> replaceSuperClassConfigs = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(file)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("ReplaceSuperClass").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getChildText("superClassName"); String replaceClassName = hook.getChildText("replaceSuperClassName"); List<String> skipClasses = new ArrayList<>(); skipClasses.add(replaceClassName); String skipClass = hook.getChildText("skipClassName"); if (skipClass != null && !"".equals(skipClass)) { if (skipClass.contains("#")) { skipClasses = Arrays.asList(skipClass.trim().split("#")); } else { skipClasses.add(skipClass); } } ReplaceSuperClassConfig r = new ReplaceSuperClassConfig(className, replaceClassName, skipClasses); replaceSuperClassConfigs.add(r); } return replaceSuperClassConfigs; } private List<ReplaceClassInvokeConfig> parseReplaceClassInvoke(File file) throws IOException, JDOMException { List<ReplaceClassInvokeConfig> replaceClassInvokeConfigs = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(file)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("ReplaceClassInvoke").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getChildText("className"); String replaceClassName = hook.getChildText("replaceClassName"); List<String> skipClasses = new ArrayList<>(); skipClasses.add(className); skipClasses.add(replaceClassName); String skipClass = hook.getChildText("skipClassName"); if (skipClass != null && !"".equals(skipClass)) { if (skipClass.contains("#")) { skipClasses = Arrays.asList(skipClass.trim().split("#")); } else { skipClasses.add(skipClass); } } ReplaceClassInvokeConfig r = new ReplaceClassInvokeConfig(className, replaceClassName, skipClasses); replaceClassInvokeConfigs.add(r); } return replaceClassInvokeConfigs; } private List<TryCatchMethodConfig> parseTryCatchMethod(File file) throws IOException, JDOMException { List<TryCatchMethodConfig> tryCatchMethodConfigs = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(file)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("TryCatchMethod").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getChildText("className"); String methodName = hook.getChildText("methodName"); String methodDescriptor = hook.getChildText("methodDescriptor"); String throwClassName = hook.getChildText("throwClassName"); String throwMethodName = hook.getChildText("throwMethodName"); if (throwMethodName == null || throwMethodName.equals("null")) { throwMethodName = methodName; } String throwMethodDescriptor = hook.getChildText("throwMethodDescriptor"); if (throwMethodDescriptor == null || throwMethodDescriptor.equals("null")) { throwMethodDescriptor = methodDescriptor; } TryCatchMethodConfig tryCatchMethodConfig = new TryCatchMethodConfig( className, methodName, methodDescriptor, throwClassName, throwMethodName, throwMethodDescriptor); tryCatchMethodConfigs.add(tryCatchMethodConfig); } return tryCatchMethodConfigs; } public List<String> parseSkipClassName(File asmConfigFile) throws IOException, JDOMException { List<String> result = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(asmConfigFile)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("SkipClass").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getText().replace(".class", "") .replace(".java", "") .replace(".", "/").trim(); result.add(className); } return result; } private List<ReplaceMethodInvokeConfig> parseReplaceMethodInvoke(File file) throws IOException, JDOMException { List<ReplaceMethodInvokeConfig> replaceMethodInvokeConfigs = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(file)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("ReplaceMethodInvoke").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getChildText("className"); if (className == null || className.equals("null")) { className = ""; } String methodName = hook.getChildText("methodName"); String methodDescriptor = hook.getChildText("methodDescriptor"); String replaceClassName = hook.getChildText("replaceClassName"); String replaceMethodName = hook.getChildText("replaceMethodName"); if (replaceMethodName == null || replaceMethodName.equals("null")) { replaceMethodName = methodName; } String replaceMethodDescriptor = hook.getChildText("replaceMethodDescriptor"); if (replaceMethodDescriptor == null) { replaceMethodDescriptor = methodDescriptor; } List<String> skipClasses = new ArrayList<>(); skipClasses.add(replaceClassName); String skipClass = hook.getChildText("skipClassName"); if (skipClass != null && !"".equals(skipClass)) { if (skipClass.contains("#")) { skipClasses = Arrays.asList(skipClass.trim().split("#")); } else { skipClasses.add(skipClass); } } List<String> excludeOwners = new ArrayList<>(); if (className.isEmpty()) { String excludeOwner = hook.getChildText("excludeClassName"); if (excludeOwner != null && !"".equals(excludeOwner)) { if (excludeOwner.contains("#")) { excludeOwners = Arrays.asList(excludeOwner.trim().split("#")); } else { excludeOwners.add(excludeOwner); } } } ReplaceMethodInvokeConfig r = new ReplaceMethodInvokeConfig(className, methodName, methodDescriptor, skipClasses, excludeOwners, replaceClassName, replaceMethodName, replaceMethodDescriptor); replaceMethodInvokeConfigs.add(r); } return replaceMethodInvokeConfigs; } private List<ReplaceMethodCodeConfig> parseReplaceMethodCode(File file) throws IOException, JDOMException { List<ReplaceMethodCodeConfig> replaceMethodCodeConfigs = new ArrayList<>(); SAXBuilder builder = new SAXBuilder(); InputStream inputStream = removeBOM(new FileInputStream(file)); Document document = builder.build(inputStream, "UTF-8"); Element root = document.getRootElement(); for (Iterator<Element> it = root.getChildren("ReplaceMethodCode").listIterator(); it.hasNext(); ) { Element hook = it.next(); String className = hook.getChildText("className"); String methodName = hook.getChildText("methodName"); String methodDescriptor = hook.getChildText("methodDescriptor"); String isInterrupt = hook.getChildText("interrupt"); boolean interrupt = isInterrupt == null || isInterrupt.equals("null") || isInterrupt.equals("true"); String replaceClassName = hook.getChildText("replaceClassName"); String replaceMethodMethodName = hook.getChildText("replaceMethodName"); if (replaceMethodMethodName == null || replaceMethodMethodName.equals("null")) { replaceMethodMethodName = methodName; } String replaceMethodDescriptor = hook.getChildText("replaceMethodDescriptor"); if (replaceMethodDescriptor == null || replaceMethodDescriptor.equals("null")) { replaceMethodDescriptor = methodDescriptor; } ReplaceMethodCodeConfig replaceMethodCodeConfig = new ReplaceMethodCodeConfig( className, methodName, methodDescriptor, interrupt, replaceClassName, replaceMethodMethodName, replaceMethodDescriptor); replaceMethodCodeConfigs.add(replaceMethodCodeConfig); } return replaceMethodCodeConfigs; } private InputStream removeBOM(InputStream in) throws IOException { PushbackInputStream testin = new PushbackInputStream(in); int ch = testin.read(); if (ch != 0xEF) { testin.unread(ch); } else if ((ch = testin.read()) != 0xBB) { testin.unread(ch); testin.unread(0xef); } else if ((ch = testin.read()) != 0xBF) { throw new IOException("错误的UTF-8格式文件"); } return testin; } }
923a70052a849b8d5ed29d1a612f7af2d015cf0a
662
java
Java
goci-core/goci-repository/src/main/java/uk/ac/ebi/spot/goci/repository/PlatformRepository.java
markxiaotao/goci
5246e56df1d02fd42453345424ece24f532ca0a4
[ "Apache-2.0" ]
23
2015-03-30T15:23:32.000Z
2022-03-22T18:17:07.000Z
goci-core/goci-repository/src/main/java/uk/ac/ebi/spot/goci/repository/PlatformRepository.java
markxiaotao/goci
5246e56df1d02fd42453345424ece24f532ca0a4
[ "Apache-2.0" ]
549
2015-02-23T15:54:21.000Z
2022-03-31T11:43:49.000Z
goci-core/goci-repository/src/main/java/uk/ac/ebi/spot/goci/repository/PlatformRepository.java
markxiaotao/goci
5246e56df1d02fd42453345424ece24f532ca0a4
[ "Apache-2.0" ]
19
2015-02-23T15:21:05.000Z
2022-01-10T16:08:57.000Z
26.48
132
0.803625
999,209
package uk.ac.ebi.spot.goci.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import uk.ac.ebi.spot.goci.model.Platform; import java.util.List; /** * Created by dwelter on 10/03/16. */ @RepositoryRestResource public interface PlatformRepository extends JpaRepository<Platform, Long>{ Platform findByManufacturer(String manufacturer); // List<Platform> findByStudyId(Long studyId); List<Platform> findByStudiesIdAndStudiesHousekeepingCatalogPublishDateIsNotNullAndStudiesHousekeepingCatalogUnpublishDateIsNull( Long studyId); }
923a707cefadc53f3493d13026f22dbc7f33cd25
659
java
Java
sandbox/src/main/java/my/lux/brand/sandbox/Equation.java
RS1987/java_pft
c8bf764cc7816d4d245ed5dd29cae80c08a4b45b
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/my/lux/brand/sandbox/Equation.java
RS1987/java_pft
c8bf764cc7816d4d245ed5dd29cae80c08a4b45b
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/my/lux/brand/sandbox/Equation.java
RS1987/java_pft
c8bf764cc7816d4d245ed5dd29cae80c08a4b45b
[ "Apache-2.0" ]
null
null
null
14.326087
50
0.394537
999,210
package my.lux.brand.sandbox; /** * Created by Alex on 3/6/2016. */ public class Equation { private double a; private double b; private double c; private int n; public Equation(double a, double b, double c) { this.a = a; this.b = b; this.c = c; double d = b*b - 4*a*c; if (a != 0) { if(d > 0) { n = 2; } else if(d == 0) { n = 1; } else { n = 0; } } else if (b != 0) { n = 1; } else if(c != 0) { n = 0; } else { n = -1; } } public int rootNumber() { return n; } }
923a70c78e7fba0ce005e3f683019098967fc82c
6,434
java
Java
java/src/org/nachodb/GenericIndex.java
kjk/volante-obsolete
b01cef957ebfccae093b5812e081e6cb74ccd824
[ "MIT-0" ]
4
2015-11-05T17:49:08.000Z
2021-08-11T22:54:18.000Z
java/src/org/nachodb/GenericIndex.java
kjk/volante-obsolete
b01cef957ebfccae093b5812e081e6cb74ccd824
[ "MIT-0" ]
null
null
null
java/src/org/nachodb/GenericIndex.java
kjk/volante-obsolete
b01cef957ebfccae093b5812e081e6cb74ccd824
[ "MIT-0" ]
4
2016-01-26T12:15:35.000Z
2021-08-11T22:54:20.000Z
42.893333
100
0.660242
999,211
package org.nachodb; import java.util.*; /** * Interface of object index. * This is base interface for Index and FieldIndex, allowing to write generic algorithms * working with both itype of indices. */ public interface GenericIndex extends IPersistent, IResource { /** * Get object by key (exact match) * @param key specified key. It should match with type of the index and should be inclusive. * @return object with this value of the key or <code>null</code> if key not found * @exception StorageError(StorageError.KEY_NOT_UNIQUE) exception if there are more than * one objects in the index with specified value of the key. */ public IPersistent get(Key key); /** * Get objects which key value belongs to the specified range. * Either from boundary, either till boundary either both of them can be <code>null</code>. * In last case the method returns all objects from the index. * @param from low boundary. If <code>null</code> then low boundary is not specified. * Low boundary can be inclusive or exclusive. * @param till high boundary. If <code>null</code> then high boundary is not specified. * High boundary can be inclusive or exclusive. * @return array of objects which keys belongs to the specified interval, ordered by key value */ public IPersistent[] get(Key from, Key till); /** * Get object by string key (exact match) * @param key string key * @return object with this value of the key or <code>null</code> if key not[ found * @exception StorageError(StorageError.KEY_NOT_UNIQUE) exception if there are more than * one objects in the index with specified value of the key. */ public IPersistent get(String key); /** * Get objects with string key prefix * @param prefix string key prefix * @return array of objects which key starts with this prefix */ public IPersistent[] getPrefix(String prefix); /** * Locate all objects which key is prefix of specified word. * @param word string which prefixes are located in index * @return array of objects which key is prefix of specified word, ordered by key value */ public IPersistent[] prefixSearch(String word); /** * Get number of objects in the index * @return number of objects in the index */ public int size(); /** * Remove all objects from the index */ public void clear(); /** * Get all objects in the index as array ordered by index key. * @return array of objects in the index ordered by key value */ public IPersistent[] toPersistentArray(); /** * Get all objects in the index as array ordered by index key. * The runtime type of the returned array is that of the specified array. * If the index fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this index.<p> * * If this index fits in the specified array with room to spare * (i.e., the array has more elements than this index), the element * in the array immediately following the end of the index is set to * <tt>null</tt>. This is useful in determining the length of this * index <i>only</i> if the caller knows that this index does * not contain any <tt>null</tt> elements.)<p> * @param arr specified array * @return array of all objects in the index */ public IPersistent[] toPersistentArray(IPersistent[] arr); /** * Get iterator for traversing all objects in the index. * Objects are iterated in the ascent key order. * You should not update/remove or add members to the index during iteration * @return index iterator */ public Iterator iterator(); /** * Get iterator for traversing all entries in the index. * Iterator next() method returns object implementing <code>Map.Entry</code> interface * which allows to get entry key and value. * Objects are iterated in the ascent key order. * You should not update/remove or add members to the index during iteration * @return index iterator */ public Iterator entryIterator(); static final int ASCENT_ORDER = 0; static final int DESCENT_ORDER = 1; /** * Get iterator for traversing objects in the index with key belonging to the specified range. * You should not update/remove or add members to the index during iteration * @param from low boundary. If <code>null</code> then low boundary is not specified. * Low boundary can be inclusive or exclusive. * @param till high boundary. If <code>null</code> then high boundary is not specified. * High boundary can be inclusive or exclusive. * @param order <code>ASCENT_ORDER</code> or <code>DESCENT_ORDER</code> * @return selection iterator */ public Iterator iterator(Key from, Key till, int order); /** * Get iterator for traversing index entries with key belonging to the specified range. * Iterator next() method returns object implementing <code>Map.Entry</code> interface * You should not update/remove or add members to the index during iteration * @param from low boundary. If <code>null</code> then low boundary is not specified. * Low boundary can be inclusive or exclusive. * @param till high boundary. If <code>null</code> then high boundary is not specified. * High boundary can be inclusive or exclusive. * @param order <code>ASCENT_ORDER</code> or <code>DESCENT_ORDER</code> * @return selection iterator */ public Iterator entryIterator(Key from, Key till, int order); /** * Get iterator for records which keys started with specified prefix * Objects are iterated in the ascent key order. * You should not update/remove or add members to the index during iteration * @param prefix key prefix * @return selection iterator */ public Iterator prefixIterator(String prefix); /** * Get type of index key * @return type of index key */ public Class getKeyType(); }
923a72d7d98b13f5a020d0b57db6a4772bd57b7a
2,355
java
Java
JCL_Android/app/src/main/java/org/jf/dexlib2/immutable/value/ImmutableIntEncodedValue.java
JavaCaeLa/JCL
7c6d8b54b63a83e58928a4f12f08f4be01b3a001
[ "Apache-2.0" ]
7
2017-05-16T18:42:00.000Z
2021-03-19T17:15:37.000Z
JCL_Android/app/src/main/java/org/jf/dexlib2/immutable/value/ImmutableIntEncodedValue.java
JavaCaeLa/JCL
7c6d8b54b63a83e58928a4f12f08f4be01b3a001
[ "Apache-2.0" ]
41
2017-04-17T22:32:04.000Z
2018-08-30T20:33:46.000Z
JCL_Android/app/src/main/java/org/jf/dexlib2/immutable/value/ImmutableIntEncodedValue.java
AndreJCL/JCL
7c6d8b54b63a83e58928a4f12f08f4be01b3a001
[ "Apache-2.0" ]
4
2017-09-04T18:53:23.000Z
2018-08-22T13:11:35.000Z
43.611111
100
0.763482
999,212
/* * Copyright 2012, Google Inc. * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.immutable.value; import org.jf.dexlib2.base.value.BaseIntEncodedValue; import org.jf.dexlib2.iface.value.IntEncodedValue; public class ImmutableIntEncodedValue extends BaseIntEncodedValue implements ImmutableEncodedValue { private static final long serialVersionUID = 4214155978478410287L; protected final int value; public ImmutableIntEncodedValue(int value) { this.value = value; } public static ImmutableIntEncodedValue of(IntEncodedValue intEncodedValue) { if (intEncodedValue instanceof ImmutableIntEncodedValue) { return (ImmutableIntEncodedValue)intEncodedValue; } return new ImmutableIntEncodedValue(intEncodedValue.getValue()); } @Override public int getValue() { return value; } }
923a72f40291560fe33036bbe227957c0c9dc017
7,744
java
Java
AtiwWatch - core/console/com/strongjoshua/console/AbstractConsole.java
joham97/AtiwWatch
310663ceafcc393f3b7dd21f2e646fd65e91e2d1
[ "Apache-2.0" ]
null
null
null
AtiwWatch - core/console/com/strongjoshua/console/AbstractConsole.java
joham97/AtiwWatch
310663ceafcc393f3b7dd21f2e646fd65e91e2d1
[ "Apache-2.0" ]
null
null
null
AtiwWatch - core/console/com/strongjoshua/console/AbstractConsole.java
joham97/AtiwWatch
310663ceafcc393f3b7dd21f2e646fd65e91e2d1
[ "Apache-2.0" ]
null
null
null
25.142857
109
0.647856
999,213
/** * */ package com.strongjoshua.console; import java.io.PrintWriter; import java.io.StringWriter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Method; import com.badlogic.gdx.utils.reflect.ReflectionException; /** @author Eric */ public abstract class AbstractConsole implements Console, Disposable { protected CommandExecutor exec; protected final Log log; protected boolean logToSystem; protected boolean disabled; protected boolean executeHiddenCommands = true; protected boolean displayHiddenCommands = false; protected boolean consoleTrace = false; public AbstractConsole () { log = new Log(); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#setLoggingToSystem(java.lang.Boolean) */ @Override public void setLoggingToSystem (Boolean log) { this.logToSystem = log; } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#log(java.lang.String, com.strongjoshua.console.GUIConsole.LogLevel) */ @Override public void log (String msg, LogLevel level) { log.addEntry(msg, level); if (logToSystem) { switch (level) { case ERROR: System.err.println("> " + msg); break; default: System.out.println("> " + msg); break; } } } public void log (String msg, Color color) { log.addEntry(msg, color); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#log(java.lang.String) */ @Override public void log (String msg) { this.log(msg, LogLevel.DEFAULT); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#printLogToFile(java.lang.String) */ @Override public void printLogToFile (String file) { this.printLogToFile(Gdx.files.local(file)); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#printLogToFile(com.badlogic.gdx.files.FileHandle) */ @Override public void printLogToFile (FileHandle fh) { if (log.printToFile(fh)) { log("Successfully wrote logs to file.", LogLevel.SUCCESS); } else { log("Unable to write logs to file.", LogLevel.ERROR); } } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#isDisabled() */ @Override public boolean isDisabled () { return disabled; } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#setDisabled(boolean) */ @Override public void setDisabled (boolean disabled) { this.disabled = disabled; } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#setCommandExecutor(com.strongjoshua.console.CommandExecutor) */ @Override public void setCommandExecutor (CommandExecutor commandExec) { exec = commandExec; exec.setConsole(this); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#execCommand(java.lang.String) */ @Override public void execCommand (String command) { if (disabled) return; if(command.charAt(0) != '/'){ exec.defaultCommand(command); return; }else{ command = command.substring(1, command.length()); } log(command, LogLevel.COMMAND); String[] parts = command.split(" "); String methodName = parts[0]; String[] sArgs = null; if (parts.length > 1) { sArgs = new String[parts.length - 1]; for (int i = 1; i < parts.length; i++) { sArgs[i - 1] = parts[i]; } } Class<? extends CommandExecutor> clazz = exec.getClass(); Method[] methods = ClassReflection.getMethods(clazz); Array<Integer> possible = new Array<Integer>(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equalsIgnoreCase(methodName) && ConsoleUtils.canExecuteCommand(this, method)) { possible.add(i); } } if (possible.size <= 0) { log("No such method found.", LogLevel.ERROR); return; } int size = possible.size; int numArgs = sArgs == null ? 0 : sArgs.length; for (int i = 0; i < size; i++) { Method m = methods[possible.get(i)]; Class<?>[] params = m.getParameterTypes(); if (numArgs == params.length) { try { Object[] args = null; try { if (sArgs != null) { args = new Object[numArgs]; for (int j = 0; j < params.length; j++) { Class<?> param = params[j]; final String value = sArgs[j]; if (param.equals(String.class)) { args[j] = value; } else if (param.equals(Boolean.class) || param.equals(boolean.class)) { args[j] = Boolean.parseBoolean(value); } else if (param.equals(Byte.class) || param.equals(byte.class)) { args[j] = Byte.parseByte(value); } else if (param.equals(Short.class) || param.equals(short.class)) { args[j] = Short.parseShort(value); } else if (param.equals(Integer.class) || param.equals(int.class)) { args[j] = Integer.parseInt(value); } else if (param.equals(Long.class) || param.equals(long.class)) { args[j] = Long.parseLong(value); } else if (param.equals(Float.class) || param.equals(float.class)) { args[j] = Float.parseFloat(value); } else if (param.equals(Double.class) || param.equals(double.class)) { args[j] = Double.parseDouble(value); } } } } catch (Exception e) { // Error occurred trying to parse parameter, continue to next function continue; } m.setAccessible(true); m.invoke(exec, args); return; } catch (ReflectionException e) { String msg = e.getMessage(); if (msg == null || msg.length() <= 0 || msg.equals("")) { msg = "Unknown Error"; e.printStackTrace(); } log(msg, LogLevel.ERROR); if (consoleTrace) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log(sw.toString(), LogLevel.ERROR); } return; } } } log("Bad parameters. Check your code.", LogLevel.ERROR); } @Override public void printCommands () { Method[] pMethods = ClassReflection.getDeclaredMethods(exec.getClass().getSuperclass()); Method[] mMethods = ClassReflection.getDeclaredMethods(exec.getClass()); Method[] methods = new Method[pMethods.length + mMethods.length]; for (int i = 0; i < pMethods.length; i++) methods[i] = pMethods[i]; for (int i = 0; i < mMethods.length; i++) methods[i + pMethods.length] = mMethods[i]; for (int j = 0; j < methods.length; j++) { Method m = methods[j]; if (m.isPublic() && ConsoleUtils.canDisplayCommand(this, m) && !m.getName().equals("defaultCommand")) { String s = "/"; s += m.getName(); s += " : "; Class<?>[] params = m.getParameterTypes(); for (int i = 0; i < params.length; i++) { s += params[i].getSimpleName(); if (i < params.length - 1) { s += ", "; } } log(s); } } log("Befehle ohne / werden per Chat versendet"); } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#setExecuteHiddenCommands(boolean) */ @Override public void setExecuteHiddenCommands (boolean enabled) { executeHiddenCommands = enabled; } @Override public boolean isExecuteHiddenCommandsEnabled () { return executeHiddenCommands; } /* * (non-Javadoc) * * @see com.strongjoshua.console.Console#setDisplayHiddenCommands(boolean) */ @Override public void setDisplayHiddenCommands (boolean enabled) { displayHiddenCommands = enabled; } @Override public boolean isDisplayHiddenCommandsEnabled () { return displayHiddenCommands; } @Override public void setConsoleStackTrace (boolean enabled) { this.consoleTrace = enabled; } }
923a74a79f8e03618a1c767c7477f4fa6b6a6043
252
java
Java
iotsys-obix/src/obix/units/Hectopascal.java
mjung85/iotsys
c50d6f61d7d2c41ad26c03bf4f565b0c8f1be853
[ "BSD-3-Clause" ]
32
2016-03-24T06:22:03.000Z
2021-12-28T00:07:34.000Z
iotsys-obix/src/obix/units/Hectopascal.java
mjung85/iotsys
c50d6f61d7d2c41ad26c03bf4f565b0c8f1be853
[ "BSD-3-Clause" ]
5
2015-08-09T08:35:53.000Z
2019-06-13T16:38:42.000Z
iotsys-obix/src/obix/units/Hectopascal.java
mjung85/iotsys
c50d6f61d7d2c41ad26c03bf4f565b0c8f1be853
[ "BSD-3-Clause" ]
16
2016-03-09T18:06:54.000Z
2021-07-20T03:09:06.000Z
21
66
0.68254
999,214
package obix.units; import obix.contracts.impl.DimensionImpl; import obix.contracts.impl.UnitImpl; public class Hectopascal extends UnitImpl { public Hectopascal() { super("hPa", 100, 0, new DimensionImpl(1, -1, -2, 0, 0, 0, 0)); } }
923a74f44caff83210302eef74a3642ed881f621
842
java
Java
module/JepRiaShowcase/App/gwt/src/java/com/technology/jep/jepriashowcase/goods/shared/service/GoodsService.java
Dobrynin91/jepria-showcase
166c52cb2adcc2b8ae4e9bcde78713f027b50744
[ "Apache-2.0" ]
null
null
null
module/JepRiaShowcase/App/gwt/src/java/com/technology/jep/jepriashowcase/goods/shared/service/GoodsService.java
Dobrynin91/jepria-showcase
166c52cb2adcc2b8ae4e9bcde78713f027b50744
[ "Apache-2.0" ]
null
null
null
module/JepRiaShowcase/App/gwt/src/java/com/technology/jep/jepriashowcase/goods/shared/service/GoodsService.java
Dobrynin91/jepria-showcase
166c52cb2adcc2b8ae4e9bcde78713f027b50744
[ "Apache-2.0" ]
null
null
null
46.777778
109
0.84323
999,215
package com.technology.jep.jepriashowcase.goods.shared.service; import java.util.List; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.technology.jep.jepria.shared.exceptions.ApplicationException; import com.technology.jep.jepria.shared.field.option.JepOption; import com.technology.jep.jepria.shared.service.data.JepDataService; @RemoteServiceRelativePath("ProtectedServices/GoodsService") public interface GoodsService extends JepDataService { List<JepOption> getGoodsType() throws ApplicationException; List<JepOption> getUnit() throws ApplicationException; List<JepOption> getMotivationType() throws ApplicationException; List<JepOption> getGoodsCatalog(Integer parentGoodsCatalogId, Integer goodsId) throws ApplicationException; List<JepOption> getGoodsSegment() throws ApplicationException; }
923a7661fb07197c1fb359c1e20160e0d40d9781
1,203
java
Java
api-model/src/main/java/io/enmasse/iot/model/v1/DeviceConnectionServiceConfig.java
dlabaj/enmasse
663a0461dbece6c56cc329a5f89e5d959835078d
[ "Apache-2.0" ]
1
2020-07-09T12:07:51.000Z
2020-07-09T12:07:51.000Z
api-model/src/main/java/io/enmasse/iot/model/v1/DeviceConnectionServiceConfig.java
dlabaj/enmasse
663a0461dbece6c56cc329a5f89e5d959835078d
[ "Apache-2.0" ]
1
2019-11-27T14:38:41.000Z
2019-11-27T14:45:31.000Z
api-model/src/main/java/io/enmasse/iot/model/v1/DeviceConnectionServiceConfig.java
dlabaj/enmasse
663a0461dbece6c56cc329a5f89e5d959835078d
[ "Apache-2.0" ]
null
null
null
26.733333
101
0.693267
999,216
/* * Copyright 2020, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.iot.model.v1; import com.fasterxml.jackson.annotation.JsonInclude; import io.fabric8.kubernetes.api.model.Doneable; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.Inline; @Buildable( editableEnabled = false, generateBuilderPackage = false, builderPackage = "io.fabric8.kubernetes.api.builder", inline = @Inline( type = Doneable.class, prefix = "Doneable", value = "done")) @JsonInclude(JsonInclude.Include.NON_NULL) public class DeviceConnectionServiceConfig { private InfinispanDeviceConnection infinispan; private JdbcDeviceConnection jdbc; public InfinispanDeviceConnection getInfinispan() { return infinispan; } public void setInfinispan(InfinispanDeviceConnection infinispan) { this.infinispan = infinispan; } public JdbcDeviceConnection getJdbc() { return jdbc; } public void setJdbc(JdbcDeviceConnection jdbc) { this.jdbc = jdbc; } }
923a76ab95fa6ca08f1eba8ed7621e90d26fce43
2,855
java
Java
client/src/test/java/com/alibaba/nacos/client/naming/beat/BeatInfoTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
23,439
2018-06-15T07:02:07.000Z
2022-03-31T14:18:55.000Z
client/src/test/java/com/alibaba/nacos/client/naming/beat/BeatInfoTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
6,521
2018-07-22T15:40:04.000Z
2022-03-31T16:00:33.000Z
client/src/test/java/com/alibaba/nacos/client/naming/beat/BeatInfoTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
10,494
2018-07-20T16:37:36.000Z
2022-03-31T12:49:44.000Z
32.078652
104
0.615061
999,217
/* * * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.alibaba.nacos.client.naming.beat; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class BeatInfoTest { @Test public void testGetterAndSetter() { BeatInfo info = new BeatInfo(); String ip = "1.1.1.1"; info.setIp(ip); int port = 10000; info.setPort(port); double weight = 1.0; info.setWeight(weight); String serviceName = "serviceName"; info.setServiceName(serviceName); String cluster = "cluster1"; info.setCluster(cluster); Map<String, String> meta = new HashMap<>(); meta.put("a", "b"); info.setMetadata(meta); long period = 100; info.setPeriod(period); info.setScheduled(true); info.setStopped(true); Assert.assertEquals(ip, info.getIp()); Assert.assertEquals(port, info.getPort()); Assert.assertEquals(weight, info.getWeight(), 0.1); Assert.assertEquals(serviceName, info.getServiceName()); Assert.assertEquals(meta, info.getMetadata()); Assert.assertEquals(period, info.getPeriod()); Assert.assertTrue(info.isScheduled()); Assert.assertTrue(info.isStopped()); } @Test public void testToString() { BeatInfo info = new BeatInfo(); String ip = "1.1.1.1"; info.setIp(ip); int port = 10000; info.setPort(port); double weight = 1.0; info.setWeight(weight); String serviceName = "serviceName"; info.setServiceName(serviceName); String cluster = "cluster1"; info.setCluster(cluster); Map<String, String> meta = new HashMap<>(); meta.put("a", "b"); info.setMetadata(meta); long period = 100; info.setPeriod(period); info.setScheduled(true); info.setStopped(true); String expect = "BeatInfo{port=10000, ip='1.1.1.1', " + "weight=1.0, serviceName='serviceName'," + " cluster='cluster1', metadata={a=b}," + " scheduled=true, period=100, stopped=true}"; Assert.assertEquals(expect, info.toString()); } }
923a77ac43366687e83bd5f8d938ef70742e85d0
694
java
Java
swords-inventory/src/main/java/com/morethanheroic/swords/inventory/service/InventoryFacade.java
daggers-and-sorcery/daggers-and-sorcery-backend
96ea5919e6becf5c7cdb888fb2ec1eafba2b0aac
[ "MIT" ]
null
null
null
swords-inventory/src/main/java/com/morethanheroic/swords/inventory/service/InventoryFacade.java
daggers-and-sorcery/daggers-and-sorcery-backend
96ea5919e6becf5c7cdb888fb2ec1eafba2b0aac
[ "MIT" ]
null
null
null
swords-inventory/src/main/java/com/morethanheroic/swords/inventory/service/InventoryFacade.java
daggers-and-sorcery/daggers-and-sorcery-backend
96ea5919e6becf5c7cdb888fb2ec1eafba2b0aac
[ "MIT" ]
null
null
null
27.76
77
0.773775
999,218
package com.morethanheroic.swords.inventory.service; import com.morethanheroic.swords.inventory.domain.InventoryEntity; import com.morethanheroic.swords.user.domain.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @deprecated Don't use this class. */ @Service public class InventoryFacade { @Autowired private InventoryEntityFactory inventoryEntityFactory; /** * @deprecated Use {@link InventoryEntityFactory#getEntity(int)} instead. */ @Deprecated public InventoryEntity getInventory(UserEntity userEntity) { return inventoryEntityFactory.getEntity(userEntity); } }
923a77d7dd588f389d5c6b86054b7dbd023fc32e
2,195
java
Java
src/main/java/com/google/firebase/database/core/view/QuerySpec.java
the-real-mrcs/firebase-admin-java
6e507af6fd84efcd7f8e79fc1561d92a0a72bbec
[ "Apache-2.0" ]
452
2017-05-17T20:12:15.000Z
2022-03-26T08:11:12.000Z
src/main/java/com/google/firebase/database/core/view/QuerySpec.java
the-real-mrcs/firebase-admin-java
6e507af6fd84efcd7f8e79fc1561d92a0a72bbec
[ "Apache-2.0" ]
326
2017-05-18T08:28:50.000Z
2022-03-30T18:51:09.000Z
src/main/java/com/google/firebase/database/core/view/QuerySpec.java
the-real-mrcs/firebase-admin-java
6e507af6fd84efcd7f8e79fc1561d92a0a72bbec
[ "Apache-2.0" ]
260
2017-05-18T06:13:50.000Z
2022-03-28T11:47:39.000Z
23.105263
86
0.677449
999,219
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.database.core.view; import com.google.firebase.database.core.Path; import com.google.firebase.database.snapshot.Index; import java.util.Map; public class QuerySpec { private final Path path; private final QueryParams params; public QuerySpec(Path path, QueryParams params) { this.path = path; this.params = params; } public static QuerySpec defaultQueryAtPath(Path path) { return new QuerySpec(path, QueryParams.DEFAULT_PARAMS); } public static QuerySpec fromPathAndQueryObject(Path path, Map<String, Object> map) { QueryParams params = QueryParams.fromQueryObject(map); return new QuerySpec(path, params); } public Path getPath() { return this.path; } public QueryParams getParams() { return this.params; } public Index getIndex() { return this.params.getIndex(); } public boolean isDefault() { return this.params.isDefault(); } public boolean loadsAllData() { return this.params.loadsAllData(); } @Override public String toString() { return this.path + ":" + params; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QuerySpec that = (QuerySpec) o; if (!path.equals(that.path)) { return false; } if (!params.equals(that.params)) { return false; } return true; } @Override public int hashCode() { int result = path.hashCode(); result = 31 * result + params.hashCode(); return result; } }
923a7899711156465225d3d97fed38f2d7b65ad3
301
java
Java
src/main/java/com/barreeyentos/tock/Application.java
barreeyentos/tock
62e092d7646b082aa56d702d3280ccddb4377ecd
[ "MIT" ]
null
null
null
src/main/java/com/barreeyentos/tock/Application.java
barreeyentos/tock
62e092d7646b082aa56d702d3280ccddb4377ecd
[ "MIT" ]
null
null
null
src/main/java/com/barreeyentos/tock/Application.java
barreeyentos/tock
62e092d7646b082aa56d702d3280ccddb4377ecd
[ "MIT" ]
null
null
null
23.153846
68
0.817276
999,220
package com.barreeyentos.tock; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
923a7b7b585b572d8c60825e2857f7a5a206d7f3
183
java
Java
api/src/main/java/ca/bc/gov/educ/api/sld/notification/constants/Topics.java
bcgov/EDUC-SLD-NOTIFICATION-API
dfb96632c159e299efafc804fa1e0e9e7e90ddff
[ "Apache-2.0" ]
1
2021-05-14T00:56:56.000Z
2021-05-14T00:56:56.000Z
api/src/main/java/ca/bc/gov/educ/api/sld/notification/constants/Topics.java
bcgov/EDUC-SLD-NOTIFICATION-API
dfb96632c159e299efafc804fa1e0e9e7e90ddff
[ "Apache-2.0" ]
2
2021-05-10T23:03:52.000Z
2022-03-25T00:22:48.000Z
api/src/main/java/ca/bc/gov/educ/api/sld/notification/constants/Topics.java
bcgov/EDUC-SLD-NOTIFICATION-API
dfb96632c159e299efafc804fa1e0e9e7e90ddff
[ "Apache-2.0" ]
null
null
null
15.25
54
0.677596
999,221
package ca.bc.gov.educ.api.sld.notification.constants; /** * The enum Topics. */ public enum Topics { /** * The Pen services events topic. */ PEN_SERVICES_EVENTS_TOPIC }
923a7ba16d53de5abc7aae18fa774fa15a4a09e0
4,724
java
Java
offer/src/main/java/com/java/study/algorithm/zuo/abasic/basic_class_06/Code_02_SkipList.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
1
2020-12-02T03:14:19.000Z
2020-12-02T03:14:19.000Z
offer/src/main/java/com/java/study/algorithm/zuo/abasic/basic_class_06/Code_02_SkipList.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
1
2021-05-08T18:03:22.000Z
2021-05-08T18:03:22.000Z
offer/src/main/java/com/java/study/algorithm/zuo/abasic/basic_class_06/Code_02_SkipList.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
null
null
null
28.119048
92
0.509526
999,222
package com.java.study.algorithm.zuo.abasic.basic_class_06; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 跳表 */ public class Code_02_SkipList { public static class SkipListNode { private Integer value; private List<SkipListNode> nextNodeList; public SkipListNode(Integer value) { this.value = value; this.nextNodeList = new ArrayList<>(); } } public static class SkipList { SkipListNode head; int maxLevel; int size; private static final double PROBABILITY = 0.5; public SkipList() { size = 0; maxLevel = 0; head = new SkipListNode(null); head.nextNodeList.add(null); } public SkipListNode getHead() { return head; } public void add(int newValue) { if (!contains(newValue)) { size++; int level = 0; while (Math.random() < PROBABILITY) { level++; } while (level > maxLevel) { head.nextNodeList.add(head); maxLevel++; } SkipListNode newNode = new SkipListNode(newValue); SkipListNode current = head; do { current = findNext(newValue, current, level); newNode.nextNodeList.add(0, current.nextNodeList.get(level)); current.nextNodeList.set(level, newNode); } while (level-- > 0); } } public void delete(Integer deleteValue) { if (contains(deleteValue)) { SkipListNode deleteNode = find(deleteValue); size--; int level = maxLevel; SkipListNode current = head; do { current = findNext(deleteNode.value, current, level); if (deleteNode.nextNodeList.size() > level) { current.nextNodeList.set(level, deleteNode.nextNodeList.get(level)); } } while (level-- > 0); } // do { // current = findNext(deleteNode.value, current, level); // if (deleteNode.nextNodes.size() > level) { // current.nextNodes.set(level, deleteNode.nextNodes.get(level)); // } // } while (level-- > 0); } private boolean contains(int value) { SkipListNode node = find(value); return node != null && node.value != null && equalTo(node.value, value); } private SkipListNode find(int value) { return find(value, head, maxLevel); } private SkipListNode find(Integer value, SkipListNode current, int level) { do { current = findNext(value, current, level); } while (level-- > 0); return current; } private SkipListNode findNext(Integer e, SkipListNode current, int level) { SkipListNode next = current.nextNodeList.get(level); while (next != null) { Integer value = next.value; if (lessThan(e, value)) { break; } current = next; next = current.nextNodeList.get(level); } return current; } private boolean lessThan(Integer a, Integer b) { return a.compareTo(b) < 0; } private boolean equalTo(Integer a, Integer b) { return a.compareTo(b) == 0; } public Iterator<Integer> iterator() { return new SkipListIterator(this); } public int size() { return size; } } public static class SkipListIterator implements Iterator<Integer> { private SkipList skipList; private SkipListNode current; public SkipListIterator(SkipList skipList) { this.skipList = skipList; current = skipList.head; } @Override public boolean hasNext() { return current.nextNodeList.get(0) != null; } @Override public Integer next() { current = current.nextNodeList.get(0); return current.value; } } public static void main(String[] args) { SkipList skipList = new SkipList(); skipList.add(1); System.out.println(skipList.contains(1)); skipList.delete(1); System.out.println(skipList.contains(1)); } }
923a7c68b6ecb96eaec06d8209c67e2e7e6a826c
830
java
Java
JavaEE_SummerProject/src/main/java/com/xjtuse/summerproject/controllerEntity/Attachment.java
tianfr/2020Summer_JavaEE
df1634649a24cf9dbe1e850937257b0bef4a797d
[ "MIT" ]
null
null
null
JavaEE_SummerProject/src/main/java/com/xjtuse/summerproject/controllerEntity/Attachment.java
tianfr/2020Summer_JavaEE
df1634649a24cf9dbe1e850937257b0bef4a797d
[ "MIT" ]
2
2020-07-03T13:14:03.000Z
2020-07-07T17:31:13.000Z
JavaEE_SummerProject/src/main/java/com/xjtuse/summerproject/controllerEntity/Attachment.java
tianfr/2020Summer_JavaEE
df1634649a24cf9dbe1e850937257b0bef4a797d
[ "MIT" ]
null
null
null
25.151515
64
0.650602
999,223
package com.xjtuse.summerproject.controllerEntity; import java.io.Serializable; public class Attachment implements Serializable { private String attachment_path; private String attachment_name; @Override public String toString() { return "Attachment{" + "attachment_path='" + attachment_path + '\'' + ", attachment_name='" + attachment_name + '\'' + '}'; } public String getAttachment_path() { return attachment_path; } public void setAttachment_path(String attachment_path) { this.attachment_path = attachment_path; } public String getAttachment_name() { return attachment_name; } public void setAttachment_name(String attachment_name) { this.attachment_name = attachment_name; } }
923a7d1314b97802df2c0f97c6e0a1cc35e1bfa6
899
java
Java
droidBugLib/src/main/java/de/siebn/javaBug/android/BugViewHelper.java
MaxNagl/droidBug
1ec1892fc6bb61d113d5af067949fdb7ddfa2019
[ "BSD-3-Clause" ]
null
null
null
droidBugLib/src/main/java/de/siebn/javaBug/android/BugViewHelper.java
MaxNagl/droidBug
1ec1892fc6bb61d113d5af067949fdb7ddfa2019
[ "BSD-3-Clause" ]
null
null
null
droidBugLib/src/main/java/de/siebn/javaBug/android/BugViewHelper.java
MaxNagl/droidBug
1ec1892fc6bb61d113d5af067949fdb7ddfa2019
[ "BSD-3-Clause" ]
1
2018-04-16T18:39:18.000Z
2018-04-16T18:39:18.000Z
27.242424
82
0.602892
999,224
package de.siebn.javaBug.android; import android.annotation.SuppressLint; import android.view.View; import android.view.ViewGroup; import java.util.*; public class BugViewHelper { public static ArrayList<View> getSortedChildren(ViewGroup viewGroup) { final int childrenCount = viewGroup.getChildCount(); ArrayList<View> list = new ArrayList<>(childrenCount); for (int i = 0; i < childrenCount; i++) list.add(viewGroup.getChildAt(i)); Collections.sort(list, new Comparator<View>(){ @Override public int compare(View o1, View o2) { return (int) Math.signum(getZ(o1) - getZ(o2)); } }); return list; } @SuppressLint("NewApi") public static float getZ(View view) { try { return view.getZ(); } catch (Exception e) { return 0; } } }
923a7f0b2cdf7c63922bae0669ecb1d09a99e641
352
java
Java
serverside/scribe-v1.0/src/main/java/pl/napiwo/scribe/url/ApiUrls.java
meksula/napiwo
3ff8af98b91593f76e6e921490bdf7d56239e781
[ "MIT" ]
null
null
null
serverside/scribe-v1.0/src/main/java/pl/napiwo/scribe/url/ApiUrls.java
meksula/napiwo
3ff8af98b91593f76e6e921490bdf7d56239e781
[ "MIT" ]
null
null
null
serverside/scribe-v1.0/src/main/java/pl/napiwo/scribe/url/ApiUrls.java
meksula/napiwo
3ff8af98b91593f76e6e921490bdf7d56239e781
[ "MIT" ]
null
null
null
16.761905
70
0.619318
999,225
package pl.napiwo.scribe.url; import pl.napiwo.scribe.ScribeApplication; /** * @author * Karol Meksuła * 07-10-2018 * */ public enum ApiUrls { CERBER_USER_AUTH { @Override public String getUrl() { return ScribeApplication.host + "8015/api/v1/cerber/auth"; } }; public abstract String getUrl(); }
923a80a58f421ae72765b1287f3978d2ef08a38a
1,607
java
Java
src/com/houarizegai/fxtools/sliders/model1/SliderController.java
averroes96/FXTools
3e5d1a47efadecdbbb5be6285e4a70373dc34bb6
[ "MIT" ]
53
2020-01-24T20:16:11.000Z
2022-02-03T08:26:25.000Z
src/com/houarizegai/fxtools/sliders/model1/SliderController.java
averroes96/FXTools
3e5d1a47efadecdbbb5be6285e4a70373dc34bb6
[ "MIT" ]
2
2020-05-19T19:22:05.000Z
2021-09-14T20:42:42.000Z
src/com/houarizegai/fxtools/sliders/model1/SliderController.java
averroes96/FXTools
3e5d1a47efadecdbbb5be6285e4a70373dc34bb6
[ "MIT" ]
6
2020-03-29T14:24:55.000Z
2021-03-20T15:26:34.000Z
30.903846
108
0.65837
999,226
package com.houarizegai.fxtools.sliders.model1; import java.net.URL; import java.util.ResourceBundle; import javafx.animation.Animation; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.util.Duration; public class SliderController implements Initializable { @FXML // Image of Slider private ImageView imgSlider; // counter Number of image using in slider private final byte NUMBER_IMAGE_SLIDER = 3; private int counter = 1; @Override public void initialize(URL url, ResourceBundle rb) { sliderAutoChangePictures(); } private void sliderAutoChangePictures() { // Make auto change the slider in duration Timeline sliderTimer = new Timeline(new KeyFrame(Duration.ZERO, e -> { FadeTransition ft = new FadeTransition(); ft.setNode(imgSlider); ft.setDuration(new Duration(4000)); ft.setFromValue(1.0); ft.setToValue(0.3); ft.setCycleCount(0); ft.setAutoReverse(true); ft.play(); imgSlider.setImage(new Image("com/houarizegai/fxtools/sliders/model1/img/" + counter + ".png")); if (++counter > NUMBER_IMAGE_SLIDER) { counter = 1; } }), new KeyFrame(Duration.seconds(4)) ); sliderTimer.setCycleCount(Animation.INDEFINITE); sliderTimer.play(); } }
923a80c4274606396da423f77424234513fa3cf9
2,843
java
Java
core/src/main/java/com/helicalinsight/datasource/managed/JndiConfigurer.java
RevRebel/helicalinsight
e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d
[ "Apache-2.0" ]
238
2016-12-08T06:15:56.000Z
2022-03-10T10:17:10.000Z
core/src/main/java/com/helicalinsight/datasource/managed/JndiConfigurer.java
RevRebel/helicalinsight
e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d
[ "Apache-2.0" ]
15
2017-05-11T20:20:43.000Z
2020-09-30T20:14:43.000Z
core/src/main/java/com/helicalinsight/datasource/managed/JndiConfigurer.java
RevRebel/helicalinsight
e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d
[ "Apache-2.0" ]
99
2017-05-17T17:38:32.000Z
2022-03-17T06:56:56.000Z
36.922078
107
0.666549
999,227
/** * Copyright (C) 2013-2019 Helical IT Solutions (http://www.helicalinsight.com) - All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helicalinsight.datasource.managed; import com.helicalinsight.efw.exceptions.ConfigurationException; import com.helicalinsight.efw.exceptions.JdbcConnectionException; import com.helicalinsight.efw.exceptions.MalformedJsonException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /** * Created by author on 21-Dec-14. * * @author Rajasekhar */ @Component class JndiConfigurer { private static final Logger logger = LoggerFactory.getLogger(JndiConfigurer.class); public DataSource getJndiDataSource(String json) { if (json == null) { throw new IllegalArgumentException("The parameter json is null"); } String lookUpName = JsonUtils.getKeyFromJson(json, "lookUpName"); if (lookUpName == null) { throw new MalformedJsonException("Json does not have lookUpName"); } Context initContext; try { initContext = new InitialContext(); DataSource dataSource = (DataSource) initContext.lookup(lookUpName); if (dataSource == null) { throwException(lookUpName); } else { if (logger.isInfoEnabled()) { logger.info("Jndi lookUp for the name " + lookUpName + " is successful and " + "the DataSource class is " + dataSource.getClass()); } } return dataSource; } catch (NamingException exception) { throw new JdbcConnectionException("Could not find the JNDI resource " + lookUpName, exception); } } private void throwException(String lookUpName) { throw new ConfigurationException(String.format("Could not find the JNDI resource %s. " + "Configure the JNDI DataSource in your application server and query with proper " + "lookUpName. " + "For example java:comp/env/jdbc/TestDB", lookUpName)); } }
923a80db062ebd0984fd0ade282a222571da8e15
2,238
java
Java
seguranca/src/main/java/br/com/basis/madre/seguranca/domain/Usuario.java
BasisTI/madre
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
[ "CECILL-B" ]
9
2019-10-09T15:48:37.000Z
2022-01-11T18:14:15.000Z
seguranca/src/main/java/br/com/basis/madre/seguranca/domain/Usuario.java
BasisTI/madre
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
[ "CECILL-B" ]
30
2020-03-11T12:05:35.000Z
2022-03-02T05:42:56.000Z
seguranca/src/main/java/br/com/basis/madre/seguranca/domain/Usuario.java
BasisTI/madre
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
[ "CECILL-B" ]
11
2020-08-15T15:44:48.000Z
2022-02-06T15:33:38.000Z
23.072165
99
0.616175
999,228
package br.com.basis.madre.seguranca.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import org.springframework.data.elasticsearch.annotations.FieldType; import java.io.Serializable; /** * A Usuario. */ @Entity @Table(name = "usuario") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.springframework.data.elasticsearch.annotations.Document(indexName = "madre-seguranca-usuario") public class Usuario implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqUsuario") @SequenceGenerator(name = "seqUsuario") private Long id; @NotNull @Column(name = "codigo", nullable = false) private Integer codigo; @Column(name = "login") private String login; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getCodigo() { return codigo; } public Usuario codigo(Integer codigo) { this.codigo = codigo; return this; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public String getLogin() { return login; } public Usuario login(String login) { this.login = login; return this; } public void setLogin(String login) { this.login = login; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Usuario)) { return false; } return id != null && id.equals(((Usuario) o).id); } @Override public int hashCode() { return 31; } // prettier-ignore @Override public String toString() { return "Usuario{" + "id=" + getId() + ", codigo=" + getCodigo() + ", login='" + getLogin() + "'" + "}"; } }
923a815b059ccdbf8c096f9ab4be26068f6d3c38
947
java
Java
programmers/12981/Solution.java
pparkddo/ps
7164c694403c2087a7b4b16a64f521ae327e328f
[ "MIT" ]
1
2021-04-02T09:37:11.000Z
2021-04-02T09:37:11.000Z
programmers/12981/Solution.java
pparkddo/ps
7164c694403c2087a7b4b16a64f521ae327e328f
[ "MIT" ]
null
null
null
programmers/12981/Solution.java
pparkddo/ps
7164c694403c2087a7b4b16a64f521ae327e328f
[ "MIT" ]
null
null
null
30.548387
88
0.520591
999,229
import java.util.HashSet; import java.util.Set; class Solution { public int[] solution(int n, String[] words) { Set<String> set = new HashSet<>(); for (int index = 0; index < words.length; index++) { String word = words[index]; if (index == 0) { set.add(word); continue; } if(!isCorrectContinuousWord(words[index-1], word) || !isUnique(word, set)) { int sequence = (index % n) + 1; int count = (index / n) + 1; return new int[] {sequence, count}; } set.add(word); } return new int[] {0, 0}; } private boolean isCorrectContinuousWord(String previous, String next) { return previous.charAt(previous.length()-1) == next.charAt(0); } private boolean isUnique(String word, Set<String> set) { return !set.contains(word); } }
923a817c7db18c55a0d2ce8fc580bba2012b468c
1,020
java
Java
libs/src/main/java/com/longngohoang/twitter/appcore/common/util/ParseRelativeDate.java
beyonderVN/AdvancedUI
43368a575778815f02fe9473e60514297ec24b45
[ "Apache-2.0" ]
null
null
null
libs/src/main/java/com/longngohoang/twitter/appcore/common/util/ParseRelativeDate.java
beyonderVN/AdvancedUI
43368a575778815f02fe9473e60514297ec24b45
[ "Apache-2.0" ]
null
null
null
libs/src/main/java/com/longngohoang/twitter/appcore/common/util/ParseRelativeDate.java
beyonderVN/AdvancedUI
43368a575778815f02fe9473e60514297ec24b45
[ "Apache-2.0" ]
null
null
null
31.875
87
0.668627
999,230
package com.longngohoang.twitter.appcore.common.util; import android.text.format.DateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; /** * Created by Admin on 30/10/2016. */ public class ParseRelativeDate { private static final String TAG = "ParseRelativeDate"; public static String getRelativeTimeAgo(String rawJsonDate) { String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH); sf.setLenient(true); String relativeDate = ""; try { long dateMillis = sf.parse(rawJsonDate).getTime(); relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString(); } catch (ParseException e) { e.printStackTrace(); } // Log.d(TAG, rawJsonDate+": "+relativeDate); return relativeDate; } }
923a82973dbe7bb835131a5fc8cc65346a13ef64
1,617
java
Java
sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
22.774648
75
0.616574
999,231
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.faceapi.models; import com.fasterxml.jackson.annotation.JsonProperty; /** * Hair color and associated confidence. */ public class HairColor { /** * Name of the hair color. Possible values include: 'unknown', 'white', * 'gray', 'blond', 'brown', 'red', 'black', 'other'. */ @JsonProperty(value = "color") private HairColorType color; /** * Confidence level of the color. */ @JsonProperty(value = "confidence") private double confidence; /** * Get the color value. * * @return the color value */ public HairColorType color() { return this.color; } /** * Set the color value. * * @param color the color value to set * @return the HairColor object itself. */ public HairColor withColor(HairColorType color) { this.color = color; return this; } /** * Get the confidence value. * * @return the confidence value */ public double confidence() { return this.confidence; } /** * Set the confidence value. * * @param confidence the confidence value to set * @return the HairColor object itself. */ public HairColor withConfidence(double confidence) { this.confidence = confidence; return this; } }
923a82c8473ff618272a5a8071c44685cb67670a
2,748
java
Java
util/ResponseCodes.java
maiclan/jnews
f253a2044a0ef2fdd514ef1f4cb9f6f4a2e35550
[ "MIT" ]
null
null
null
util/ResponseCodes.java
maiclan/jnews
f253a2044a0ef2fdd514ef1f4cb9f6f4a2e35550
[ "MIT" ]
null
null
null
util/ResponseCodes.java
maiclan/jnews
f253a2044a0ef2fdd514ef1f4cb9f6f4a2e35550
[ "MIT" ]
null
null
null
36.157895
71
0.683406
999,232
package util; import java.util.*; public interface ResponseCodes { // just for fun final Map<Integer, String> states = new HashMap<Integer, String>(); final boolean canUseIt = ResponseCodes(); static boolean ResponseCodes(){ states.put(100, "Continue"); states.put(101, "Switching Protocol"); states.put(102, "Processing (WebDAV)"); states.put(103, "Early Hints"); states.put(200, "OK"); states.put(201, "Created"); states.put(202, "Accepted"); states.put(203, "Non-Authoritative Information"); states.put(204, "No Content"); states.put(205, "Reset Content"); states.put(206, "Partial Content"); states.put(207, "Multi-Status (WebDAV)"); states.put(208, "Multi-Status (WebDAV)"); states.put(226, "IM Used (HTTP Delta encoding)"); states.put(300, "Multiple Choice"); states.put(301, "Moved Permanently"); states.put(302, "Found"); states.put(303, "See Other"); states.put(304, "Not Modified"); states.put(305, "Use Proxy "); states.put(306, "unused"); states.put(307, "Temporary Redirect"); states.put(308, "Permanent Redirect"); states.put(400, "Bad Request"); states.put(401, "Unauthorized"); states.put(402, "Payment Required"); states.put(403, "Forbidden"); states.put(404, "Not Found"); states.put(405, "Method Not Allowed"); states.put(406, "Not Acceptable"); states.put(407, "Proxy Authentication Required"); states.put(408, "Request Timeout"); states.put(409, "Conflict"); states.put(410, "Gone"); states.put(411, "Length Required"); states.put(412, "Precondition Failed"); states.put(413, "Payload Too Large"); states.put(414, "URI Too Long"); states.put(415, "Unsupported Media Type"); states.put(416, "Requested Range Not Satisfiable"); states.put(417, "Expectation Failed"); states.put(418, "I'm a teapot"); states.put(421, "Misdirected Request"); states.put(422, "Unprocessable Entity (WebDAV)"); states.put(423, "Locked (WebDAV)"); states.put(424, "Failed Dependency (WebDAV)"); states.put(425, "Too Early"); states.put(426, "Upgrade Required"); states.put(428, "Precondition Required"); states.put(429, "Too Many Requests"); states.put(431, "Request Header Fields Too Large"); states.put(451, "Unavailable For Legal Reasons"); states.put(500, "Internal Server Error"); states.put(501, "Not Implemented"); states.put(502, "Bad Gateway"); states.put(503, "Service Unavailable"); states.put(504, "Gateway Timeout"); states.put(505, "HTTP Version Not Supported"); states.put(506, "Variant Also Negotiates"); states.put(507, "Insufficient Storage"); states.put(508, "Loop Detected (WebDAV)"); states.put(510, "Not Extended"); states.put(511, "Network Authentication Required"); return true; } }
923a8325a02f7133284b25ca87fd7ed8f22d9f02
30,167
java
Java
elytron/src/main/java/org/wildfly/extension/elytron/_private/ElytronSubsystemMessages.java
nekdozjam/wildfly-core
346e1b30e1f58ec1fe5805eb2c59ff4bf5d65dc9
[ "Apache-2.0" ]
2
2018-01-03T06:47:38.000Z
2018-01-03T06:48:57.000Z
elytron/src/main/java/org/wildfly/extension/elytron/_private/ElytronSubsystemMessages.java
nekdozjam/wildfly-core
346e1b30e1f58ec1fe5805eb2c59ff4bf5d65dc9
[ "Apache-2.0" ]
1
2017-11-20T16:30:21.000Z
2017-11-20T16:30:21.000Z
elytron/src/main/java/org/wildfly/extension/elytron/_private/ElytronSubsystemMessages.java
nekdozjam/wildfly-core
346e1b30e1f58ec1fe5805eb2c59ff4bf5d65dc9
[ "Apache-2.0" ]
1
2018-01-03T09:54:00.000Z
2018-01-03T09:54:00.000Z
50.887015
209
0.733762
999,233
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.wildfly.extension.elytron._private; import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.NoSuchProviderException; import java.security.Policy; import java.security.Provider; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.OperationFailedException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Param; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceController.State; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartException; import org.wildfly.security.auth.server.SecurityRealm; import org.wildfly.security.x500.cert.acme.AcmeException; /** * Messages for the Elytron subsystem. * * <a href="mailto:kenaa@example.com">Darran Lofthouse</a> */ @MessageLogger(projectCode = "WFLYELY", length = 5) public interface ElytronSubsystemMessages extends BasicLogger { /** * A root logger with the category of the package name. */ ElytronSubsystemMessages ROOT_LOGGER = Logger.getMessageLogger(ElytronSubsystemMessages.class, "org.wildfly.extension.elytron"); /** * {@link OperationFailedException} if the same realm is injected multiple times for a single domain. * * @param realmName - the name of the {@link SecurityRealm} being injected. * @return The {@link OperationFailedException} for the error. */ @Message(id = 2, value = "Can not inject the same realm '%s' in a single security domain.") OperationFailedException duplicateRealmInjection(final String realmName); /** * An {@link IllegalArgumentException} if the supplied operation did not contain an address with a value for the required key. * * @param key - the required key in the address of the operation. * @return The {@link IllegalArgumentException} for the error. */ @Message(id = 3, value = "The operation did not contain an address with a value for '%s'.") IllegalArgumentException operationAddressMissingKey(final String key); /** * A {@link StartException} if it is not possible to initialise the {@link Service}. * * @param cause the cause of the failure. * @return The {@link StartException} for the error. */ @Message(id = 4, value = "Unable to start the service.") StartException unableToStartService(@Cause Exception cause); /** * An {@link OperationFailedException} if it is not possible to access the {@link KeyStore} at RUNTIME. * * @param cause the underlying cause of the failure * @return The {@link OperationFailedException} for the error. */ @Message(id = 5, value = "Unable to access KeyStore to complete the requested operation.") OperationFailedException unableToAccessKeyStore(@Cause Exception cause); // /** // * An {@link OperationFailedException} for operations that are unable to populate the result. // * // * @param cause the underlying cause of the failure. // * @return The {@link OperationFailedException} for the error. // */ // @Message(id = 6, value = "Unable to populate result.") // OperationFailedException unableToPopulateResult(@Cause Exception cause); /** * An {@link OperationFailedException} where an operation can not proceed as it's required service is not UP. * * @param serviceName the name of the service that is required. * @param state the actual state of the service. * @return The {@link OperationFailedException} for the error. */ @Message(id = 7, value = "The required service '%s' is not UP, it is currently '%s'.") OperationFailedException requiredServiceNotUp(ServiceName serviceName, State state); /** * An {@link OperationFailedException} where the name of the operation does not match the expected names. * * @param actualName the operation name contained within the request. * @param expectedNames the expected operation names. * @return The {@link OperationFailedException} for the error. */ @Message(id = 8, value = "Invalid operation name '%s', expected one of '%s'") OperationFailedException invalidOperationName(String actualName, String... expectedNames); /** * An {@link RuntimeException} where an operation can not be completed. * * @param cause the underlying cause of the failure. * @return The {@link RuntimeException} for the error. */ @Message(id = 9, value = "Unable to complete operation. '%s'") RuntimeException unableToCompleteOperation(@Cause Throwable cause, String causeMessage); /** * An {@link OperationFailedException} where this an attempt to save a KeyStore without a File defined. * * @return The {@link OperationFailedException} for the error. */ @Message(id = 10, value = "Unable to save KeyStore - KeyStore file '%s' does not exist.") OperationFailedException cantSaveWithoutFile(final String file); // /** // * A {@link StartException} for when provider registration fails due to an existing registration. // * // * @param name the name of the provider registration failed for. // * @return The {@link StartException} for the error. // */ // @Message(id = 11, value = "A Provider is already registered for '%s'") // StartException providerAlreadyRegistered(String name); /** * A {@link StartException} where a service can not identify a suitable {@link Provider} * * @param type the type being searched for. * @return The {@link StartException} for the error. */ @Message(id = 12, value = "No suitable provider found for type '%s'") StartException noSuitableProvider(String type); /** * A {@link OperationFailedException} for when an attempt is made to define a domain that has a default realm specified that * it does not actually reference. * * @param defaultRealm the name of the default_realm specified. * @return The {@link OperationFailedException} for the error. */ @Message(id = 13, value = "The default-realm '%s' is not in the list of realms [%s] referenced by this domain.") OperationFailedException defaultRealmNotReferenced(String defaultRealm, String realms); /** * A {@link StartException} for when the properties file backed realm can not be started due to problems loading the * properties files. * * @param cause the underlying cause of the error. * @return The {@link StartException} for the error. */ @Message(id = 14, value = "Unable to load the properties files required to start the properties file backed realm: Users file: '%s' Groups file: '%s'") StartException unableToLoadPropertiesFiles(@Cause Exception cause, String usersFile, String groupsFile); /** * A {@link StartException} where a custom component has been defined with configuration but does not implement * the {@code initialize(Map<String, String>)} method. * * @param className the class name of the custom component implementation being loaded. * @return The {@link StartException} for the error. */ @Message(id = 15, value = "The custom component implementation '%s' doe not implement method initialize(Map<String, String>), however configuration has been supplied.") StartException componentNotConfigurable(final String className, @Cause Exception cause); /** * An {@link OperationFailedException} where validation of a specified regular expression has failed. * * @param pattern the regular expression that failed validation. * @param cause the reported {@link Exception} during validation. * @return The {@link OperationFailedException} for the error. */ @Message(id = 16, value = "The supplied regular expression '%s' is invalid.") OperationFailedException invalidRegularExpression(String pattern, @Cause Exception cause); /** * A {@link StartException} for when the properties file backed realm can not be used because property file(s) does not exist. * * @param file the missing file detail. * @return The {@link StartException} for the error. */ @Message(id = 17, value = "Property file referenced in properties-realm does not exist: %s") StartException propertyFilesDoesNotExist(String file); /** * A {@link StartException} where a Key or Trust manager factory can not be created for a specific algorithm. * * @param type the type of manager factory being created. * @param algorithm the requested algorithm. * @return The {@link StartException} for the error. */ @Message(id = 18, value = "Unable to create %s for algorithm '%s'.") StartException unableToCreateManagerFactory(final String type, final String algorithm); /** * A {@link StartException} where a specific type can not be found in an injected value. * * @param type the type required. * @return The {@link StartException} for the error. */ @Message(id = 19, value = "No '%s' found in injected value.") StartException noTypeFound(final String type); /** * A {@link OperationFailedException} for when the properties file used by the realm can not be reloaded. * * @param cause the underlying cause of the error. * @return The {@link OperationFailedException} for the error. */ @Message(id = 20, value = "Unable to reload the properties files required to by the properties file backed realm.") OperationFailedException unableToReLoadPropertiesFiles(@Cause Exception cause); /** * A {@link StartException} for when creating of the {@link java.security.Permission} will fail. * * @param permissionClassName class-name of the created permission * @param cause the underlying cause of the error. * @return The {@link OperationFailedException} for the error. */ @Message(id = 21, value = "Exception while creating the permission object for the permission mapping. Please check [class-name], [target-name] (name of permission) and [action] of [%s].") StartException exceptionWhileCreatingPermission(String permissionClassName, @Cause Throwable cause); @Message(id = 22, value = "KeyStore file '%s' does not exist and required.") StartException keyStoreFileNotExists(final String file); @LogMessage(level = WARN) @Message(id = 23, value = "KeyStore file '%s' does not exist. Used blank.") void keyStoreFileNotExistsButIgnored(final String file); @LogMessage(level = WARN) @Message(id = 24, value = "Certificate [%s] in KeyStore is not valid") void certificateNotValid(String alias, @Cause Exception cause); @Message(id = 25, value = "Referenced property file is invalid: %s") StartException propertyFileIsInvalid(String message, @Cause Throwable cause); //@Message(id = 26, value = "trusted-security-domains cannot contain the security-domain '%s' itself") //OperationFailedException trustedDomainsCannotContainDomainItself(String domain); @Message(id = 27, value = "Unable to obtain OID for X.500 attribute '%s'") OperationFailedException unableToObtainOidForX500Attribute(String attribute); @Message(id = 28, value = "The X.500 attribute must be defined by name or by OID") OperationFailedException x500AttributeMustBeDefined(); @Message(id = 29, value = "Failed to parse URL '%s'") OperationFailedException invalidURL(String url, @Cause Exception cause); @Message(id = 30, value = "Realm '%s' does not support cache") StartException realmDoesNotSupportCache(String realmName); @Message(id = 31, value = "Unable to access CRL file.") StartException unableToAccessCRL(@Cause Exception cause); @Message(id = 32, value = "Unable to reload CRL file.") RuntimeException unableToReloadCRL(@Cause Exception cause); /** * A {@link RuntimeException} if it is not possible to access an entry from a {@link KeyStore} at RUNTIME. * * @param alias the entry that couldn't be accessed * @param keyStore the keystore * @return {@link RuntimeException} for the error. */ @Message(id = 33, value = "Unable to access entry [%s] from key store [%s].") RuntimeException unableToAccessEntryFromKeyStore(String alias, String keyStore); @Message(id = 34, value = "A principal query can only have a single key mapper") OperationFailedException jdbcRealmOnlySingleKeyMapperAllowed(); @Message(id = 35, value = "Unable to load module '%s'.") OperationFailedException unableToLoadModule(String module, @Cause Exception cause); /** * A {@link OperationFailedException} for when validating a security domain fails due to the same realm being referenced twice. * * @param realmName the name of the security realm referenced twice. * @return The {@link OperationFailedException} for the error. */ @Message(id = 36, value = "Security realm '%s' has been referenced twice in the same security domain.") OperationFailedException realmRefererencedTwice(String realmName); /** * A {@link StartException} where a specific type is not type of injected value. * * @param type the type required. * @return The {@link StartException} for the error. */ @Message(id = 37, value = "Injected value is not of '%s' type.") StartException invalidTypeInjected(final String type); @Message(id = 38, value = "Could not load permission class '%s'") StartException invalidPermissionClass(String className); @Message(id = 39, value = "Unable to reload CRL file - TrustManager is not reloadable") OperationFailedException unableToReloadCRLNotReloadable(); @Message(id = 40, value = "Unable to load the permission module '%s' for the permission mapping") StartException invalidPermissionModule(String module, @Cause Throwable cause); @Message(id = 41, value = "Unable to transform configuration to the target version - attribute '%s' is different from '%s'") String unableToTransformTornAttribute(String attribute1, String attribute2); @Message(id = 42, value = "Unable to transform multiple 'authorization-realms' to the single value") String unableToTransformMultipleRealms(); // CREDENTIAL_STORE section @Message(id = 909, value = "Credential store '%s' does not support given credential store entry type '%s'") OperationFailedException credentialStoreEntryTypeNotSupported(String credentialStoreName, String entryType); @Message(id = 910, value = "Password cannot be resolved for key-store '%s'") IOException keyStorePasswordCannotBeResolved(String path); @Message(id = 911, value = "Credential store '%s' protection parameter cannot be resolved") IOException credentialStoreProtectionParameterCannotBeResolved(String name); // @LogMessage(level = ERROR) // @Message(id = 912, value = "Credential store issue encountered") // void credentialStoreIssueEncountered(@Cause Exception cause); @Message(id = 913, value = "Credential alias '%s' of credential type '%s' already exists in the store") OperationFailedException credentialAlreadyExists(String alias, String credentialType); @Message(id = 914, value = "Provider loader '%s' cannot supply Credential Store provider of type '%s'") NoSuchProviderException providerLoaderCannotSupplyProvider(String providerLoader, String type); // @Message(id = 915, value = "Name of the credential store has to be specified in this credential-reference") // IllegalStateException nameOfCredentialStoreHasToBeSpecified(); @Message(id = 916, value = "Credential cannot be resolved") IllegalStateException credentialCannotBeResolved(); @Message(id = 917, value = "Password cannot be resolved for dir-context") StartException dirContextPasswordCannotBeResolved(@Cause Exception cause); @Message(id = 920, value = "Credential alias '%s' of credential type '%s' does not exist in the store") OperationFailedException credentialDoesNotExist(String alias, String credentialType); @Message(id = 921, value = "Location parameter is not specified for filebased keystore type '%s'") OperationFailedException filebasedKeystoreLocationMissing(String type); @Message(id = Message.NONE, value = "Reload dependent services which might already have cached the secret value") String reloadDependantServices(); @Message(id = Message.NONE, value = "Update dependent resources as alias '%s' does not exist anymore") String updateDependantServices(String alias); /* * Identity Resource Messages - 1000 */ @Message(id = 1000, value = "Identity with name [%s] already exists.") OperationFailedException identityAlreadyExists(final String principalName); @Message(id = 1001, value = "Could not create identity with name [%s].") RuntimeException couldNotCreateIdentity(final String principalName, @Cause Exception cause); @Message(id = 1002, value = "Identity with name [%s] not found.") String identityNotFound(final String principalName); @Message(id = 1003, value = "Could not delete identity with name [%s].") RuntimeException couldNotDeleteIdentity(final String principalName, @Cause Exception cause); @Message(id = 1004, value = "Identity with name [%s] not authorized.") String identityNotAuthorized(final String principalName); @Message(id = 1005, value = "Could not read identity [%s] from security domain [%s].") RuntimeException couldNotReadIdentity(final String principalName, final ServiceName domainServiceName, @Cause Exception cause); // @Message(id = 1006, value = "Unsupported password type [%s].") // RuntimeException unsupportedPasswordType(final Class passwordType); @Message(id = 1007, value = "Could not read identity with name [%s].") RuntimeException couldNotReadIdentity(final String principalName, @Cause Exception cause); @Message(id = 1008, value = "Failed to obtain the authorization identity.") RuntimeException couldNotObtainAuthorizationIdentity(@Cause Exception cause); @Message(id = 1009, value = "Failed to add attribute.") RuntimeException couldNotAddAttribute(@Cause Exception cause); @Message(id = 1010, value = "Failed to remove attribute.") RuntimeException couldNotRemoveAttribute(@Cause Exception cause); @Message(id = 1011, value = "Could not create password.") RuntimeException couldNotCreatePassword(@Cause Exception cause); @Message(id = 1012, value = "Unexpected password type [%s].") OperationFailedException unexpectedPasswordType(final String passwordType); @Message(id = 1013, value = "Pattern [%s] requires a capture group") OperationFailedException patternRequiresCaptureGroup(final String pattern); @Message(id = 1014, value = "Invalid [%s] definition. Only one of '%s' or '%s' can be set in one Object in the list of filters.") OperationFailedException invalidDefinition(final String property, String filterNameOne, String filterNameTwo); @Message(id = 1015, value = "Unable to perform automatic outflow for '%s'") IllegalStateException unableToPerformOutflow(String identityName, @Cause Exception cause); @Message(id = 1016, value = "Server '%s' not known") OperationFailedException serverNotKnown(final String server, @Cause UnknownHostException e); @Message(id = 1017, value = "Invalid value for cipher-suite-filter. %s") OperationFailedException invalidCipherSuiteFilter(@Cause Throwable cause, String causeMessage); @Message(id = 1018, value = "Invalid size %s") OperationFailedException invalidSize(String size); @Message(id = 1019, value = "The suffix (%s) can not contain seconds or milliseconds.") OperationFailedException suffixContainsMillis(String suffix); @Message(id = 1020, value = "The suffix (%s) is invalid. A suffix must be a valid date format.") OperationFailedException invalidSuffix(String suffix); // @Message(id = 1021, value = "Cannot remove the default policy provider [%s]") // OperationFailedException cannotRemoveDefaultPolicy(String defaultPolicy); @Message(id = 1022, value = "Failed to set policy [%s]") RuntimeException failedToSetPolicy(Policy policy, @Cause Exception cause); @Message(id = 1023, value = "Could not find policy provider with name [%s]") XMLStreamException cannotFindPolicyProvider(String policyProvider, @Param Location location); @Message(id = 1024, value = "Failed to register policy context handlers") RuntimeException failedToRegisterPolicyHandlers(@Cause Exception cause); @Message(id = 1025, value = "Failed to create policy [%s]") RuntimeException failedToCreatePolicy(String className, @Cause Exception cause); @LogMessage(level = WARN) @Message(id = 1026, value = "Element '%s' with attribute '%s' set to '%s' is unused. Since unused policy " + "configurations can no longer be stored in the configuration model this item is being discarded.") void discardingUnusedPolicy(String element, String attr, String name); @Message(id = 1027, value = "Key password cannot be resolved for key-store '%s'") IOException keyPasswordCannotBeResolved(String path); @Message(id = 1028, value = "Invalid value for not-before. %s") OperationFailedException invalidNotBefore(@Cause Throwable cause, String causeMessage); @Message(id = 1029, value = "Alias '%s' does not exist in KeyStore") OperationFailedException keyStoreAliasDoesNotExist(String alias); @Message(id = 1030, value = "Alias '%s' does not identify a PrivateKeyEntry in KeyStore") OperationFailedException keyStoreAliasDoesNotIdentifyPrivateKeyEntry(String alias); @Message(id = 1031, value = "Unable to obtain PrivateKey for alias '%s'") OperationFailedException unableToObtainPrivateKey(String alias); @Message(id = 1032, value = "Unable to obtain Certificate for alias '%s'") OperationFailedException unableToObtainCertificate(String alias); @Message(id = 1033, value = "No certificates found in certificate reply") OperationFailedException noCertificatesFoundInCertificateReply(); @Message(id = 1034, value = "Public key from certificate reply does not match public key from certificate in KeyStore") OperationFailedException publicKeyFromCertificateReplyDoesNotMatchKeyStore(); @Message(id = 1035, value = "Certificate reply is the same as the certificate from PrivateKeyEntry in KeyStore") OperationFailedException certificateReplySameAsCertificateFromKeyStore(); @Message(id = 1036, value = "Alias '%s' already exists in KeyStore") OperationFailedException keyStoreAliasAlreadyExists(String alias); @Message(id = 1037, value = "Top-most certificate from certificate reply is not trusted. Inspect the certificate carefully and if it is valid, execute import-certificate again with validate set to false.") OperationFailedException topMostCertificateFromCertificateReplyNotTrusted(); @Message(id = 1038, value = "Trusted certificate is already in KeyStore under alias '%s'") OperationFailedException trustedCertificateAlreadyInKeyStore(String alias); @Message(id = 1039, value = "Trusted certificate is already in cacerts KeyStore under alias '%s'") OperationFailedException trustedCertificateAlreadyInCacertsKeyStore(String alias); @Message(id = 1040, value = "Unable to determine if the certificate is trusted. Inspect the certificate carefully and if it is valid, execute import-certificate again with validate set to false.") OperationFailedException unableToDetermineIfCertificateIsTrusted(); @Message(id = 1041, value = "Certificate file does not exist") OperationFailedException certificateFileDoesNotExist(@Cause Exception cause); @Message(id = 1042, value = "Unable to obtain Entry for alias '%s'") OperationFailedException unableToObtainEntry(String alias); @Message(id = 1043, value = "Unable to create an account with the certificate authority: %s") OperationFailedException unableToCreateAccountWithCertificateAuthority(@Cause Exception cause, String causeMessage); @Message(id = 1044, value = "Unable to change the account key associated with the certificate authority: %s") OperationFailedException unableToChangeAccountKeyWithCertificateAuthority(@Cause Exception cause, String causeMessage); @Message(id = 1045, value = "Unable to deactivate the account associated with the certificate authority: %s") OperationFailedException unableToDeactivateAccountWithCertificateAuthority(@Cause Exception cause, String causeMessage); @Message(id = 1046, value = "Unable to obtain certificate authority account Certificate for alias '%s'") StartException unableToObtainCertificateAuthorityAccountCertificate(String alias); @Message(id = 1047, value = "Unable to obtain certificate authority account PrivateKey for alias '%s'") StartException unableToObtainCertificateAuthorityAccountPrivateKey(String alias); @Message(id = 1048, value = "Unable to update certificate authority account key store: %s") OperationFailedException unableToUpdateCertificateAuthorityAccountKeyStore(@Cause Exception cause, String causeMessage); @Message(id = 1049, value = "Unable to respond to challenge from certificate authority: %s") AcmeException unableToRespondToCertificateAuthorityChallenge(@Cause Exception cause, String causeMessage); @Message(id = 1050, value = "Invalid certificate authority challenge") AcmeException invalidCertificateAuthorityChallenge(); @Message(id = 1051, value = "Invalid certificate revocation reason '%s'") OperationFailedException invalidCertificateRevocationReason(String reason); @Message(id = 1052, value = "Unable to instantiate AcmeClientSpi implementation") IllegalStateException unableToInstatiateAcmeClientSpiImplementation(); @Message(id = 1053, value = "Unable to update the account with the certificate authority: %s") OperationFailedException unableToUpdateAccountWithCertificateAuthority(@Cause Exception cause, String causeMessage); @Message(id = 1054, value = "Unable to get the metadata associated with the certificate authority: %s") OperationFailedException unableToGetCertificateAuthorityMetadata(@Cause Exception cause, String causeMessage); @Message(id = 1055, value = "Invalid key size: %d") OperationFailedException invalidKeySize(int keySize); @Message(id = 1056, value = "A certificate authority account with this account key already exists. To update the contact" + " information associated with this existing account, use %s. To change the key associated with this existing account, use %s.") OperationFailedException certificateAuthorityAccountAlreadyExists(String updateAccount, String changeAccountKey); @Message(id = 1057, value = "Failed to create ServerAuthModule [%s] using module '%s'") RuntimeException failedToCreateServerAuthModule(String className, String module, @Cause Exception cause); @Message(id = 1058, value = "Failed to parse PEM public key with kid: %s") OperationFailedException failedToParsePEMPublicKey(String kid); @Message(id = 1059, value = "Unable to detect KeyStore '%s'") StartException unableToDetectKeyStore(String path); @Message(id = 1060, value = "Fileless KeyStore needs to have a defined type.") OperationFailedException filelessKeyStoreMissingType(); @Message(id = 1061, value = "Invalid value of host context map: '%s' is not valid hostname pattern.") OperationFailedException invalidHostContextMapValue(String hostname); @Message(id = 1062, value = "Value for attribute '%s' is invalid.") OperationFailedException invalidAttributeValue(String attributeName); @Message(id = 1063, value = "LetsEncrypt certificate authority is configured by default.") OperationFailedException letsEncryptNameNotAllowed(); @Message(id = 1064, value = "Failed to load OCSP responder certificate '%s'.") StartException failedToLoadResponderCert(String alias, @Cause Exception exception); @Message(id = 1065, value = "Multiple maximum-cert-path definitions found.") OperationFailedException multipleMaximumCertPathDefinitions(); @Message(id = 1066, value = "Invalid value for cipher-suite-names. %s") OperationFailedException invalidCipherSuiteNames(@Cause Throwable cause, String causeMessage); @Message(id = 1067, value = "Value '%s' is not valid regex.") OperationFailedException invalidRegex(String regex); @Message(id = 1068, value = "Duplicate PolicyContextHandler found for key '%s'.") IllegalStateException duplicatePolicyContextHandler(String key); @Message(id = 1069, value = "Invalid %s loaded, expected %s but received %s.") IllegalStateException invalidImplementationLoaded(String type, String expected, String actual); @Message(id = 1079, value = "Unable to load module '%s'.") RuntimeException unableToLoadModuleRuntime(String module, @Cause Exception cause); }
923a833f8f75ae0044b503b0986d361bc56d2415
1,536
java
Java
netty-io/src/main/java/com/example/common/util/JsonUtil.java
wniter/springboot-demo
ee959f1737c1784dce0d07f3a26e97bebbeb17be
[ "Apache-2.0" ]
null
null
null
netty-io/src/main/java/com/example/common/util/JsonUtil.java
wniter/springboot-demo
ee959f1737c1784dce0d07f3a26e97bebbeb17be
[ "Apache-2.0" ]
null
null
null
netty-io/src/main/java/com/example/common/util/JsonUtil.java
wniter/springboot-demo
ee959f1737c1784dce0d07f3a26e97bebbeb17be
[ "Apache-2.0" ]
null
null
null
23.272727
73
0.582682
999,234
package com.example.common.util; import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.UnsupportedEncodingException; public class JsonUtil { //谷歌 Gson static Gson gson = null; static { //不需要html escape gson=new GsonBuilder() .disableHtmlEscaping() // .excludeFieldsWithoutExposeAnnotation() .create(); } //Object对象转成JSON字符串后,进一步转成字节数组 public static byte[] Object2JsonBytes(Object obj) { //把对象转换成JSON String json = pojoToJson(obj); try { return json.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } //反向:字节数组,转成JSON字符串,转成Object对象 public static <T> T JsonBytes2Object(byte[] bytes, Class<T> tClass) { //字节数组,转成JSON字符串 try { String json = new String(bytes, "UTF-8"); T t = jsonToPojo(json, tClass); return t; } catch (Exception e) { e.printStackTrace(); } return null; } //使用谷歌 Gson 将 POJO 转成字符串 public static String pojoToJson(Object obj) { //String json = new Gson().toJson(obj); String json = gson.toJson(obj); return json; } //使用阿里 Fastjson 将字符串转成 POJO对象 public static <T> T jsonToPojo(String json, Class<T> tClass) { T t = JSONObject.parseObject(json, tClass); return t; } }
923a838abaf04d24e2760574f27ad41f8a6e41a2
2,824
java
Java
src/main/java/org/apache/struts2/webjars/io/EnumerationIterator.java
hiwepy/struts2-webjars-plugin
797460c0bf77702f9efb172d4081e83d00e92ab3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/struts2/webjars/io/EnumerationIterator.java
hiwepy/struts2-webjars-plugin
797460c0bf77702f9efb172d4081e83d00e92ab3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/struts2/webjars/io/EnumerationIterator.java
hiwepy/struts2-webjars-plugin
797460c0bf77702f9efb172d4081e83d00e92ab3
[ "Apache-2.0" ]
null
null
null
29.416667
100
0.546742
999,235
/* * Copyright (c) 2018 (https://github.com/hiwepy). * * 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.apache.struts2.webjars.io; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Set; /** * Aggregates Enumeration instances into one iterator and filters out duplicates. Always keeps one * ahead of the enumerator to protect against returning duplicates. */ public class EnumerationIterator<E> implements Iterator<E> { LinkedList<Enumeration<E>> enums = new LinkedList<Enumeration<E>>(); Enumeration<E> cur = null; E next = null; Set<E> loaded = new HashSet<E>(); public EnumerationIterator<E> addEnumeration(Enumeration<E> e) { if (e.hasMoreElements()) { if (cur == null) { cur = e; next = e.nextElement(); loaded.add(next); } else { enums.add(e); } } return this; } public boolean hasNext() { return (next != null); } public E next() { if (next != null) { E prev = next; next = loadNext(); return prev; } else { throw new NoSuchElementException(); } } private Enumeration<E> determineCurrentEnumeration() { if (cur != null && !cur.hasMoreElements()) { if (enums.size() > 0) { cur = enums.removeLast(); } else { cur = null; } } return cur; } private E loadNext() { if (determineCurrentEnumeration() != null) { E tmp = cur.nextElement(); int loadedSize = loaded.size(); while (loaded.contains(tmp)) { tmp = loadNext(); if (tmp == null || loaded.size() > loadedSize) { break; } } if (tmp != null) { loaded.add(tmp); } return tmp; } return null; } public void remove() { throw new UnsupportedOperationException(); } }
923a83e773df8ca9edbb49e961375c4b34294ebe
17,088
java
Java
src/main/java/org/kiwiproject/collect/KiwiArrays.java
kiwiproject/kiwi
67da2cc0c1ec141c1f301ad9e4e288b02a868d1d
[ "MIT" ]
2
2021-01-26T17:07:10.000Z
2021-04-17T04:54:14.000Z
src/main/java/org/kiwiproject/collect/KiwiArrays.java
kiwiproject/kiwi
67da2cc0c1ec141c1f301ad9e4e288b02a868d1d
[ "MIT" ]
620
2020-03-09T20:17:55.000Z
2022-03-11T18:52:52.000Z
src/main/java/org/kiwiproject/collect/KiwiArrays.java
kiwiproject/kiwi
67da2cc0c1ec141c1f301ad9e4e288b02a868d1d
[ "MIT" ]
null
null
null
39.739535
147
0.64162
999,236
package org.kiwiproject.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import lombok.experimental.UtilityClass; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Comparator; import java.util.Optional; import java.util.stream.IntStream; /** * Utility methods for working with Array instances. */ @UtilityClass public class KiwiArrays { /** * Checks whether the specified array is null or empty. * * @param items the array * @param <T> the type of items in the array * @return {@code true} if array is null or empty; {@code false} otherwise */ public static <T> boolean isNullOrEmpty(T[] items) { return items == null || items.length == 0; } /** * Checks whether the specified array is neither null nor empty. * * @param items the array * @param <T> the type of items in the array * @return {@code true} if array is <em>NOT</em> null or empty; {@code false} otherwise */ public static <T> boolean isNotNullOrEmpty(T[] items) { return !isNullOrEmpty(items); } /** * Checks whether the specified array is non-null and has only one item. * * @param items the array * @param <T> the type of items in the array * @return {@code true} if array is non-null and has exactly one item; {@code false} otherwise */ public static <T> boolean hasOneElement(T[] items) { return nonNull(items) && items.length == 1; } /** * Given an array, sort it according to the natural order, returning a new list. * * @param items the array * @param arrayType the type of the items in the array. Needed to ensure the new array is not {@code Object[]} * @param <T> the type of items in the array * @return a new sorted array */ @SuppressWarnings("unchecked") public static <T> T[] sorted(T[] items, Class<T> arrayType) { checkNonNullInputArray(items); return Arrays.stream(items) .sorted() .toArray(size -> (T[]) Array.newInstance(arrayType, size)); } /** * Given an array, sort it according to the provided {@link Comparator} returning a new array. * * @param items the array * @param comparator a Comparator to be used to compare stream elements * @param arrayType the type of the items in the array. Needed to ensure the new array is not {@code Object[]} * @param <T> the type of items in the array * @return a new sorted array */ @SuppressWarnings("unchecked") public static <T> T[] sorted(T[] items, Comparator<T> comparator, Class<T> arrayType) { checkNonNullInputArray(items); checkNotNull(comparator, "Comparator cannot be null"); return Arrays.stream(items) .sorted(comparator) .toArray(size -> (T[]) Array.newInstance(arrayType, size)); } /** * Return the first element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the first item in items * @throws IllegalArgumentException if the array does not contain at least one item * @throws NullPointerException if the array is null */ public static <T> T first(T[] items) { return nth(items, 1); } /** * Returns an {@link Optional} containing the first element in specified array of items, or an empty optional * if the array is null or empty. * * @param items the array * @param <T> the type of items in the array * @return Optional containing first element if exists, otherwise Optional.empty() */ public static <T> Optional<T> firstIfPresent(T[] items) { return isNotNullOrEmpty(items) ? Optional.of(first(items)) : Optional.empty(); } /** * Return the second element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the second item in items * @throws IllegalArgumentException if the array does not contain at least two items * @throws NullPointerException if the array is null */ public static <T> T second(T[] items) { return nth(items, 2); } /** * Return the third element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the third item in items * @throws IllegalArgumentException if the array does not contain at least three items * @throws NullPointerException if the array is null */ public static <T> T third(T[] items) { return nth(items, 3); } /** * Return the fourth element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the fourth item in items * @throws IllegalArgumentException if the array does not contain at least four items * @throws NullPointerException if the array is null */ public static <T> T fourth(T[] items) { return nth(items, 4); } /** * Return the fifth element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the fifth item in items * @throws IllegalArgumentException if the array does not contain at least five items * @throws NullPointerException if the array is null */ public static <T> T fifth(T[] items) { return nth(items, 5); } /** * Returns the penultimate (second to last) element in the specified array. * * @param items the array * @param <T> the type of items in the array * @return the penultimate item in items * @throws IllegalArgumentException if the array does not contain at least two items * @throws NullPointerException if the array is null * @see #secondToLast(Object[]) */ public static <T> T penultimate(T[] items) { checkMinimumSize(items, 2); return nth(items, items.length - 1); } /** * Synonym for {@link #penultimate(Object[])}. * * @param items the array * @param <T> the type of items in the array * @return the penultimate item in items * @throws IllegalArgumentException if the array does not contain at least two items * @throws NullPointerException if the array is null * @see #penultimate(Object[]) */ public static <T> T secondToLast(T[] items) { return penultimate(items); } /** * Returns the last element in the specified array of items. * * @param items the array * @param <T> the type of items in the array * @return the last item in the list * @throws IllegalArgumentException if the array does not contain at least one item * @throws NullPointerException if the array is null */ public static <T> T last(T[] items) { return nth(items, items.length); } /** * Returns an {@link Optional} containing the last element in specified array of items, or an empty optional * if the array is null or empty. * * @param items the array * @param <T> the type of items in the array * @return Optional containing last element if exists, otherwise Optional.empty() */ public static <T> Optional<T> lastIfPresent(T[] items) { return isNotNullOrEmpty(items) ? Optional.of(last(items)) : Optional.empty(); } /** * Return the nth element in the specified array of items, starting at one for the first element, two for the * second, etc. * * @param items the array * @param number the number of the element to retrieve, starting at one (<i>not zero</i>) * @param <T> the type of items in the array * @return the nth item in items * @throws IllegalArgumentException if the array does not contain at least number items * @throws NullPointerException if the array is null */ public static <T> T nth(T[] items, int number) { checkMinimumSize(items, number); return items[number - 1]; } /** * Returns a array of the collection elements with duplicates stripped out. * * @param collection the collection of values * @param arrayType the type of the items in the array. Needed to ensure the new array is not {@code Object[]} * @param <T> the type of items in the collection * @return a new array with only unique elements * @throws IllegalArgumentException if the collection is null */ public static <T> T[] distinct(T[] collection, Class<T> arrayType) { checkArgument(nonNull(collection), "collection can not be null"); return distinctOrNull(collection, arrayType); } /** * Returns a array of the collection elements with duplicates stripped out or `null` if a null value is passed in. * * @param collection the collection of values * @param arrayType the type of the items in the array. Needed to ensure the new array is not {@code Object[]} * @param <T> the type of items in the collection * @return a new array with only unique elements or null. */ @SuppressWarnings({"unchecked", "java:S1168"}) //Ignoring Sonar warning to return empty array since this method's name says it will return null public static <T> T[] distinctOrNull(T[] collection, Class<T> arrayType) { if (isNull(collection)) { return null; } return Arrays.stream(collection) .distinct() .toArray(val -> (T[]) Array.newInstance(arrayType, val)); } /** * Returns a new array with the same elements and the same size as the original, however the initial position in the array * is now the element specified by the "startOffset" and the array wraps around through the contents to end with "startOffset" - 1 * * @param input the original array * @param startOffset the desired offset to start the new array * @param arrayType the type of the items in the array. Needed to ensure the new array is not {@code Object[]} * @param <T> the type of the items in the array * @return a new array starting at the desired offset */ @SuppressWarnings("unchecked") public static <T> T[] newArrayStartingAtCircularOffset(T[] input, long startOffset, Class<T> arrayType) { var size = input.length; return IntStream.range(0, size) .mapToObj(i -> input[(int) (startOffset + i) % size]) .toArray(val -> (T[]) Array.newInstance(arrayType, val)); } /** * Returns a new array containing the portion of the given array excluding the first element. * * @param items the array * @param <T> the type of the items in the array * @return a new array containing the given array excluding the first item * @throws NullPointerException if the array is null */ public static <T> T[] subArrayExcludingFirst(T[] items) { checkNonNullInputArray(items); if (items.length == 0) { return zeroSubArray(items); } return Arrays.copyOfRange(items, 1, items.length); } /** * Returns a new array containing the portion of the given array excluding the last element. * * @param items the array * @param <T> the type of the items in the array * @return a new array containing the given array excluding the last item * @throws NullPointerException if the array is null */ public static <T> T[] subArrayExcludingLast(T[] items) { checkNonNullInputArray(items); if (items.length == 0) { return zeroSubArray(items); } return Arrays.copyOfRange(items, 0, items.length-1); } private static <T> T[] zeroSubArray(T[] items) { return Arrays.copyOf(items, 0); } /** * Returns a new array containing the portion of the given array starting at the given logical element number, where the * numbers start at one, until and including the last element in the array. This is useful if something is using * one-based element numbers for some reason. Use {@link #subArrayFromIndex(Object[], int)} if you want to use zero-based * list indices. * * @param items the array * @param number the number of the element to start the subarray, starting at one (<i>not zero</i>) * @param <T> the type of items in the array * @return a new array containing the given array, starting at the given one-based number * @throws NullPointerException if the array is null * @throws IllegalArgumentException if the given number is negative or is higher than the size of the array */ public static <T> T[] subArrayFrom(T[] items, int number) { checkMinimumSize(items, number); return Arrays.copyOfRange(items, number - 1, items.length); } /** * Returns a new array containing the portion of the given array starting at the given index, until and including the last * element in the array. * * @param items the array * @param index the index in the array to start the subarray, zero-based like normal Array accessors * @param <T> the type of items in the array * @return a new array containing the given array, starting at the given zero-based index * @throws NullPointerException if the array is null * @throws IllegalArgumentException if the given index is negative or is higher than the last index in the array */ public static <T> T[] subArrayFromIndex(T[] items, int index) { checkMinimumSize(items, index + 1); return Arrays.copyOfRange(items, index, items.length); } /** * Returns a new array containing the "first N" elements of the input array. * <p> * If the given number is larger than the size of the array, the entire array is returned, rather than throw * an exception. In this case, the input array is returned directly, i.e. {@code return items}. * * @param items the array * @param number the number of items wanted from the start of the array * @param <T> the type of items in the array * @return a new array containing the given array containing the last {@code number} elements */ public static <T> T[] firstN(T[] items, int number) { checkNonNullInputArray(items); checkMinSizeIsPositive(number); if (number > items.length) { return items; } return Arrays.copyOfRange(items, 0, number); } /** * Returns a new array containing the "last N" elements of the input array. * <p> * If the given number is larger than the size of the array, the entire array is returned, rather than throw * an exception. In this case, the input array is returned directly, i.e. {@code return items}. * * @param items the array * @param number the number of items wanted from the end of the array * @param <T> the type of items in the array * @return a new array containing the given array containing the first {@code number} elements */ public static <T> T[] lastN(T[] items, int number) { checkNonNullInputArray(items); checkMinSizeIsPositive(number); if (number > items.length) { return items; } var startIndex = items.length - number; return Arrays.copyOfRange(items, startIndex, items.length); } /** * Checks that the given array is not null and has the given minimum size. * * @param items the array * @param minSize the minimum required size * @param <T> the type of the items in the array * @throws NullPointerException if the array is null * @throws IllegalArgumentException if minSize is not positive or the array does not contain minSize elements */ public static <T> void checkMinimumSize(T[] items, int minSize) { checkNonNullInputArray(items); checkMinSizeIsPositive(minSize); checkArgument(items.length >= minSize, "expected at least %s items (actual size: %s)", minSize, items.length); } private static void checkMinSizeIsPositive(int minSize) { checkArgument(minSize > 0, "number must be positive"); } /** * Checks that the given array is not null. * * @param items the array * @param <T> the type of items in the array * @throws NullPointerException if the array is null */ public static <T> void checkNonNullInputArray(T[] items) { checkNotNull(items, "items cannot be null"); } }
923a84a27b942a595ae1e8915dd5220a3d52b2cb
3,003
java
Java
src/main/java/tech/gusavila92/apache/http/message/BasicHeader.java
AlexanderShirokih/java-android-websocket-client
e978d45a7ea79e1b41d1b32d22ac08681e435d14
[ "Apache-2.0" ]
93
2017-09-14T09:14:44.000Z
2022-01-08T15:01:51.000Z
src/main/java/tech/gusavila92/apache/http/message/BasicHeader.java
AlexanderShirokih/java-android-websocket-client
e978d45a7ea79e1b41d1b32d22ac08681e435d14
[ "Apache-2.0" ]
23
2017-04-23T19:29:44.000Z
2021-11-29T17:18:04.000Z
src/main/java/tech/gusavila92/apache/http/message/BasicHeader.java
AlexanderShirokih/java-android-websocket-client
e978d45a7ea79e1b41d1b32d22ac08681e435d14
[ "Apache-2.0" ]
27
2017-05-11T18:58:09.000Z
2022-01-27T23:20:14.000Z
31.28125
79
0.668332
999,237
/* * ==================================================================== * 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. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package tech.gusavila92.apache.http.message; import java.io.Serializable; import tech.gusavila92.apache.http.Header; import tech.gusavila92.apache.http.HeaderElement; import tech.gusavila92.apache.http.ParseException; import tech.gusavila92.apache.http.annotation.ThreadingBehavior; import tech.gusavila92.apache.http.annotation.Contract; import tech.gusavila92.apache.http.util.Args; /** * Basic implementation of {@link Header}. * * @since 4.0 */ @Contract(threading = ThreadingBehavior.IMMUTABLE) public class BasicHeader implements Header, Cloneable, Serializable { private static final long serialVersionUID = -5427236326487562174L; private final String name; private final String value; /** * Constructor with name and value * * @param name the header name * @param value the header value */ public BasicHeader(final String name, final String value) { super(); this.name = Args.notNull(name, "Name"); this.value = value; } @Override public String getName() { return this.name; } @Override public String getValue() { return this.value; } @Override public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.INSTANCE.formatHeader(null, this).toString(); } @Override public HeaderElement[] getElements() throws ParseException { if (this.value != null) { // result intentionally not cached, it's probably not used again return BasicHeaderValueParser.parseElements(this.value, null); } else { return new HeaderElement[] {}; } } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
923a86a6922f3b7fff18ab4b92344d6e5dcfa4d8
918
java
Java
app/src/main/java/perfectstrong/sonako/sonakoreader/database/GenresConverter.java
perfectstrong/SonakoReader
b1c2f67cf248c0de0a3db49f6b7b33abbf8c7cac
[ "MIT" ]
2
2019-04-28T21:13:50.000Z
2019-05-15T07:41:55.000Z
app/src/main/java/perfectstrong/sonako/sonakoreader/database/GenresConverter.java
perfectstrong/SonakoReader
b1c2f67cf248c0de0a3db49f6b7b33abbf8c7cac
[ "MIT" ]
10
2019-05-10T12:06:14.000Z
2019-06-22T09:45:30.000Z
app/src/main/java/perfectstrong/sonako/sonakoreader/database/GenresConverter.java
perfectstrong/SonakoReader
b1c2f67cf248c0de0a3db49f6b7b33abbf8c7cac
[ "MIT" ]
null
null
null
27.818182
75
0.636166
999,238
package perfectstrong.sonako.sonakoreader.database; import java.util.Arrays; import java.util.List; import androidx.room.TypeConverter; @SuppressWarnings("WeakerAccess") public class GenresConverter { public static final String SEPARATOR = ","; public static final String REPLACEMENT = " "; @TypeConverter public List<String> fromCompressedString(String genres) { if (genres == null) return null; else return Arrays.asList(genres.split(SEPARATOR)); } @TypeConverter public String fromList(List<String> genres) { if (genres == null || genres.isEmpty()) return null; StringBuilder str = new StringBuilder(genres.get(0)); for (int i = 1; i < genres.size(); i++) { str.append(SEPARATOR) .append(genres.get(i).replace(SEPARATOR, REPLACEMENT)); } return str.toString(); } }
923a872aad0e02896bcfbebed010f1a7125bc297
138
java
Java
igloo/igloo-components/igloo-component-jpa-more-test/src/test/java/test/jpa/more/business/JpaMoreTestBusinessPackage.java
igloo-project/igloo-parent
bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999
[ "Apache-2.0" ]
17
2017-10-19T07:03:44.000Z
2022-01-17T20:44:22.000Z
igloo/igloo-components/igloo-component-jpa-more-test/src/test/java/test/jpa/more/business/JpaMoreTestBusinessPackage.java
igloo-project/igloo-parent
bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999
[ "Apache-2.0" ]
38
2018-01-22T15:57:35.000Z
2022-01-14T16:28:45.000Z
igloo/igloo-components/igloo-component-jpa-more-test/src/test/java/test/jpa/more/business/JpaMoreTestBusinessPackage.java
igloo-project/igloo-parent
bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999
[ "Apache-2.0" ]
6
2017-10-19T07:03:50.000Z
2020-08-06T16:12:35.000Z
17.25
58
0.782609
999,239
package test.jpa.more.business; public final class JpaMoreTestBusinessPackage { // NOSONAR private JpaMoreTestBusinessPackage() {}; }
923a880beacdbdcca24f577e5c2a3c5ad46b00e7
767
java
Java
Encapsulamento/Principal.java
JoaoV-A01/ETECCT_2-B_DS
f1058e4e88a88cf6a052363b57ce1fb25efa2a66
[ "MIT" ]
null
null
null
Encapsulamento/Principal.java
JoaoV-A01/ETECCT_2-B_DS
f1058e4e88a88cf6a052363b57ce1fb25efa2a66
[ "MIT" ]
null
null
null
Encapsulamento/Principal.java
JoaoV-A01/ETECCT_2-B_DS
f1058e4e88a88cf6a052363b57ce1fb25efa2a66
[ "MIT" ]
null
null
null
21.305556
59
0.647979
999,240
public class Principal { public static void main(String[] args) { Caminhão cami = new Caminhão("Vermelho","Honda","lulu"); System.out.println("CAMINHÃO"); cami.setCor("Rosa"); cami.setModelo("Toyota"); cami.setDono("Sabrina de Mewlo"); cami.apresentarCaminhão(); Carro car = new Carro("Amarelo","Ford","Swain de Noxus"); System.out.println("CARRO"); car.setCor("Vermelho"); car.setModelo("Volkswagen"); car.setDono("Pou de Santos"); car.apresentarCarro(); Moto mot = new Moto(); mot.cor = "Cinza"; mot.modelo = "Corsa"; mot.dono = "Pauilin de Souza"; System.out.println("MOTO"); mot.alterarCor("Azul"); mot.alterarModelo("Chevrolet"); mot.alterarDono("Junin Almeida"); mot.apresentarMoto(); } }
923a88b25c8b662ac4857cb47c4b67022c37b82f
8,505
java
Java
app/src/main/java/top/geek_studio/chenlongcould/musicplayer/fragment/FileViewFragment.java
AugustToko/ACG-Player
1a76dcf2a7a4cb825adbe120ca445a08c79b00c8
[ "Apache-2.0" ]
6
2019-05-26T03:03:54.000Z
2020-02-24T15:53:03.000Z
app/src/main/java/top/geek_studio/chenlongcould/musicplayer/fragment/FileViewFragment.java
AugustToko/ACG-Player
1a76dcf2a7a4cb825adbe120ca445a08c79b00c8
[ "Apache-2.0" ]
86
2019-05-24T05:07:04.000Z
2019-07-13T04:46:43.000Z
app/src/main/java/top/geek_studio/chenlongcould/musicplayer/fragment/FileViewFragment.java
AugustToko/ACG-Player
1a76dcf2a7a4cb825adbe120ca445a08c79b00c8
[ "Apache-2.0" ]
3
2019-02-19T21:23:05.000Z
2019-12-16T13:02:40.000Z
30.703971
146
0.734862
999,241
package top.geek_studio.chenlongcould.musicplayer.fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; import org.jetbrains.annotations.NotNull; import top.geek_studio.chenlongcould.geeklibrary.OpenFile; import top.geek_studio.chenlongcould.musicplayer.Data; import top.geek_studio.chenlongcould.musicplayer.GlideApp; import top.geek_studio.chenlongcould.musicplayer.R; import top.geek_studio.chenlongcould.musicplayer.activity.main.MainActivity; import top.geek_studio.chenlongcould.musicplayer.databinding.FragmentFileViewerBinding; import top.geek_studio.chenlongcould.musicplayer.model.Item; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; // FIXME: 2019/5/22 bugs... public final class FileViewFragment extends BaseListFragment { public static final String TAG = "FileViewFragment"; private FragmentFileViewerBinding mFileViewerBinding; private MainActivity mMainActivity; private List<File> mFileItems = new ArrayList<>(); private MyAdapter mMyAdapter; private File mCurrentFile; public static FileViewFragment newInstance() { return new FileViewFragment(); } @Override public FragmentType getFragmentType() { return FragmentType.FILE_VIEW_FRAGMENT; } @Override public void onDestroy() { super.onDestroy(); mFileItems.clear(); } @Override public void reloadData() { super.reloadData(); mFileItems.clear(); initData(); } private void initData() { if (ContextCompat.checkSelfPermission(mMainActivity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { final File file = Environment.getExternalStorageDirectory(); if (file != null && file.exists()) { List<File> files = Arrays.asList(file.listFiles()); if (files != null && files.size() > 0) { mFileItems.addAll(files); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mFileItems.sort(File::compareTo); } mCurrentFile = file; mMyAdapter.notifyDataSetChanged(); } } } @Override public void onAttach(@NotNull Context context) { super.onAttach(context); mMainActivity = (MainActivity) context; } @NotNull @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mFileViewerBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_file_viewer, container, false); mFileViewerBinding.includeRecyclerView.recyclerView.setLayoutManager(new LinearLayoutManager(mMainActivity)); mFileViewerBinding.includeRecyclerView.recyclerView.addItemDecoration(new DividerItemDecoration(mMainActivity, DividerItemDecoration.VERTICAL)); mMyAdapter = new MyAdapter(mFileItems); mFileViewerBinding.includeRecyclerView.recyclerView.setAdapter(mMyAdapter); initData(); return mFileViewerBinding.getRoot(); } @Override public void onDetach() { mFileItems.clear(); super.onDetach(); } public File getCurrentFile() { return mCurrentFile; } public void onBackPressed() { mCurrentFile = mCurrentFile.getParentFile(); mFileItems.clear(); mFileItems.addAll(new ArrayList<>(Arrays.asList(mCurrentFile.listFiles()))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mFileItems.sort(File::compareTo); } mMyAdapter.notifyDataSetChanged(); } @Override public boolean removeItem(@Nullable Item item) { // none return false; } @Override public boolean addItem(@Nullable Item item) { // none return false; } class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter { private List<File> mFiles; MyAdapter(List<File> files) { mFiles = files; } String getFileSize(File f) { float fileSize = f.length() / 1024; //kb int sizeLength = String.valueOf((int) fileSize).length(); if (sizeLength <= 3) { return (double) Math.round(fileSize * 100) / 100 + "KB"; } else if (sizeLength < 7) { return (double) Math.round(fileSize / 1024 * 100) / 100 + "MB"; } else { return (double) Math.round(fileSize / 1024 / 1024 * 100) / 100 + "GB"; } } @Override public void onBindViewHolder(@NonNull MyAdapter.ViewHolder holder, int position) { if (position == 0) holder.itemView.setPadding(0, MainActivity.PADDING, 0, 0); // show file size (b kb mb gb) if (!mFiles.get(position).isDirectory()) { holder.subTile_2.setText(String.valueOf(getFileSize(mFiles.get(holder.getAdapterPosition())))); } else { holder.subTile_2.setText("---"); } //local holder.subTitle.setText(String.valueOf(Data.S_SIMPLE_DATE_FORMAT_FILE.format(new Date(mFiles.get(position).lastModified())))); holder.itemText.setText(mFiles.get(position).getName()); if (mFiles.get(position).isDirectory()) { GlideApp.with(mMainActivity).load(R.drawable.ic_folder_24px).into(holder.itemIco); } else { File file = mFiles.get(position); String end = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase(); if ("mp4".equals(end) || "avi".equals(end) || "wmv".equals(end) || "mov".equals(end)) { GlideApp.with(mMainActivity).load(R.drawable.ic_movie_creation_24px).into(holder.itemIco); } else if ("jpg".equals(end) || "png".equals(end) || "gif".equals(end) || "psd".equals(end) || "ai".equals(end)) { GlideApp.with(mMainActivity).load(R.drawable.ic_image_24px).into(holder.itemIco); } else if ("mp3".equals(end) || "wav".equals(end) || "dsd".equals(end) || "dst".equals(end) || "ogg".equals(end) || "flac".equals(end)) { GlideApp.with(mMainActivity).load(R.drawable.ic_audiotrack_24px).into(holder.itemIco); } else { GlideApp.with(mMainActivity).load(R.drawable.ic_insert_drive_file_24px).into(holder.itemIco); } } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_file_item, parent, false); ViewHolder holder = new ViewHolder(view); holder.itemView.setOnClickListener(v -> { if (mFileItems.get(holder.getAdapterPosition()).isFile()) { Intent intent; OpenFile.init(mMainActivity.getPackageName()); if ((intent = OpenFile.openFile(mMainActivity, mFileItems.get(holder.getAdapterPosition()).getPath())) != null) { startActivity(intent); } else { Toast.makeText(mMainActivity, "Open File", Toast.LENGTH_LONG).show(); } return; } final ArrayList<File> temp = new ArrayList<>(Arrays.asList(mFileItems.get(holder.getAdapterPosition()).listFiles())); mCurrentFile = mFiles.get(holder.getAdapterPosition()); mFileItems.clear(); mFileItems.addAll(temp); //sort if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mFileItems.sort(File::compareTo); } mMyAdapter.notifyDataSetChanged(); }); return holder; } @NonNull @Override public String getSectionName(int position) { return String.valueOf(mFileItems.get(position).getName().charAt(0)); } @Override public void onViewRecycled(@NonNull ViewHolder holder) { super.onViewRecycled(holder); // reset holder.itemView.setPadding(0, 0, 0, 0); } @Override public int getItemCount() { return mFileItems.size(); } class ViewHolder extends RecyclerView.ViewHolder { ImageView itemIco; TextView itemText; TextView subTitle; TextView subTile_2; ViewHolder(View itemView) { super(itemView); itemIco = itemView.findViewById(R.id.item_ico); itemText = itemView.findViewById(R.id.item_text); subTitle = itemView.findViewById(R.id.item_small_text); subTile_2 = itemView.findViewById(R.id.item_small_text_2); } } } }
923a89304d52340614898c9cd5415eccf78baca3
1,673
java
Java
endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java
rishisharma-google/endpoints-java
39b73744c9ee4e39e94d6d11638ba34810e5de07
[ "Apache-2.0" ]
36
2016-09-02T13:02:04.000Z
2022-01-22T16:22:43.000Z
endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java
rishisharma-google/endpoints-java
39b73744c9ee4e39e94d6d11638ba34810e5de07
[ "Apache-2.0" ]
188
2016-09-01T22:23:32.000Z
2022-03-09T08:30:25.000Z
endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java
rishisharma-google/endpoints-java
39b73744c9ee4e39e94d6d11638ba34810e5de07
[ "Apache-2.0" ]
28
2016-09-01T22:04:40.000Z
2021-11-12T15:32:53.000Z
40.804878
98
0.762104
999,242
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.server.spi.config; import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.auth.common.User; import javax.servlet.http.HttpServletRequest; /** * Interface for Endpoints authenticators. To create a custom authenticator, implement and assign * your authenticator class in the {@code authenticator} configuration property. */ // TODO: Figure out some way to pass in configuration to the custom authenticator similar // (but more generialized) to how the current Google authenticator takes scopes, client ids, etc. // Maybe some configured string that either gets passed into the constructor or the authenticate // method. // Or maybe this is good enough already. Just create a separate Authenticator class for each // configuration you want. public interface Authenticator { /** * Authenticates the user from {@code request}. * * @return The authenticated user or null if there is no auth or auth has failed. */ User authenticate(HttpServletRequest request) throws ServiceException; }
923a8993affb46b33ad2e160dc0ac60c165e8a57
229
java
Java
server/src/main/java/org/cloudfoundry/identity/uaa/mfa/exception/MfaProviderUpdateIsNotAllowed.java
rwinch/uaa
490484f64bc1ea81129d9192f4b3d372fb9bcfa9
[ "Apache-2.0" ]
1
2019-10-22T09:08:22.000Z
2019-10-22T09:08:22.000Z
server/src/main/java/org/cloudfoundry/identity/uaa/mfa/exception/MfaProviderUpdateIsNotAllowed.java
rwinch/uaa
490484f64bc1ea81129d9192f4b3d372fb9bcfa9
[ "Apache-2.0" ]
39
2019-05-24T18:41:59.000Z
2019-07-04T05:03:25.000Z
server/src/main/java/org/cloudfoundry/identity/uaa/mfa/exception/MfaProviderUpdateIsNotAllowed.java
rwinch/uaa
490484f64bc1ea81129d9192f4b3d372fb9bcfa9
[ "Apache-2.0" ]
1
2022-02-05T04:25:13.000Z
2022-02-05T04:25:13.000Z
28.625
62
0.759825
999,243
package org.cloudfoundry.identity.uaa.mfa.exception; public class MfaProviderUpdateIsNotAllowed extends Exception { public MfaProviderUpdateIsNotAllowed() { super("Updating an MFA provider is not allowed."); } }
923a89dd769c5a90e8ab51b6cbba7e1a65266531
3,960
java
Java
cameraview/src/main/java/com/otaliastudios/cameraview/engine/lock/ExposureLock.java
Ravens0610/CameraView
daf7a0bf44a733fa6d5fef33382a36d728ab6bbd
[ "MIT" ]
4,436
2017-08-13T23:28:11.000Z
2022-03-31T08:57:15.000Z
cameraview/src/main/java/com/otaliastudios/cameraview/engine/lock/ExposureLock.java
Ravens0610/CameraView
daf7a0bf44a733fa6d5fef33382a36d728ab6bbd
[ "MIT" ]
1,102
2017-08-25T08:04:56.000Z
2022-03-31T15:51:17.000Z
cameraview/src/main/java/com/otaliastudios/cameraview/engine/lock/ExposureLock.java
Ravens0610/CameraView
daf7a0bf44a733fa6d5fef33382a36d728ab6bbd
[ "MIT" ]
909
2017-08-23T11:23:19.000Z
2022-03-31T03:19:19.000Z
44
97
0.667424
999,244
package com.otaliastudios.cameraview.engine.lock; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import com.otaliastudios.cameraview.CameraLogger; import com.otaliastudios.cameraview.engine.action.ActionHolder; @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public class ExposureLock extends BaseLock { private final static String TAG = ExposureLock.class.getSimpleName(); private final static CameraLogger LOG = CameraLogger.create(TAG); @Override protected boolean checkIsSupported(@NonNull ActionHolder holder) { boolean isNotLegacy = readCharacteristic( CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL, -1) != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; // Not sure we should check aeMode as well, probably all aeModes support locking, // but this should not be a big issue since we're not even using different AE modes. Integer aeMode = holder.getBuilder(this).get(CaptureRequest.CONTROL_AE_MODE); boolean isAEOn = aeMode != null && (aeMode == CameraCharacteristics.CONTROL_AE_MODE_ON || aeMode == CameraCharacteristics.CONTROL_AE_MODE_ON_ALWAYS_FLASH || aeMode == CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH || aeMode == CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE || aeMode == 5 /* CameraCharacteristics.CONTROL_AE_MODE_ON_EXTERNAL_FLASH, API 28 */); boolean result = isNotLegacy && isAEOn; LOG.i("checkIsSupported:", result); return result; } @Override protected boolean checkShouldSkip(@NonNull ActionHolder holder) { CaptureResult lastResult = holder.getLastResult(this); if (lastResult != null) { Integer aeState = lastResult.get(CaptureResult.CONTROL_AE_STATE); boolean result = aeState != null && aeState == CaptureResult.CONTROL_AE_STATE_LOCKED; LOG.i("checkShouldSkip:", result); return result; } else { LOG.i("checkShouldSkip: false - lastResult is null."); return false; } } @Override protected void onStarted(@NonNull ActionHolder holder) { int cancelTrigger = Build.VERSION.SDK_INT >= 23 ? CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL : CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE; holder.getBuilder(this).set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, cancelTrigger); holder.getBuilder(this).set(CaptureRequest.CONTROL_AE_LOCK, true); holder.applyBuilder(this); } @Override public void onCaptureCompleted(@NonNull ActionHolder holder, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { super.onCaptureCompleted(holder, request, result); Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); LOG.i("processCapture:", "aeState:", aeState); if (aeState == null) return; switch (aeState) { case CaptureRequest.CONTROL_AE_STATE_LOCKED: { setState(STATE_COMPLETED); break; } case CaptureRequest.CONTROL_AE_STATE_PRECAPTURE: case CaptureRequest.CONTROL_AE_STATE_CONVERGED: case CaptureRequest.CONTROL_AE_STATE_INACTIVE: case CaptureRequest.CONTROL_AE_STATE_SEARCHING: case CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED: { // Wait... break; } } } }
923a8b351a0b46ed7a1b1a8942682668d5e782f3
5,035
java
Java
asset-collect/src/main/java/com/ruoyi/robot/domain/TLcRobotTask.java
liurunkaiGit/asset
ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff
[ "MIT" ]
null
null
null
asset-collect/src/main/java/com/ruoyi/robot/domain/TLcRobotTask.java
liurunkaiGit/asset
ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff
[ "MIT" ]
3
2021-02-03T19:36:18.000Z
2021-09-20T21:00:33.000Z
asset-collect/src/main/java/com/ruoyi/robot/domain/TLcRobotTask.java
liurunkaiGit/asset
ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff
[ "MIT" ]
1
2020-11-24T01:06:00.000Z
2020-11-24T01:06:00.000Z
19.291188
190
0.569215
999,245
package com.ruoyi.robot.domain; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import lombok.Data; import lombok.experimental.Accessors; import java.math.BigDecimal; import java.util.Date; import java.util.Set; /** * 【请填写功能名称】对象 t_lc_robot_task * * @author liurunkai * @date 2020-03-18 */ @Data @Accessors(chain = true) public class TLcRobotTask extends BaseEntity { private static final long serialVersionUID = 1L; /** * 主键id */ private Long id; /** * 任务id */ // @Excel(name = "任务id") private Long taskId; /** * 机器人任务id */ @Excel(name = "任务id") private Integer robotTastId; /** * 案件编号 */ @Excel(name = "机构案件号") private String caseNo; /** * 客户名称 */ @Excel(name = "客户姓名") private String curName; /** * 任务名称 */ @Excel(name = "会话名称") private String taskName; /** * 业务归属人 */ @Excel(name = "业务归属人 ") private String ownerName; /** * 手别 */ @Excel(name = "手别") private String transferType; /** * 委案金额 */ @Excel(name = "委案金额") private BigDecimal arrearsTotal; /** * 话术名称 */ @Excel(name = "话术名称") private String speechCraftName; /** * 任务创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "任务创建时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 任务拨打结束时间 */ @Excel(name = "拨打结束时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") private Date callEndDate; /** * 机器人任务状态 */ // @Excel(name = "机器人任务状态", readConverterExp = "1=外呼中,2=已完成,4=暂停,6=停止,50=拉回") private Integer robotTaskStatus; /** * 客户意向标签 */ @Excel(name = "意向标签") private String resultValueAlias; /** * 通话状态 */ @Excel(name = "通话状态", readConverterExp = "0=已接听,1=拒接,2=无法接通,3=主叫号码不可用,4=空号,5=关机,6=占线,7=停机,8=未接,9=主叫欠费,10=呼损,11=黑名单,22=线路盲区") private String callStatus; /** * 通话时长 */ @Excel(name = "通话时长") private String callLen; /** * 任务状态 */ @Excel(name = "任务状态", readConverterExp = "1=未分配,2=已分配,3=已结案") private Integer taskStatus; /** * 任务类型 */ @Excel(name = "任务类型", readConverterExp = "1=初次生成,2=重新分派,3=临时代理,4=协助催收,5=临时代理回收,6=异常案件转分配,7=结案转移,8=灰色队列,9=从灰色队列移除,10=协助催收申请,11=停催申请,12=停止催收,13=停止催收激活,14=停止催收拒绝,15=拒绝协催,16=机器人协催,17=机器人拉回") private Integer taskType; /** * 通话内容 */ // @Excel(name = "通话内容") private String callContent; /** * 通话录音 */ @Excel(name = "通话录音") private String callRadio; /** * 拨打开始时间 */ // @Excel(name = "拨打开始时间", width = 30, dateFormat = "yyyy-MM-dd") private Date callStartDate; /** * 客户手机号 */ // @Excel(name = "客户手机号") private String phone; /** * 所属机构id */ // @Excel(name = "所属机构id") private String orgId; /** * 所属机构名称 */ // @Excel(name = "所属机构名称") private String orgName; private String robot; /** * 呼叫类型,1:重复呼叫,2:停止呼叫,3:第二天呼叫 */ // @Excel(name = "呼叫类型,1:重复呼叫,2:停止呼叫,3:第二天呼叫") private Integer isRecall; /** * 连续呼叫天数 */ // @Excel(name = "连续呼叫天数") private Integer continueDays; /** * 当天连续呼叫次数 */ // @Excel(name = "当天连续呼叫次数") private Integer continueFrequency; // ===== private Date startCreateTime; private Date endCreateTime; private Date startCallEndDate; private Date endCallEndDate; private String startCallLen; private String endCallLen; private Set<Long> deptIds; @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 自由查询SQL */ private String freeSQL; /** * 电话码键值 */ // @Excel(name = "电话码键值") private String callSign; /** * 电话码中文 */ // @Excel(name = "电话码中文") private String callSignValue; /** * 修改人 */ // @Excel(name = "修改人") private Long modifyBy; /** * 修改时间 */ // @Excel(name = "修改时间", width = 30, dateFormat = "yyyy-MM-dd") private Date modifyTime; /** * 呼入回调时间 */ // @Excel(name = "呼入回调时间", width = 30, dateFormat = "yyyy-MM-dd") private Date callBackTime; // ====字段动态查询====== // private Date start_create_time; // private Date end_create_time; // private Date start_call_end_date; // private Date end_call_end_date; // private String owner_name; // private String task_type; // private String start_call_len; // private String end_call_len; // private String result_value_alias; // private String transfer_type; // private String speech_craft_name; // private String cur_name; // private String sql; private String actionCode; }
923a8b521df3cac1131fe50d0640068a8a85d3db
4,583
java
Java
src/main/java/com/github/ivangomes/elementrank/ElementRankIndexBuilder.java
ivan-gomes/uml-search-engine
2f32f21b81d5dcf20796af8c6fab84edf389f65d
[ "Apache-2.0" ]
2
2017-12-23T09:42:40.000Z
2019-03-13T04:21:45.000Z
src/main/java/com/github/ivangomes/elementrank/ElementRankIndexBuilder.java
ivan-gomes/uml-search-engine
2f32f21b81d5dcf20796af8c6fab84edf389f65d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/ivangomes/elementrank/ElementRankIndexBuilder.java
ivan-gomes/uml-search-engine
2f32f21b81d5dcf20796af8c6fab84edf389f65d
[ "Apache-2.0" ]
null
null
null
52.079545
360
0.676849
999,246
package com.github.ivangomes.elementrank; import com.github.ivangomes.elasticsearch.TypeFieldsQuery; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequestBuilder; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.DisMaxQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; @ToString @RequiredArgsConstructor @Accessors(fluent = true, chain = true) @Setter public class ElementRankIndexBuilder implements Supplier<ElementRankIndex> { @NonNull private final TransportClient client; @NonNull private final String index, type; private int scrollKeepAlive, size; private boolean undirectedGraph; @Override public ElementRankIndex get() { ElementRankIndex elementRankIndex = new ElementRankIndex(); List<String> idFields = new TypeFieldsQuery(client, index, type).get().entrySet().stream().filter(entry -> !entry.getKey().isEmpty() && entry.getKey().get(entry.getKey().size() - 1).matches("\\w+Id(s)?") && entry.getValue().equals("text")).map(Map.Entry::getKey).map(path -> path.stream().collect(Collectors.joining("."))).collect(Collectors.toList()); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type); if (scrollKeepAlive != 0) { searchRequestBuilder.setScroll(new TimeValue(scrollKeepAlive)); } if (size != 0) { searchRequestBuilder.setSize(size); } SearchResponse elementsResponse = searchRequestBuilder.get(); int i = 0; do { for (SearchHit elementHit : elementsResponse.getHits().getHits()) { System.out.println("[INFO] [" + ++i + "] Indexing " + elementHit.getId()); elementRankIndex.addPage(elementHit.getId()); DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery(); idFields.forEach(idField -> disMaxQueryBuilder.add(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery(idField + ".keyword", elementHit.getId())))); SearchRequestBuilder incomingLinksBuilder = client.prepareSearch(this.index).setTypes(type).setQuery(disMaxQueryBuilder); if (scrollKeepAlive != 0) { incomingLinksBuilder.setScroll(new TimeValue(scrollKeepAlive)); } if (size != 0) { incomingLinksBuilder.setSize(size); } SearchResponse incomingLinksResponse = incomingLinksBuilder.get(); do { for (SearchHit incomingLinkHit : incomingLinksResponse.getHits().getHits()) { elementRankIndex.addLink(incomingLinkHit.getId(), elementHit.getId()); if (undirectedGraph) { elementRankIndex.addLink(elementHit.getId(), incomingLinkHit.getId()); } } SearchScrollRequestBuilder incomingLinksSearchScrollRequestBuilder = client.prepareSearchScroll(incomingLinksResponse.getScrollId()); if (scrollKeepAlive != 0) { incomingLinksSearchScrollRequestBuilder.setScroll(new TimeValue(scrollKeepAlive)); } incomingLinksResponse = incomingLinksSearchScrollRequestBuilder.execute().actionGet(); } while (incomingLinksResponse.getHits().getHits().length != 0); client.prepareClearScroll().addScrollId(incomingLinksResponse.getScrollId()).get(); } SearchScrollRequestBuilder searchScrollRequestBuilder = client.prepareSearchScroll(elementsResponse.getScrollId()); if (scrollKeepAlive != 0) { searchScrollRequestBuilder.setScroll(new TimeValue(scrollKeepAlive)); } elementsResponse = searchScrollRequestBuilder.execute().actionGet(); } while (elementsResponse.getHits().getHits().length != 0); client.prepareClearScroll().addScrollId(elementsResponse.getScrollId()).get(); return elementRankIndex; } }
923a8b563127da01bf67911449ea87783cc6cc90
773
java
Java
code/interview-questions/src/main/java/cc/caker/interview/question04/Question.java
cakeralter/study
dc299bf990bb5f485ee7eff51d7139bc918d60da
[ "MIT" ]
6
2020-07-21T07:00:22.000Z
2020-08-13T05:57:53.000Z
code/interview-questions/src/main/java/cc/caker/interview/question04/Question.java
cakeralter/study
dc299bf990bb5f485ee7eff51d7139bc918d60da
[ "MIT" ]
2
2022-03-24T12:52:04.000Z
2022-03-24T12:52:09.000Z
code/interview-questions/src/main/java/cc/caker/interview/question04/Question.java
cakeralter/study
dc299bf990bb5f485ee7eff51d7139bc918d60da
[ "MIT" ]
null
null
null
20.891892
61
0.5511
999,247
package cc.caker.interview.question04; /** * @author cakeralter * @date 2020/7/25 */ public class Question { public static void main(String[] args) { Base base = new Sub(); // 可变参数和数组构成重写 --- Sub.print(int a, int[] arr) base.print(1, 2, 3); Sub sub = (Sub) base; // 重载确定参数优先 --- Sub.print(int a, int b, int c) sub.print(1, 2, 3); } } class Base { public void print(int a, int... arr) { System.out.println("Base.print(int a, int... arr)"); } } class Sub extends Base { public void print(int a, int[] arr) { System.out.println("Sub.print(int a, int[] arr)"); } public void print(int a, int b, int c) { System.out.println("Sub.print(int a, int b, int c)"); } }
923a8bc7bdb88f153b58c1eaacef7d14bffb3a55
954
java
Java
wormhole-bootstrap/src/main/java/com/zergclan/wormhole/bootstrap/scheduling/ExecutionStep.java
wenguozhang/wormhole
4b87bb0cc7ddec28c215f83f4323d80fca2ba259
[ "Apache-2.0" ]
null
null
null
wormhole-bootstrap/src/main/java/com/zergclan/wormhole/bootstrap/scheduling/ExecutionStep.java
wenguozhang/wormhole
4b87bb0cc7ddec28c215f83f4323d80fca2ba259
[ "Apache-2.0" ]
1
2021-11-27T04:23:05.000Z
2021-11-27T04:24:57.000Z
wormhole-bootstrap/src/main/java/com/zergclan/wormhole/bootstrap/scheduling/ExecutionStep.java
wenguozhang/wormhole
4b87bb0cc7ddec28c215f83f4323d80fca2ba259
[ "Apache-2.0" ]
null
null
null
35.333333
75
0.747379
999,248
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zergclan.wormhole.bootstrap.scheduling; /** * Execution step. */ public enum ExecutionStep { NEW, READY, EXECUTION, COMPLETE }
923a8c045246e444b25e5eed03a36bb418208db8
6,487
java
Java
aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/ClusterJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/ClusterJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/ClusterJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
45.048611
158
0.606752
999,249
/* * 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.ecs.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.ecs.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Cluster JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ClusterJsonUnmarshaller implements Unmarshaller<Cluster, JsonUnmarshallerContext> { public Cluster unmarshall(JsonUnmarshallerContext context) throws Exception { Cluster cluster = new Cluster(); 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 null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("clusterArn", targetDepth)) { context.nextToken(); cluster.setClusterArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("clusterName", targetDepth)) { context.nextToken(); cluster.setClusterName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("configuration", targetDepth)) { context.nextToken(); cluster.setConfiguration(ClusterConfigurationJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("status", targetDepth)) { context.nextToken(); cluster.setStatus(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("registeredContainerInstancesCount", targetDepth)) { context.nextToken(); cluster.setRegisteredContainerInstancesCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("runningTasksCount", targetDepth)) { context.nextToken(); cluster.setRunningTasksCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("pendingTasksCount", targetDepth)) { context.nextToken(); cluster.setPendingTasksCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("activeServicesCount", targetDepth)) { context.nextToken(); cluster.setActiveServicesCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("statistics", targetDepth)) { context.nextToken(); cluster.setStatistics(new ListUnmarshaller<KeyValuePair>(KeyValuePairJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("tags", targetDepth)) { context.nextToken(); cluster.setTags(new ListUnmarshaller<Tag>(TagJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("settings", targetDepth)) { context.nextToken(); cluster.setSettings(new ListUnmarshaller<ClusterSetting>(ClusterSettingJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("capacityProviders", targetDepth)) { context.nextToken(); cluster.setCapacityProviders(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("defaultCapacityProviderStrategy", targetDepth)) { context.nextToken(); cluster.setDefaultCapacityProviderStrategy(new ListUnmarshaller<CapacityProviderStrategyItem>(CapacityProviderStrategyItemJsonUnmarshaller .getInstance()) .unmarshall(context)); } if (context.testExpression("attachments", targetDepth)) { context.nextToken(); cluster.setAttachments(new ListUnmarshaller<Attachment>(AttachmentJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("attachmentsStatus", targetDepth)) { context.nextToken(); cluster.setAttachmentsStatus(context.getUnmarshaller(String.class).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 cluster; } private static ClusterJsonUnmarshaller instance; public static ClusterJsonUnmarshaller getInstance() { if (instance == null) instance = new ClusterJsonUnmarshaller(); return instance; } }
923a8c0a15a8252420428a75798477518d145ea2
7,038
java
Java
src/main/java/com/google/security/zynamics/reil/translators/arm/ARMSmlaldTranslator.java
mayl8822/binnavi
4cfdd91cdda2a6150f537df91a8c4221ae50bb6d
[ "Apache-2.0" ]
3,083
2015-08-19T13:31:12.000Z
2022-03-30T09:22:21.000Z
src/main/java/com/google/security/zynamics/reil/translators/arm/ARMSmlaldTranslator.java
mayl8822/binnavi
4cfdd91cdda2a6150f537df91a8c4221ae50bb6d
[ "Apache-2.0" ]
99
2015-08-19T14:42:49.000Z
2021-04-13T10:58:32.000Z
src/main/java/com/google/security/zynamics/reil/translators/arm/ARMSmlaldTranslator.java
mayl8822/binnavi
4cfdd91cdda2a6150f537df91a8c4221ae50bb6d
[ "Apache-2.0" ]
613
2015-08-19T14:15:44.000Z
2022-03-26T04:40:55.000Z
51
99
0.745524
999,250
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.reil.translators.arm; import com.google.security.zynamics.reil.OperandSize; import com.google.security.zynamics.reil.ReilHelpers; import com.google.security.zynamics.reil.ReilInstruction; import com.google.security.zynamics.reil.translators.ITranslationEnvironment; import com.google.security.zynamics.reil.translators.InternalTranslationException; import com.google.security.zynamics.reil.translators.TranslationHelpers; import com.google.security.zynamics.zylib.disassembly.IInstruction; import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode; import java.util.List; public class ARMSmlaldTranslator extends ARMBaseTranslator { @Override protected void translateCore(final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) { final IOperandTreeNode registerOperand1 = instruction.getOperands().get(0).getRootNode().getChildren().get(0); final IOperandTreeNode registerOperand2 = instruction.getOperands().get(1).getRootNode().getChildren().get(0); final IOperandTreeNode registerOperand3 = instruction.getOperands().get(2).getRootNode().getChildren().get(0); final IOperandTreeNode registerOperand4 = instruction.getOperands().get(3).getRootNode().getChildren().get(0); final String sourceRegister1 = (registerOperand1.getValue()); final String sourceRegister2 = (registerOperand2.getValue()); final String sourceRegister3 = (registerOperand3.getValue()); final String sourceRegister4 = (registerOperand4.getValue()); final OperandSize bt = OperandSize.BYTE; final OperandSize wd = OperandSize.WORD; final OperandSize dw = OperandSize.DWORD; final OperandSize qw = OperandSize.QWORD; long baseOffset = (instruction.getAddress().toLong() * 0x100) + instructions.size(); final String accValue = environment.getNextVariableString(); final String operand2 = environment.getNextVariableString(); final String operand2from15to0 = environment.getNextVariableString(); final String operand2from31to16 = environment.getNextVariableString(); final String registerRm15to0 = environment.getNextVariableString(); final String registerRm31to16 = environment.getNextVariableString(); final String tmpAccValue = environment.getNextVariableString(); final String tmpResult1 = environment.getNextVariableString(); final String tmpResult2 = environment.getNextVariableString(); final String tmpResult3 = environment.getNextVariableString(); final String tmpRotate1 = environment.getNextVariableString(); final String tmpRotate2 = environment.getNextVariableString(); final String product1 = environment.getNextVariableString(); final String product2 = environment.getNextVariableString(); if (instruction.getMnemonic().contains("X")) { instructions.add(ReilHelpers.createBsh(baseOffset++, dw, sourceRegister4, bt, String.valueOf(-16), dw, tmpRotate1)); instructions.add(ReilHelpers.createBsh(baseOffset++, dw, sourceRegister4, bt, String.valueOf(16), dw, tmpRotate2)); instructions.add(ReilHelpers.createOr(baseOffset++, dw, tmpRotate1, dw, tmpRotate2, dw, operand2)); instructions.add(ReilHelpers.createAnd(baseOffset++, dw, operand2, dw, String.valueOf(0xFFFFFFFFL), dw, operand2)); } else { instructions.add(ReilHelpers.createStr(baseOffset++, dw, sourceRegister4, dw, operand2)); } instructions.add(ReilHelpers.createStr(baseOffset++, dw, sourceRegister1, qw, accValue)); instructions.add(ReilHelpers.createBsh(baseOffset++, dw, sourceRegister2, wd, String.valueOf(32L), qw, tmpAccValue)); instructions.add(ReilHelpers .createOr(baseOffset++, qw, tmpAccValue, dw, accValue, qw, accValue)); instructions.add(ReilHelpers.createAnd(baseOffset++, dw, operand2, dw, String.valueOf(0xFFFFL), dw, operand2from15to0)); instructions.add(ReilHelpers.createBsh(baseOffset++, dw, operand2, dw, String.valueOf(-16L), dw, operand2from31to16)); instructions.add(ReilHelpers.createAnd(baseOffset++, dw, sourceRegister3, dw, String.valueOf(0xFFFFL), dw, registerRm15to0)); instructions.add(ReilHelpers.createBsh(baseOffset++, dw, sourceRegister3, dw, String.valueOf(-16L), dw, registerRm31to16)); Helpers.signedMul(baseOffset, environment, instruction, instructions, wd, registerRm15to0, wd, operand2from15to0, dw, product1); baseOffset = ReilHelpers.nextReilAddress(instruction, instructions); Helpers.signedMul(baseOffset, environment, instruction, instructions, wd, registerRm31to16, wd, operand2from31to16, dw, product2); baseOffset = ReilHelpers.nextReilAddress(instruction, instructions); instructions.add(ReilHelpers .createAdd(baseOffset++, dw, product1, dw, product2, qw, tmpResult1)); instructions.add(ReilHelpers.createAnd(baseOffset++, qw, tmpResult1, dw, String.valueOf(0xFFFFFFFFL), dw, tmpResult1)); instructions.add(ReilHelpers.createAdd(baseOffset++, dw, tmpResult1, qw, accValue, qw, tmpResult2)); instructions.add(ReilHelpers.createAnd(baseOffset++, qw, tmpResult2, dw, String.valueOf(0xFFFFFFFFL), dw, sourceRegister1)); instructions.add(ReilHelpers.createAnd(baseOffset++, qw, tmpResult2, qw, String.valueOf(0xFFFFFFFF00000000L), qw, tmpResult3)); instructions.add(ReilHelpers.createBsh(baseOffset++, qw, tmpResult3, dw, String.valueOf(-32L), dw, sourceRegister2)); } /** * SMLALD{X}{<cond>} <RdLo>, <RdHi>, <Rm>, <Rs> * * Operation: * * if ConditionPassed(cond) then if X == 1 then operand2 = Rs Rotate_Right 16 else operand2 = Rs * accvalue[31:0] = RdLo accvalue[63:32] = RdHi product1 = Rm[15:0] * operand2[15:0] // Signed * multiplication product2 = Rm[31:16] * operand2[31:16] // Signed multiplication result = * accvalue + product1 + product2 // Signed addition RdLo = result[31:0] RdHi = result[63:32] */ @Override public void translate(final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "SMLALD"); translateAll(environment, instruction, "SMLALD", instructions); } }
923a8c3a436f200f18e9e6439ab11a4cc3ac838b
203
java
Java
src/main/java/com/infosupport/training/reactjs/gtdserver/security/UserService.java
mthmulders/gtd-server
b6205004115d8e0546879adb8862df455e006e6e
[ "MIT" ]
null
null
null
src/main/java/com/infosupport/training/reactjs/gtdserver/security/UserService.java
mthmulders/gtd-server
b6205004115d8e0546879adb8862df455e006e6e
[ "MIT" ]
30
2019-12-07T07:31:08.000Z
2021-03-22T06:16:27.000Z
src/main/java/com/infosupport/training/reactjs/gtdserver/security/UserService.java
mthmulders/gtd-server
b6205004115d8e0546879adb8862df455e006e6e
[ "MIT" ]
null
null
null
22.555556
60
0.783251
999,251
package com.infosupport.training.reactjs.gtdserver.security; import java.util.Optional; public interface UserService { void create(User user); Optional<User> findByUsername(String username); }
923a8cafaf5e0798fb6e02d13c9f1b775dfc535d
2,629
java
Java
src/edu/mit/compilers/Main.java
MuhammadMouradG/EJUST_CSE422_Decaf_Compiler
b166404fd77e16a771688c199def2e90b7181cb2
[ "MIT" ]
null
null
null
src/edu/mit/compilers/Main.java
MuhammadMouradG/EJUST_CSE422_Decaf_Compiler
b166404fd77e16a771688c199def2e90b7181cb2
[ "MIT" ]
null
null
null
src/edu/mit/compilers/Main.java
MuhammadMouradG/EJUST_CSE422_Decaf_Compiler
b166404fd77e16a771688c199def2e90b7181cb2
[ "MIT" ]
null
null
null
34.592105
135
0.534043
999,252
package edu.mit.compilers; import java.io.*; import antlr.Token; import edu.mit.compilers.grammar.*; import edu.mit.compilers.tools.CLI; import edu.mit.compilers.tools.CLI.Action; class Main { public static void main(String[] args) { try { CLI.parse(args, new String[0]); InputStream inputStream = args.length == 0 ? System.in : new java.io.FileInputStream(CLI.infile); PrintStream outputStream = CLI.outfile == null ? System.out : new java.io.PrintStream(new java.io.FileOutputStream(CLI.outfile)); if (CLI.target == Action.SCAN) { DecafScanner scanner = new DecafScanner(new DataInputStream(inputStream)); scanner.setTrace(CLI.debug); Token token; boolean done = false; while (!done) { try { for (token = scanner.nextToken(); token.getType() != DecafParserTokenTypes.EOF; token = scanner.nextToken()) { String type = ""; String text = token.getText(); switch (token.getType()) { // TODO: add strings for the other types here... case DecafScannerTokenTypes.INTLITERAL: type = " INTLITERAL"; break; case DecafScannerTokenTypes.STRINGLITERAL: type = " STRINGLITERAL"; break; case DecafScannerTokenTypes.CHARLITERAL: type = " CHARLITERAL"; break; case DecafScannerTokenTypes.ID: type = " IDENTIFIER"; break; case DecafScannerTokenTypes.TK_true: type = " BOOLEANLITERAL"; break; case DecafScannerTokenTypes.TK_false: type = " BOOLEANLITERAL"; break; } outputStream.println(token.getLine() + type + " " + text); } done = true; } catch(Exception e) { // print the error: System.err.println(CLI.infile + " " + e); scanner.consume(); } } } else if (CLI.target == Action.PARSE || CLI.target == Action.DEFAULT) { DecafScanner scanner = new DecafScanner(new DataInputStream(inputStream)); DecafParser parser = new DecafParser(scanner); parser.setTrace(CLI.debug); parser.program(); if(parser.getError()) { System.exit(1); } } } catch(Exception e) { // print the error: System.err.println(CLI.infile+" "+e); } } }
923a8cbc8c101a0955d05fa65efe9597dd4e5cfd
7,685
java
Java
Projects/7.3 Expense Planner/ExpensePlannerGUI.java
brimstone-/APCompSci
20dee0c454eb0534a90e341c35201c0b98547c66
[ "MIT" ]
null
null
null
Projects/7.3 Expense Planner/ExpensePlannerGUI.java
brimstone-/APCompSci
20dee0c454eb0534a90e341c35201c0b98547c66
[ "MIT" ]
null
null
null
Projects/7.3 Expense Planner/ExpensePlannerGUI.java
brimstone-/APCompSci
20dee0c454eb0534a90e341c35201c0b98547c66
[ "MIT" ]
null
null
null
38.044554
115
0.565647
999,253
//----------------------------------------------------------------- // ExpensePlannerGUI.java // // GUI to calculate buying items on a wishlist with funds // gained on a monthly basis. // Items are bought in queue order. //----------------------------------------------------------------- import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class ExpensePlannerGUI { private int WIDTH = 700; private int HEIGHT = 300; private JFrame frame; private JPanel panel; private JFrame itemFrame; private JPanel itemPanel; private JLabel setAllowanceLabel; private TextField setAllowanceField; private JLabel currentAllowanceLabel; private JLabel currentAllowanceAlert; private int allowance = 0; private JButton nextButton; private int balance = 0; private JLabel currentBalanceLabel; private JLabel currentMonthLabel; private int month = 1; private String currentMonth; private JLabel itemNameLabel; private JLabel itemCostLabel; private TextField itemCostField; private TextField itemNameField; private JLabel confirmationLabel; private JLabel itemBoughtLabel; private String itemBought = ""; private JButton itemButton; private JButton wishlistButton; private JLabel wishlistLabel; LinkedList<Item> wishes = new LinkedList<Item>(); //----------------------------------------------------------------- // Constructor: Sets up the GUI. //----------------------------------------------------------------- public ExpensePlannerGUI() { frame = new JFrame ("Expense Planner"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setPreferredSize (new Dimension(WIDTH, HEIGHT)); panel.setBackground (Color.gray); setAllowanceLabel = new JLabel("Set the Monthly Allowance (Press <ENTER>)"); setAllowanceField = new TextField(15); currentAllowanceLabel = new JLabel("Allowance set aside each month: "); setAllowanceField.addActionListener(new allowanceFieldListener()); currentAllowanceAlert = new JLabel(""); nextButton = new JButton("Go to next month"); nextButton.addActionListener(new nextButtonListener()); currentBalanceLabel = new JLabel("Current Balance: "); currentMonthLabel = new JLabel("Current Month: "); itemButton = new JButton("Add an item to the wishlist"); itemButton.addActionListener(new itemButtonListener()); itemNameLabel = new JLabel("Item Name: "); itemCostLabel = new JLabel("Item Cost: "); itemCostField = new TextField(15); itemNameField = new TextField(15); confirmationLabel = new JLabel(""); itemBoughtLabel = new JLabel(""); wishlistButton = new JButton("View current wishlist"); wishlistButton.addActionListener(new wishlistButtonListener()); wishlistLabel = new JLabel(""); panel.add(setAllowanceLabel); panel.add(currentAllowanceAlert); panel.add(setAllowanceField); panel.add(currentAllowanceLabel); panel.add(currentBalanceLabel); panel.add(currentMonthLabel); panel.add(nextButton); panel.add(itemBoughtLabel); panel.add(itemNameLabel); panel.add(itemNameField); panel.add(itemCostLabel); panel.add(itemCostField); panel.add(confirmationLabel); panel.add(itemButton); panel.add(wishlistButton); panel.add(wishlistLabel); frame.getContentPane().add (panel, BorderLayout.LINE_START); } //----------------------------------------------------------------- // Displays the primary application frame. //----------------------------------------------------------------- public void display() { frame.pack(); frame.setVisible(true); } //----------------------------------------------------------------- // Represents a listener for button push (action) events //----------------------------------------------------------------- private class allowanceFieldListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (!setAllowanceField.getText().trim().equals("")) { allowance = Integer.parseInt(setAllowanceField.getText()); currentAllowanceLabel.setText(""); currentAllowanceLabel.setText("Allowance set aside each month: " + allowance); currentAllowanceAlert.setText(""); } else { currentAllowanceAlert.setText("Please enter a sum to set aside each month."); } } } private class nextButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { balance += allowance; while (!wishes.isEmpty() && wishes.peek().getCost() < balance) { Item temp = wishes.getFirst(); while (temp != null && temp.getCost() < balance) { balance -= temp.getCost(); itemBought += temp.getDescription() + " has been purchased for $" + temp.getCost() + ", "; wishes.remove(); itemBoughtLabel.setText(""); itemBoughtLabel.setText(itemBought); if (wishes.peek() != null) temp = wishes.getFirst(); else temp = null; } itemBought = ""; } currentBalanceLabel.setText(""); currentBalanceLabel.setText("Current Balance: " + balance); month++; if (month > 12) month = 1; currentMonth = returnMonth(month); currentMonthLabel.setText("Current Month: " + currentMonth); } } private class itemButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (!itemNameField.getText().trim().equals("") && !itemCostField.getText().trim().equals("")) { Item buyThis = new Item(itemNameField.getText().trim(), Integer.parseInt(itemCostField.getText())); wishes.add(buyThis); itemNameField.setText(""); itemCostField.setText(""); confirmationLabel.setText("Got it!"); } else { confirmationLabel.setText("Please enter valid input for the item description and cost."); } } } private class wishlistButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (!wishes.isEmpty()) { wishlistLabel.setText("Items to be bought: " + wishes.toString() + ""); } else { wishlistLabel.setText("No items to be bought, add something to the wishlist!"); } } } public static String returnMonth(int num) { if (num == 1) return "Janurary"; else if (num == 2) return "February"; else if (num == 3) return "March"; else if (num == 4) return "April"; else if (num == 5) return "May"; else if (num == 6) return "June"; else if (num == 7) return "July"; else if (num == 8) return "August"; else if (num == 9) return "September"; else if (num == 10) return "October"; else if (num == 11) return "November"; else return "December"; } }
923a8cca308881b17408116cd11839aa5bc21cf0
2,627
java
Java
src/test/java/seedu/address/testutil/GuestBuilder.java
alyssa-savier/tp
576eb3f4fd9da3a07c3d5fe08065efabe0e5e277
[ "MIT" ]
null
null
null
src/test/java/seedu/address/testutil/GuestBuilder.java
alyssa-savier/tp
576eb3f4fd9da3a07c3d5fe08065efabe0e5e277
[ "MIT" ]
null
null
null
src/test/java/seedu/address/testutil/GuestBuilder.java
alyssa-savier/tp
576eb3f4fd9da3a07c3d5fe08065efabe0e5e277
[ "MIT" ]
null
null
null
30.905882
120
0.676437
999,254
package seedu.address.testutil; import static seedu.address.testutil.TypicalPassportNumbers.PASSPORT_NUMBER_DEFAULT; import seedu.address.model.person.Email; import seedu.address.model.person.Guest; import seedu.address.model.person.Name; import seedu.address.model.person.PassportNumber; import seedu.address.model.person.RoomNumber; import seedu.address.model.tag.Tag; import seedu.address.model.util.SampleDataUtil; public class GuestBuilder extends PersonBuilder { public static final RoomNumber DEFAULT_ROOM_NUMBER = new RoomNumber("10101"); public static final PassportNumber DEFAULT_PASSPORT_NUMBER = new PassportNumber(PASSPORT_NUMBER_DEFAULT.toString()); private static final Tag DEFAULT_TAG = new Tag("Guest"); private RoomNumber roomNumber; private PassportNumber passportNumber; /** * Creates a {@code GuestBuilder} with the default details. */ public GuestBuilder() { super(); roomNumber = DEFAULT_ROOM_NUMBER; passportNumber = DEFAULT_PASSPORT_NUMBER; getTags().add(DEFAULT_TAG); } /** * Initializes the GuestBuilder with the data of {@code guestToCopy}. */ public GuestBuilder(Guest guestToCopy) { super(guestToCopy); roomNumber = guestToCopy.getRoomNumber(); passportNumber = guestToCopy.getPassportNumber(); } /** * Sets the {@code Name} of the {@code Guest} that we are building. */ public GuestBuilder withName(String name) { setName(new Name(name)); return this; } /** * Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code Guest} that we are building. */ public GuestBuilder withTags(String... tags) { setTags(SampleDataUtil.getTagSet(tags)); return this; } /** * Sets the {@code Email} of the {@code Guest} that we are building. */ public GuestBuilder withEmail(String email) { setEmail(new Email(email)); return this; } /** * Sets the {@code RoomNumber} of the {@code Guest} that we are building. */ public GuestBuilder withRoomNumber(String roomNumber) { this.roomNumber = new RoomNumber(roomNumber); return this; } /** * Sets the {@code PassportNumber} of the {@code Guest} that we are building. */ public GuestBuilder withPassportNumber(String passportNumber) { this.passportNumber = new PassportNumber(passportNumber); return this; } public Guest build() { return new Guest(getName(), getEmail(), getTags(), roomNumber, passportNumber); } }
923a8dbdb2a94c695a60ffff03ab171bbf9b5e18
2,760
java
Java
server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileCacheableMailQueueFactoryTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
3
2017-02-08T09:35:46.000Z
2020-05-22T07:03:51.000Z
server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileCacheableMailQueueFactoryTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
8
2015-12-07T12:05:09.000Z
2022-03-23T07:22:22.000Z
server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileCacheableMailQueueFactoryTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
5
2015-12-10T12:13:24.000Z
2020-05-22T07:03:57.000Z
48.421053
141
0.662319
999,255
/**************************************************************** * 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.james.queue.file; import org.apache.james.filesystem.api.mock.MockFileSystem; import org.apache.james.queue.api.MailQueueFactory; import org.apache.james.queue.api.MailQueueFactoryContract; import org.apache.james.queue.api.ManageableMailQueue; import org.apache.james.queue.api.ManageableMailQueueFactoryContract; import org.apache.james.queue.api.RawMailQueueItemDecoratorFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @Disabled("FileMailQueue is an outdated unmaintained component suffering incomplete features and is not thread safe" + "This includes: " + " - JAMES-2298 Unsupported remove management feature" + " - JAMES-2954 Incomplete browse implementation" + " - JAMES-2544 Mixing concurrent operation might lead to a deadlock and missing fields" + " - JAMES-2979 dequeue is not thread safe") public class FileCacheableMailQueueFactoryTest implements MailQueueFactoryContract<ManageableMailQueue>, ManageableMailQueueFactoryContract { private FileMailQueueFactory mailQueueFactory; private MockFileSystem fileSystem; @BeforeEach public void setUp() throws Exception { fileSystem = new MockFileSystem(); mailQueueFactory = new FileMailQueueFactory(fileSystem, new RawMailQueueItemDecoratorFactory()); } @AfterEach void teardown() { fileSystem.clear(); } @Override public MailQueueFactory<ManageableMailQueue> getMailQueueFactory() { return mailQueueFactory; } }
923a8ded6df0f5f30f0af17a7790b986358b5a5d
129
java
Java
tools/templates/proj.android/src/org/oxygine/${PROJECT}/MainActivity.java
k3m3/oxygine-framework
60bbb98d0bb7fa4c425818a669077819148f27b4
[ "MIT" ]
803
2015-01-03T13:11:43.000Z
2022-03-15T17:38:58.000Z
tools/templates/proj.android/src/org/oxygine/${PROJECT}/MainActivity.java
sky-vertos/oxygine-framework
60bbb98d0bb7fa4c425818a669077819148f27b4
[ "MIT" ]
100
2015-01-07T17:07:56.000Z
2021-12-21T20:09:20.000Z
tools/templates/proj.android/src/org/oxygine/${PROJECT}/MainActivity.java
sky-vertos/oxygine-framework
60bbb98d0bb7fa4c425818a669077819148f27b4
[ "MIT" ]
265
2015-01-03T13:11:43.000Z
2022-03-01T04:37:15.000Z
14.333333
49
0.79845
999,256
package org.oxygine.${PROJECT}; import org.oxygine.lib.OxygineActivity; public class MainActivity extends OxygineActivity { }
923a8f72ef4aad44d68f8d2d2a39d58757b8d09e
2,739
java
Java
[Easy] 0066. Plus One/PlusOne.java
williamhsucs/leetcode
c136b4b9a87fed9bc53939c3d6c9a1652b1d1cf9
[ "MIT" ]
1
2021-08-24T13:09:20.000Z
2021-08-24T13:09:20.000Z
[Easy] 0066. Plus One/PlusOne.java
williamhsucs/leetcode
c136b4b9a87fed9bc53939c3d6c9a1652b1d1cf9
[ "MIT" ]
null
null
null
[Easy] 0066. Plus One/PlusOne.java
williamhsucs/leetcode
c136b4b9a87fed9bc53939c3d6c9a1652b1d1cf9
[ "MIT" ]
null
null
null
21.398438
91
0.424608
999,257
/** * Problem * https://leetcode.com/problems/plus-one/ * * ************************************************************* * * Input: digits = [1,2,3] * * Output: [1,2,4] * * Explanation: * The array represents the integer 123. * Incrementing by one gives 123 + 1 = 124. * Thus, the result should be [1,2,4]. * * ************************************************************* * * Input: digits = [4,3,2,1] * * Output: [4,3,2,2] * * Explanation: * The array represents the integer 4321. * Incrementing by one gives 4321 + 1 = 4322. * Thus, the result should be [4,3,2,2]. * * ************************************************************* * * Input: digits = [0] * * Output: [1] * * Explanation: * The array represents the integer 0. * Incrementing by one gives 0 + 1 = 1. * Thus, the result should be [1]. * * ************************************************************* * * Input: digits = [9] * * Output: [1,0] * * Explanation: * The array represents the integer 9. * Incrementing by one gives 9 + 1 = 10. * Thus, the result should be [1,0]. * * ************************************************************* * Time Complexity: O(n) * - for loop * Space Complexity: O(n) * - If it has the carry number at the greatest digit. * It means that must to declare an extra space(new array) to store new greatest digit. */ class PlusOne { public int[] plusOne(int[] digits) { /** * Time Complexity: O(n) */ for (int i = digits.length - 1; i >= 0; i--) { if (digits[i] != 9) { digits[i]++; break; } else { digits[i] = 0; } } if (digits[0] == 0) { /** * Space Complexity: O(n) */ int[] ret = new int[digits.length + 1]; ret[0] = 1; return ret; } else { /** * Space Complexity: O(1) */ return digits; } } } class PlusOneVerOne { public int[] plusOne(int[] digits) { int carry = 0; /** * Time Complexity: O(n) */ for (int i = digits.length - 1; i >= 0; i--) { if (i == digits.length - 1 || carry == 1) { digits[i] += 1; carry = 0; } if (digits[i] == 10) { digits[i] = 0; carry = 1; } } if (carry == 1) { /** * Space Complexity: O(n) */ int[] ret = new int[digits.length + 1]; /** * Time Complexity: O(n) */ for (int i = ret.length - 1; i >= 1; i--) { ret[i] = digits[i - 1]; } ret[0] = 1; return ret; } else { /** * Time Complexity: O(n) * Space Complexity: O(1) */ return digits; } } }
923a907f2bdbbc91b633e48957449bb6d6fe5e48
706
java
Java
business/pay/pay-api/src/main/java/study/daydayup/wolf/business/pay/api/domain/enums/PaymentLogTypeEnum.java
wolforest/wolf
207c61cd473d1433bf3e4fc5a591aaf3a5964418
[ "MIT" ]
18
2019-10-05T06:00:36.000Z
2021-12-14T10:20:58.000Z
business/pay/pay-api/src/main/java/study/daydayup/wolf/business/pay/api/domain/enums/PaymentLogTypeEnum.java
wolforest/wolf
207c61cd473d1433bf3e4fc5a591aaf3a5964418
[ "MIT" ]
1
2020-02-06T15:50:36.000Z
2020-02-06T15:50:39.000Z
business/pay/pay-api/src/main/java/study/daydayup/wolf/business/pay/api/domain/enums/PaymentLogTypeEnum.java
wolforest/wolf
207c61cd473d1433bf3e4fc5a591aaf3a5964418
[ "MIT" ]
12
2020-01-14T01:04:12.000Z
2022-02-22T07:21:37.000Z
22.0625
59
0.65864
999,258
package study.daydayup.wolf.business.pay.api.domain.enums; import lombok.Getter; import study.daydayup.wolf.common.lang.enums.CodeBasedEnum; /** * study.daydayup.wolf.common.lang.enums * * @author Wingle * @since 2019/9/29 4:51 PM **/ @Getter public enum PaymentLogTypeEnum implements CodeBasedEnum { PAYOUT_NOTIFY(21, "放款通知"), PAYOUT_REQUEST(20, "放款请求"), TRADE_NOTIFY(10, "私对私"), REFUND_REQUEST(8, "退款请求"), PAY_DUPLICATE(4, "重复支付"), PAY_RETURN(3, "支付通知"), PAY_NOTIFY(2, "支付通知"), PAY_REQUEST(1, "支付请求"), ; private int code; private String name; PaymentLogTypeEnum(int code, String name) { this.code = code; this.name = name; } }
923a91568cb77e77e0144a34296e40a1ad273b79
2,825
java
Java
app-ui/src/main/java/com/mercury/platform/ui/components/panel/misc/MercuryAppLoadingUI.java
charon166/MercuryTrade
31fc82c67fbbe4146e7b8c5d89f51ed3ae9581fe
[ "MIT" ]
584
2017-02-22T22:40:32.000Z
2022-02-25T22:57:05.000Z
app-ui/src/main/java/com/mercury/platform/ui/components/panel/misc/MercuryAppLoadingUI.java
charon166/MercuryTrade
31fc82c67fbbe4146e7b8c5d89f51ed3ae9581fe
[ "MIT" ]
398
2017-02-11T19:02:23.000Z
2022-01-01T12:14:12.000Z
app-ui/src/main/java/com/mercury/platform/ui/components/panel/misc/MercuryAppLoadingUI.java
charon166/MercuryTrade
31fc82c67fbbe4146e7b8c5d89f51ed3ae9581fe
[ "MIT" ]
236
2017-03-13T15:21:27.000Z
2022-03-22T02:19:52.000Z
36.688312
150
0.660177
999,259
package com.mercury.platform.ui.components.panel.misc; import com.mercury.platform.ui.adr.components.panel.ui.MercuryLoading; import com.mercury.platform.ui.misc.AppThemeColor; import org.imgscalr.Scalr; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.IOException; public class MercuryAppLoadingUI extends ComponentUI { private MercuryLoading component; public MercuryAppLoadingUI(MercuryLoading component) { this.component = component; } public ImageIcon getIcon(String iconPath, int size) { BufferedImage icon = null; try { BufferedImage buttonIcon = ImageIO.read(getClass().getClassLoader().getResource(iconPath)); icon = Scalr.resize(buttonIcon, size); } catch (IOException e) { e.printStackTrace(); } return new ImageIcon(icon); } @Override public void paint(Graphics g, JComponent c) { if (component.getWidth() == 0) { return; } Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); double degree = 360 * component.getPercentComplete(); double size = 120; double iconSize = 46; double outerR = size * .5; double bgR = outerR * 1.04; double innerR = outerR * .78; double pointX = component.getWidth() * .5; double pointY = component.getHeight() * .5; Shape inner = new Ellipse2D.Double(pointX - innerR, pointY - innerR, innerR * 2, innerR * 2); Shape outer = new Ellipse2D.Double(pointX - outerR, pointY - outerR, size, size); Shape bg = new Ellipse2D.Double(pointX - bgR, pointY - bgR, bgR * 2, bgR * 2); Shape sector = new Arc2D.Double(pointX - outerR, pointY - outerR, size, size, 90 - degree, degree, Arc2D.PIE); Area foreground = new Area(sector); Area background = new Area(outer); Area bgArea = new Area(bg); Area hole = new Area(inner); foreground.subtract(hole); background.subtract(hole); g2.setPaint(AppThemeColor.ADR_FOOTER_BG); g2.fill(bgArea); g2.setPaint(this.component.getBackground()); g2.drawImage(this.getIcon("app/app-icon-big.png", (int) iconSize * 2).getImage(), (int) (pointX - iconSize), (int) (pointY - iconSize), null); g2.fill(background); g2.setPaint(component.getForeground()); g2.fill(foreground); g2.dispose(); } }
923a922e256524a8e38207415e9d4ffa5be20e73
9,308
java
Java
org.hl7.fhir.convertors/src/main/java/org/hl7/fhir/convertors/conv40_50/Group.java
jasmdk/org.hl7.fhir.core
fea455fbe4539145de5bf734e1737777eb9715e3
[ "Apache-2.0" ]
null
null
null
org.hl7.fhir.convertors/src/main/java/org/hl7/fhir/convertors/conv40_50/Group.java
jasmdk/org.hl7.fhir.core
fea455fbe4539145de5bf734e1737777eb9715e3
[ "Apache-2.0" ]
null
null
null
org.hl7.fhir.convertors/src/main/java/org/hl7/fhir/convertors/conv40_50/Group.java
jasmdk/org.hl7.fhir.core
fea455fbe4539145de5bf734e1737777eb9715e3
[ "Apache-2.0" ]
null
null
null
44.535885
193
0.73281
999,260
package org.hl7.fhir.convertors.conv40_50; /*- * #%L * org.hl7.fhir.convertors * %% * Copyright (C) 2014 - 2019 Health Level 7 * %% * 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% */ import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.convertors.VersionConvertor_40_50; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Sun, Feb 24, 2019 11:37+1100 for FHIR v4.0.0 public class Group extends VersionConvertor_40_50 { public static org.hl7.fhir.r5.model.Group convertGroup(org.hl7.fhir.r4.model.Group src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r5.model.Group tgt = new org.hl7.fhir.r5.model.Group(); copyDomainResource(src, tgt); for (org.hl7.fhir.r4.model.Identifier t : src.getIdentifier()) tgt.addIdentifier(convertIdentifier(t)); if (src.hasActive()) tgt.setActiveElement(convertBoolean(src.getActiveElement())); if (src.hasType()) tgt.setType(convertGroupType(src.getType())); if (src.hasActual()) tgt.setActualElement(convertBoolean(src.getActualElement())); if (src.hasCode()) tgt.setCode(convertCodeableConcept(src.getCode())); if (src.hasName()) tgt.setNameElement(convertString(src.getNameElement())); if (src.hasQuantity()) tgt.setQuantityElement(convertUnsignedInt(src.getQuantityElement())); if (src.hasManagingEntity()) tgt.setManagingEntity(convertReference(src.getManagingEntity())); for (org.hl7.fhir.r4.model.Group.GroupCharacteristicComponent t : src.getCharacteristic()) tgt.addCharacteristic(convertGroupCharacteristicComponent(t)); for (org.hl7.fhir.r4.model.Group.GroupMemberComponent t : src.getMember()) tgt.addMember(convertGroupMemberComponent(t)); return tgt; } public static org.hl7.fhir.r4.model.Group convertGroup(org.hl7.fhir.r5.model.Group src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r4.model.Group tgt = new org.hl7.fhir.r4.model.Group(); copyDomainResource(src, tgt); for (org.hl7.fhir.r5.model.Identifier t : src.getIdentifier()) tgt.addIdentifier(convertIdentifier(t)); if (src.hasActive()) tgt.setActiveElement(convertBoolean(src.getActiveElement())); if (src.hasType()) tgt.setType(convertGroupType(src.getType())); if (src.hasActual()) tgt.setActualElement(convertBoolean(src.getActualElement())); if (src.hasCode()) tgt.setCode(convertCodeableConcept(src.getCode())); if (src.hasName()) tgt.setNameElement(convertString(src.getNameElement())); if (src.hasQuantity()) tgt.setQuantityElement(convertUnsignedInt(src.getQuantityElement())); if (src.hasManagingEntity()) tgt.setManagingEntity(convertReference(src.getManagingEntity())); for (org.hl7.fhir.r5.model.Group.GroupCharacteristicComponent t : src.getCharacteristic()) tgt.addCharacteristic(convertGroupCharacteristicComponent(t)); for (org.hl7.fhir.r5.model.Group.GroupMemberComponent t : src.getMember()) tgt.addMember(convertGroupMemberComponent(t)); return tgt; } public static org.hl7.fhir.r5.model.Group.GroupType convertGroupType(org.hl7.fhir.r4.model.Group.GroupType src) throws FHIRException { if (src == null) return null; switch (src) { case PERSON: return org.hl7.fhir.r5.model.Group.GroupType.PERSON; case ANIMAL: return org.hl7.fhir.r5.model.Group.GroupType.ANIMAL; case PRACTITIONER: return org.hl7.fhir.r5.model.Group.GroupType.PRACTITIONER; case DEVICE: return org.hl7.fhir.r5.model.Group.GroupType.DEVICE; case MEDICATION: return org.hl7.fhir.r5.model.Group.GroupType.MEDICATION; case SUBSTANCE: return org.hl7.fhir.r5.model.Group.GroupType.SUBSTANCE; default: return org.hl7.fhir.r5.model.Group.GroupType.NULL; } } public static org.hl7.fhir.r4.model.Group.GroupType convertGroupType(org.hl7.fhir.r5.model.Group.GroupType src) throws FHIRException { if (src == null) return null; switch (src) { case PERSON: return org.hl7.fhir.r4.model.Group.GroupType.PERSON; case ANIMAL: return org.hl7.fhir.r4.model.Group.GroupType.ANIMAL; case PRACTITIONER: return org.hl7.fhir.r4.model.Group.GroupType.PRACTITIONER; case DEVICE: return org.hl7.fhir.r4.model.Group.GroupType.DEVICE; case MEDICATION: return org.hl7.fhir.r4.model.Group.GroupType.MEDICATION; case SUBSTANCE: return org.hl7.fhir.r4.model.Group.GroupType.SUBSTANCE; default: return org.hl7.fhir.r4.model.Group.GroupType.NULL; } } public static org.hl7.fhir.r5.model.Group.GroupCharacteristicComponent convertGroupCharacteristicComponent(org.hl7.fhir.r4.model.Group.GroupCharacteristicComponent src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r5.model.Group.GroupCharacteristicComponent tgt = new org.hl7.fhir.r5.model.Group.GroupCharacteristicComponent(); copyElement(src, tgt); if (src.hasCode()) tgt.setCode(convertCodeableConcept(src.getCode())); if (src.hasValue()) tgt.setValue(convertType(src.getValue())); if (src.hasExclude()) tgt.setExcludeElement(convertBoolean(src.getExcludeElement())); if (src.hasPeriod()) tgt.setPeriod(convertPeriod(src.getPeriod())); return tgt; } public static org.hl7.fhir.r4.model.Group.GroupCharacteristicComponent convertGroupCharacteristicComponent(org.hl7.fhir.r5.model.Group.GroupCharacteristicComponent src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r4.model.Group.GroupCharacteristicComponent tgt = new org.hl7.fhir.r4.model.Group.GroupCharacteristicComponent(); copyElement(src, tgt); if (src.hasCode()) tgt.setCode(convertCodeableConcept(src.getCode())); if (src.hasValue()) tgt.setValue(convertType(src.getValue())); if (src.hasExclude()) tgt.setExcludeElement(convertBoolean(src.getExcludeElement())); if (src.hasPeriod()) tgt.setPeriod(convertPeriod(src.getPeriod())); return tgt; } public static org.hl7.fhir.r5.model.Group.GroupMemberComponent convertGroupMemberComponent(org.hl7.fhir.r4.model.Group.GroupMemberComponent src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r5.model.Group.GroupMemberComponent tgt = new org.hl7.fhir.r5.model.Group.GroupMemberComponent(); copyElement(src, tgt); if (src.hasEntity()) tgt.setEntity(convertReference(src.getEntity())); if (src.hasPeriod()) tgt.setPeriod(convertPeriod(src.getPeriod())); if (src.hasInactive()) tgt.setInactiveElement(convertBoolean(src.getInactiveElement())); return tgt; } public static org.hl7.fhir.r4.model.Group.GroupMemberComponent convertGroupMemberComponent(org.hl7.fhir.r5.model.Group.GroupMemberComponent src) throws FHIRException { if (src == null) return null; org.hl7.fhir.r4.model.Group.GroupMemberComponent tgt = new org.hl7.fhir.r4.model.Group.GroupMemberComponent(); copyElement(src, tgt); if (src.hasEntity()) tgt.setEntity(convertReference(src.getEntity())); if (src.hasPeriod()) tgt.setPeriod(convertPeriod(src.getPeriod())); if (src.hasInactive()) tgt.setInactiveElement(convertBoolean(src.getInactiveElement())); return tgt; } }
923a92f4b73c72a75fe5449ded9b158a98ceb56f
13,083
java
Java
test/koopa/grammars/cobol/test/UseStatementTest.java
goblindegook/Koopa
4d419b446b80a7e26298f423aa85e0ac9e6dfbc9
[ "BSD-3-Clause" ]
5
2015-02-28T16:27:07.000Z
2019-10-10T13:47:01.000Z
test/koopa/grammars/cobol/test/UseStatementTest.java
goblindegook/Koopa
4d419b446b80a7e26298f423aa85e0ac9e6dfbc9
[ "BSD-3-Clause" ]
null
null
null
test/koopa/grammars/cobol/test/UseStatementTest.java
goblindegook/Koopa
4d419b446b80a7e26298f423aa85e0ac9e6dfbc9
[ "BSD-3-Clause" ]
1
2017-09-04T21:46:54.000Z
2017-09-04T21:46:54.000Z
37.70317
134
0.696018
999,261
package koopa.grammars.cobol.test; import junit.framework.TestCase; import koopa.parsers.Parser; import koopa.tokenizers.cobol.SourceFormat; import koopa.tokenizers.cobol.TestTokenizer; import org.junit.Test; /** This code was generated from UseStatement.stage. */ public class UseStatementTest extends TestCase { private static koopa.grammars.cobol.CobolGrammar grammar = new koopa.grammars.cobol.CobolGrammar(); @Test public void testUseStatement_1() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_2() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER EXCEPTION PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_3() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER ERROR PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_4() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER EXCEPTION PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_5() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD ERROR PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_6() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD EXCEPTION PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_7() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER STANDARD ERROR PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_8() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER STANDARD EXCEPTION PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_9() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_10() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON foo bar . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_11() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON INPUT . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_12() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON OUTPUT . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_13() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON I-O . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_14() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR PROCEDURE ON EXTEND . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_15() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR\n PROCEDURE ON foo\n GIVING bar . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_16() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ERROR\n PROCEDURE ON foo\n GIVING bar baz . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_17() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_18() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE GLOBAL AFTER STANDARD LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_19() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_20() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_21() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON foo bar . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_22() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON OUTPUT . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_23() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON INPUT . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_24() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON I-O . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_25() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER LABEL PROCEDURE ON EXTEND . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_26() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_27() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD BEGINNING LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_28() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD ENDING LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_29() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD FILE LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_30() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD REEL LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_31() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER STANDARD UNIT LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_32() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER BEGINNING FILE LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_33() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER BEGINNING REEL LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_34() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER BEGINNING UNIT LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_35() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ENDING FILE LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_36() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ENDING REEL LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } @Test public void testUseStatement_37() { Parser parser = grammar.useStatement(); assertNotNull(parser); TestTokenizer tokenizer = new TestTokenizer(SourceFormat.FREE, " USE AFTER ENDING UNIT LABEL PROCEDURE ON foo . "); assertTrue(parser.accepts(tokenizer)); assertTrue(tokenizer.isWhereExpected()); } }
923a934d4a77cf45a4f99cc01c79b008953931b4
1,356
java
Java
src/main/java/frc/robot/commands/RollIn.java
SkylineSpartabots/YogaBallBot
8065795a07f066ee046a1c35cdb8a81e3d48fa70
[ "BSD-3-Clause" ]
2
2017-09-26T04:23:38.000Z
2019-02-14T03:11:54.000Z
src/main/java/frc/robot/commands/RollIn.java
SkylineSpartabots/YogaBallBot
8065795a07f066ee046a1c35cdb8a81e3d48fa70
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/RollIn.java
SkylineSpartabots/YogaBallBot
8065795a07f066ee046a1c35cdb8a81e3d48fa70
[ "BSD-3-Clause" ]
1
2017-09-26T04:23:42.000Z
2017-09-26T04:23:42.000Z
22.983051
77
0.702802
999,262
package frc.robot.commands; import edu.wpi.first.wpilibj.command.Command; import frc.robot.Robot; /** * Rolls a ball into the bot with specified roller speed. */ public class RollIn extends Command { private double power; /** * If usingController is true, the command ends when the button is released. * Otherwise, the roll out command stops after 0.9s. * * @param power of the roller, between 0 and 1. * @param usingController whether or not the command was started by the * controller */ public RollIn(double power) { requires(Robot.m_roller); this.power = power; } // Called just before this Command runs the first time @Override protected void initialize() { Robot.m_roller.extendIntake(); } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { Robot.m_roller.roll(power); } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return !Robot.m_oi.dancePad.getRollInButton().get(); } // Called once after isFinished returns true @Override protected void end() { Robot.m_roller.roll(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { end(); } }