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
sequence
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
sequence
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
sequence
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
3e032baf77e539e8d7b77d8fdd36957efbe3da8b
933
java
Java
projects/OG-Engine/src/main/java/com/opengamma/engine/view/worker/trigger/ViewCycleEligibility.java
emcleod/OG-Platform
dbd4e1c64907f6a2dd27a62d252e9c61e609f779
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
projects/OG-Engine/src/main/java/com/opengamma/engine/view/worker/trigger/ViewCycleEligibility.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
1
2021-08-02T17:20:43.000Z
2021-08-02T17:20:43.000Z
projects/OG-Engine/src/main/java/com/opengamma/engine/view/worker/trigger/ViewCycleEligibility.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
22.756098
92
0.596999
1,310
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.view.worker.trigger; /** * Enumerates the levels of eligibility to perform a view cycle. */ public enum ViewCycleEligibility { /** * Indicates that a view cycle is eligible to be performed if necessary. */ ELIGIBLE, /** * Indicates that no view cycle should be performed. */ PREVENT, /** * Indicates that a view cycle should be performed. */ FORCE; //------------------------------------------------------------------------- public static ViewCycleEligibility merge(ViewCycleEligibility a, ViewCycleEligibility b) { if (a == null) { return b; } if (b == null) { return a; } // Declared in increasing order of importance return values()[Math.max(a.ordinal(), b.ordinal())]; } }
3e032be217ac433ed9dc0a44827bd6f8d263c47e
778
java
Java
edmm-core/src/main/java/io/github/edmm/plugins/cloudify/model/azure/Operation.java
codacy-badger/transformation-framework
f32d936c78b58b1cb58bf4c7e6f7befcfe7d7460
[ "Apache-2.0" ]
null
null
null
edmm-core/src/main/java/io/github/edmm/plugins/cloudify/model/azure/Operation.java
codacy-badger/transformation-framework
f32d936c78b58b1cb58bf4c7e6f7befcfe7d7460
[ "Apache-2.0" ]
null
null
null
edmm-core/src/main/java/io/github/edmm/plugins/cloudify/model/azure/Operation.java
codacy-badger/transformation-framework
f32d936c78b58b1cb58bf4c7e6f7befcfe7d7460
[ "Apache-2.0" ]
null
null
null
22.882353
99
0.674807
1,311
package io.github.edmm.plugins.cloudify.model.azure; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; public class Operation { @Setter @Getter private String name; @Setter @Getter private String source; @Getter private List<Script> scripts = new ArrayList<>(); public Operation(String name, String source) { this.name = name; this.source = source; } public void addScript(String name, String path) { List<String> previous = scripts.stream().map(Script::getName).collect(Collectors.toList()); Script result = Script.builder().name(name).path(path).previous(previous).build(); scripts.add(result); } }
3e032dac1767a0667768c533a4884eaf8fb9ad9a
1,337
java
Java
jaxb-ri/xjc/src/main/java/com/sun/tools/xjc/generator/bean/field/ConstFieldRenderer.java
clara0/jaxb-ri
9127f91d89fca5633e7acc18b1c5ca47f2d3db1a
[ "BSD-3-Clause" ]
140
2018-09-19T01:13:56.000Z
2022-03-28T21:25:15.000Z
jaxb-ri/xjc/src/main/java/com/sun/tools/xjc/generator/bean/field/ConstFieldRenderer.java
clara0/jaxb-ri
9127f91d89fca5633e7acc18b1c5ca47f2d3db1a
[ "BSD-3-Clause" ]
257
2018-09-21T17:52:36.000Z
2022-03-25T13:18:15.000Z
jaxb-ri/xjc/src/main/java/com/sun/tools/xjc/generator/bean/field/ConstFieldRenderer.java
clara0/jaxb-ri
9127f91d89fca5633e7acc18b1c5ca47f2d3db1a
[ "BSD-3-Clause" ]
96
2018-10-08T16:17:04.000Z
2022-03-04T21:06:26.000Z
31.093023
80
0.729993
1,312
/* * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.tools.xjc.generator.bean.field; import com.sun.tools.xjc.generator.bean.ClassOutlineImpl; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.outline.FieldOutline; /** * {@link FieldRenderer} for possibly constant field. * * <p> * Since we don't know if the constant can be actually generated until * we get to the codemodel building phase, this renderer lazily * determines if it wants to generate a constant field or a normal property. * * @author Kohsuke Kawaguchi */ final class ConstFieldRenderer implements FieldRenderer { private final FieldRenderer fallback; protected ConstFieldRenderer(FieldRenderer fallback) { this.fallback = fallback; } @Override public FieldOutline generate(ClassOutlineImpl outline, CPropertyInfo prop) { if(prop.defaultValue.compute(outline.parent())==null) return fallback.generate(outline, prop); else return new ConstField(outline,prop); } }
3e032ef3d08f6ce1bab9fad19ad29bf61798a65d
297
java
Java
QiunetUtils/src/main/java/org/qiunet/utils/listener/_EventHandlers.java
wenguangwen/DuoDuo
dd7b94386d2bfff5d638f933aa1f33ccd8a979db
[ "Apache-2.0" ]
null
null
null
QiunetUtils/src/main/java/org/qiunet/utils/listener/_EventHandlers.java
wenguangwen/DuoDuo
dd7b94386d2bfff5d638f933aa1f33ccd8a979db
[ "Apache-2.0" ]
null
null
null
QiunetUtils/src/main/java/org/qiunet/utils/listener/_EventHandlers.java
wenguangwen/DuoDuo
dd7b94386d2bfff5d638f933aa1f33ccd8a979db
[ "Apache-2.0" ]
null
null
null
15.631579
35
0.690236
1,313
package org.qiunet.utils.listener; import java.lang.annotation.*; /** * 容易和EventHandler 混淆. * 所以加个 _ */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface _EventHandlers { /*** * 这里应该填枚举值. 但是java限制很多 * 只能使用常量. * @return */ EventHandler[] value(); }
3e032f1cbb3ad52c2a036c9dfaf938c8830abb82
9,243
java
Java
de/fraunhofer/iais/eis/ConfigurationModelBuilder.java
International-Data-Spaces-Association/Java-Representation-of-IDS-Information-Model
ba5fe3f86f86d56f58cb2fef15f6fdd6b2d9d738
[ "Apache-2.0" ]
2
2021-06-23T07:28:13.000Z
2021-07-24T08:59:37.000Z
de/fraunhofer/iais/eis/ConfigurationModelBuilder.java
International-Data-Spaces-Association/Java-Representation-of-IDS-Information-Model
ba5fe3f86f86d56f58cb2fef15f6fdd6b2d9d738
[ "Apache-2.0" ]
13
2021-05-20T13:18:14.000Z
2021-11-24T08:01:18.000Z
de/fraunhofer/iais/eis/ConfigurationModelBuilder.java
International-Data-Spaces-Association/Java-Representation-of-IDS-Information-Model
ba5fe3f86f86d56f58cb2fef15f6fdd6b2d9d738
[ "Apache-2.0" ]
1
2021-10-03T15:23:31.000Z
2021-10-03T15:23:31.000Z
35.964981
112
0.719031
1,314
package de.fraunhofer.iais.eis; import java.net.URI; import java.util.List; import de.fraunhofer.iais.eis.util.*; public class ConfigurationModelBuilder implements Builder<ConfigurationModel> { private ConfigurationModelImpl configurationModelImpl; public ConfigurationModelBuilder() { configurationModelImpl = new ConfigurationModelImpl(); } public ConfigurationModelBuilder(URI id) { this(); configurationModelImpl.id = id; } /** * This function allows setting a value for _userAuthentication * * @param _userAuthentication_ desired value to be set * @return Builder object with new value for _userAuthentication */ public ConfigurationModelBuilder _userAuthentication_(List<UserAuthentication> _userAuthentication_) { this.configurationModelImpl.setUserAuthentication(_userAuthentication_); return this; } /** * This function allows adding a value to the List _userAuthentication * * @param _userAuthentication_ desired value to be added * @return Builder object with new value for _userAuthentication */ public ConfigurationModelBuilder _userAuthentication_(UserAuthentication _userAuthentication_) { this.configurationModelImpl.getUserAuthentication().add(_userAuthentication_); return this; } /** * This function allows setting a value for _configurationModelLogLevel * * @param _configurationModelLogLevel_ desired value to be set * @return Builder object with new value for _configurationModelLogLevel */ public ConfigurationModelBuilder _configurationModelLogLevel_(LogLevel _configurationModelLogLevel_) { this.configurationModelImpl.setConfigurationModelLogLevel(_configurationModelLogLevel_); return this; } /** * This function allows setting a value for _connectorStatus * * @param _connectorStatus_ desired value to be set * @return Builder object with new value for _connectorStatus */ public ConfigurationModelBuilder _connectorStatus_(ConnectorStatus _connectorStatus_) { this.configurationModelImpl.setConnectorStatus(_connectorStatus_); return this; } /** * This function allows setting a value for _connectorDeployMode * * @param _connectorDeployMode_ desired value to be set * @return Builder object with new value for _connectorDeployMode */ public ConfigurationModelBuilder _connectorDeployMode_(ConnectorDeployMode _connectorDeployMode_) { this.configurationModelImpl.setConnectorDeployMode(_connectorDeployMode_); return this; } /** * This function allows setting a value for _connectorDescription * * @param _connectorDescription_ desired value to be set * @return Builder object with new value for _connectorDescription */ public ConfigurationModelBuilder _connectorDescription_(Connector _connectorDescription_) { this.configurationModelImpl.setConnectorDescription(_connectorDescription_); return this; } /** * This function allows setting a value for _connectorProxy * * @param _connectorProxy_ desired value to be set * @return Builder object with new value for _connectorProxy */ public ConfigurationModelBuilder _connectorProxy_(List<Proxy> _connectorProxy_) { this.configurationModelImpl.setConnectorProxy(_connectorProxy_); return this; } /** * This function allows adding a value to the List _connectorProxy * * @param _connectorProxy_ desired value to be added * @return Builder object with new value for _connectorProxy */ public ConfigurationModelBuilder _connectorProxy_(Proxy _connectorProxy_) { this.configurationModelImpl.getConnectorProxy().add(_connectorProxy_); return this; } /** * This function allows setting a value for _trustStore * * @param _trustStore_ desired value to be set * @return Builder object with new value for _trustStore */ public ConfigurationModelBuilder _trustStore_(URI _trustStore_) { this.configurationModelImpl.setTrustStore(_trustStore_); return this; } /** * This function allows setting a value for _trustStoreAlias * * @param _trustStoreAlias_ desired value to be set * @return Builder object with new value for _trustStoreAlias */ public ConfigurationModelBuilder _trustStoreAlias_(String _trustStoreAlias_) { this.configurationModelImpl.setTrustStoreAlias(_trustStoreAlias_); return this; } /** * This function allows setting a value for _trustStorePassword * * @param _trustStorePassword_ desired value to be set * @return Builder object with new value for _trustStorePassword */ public ConfigurationModelBuilder _trustStorePassword_(String _trustStorePassword_) { this.configurationModelImpl.setTrustStorePassword(_trustStorePassword_); return this; } /** * This function allows setting a value for _keyStore * * @param _keyStore_ desired value to be set * @return Builder object with new value for _keyStore */ public ConfigurationModelBuilder _keyStore_(URI _keyStore_) { this.configurationModelImpl.setKeyStore(_keyStore_); return this; } /** * This function allows setting a value for _keyStoreAlias * * @param _keyStoreAlias_ desired value to be set * @return Builder object with new value for _keyStoreAlias */ public ConfigurationModelBuilder _keyStoreAlias_(String _keyStoreAlias_) { this.configurationModelImpl.setKeyStoreAlias(_keyStoreAlias_); return this; } /** * This function allows setting a value for _keyStorePassword * * @param _keyStorePassword_ desired value to be set * @return Builder object with new value for _keyStorePassword */ public ConfigurationModelBuilder _keyStorePassword_(String _keyStorePassword_) { this.configurationModelImpl.setKeyStorePassword(_keyStorePassword_); return this; } /** * This function allows setting a value for _configuredBroker * * @param _configuredBroker_ desired value to be set * @return Builder object with new value for _configuredBroker */ public ConfigurationModelBuilder _configuredBroker_(BrokerCatalog _configuredBroker_) { this.configurationModelImpl.setConfiguredBroker(_configuredBroker_); return this; } /** * This function allows setting a value for _appRoute * * @param _appRoute_ desired value to be set * @return Builder object with new value for _appRoute */ public ConfigurationModelBuilder _appRoute_(List<AppRoute> _appRoute_) { this.configurationModelImpl.setAppRoute(_appRoute_); return this; } /** * This function allows adding a value to the List _appRoute * * @param _appRoute_ desired value to be added * @return Builder object with new value for _appRoute */ public ConfigurationModelBuilder _appRoute_(AppRoute _appRoute_) { this.configurationModelImpl.getAppRoute().add(_appRoute_); return this; } /** * This function allows setting a value for _configuredAppStore * * @param _configuredAppStore_ desired value to be set * @return Builder object with new value for _configuredAppStore */ public ConfigurationModelBuilder _configuredAppStore_(AppStoreCatalog _configuredAppStore_) { this.configurationModelImpl.setConfiguredAppStore(_configuredAppStore_); return this; } /** * This function allows setting a value for _configuredAppResource * * @param _configuredAppResource_ desired value to be set * @return Builder object with new value for _configuredAppResource */ public ConfigurationModelBuilder _configuredAppResource_(AppResourceCatalog _configuredAppResource_) { this.configurationModelImpl.setConfiguredAppResource(_configuredAppResource_); return this; } /** * This function allows setting a value for _configuredClearingHouse * * @param _configuredClearingHouse_ desired value to be set * @return Builder object with new value for _configuredClearingHouse */ public ConfigurationModelBuilder _configuredClearingHouse_(ClearingHouseCatalog _configuredClearingHouse_) { this.configurationModelImpl.setConfiguredClearingHouse(_configuredClearingHouse_); return this; } /** * This function takes the values that were set previously via the other functions of this class and * turns them into a Java bean. * * @return Bean with specified values * @throws ConstraintViolationException This exception is thrown, if a validator is used and a * violation is found. */ @Override public ConfigurationModel build() throws ConstraintViolationException { VocabUtil.getInstance().validate(configurationModelImpl); return configurationModelImpl; } }
3e032f32957d62eda2ce721a61ab9b4a3100a833
6,970
java
Java
datavec/datavec-api/src/test/java/org/datavec/api/transform/ops/AggregableMultiOpTest.java
raver119/deeplearning4j
7502e41e6291151b121eb11983456c3f4473a08f
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
datavec/datavec-api/src/test/java/org/datavec/api/transform/ops/AggregableMultiOpTest.java
fbrunacci/deeplearning4j
a76f957b72056138340a09ca654cd3ac395e3660
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
datavec/datavec-api/src/test/java/org/datavec/api/transform/ops/AggregableMultiOpTest.java
fbrunacci/deeplearning4j
a76f957b72056138340a09ca654cd3ac395e3660
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
43.836478
100
0.647633
1,315
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.datavec.api.transform.ops; import org.datavec.api.writable.Writable; import org.junit.Test; import org.nd4j.common.tests.BaseND4JTest; import java.io.Serializable; import java.util.*; import static org.junit.Assert.assertTrue; /** * Created by huitseeker on 5/14/17. */ public class AggregableMultiOpTest extends BaseND4JTest { private List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); @Test public void testMulti() throws Exception { AggregatorImpls.AggregableFirst<Integer> af = new AggregatorImpls.AggregableFirst<>(); AggregatorImpls.AggregableSum<Integer> as = new AggregatorImpls.AggregableSum<>(); AggregableMultiOp<Integer> multi = new AggregableMultiOp<>(Arrays.asList(af, as)); assertTrue(multi.getOperations().size() == 2); for (int i = 0; i < intList.size(); i++) { multi.accept(intList.get(i)); } // mutablility assertTrue(as.get().toDouble() == 45D); assertTrue(af.get().toInt() == 1); List<Writable> res = multi.get(); assertTrue(res.get(1).toDouble() == 45D); assertTrue(res.get(0).toInt() == 1); AggregatorImpls.AggregableFirst<Integer> rf = new AggregatorImpls.AggregableFirst<>(); AggregatorImpls.AggregableSum<Integer> rs = new AggregatorImpls.AggregableSum<>(); AggregableMultiOp<Integer> reverse = new AggregableMultiOp<>(Arrays.asList(rf, rs)); for (int i = 0; i < intList.size(); i++) { reverse.accept(intList.get(intList.size() - i - 1)); } List<Writable> revRes = reverse.get(); assertTrue(revRes.get(1).toDouble() == 45D); assertTrue(revRes.get(0).toInt() == 9); multi.combine(reverse); List<Writable> combinedRes = multi.get(); assertTrue(combinedRes.get(1).toDouble() == 90D); assertTrue(combinedRes.get(0).toInt() == 1); } @Test public void testAllAggregateOpsAreSerializable() throws Exception { Set<String> allTypes = new HashSet<>(); allTypes.add("org.datavec.api.transform.ops.LongWritableOp"); allTypes.add("org.datavec.api.transform.ops.IntWritableOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableMean"); allTypes.add("org.datavec.api.transform.ops.StringAggregatorImpls$AggregableStringReduce"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableRange"); allTypes.add("org.datavec.api.transform.ops.AggregatorImplsTest"); allTypes.add("org.datavec.api.transform.ops.DispatchWithConditionOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableVariance"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls"); allTypes.add("org.datavec.api.transform.ops.FloatWritableOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableProd"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableLast"); allTypes.add("org.datavec.api.transform.ops.StringAggregatorImpls$AggregableStringPrepend"); allTypes.add("org.datavec.api.transform.ops.ByteWritableOp"); allTypes.add("org.datavec.api.transform.ops.AggregableMultiOpTest"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableStdDev"); allTypes.add("org.datavec.api.transform.ops.StringAggregatorImpls$1"); allTypes.add("org.datavec.api.transform.ops.DispatchOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableMin"); allTypes.add("org.datavec.api.transform.ops.StringAggregatorImpls$AggregableStringAppend"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableCount"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableSum"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregablePopulationVariance"); allTypes.add("org.datavec.api.transform.ops.AggregableCheckingOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableMax"); allTypes.add("org.datavec.api.transform.ops.AggregableMultiOp"); allTypes.add("org.datavec.api.transform.ops.IAggregableReduceOp"); allTypes.add("org.datavec.api.transform.ops.DispatchOpTest"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableCountUnique"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableUncorrectedStdDev"); allTypes.add("org.datavec.api.transform.ops.StringWritableOp"); allTypes.add("org.datavec.api.transform.ops.StringAggregatorImpls"); allTypes.add("org.datavec.api.transform.ops.DoubleWritableOp"); allTypes.add("org.datavec.api.transform.ops.AggregatorImpls$AggregableFirst"); Set<String> ops = new HashSet<>(); for (String type : allTypes) { if (type.startsWith("org.datavec.api.transform.ops")) { if (type.endsWith("Op")) { ops.add(type); } if (type.contains("Aggregable") && !type.endsWith("Test")) { ops.add(type); } } } for (String op : ops) { Class<?> cls = Class.forName(op); assertTrue(op + " should implement Serializable", implementsSerializable(cls)); } } private boolean implementsSerializable(Class<?> cls) { if (cls == null) { return false; } if (cls == Serializable.class) { return true; } Class<?>[] interfaces = cls.getInterfaces(); Set<Class<?>> parents = new HashSet<>(); parents.add(cls.getSuperclass()); for (Class<?> anInterface : interfaces) { Collections.addAll(parents, anInterface.getInterfaces()); if (anInterface.equals(Serializable.class)) { return true; } } for (Class<?> parent : parents) { if (implementsSerializable(parent)) { return true; } } return false; } }
3e032f849777f962511b77316dee8fc5fa576bf2
1,292
java
Java
grobid-core/src/main/java/org/grobid/core/lang/impl/CybozuLanguageDetector.java
vikhil0609/grobid
50f9ed5766d4d1b3bae6f00597482ae1095f8c9d
[ "Apache-2.0" ]
1,666
2015-02-02T17:09:07.000Z
2022-03-31T21:40:48.000Z
grobid-core/src/main/java/org/grobid/core/lang/impl/CybozuLanguageDetector.java
vikhil0609/grobid
50f9ed5766d4d1b3bae6f00597482ae1095f8c9d
[ "Apache-2.0" ]
844
2015-01-05T14:36:47.000Z
2022-03-29T08:47:31.000Z
grobid-core/src/main/java/org/grobid/core/lang/impl/CybozuLanguageDetector.java
vikhil0609/grobid
50f9ed5766d4d1b3bae6f00597482ae1095f8c9d
[ "Apache-2.0" ]
348
2015-01-12T01:48:36.000Z
2022-03-24T12:38:06.000Z
34.918919
112
0.676471
1,316
package org.grobid.core.lang.impl; import com.cybozu.labs.langdetect.Detector; import com.cybozu.labs.langdetect.DetectorFactory; import com.cybozu.labs.langdetect.LangDetectException; import org.grobid.core.lang.Language; import org.grobid.core.lang.LanguageDetector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; public class CybozuLanguageDetector implements LanguageDetector { private static final Logger LOGGER = LoggerFactory.getLogger(CybozuLanguageDetector.class); @Override public Language detect(String text) { Detector detector; try { detector = DetectorFactory.create(); detector.append(text); ArrayList<com.cybozu.labs.langdetect.Language> probabilities = detector.getProbabilities(); if (probabilities == null || probabilities.isEmpty()) { return null; } LOGGER.debug(probabilities.toString()); com.cybozu.labs.langdetect.Language l = probabilities.get(0); return new Language(l.lang, l.prob); } catch (LangDetectException e) { LOGGER.warn("Cannot detect language because of: " + e.getClass().getName() + ": " + e.getMessage()); return null; } } }
3e03305f3bb21859b03de4b20da72467e1f48654
1,824
java
Java
hatunatu-util/src/main/java/jp/fieldnotes/hatunatu/util/exception/NoSuchFieldRuntimeException.java
azusa/hatunatu
f31a8a8e6fa819cf89d41d2fec44c5958326454c
[ "Apache-2.0" ]
null
null
null
hatunatu-util/src/main/java/jp/fieldnotes/hatunatu/util/exception/NoSuchFieldRuntimeException.java
azusa/hatunatu
f31a8a8e6fa819cf89d41d2fec44c5958326454c
[ "Apache-2.0" ]
null
null
null
hatunatu-util/src/main/java/jp/fieldnotes/hatunatu/util/exception/NoSuchFieldRuntimeException.java
azusa/hatunatu
f31a8a8e6fa819cf89d41d2fec44c5958326454c
[ "Apache-2.0" ]
null
null
null
26.434783
86
0.660088
1,317
/* * Copyright 2004-2012 the Seasar Foundation and the Others. * * 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 jp.fieldnotes.hatunatu.util.exception; import jp.fieldnotes.hatunatu.util.collection.ArrayUtil; /** * {@link NoSuchFieldException}をラップする例外です。 * * @author higa */ public class NoSuchFieldRuntimeException extends SRuntimeException { private static final long serialVersionUID = 6609175673610180338L; private final Class<?> targetClass; private final String fieldName; /** * {@link NoSuchFieldRuntimeException}を作成します。 * * @param targetClass * ターゲットクラス * @param fieldName * フィールド名 * @param cause * 原因となった例外 */ public NoSuchFieldRuntimeException(final Class<?> targetClass, final String fieldName, final Throwable cause) { super("EUTL0070", ArrayUtil.asArray(targetClass.getName(), fieldName), cause); this.targetClass = targetClass; this.fieldName = fieldName; } /** * ターゲットクラスを返します。 * * @return ターゲットクラス */ public Class<?> getTargetClass() { return targetClass; } /** * フィールド名を返します。 * * @return フィールド名 */ public String getFieldName() { return fieldName; } }
3e0330c1934c2e3b90f2f8291bc8e4b757781e5e
1,278
java
Java
src/main/java/com/carlosarroyoam/users/exception/mapper/WebApplicationExceptionMapper.java
carlosarroyoam/Development-WebServices
b78f0e69a8dcf663d22f8b7a58275c92fed00c72
[ "Apache-2.0" ]
null
null
null
src/main/java/com/carlosarroyoam/users/exception/mapper/WebApplicationExceptionMapper.java
carlosarroyoam/Development-WebServices
b78f0e69a8dcf663d22f8b7a58275c92fed00c72
[ "Apache-2.0" ]
null
null
null
src/main/java/com/carlosarroyoam/users/exception/mapper/WebApplicationExceptionMapper.java
carlosarroyoam/Development-WebServices
b78f0e69a8dcf663d22f8b7a58275c92fed00c72
[ "Apache-2.0" ]
null
null
null
32.769231
101
0.798905
1,318
package com.carlosarroyoam.users.exception.mapper; import java.time.ZoneId; import java.time.ZonedDateTime; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import com.carlosarroyoam.users.dto.APIErrorDto; /** * An {@link ExceptionMapper} implementation for all * {@link WebApplicationException}s. */ @Provider public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Context private UriInfo uriInfo; @Override public Response toResponse(WebApplicationException exception) { APIErrorDto apiErrorDto = new APIErrorDto(); apiErrorDto.setMessage(exception.getMessage()); apiErrorDto.setError(exception.getResponse().getStatusInfo().getReasonPhrase()); apiErrorDto.setStatus(exception.getResponse().getStatusInfo().getStatusCode()); apiErrorDto.setPath(uriInfo.getPath()); apiErrorDto.setTimestamp(ZonedDateTime.now(ZoneId.of("UTC")).withFixedOffsetZone()); return Response.status(exception.getResponse().getStatusInfo().getStatusCode()).entity(apiErrorDto) .type(MediaType.APPLICATION_JSON).build(); } }
3e03311898858c541a532fc2cc1d81a55864977b
2,181
java
Java
Android/app/src/main/java/com/serviciomecanico/serviciomecanico/Adaptadores/HerramientaAdapter.java
dannyhvalenz/TallerMecanicoAndroid
d5b14f8bdfa4b7a5afaa627bc57d383dd1105f4a
[ "MIT" ]
1
2019-05-09T22:32:12.000Z
2019-05-09T22:32:12.000Z
Android/app/src/main/java/com/serviciomecanico/serviciomecanico/Adaptadores/HerramientaAdapter.java
dannyhvalenz/TallerMecanicoAndroid
d5b14f8bdfa4b7a5afaa627bc57d383dd1105f4a
[ "MIT" ]
null
null
null
Android/app/src/main/java/com/serviciomecanico/serviciomecanico/Adaptadores/HerramientaAdapter.java
dannyhvalenz/TallerMecanicoAndroid
d5b14f8bdfa4b7a5afaa627bc57d383dd1105f4a
[ "MIT" ]
2
2019-05-01T13:22:03.000Z
2019-05-01T17:05:05.000Z
35.177419
125
0.755158
1,319
package com.serviciomecanico.serviciomecanico.Adaptadores; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.serviciomecanico.serviciomecanico.Modelo.Herramienta; import com.serviciomecanico.serviciomecanico.Modelo.Inventario; import com.serviciomecanico.serviciomecanico.R; import java.util.List; public class HerramientaAdapter extends RecyclerView.Adapter<HerramientaAdapter.ViewHolder> { List<Herramienta> herramienta; static Context context; public static class ViewHolder extends RecyclerView.ViewHolder{ public CardView cdv_herramienta; public TextView edt_marca_herramienta, edt_cantidad_herramienta, txv_nombre_herramienta, txv_descripcion_herramienta; public ViewHolder(View view){ super(view); cdv_herramienta = view.findViewById(R.id.cdv_herramienta); edt_marca_herramienta = view.findViewById(R.id.edt_marca_herramienta); edt_cantidad_herramienta = view.findViewById(R.id.edt_cantidad_herramienta); txv_nombre_herramienta = view.findViewById(R.id.txv_nombre_herramienta); txv_descripcion_herramienta = view.findViewById(R.id.txv_descripcion_herramienta); } } public HerramientaAdapter(Context context, List<Herramienta> herramienta){ this.context = context; this.herramienta = herramienta; } //Crecion del holder @NonNull @Override public HerramientaAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.herramienta,parent,false); HerramientaAdapter.ViewHolder viewHolder = new HerramientaAdapter.ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { } @Override public int getItemCount() { return herramienta.size(); } }
3e03315199d85047e8c63c378374791e2fb39513
1,490
java
Java
Bukkit/SQApocalypse/src/main/java/com/starquestminecraft/bukkit/apocalypse/task/ScoreUpdateTask.java
Steffbeard/StarQuestCode
2ad542226410aed33d2a6061522c94463a3c4470
[ "MIT" ]
null
null
null
Bukkit/SQApocalypse/src/main/java/com/starquestminecraft/bukkit/apocalypse/task/ScoreUpdateTask.java
Steffbeard/StarQuestCode
2ad542226410aed33d2a6061522c94463a3c4470
[ "MIT" ]
null
null
null
Bukkit/SQApocalypse/src/main/java/com/starquestminecraft/bukkit/apocalypse/task/ScoreUpdateTask.java
Steffbeard/StarQuestCode
2ad542226410aed33d2a6061522c94463a3c4470
[ "MIT" ]
null
null
null
28.113208
111
0.696644
1,320
package com.starquestminecraft.bukkit.apocalypse.task; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.starquestminecraft.bukkit.apocalypse.SQApocalypse; public class ScoreUpdateTask extends BukkitRunnable { private final SQApocalypse plugin; private final RegionManager rm; private final WorldGuardPlugin wg; public ScoreUpdateTask(final SQApocalypse plugin) { this.plugin = plugin; this.wg = WorldGuardPlugin.inst(); this.rm = wg.getRegionManager(plugin.getServer().getWorld(plugin.getServer().getServerName())); } @Override public void run() { plugin.getLogger().info("Updating scores."); for(Player player : plugin.getServer().getOnlinePlayers()) { ApplicableRegionSet set = rm.getApplicableRegions(player.getLocation()); for(ProtectedRegion region : set) { if(region.getId().equalsIgnoreCase("OriginStation")) { player.sendMessage("Your score was not updated because you are in the spawn no-pvp zone."); } } plugin.getDB().addScore(player.getUniqueId(), 1); } } }
3e0333248aafac7159e47513c06c7728ce7abea0
315
java
Java
src/de/theholyexception/holyapi/datastorage/dataconnection/enums/DataDefaultValue.java
TheHolyException/HolyAPI
403582a2c71e3f94037f84cdaf7c050040d0b112
[ "BSD-3-Clause" ]
null
null
null
src/de/theholyexception/holyapi/datastorage/dataconnection/enums/DataDefaultValue.java
TheHolyException/HolyAPI
403582a2c71e3f94037f84cdaf7c050040d0b112
[ "BSD-3-Clause" ]
null
null
null
src/de/theholyexception/holyapi/datastorage/dataconnection/enums/DataDefaultValue.java
TheHolyException/HolyAPI
403582a2c71e3f94037f84cdaf7c050040d0b112
[ "BSD-3-Clause" ]
null
null
null
15.75
69
0.733333
1,321
package de.theholyexception.holyapi.datastorage.dataconnection.enums; public enum DataDefaultValue { NULL("DEFAULT NULL"), AUTO_INCREMENT("AUTO_INCREMENT"), CUSTOM(null); private String value; DataDefaultValue(String value) { this.value = value; } public String getValue() { return value; } }
3e0333e04a9a59a7590030073481544b43d747f5
19,972
java
Java
openfire_src/work/jspc/java/org/jivesoftware/openfire/admin/private_002ddata_002dsettings_jsp.java
paridhika/XMPP_Parking
180298d0d689362056c9f9950bd2ac30265f76ed
[ "Apache-2.0" ]
4
2016-09-02T13:34:24.000Z
2016-11-17T05:11:06.000Z
openfire_src/work/jspc/java/org/jivesoftware/openfire/admin/private_002ddata_002dsettings_jsp.java
paridhika/XMPP_Parking
180298d0d689362056c9f9950bd2ac30265f76ed
[ "Apache-2.0" ]
null
null
null
openfire_src/work/jspc/java/org/jivesoftware/openfire/admin/private_002ddata_002dsettings_jsp.java
paridhika/XMPP_Parking
180298d0d689362056c9f9950bd2ac30265f76ed
[ "Apache-2.0" ]
null
null
null
62.4125
309
0.760615
1,322
/* * Generated by the Jasper component of Apache Tomcat * Version: JspC/ApacheTomcat8 * Generated at: 2016-08-23 16:29:31 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.jivesoftware.openfire.admin; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import org.jivesoftware.util.*; import org.jivesoftware.openfire.*; public final class private_002ddata_002dsettings_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, "error.jsp", true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n\n\n\n\n\n"); org.jivesoftware.util.WebManager webManager = null; webManager = (org.jivesoftware.util.WebManager) _jspx_page_context.getAttribute("webManager", javax.servlet.jsp.PageContext.PAGE_SCOPE); if (webManager == null){ webManager = new org.jivesoftware.util.WebManager(); _jspx_page_context.setAttribute("webManager", webManager, javax.servlet.jsp.PageContext.PAGE_SCOPE); } out.write('\n'); webManager.init(request, response, session, application, out ); out.write("\n\n<html>\n<head>\n<title>"); if (_jspx_meth_fmt_005fmessage_005f0(_jspx_page_context)) return; out.write("</title>\n<meta name=\"pageID\" content=\"server-data-settings\"/>\n<meta name=\"helpPage\" content=\"set_private_data_storage_policy.html\"/>\n</head>\n<body>\n\n"); // Get parameters: boolean update = request.getParameter("update") != null; boolean privateEnabled = ParamUtils.getBooleanParameter(request,"privateEnabled"); // Get an audit manager: PrivateStorage privateStorage = webManager.getPrivateStore(); if (update) { privateStorage.setEnabled(privateEnabled); // Log the event webManager.logEvent((privateEnabled ? "enabled" : "disabled")+" private data storage", null); out.write("\n <div class=\"jive-success\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n <tbody>\n <tr><td class=\"jive-icon\"><img src=\"images/success-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></td>\n <td class=\"jive-icon-label\">\n "); if (_jspx_meth_fmt_005fmessage_005f1(_jspx_page_context)) return; out.write("\n </td></tr>\n </tbody>\n </table>\n </div><br>\n "); } // Set page vars privateEnabled = privateStorage.isEnabled(); out.write("\n\n<p>\n"); if (_jspx_meth_fmt_005fmessage_005f2(_jspx_page_context)) return; out.write("\n</p>\n\n<!-- BEGIN 'Set Private Data Policy' -->\n<form action=\"private-data-settings.jsp\">\n\t<div class=\"jive-contentBoxHeader\">\n\t\t"); if (_jspx_meth_fmt_005fmessage_005f3(_jspx_page_context)) return; out.write("\n\t</div>\n\t<div class=\"jive-contentBox\">\n\t\t<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n\t\t<tbody>\n\t\t\t<tr valign=\"top\">\n\t\t\t\t<td width=\"1%\" nowrap>\n\t\t\t\t\t<input type=\"radio\" name=\"privateEnabled\" value=\"true\" id=\"rb01\"\n\t\t\t\t\t "); out.print( (privateEnabled ? "checked" : "") ); out.write(">\n\t\t\t\t</td>\n\t\t\t\t<td width=\"99%\">\n\t\t\t\t\t<label for=\"rb01\">\n\t\t\t\t\t<b>"); if (_jspx_meth_fmt_005fmessage_005f4(_jspx_page_context)) return; out.write("</b> -\n\t\t\t\t\t"); if (_jspx_meth_fmt_005fmessage_005f5(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</label>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr valign=\"top\">\n\t\t\t\t<td width=\"1%\" nowrap>\n\t\t\t\t\t<input type=\"radio\" name=\"privateEnabled\" value=\"false\" id=\"rb02\"\n\t\t\t\t\t "); out.print( (!privateEnabled ? "checked" : "") ); out.write(">\n\t\t\t\t</td>\n\t\t\t\t<td width=\"99%\">\n\t\t\t\t\t<label for=\"rb02\">\n\t\t\t\t\t<b>"); if (_jspx_meth_fmt_005fmessage_005f6(_jspx_page_context)) return; out.write("</b> -\n\t\t\t\t\t"); if (_jspx_meth_fmt_005fmessage_005f7(_jspx_page_context)) return; out.write("\n\t\t\t\t\t</label>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t</div>\n <input type=\"submit\" name=\"update\" value=\""); if (_jspx_meth_fmt_005fmessage_005f8(_jspx_page_context)) return; out.write("\">\n</form>\n<!-- END 'Set Private Data Policy' -->\n\n</body>\n</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_fmt_005fmessage_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f0.setParent(null); // /private-data-settings.jsp(33,7) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f0.setKey("private.data.settings.title"); int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag(); if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return false; } private boolean _jspx_meth_fmt_005fmessage_005f1(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f1.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f1.setParent(null); // /private-data-settings.jsp(56,8) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f1.setKey("private.data.settings.update"); int _jspx_eval_fmt_005fmessage_005f1 = _jspx_th_fmt_005fmessage_005f1.doStartTag(); if (_jspx_th_fmt_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f1); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f1); return false; } private boolean _jspx_meth_fmt_005fmessage_005f2(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f2 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f2.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f2.setParent(null); // /private-data-settings.jsp(70,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f2.setKey("private.data.settings.info"); int _jspx_eval_fmt_005fmessage_005f2 = _jspx_th_fmt_005fmessage_005f2.doStartTag(); if (_jspx_th_fmt_005fmessage_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f2); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f2); return false; } private boolean _jspx_meth_fmt_005fmessage_005f3(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f3 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f3.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f3.setParent(null); // /private-data-settings.jsp(76,2) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f3.setKey("private.data.settings.policy"); int _jspx_eval_fmt_005fmessage_005f3 = _jspx_th_fmt_005fmessage_005f3.doStartTag(); if (_jspx_th_fmt_005fmessage_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f3); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f3); return false; } private boolean _jspx_meth_fmt_005fmessage_005f4(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f4 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f4.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f4.setParent(null); // /private-data-settings.jsp(88,8) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f4.setKey("private.data.settings.enable_storage"); int _jspx_eval_fmt_005fmessage_005f4 = _jspx_th_fmt_005fmessage_005f4.doStartTag(); if (_jspx_th_fmt_005fmessage_005f4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f4); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f4); return false; } private boolean _jspx_meth_fmt_005fmessage_005f5(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f5 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f5.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f5.setParent(null); // /private-data-settings.jsp(89,5) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f5.setKey("private.data.settings.enable_storage_info"); int _jspx_eval_fmt_005fmessage_005f5 = _jspx_th_fmt_005fmessage_005f5.doStartTag(); if (_jspx_th_fmt_005fmessage_005f5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f5); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f5); return false; } private boolean _jspx_meth_fmt_005fmessage_005f6(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f6 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f6.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f6.setParent(null); // /private-data-settings.jsp(100,8) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f6.setKey("private.data.settings.disable_storage"); int _jspx_eval_fmt_005fmessage_005f6 = _jspx_th_fmt_005fmessage_005f6.doStartTag(); if (_jspx_th_fmt_005fmessage_005f6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f6); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f6); return false; } private boolean _jspx_meth_fmt_005fmessage_005f7(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f7 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f7.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f7.setParent(null); // /private-data-settings.jsp(101,5) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f7.setKey("private.data.settings.disable_storage_info"); int _jspx_eval_fmt_005fmessage_005f7 = _jspx_th_fmt_005fmessage_005f7.doStartTag(); if (_jspx_th_fmt_005fmessage_005f7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f7); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f7); return false; } private boolean _jspx_meth_fmt_005fmessage_005f8(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f8 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f8.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f8.setParent(null); // /private-data-settings.jsp(108,46) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f8.setKey("global.save_settings"); int _jspx_eval_fmt_005fmessage_005f8 = _jspx_th_fmt_005fmessage_005f8.doStartTag(); if (_jspx_th_fmt_005fmessage_005f8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f8); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f8); return false; } }
3e0333ecbc35d7bda479a22c37110f4ebda66e17
136
java
Java
qt-creator-opensource-src-4.6.1/src/shared/qbs/tests/auto/blackbox/testdata-java/java/inner-class/InnerClass.java
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
Src/shared/qbs/tests/auto/blackbox/testdata-java/java/inner-class/InnerClass.java
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
null
null
null
Src/shared/qbs/tests/auto/blackbox/testdata-java/java/inner-class/InnerClass.java
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
19.428571
64
0.720588
1,323
public class InnerClass { private final InnerInnerClass clazz = new InnerInnerClass(); private class InnerInnerClass { } }
3e0335978d0af80f69ceeaa9053a73e928de4e5d
2,720
java
Java
runescape-client/src/main/java/class290.java
archubbuck/runelite
6583edb634ec65b8515367cb52f6d27507d9c3d7
[ "BSD-2-Clause" ]
1
2020-01-07T18:55:42.000Z
2020-01-07T18:55:42.000Z
runescape-client/src/main/java/class290.java
archubbuck/runelite
6583edb634ec65b8515367cb52f6d27507d9c3d7
[ "BSD-2-Clause" ]
null
null
null
runescape-client/src/main/java/class290.java
archubbuck/runelite
6583edb634ec65b8515367cb52f6d27507d9c3d7
[ "BSD-2-Clause" ]
3
2020-01-23T15:16:33.000Z
2020-06-28T15:19:58.000Z
20.923077
75
0.561765
1,324
import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("kh") public class class290 { @ObfuscatedName("c") static char[] field3646; @ObfuscatedName("t") static char[] field3648; @ObfuscatedName("o") static char[] field3647; @ObfuscatedName("e") static int[] field3645; static { field3646 = new char[64]; int var0; for (var0 = 0; var0 < 26; ++var0) { field3646[var0] = (char)(var0 + 65); } for (var0 = 26; var0 < 52; ++var0) { field3646[var0] = (char)(var0 + 97 - 26); } for (var0 = 52; var0 < 62; ++var0) { field3646[var0] = (char)(var0 + 48 - 52); } field3646[62] = '+'; field3646[63] = '/'; field3648 = new char[64]; for (var0 = 0; var0 < 26; ++var0) { field3648[var0] = (char)(var0 + 65); } for (var0 = 26; var0 < 52; ++var0) { field3648[var0] = (char)(var0 + 97 - 26); } for (var0 = 52; var0 < 62; ++var0) { field3648[var0] = (char)(var0 + 48 - 52); } field3648[62] = '*'; field3648[63] = '-'; field3647 = new char[64]; for (var0 = 0; var0 < 26; ++var0) { field3647[var0] = (char)(var0 + 65); } for (var0 = 26; var0 < 52; ++var0) { field3647[var0] = (char)(var0 + 97 - 26); } for (var0 = 52; var0 < 62; ++var0) { field3647[var0] = (char)(var0 + 48 - 52); } field3647[62] = '-'; field3647[63] = '_'; field3645 = new int[128]; for (var0 = 0; var0 < field3645.length; ++var0) { field3645[var0] = -1; } for (var0 = 65; var0 <= 90; ++var0) { field3645[var0] = var0 - 65; } for (var0 = 97; var0 <= 122; ++var0) { field3645[var0] = var0 - 97 + 26; } for (var0 = 48; var0 <= 57; ++var0) { field3645[var0] = var0 - 48 + 52; } int[] var2 = field3645; field3645[43] = 62; var2[42] = 62; int[] var1 = field3645; field3645[47] = 63; var1[45] = 63; } @ObfuscatedName("c") @ObfuscatedSignature( signature = "([Ljava/lang/CharSequence;III)Ljava/lang/String;", garbageValue = "-514037609" ) public static String method5360(CharSequence[] var0, int var1, int var2) { if (var2 == 0) { return ""; } else if (var2 == 1) { CharSequence var3 = var0[var1]; return var3 == null ? "null" : var3.toString(); } else { int var8 = var2 + var1; int var4 = 0; for (int var5 = var1; var5 < var8; ++var5) { CharSequence var6 = var0[var5]; if (var6 == null) { var4 += 4; } else { var4 += var6.length(); } } StringBuilder var9 = new StringBuilder(var4); for (int var10 = var1; var10 < var8; ++var10) { CharSequence var7 = var0[var10]; if (var7 == null) { var9.append("null"); } else { var9.append(var7); } } return var9.toString(); } } }
3e033639640b9feefc571473d604b41fc2ca4399
5,691
java
Java
Lesson06-Visualizer-Preferences/T06.10-Exercise-EditTextPreferenceConstraints/app/src/main/java/android/example/com/visualizerpreferences/SettingsFragment.java
nehabalaji/exercise
40b53c36ad4c32083050c1299fa5eb0f5976e011
[ "Apache-2.0" ]
null
null
null
Lesson06-Visualizer-Preferences/T06.10-Exercise-EditTextPreferenceConstraints/app/src/main/java/android/example/com/visualizerpreferences/SettingsFragment.java
nehabalaji/exercise
40b53c36ad4c32083050c1299fa5eb0f5976e011
[ "Apache-2.0" ]
null
null
null
Lesson06-Visualizer-Preferences/T06.10-Exercise-EditTextPreferenceConstraints/app/src/main/java/android/example/com/visualizerpreferences/SettingsFragment.java
nehabalaji/exercise
40b53c36ad4c32083050c1299fa5eb0f5976e011
[ "Apache-2.0" ]
null
null
null
43.113636
112
0.676682
1,325
package android.example.com.visualizerpreferences; /* * Copyright (C) 2016 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. */ import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.EditTextPreference; import android.support.v7.preference.ListPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.preference.PreferenceScreen; import android.widget.Toast; // TODO (1) Implement OnPreferenceChangeListener public class SettingsFragment extends PreferenceFragmentCompat implements OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener { @Override public void onCreatePreferences(Bundle bundle, String s) { // Add visualizer preferences, defined in the XML file in res->xml->pref_visualizer addPreferencesFromResource(R.xml.pref_visualizer); SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences(); PreferenceScreen prefScreen = getPreferenceScreen(); int count = prefScreen.getPreferenceCount(); // Go through all of the preferences, and set up their preference summary. for (int i = 0; i < count; i++) { Preference p = prefScreen.getPreference(i); // You don't need to set up preference summaries for checkbox preferences because // they are already set up in xml using summaryOff and summary On if (!(p instanceof CheckBoxPreference)) { String value = sharedPreferences.getString(p.getKey(), ""); setPreferenceSummary(p, value); } } // TODO (3) Add the OnPreferenceChangeListener specifically to the EditTextPreference Preference preference = findPreference(getString(R.string.pref_size_key)); preference.setOnPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Figure out which preference was changed Preference preference = findPreference(key); if (null != preference) { // Updates the summary for the preference if (!(preference instanceof CheckBoxPreference)) { String value = sharedPreferences.getString(preference.getKey(), ""); setPreferenceSummary(preference, value); } } } /** * Updates the summary for the preference * * @param preference The preference to be updated * @param value The value that the preference was updated to */ private void setPreferenceSummary(Preference preference, String value) { if (preference instanceof ListPreference) { // For list preferences, figure out the label of the selected value ListPreference listPreference = (ListPreference) preference; int prefIndex = listPreference.findIndexOfValue(value); if (prefIndex >= 0) { // Set the summary to that label listPreference.setSummary(listPreference.getEntries()[prefIndex]); } } else if (preference instanceof EditTextPreference) { // For EditTextPreferences, set the summary to the value's simple string representation. preference.setSummary(value); } } // TODO (2) Override onPreferenceChange. This method should try to convert the new preference value // to a float; if it cannot, show a helpful error message and return false. If it can be converted // to a float check that that float is between 0 (exclusive) and 3 (inclusive). If it isn't, show // an error message and return false. If it is a valid number, return true. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onDestroy() { super.onDestroy(); getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Toast error = Toast.makeText(getContext(), "Enter a valid number between 0.1 to 3", Toast.LENGTH_SHORT); String sizeKey = getString(R.string.pref_size_key); if(preference.getKey().equals(sizeKey)){ String stringSize = (String) newValue; try { Float size = Float.parseFloat(stringSize); if(size<0.1 || size>3){ error.show(); return false; } } catch (NumberFormatException e) { e.printStackTrace(); error.show(); return false; } } return true; } }
3e03363ddf3ab6b9b9f023bcd41c8c4f7ed87653
583
java
Java
Assignments/Introduction to Computer Science II/PS5/src/ps5/PipelineSegment.java
oliviapy960825/oliviapy960825.github.io
7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde
[ "CC-BY-3.0" ]
null
null
null
Assignments/Introduction to Computer Science II/PS5/src/ps5/PipelineSegment.java
oliviapy960825/oliviapy960825.github.io
7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde
[ "CC-BY-3.0" ]
null
null
null
Assignments/Introduction to Computer Science II/PS5/src/ps5/PipelineSegment.java
oliviapy960825/oliviapy960825.github.io
7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde
[ "CC-BY-3.0" ]
null
null
null
18.21875
73
0.627787
1,326
package ps5; /** * Represents the data of the pipeline. * * @author jatlas */ public class PipelineSegment { private int length; private int inDiameter; private int outDiameter; public PipelineSegment(int length, int inDiameter, int outDiameter) { this.length = length; this.inDiameter = inDiameter; this.outDiameter = outDiameter; } public int getLength() { return length; } public int getInDiameter() { return inDiameter; } public int getOutDiameter() { return outDiameter; } }
3e0336dda904b7665ea2180d39aa5b1b55ded70e
2,887
java
Java
src/main/java/gov/loc/repository/bagit/reader/FetchReader.java
alexwlchan/bagit-java
2b7002e62d721f5eb50461e4c4c70a6ef643ec1d
[ "MIT" ]
61
2015-02-05T14:43:04.000Z
2021-12-05T15:54:25.000Z
src/main/java/gov/loc/repository/bagit/reader/FetchReader.java
DANS-KNAW/bagit-java
dcf04dd5576aaa17fd98793970fcfa464b230e0c
[ "MIT" ]
118
2015-02-05T14:42:28.000Z
2022-02-16T13:34:26.000Z
src/main/java/gov/loc/repository/bagit/reader/FetchReader.java
DANS-KNAW/bagit-java
dcf04dd5576aaa17fd98793970fcfa464b230e0c
[ "MIT" ]
50
2015-02-05T15:23:48.000Z
2021-05-10T22:16:18.000Z
37.986842
187
0.709387
1,327
package gov.loc.repository.bagit.reader; import java.io.BufferedReader; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import gov.loc.repository.bagit.domain.FetchItem; import gov.loc.repository.bagit.exceptions.InvalidBagitFileFormatException; import gov.loc.repository.bagit.exceptions.MaliciousPathException; /** * This class is responsible for reading and parsing fetch.txt file from the filesystem */ public final class FetchReader { private static final Logger logger = LoggerFactory.getLogger(FetchReader.class); private static final ResourceBundle messages = ResourceBundle.getBundle("MessageBundle"); private static final String FETCH_LINE_REGEX = ".*[ \t]*(\\d*|-)[ \t]*.*"; private FetchReader(){ //intentionally left empty } /** * Reads a fetch.txt file * * @param fetchFile the specific fetch file * @param encoding the encoding to read the file with * @param bagRootDir the root directory of the bag * @return a list of items to fetch * * @throws IOException if there is a problem reading a file * @throws MaliciousPathException if the path was crafted to point outside the bag directory * @throws InvalidBagitFileFormatException if the fetch format does not follow the bagit specification */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public static List<FetchItem> readFetch(final Path fetchFile, final Charset encoding, final Path bagRootDir) throws IOException, MaliciousPathException, InvalidBagitFileFormatException{ logger.info(messages.getString("reading_fetch_file"), fetchFile); final List<FetchItem> itemsToFetch = new ArrayList<>(); try(final BufferedReader reader = Files.newBufferedReader(fetchFile, encoding)){ String line = reader.readLine(); String[] parts = null; long length = 0; URL url = null; while(line != null){ if(line.matches(FETCH_LINE_REGEX) && !line.matches("\\s*")){ parts = line.split("\\s+", 3); final Path path = TagFileReader.createFileFromManifest(bagRootDir, parts[2]); length = parts[1].equals("-") ? -1 : Long.decode(parts[1]); url = new URL(parts[0]); logger.debug(messages.getString("read_fetch_file_line"), url, length, parts[2], fetchFile); final FetchItem itemToFetch = new FetchItem(url, length, path); itemsToFetch.add(itemToFetch); } else{ throw new InvalidBagitFileFormatException(messages.getString("invalid_fetch_file_line_error").replace("{}", line)); } line = reader.readLine(); } } return itemsToFetch; } }
3e03371de0b706afe7c56d9a3c1b83baa5bbfba3
201
java
Java
src/Model/GameOfLife.java
DeepTranslation/GameOfLife
76c7fd2d413a8bdfd605c3116c288f9d690930d2
[ "MIT" ]
null
null
null
src/Model/GameOfLife.java
DeepTranslation/GameOfLife
76c7fd2d413a8bdfd605c3116c288f9d690930d2
[ "MIT" ]
null
null
null
src/Model/GameOfLife.java
DeepTranslation/GameOfLife
76c7fd2d413a8bdfd605c3116c288f9d690930d2
[ "MIT" ]
null
null
null
15.461538
53
0.606965
1,328
package Model; import View.*; public class GameOfLife { public static void main(String[] args) { Controller controller = new Controller(); controller.launch(); } }
3e03392d70384b9ca005b9878bf96cc93e0c1b16
1,064
java
Java
sscontrol-core-utils-system-mappings/src/main/java/com/anrisoftware/sscontrol/utils/systemmappings/external/SystemNameMappings.java
devent/sscontrol-core
467fcac9099172c532ea849649201afe5ead12b6
[ "Apache-2.0" ]
null
null
null
sscontrol-core-utils-system-mappings/src/main/java/com/anrisoftware/sscontrol/utils/systemmappings/external/SystemNameMappings.java
devent/sscontrol-core
467fcac9099172c532ea849649201afe5ead12b6
[ "Apache-2.0" ]
null
null
null
sscontrol-core-utils-system-mappings/src/main/java/com/anrisoftware/sscontrol/utils/systemmappings/external/SystemNameMappings.java
devent/sscontrol-core
467fcac9099172c532ea849649201afe5ead12b6
[ "Apache-2.0" ]
null
null
null
30.111111
75
0.698339
1,329
/** * Copyright © 2020 Erwin Müller ([email protected]) * * 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.anrisoftware.sscontrol.utils.systemmappings.external; /** * Maps system names. * * @author Erwin Müller {@literal <[email protected]>} * @version 1.0 */ public interface SystemNameMappings { /** * Returns the system to the name. * * @param system * the name like debian, centos, windows. * @return the system like linux, macos, windows. */ String getMapping(String system); }
3e033abc547d0d40a6e61d62f91240c333f1014d
4,229
java
Java
common/src/main/java/xyz/jpenilla/squaremap/common/command/commands/ProgressLoggingCommand.java
jpenilla/squaremap
5bbb92f88fa7949584a090ca553ef93d649b32f3
[ "MIT" ]
139
2021-12-04T05:53:31.000Z
2022-03-31T13:59:03.000Z
common/src/main/java/xyz/jpenilla/squaremap/common/command/commands/ProgressLoggingCommand.java
jpenilla/Pl3xMap
f69e85febc7920a438fbf293f1c7e172489d7836
[ "MIT" ]
31
2021-12-08T14:11:26.000Z
2022-03-28T16:31:28.000Z
common/src/main/java/xyz/jpenilla/squaremap/common/command/commands/ProgressLoggingCommand.java
jpenilla/Pl3xMap
f69e85febc7920a438fbf293f1c7e172489d7836
[ "MIT" ]
19
2021-12-07T05:41:44.000Z
2022-03-18T10:27:58.000Z
44.052083
144
0.746276
1,330
package xyz.jpenilla.squaremap.common.command.commands; import cloud.commandframework.Command; import cloud.commandframework.arguments.standard.IntegerArgument; import cloud.commandframework.context.CommandContext; import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys; import com.google.inject.Inject; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; import xyz.jpenilla.squaremap.common.WorldManager; import xyz.jpenilla.squaremap.common.command.Commander; import xyz.jpenilla.squaremap.common.command.Commands; import xyz.jpenilla.squaremap.common.command.SquaremapCommand; import xyz.jpenilla.squaremap.common.config.Config; import xyz.jpenilla.squaremap.common.config.Messages; import xyz.jpenilla.squaremap.common.data.MapWorldInternal; import xyz.jpenilla.squaremap.common.util.Components; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.event.ClickEvent.runCommand; import static net.kyori.adventure.text.format.NamedTextColor.GREEN; import static net.kyori.adventure.text.format.NamedTextColor.RED; @DefaultQualifier(NonNull.class) public final class ProgressLoggingCommand extends SquaremapCommand { private final WorldManager worldManager; @Inject private ProgressLoggingCommand( final Commands commands, final WorldManager worldManager ) { super(commands); this.worldManager = worldManager; } @Override public void register() { final Command.Builder<Commander> progressLogging = this.commands.rootBuilder() .literal("progresslogging") .permission("squaremap.command.progresslogging"); this.commands.register(progressLogging .meta(MinecraftExtrasMetaKeys.DESCRIPTION, Messages.PROGRESSLOGGING_COMMAND_DESCRIPTION.asComponent()) .handler(this::executePrint)); this.commands.register(progressLogging.literal("toggle") .meta(MinecraftExtrasMetaKeys.DESCRIPTION, Messages.PROGRESSLOGGING_TOGGLE_COMMAND_DESCRIPTION.asComponent()) .handler(this::executeToggle)); this.commands.register(progressLogging.literal("rate") .argument(IntegerArgument.<Commander>newBuilder("seconds").withMin(1)) .meta(MinecraftExtrasMetaKeys.DESCRIPTION, Messages.PROGRESSLOGGING_RATE_COMMAND_DESCRIPTION.asComponent()) .handler(this::executeRate)); } private void executePrint(final CommandContext<Commander> context) { context.getSender().sendMessage( Messages.PROGRESSLOGGING_STATUS_MESSAGE.withPlaceholders( Components.placeholder("seconds", Config.PROGRESS_LOGGING_INTERVAL), Components.placeholder("enabled", clickAndHover(Config.PROGRESS_LOGGING ? text("✔", GREEN) : text("✖", RED))) ) ); } private void executeToggle(final CommandContext<Commander> context) { Config.toggleProgressLogging(); this.worldManager.worlds() .forEach(MapWorldInternal::restartRenderProgressLogging); final ComponentLike message; if (Config.PROGRESS_LOGGING) { message = Messages.PROGRESSLOGGING_ENABLED_MESSAGE; } else { message = Messages.PROGRESSLOGGING_DISABLED_MESSAGE; } context.getSender().sendMessage(clickAndHover(message)); } private static Component clickAndHover(final ComponentLike componentLike) { return componentLike.asComponent().hoverEvent(Messages.CLICK_TO_TOGGLE.asComponent()) .clickEvent(runCommand("/" + Config.MAIN_COMMAND_LABEL + " progresslogging toggle")); } private void executeRate(final CommandContext<Commander> context) { final int seconds = context.get("seconds"); Config.setLoggingInterval(seconds); this.worldManager.worlds() .forEach(MapWorldInternal::restartRenderProgressLogging); context.getSender().sendMessage(Messages.PROGRESSLOGGING_SET_RATE_MESSAGE.withPlaceholders(Components.placeholder("seconds", seconds))); } }
3e033cbbf7d085e03b0f46d5d075604e58154afb
6,614
java
Java
src/test/java/net/jforum/csrf/CsrfTest.java
anbuashokcs/jforum2
2e9193eb05f5c25cabdaf2cf424430d1d177e39f
[ "BSD-3-Clause" ]
null
null
null
src/test/java/net/jforum/csrf/CsrfTest.java
anbuashokcs/jforum2
2e9193eb05f5c25cabdaf2cf424430d1d177e39f
[ "BSD-3-Clause" ]
null
null
null
src/test/java/net/jforum/csrf/CsrfTest.java
anbuashokcs/jforum2
2e9193eb05f5c25cabdaf2cf424430d1d177e39f
[ "BSD-3-Clause" ]
null
null
null
36.142077
124
0.699123
1,331
package net.jforum.csrf; import static org.junit.Assert.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import org.junit.*; /** * Checks consistency of csrf.properties. In particular: keys have valid values, * no duplicate keys and no missing keys (per action method names). * * @author Jeanne Boyarsky, Andowson Chang * @version $Id: $ */ public class CsrfTest { private static final String rootDir = CsrfTest.class.getResource("/").getPath(); private static final String JFORUM_DIRECTORY = rootDir.substring(0, rootDir.length() - "/target/test-classes/".length()); private static final String CSRF_PROPERTIES = JFORUM_DIRECTORY + "/src/main/config/csrf.properties"; private Collection<String> packagesWithActions; /** * Could have just hard coded the action directories. Wrote a method because * wanted to turn this into a unit test later and then automation is useful. * * @throws Exception */ @Before public void findAllPackagesWithActions() throws Exception { packagesWithActions = new HashSet<String>(); String configDirectory = JFORUM_DIRECTORY + "/src/main/config"; Properties props = new Properties(); props.load(new FileInputStream(new File(configDirectory, "modulesMapping.properties"))); for (Object value : props.values()) { String fullyQualifiedClassName = (String) value; // remove everything after the last dot (class name) String packageName = fullyQualifiedClassName.replaceFirst( "\\.\\w+$", ""); packagesWithActions.add(packageName); } } @Test public void listUniqueMethodNamesInAllActions() throws Exception { Set<String> methodNames = getAllUniqueActionMethodNames(); Set<String> csrfAcknowledgedMethodNames = getActionMethodNamesFromCsrfFile(); methodNames.removeAll(csrfAcknowledgedMethodNames); assertEquals( "The method you've just added requires you to go into the csrf.properties file and read/follow " + "the instructions in the comment header. Method: " + methodNames, 0, methodNames.size()); } @Test public void listMethodNamesinCsrfPropertiesNotMappingToActions() throws Exception { Set<String> methodNames = getAllUniqueActionMethodNames(); Set<String> csrfAcknowledgedMethodNames = getActionMethodNamesFromCsrfFile(); csrfAcknowledgedMethodNames.removeAll(methodNames); assertEquals( "csrf.properties refers to the following method(s) that don't exist. Time to clean up CSRF file?" + " Method(s): " + csrfAcknowledgedMethodNames, 0, csrfAcknowledgedMethodNames.size()); } @Test public void csrfPropertyValuesValid() throws Exception { Properties props = getCsrfProperties(); for (Object obj : props.keySet()) { String key = obj.toString().trim(); String value = props.getProperty(key); assertTrue(value + " is not recognized in csrf.properties for key: " + key + ". Please check for typos.", value.equals("AddToken") || value.equals("NoCsrfWorriesHere")); } } @Test public void checkNoDuplicatesinCsrfFile() throws Exception { Properties props = getCsrfProperties(); List<String> fullListOfKeys = getListOfKeysIncludingDuplicates(); for (Object key : props.keySet()) { fullListOfKeys.remove(key); } for (String name: fullListOfKeys) { System.out.println(name); } assertTrue( "You've accidentally added a duplicate key in csrf.properties. Please delete the extra lines of: " + fullListOfKeys, fullListOfKeys.isEmpty()); } private List<String> getListOfKeysIncludingDuplicates() { List<String> fullListOfKeys = new ArrayList<String>(); Scanner scanner = null; try { //scanner = new Scanner(CsrfTest.class.getResourceAsStream(CSRF_PROPERTIES)); scanner = new Scanner(new FileInputStream(CSRF_PROPERTIES)); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (!line.trim().equals("") && !line.startsWith("#")) { fullListOfKeys.add(line.split("=")[0]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } return fullListOfKeys; } /** * Uses reflection rather than the names in modulesMapping because some of * the AJAX ones aren't in there. Most notably the admin delete forum * action. The most destructive operation a CSRF could target wouldn't have * been caught with the alternate approach. Plus, these methods could be * invoked even without being in the modulesMapping via URL crafting. * * @throws Exception */ private Set<String> getAllUniqueActionMethodNames() throws Exception { Set<String> methodNames = new HashSet<String>(); String sourceDirectory = JFORUM_DIRECTORY + "/src/main/java/"; for (String packageName : packagesWithActions) { String packageDirectory = sourceDirectory + packageName.replaceAll("\\.", "/"); File[] directoryContents = new File(packageDirectory) .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".java"); } }); for (File file : directoryContents) { methodNames.addAll(getPublicMethodNamesIn(packageName, file.getName())); } } return methodNames; } private Collection<String> getPublicMethodNamesIn(String packageName, String className) throws Exception { Set<String> result = new HashSet<String>(); String fullyQualifiedClassName = packageName + "." + className.replaceFirst(".java", ""); Class<?> clazz = Class.forName(fullyQualifiedClassName); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { // if isn't public, has return value or has parameters, it is a // helper method if (Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 0) { result.add(method.getName()); } } return result; } private Set<String> getActionMethodNamesFromCsrfFile() throws Exception { Set<String> result = new HashSet<String>(); Properties props = getCsrfProperties(); for (Object key : props.keySet()) { result.add(key.toString()); } return result; } private Properties getCsrfProperties() throws IOException, FileNotFoundException { Properties props = new Properties(); //props.load(CsrfTest.class.getResourceAsStream(CSRF_PROPERTIES)); props.load(new FileInputStream(CSRF_PROPERTIES)); return props; } }
3e033cc1e0146ae05418d4923851df688e681f47
935
java
Java
iot-server-ability/src/main/java/com/tuya/iot/server/ability/idaas/model/PermissionCreateReq.java
tuya/iot-server
b15c23114a4838efea06bbc7d47aefba4bd1c06c
[ "Apache-2.0" ]
10
2021-07-28T03:50:50.000Z
2022-03-21T07:50:17.000Z
iot-server-ability/src/main/java/com/tuya/iot/server/ability/idaas/model/PermissionCreateReq.java
tuya/iot-server
b15c23114a4838efea06bbc7d47aefba4bd1c06c
[ "Apache-2.0" ]
4
2021-07-29T06:20:54.000Z
2021-08-10T11:25:12.000Z
iot-server-ability/src/main/java/com/tuya/iot/server/ability/idaas/model/PermissionCreateReq.java
tuya/iot-server
b15c23114a4838efea06bbc7d47aefba4bd1c06c
[ "Apache-2.0" ]
10
2021-08-24T08:47:54.000Z
2022-03-02T02:35:53.000Z
15.915254
50
0.646432
1,332
package com.tuya.iot.server.ability.idaas.model; import com.google.gson.annotations.SerializedName; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.FieldDefaults; /** * @author [email protected] * @description * @date 2021/05/24 */ @Data @FieldDefaults(level = AccessLevel.PRIVATE) @Builder @NoArgsConstructor @AllArgsConstructor public class PermissionCreateReq { /** * 权限标识 */ @SerializedName("permissionCode") String permissionCode; /** * 显示名称 */ String name; /** * 权限类型(api/menu/button/data) */ Integer type; /** * 父级权限code */ @SerializedName("parentCode") String parentCode; /** * 展示顺序 */ Integer order; /** * 备注 */ String remark; @SerializedName("spaceId") String spaceId; }
3e033cd014090f8b8e259e0792358777b21efc50
2,804
java
Java
src/liqui/droid/service/task/SyncMemberImage.java
LiquidFeedbackUA/liquidfeedback-android
dd3408bc9dd7b2192ce2a34432822f0b7f366371
[ "Apache-2.0" ]
2
2015-01-01T11:22:36.000Z
2015-06-01T21:17:23.000Z
src/liqui/droid/service/task/SyncMemberImage.java
Zidjinn/liquidfeedback-android
dd3408bc9dd7b2192ce2a34432822f0b7f366371
[ "Apache-2.0" ]
null
null
null
src/liqui/droid/service/task/SyncMemberImage.java
Zidjinn/liquidfeedback-android
dd3408bc9dd7b2192ce2a34432822f0b7f366371
[ "Apache-2.0" ]
null
null
null
35.05
101
0.648359
1,333
/* * Copyright 2012 Jakob Flierl * * 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 liqui.droid.service.task; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import java.util.List; import lfapi.v2.schema.Member; import lfapi.v2.services.LiquidFeedbackServiceFactory; import lfapi.v2.services.LiquidFeedbackService.MemberService; import lfapi.v2.services.auth.SessionKeyAuthentication; import liqui.droid.Constants; import liqui.droid.db.DB; import liqui.droid.db.DBProvider; public class SyncMemberImage extends SyncAbstractTask { public SyncMemberImage(Context ctx, Intent intent, LiquidFeedbackServiceFactory factory, String databaseName) { super(ctx, intent, factory, databaseName, DB.Member.Image.TABLE, SYNC_TIME_HOUR_12); } public int sync(Context ctx, String ids) { MemberService service = mFactory.createMemberService(); if (isAuthenticated()) { service.setAuthentication(new SessionKeyAuthentication(getSessionKey())); } int nr = 0; int page = 0; boolean hasMore = true; while (hasMore) { Member.Image.Options mo = new Member.Image.Options(); mo.memberId = ids; mo.limit = Constants.LIMIT; mo.offset = ((page++) * mo.limit); List<Member.Image> l = service.getMemberImage("avatar", mo); if (l.size() < mo.limit) { hasMore = false; } ContentValues[] v = new ContentValues[l.size()]; int idx = 0; for (Member.Image m : l) { ContentValues values = new ContentValues(); values.put(DB.Member.Image.COLUMN_MEMBER_ID, m.memberId); values.put(DB.Member.Image.COLUMN_IMAGE_TYPE, m.imageType); values.put(DB.Member.Image.COLUMN_SCALED, m.scaled); values.put(DB.Member.Image.COLUMN_CONTENT_TYPE, m.contentType); values.put(DB.Member.Image.COLUMN_DATA, m.data); v[idx++] = values; } nr += ctx.getContentResolver().bulkInsert(dbUri(DBProvider.MEMBER_IMAGE_CONTENT_URI), v); } return nr; } }
3e033d6ca87cb2b47d6c0ca7bcc98aeb103d9570
576
java
Java
JavaWebModule/JavaDBFundamentals/JavaOOPPrinciples_Exercise/Telephony/src/Main.java
boggroZZdev/SoftUniHomeWork
9a19f70c432e457f22bc021d1b3ee374232acbab
[ "MIT" ]
null
null
null
JavaWebModule/JavaDBFundamentals/JavaOOPPrinciples_Exercise/Telephony/src/Main.java
boggroZZdev/SoftUniHomeWork
9a19f70c432e457f22bc021d1b3ee374232acbab
[ "MIT" ]
null
null
null
JavaWebModule/JavaDBFundamentals/JavaOOPPrinciples_Exercise/Telephony/src/Main.java
boggroZZdev/SoftUniHomeWork
9a19f70c432e457f22bc021d1b3ee374232acbab
[ "MIT" ]
null
null
null
26.181818
86
0.649306
1,334
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] numbers = reader.readLine().split(" "); String[] urls = reader.readLine().split(" "); Smartphone ph = new Smartphone(); Arrays.stream(numbers).forEach(ph::call); Arrays.stream(urls).forEach(ph::browse); } }
3e033dd0adedfc6a53a6d100e2cc201a5fc8a085
2,525
java
Java
src/test/java/com/lahzouz/graphqlfilter/CommonFilterTest.java
fossabot/graphql-java-filter
f81c833b4b52eefcba0fa2af6bda92381ee46945
[ "Apache-2.0" ]
null
null
null
src/test/java/com/lahzouz/graphqlfilter/CommonFilterTest.java
fossabot/graphql-java-filter
f81c833b4b52eefcba0fa2af6bda92381ee46945
[ "Apache-2.0" ]
1
2020-04-13T11:10:11.000Z
2020-04-13T11:10:11.000Z
src/test/java/com/lahzouz/graphqlfilter/CommonFilterTest.java
fossabot/graphql-java-filter
f81c833b4b52eefcba0fa2af6bda92381ee46945
[ "Apache-2.0" ]
2
2020-04-13T11:00:18.000Z
2020-04-13T11:04:08.000Z
35.069444
106
0.64198
1,335
package com.lahzouz.graphqlfilter; import com.lahzouz.graphqlfilter.util.QueryFile; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; public class CommonFilterTest extends AbstractFilterTest { @Test public void testSingleAnd() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "and", "single")); Assertions.assertThat(nodes.size()).isEqualTo(1); Assertions.assertThat(nodes.get(0).get("uuid")).isEqualTo("1f9c42ed-506d-481d-b31e-1a9466e31a81"); } @Test public void testEmptyAnd() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "and", "empty")); Assertions.assertThat(nodes.size()).isEqualTo(testData.size()); } @Test public void testBogusAnd() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "and", "bogus")); Assertions.assertThat(nodes.size()).isEqualTo(0); } @Test public void testSimpleAnd() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "and", "simple")); Assertions.assertThat(nodes.size()).isEqualTo(2); nodes.stream() .map(node -> ((String) node.get("name")).startsWith("Tree")) .forEach(aBoolean -> Assertions.assertThat(aBoolean).isTrue()); } @Test public void testSingleOr() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "or", "single")); Assertions.assertThat(nodes.size()).isEqualTo(1); Assertions.assertThat(nodes.get(0).get("uuid")).isEqualTo("1f9c42ed-506d-481d-b31e-1a9466e31a81"); } @Test public void testEmptyOr() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "or", "empty")); Assertions.assertThat(nodes.size()).isEqualTo(testData.size()); } @Test public void testMultipleOr() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "or", "multiple")); Assertions.assertThat(nodes.size()).isEqualTo(1); } @Test public void testSimpleOr() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "or", "simple")); Assertions.assertThat(nodes.size()).isEqualTo(2); } @Test public void testIsNull() { List<Map<String, ?>> nodes = queryNodesAsList(new QueryFile("common", "isNull")); Assertions.assertThat(nodes.size()).isEqualTo(1); } }
3e033de8d9dda33e698732822c130a16f75939e3
676
java
Java
footballmanager/src/main/java/com/jeff/footballmanager/utils/MyDrawable.java
topsecretabc/GraduationProject
4f10a2756cc9c58fe990fe6e30e2e503a5cdb2f1
[ "Apache-2.0" ]
2
2017-08-16T00:56:01.000Z
2019-04-16T16:29:20.000Z
footballmanager/src/main/java/com/jeff/footballmanager/utils/MyDrawable.java
topsecretabc/GraduationProject
4f10a2756cc9c58fe990fe6e30e2e503a5cdb2f1
[ "Apache-2.0" ]
null
null
null
footballmanager/src/main/java/com/jeff/footballmanager/utils/MyDrawable.java
topsecretabc/GraduationProject
4f10a2756cc9c58fe990fe6e30e2e503a5cdb2f1
[ "Apache-2.0" ]
null
null
null
26
114
0.757396
1,336
package com.jeff.footballmanager.utils; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class MyDrawable extends BitmapDrawable { Drawable drawable; @Override public void draw(Canvas canvas) { super.draw(canvas); if(null!=drawable){ drawable.draw(canvas); } } public void setDrawable(Drawable drawable,double scale) { this.drawable = drawable; drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*scale), (int)(drawable.getIntrinsicHeight()*scale)); setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*scale), (int)(drawable.getIntrinsicHeight()*scale)); } }
3e033ef97f9283c4dee9842956a4e1651475bafe
83
java
Java
xmppbot-core/src/main/java/de/raion/xmppbot/io/package-info.java
brndkfr/xmppbot
e21ca352fd5fc270e6a8563c340dc2c549d17734
[ "Apache-2.0" ]
null
null
null
xmppbot-core/src/main/java/de/raion/xmppbot/io/package-info.java
brndkfr/xmppbot
e21ca352fd5fc270e6a8563c340dc2c549d17734
[ "Apache-2.0" ]
null
null
null
xmppbot-core/src/main/java/de/raion/xmppbot/io/package-info.java
brndkfr/xmppbot
e21ca352fd5fc270e6a8563c340dc2c549d17734
[ "Apache-2.0" ]
null
null
null
20.75
46
0.662651
1,337
/** * io related classes like reader, writer, ... */ package de.raion.xmppbot.io;
3e033f8a0ce343088decafb1fd57634929610405
1,979
java
Java
src/test/java/org/swingk/io/dirtree/DirTreeModelTest.java
synapticloopltd/directory-tree
69d048999504fb47d1c9d32ed8da0e927c8f7bc2
[ "Apache-2.0" ]
null
null
null
src/test/java/org/swingk/io/dirtree/DirTreeModelTest.java
synapticloopltd/directory-tree
69d048999504fb47d1c9d32ed8da0e927c8f7bc2
[ "Apache-2.0" ]
null
null
null
src/test/java/org/swingk/io/dirtree/DirTreeModelTest.java
synapticloopltd/directory-tree
69d048999504fb47d1c9d32ed8da0e927c8f7bc2
[ "Apache-2.0" ]
null
null
null
40.387755
101
0.754927
1,338
package org.swingk.io.dirtree; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import javax.swing.tree.TreePath; import java.nio.file.Path; import java.util.ArrayList; import java.util.Optional; public class DirTreeModelTest { @Test public void basicTest() { var model = new DirTreeModel<>(DirTreeUtils.NAME_COMPARATOR, true, true, new DefaultNodeFactory()); Assertions.assertNotNull(model.getRoot()); Assertions.assertFalse(model.isLeaf(model.getRoot())); Assertions.assertNull(model.getRoot().getDirectory()); Assertions.assertNull(model.getRoot().getFileSystem()); Assertions.assertEquals(1, model.getChildCount(model.getRoot())); Assertions.assertNotNull(model.getFileSystemNode()); Assertions.assertNull(model.getFileSystemNode().getDirectory()); Assertions.assertNotNull(model.getFileSystemNode().getFileSystem()); Assertions.assertFalse(model.isLeaf(model.getFileSystemNode())); var fsRoots = new ArrayList<DefaultDirNode>(); for (int i = 0; i < model.getChildCount(model.getFileSystemNode()); i++) { fsRoots.add(model.getChild(model.getFileSystemNode(), i)); } Assertions.assertFalse(fsRoots.isEmpty()); for (int i = 0; i < fsRoots.size(); i++) { Assertions.assertEquals(0, fsRoots.get(i).getDirectory().getNameCount()); Assertions.assertEquals(i, model.getIndexOfChild(model.getFileSystemNode(), fsRoots.get(i))); } Path fsRoot0 = fsRoots.get(0).getDirectory(); Assertions.assertNotNull(fsRoot0); Optional<TreePath> p = model.getTreePath(fsRoot0); Assertions.assertTrue(p.isPresent()); Assertions.assertEquals(new TreePath(new Object[]{model.getRoot(), model.getFileSystemNode(), fsRoots.get(0)}), p.get()); Assertions.assertEquals(new TreePath(new Object[]{model.getRoot(), model.getFileSystemNode()}), model.getFileSystemNodeTreePath()); Assertions.assertThrows(IllegalArgumentException.class, () -> model.getTreePath(Path.of("non_absolute_path_dir_tree"))); } }
3e033fa059ee59161d933065c850b1795ba11a40
288
java
Java
0029 - Overriding Methods/B.java
FahimFBA/OOP-FBA-Notes-of-Dewan_Farid_Sir
c463a33668eca2ac6dbe7df0f32a94331c365d80
[ "MIT" ]
1
2022-03-02T14:37:03.000Z
2022-03-02T14:37:03.000Z
0029 - Overriding Methods/B.java
FahimFBA/OOP-FBA-Notes-of-Dewan_Farid_Sir
c463a33668eca2ac6dbe7df0f32a94331c365d80
[ "MIT" ]
null
null
null
0029 - Overriding Methods/B.java
FahimFBA/OOP-FBA-Notes-of-Dewan_Farid_Sir
c463a33668eca2ac6dbe7df0f32a94331c365d80
[ "MIT" ]
1
2022-03-02T15:03:50.000Z
2022-03-02T15:03:50.000Z
18
50
0.527778
1,339
class A { public void show(){ System.out.println("Bird can fly"); } } public class B extends A { public void show(){ System.out.println("Bird fly in the sky"); } public static void main(String[] args){ B b = new B(); b.show(); } }
3e03401d4810ba3f37271c9446f592502a07d7c7
4,280
java
Java
core.collaboration/src/main/java/collabware/collaboration/internal/context/VectorBasedContext.java
HotblackDesiato/collabware
3fc4d6d9214d63cb6a9273720124e1fa0379601f
[ "MIT" ]
2
2015-03-30T18:59:18.000Z
2021-04-13T03:43:38.000Z
core.collaboration/src/main/java/collabware/collaboration/internal/context/VectorBasedContext.java
HotblackDesiato/collabware
3fc4d6d9214d63cb6a9273720124e1fa0379601f
[ "MIT" ]
null
null
null
core.collaboration/src/main/java/collabware/collaboration/internal/context/VectorBasedContext.java
HotblackDesiato/collabware
3fc4d6d9214d63cb6a9273720124e1fa0379601f
[ "MIT" ]
null
null
null
35.666667
125
0.79743
1,340
package collabware.collaboration.internal.context; import static collabware.collaboration.internal.context.ContextHelper.clientNumberOf; import static collabware.collaboration.internal.context.ContextHelper.contextOf; import static collabware.collaboration.internal.context.ContextHelper.ownSequenceNumberOf; import collabware.api.operations.context.Context; import collabware.api.operations.context.ContextDifference; import collabware.api.operations.context.ContextualizedOperation; import collabware.api.operations.context.NonConsecutiveContextException; import collabware.api.operations.context.OperationsSet; /** * A vector-based implementation of an Context. * The underlying vector has one sequence number per client and gets * incremented with every operation performed by the corresponding client. * Just by looking a vector, we can very quickly decide whether an operation is * include in a context and whether a context is a sub-context of another. This is * very important for the performance of the transformation algorithm. * */ public class VectorBasedContext implements Context { private final ContextVector sequenceNumbers; private final int clientNumber; public VectorBasedContext(int client, int[] sequenceNumbers) { this(client, new ContextVector(sequenceNumbers)); } public VectorBasedContext(int client) { this(client, new int[0]); } public VectorBasedContext(int client, ContextVector contextVector) { this.clientNumber = client; this.sequenceNumbers = contextVector; } /** * @param operation the operation to include * @return new Context, which includes operation o. * @throws NonConsecutiveContextException */ public Context including(ContextualizedOperation operation) { assertCanInclude(contextOf(operation)); ContextVector includingContextVector = sequenceNumbers.updating(clientNumberOf(operation), ownSequenceNumberOf(operation)); return new VectorBasedContext(getClientNumber(), includingContextVector ); } public Context including(Context context) { assertCanInclude((VectorBasedContext)context); ContextVector includingContextVector = sequenceNumbers.updating(context.getClientNumber(), nextSequenceNumberOf(context)); return new VectorBasedContext(getClientNumber(), includingContextVector ); } private int nextSequenceNumberOf(Context context) { return ((VectorBasedContext) context).getSequenceNumbers().get(context.getClientNumber())+1; } private void assertCanInclude(VectorBasedContext otherContext) { int otherClientNumber = otherContext.getClientNumber(); if (!otherContext.isSubsetOf(this) && !equalSequenceNumbersAt(otherClientNumber, otherContext)) throw new NonConsecutiveContextException(); } private boolean equalSequenceNumbersAt(int index, VectorBasedContext otherContext) { return this.sequenceNumbers.get(index) == otherContext.sequenceNumbers.get(index); } public boolean contains(ContextualizedOperation o) { try { return o.getSelfIncludingContext().isSubsetOf(this); } catch (NonConsecutiveContextException cannotHappen) { return false; } } public boolean isSubsetOf(OperationsSet superContext) { VectorBasedContext superContextImpl = (VectorBasedContext) superContext; return this.sequenceNumbers.lessThanOrEqual(superContextImpl.sequenceNumbers); } public int getClientNumber() { return clientNumber; } public ContextDifference minus(OperationsSet subtrahend) { return new ContextDifferenceImpl(this, (VectorBasedContext) subtrahend); } public ContextVector getSequenceNumbers() { return sequenceNumbers; } public int hashCode() { return 17*sequenceNumbers.hashCode(); } @Override public boolean equals(Object o) { if (o == this) return true; if (o instanceof Context) return equalsContext((VectorBasedContext) o); return false; } private boolean equalsContext(Context context) { ContextVector otherSequenceNumbers = ((VectorBasedContext)context ).getSequenceNumbers(); return sequenceNumbers.equals(otherSequenceNumbers); } @Override public String toString() { return "sequenceNumbers: "+sequenceNumbers+", clientNumber: " + clientNumber; } public Context next() { return new VectorBasedContext(clientNumber, sequenceNumbers.incrementing(clientNumber)); } }
3e03402676851720189b2681a6faed2ac7c18d39
842
java
Java
app/src/main/java/com/golda/recallme/ui/viewmodel/EditAlarmActivityViewModel.java
GoldaEV/RecallMe
acae04a98dfecc3c76fd06319120a69dc75708fb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/golda/recallme/ui/viewmodel/EditAlarmActivityViewModel.java
GoldaEV/RecallMe
acae04a98dfecc3c76fd06319120a69dc75708fb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/golda/recallme/ui/viewmodel/EditAlarmActivityViewModel.java
GoldaEV/RecallMe
acae04a98dfecc3c76fd06319120a69dc75708fb
[ "Apache-2.0" ]
null
null
null
25.515152
73
0.723278
1,341
package com.golda.recallme.ui.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.support.annotation.NonNull; import com.golda.recallme.alarm.db.AlarmDBUtils; import com.golda.recallme.models.alarm.AlarmModel; public class EditAlarmActivityViewModel extends AndroidViewModel { private static LiveData<AlarmModel> alarmModel; public EditAlarmActivityViewModel(@NonNull Application application) { super(application); } public LiveData<AlarmModel> getAlarmModel(int id) { if (alarmModel == null) { alarmModel = AlarmDBUtils.getLiveAlarmModel(id); } return alarmModel; } @Override protected void onCleared() { super.onCleared(); alarmModel = null; } }
3e03402d8128875639869ad3ba6513e32b7bda83
1,326
java
Java
src/main/java/ru/iris/xiaomi4j/watchers/Notification.java
MrNeuronix/Xiaomi4J
f937882dbe8d0922942f011893575833499cd4d6
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/iris/xiaomi4j/watchers/Notification.java
MrNeuronix/Xiaomi4J
f937882dbe8d0922942f011893575833499cd4d6
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/iris/xiaomi4j/watchers/Notification.java
MrNeuronix/Xiaomi4J
f937882dbe8d0922942f011893575833499cd4d6
[ "Apache-2.0" ]
null
null
null
22.1
75
0.729261
1,342
/* * Copyright 2017 Nikolay A. Viguro * * 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 ru.iris.xiaomi4j.watchers; import com.google.gson.JsonObject; import ru.iris.xiaomi4j.enums.Devices; public class Notification { private String command; private JsonObject rawMessage; private Devices type; private String sid; public JsonObject getRawMessage() { return rawMessage; } public void setRawMessage(JsonObject rawMessage) { this.rawMessage = rawMessage; } public Devices getType() { return type; } public void setType(Devices type) { this.type = type; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } }
3e03413598b1cf64f8b6daf970947aaba319ce94
7,163
java
Java
Ref-Finder/code/lsd/serp/util/LRUMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/lsd/serp/util/LRUMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/lsd/serp/util/LRUMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
16.69697
74
0.624878
1,343
/* * Ref-Finder * Copyright (C) <2015> <PLSE_UCLA> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serp.util; import java.util.*; /** * <p>Map that keeps items in order from most to least recently used. * Performance is similar to that of a {@link TreeMap}.</p> * * <p>Operations on the map's entry and key sets do not affect * ordering.</p> * * <p>This implementation is not synchronized.</p> * * @author Abe White */ public class LRUMap implements SortedMap { private Map _orders = new HashMap (); private TreeMap _values = new TreeMap (); private int _order = Integer.MAX_VALUE; public Comparator comparator () { return null; } public Object firstKey () { return ((OrderKey) _values.firstKey ()).key; } public Object lastKey () { return ((OrderKey) _values.lastKey ()).key; } /** * Not supported. */ public SortedMap headMap (Object toKey) { throw new UnsupportedOperationException (); } /** * Not supported. */ public SortedMap subMap (Object fromKey, Object toKey) { throw new UnsupportedOperationException (); } /** * Not supported. */ public SortedMap tailMap (Object fromKey) { throw new UnsupportedOperationException (); } public void clear () { _orders.clear (); _values.clear (); } public boolean containsKey (Object key) { return _orders.containsKey (key); } public boolean containsValue (Object value) { return _values.containsValue (value); } public Set entrySet () { return new EntrySet (); } public boolean equals (Object other) { if (other == this) return true; if (!(other instanceof Map)) return false; // easy way to compare on mappings return new HashMap (this).equals (other); } public Object get (Object key) { Object order = _orders.remove (key); if (order == null) return null; // get old value and re-cache as lowest order Object value = _values.remove (order); order = nextOrderKey (key); _orders.put (key, order); _values.put (order, value); return value; } public boolean isEmpty () { return _orders.isEmpty (); } public Set keySet () { return new KeySet (); } public Object put (Object key, Object value) { Object order = nextOrderKey (key); Object oldOrder = _orders.put (key, order); Object rem = null; if (oldOrder != null) rem = _values.remove (oldOrder); _values.put (order, value); return rem; } public void putAll (Map map) { Map.Entry entry; for (Iterator itr = map.entrySet ().iterator (); itr.hasNext ();) { entry = (Map.Entry) itr.next (); put (entry.getKey (), entry.getValue ()); } } public Object remove (Object key) { Object order = _orders.remove (key); if (order != null) return _values.remove (order); return null; } public int size () { return _orders.size (); } public Collection values () { return new ValueCollection (); } public String toString () { return entrySet ().toString (); } /** * Return the next key to use in the values map. */ private synchronized OrderKey nextOrderKey (Object key) { OrderKey ok = new OrderKey (); ok.key = key; ok.order = _order--; return ok; } /** * Keys used in the map from orders to values. */ private static final class OrderKey implements Comparable { public Object key = null; public int order = 0; public int compareTo (Object other) { return order - ((OrderKey) other).order; } } /** * View of a single map entry. */ private static final class MapEntry implements Map.Entry { private Map.Entry _valuesEntry = null; public MapEntry (Map.Entry valuesEntry) { _valuesEntry = valuesEntry; } public Object getKey () { OrderKey ok = (OrderKey) _valuesEntry.getKey (); return ok.key; } public Object getValue () { return _valuesEntry.getValue (); } public Object setValue (Object value) { return _valuesEntry.setValue (value); } public boolean equals (Object other) { if (other == this) return true; if (!(other instanceof Map.Entry)) return false; Object key = getKey (); Object key2 = ((Map.Entry) other).getKey (); if ((key == null && key2 != null) || (key != null && !key.equals (key2))) return false; Object val = getValue (); Object val2 = ((Map.Entry) other).getValue (); return (val == null && val2 == null) || (val != null && val2.equals (val2)); } } /** * View of the entry set. */ private class EntrySet extends AbstractSet { public int size () { return LRUMap.this.size (); } public boolean add (Object o) { Map.Entry entry = (Map.Entry) o; put (entry.getKey (), entry.getValue ()); return true; } public Iterator iterator () { final Iterator valuesItr = _values.entrySet ().iterator (); return new Iterator () { private MapEntry _last = null; public boolean hasNext () { return valuesItr.hasNext (); } public Object next () { _last = new MapEntry ((Map.Entry) valuesItr.next ()); return _last; } public void remove () { valuesItr.remove (); _orders.remove (_last.getKey ()); } }; } } /** * View of the key set. */ private class KeySet extends AbstractSet { public int size () { return LRUMap.this.size (); } public Iterator iterator () { final Iterator keysItr = _values.keySet ().iterator (); return new Iterator () { private Object _last = null; public boolean hasNext () { return keysItr.hasNext (); } public Object next () { _last = ((OrderKey) keysItr.next ()).key; return _last; } public void remove () { keysItr.remove (); _orders.remove (_last); } }; } } /** * View of the value collection. */ private class ValueCollection extends AbstractCollection { public int size () { return LRUMap.this.size (); } public Iterator iterator () { final Iterator valuesItr = _values.entrySet ().iterator (); return new Iterator () { private Object _last = null; public boolean hasNext () { return valuesItr.hasNext (); } public Object next () { Map.Entry entry = (Map.Entry) valuesItr.next (); _last = ((OrderKey) entry.getKey ()).key; return entry.getValue (); } public void remove () { valuesItr.remove (); _orders.remove (_last); } }; } } }
3e03417595c406ac231a46dd1af23dfd8faa4036
10,212
java
Java
app/build/generated/not_namespaced_r_class_sources/debug/r/android/support/graphics/drawable/animated/R.java
matxc/AndroidTraining1-SportNews1
c3c0369f120df63a65f35dceaec42febee1d11f4
[ "Apache-2.0" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/debug/r/android/support/graphics/drawable/animated/R.java
matxc/AndroidTraining1-SportNews1
c3c0369f120df63a65f35dceaec42febee1d11f4
[ "Apache-2.0" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/debug/r/android/support/graphics/drawable/animated/R.java
matxc/AndroidTraining1-SportNews1
c3c0369f120df63a65f35dceaec42febee1d11f4
[ "Apache-2.0" ]
null
null
null
54.903226
147
0.736193
1,344
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.graphics.drawable.animated; public final class R { private R() {} public static final class attr { private attr() {} public static final int coordinatorLayoutStyle = 0x7f040076; public static final int font = 0x7f04009e; public static final int fontProviderAuthority = 0x7f0400a0; public static final int fontProviderCerts = 0x7f0400a1; public static final int fontProviderFetchStrategy = 0x7f0400a2; public static final int fontProviderFetchTimeout = 0x7f0400a3; public static final int fontProviderPackage = 0x7f0400a4; public static final int fontProviderQuery = 0x7f0400a5; public static final int fontStyle = 0x7f0400a6; public static final int fontWeight = 0x7f0400a7; public static final int keylines = 0x7f0400c1; public static final int layout_anchor = 0x7f0400c4; public static final int layout_anchorGravity = 0x7f0400c5; public static final int layout_behavior = 0x7f0400c6; public static final int layout_dodgeInsetEdges = 0x7f0400eb; public static final int layout_insetEdge = 0x7f0400f4; public static final int layout_keyline = 0x7f0400f5; public static final int statusBarBackground = 0x7f040142; } public static final class bool { private bool() {} public static final int abc_action_bar_embed_tabs = 0x7f050000; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f06004d; public static final int notification_icon_bg_color = 0x7f06004e; public static final int ripple_material_light = 0x7f060059; public static final int secondary_text_default_material_light = 0x7f06005b; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f070050; public static final int compat_button_inset_vertical_material = 0x7f070051; public static final int compat_button_padding_horizontal_material = 0x7f070052; public static final int compat_button_padding_vertical_material = 0x7f070053; public static final int compat_control_corner_material = 0x7f070054; public static final int notification_action_icon_size = 0x7f07008a; public static final int notification_action_text_size = 0x7f07008b; public static final int notification_big_circle_margin = 0x7f07008c; public static final int notification_content_margin_start = 0x7f07008d; public static final int notification_large_icon_height = 0x7f07008e; public static final int notification_large_icon_width = 0x7f07008f; public static final int notification_main_column_padding_top = 0x7f070090; public static final int notification_media_narrow_margin = 0x7f070091; public static final int notification_right_icon_size = 0x7f070092; public static final int notification_right_side_padding_top = 0x7f070093; public static final int notification_small_icon_background_padding = 0x7f070094; public static final int notification_small_icon_size_as_large = 0x7f070095; public static final int notification_subtext_size = 0x7f070096; public static final int notification_top_pad = 0x7f070097; public static final int notification_top_pad_large_text = 0x7f070098; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f08006e; public static final int notification_bg = 0x7f08006f; public static final int notification_bg_low = 0x7f080070; public static final int notification_bg_low_normal = 0x7f080071; public static final int notification_bg_low_pressed = 0x7f080072; public static final int notification_bg_normal = 0x7f080073; public static final int notification_bg_normal_pressed = 0x7f080074; public static final int notification_icon_background = 0x7f080075; public static final int notification_template_icon_bg = 0x7f080076; public static final int notification_template_icon_low_bg = 0x7f080077; public static final int notification_tile_bg = 0x7f080078; public static final int notify_panel_notification_icon_bg = 0x7f080079; } public static final class id { private id() {} public static final int action_container = 0x7f09000e; public static final int action_divider = 0x7f090010; public static final int action_image = 0x7f090011; public static final int action_text = 0x7f090017; public static final int actions = 0x7f090018; public static final int async = 0x7f09001e; public static final int blocking = 0x7f090022; public static final int bottom = 0x7f090023; public static final int chronometer = 0x7f09002b; public static final int end = 0x7f09003d; public static final int forever = 0x7f090049; public static final int icon = 0x7f09004e; public static final int icon_group = 0x7f09004f; public static final int info = 0x7f090052; public static final int italic = 0x7f090053; public static final int left = 0x7f090056; public static final int line1 = 0x7f090057; public static final int line3 = 0x7f090058; public static final int none = 0x7f090065; public static final int normal = 0x7f090066; public static final int notification_background = 0x7f090067; public static final int notification_main_column = 0x7f090068; public static final int notification_main_column_container = 0x7f090069; public static final int right = 0x7f090074; public static final int right_icon = 0x7f090075; public static final int right_side = 0x7f090076; public static final int start = 0x7f09009c; public static final int tag_transition_group = 0x7f0900a3; public static final int text = 0x7f0900a4; public static final int text2 = 0x7f0900a5; public static final int time = 0x7f0900ab; public static final int title = 0x7f0900ac; public static final int top = 0x7f0900b0; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f0a000a; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b002c; public static final int notification_action_tombstone = 0x7f0b002d; public static final int notification_template_custom_big = 0x7f0b0034; public static final int notification_template_icon_group = 0x7f0b0035; public static final int notification_template_part_chronometer = 0x7f0b0039; public static final int notification_template_part_time = 0x7f0b003a; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0d002a; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0e00f4; public static final int TextAppearance_Compat_Notification_Info = 0x7f0e00f5; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e00f7; public static final int TextAppearance_Compat_Notification_Time = 0x7f0e00fa; public static final int TextAppearance_Compat_Notification_Title = 0x7f0e00fc; public static final int Widget_Compat_NotificationActionContainer = 0x7f0e0172; public static final int Widget_Compat_NotificationActionText = 0x7f0e0173; public static final int Widget_Support_CoordinatorLayout = 0x7f0e017f; } public static final class styleable { private styleable() {} public static final int[] CoordinatorLayout = { 0x7f0400c1, 0x7f040142 }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f0400c4, 0x7f0400c5, 0x7f0400c6, 0x7f0400eb, 0x7f0400f4, 0x7f0400f5 }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0400a0, 0x7f0400a1, 0x7f0400a2, 0x7f0400a3, 0x7f0400a4, 0x7f0400a5 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x7f04009e, 0x7f0400a6, 0x7f0400a7 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_font = 3; public static final int FontFamilyFont_fontStyle = 4; public static final int FontFamilyFont_fontWeight = 5; } }
3e034195490bffa4b77e1a752702250c4c862494
3,196
java
Java
core/src/main/java/eu/mihosoft/vmf/core/GetterOnly.java
pzugel/VMF
7d70fa9276776f3f6d2e89d7751dd731ea979008
[ "Apache-2.0" ]
10
2018-07-17T12:21:12.000Z
2021-12-13T10:59:31.000Z
core/src/main/java/eu/mihosoft/vmf/core/GetterOnly.java
pzugel/VMF
7d70fa9276776f3f6d2e89d7751dd731ea979008
[ "Apache-2.0" ]
46
2018-07-31T09:04:49.000Z
2022-03-09T12:25:18.000Z
core/src/main/java/eu/mihosoft/vmf/core/GetterOnly.java
pzugel/VMF
7d70fa9276776f3f6d2e89d7751dd731ea979008
[ "Apache-2.0" ]
6
2018-07-16T16:41:12.000Z
2020-07-31T15:31:31.000Z
39.555556
206
0.735955
1,345
/* * Copyright 2017-2019 Michael Hoffer <[email protected]>. All rights reserved. * Copyright 2017-2019 Goethe Center for Scientific Computing, University Frankfurt. 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. * * If you use this software for scientific research then please cite the following publication(s): * * M. Hoffer, C. Poliwoda, & G. Wittum. (2013). Visual reflection library: * a framework for declarative GUI programming on the Java platform. * Computing and Visualization in Science, 2013, 16(4), * 181–192. http://doi.org/10.1007/s00791-014-0230-y */ package eu.mihosoft.vmf.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that only the getter method of a property should be publically available. This is no alternative to immutable * types. Actually, the purpose of this annotation is to allow a common interface for immutable and mutable types. It is * only valid in combination with {@link InterfaceOnly} and cannot be applied to regular types. * * <h3>Example Model:</h3> * <pre><code> * package mypkg.vmfmodel; * import eu.mihosoft.vmf.core.*; * * @InterfaceOnly * interface WithName { * * @GetterOnly * String getName(); * * } * * interface ImmutableObj extends WithName { } * * interface MutableObj extends WithName { } * </code></pre> * * Both, the mutable and the immutable entity can be casted to their common super interface {@code WithName}. * * <pre><code> * ImmutableObj immutableObj = ImmutableObj.newBuilder().withName("immutable obj").build(); * MutableObj mutableObj = MutableObj.newBuilder().withName("mutable obj").build(); * WithName withName1 = immutableObj; * WithName withName2 = mutableObj; * </code></pre> * * This is possible because VMF detects that {@code WithName} is effectively 'immutable', i.e., * equivalent to its read-only type {@code ReadOnlyWithName} and only has/inherits immutable property types. * That is, it is compatible with the immutable type which can safely inherit from the {@code WithName} * interface without breaking its contract. * * <p>Created by miho on 02.01.2017.</p> * * @author Michael Hoffer <[email protected]> * * @see {@link InterfaceOnly} * @see {@link Immutable} * @see <a href="https://github.com/miho/VMF-Tutorials/blob/master/VMF-Tutorial-07/README.md#how-can-mutable-and-immutable-types-share-a-common-super-type">Tutorial on Immutable Objects and ReadOnly API</a> */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface GetterOnly { }
3e0341cda16cb09884a28ba7c7ccddcbd8e1f1cd
1,270
java
Java
src/chatproject/packets/servercompackets/ReserveNameRequest.java
michael-kamel/reactor
55587b2515becd75d90a0065f8dff36a925029c7
[ "MIT" ]
null
null
null
src/chatproject/packets/servercompackets/ReserveNameRequest.java
michael-kamel/reactor
55587b2515becd75d90a0065f8dff36a925029c7
[ "MIT" ]
null
null
null
src/chatproject/packets/servercompackets/ReserveNameRequest.java
michael-kamel/reactor
55587b2515becd75d90a0065f8dff36a925029c7
[ "MIT" ]
null
null
null
27.608696
104
0.751181
1,346
package chatproject.packets.servercompackets; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import chatproject.constants.Constants; import chatproject.exceptions.PacketLengthNotMatching; import chatproject.packets.Packet; public class ReserveNameRequest extends Packet { private String name; public ReserveNameRequest(ByteBuffer buf) throws PacketLengthNotMatching, UnsupportedEncodingException { super(buf); } public ReserveNameRequest(String name) { super(5 + name.length() * Constants.DEFAULT_CHARSET_CHAR_LENGTH , (byte)12); this.name = name; } public String getName() { return name; } public ByteBuffer serialize() throws IOException { ByteBuffer buf = ByteBuffer.allocate(5 + name.length() * Constants.DEFAULT_CHARSET_CHAR_LENGTH); intiateSerialization(buf); buf.put(name.getBytes(Constants.DEFAULT_CHARSET)); buf.flip(); return buf; } public void deserialize(ByteBuffer buf) throws UnsupportedEncodingException, PacketLengthNotMatching { intiateDeserialization(buf); byte[] nameBuf = new byte[buf.capacity() - 5]; buf.get(nameBuf, 0, nameBuf.length); name = new String(nameBuf, Constants.DEFAULT_CHARSET); } }
3e0341f3ce468df9ada567a0f2272da45d34ce1c
6,007
java
Java
applications/signalmapeditor/src/main/java/uk/trainwatch/nrod/signalmapeditor/Project.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
15
2015-02-10T13:23:36.000Z
2021-12-21T13:34:54.000Z
applications/signalmapeditor/src/main/java/uk/trainwatch/nrod/signalmapeditor/Project.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
55
2015-04-04T12:35:08.000Z
2017-09-04T17:56:56.000Z
applications/signalmapeditor/src/main/java/uk/trainwatch/nrod/signalmapeditor/Project.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
4
2015-11-16T03:20:54.000Z
2022-03-06T00:36:20.000Z
28.469194
123
0.639088
1,347
/* * 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 uk.trainwatch.nrod.signalmapeditor; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import javax.swing.Action; import javax.swing.JEditorPane; import javax.swing.JTextField; import uk.trainwatch.nrod.signalmapeditor.map.SignalMap; /** * * @author peter */ public enum Project implements PropertyChangeListener { INSTANCE; /** * Predicate that returns true if the value in a {@link PropertyChangeEvent} has not changed */ public static final Predicate<PropertyChangeEvent> UNCHANGED = e -> Objects.equals( e.getOldValue(), e.getNewValue() ); /** * Predicate that returns true if the value in a {@link PropertyChangeEvent} has changed */ public static final Predicate<PropertyChangeEvent> CHANGED = UNCHANGED.negate(); public static final String PROP_CHANGED = "projectChanged"; private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport( this ); private final SignalMap map; private boolean changed = false; @SuppressWarnings("LeakingThisInConstructor") private Project() { map = new SignalMap(); map.addPropertyChangeListener( this ); } public void newMap() { map.setArea( "MA" ); try { map.setAuthor( System.getProperty( "user.name" ) + "@" + InetAddress.getLocalHost(). getHostName() ); } catch( UnknownHostException ex ) { map.setAuthor( System.getProperty( "user.name" ) + "@localhost" ); } map.setTitle( "Untitled" ); map.setVersion( "1.0" ); map.clear(); setChanged( false ); } @Override public void propertyChange( PropertyChangeEvent evt ) { setChanged( true ); // Pass it on propertyChangeSupport.firePropertyChange( evt.getPropertyName(), evt.getOldValue(), evt.getNewValue() ); } /** * Get the value of changed * * @return the value of changed */ public boolean isChanged() { return changed; } /** * Set the value of changed * * @param changed new value of changed */ public void setChanged( boolean changed ) { boolean oldChanged = this.changed; this.changed = changed; propertyChangeSupport.firePropertyChange( PROP_CHANGED, oldChanged, changed ); } /** * Similar to {@link #setChanged(boolean)} but only sets it * <p> */ public void markAsChanged() { setChanged( true ); } /** * Add PropertyChangeListener. * * @param listener */ public void addPropertyChangeListener( PropertyChangeListener listener ) { propertyChangeSupport.addPropertyChangeListener( listener ); } public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener ) { propertyChangeSupport.addPropertyChangeListener( propertyName, listener ); } /** * Remove PropertyChangeListener. * * @param listener */ public void removePropertyChangeListener( PropertyChangeListener listener ) { propertyChangeSupport.removePropertyChangeListener( listener ); } public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener ) { propertyChangeSupport.removePropertyChangeListener( propertyName, listener ); } /** * Enables an action if we are changed * <p> * @param action */ public void enableActionWhenChanged( Action action ) { addPropertyChangeListener( PROP_CHANGED, e -> action.setEnabled( CHANGED.test( e ) ) ); action.setEnabled( changed ); } public void disableActionWhenChanged( Action action ) { addPropertyChangeListener( PROP_CHANGED, e -> action.setEnabled( UNCHANGED.test( e ) ) ); action.setEnabled( !changed ); } public void addTextField( JTextField f, String property, Supplier<String> getter, Consumer<String> setter ) { // Set the field to the initial value f.setText( getter.get() ); // Set the field when the property changes addPropertyChangeListener( property, e -> f.setText( getter.get() ) ); // Set the property when the field changes - i.e. enter pressed f.addActionListener( e -> setter.accept( f.getText() ) ); // Also when focus is lost - i.e. tab out does not get any change f.addFocusListener( new FocusAdapter() { @Override public void focusLost( FocusEvent e ) { setter.accept( f.getText() ); } } ); } public void addEditorPane( JEditorPane f, String property, Supplier<String> getter, Consumer<String> setter ) { // Set the field to the initial value f.setText( getter.get() ); // Set the field when the property changes addPropertyChangeListener( property, e -> f.setText( getter.get() ) ); // Also when focus is lost - i.e. tab out does not get any change f.addFocusListener( new FocusAdapter() { @Override public void focusLost( FocusEvent e ) { setter.accept( f.getText() ); } } ); } public boolean isPresent() { return map != null; } public SignalMap getMap() { return map; } }
3e0342284170f60dfd21e54748d422e9ab7080e5
3,366
java
Java
src/beans/RegistrationEAO.java
CodeGuro/SixTwelveProject
615d12c61f0e4a6a9a9eb39591777a30ec298859
[ "BSD-2-Clause" ]
null
null
null
src/beans/RegistrationEAO.java
CodeGuro/SixTwelveProject
615d12c61f0e4a6a9a9eb39591777a30ec298859
[ "BSD-2-Clause" ]
null
null
null
src/beans/RegistrationEAO.java
CodeGuro/SixTwelveProject
615d12c61f0e4a6a9a9eb39591777a30ec298859
[ "BSD-2-Clause" ]
null
null
null
24.569343
70
0.686572
1,348
package beans; import java.util.List; import java.util.ArrayList; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.RollbackException; import javax.persistence.TypedQuery; import javax.faces.validator.ValidatorException; import resources.Address; import resources.Group; import resources.User; import resources.Util; /** * Session Bean implementation class RegistrationEAO */ @Stateless( mappedName = "registrationEAO" ) @LocalBean public class RegistrationEAO { @PersistenceContext( ) private EntityManager entityManager; public RegistrationEAO() { } public boolean persistUser( RegistrationBean regBean ) { try { // Map a User instance to persist in the db User user = new User(); user.setUsername( regBean.getUsername() ); user.setPassword( Util.hash( regBean.getPassword() ) ); user.setFirstname( regBean.getFirstname() ); user.setLastname( regBean.getLastname() ); user.setBirth( regBean.getDob().toString() ); user.setEmail( regBean.getEmail() ); // Map an Address instance to persist in the db Address address = new Address(); address.setStreet( regBean.getStreet() ); address.setSuburb( regBean.getSuburb() ); address.setCity( regBean.getCity() ); address.setZip( regBean.getZip() ); address.setState_Province( regBean.getProvince() ); address.setCountry( regBean.getCountry() ); user.setAddress( address ); List< User > users = new ArrayList< User >(); users.add( user ); address.setUsers( users ); // Use JPQL to append the groups StringBuffer buffer = new StringBuffer(); String[] targets = regBean.getSelectedGroups(); buffer.append( "SELECT c FROM Group c WHERE c.groupname=?1" ); int count = 2; for( int x = 1; x < targets.length; x++ ) { buffer.append( " OR c.groupname=?" + count ); count++; } // Add the parameter values to the query count = 1; Query query = this.entityManager.createQuery( buffer.toString() ); for( String target : targets ) { query.setParameter( count, target ); count++; } // Fix for expression of type list needs express conversion to // conform // to conversion List // List groups = query.getResultList(); List< Group > groups = Util.castList( Group.class, query.getResultList() ); // Add user to each group for( Group group : groups ) { group.getUsers().add( user ); } // Add Groups to user user.setGroups( groups ); // Commit data to the database entityManager.persist( user ); return true; } catch ( RollbackException e ) { Throwable en = e.getCause(); en.printStackTrace(); } catch ( Exception e ) { e.printStackTrace(); } return false; } public boolean CheckRegisteredUser( String usname, String passwd ) throws ValidatorException { EntityManager em = this.entityManager; @SuppressWarnings( "unchecked" ) TypedQuery< User > query = (TypedQuery< User >)em.createNativeQuery( "SELECT * FROM mydb.user WHERE username = \"" + usname + "\"", User.class ); List< User > users = query.getResultList(); for( User user : users ) { if( user.getPassword().equals( Util.hash( passwd ) ) ) return true; } return false; } }
3e034243f4b61bbe5f1e18d77a585eb4b10ac659
1,162
java
Java
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/competitionsetup/applicationformbuilder/template/AssessmentOnlyTemplate.java
InnovateUKGitHub/innovation-funding-service
56ed6468b05c88ba59762687ebb35150e6d1e436
[ "MIT" ]
40
2017-03-29T13:58:42.000Z
2021-07-04T22:13:12.000Z
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/competitionsetup/applicationformbuilder/template/AssessmentOnlyTemplate.java
InnovateUKGitHub/innovation-funding-service
56ed6468b05c88ba59762687ebb35150e6d1e436
[ "MIT" ]
19
2017-09-30T11:57:32.000Z
2022-02-13T18:38:48.000Z
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/competitionsetup/applicationformbuilder/template/AssessmentOnlyTemplate.java
InnovateUKGitHub/innovation-funding-service
56ed6468b05c88ba59762687ebb35150e6d1e436
[ "MIT" ]
20
2017-04-05T11:34:30.000Z
2022-03-22T14:42:08.000Z
31.405405
90
0.717728
1,349
package org.innovateuk.ifs.competitionsetup.applicationformbuilder.template; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.resource.CompetitionTypeEnum; import org.innovateuk.ifs.competitionsetup.applicationformbuilder.builder.SectionBuilder; import org.springframework.stereotype.Component; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static org.innovateuk.ifs.competitionsetup.applicationformbuilder.CommonBuilders.*; @Component public class AssessmentOnlyTemplate implements CompetitionTemplate { @Override public CompetitionTypeEnum type() { return CompetitionTypeEnum.ASSESSMENT_ONLY; } @Override public Competition copyTemplatePropertiesToCompetition(Competition competition) { return competition; } @Override public List<SectionBuilder> sections() { return newArrayList( projectDetails() .withQuestions(newArrayList( applicationDetails() )), applicationQuestions() ); } }
3e0342a0ebadb3b77651077472ee590a524b668f
315
java
Java
labs/trans-st2/src/OutputModelObject.java
parrt/cs652
24a2353290887203c11a0a50bc703084374483c0
[ "BSD-3-Clause" ]
110
2015-01-01T00:00:35.000Z
2022-02-15T11:17:24.000Z
labs/trans-st2/src/OutputModelObject.java
Ducasse/cs652
24a2353290887203c11a0a50bc703084374483c0
[ "BSD-3-Clause" ]
4
2015-02-27T21:59:33.000Z
2019-04-09T16:05:01.000Z
labs/trans-st2/src/OutputModelObject.java
Ducasse/cs652
24a2353290887203c11a0a50bc703084374483c0
[ "BSD-3-Clause" ]
67
2015-01-16T05:09:31.000Z
2021-10-12T09:18:39.000Z
26.25
69
0.733333
1,350
import org.stringtemplate.v4.ST; /** A generic root for any object representing an output component */ public abstract class OutputModelObject { public ST getTemplate() { String className = getClass().getSimpleName(); ST st = Gen.templates.getInstanceOf(className); st.add("model", this); return st; } }
3e03431aea64b6b397900c7d38d43f5b6a5ddea2
1,133
java
Java
src/main/java/net/openhft/chronicle/wire/YamlMethodTester.java
horsebridge/Chronicle-Wire
51382dca03dbf4fdd3b7a4fe1abd3ee8302ee7ea
[ "Apache-2.0" ]
273
2015-01-16T23:14:39.000Z
2022-03-24T08:12:34.000Z
src/main/java/net/openhft/chronicle/wire/YamlMethodTester.java
horsebridge/Chronicle-Wire
51382dca03dbf4fdd3b7a4fe1abd3ee8302ee7ea
[ "Apache-2.0" ]
334
2015-08-11T21:59:09.000Z
2022-03-30T19:00:53.000Z
src/main/java/net/openhft/chronicle/wire/YamlMethodTester.java
horsebridge/Chronicle-Wire
51382dca03dbf4fdd3b7a4fe1abd3ee8302ee7ea
[ "Apache-2.0" ]
121
2015-01-16T23:14:42.000Z
2022-03-04T04:54:20.000Z
33.323529
119
0.737864
1,351
/* * Copyright 2016-2020 chronicle.software * * https://chronicle.software * * 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 net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import java.util.function.Function; public class YamlMethodTester<T> extends TextMethodTester<T> { public YamlMethodTester(String input, Function<T, Object> componentFunction, Class<T> outputClass, String output) { super(input, componentFunction, outputClass, output); } @Override protected Wire createWire(Bytes bytes) { return new YamlWire(bytes).useTextDocuments(); } }
3e03434ca93cffb2b44e7d7e98b53dbd44ee0865
686
java
Java
src/main/java/farsight/testing/jbehave/steps/core/PipelineVariableStep.java
beaglos/testing-jbehave
859cb1d0e1826a27e8cb3811e514184134686b17
[ "MIT" ]
null
null
null
src/main/java/farsight/testing/jbehave/steps/core/PipelineVariableStep.java
beaglos/testing-jbehave
859cb1d0e1826a27e8cb3811e514184134686b17
[ "MIT" ]
null
null
null
src/main/java/farsight/testing/jbehave/steps/core/PipelineVariableStep.java
beaglos/testing-jbehave
859cb1d0e1826a27e8cb3811e514184134686b17
[ "MIT" ]
1
2020-10-07T19:16:47.000Z
2020-10-07T19:16:47.000Z
26.384615
102
0.813411
1,352
package farsight.testing.jbehave.steps.core; import com.wm.data.IData; import farsight.testing.jbehave.ExecutionContext; import farsight.testing.jbehave.steps.WmStep; import farsight.testing.utils.jexl.JexlExpressionUtil; public class PipelineVariableStep implements WmStep { private final String jexlValueExpressions; public PipelineVariableStep(String jexlValueExpressions) { this.jexlValueExpressions = jexlValueExpressions; } @Override public void execute(ExecutionContext ctx) throws Exception { IData idata = ctx.getPipeline(); idata = JexlExpressionUtil.executeValueExpressions(idata, jexlValueExpressions, ctx.getResources()); ctx.setPipeline(idata); } }
3e0343a21ae8e41996fcb2f72f4e55dee33019a3
840
java
Java
app/src/main/java/com/oops/render/ShakeDrawer.java
sunjinbo/oops
62e25006fe6d7d3e77a2e72bdbaee29fc2d3cc58
[ "MIT" ]
null
null
null
app/src/main/java/com/oops/render/ShakeDrawer.java
sunjinbo/oops
62e25006fe6d7d3e77a2e72bdbaee29fc2d3cc58
[ "MIT" ]
1
2021-04-14T10:35:06.000Z
2021-08-05T12:46:34.000Z
app/src/main/java/com/oops/render/ShakeDrawer.java
sunjinbo/oops
62e25006fe6d7d3e77a2e72bdbaee29fc2d3cc58
[ "MIT" ]
null
null
null
25.454545
111
0.675
1,353
package com.oops.render; import android.content.Context; import android.opengl.GLES20; import com.oops.R; /** * ShakeDrawer class. */ public class ShakeDrawer extends BaseDrawer { private final int uFitTimeLocation; private boolean mIsStart = true; private long mStart; public ShakeDrawer(Context context, int textureID) { super(context, textureID, R.raw.direct_vertex_shader, R.raw.filter_shake_fragment_shader); uFitTimeLocation = GLES20.glGetUniformLocation(mProgramId, "fit_time"); } @Override protected void childDraw() { super.childDraw(); if (mIsStart) { mStart = System.currentTimeMillis(); mIsStart = false; } GLES20.glUniform1f(uFitTimeLocation, ((float) (System.currentTimeMillis() - mStart) / 2000.0f) % 0.2f); } }
3e03440e81325cdf68898ee45cf62fec6c1d4e53
4,560
java
Java
ygcms-web/src/main/java/org/pro/ygcms/facade/impl/CmsChannelTxtFacadeImpl.java
guokaijava/ygcms
c4f7ead2ab52cb27b899a188160db11b0a1fa729
[ "MIT" ]
null
null
null
ygcms-web/src/main/java/org/pro/ygcms/facade/impl/CmsChannelTxtFacadeImpl.java
guokaijava/ygcms
c4f7ead2ab52cb27b899a188160db11b0a1fa729
[ "MIT" ]
null
null
null
ygcms-web/src/main/java/org/pro/ygcms/facade/impl/CmsChannelTxtFacadeImpl.java
guokaijava/ygcms
c4f7ead2ab52cb27b899a188160db11b0a1fa729
[ "MIT" ]
null
null
null
38
142
0.732675
1,354
package org.pro.ygcms.facade.impl; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import org.dayatang.domain.InstanceFactory; import org.dayatang.querychannel.QueryChannelService; import org.dayatang.utils.Page; import org.openkoala.koala.commons.InvokeResult; import org.pro.ygcms.application.CmsChannelTxtApplication; import org.pro.ygcms.core.domain.channel.CmsChannelTxt; import org.pro.ygcms.facade.CmsChannelTxtFacade; import org.pro.ygcms.facade.dto.CmsChannelTxtDTO; import org.pro.ygcms.facade.impl.assembler.CmsChannelTxtAssembler; @Named public class CmsChannelTxtFacadeImpl implements CmsChannelTxtFacade { @Inject private CmsChannelTxtApplication application; private QueryChannelService queryChannel; private QueryChannelService getQueryChannelService(){ if(queryChannel==null){ queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel"); } return queryChannel; } public InvokeResult getCmsChannelTxt(Long id) { return InvokeResult.success(CmsChannelTxtAssembler.toDTO(application.getCmsChannelTxt(id))); } public InvokeResult creatCmsChannelTxt(CmsChannelTxtDTO cmsChannelTxtDTO) { application.creatCmsChannelTxt(CmsChannelTxtAssembler.toEntity(cmsChannelTxtDTO)); return InvokeResult.success(); } public InvokeResult updateCmsChannelTxt(CmsChannelTxtDTO cmsChannelTxtDTO) { CmsChannelTxt cmsChannelTxt = application.getCmsChannelTxtByCid(cmsChannelTxtDTO.getChannelId()); if(cmsChannelTxt==null){ application.creatCmsChannelTxt(CmsChannelTxtAssembler.toEntity(cmsChannelTxtDTO)); }else{ cmsChannelTxt.setTxt(cmsChannelTxtDTO.getTxt()); application.updateCmsChannelTxt(cmsChannelTxt); } return InvokeResult.success(); } public InvokeResult removeCmsChannelTxt(Long id) { application.removeCmsChannelTxt(application.getCmsChannelTxt(id)); return InvokeResult.success(); } public InvokeResult removeCmsChannelTxts(Long[] ids) { Set<CmsChannelTxt> cmsChannelTxts= new HashSet<CmsChannelTxt>(); for (Long id : ids) { cmsChannelTxts.add(application.getCmsChannelTxt(id)); } application.removeCmsChannelTxts(cmsChannelTxts); return InvokeResult.success(); } public List<CmsChannelTxtDTO> findAllCmsChannelTxt() { return CmsChannelTxtAssembler.toDTOs(application.findAllCmsChannelTxt()); } public Page<CmsChannelTxtDTO> pageQueryCmsChannelTxt(CmsChannelTxtDTO queryVo, int currentPage, int pageSize) { List<Object> conditionVals = new ArrayList<Object>(); StringBuilder jpql = new StringBuilder("select _cmsChannelTxt from CmsChannelTxt _cmsChannelTxt where 1=1 "); if (queryVo.getChannelId() != null) { jpql.append(" and _cmsChannelTxt.channelId=?"); conditionVals.add(queryVo.getChannelId()); } if (queryVo.getTxt() != null && !"".equals(queryVo.getTxt())) { jpql.append(" and _cmsChannelTxt.txt like ?"); conditionVals.add(MessageFormat.format("%{0}%", queryVo.getTxt())); } if (queryVo.getTxt1() != null && !"".equals(queryVo.getTxt1())) { jpql.append(" and _cmsChannelTxt.txt1 like ?"); conditionVals.add(MessageFormat.format("%{0}%", queryVo.getTxt1())); } if (queryVo.getTxt2() != null && !"".equals(queryVo.getTxt2())) { jpql.append(" and _cmsChannelTxt.txt2 like ?"); conditionVals.add(MessageFormat.format("%{0}%", queryVo.getTxt2())); } if (queryVo.getTxt3() != null && !"".equals(queryVo.getTxt3())) { jpql.append(" and _cmsChannelTxt.txt3 like ?"); conditionVals.add(MessageFormat.format("%{0}%", queryVo.getTxt3())); } @SuppressWarnings("unchecked") Page<CmsChannelTxt> pages = getQueryChannelService() .createJpqlQuery(jpql.toString()) .setParameters(conditionVals) .setPage(currentPage, pageSize) .pagedList(); return new Page<CmsChannelTxtDTO>(pages.getStart(), pages.getResultCount(),pageSize, CmsChannelTxtAssembler.toDTOs(pages.getData())); } @Override public CmsChannelTxtDTO getCmsChannelTxtByCid(String id) { return CmsChannelTxtAssembler.toDTO(application.getCmsChannelTxtByCid(id)); } @Override public void removeCmsChannelTxtByCid(String channelId) { application.removeCmsChannelTxt(application.getCmsChannelTxtByCid(channelId)); } }
3e034469ac56eb68bc3179797c96f380a261f6bc
23,032
java
Java
src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodydate/implementation/DatesImpl.java
RichardSlater/autorest
9e7956e6196bf380d58023d9eed0dde09c4ad3d1
[ "MIT" ]
3
2018-03-20T22:36:32.000Z
2021-07-15T02:36:51.000Z
src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodydate/implementation/DatesImpl.java
brywang-msft/autorest
3090ab1250a03562e4961b5c7cd46c1572260f8f
[ "MIT" ]
null
null
null
src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodydate/implementation/DatesImpl.java
brywang-msft/autorest
3090ab1250a03562e4961b5c7cd46c1572260f8f
[ "MIT" ]
null
null
null
39.438356
148
0.63846
1,355
/** * 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. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.bodydate.implementation; import retrofit2.Retrofit; import fixtures.bodydate.Dates; import com.google.common.reflect.TypeToken; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import fixtures.bodydate.models.ErrorException; import java.io.IOException; import okhttp3.ResponseBody; import org.joda.time.LocalDate; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.PUT; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Dates. */ public class DatesImpl implements Dates { /** The Retrofit service to perform REST calls. */ private DatesService service; /** The service client containing this operation class. */ private AutoRestDateTestServiceImpl client; /** * Initializes an instance of Dates. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public DatesImpl(Retrofit retrofit, AutoRestDateTestServiceImpl client) { this.service = retrofit.create(DatesService.class); this.client = client; } /** * The interface defining all the services for Dates to be * used by Retrofit to perform actually REST calls. */ interface DatesService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getNull" }) @GET("date/null") Observable<Response<ResponseBody>> getNull(); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getInvalidDate" }) @GET("date/invaliddate") Observable<Response<ResponseBody>> getInvalidDate(); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getOverflowDate" }) @GET("date/overflowdate") Observable<Response<ResponseBody>> getOverflowDate(); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getUnderflowDate" }) @GET("date/underflowdate") Observable<Response<ResponseBody>> getUnderflowDate(); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates putMaxDate" }) @PUT("date/max") Observable<Response<ResponseBody>> putMaxDate(@Body LocalDate dateBody); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getMaxDate" }) @GET("date/max") Observable<Response<ResponseBody>> getMaxDate(); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates putMinDate" }) @PUT("date/min") Observable<Response<ResponseBody>> putMinDate(@Body LocalDate dateBody); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.bodydate.Dates getMinDate" }) @GET("date/min") Observable<Response<ResponseBody>> getMinDate(); } /** * Get null date value. * * @return the LocalDate object if successful. */ public LocalDate getNull() { return getNullWithServiceResponseAsync().toBlocking().single().body(); } /** * Get null date value. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getNullAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getNullWithServiceResponseAsync(), serviceCallback); } /** * Get null date value. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getNullAsync() { return getNullWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get null date value. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getNullWithServiceResponseAsync() { return service.getNull() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getNullDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getNullDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Get invalid date value. * * @return the LocalDate object if successful. */ public LocalDate getInvalidDate() { return getInvalidDateWithServiceResponseAsync().toBlocking().single().body(); } /** * Get invalid date value. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getInvalidDateAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getInvalidDateWithServiceResponseAsync(), serviceCallback); } /** * Get invalid date value. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getInvalidDateAsync() { return getInvalidDateWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get invalid date value. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getInvalidDateWithServiceResponseAsync() { return service.getInvalidDate() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getInvalidDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getInvalidDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Get overflow date value. * * @return the LocalDate object if successful. */ public LocalDate getOverflowDate() { return getOverflowDateWithServiceResponseAsync().toBlocking().single().body(); } /** * Get overflow date value. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getOverflowDateAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getOverflowDateWithServiceResponseAsync(), serviceCallback); } /** * Get overflow date value. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getOverflowDateAsync() { return getOverflowDateWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get overflow date value. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getOverflowDateWithServiceResponseAsync() { return service.getOverflowDate() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getOverflowDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getOverflowDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Get underflow date value. * * @return the LocalDate object if successful. */ public LocalDate getUnderflowDate() { return getUnderflowDateWithServiceResponseAsync().toBlocking().single().body(); } /** * Get underflow date value. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getUnderflowDateAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getUnderflowDateWithServiceResponseAsync(), serviceCallback); } /** * Get underflow date value. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getUnderflowDateAsync() { return getUnderflowDateWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get underflow date value. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getUnderflowDateWithServiceResponseAsync() { return service.getUnderflowDate() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getUnderflowDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getUnderflowDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Put max date value 9999-12-31. * * @param dateBody the LocalDate value */ public void putMaxDate(LocalDate dateBody) { putMaxDateWithServiceResponseAsync(dateBody).toBlocking().single().body(); } /** * Put max date value 9999-12-31. * * @param dateBody the LocalDate value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Void> putMaxDateAsync(LocalDate dateBody, final ServiceCallback<Void> serviceCallback) { return ServiceCall.fromResponse(putMaxDateWithServiceResponseAsync(dateBody), serviceCallback); } /** * Put max date value 9999-12-31. * * @param dateBody the LocalDate value * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> putMaxDateAsync(LocalDate dateBody) { return putMaxDateWithServiceResponseAsync(dateBody).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Put max date value 9999-12-31. * * @param dateBody the LocalDate value * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> putMaxDateWithServiceResponseAsync(LocalDate dateBody) { if (dateBody == null) { throw new IllegalArgumentException("Parameter dateBody is required and cannot be null."); } return service.putMaxDate(dateBody) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = putMaxDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> putMaxDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Get max date value 9999-12-31. * * @return the LocalDate object if successful. */ public LocalDate getMaxDate() { return getMaxDateWithServiceResponseAsync().toBlocking().single().body(); } /** * Get max date value 9999-12-31. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getMaxDateAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getMaxDateWithServiceResponseAsync(), serviceCallback); } /** * Get max date value 9999-12-31. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getMaxDateAsync() { return getMaxDateWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get max date value 9999-12-31. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getMaxDateWithServiceResponseAsync() { return service.getMaxDate() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getMaxDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getMaxDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Put min date value 0000-01-01. * * @param dateBody the LocalDate value */ public void putMinDate(LocalDate dateBody) { putMinDateWithServiceResponseAsync(dateBody).toBlocking().single().body(); } /** * Put min date value 0000-01-01. * * @param dateBody the LocalDate value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Void> putMinDateAsync(LocalDate dateBody, final ServiceCallback<Void> serviceCallback) { return ServiceCall.fromResponse(putMinDateWithServiceResponseAsync(dateBody), serviceCallback); } /** * Put min date value 0000-01-01. * * @param dateBody the LocalDate value * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> putMinDateAsync(LocalDate dateBody) { return putMinDateWithServiceResponseAsync(dateBody).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Put min date value 0000-01-01. * * @param dateBody the LocalDate value * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> putMinDateWithServiceResponseAsync(LocalDate dateBody) { if (dateBody == null) { throw new IllegalArgumentException("Parameter dateBody is required and cannot be null."); } return service.putMinDate(dateBody) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = putMinDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> putMinDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Get min date value 0000-01-01. * * @return the LocalDate object if successful. */ public LocalDate getMinDate() { return getMinDateWithServiceResponseAsync().toBlocking().single().body(); } /** * Get min date value 0000-01-01. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<LocalDate> getMinDateAsync(final ServiceCallback<LocalDate> serviceCallback) { return ServiceCall.fromResponse(getMinDateWithServiceResponseAsync(), serviceCallback); } /** * Get min date value 0000-01-01. * * @return the observable to the LocalDate object */ public Observable<LocalDate> getMinDateAsync() { return getMinDateWithServiceResponseAsync().map(new Func1<ServiceResponse<LocalDate>, LocalDate>() { @Override public LocalDate call(ServiceResponse<LocalDate> response) { return response.body(); } }); } /** * Get min date value 0000-01-01. * * @return the observable to the LocalDate object */ public Observable<ServiceResponse<LocalDate>> getMinDateWithServiceResponseAsync() { return service.getMinDate() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LocalDate>>>() { @Override public Observable<ServiceResponse<LocalDate>> call(Response<ResponseBody> response) { try { ServiceResponse<LocalDate> clientResponse = getMinDateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LocalDate> getMinDateDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return this.client.restClient().responseBuilderFactory().<LocalDate, ErrorException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LocalDate>() { }.getType()) .registerError(ErrorException.class) .build(response); } }
3e0344ea461e5b296ee06f21f2c998ede855cf79
948
java
Java
src/edu/washington/cse/concerto/interpreter/EmbeddedState.java
uwplse/concerto
a23d35eae9f6be8c0c1e8e0e4adac5aa3386c1df
[ "MIT" ]
4
2019-03-11T02:02:20.000Z
2022-01-30T07:53:09.000Z
src/edu/washington/cse/concerto/interpreter/EmbeddedState.java
uwplse/concerto
a23d35eae9f6be8c0c1e8e0e4adac5aa3386c1df
[ "MIT" ]
null
null
null
src/edu/washington/cse/concerto/interpreter/EmbeddedState.java
uwplse/concerto
a23d35eae9f6be8c0c1e8e0e4adac5aa3386c1df
[ "MIT" ]
null
null
null
32.689655
97
0.767932
1,356
package edu.washington.cse.concerto.interpreter; import edu.washington.cse.concerto.interpreter.lattice.Lattice; public class EmbeddedState<T> { public final T state; public final Lattice<T> stateLattice; public EmbeddedState(final T state, final Lattice<T> stateLattice) { this.state = state; this.stateLattice = stateLattice; } public boolean lessThan(final EmbeddedState<T> other) { assert this.stateLattice == other.stateLattice; return this.stateLattice.lessEqual(this.state, other.state); } public EmbeddedState<T> join(final EmbeddedState<T> other) { assert this.stateLattice == other.stateLattice; return new EmbeddedState<>(this.stateLattice.join(this.state, other.state), this.stateLattice); } public EmbeddedState<T> widen(final EmbeddedState<T> next) { assert this.stateLattice == next.stateLattice; return new EmbeddedState<>(this.stateLattice.widen(this.state, next.state), this.stateLattice); } }
3e034511e6d5bedd8dcf67c83ae5993358643ddc
4,587
java
Java
src/main/java/pinacolada/patches/VictoryPatches.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
null
null
null
src/main/java/pinacolada/patches/VictoryPatches.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
null
null
null
src/main/java/pinacolada/patches/VictoryPatches.java
Darkon47/STS-FoolMod
85ebfd1f93edd2a1ec738a294b95a3a299564077
[ "Apache-2.0" ]
null
null
null
40.236842
185
0.69806
1,357
package pinacolada.patches; import com.badlogic.gdx.math.MathUtils; import com.evacipated.cardcrawl.modthespire.lib.*; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.dungeons.TheEnding; import com.megacrit.cardcrawl.rooms.VictoryRoom; import com.megacrit.cardcrawl.screens.GameOverScreen; import com.megacrit.cardcrawl.screens.GameOverStat; import com.megacrit.cardcrawl.screens.VictoryScreen; import eatyourbeets.monsters.Bosses.TheUnnamed; import eatyourbeets.utilities.FieldInfo; import pinacolada.resources.PGR; import pinacolada.utilities.PCLGameUtilities; import pinacolada.utilities.PCLJUtils; import java.util.ArrayList; // Act 5 and Act 3 victory logic public class VictoryPatches { private static final FieldInfo<ArrayList<GameOverStat>> _stats = PCLJUtils.GetField("stats", GameOverScreen.class); private static final FieldInfo<Integer> _bossPoints = PCLJUtils.GetField("bossPoints", GameOverScreen.class); private static final TheUnnamed.Data data = new TheUnnamed.Data(TheUnnamed.ID); private static int glyphBonus = 0; private static GameOverStat GetAscensionGlyphStats() { return new GameOverStat(PGR.PCL.Strings.CharSelect.AscensionGlyph, data.strings.DIALOG[28], String.valueOf(glyphBonus)); } private static GameOverStat GetUnnamedGameOverStats() { return new GameOverStat(data.strings.NAME, data.strings.DIALOG[28], String.valueOf(GetUnnamedScoreBonus())); } private static GameOverStat GetLongestComboStats() { return new GameOverStat(PGR.PCL.Strings.Combat.Rerolls, null, String.valueOf(PGR.PCL.Dungeon.GetLongestMatchCombo())); } private static int GetAscensionGlyphScoreBonus(int baseScore) { return MathUtils.round((float)baseScore * 0.02F * PCLJUtils.Sum(PGR.PCL.Dungeon.AscensionGlyphCounters, Integer::floatValue)); } private static int GetUnnamedScoreBonus() { return 300 + Math.round(200 * (PCLGameUtilities.GetAscensionLevel() / 20f)); } @SpirePatch(clz = VictoryRoom.class, method = "onPlayerEntry") public static class VictoryRoomPatches_onEnterRoom { @SpirePrefixPatch public static void Method(VictoryRoom __instance) { if (Settings.isStandardRun() && __instance.eType == VictoryRoom.EventType.HEART // this is the room you enter after defeating act 3 Boss && AbstractDungeon.player.chosenClass == PGR.Fool.PlayerClass) { PGR.Fool.Data.RecordVictory(PCLGameUtilities.GetActualAscensionLevel()); } } } @SpirePatch(clz = VictoryScreen.class, method = "createGameOverStats") public static class VictoryScreenPatches_createGameOverStats { @SpirePostfixPatch public static void Method(VictoryScreen __instance) { ArrayList<GameOverStat> stats = _stats.Get(__instance); if (glyphBonus > 0) { stats.add(Math.max(0, stats.size() - 2), GetAscensionGlyphStats()); } stats.add(Math.max(0, stats.size() - 2), GetLongestComboStats()); if (PGR.PCL.Dungeon.IsUnnamedReign()) { _bossPoints.Set(__instance, _bossPoints.Get(__instance) + GetUnnamedScoreBonus()); stats.add(Math.max(0, stats.size() - 2), GetUnnamedGameOverStats()); } if (Settings.isStandardRun() && PCLGameUtilities.IsPCLPlayerClass()) { PGR.Fool.Data.RecordTrueVictory(PCLGameUtilities.GetActualAscensionLevel(), (PGR.PCL.Dungeon.IsUnnamedReign() ? 3 : CardCrawlGame.dungeon instanceof TheEnding ? 2 : 1)); } } } @SpirePatch(clz = GameOverScreen.class, method = "calcScore", paramtypez = {boolean.class}) public static class GameOverScreenPatches_calcScore { @SpirePostfixPatch public static int Method(int __result, boolean isVictory) { glyphBonus = GetAscensionGlyphScoreBonus(__result); return __result + glyphBonus; } } @SpirePatch(clz = GameOverScreen.class, method = "checkScoreBonus", paramtypez = {boolean.class}) public static class GameOverScreenPatches_checkScoreBonus { @SpireInsertPatch(rloc = 1, localvars = {"points"}) public static void Method(boolean isVictory, @ByRef int[] points) { points[0] += PGR.PCL.Dungeon.GetLongestMatchCombo(); } } }
3e0346282923c8b9bb51d7fa43d293a84bbd5eb7
1,336
java
Java
cooper-source/cooper-parse/src/main/java/jdepend/parse/sql/IBATIS20SQLConfigParse.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
9
2015-01-30T06:55:28.000Z
2019-11-28T08:47:14.000Z
cooper-source/cooper-parse/src/main/java/jdepend/parse/sql/IBATIS20SQLConfigParse.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
3
2015-08-12T23:09:51.000Z
2018-12-07T06:10:44.000Z
cooper-source/cooper-parse/src/main/java/jdepend/parse/sql/IBATIS20SQLConfigParse.java
jdepend/cooper
baac23d8372a4ece5c103a815b2a573a55ee59cb
[ "Apache-2.0" ]
7
2015-03-05T07:33:55.000Z
2021-12-14T07:17:40.000Z
31.809524
89
0.711078
1,358
package jdepend.parse.sql; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jdepend.framework.log.LogUtil; import jdepend.metadata.TableInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class IBATIS20SQLConfigParse implements ConfigParse { @Override public void parse(Document doc) { Map<String, List<TableInfo>> tables = new HashMap<String, List<TableInfo>>(); Element root = doc.getDocumentElement(); String namespace = root.getAttribute("namespace"); LogUtil.getInstance(IBATIS20SQLConfigParse.class).systemLog("namespace:" + namespace); List<String> tagNames = new ArrayList<String>(); tagNames.add("insert"); tagNames.add("update"); tagNames.add("delete"); tagNames.add("select"); for (String tagName : tagNames) { NodeList tags = doc.getElementsByTagName(tagName); for (int i = 0; i < tags.getLength(); i++) { Element tag = (Element) tags.item(i); String sql = tag.getTextContent(); tables.put(namespace + "." + tag.getAttribute("id"), SqlParseUtil.parserSql(sql)); } } LogUtil.getInstance(IBATIS20SQLConfigParse.class).systemLog("tables:" + tables); ConfigParseMgr.getInstance().addTables(TableInfoItem.KeyType, tables); } }
3e034692aca63b0e511ab37baa4c9eea2224ae3a
2,832
java
Java
service-fee/src/main/java/com/java110/fee/cmd/feePrintPage/DeleteFeePrintPageCmd.java
yingxx26/MicroCommunity
8f33010207f58aca006b29bcd226813521639fbf
[ "Apache-2.0" ]
null
null
null
service-fee/src/main/java/com/java110/fee/cmd/feePrintPage/DeleteFeePrintPageCmd.java
yingxx26/MicroCommunity
8f33010207f58aca006b29bcd226813521639fbf
[ "Apache-2.0" ]
null
null
null
service-fee/src/main/java/com/java110/fee/cmd/feePrintPage/DeleteFeePrintPageCmd.java
yingxx26/MicroCommunity
8f33010207f58aca006b29bcd226813521639fbf
[ "Apache-2.0" ]
1
2022-02-26T07:45:16.000Z
2022-02-26T07:45:16.000Z
39.319444
119
0.776404
1,359
/* * Copyright 2017-2020 吴学文 and java110 team. * * 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.java110.fee.cmd.feePrintPage; import com.alibaba.fastjson.JSONObject; import com.java110.core.annotation.Java110Cmd; import com.java110.core.annotation.Java110Transactional; import com.java110.core.context.ICmdDataFlowContext; import com.java110.core.event.cmd.AbstractServiceCmdListener; import com.java110.core.event.cmd.CmdEvent; import com.java110.intf.fee.IFeePrintPageV1InnerServiceSMO; import com.java110.po.feePrintPage.FeePrintPagePo; import com.java110.utils.exception.CmdException; import com.java110.utils.util.Assert; import com.java110.utils.util.BeanConvertUtil; import com.java110.vo.ResultVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * 类表述:删除 * 服务编码:feePrintPage.deleteFeePrintPage * 请求路劲:/app/feePrintPage.DeleteFeePrintPage * add by 吴学文 at 2021-09-16 22:26:04 mail: [email protected] * open source address: https://gitee.com/wuxw7/MicroCommunity * 官网:http://www.homecommunity.cn * 温馨提示:如果您对此文件进行修改 请不要删除原有作者及注释信息,请补充您的 修改的原因以及联系邮箱如下 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复,注释10至20行 加入 20行至30行 */ @Java110Cmd(serviceCode = "feePrintPage.deleteFeePrintPage") public class DeleteFeePrintPageCmd extends AbstractServiceCmdListener { private static Logger logger = LoggerFactory.getLogger(DeleteFeePrintPageCmd.class); @Autowired private IFeePrintPageV1InnerServiceSMO feePrintPageV1InnerServiceSMOImpl; @Override public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) { Assert.hasKeyAndValue(reqJson, "pageId", "pageId不能为空"); Assert.hasKeyAndValue(reqJson, "communityId", "communityId不能为空"); } @Override @Java110Transactional public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException { FeePrintPagePo feePrintPagePo = BeanConvertUtil.covertBean(reqJson, FeePrintPagePo.class); int flag = feePrintPageV1InnerServiceSMOImpl.deleteFeePrintPage(feePrintPagePo); if (flag < 1) { throw new CmdException("删除数据失败"); } cmdDataFlowContext.setResponseEntity(ResultVo.success()); } }
3e0346cfca77d2d5188ea83359efa1ae4ef05641
2,908
java
Java
std-juc/src/main/java/com/std/juc/aqs/ConditionStart.java
sence-std/std-base
9bc59f6663d87b919cc5f5fe6647995e0ad5df75
[ "MIT" ]
2
2015-04-07T06:08:15.000Z
2015-12-17T08:40:19.000Z
std-juc/src/main/java/com/std/juc/aqs/ConditionStart.java
sence-std/std-base
9bc59f6663d87b919cc5f5fe6647995e0ad5df75
[ "MIT" ]
null
null
null
std-juc/src/main/java/com/std/juc/aqs/ConditionStart.java
sence-std/std-base
9bc59f6663d87b919cc5f5fe6647995e0ad5df75
[ "MIT" ]
null
null
null
24.644068
72
0.483494
1,360
/** * @FileName: ConditionStart.java * @Package: com.std.thread * @author liusq23 * @created 2018/2/8 上午10:19 * <p> * Copyright 2015 ziroom */ package com.std.juc.aqs; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * <p> * 学习ReentrantLock Condition * 实现多线程顺序打印 A B C * ThreadA 打印 A * ThreadB 打印 B * ThreadC 打印 C * 这种方案会导致线程signal了一个没有到达await点的线程,例如: * ThreadA 在signal ThreadB 继续 signal ThreadC后 * ThreadA 还未到达await点,这个时候ThreadC signal了 会导致 ThreadA 永远等待,线程卡死 * A signal * C将到达await点... * A将到达await点... * </p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author liusq23 * @since 1.0 * @version 1.0 */ public class ConditionStart { private ReentrantLock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private Condition c3 = lock.newCondition(); public void printA(){ while(true){ lock.lock(); try { System.out.println("A将到达await点..."); c1.await(); System.out.println("A"); c2.signal(); System.out.println("B signal"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } public void printB(){ while(true){ lock.lock(); try { System.out.println("B将到达await点..."); c2.await(); System.out.println("B"); c3.signal(); System.out.println("C signal"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } public void printC(){ while(true){ lock.lock(); try { System.out.println("C将到达await点..."); c3.await(); System.out.println("C"); c1.signal(); System.out.println("A signal"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } public void doSignalA(){ lock.lock(); try { c1.signal(); }finally { lock.unlock(); } } public static void main(String[] args) throws InterruptedException { ConditionStart cs = new ConditionStart(); new Thread(()->cs.printA()).start(); new Thread(()->cs.printB()).start(); new Thread(()->cs.printC()).start(); cs.doSignalA(); synchronized (cs) { cs.wait(); } } }
3e03490fe2513b1df0a30615e618c657b7f5bb47
1,970
java
Java
core/src/main/java/org/infinispan/configuration/cache/EncodingConfigurationBuilder.java
xiaodong-xie/infinispan
13d7f252e1f332c7aa178e665f6fd79ce5a1ab64
[ "Apache-2.0" ]
1
2020-06-01T21:20:47.000Z
2020-06-01T21:20:47.000Z
core/src/main/java/org/infinispan/configuration/cache/EncodingConfigurationBuilder.java
gustavolira/infinispan
ea7c44e210b9366ef832d80c462cd80899e85446
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/infinispan/configuration/cache/EncodingConfigurationBuilder.java
gustavolira/infinispan
ea7c44e210b9366ef832d80c462cd80899e85446
[ "Apache-2.0" ]
null
null
null
32.295082
127
0.758376
1,361
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.Builder; import org.infinispan.configuration.global.GlobalConfiguration; /** * @since 9.2 */ public class EncodingConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<EncodingConfiguration> { private ContentTypeConfigurationBuilder keyContentTypeBuilder = new ContentTypeConfigurationBuilder(this); private ContentTypeConfigurationBuilder valueContentTypeBuilder = new ContentTypeConfigurationBuilder(this); EncodingConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public void validate() { keyContentTypeBuilder.validate(); valueContentTypeBuilder.validate(); } public ContentTypeConfigurationBuilder key() { return keyContentTypeBuilder; } public ContentTypeConfigurationBuilder value() { return valueContentTypeBuilder; } @Override public EncodingConfiguration create() { ContentTypeConfiguration keyContentType = keyContentTypeBuilder.create(); ContentTypeConfiguration valueContentType = valueContentTypeBuilder.create(); return new EncodingConfiguration(keyContentType, valueContentType); } @Override public Builder<?> read(EncodingConfiguration template) { this.keyContentTypeBuilder = new ContentTypeConfigurationBuilder(this).read(template.keyDataType()); this.valueContentTypeBuilder = new ContentTypeConfigurationBuilder(this).read(template.valueDataType()); return this; } @Override public void validate(GlobalConfiguration globalConfig) { keyContentTypeBuilder.validate(); valueContentTypeBuilder.validate(); } @Override public String toString() { return "DataTypeConfigurationBuilder{" + "keyContentTypeBuilder=" + keyContentTypeBuilder + ", valueContentTypeBuilder=" + valueContentTypeBuilder + '}'; } }
3e034912a4850b04973296ca56f94d920aad9d4e
7,250
java
Java
src/corbaExample/src/java/com/healthmarketscience/rmiio/_RemoteInputStreamServer_Tie.java
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
7
2016-04-05T15:58:01.000Z
2020-10-30T18:38:05.000Z
src/corbaExample/src/java/com/healthmarketscience/rmiio/_RemoteInputStreamServer_Tie.java
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
2
2016-07-04T01:32:56.000Z
2020-12-11T02:54:56.000Z
src/corbaExample/src/java/com/healthmarketscience/rmiio/_RemoteInputStreamServer_Tie.java
jahlborn/rmiio
58c05f29e6dbc44c0f18c9a2247aff113d487c71
[ "Apache-2.0" ]
6
2016-04-05T15:58:16.000Z
2020-04-27T21:45:47.000Z
40.055249
112
0.484414
1,362
// Tie class generated by rmic, do not edit. // Contents subject to change without notice. package com.healthmarketscience.rmiio; import java.io.IOException; import java.io.Serializable; import java.rmi.Remote; import java.rmi.RemoteException; import javax.rmi.CORBA.Tie; import javax.rmi.CORBA.Util; import org.omg.CORBA.BAD_OPERATION; import org.omg.CORBA.ORB; import org.omg.CORBA.SystemException; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import org.omg.CORBA.portable.ResponseHandler; import org.omg.CORBA.portable.UnknownException; import org.omg.PortableServer.Servant; public class _RemoteInputStreamServer_Tie extends Servant implements Tie { private RemoteInputStreamServer target = null; private static final String[] _type_ids = { "RMI:com.healthmarketscience.rmiio.RemoteInputStream:0000000000000000" }; public void setTarget(Remote target) { this.target = (RemoteInputStreamServer) target; } public Remote getTarget() { return target; } public org.omg.CORBA.Object thisObject() { return _this_object(); } public void deactivate() { try{ _poa().deactivate_object(_poa().servant_to_id(this)); }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ } } public ORB orb() { return _orb(); } public void orb(ORB orb) { try { ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); } catch(ClassCastException e) { throw new org.omg.CORBA.BAD_PARAM ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); } } public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ return _type_ids; } public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { try { org.omg.CORBA_2_3.portable.InputStream in = (org.omg.CORBA_2_3.portable.InputStream) _in; switch (method.length()) { case 4: if (method.equals("skip")) { long arg0 = in.read_longlong(); int arg1 = in.read_long(); long result; try { result = target.skip(arg0, arg1); } catch (IOException ex) { String id = "IDL:java/io/IOEx:1.0"; org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); out.write_string(id); out.write_value(ex,IOException.class); return out; } OutputStream out = reply.createReply(); out.write_longlong(result); return out; } case 5: if (method.equals("close")) { boolean arg0 = in.read_boolean(); try { target.close(arg0); } catch (IOException ex) { String id = "IDL:java/io/IOEx:1.0"; org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); out.write_string(id); out.write_value(ex,IOException.class); return out; } OutputStream out = reply.createReply(); return out; } case 9: if (method.equals("available")) { int result; try { result = target.available(); } catch (IOException ex) { String id = "IDL:java/io/IOEx:1.0"; org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); out.write_string(id); out.write_value(ex,IOException.class); return out; } OutputStream out = reply.createReply(); out.write_long(result); return out; } case 10: if (method.equals("readPacket")) { int arg0 = in.read_long(); byte[] result; try { result = target.readPacket(arg0); } catch (IOException ex) { String id = "IDL:java/io/IOEx:1.0"; org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); out.write_string(id); out.write_value(ex,IOException.class); return out; } org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); out.write_value(cast_array(result),byte[].class); return out; } case 20: if (method.equals("usingGZIPCompression")) { boolean result; try { result = target.usingGZIPCompression(); } catch (IOException ex) { String id = "IDL:java/io/IOEx:1.0"; org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); out.write_string(id); out.write_value(ex,IOException.class); return out; } OutputStream out = reply.createReply(); out.write_boolean(result); return out; } } throw new BAD_OPERATION(); } catch (SystemException ex) { throw ex; } catch (Throwable ex) { throw new UnknownException(ex); } } // This method is required as a work-around for // a bug in the JDK 1.1.6 verifier. private Serializable cast_array(Object obj) { return (Serializable)obj; } }
3e034a211c97776b3fbaabec09415dd9ee472dee
1,952
java
Java
testsuite/basic/src/test/java/io/smallrye/faulttolerance/fallbackmethod/nonpublic/NonPublicFallbackMethodTest.java
michalszynkiewicz/smallrye-fault-tolerance
ef4bc788228797a043f71016d1524a2b75de5078
[ "Apache-2.0" ]
null
null
null
testsuite/basic/src/test/java/io/smallrye/faulttolerance/fallbackmethod/nonpublic/NonPublicFallbackMethodTest.java
michalszynkiewicz/smallrye-fault-tolerance
ef4bc788228797a043f71016d1524a2b75de5078
[ "Apache-2.0" ]
3
2019-02-14T11:37:00.000Z
2019-02-18T10:48:55.000Z
testsuite/basic/src/test/java/io/smallrye/faulttolerance/fallbackmethod/nonpublic/NonPublicFallbackMethodTest.java
michalszynkiewicz/smallrye-fault-tolerance
ef4bc788228797a043f71016d1524a2b75de5078
[ "Apache-2.0" ]
null
null
null
31.483871
109
0.746414
1,363
/* * Copyright 2017 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.smallrye.faulttolerance.fallbackmethod.nonpublic; import static org.junit.Assert.assertEquals; import java.util.Collections; import javax.inject.Inject; import io.smallrye.faulttolerance.TestArchive; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Martin Kouba */ @RunWith(Arquillian.class) public class NonPublicFallbackMethodTest { @Deployment public static JavaArchive createTestArchive() { return TestArchive.createBase(NonPublicFallbackMethodTest.class) .addPackage(NonPublicFallbackMethodTest.class.getPackage()); } @Inject FaultyService service; @Test public void testFallbackMethod() throws NoSuchMethodException, SecurityException { FaultyService.COUNTER.set(0); assertEquals(service.foo(), 1); assertEquals(FaultyService.COUNTER.get(), 3); } @Test public void testFallbackMethodParameterizedReturnType() throws NoSuchMethodException, SecurityException { FaultyService.COUNTER.set(0); assertEquals(service.fooParameterized(), Collections.emptyList()); assertEquals(FaultyService.COUNTER.get(), 3); } }
3e034abf362a17cca43b998f887e487ef8af9d59
1,918
java
Java
src/editor/utils/SelectionRectangle.java
ljolliet/ShapeEditor
e97644a9adb2fdd3397dc86d1d98d4d675d48ee1
[ "MIT" ]
3
2020-05-25T10:08:24.000Z
2021-05-27T13:40:39.000Z
src/editor/utils/SelectionRectangle.java
ljolliet/ShapeEditor
e97644a9adb2fdd3397dc86d1d98d4d675d48ee1
[ "MIT" ]
null
null
null
src/editor/utils/SelectionRectangle.java
ljolliet/ShapeEditor
e97644a9adb2fdd3397dc86d1d98d4d675d48ee1
[ "MIT" ]
null
null
null
30.444444
91
0.660063
1,364
/* * Copyright (c) 2020 ShapeEditor. * @authors L. Jolliet, L. Sicardon, P. Vigneau * @version 1.0 * Architecture Logicielle - Université de Bordeaux */ package editor.utils; import ui.ApplicationI; public class SelectionRectangle implements SelectionShape { private Point2D selectionStartPoint = new Point2D(0.,0.); private Point2D selectionEndPoint = new Point2D(0.,0.); private boolean on = false; @Override public Point2D getPosition() { double x = Math.min(selectionStartPoint.x, selectionEndPoint.x); double y = Math.min(selectionStartPoint.y, selectionEndPoint.y); return new Point2D(x,y); } @Override public boolean contains(Point2D p) { Point2D position = getPosition(); return position.x <= p.x && p.x <= position.x + getWidth() && position.y <= p.y && p.y <= position.y + getHeight(); } @Override public void setSelectionStartPoint(Point2D selectionStartPoint) { double x = Math.max(0, Math.min(ApplicationI.SCENE_WIDTH, selectionStartPoint.x)); double y = Math.max(0, Math.min(ApplicationI.SCENE_HEIGHT, selectionStartPoint.y)); this.selectionStartPoint = new Point2D(x, y); } @Override public void setSelectionEndPoint(Point2D selectionEndPoint) { double x = Math.max(0, Math.min(ApplicationI.SCENE_WIDTH, selectionEndPoint.x)); double y = Math.max(0, Math.min(ApplicationI.SCENE_HEIGHT, selectionEndPoint.y)); this.selectionEndPoint = new Point2D(x, y); } @Override public void setOn(boolean on) { this.on = on; } @Override public boolean isOn() { return this.on; } public double getWidth() { return Math.abs(selectionEndPoint.x - selectionStartPoint.x); } public double getHeight() { return Math.abs(selectionEndPoint.y - selectionStartPoint.y); } }
3e034b41587881090c019863944f4d0e92973900
124
java
Java
app/src/main/java/com/appsmata/qtoa/models/BackgroundDrawer.java
mwendwa5/qa-android
9a669297bcabada01a082087abebcbb02f24fca7
[ "MIT" ]
null
null
null
app/src/main/java/com/appsmata/qtoa/models/BackgroundDrawer.java
mwendwa5/qa-android
9a669297bcabada01a082087abebcbb02f24fca7
[ "MIT" ]
null
null
null
app/src/main/java/com/appsmata/qtoa/models/BackgroundDrawer.java
mwendwa5/qa-android
9a669297bcabada01a082087abebcbb02f24fca7
[ "MIT" ]
1
2021-12-08T10:03:33.000Z
2021-12-08T10:03:33.000Z
17.714286
35
0.758065
1,365
package com.appsmata.qtoa.models; public class BackgroundDrawer { public int id; public String background_image; }
3e034bcfbc4a7c4bba9ced2e9d16db2fc11ffa98
826
java
Java
app/src/main/java/uk/ac/soton/ecs/comp6237/l2/ItemBasedRecDemo.java
jonhare/COMP6237
e44c09c32ca28af54a5749313e34f640c84e2977
[ "BSD-3-Clause" ]
24
2017-05-09T19:06:14.000Z
2022-02-10T11:30:26.000Z
app/src/main/java/uk/ac/soton/ecs/comp6237/l2/ItemBasedRecDemo.java
QiongDS/COMP6237
08cffe5ddc6b9bc447faf0d7d196f4c2bdd46fa1
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/uk/ac/soton/ecs/comp6237/l2/ItemBasedRecDemo.java
QiongDS/COMP6237
08cffe5ddc6b9bc447faf0d7d196f4c2bdd46fa1
[ "BSD-3-Clause" ]
23
2016-02-01T21:31:02.000Z
2020-10-24T09:18:37.000Z
31.769231
86
0.791768
1,366
package uk.ac.soton.ecs.comp6237.l2; import java.io.IOException; import javax.swing.JSplitPane; import org.openimaj.content.slideshow.SlideshowApplication; import uk.ac.soton.ecs.comp6237.utils.GroovyREPLConsoleSlide; import uk.ac.soton.ecs.comp6237.utils.Utils; import uk.ac.soton.ecs.comp6237.utils.annotations.Demonstration; @Demonstration(title = "Item-based recommendation") public class ItemBasedRecDemo extends GroovyREPLConsoleSlide { public ItemBasedRecDemo() throws IOException { super(JSplitPane.VERTICAL_SPLIT, Lecture2.class.getResource("ItemRec.groovy"), "getRecommendations(data, 'Toby')", "getRecommendedItems(data, itemsim, 'Toby')"); } public static void main(String[] args) throws IOException { new SlideshowApplication(new ItemBasedRecDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); } }
3e034bfd398b49111534fc6637212e4686999d88
4,556
java
Java
hibernate/src/main/java/org/xchain/namespaces/hibernate/GetCommand.java
ctrimble/xchain
a45558b9f11b6ecf95cb7952272777af720e69d5
[ "Apache-2.0" ]
1
2020-12-10T01:02:42.000Z
2020-12-10T01:02:42.000Z
hibernate/src/main/java/org/xchain/namespaces/hibernate/GetCommand.java
ctrimble/xchain
a45558b9f11b6ecf95cb7952272777af720e69d5
[ "Apache-2.0" ]
null
null
null
hibernate/src/main/java/org/xchain/namespaces/hibernate/GetCommand.java
ctrimble/xchain
a45558b9f11b6ecf95cb7952272777af720e69d5
[ "Apache-2.0" ]
null
null
null
35.874016
139
0.699956
1,367
/** * Copyright 2011 meltmedia * * 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.xchain.namespaces.hibernate; import java.io.Serializable; import org.apache.commons.jxpath.JXPathContext; import org.hibernate.Session; import org.hibernate.metadata.ClassMetadata; import org.xchain.annotations.Attribute; import org.xchain.annotations.AttributeType; import org.xchain.annotations.Element; import org.xchain.framework.jxpath.ScopedQNameVariables; import org.xchain.framework.jxpath.Scope; import org.xchain.framework.hibernate.HibernateLifecycle; /** * <p>The <code>get</code> command starts executes the Get method on the current session. The <code>class-name</code> attribute identifies * the class to be loaded. The <code>id</code> attribute identifies the unique identifier for the class to be loaded.</p> * * <p>This must reference an active <code>session</code>.</p> * * <code class="source"> * &lt;xchain:session xmlns:xchain="http://www.xchain.org/hibernate/1.0"&gt; * &lt;xchain:transaction&gt; * ... * &lt;xchain:get id="'1'" class-name="'my.package.entity'" variable="result" scope="request"/&gt; * ... * &lt;/xchain:transaction&gt; * &lt;/xchain:session&gt; * </code> * * @author Devon Tackett * @author Christian Trimble * * @see SessionCommand * @see org.hibernate.Session#get(Class, Serializable) */ @Element(localName="get") public abstract class GetCommand extends AbstractSessionCommand { /** * ID of the entity to retrieve. */ @Attribute(localName="id", type=AttributeType.JXPATH_VALUE) public abstract Serializable getId( JXPathContext context, Class type ); public abstract boolean hasId(); /** * The class of the entity to retrieve. */ @Attribute(localName="class-name", type=AttributeType.JXPATH_VALUE) public abstract String getClassName( JXPathContext context ); public abstract boolean hasClassName(); /** * Where to store the retrieved entity. */ @Attribute(localName="result", type=AttributeType.QNAME) public abstract String getResult( JXPathContext context); public abstract boolean hasResult(); /** * Variable of where to store the entity. */ @Attribute(localName="variable", type=AttributeType.QNAME) public abstract String getVariable( JXPathContext context); public abstract boolean hasVariable(); /** * Scope of the variable storing the entity. * @see Scope */ @Attribute(localName="scope", type=AttributeType.LITERAL, defaultValue="execution") public abstract Scope getScope(JXPathContext context); protected void storeValue(JXPathContext context, Object value) throws Exception { if (hasResult()) { // TODO This should check that the path exists first. If it doesn't exist, create it. context.setValue(getResult(context), value); } else if (hasVariable()) { ((ScopedQNameVariables)context.getVariables()).declareVariable( getVariable(context), value, getScope(context) ); } else { throw new Exception("Result or Variable must be given."); } } /** * Performs a Get for the given class-name with the given id and stores the result in the given * result QName. */ public boolean execute( JXPathContext context ) throws Exception { if (!hasId()) throw new Exception("A get command must have an id."); if (!hasClassName()) throw new Exception("A get command must have a class-name."); // Get the session from the context. Session session = HibernateLifecycle.getCurrentSession(getName(context)); // Get the metadata of the entity to be loaded from hibernate ClassMetadata metadata = session.getSessionFactory().getClassMetadata(getClassName(context)); storeValue(context, session.get(getClassName(context), getId(context, metadata.getIdentifierType().getReturnedClass()))); // The get is executed. return false; } }
3e034ce0c349abaf4069cffc3a75d839d3759fb1
3,288
java
Java
strongbox-web-core/src/test/java/org/carlspring/strongbox/controllers/PingControllerTest.java
vamvindev/strongbox
0006a6872476b92055406de2ce889219dcdb0f91
[ "Apache-2.0" ]
1
2018-10-15T20:49:56.000Z
2018-10-15T20:49:56.000Z
strongbox-web-core/src/test/java/org/carlspring/strongbox/controllers/PingControllerTest.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
strongbox-web-core/src/test/java/org/carlspring/strongbox/controllers/PingControllerTest.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
29.621622
76
0.598844
1,368
package org.carlspring.strongbox.controllers; import org.carlspring.strongbox.config.IntegrationTest; import org.carlspring.strongbox.rest.common.MavenRestAssuredBaseTest; import org.apache.http.HttpHeaders; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.context.junit4.SpringRunner; import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; /** * @author Steve Todorov */ @IntegrationTest @RunWith(SpringRunner.class) public class PingControllerTest extends MavenRestAssuredBaseTest { @Override public void init() throws Exception { super.init(); setContextBaseUrl(getContextBaseUrl() + "/api/ping"); } @Test public void testShouldReturnPongText() { given().header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE) .when() .get(getContextBaseUrl()) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(equalTo("pong")); } @Test public void testShouldReturnPongJSON() { given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(getContextBaseUrl()) .peek() .then() .statusCode(HttpStatus.OK.value()) .body("message", equalTo("pong")); } @Test public void testShouldReturnPongForAuthenticatedUsersJSON() { given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(getContextBaseUrl() + "/token") .peek() .then() .statusCode(HttpStatus.OK.value()) .body("message", equalTo("pong")); } @Test public void testShouldReturnPongForAuthenticatedUsersText() { given().header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE) .when() .get(getContextBaseUrl() + "/token") .peek() .then() .statusCode(HttpStatus.OK.value()) .body(equalTo("pong")); } @Test @WithAnonymousUser public void testAnonymousUsersShouldNotBeAbleToAccessJSON() { given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(getContextBaseUrl() + "/token") .peek() .then() .log().all() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body(notNullValue()); } @Test @WithAnonymousUser public void testAnonymousUsersShouldNotBeAbleToAccessText() { given().header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE) .when() .get(getContextBaseUrl() + "/token") .peek() .then() .log().all() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body(notNullValue()); } }
3e034dafccc6abc554ff17ede09b2eb285f94d71
1,018
java
Java
src/testexec/VariableHandler.java
phaupt/sipproxy
c5524948f05a1a3b03696ffc59f89f08089d063c
[ "Apache-2.0" ]
1
2019-05-24T17:45:51.000Z
2019-05-24T17:45:51.000Z
src/testexec/VariableHandler.java
phaupt/sipproxy
c5524948f05a1a3b03696ffc59f89f08089d063c
[ "Apache-2.0" ]
null
null
null
src/testexec/VariableHandler.java
phaupt/sipproxy
c5524948f05a1a3b03696ffc59f89f08089d063c
[ "Apache-2.0" ]
null
null
null
28.277778
106
0.630648
1,369
package testexec; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import pd.IVar; public class VariableHandler implements IVariableHandler { private Map<String, String> variableMap; public VariableHandler(){ variableMap = new Hashtable<String, String>(); } public void addVariables(Vector<? extends IVar> variables){ addVariables(variables, null); } public void addVariables( Vector<? extends IVar> variables, IVariableReplacer variableReplacer) { //Add each Variable in Vector to Map. //Already defines Variables with same name will be replaced for(IVar var: variables){ String name = var.getName(); String value = var.getValue(variableReplacer); variableMap.put(name, value); } } public void clear() { variableMap.clear(); } public String getVar( String name ) { return variableMap.get(name); } }
3e034e4515b0f5d95a8ecd46f6f6082fa9caebd0
2,070
java
Java
Product/src/main/java/com/newhopemail/product/controller/ProductAttrValueController.java
Mrzaotian/NewHopeMail
a0c92a3530c4bf167b9058a4d11ae32af13a2221
[ "Apache-2.0" ]
null
null
null
Product/src/main/java/com/newhopemail/product/controller/ProductAttrValueController.java
Mrzaotian/NewHopeMail
a0c92a3530c4bf167b9058a4d11ae32af13a2221
[ "Apache-2.0" ]
null
null
null
Product/src/main/java/com/newhopemail/product/controller/ProductAttrValueController.java
Mrzaotian/NewHopeMail
a0c92a3530c4bf167b9058a4d11ae32af13a2221
[ "Apache-2.0" ]
null
null
null
24.678571
80
0.711047
1,370
package com.newhopemail.product.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.newhopemail.product.entity.ProductAttrValueEntity; import com.newhopemail.product.service.ProductAttrValueService; import com.newhopemail.common.utils.PageUtils; import com.newhopemail.common.utils.R; /** * spu属性值 * * @author zao * @email [email protected] * @date 2021-04-26 01:58:32 */ @RestController @RequestMapping("product/productattrvalue") public class ProductAttrValueController { @Autowired private ProductAttrValueService productAttrValueService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = productAttrValueService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ ProductAttrValueEntity productAttrValue = productAttrValueService.getById(id); return R.ok().put("productAttrValue", productAttrValue); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody ProductAttrValueEntity productAttrValue){ productAttrValueService.save(productAttrValue); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody ProductAttrValueEntity productAttrValue){ productAttrValueService.updateById(productAttrValue); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ productAttrValueService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
3e034e823dc77495ffa89943c75d65ee84526b19
1,711
java
Java
rolemanagerservice/src/main/java/com/niek125/rolemanagerservice/controllers/RoleController.java
Data-Editor/DataEditorRoleManager
388eb524e64fd451ada20677bf6f9e2336335a17
[ "MIT" ]
null
null
null
rolemanagerservice/src/main/java/com/niek125/rolemanagerservice/controllers/RoleController.java
Data-Editor/DataEditorRoleManager
388eb524e64fd451ada20677bf6f9e2336335a17
[ "MIT" ]
null
null
null
rolemanagerservice/src/main/java/com/niek125/rolemanagerservice/controllers/RoleController.java
Data-Editor/DataEditorRoleManager
388eb524e64fd451ada20677bf6f9e2336335a17
[ "MIT" ]
null
null
null
39.790698
98
0.766803
1,371
package com.niek125.rolemanagerservice.controllers; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.niek125.rolemanagerservice.models.Role; import com.niek125.rolemanagerservice.repository.RoleRepo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/role") public class RoleController { private final Logger logger = LoggerFactory.getLogger(RoleController.class); private final RoleRepo roleRepo; private final ObjectMapper mapper; @Autowired public RoleController(RoleRepo roleRepo, ObjectMapper mapper) { this.roleRepo = roleRepo; this.mapper = mapper; } @RequestMapping(value = "/getroles/{userid}", method = RequestMethod.GET) public String getRoles(@PathVariable("userid") String userid) throws JsonProcessingException { logger.info("getting roles for: " + userid); final List<Role> roles = roleRepo.findRolesByUserid(userid); logger.info("constructing json"); final String rls = mapper.writeValueAsString(roles); final DocumentContext doc = JsonPath.parse(rls).delete("$..userid").delete("$..roleid"); logger.info("returning json"); return doc.jsonString(); } }
3e034f5d3fd1dd559cc3dc4dda3165bab1c0bcc1
9,969
java
Java
entity-view/api/src/main/java/com/blazebit/persistence/view/EntityViewSetting.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
1
2019-04-22T08:48:39.000Z
2019-04-22T08:48:39.000Z
entity-view/api/src/main/java/com/blazebit/persistence/view/EntityViewSetting.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
null
null
null
entity-view/api/src/main/java/com/blazebit/persistence/view/EntityViewSetting.java
cybernetics/blaze-persistence
2e4270829aaddda5fa2ca2a4a15d89dd549bf8cf
[ "Apache-2.0" ]
null
null
null
33.79322
133
0.675695
1,372
/* * Copyright 2014 Blazebit. * * 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.blazebit.persistence.view; import com.blazebit.persistence.CriteriaBuilder; import com.blazebit.persistence.PaginatedCriteriaBuilder; import com.blazebit.persistence.QueryBuilder; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * A {@linkplain EntityViewSetting} is a set of filters and sorters that can be * applied to a {@link CriteriaBuilder}. Filters and sorters are added for * entity view attribute names. It also supports pagination and optional * parameters. Optional parameters are only set on a criteria builder if they * are needed but not satisfied. * * @param <T> The type of the entity view * @param <Q> {@linkplain PaginatedCriteriaBuilder} if paginated, {@linkplain CriteriaBuilder} otherwise * @author Christian Beikov * @since 1.0 */ public final class EntityViewSetting<T, Q extends QueryBuilder<T, Q>> { private final Class<T> entityViewClass; private final int firstResult; private final int maxResults; private final boolean paginated; private final Set<String> viewNamedFilters = new LinkedHashSet<String>(); private final Set<String> attributeNamedFilters = new LinkedHashSet<String>(); private final Map<String, Sorter> attributeSorters = new LinkedHashMap<String, Sorter>(); private final Map<String, Object> attributeFilters = new LinkedHashMap<String, Object>(); private final Map<String, Object> optionalParameters = new HashMap<String, Object>(); private EntityViewSetting(Class<T> entityViewClass, int firstRow, int maxRows, boolean paginate) { this.entityViewClass = entityViewClass; this.firstResult = firstRow; this.maxResults = maxRows; this.paginated = paginate; } /** * Creates a new {@linkplain EntityViewSetting} that can be applied on * criteria builders. * * @param entityViewClass The entity view class that should be used for the object builder * @param <T> The type of the entity view * @return A new entity view setting */ public static <T> EntityViewSetting<T, CriteriaBuilder<T>> create(Class<T> entityViewClass) { return new EntityViewSetting<T, CriteriaBuilder<T>>(entityViewClass, 0, Integer.MAX_VALUE, false); } /** * Creates a new {@linkplain EntityViewSetting} that can be applied on * criteria builders. * * @param entityViewClass The entity view class that should be used for the object builder * @param firstRow The position of the first result to retrieve, numbered from 0 * @param maxRows The maximum number of results to retrieve * @param <T> The type of the entity view * @return A new entity view setting */ public static <T> EntityViewSetting<T, PaginatedCriteriaBuilder<T>> create(Class<T> entityViewClass, int firstRow, int maxRows) { return new EntityViewSetting<T, PaginatedCriteriaBuilder<T>>(entityViewClass, firstRow, maxRows, true); } /** * Returns the entity view class. * * @return The entity view class */ public Class<T> getEntityViewClass() { return entityViewClass; } /** * The first result that the criteria builder should return. Returns 0 if no * pagination will be applied. * * @see QueryBuilder#page(int, int) * @return The first result */ public int getFirstResult() { return firstResult; } /** * The maximum number of results that the criteria builder should return. * Returns {@linkplain java.lang.Integer#MAX_VALUE} if no pagination will be * applied. * * @see QueryBuilder#page(int, int) * @return The maximum number of results */ public int getMaxResults() { return maxResults; } /** * Returns true if this entiy view setting applies pagination, false otherwise. * * @return True if this entiy view setting applies pagination, false otherwise */ public boolean isPaginated() { return paginated; } /** * Adds the given attribute sorters to the attribute sorters of this * setting. Note that the attribute sorter order is retained. * * @param attributeSorters The attribute sorters to add */ public void addAttributeSorters(Map<String, Sorter> attributeSorters) { this.attributeSorters.putAll(attributeSorters); } /** * Adds the given attribute sorter to the attribute sorters of this setting. * Note that the attribute sorter order is retained. * * @param attributeName The name of the attribute sorter * @param sorter The sorter for the attribute sorter */ public void addAttributeSorter(String attributeName, Sorter sorter) { this.attributeSorters.put(attributeName, sorter); } /** * Returns true if sorters have been added, otherwise false. * * @return true if sorters have been added, otherwise false */ public boolean hasAttributeSorters() { return !attributeSorters.isEmpty(); } /** * Returns a copy of the attribute sorters that have been added. * * @return The attribute sorters */ public Map<String, Sorter> getAttributeSorters() { return attributeSorters; } /** * Adds the given attribute filters to the attribute filters of this * setting. * * @param attributeFilters The attribute filters to add */ public void addAttributeFilters(Map<String, String> attributeFilters) { this.attributeFilters.putAll(attributeFilters); } /** * Adds the given attribute filter to the attribute filters of this setting. * * @param attributeName The name of the attribute filter * @param filterValue The filter value for the attribute filter */ public void addAttributeFilter(String attributeName, String filterValue) { this.attributeFilters.put(attributeName, filterValue); } /** * Returns true if filters have been added, otherwise false. * * @return true if filters have been added, otherwise false */ public boolean hasAttributeFilters() { return !attributeFilters.isEmpty() ; } /** * Returns a copy of the attribute filters that have been added. * * @return The attribute filters */ public Map<String, Object> getAttributeFilters() { return attributeFilters; } /** * Enables and adds the attribute filter with the given name in this setting. * * @param filterName The name of the attribute filter */ public void addAttributeNamedFilter(String filterName) { this.attributeNamedFilters.add(filterName); } /** * Returns true if named filters for attributes have been added, otherwise false. * * @return true if named filters for attributes have been added, otherwise false */ public boolean hasAttributeNamedFilters() { return !attributeNamedFilters.isEmpty(); } /** * Returns a copy of the named filters for attributes that have been added. * * @return The named filters for attributes */ public Set<String> getAttributeNamedFilters() { return attributeNamedFilters; } /** * Enables and adds the view filter with the given name in this setting. * * @param filterName The name of the view filter */ public void addViewFilter(String filterName) { this.viewNamedFilters.add(filterName); } /** * Returns true if named filters for the view have been added, otherwise false. * * @return true if named filters for the view have been added, otherwise false */ public boolean hasViewFilters() { return !viewNamedFilters.isEmpty(); } /** * Returns a copy of the named filters for the view that have been added. * * @return The named filters for the view */ public Set<String> getViewFilters() { return viewNamedFilters; } /** * Adds the given optional parameters to the optional parameters of this * setting. * * @param optionalParameters The optional parameters to add */ public void addOptionalParameters(Map<String, Object> optionalParameters) { this.optionalParameters.putAll(optionalParameters); } /** * Adds the given optional parameter to the optional parameters of this * setting. * * @param parameterName The name of the optional parameter * @param value The value of the optional parameter */ public void addOptionalParameter(String parameterName, Object value) { this.optionalParameters.put(parameterName, value); } /** * Returns true if optional parameters have been added, otherwise false. * * @return true if optional parameters have been added, otherwise false */ public boolean hasOptionalParameters() { return !optionalParameters.isEmpty(); } /** * Returns a copy of the optional parameters that have been added. * * @return The optional parameters */ public Map<String, Object> getOptionalParameters() { return optionalParameters; } }
3e03501efa146e9d6b8e3a3125ff195e49b131ab
3,034
java
Java
A Star/src/jps/JPS_GUI.java
egordon9dev/A-pathfinder-test
4148b71ca40addbf159728429b71f036a7e8e6c8
[ "MIT" ]
1
2020-12-20T16:43:00.000Z
2020-12-20T16:43:00.000Z
A Star/src/jps/JPS_GUI.java
egordon9dev/Jump-Point-Search
4148b71ca40addbf159728429b71f036a7e8e6c8
[ "MIT" ]
null
null
null
A Star/src/jps/JPS_GUI.java
egordon9dev/Jump-Point-Search
4148b71ca40addbf159728429b71f036a7e8e6c8
[ "MIT" ]
null
null
null
32.623656
96
0.539222
1,374
package jps; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; class MyPanel extends JPanel implements ActionListener { private int x, y, pos; private JPS jps; private int gridWidth, gridHeight, nodeSpace; public ArrayList<Node> path; public MyPanel(LayoutManager layout, JPS jps) { super(layout); this.jps = jps; gridWidth = jps.getGridWidth(); gridHeight = jps.getGridHeight(); nodeSpace = jps.getNodeSpace(); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); Timer timer = new Timer(20, this); timer.start(); x = 0; y = 0; pos = -1; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); final int k = 25; g.setColor(new Color(160, 160, 160)); g.fillRect(k, k, gridWidth * nodeSpace, gridHeight * nodeSpace); g.setColor(new Color(100, 100, 100, 150)); Node nodes[][] = jps.getNodes(); g.setColor(Color.WHITE); for(int y = 0; y < nodes.length; y++) { for(int x = 0; x < nodes[0].length; x++) { Node n = nodes[y][x]; if(!n.walkable) { g.fillRect((int)n.x + k, (int)n.y + k, nodeSpace, nodeSpace); } } } if(path != null) { g.setColor(Color.BLACK); for(int i = 0; i < path.size(); i++) { Node n = path.get(i); g.fillRect((int) n.x + k, (int) n.y + k, nodeSpace, nodeSpace); } } g.setColor(Color.BLACK); g.setFont(new Font("TimesRoman", Font.BOLD, 30)); g.drawString(Long.toString(jps.getDt()), 200, 30); Toolkit.getDefaultToolkit().sync(); } @Override public void actionPerformed(ActionEvent e) { repaint(); } } public class JPS_GUI { private static MyPanel panel; public static void setupGUI(ArrayList<Node> path, JPS jps) { panel = new MyPanel(new FlowLayout(), jps); panel.path = path; JFrame frame = new JFrame(); frame.add(panel); frame.setSize(856, 878);// 56, 78 frame.setResizable(false); frame.setTitle("Jump Point Search (improved A*) Pathfinder"); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.requestFocus(); EventQueue.invokeLater(new Runnable() { @Override public void run() { frame.setVisible(true); } }); } public static void main(String args[]) { JPS jps = new JPS(200, 200, 4); ArrayList<Node> path = jps.findPath(0, 0, jps.getGridWidth()-1, jps.getGridHeight()-1); setupGUI(path, jps); } }
3e03505681d813e96771024af3459586a3c3fc2e
3,288
java
Java
src/main/java/amerifrance/guideapi/RegistrarGuideAPI.java
josephcsible/Guide-API
fbcff111245e6f29522fa88906d7aedebe27217e
[ "MIT" ]
32
2015-02-12T04:48:31.000Z
2020-11-23T03:58:52.000Z
src/main/java/amerifrance/guideapi/RegistrarGuideAPI.java
josephcsible/Guide-API
fbcff111245e6f29522fa88906d7aedebe27217e
[ "MIT" ]
119
2015-04-08T09:26:53.000Z
2020-09-09T22:47:43.000Z
src/main/java/amerifrance/guideapi/RegistrarGuideAPI.java
josephcsible/Guide-API
fbcff111245e6f29522fa88906d7aedebe27217e
[ "MIT" ]
40
2015-04-16T19:01:23.000Z
2022-02-05T15:25:27.000Z
47.652174
147
0.733577
1,375
package amerifrance.guideapi; import amerifrance.guideapi.api.GuideAPI; import amerifrance.guideapi.api.IGuideBook; import amerifrance.guideapi.api.IPage; import amerifrance.guideapi.api.impl.Book; import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract; import amerifrance.guideapi.api.impl.abstraction.EntryAbstract; import amerifrance.guideapi.item.ItemGuideBook; import amerifrance.guideapi.page.PageJsonRecipe; import amerifrance.guideapi.util.APISetter; import amerifrance.guideapi.util.AnnotationHandler; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.biome.Biome; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import org.apache.commons.lang3.tuple.Pair; @Mod.EventBusSubscriber public class RegistrarGuideAPI { /* * Why Register<Biome>? Well, that's an easy one. We need to register our items during the registry event phase so they * can be properly used during init and beyond. However, we cannot handle it during Register<Item> because any mods * using @ObjectHolder will not have their Item fields populated. Thus, we must use an event that fires *after* * Item object holders are populated, but *before* the recipe registry. Since the events are fired in alphabetical order, * we just pick one that starts with a letter before "r". */ @SubscribeEvent public static void registerItemsInADifferentRegistryEventBecauseLoadOrderingAndObjectHoldersAreImportant(RegistryEvent.Register<Biome> event) { AnnotationHandler.gatherBooks(GuideMod.dataTable); for (Book book : GuideAPI.getBooks().values()) { Item guideBook = new ItemGuideBook(book); guideBook.setRegistryName(book.getRegistryName().toString().replace(":", "-")); ForgeRegistries.ITEMS.register(guideBook); APISetter.setBookForStack(book, new ItemStack(guideBook)); } } @SubscribeEvent(priority = EventPriority.LOWEST) public static void registerRecipes(RegistryEvent.Register<IRecipe> event) { for (Pair<Book, IGuideBook> guide : AnnotationHandler.BOOK_CLASSES) { IRecipe recipe = guide.getRight().getRecipe(GuideAPI.getStackFromBook(guide.getLeft())); if (recipe != null) event.getRegistry().register(recipe); } for (Book book : GuideAPI.getBooks().values()) for (CategoryAbstract cat : book.getCategoryList()) for (EntryAbstract entry : cat.entries.values()) for (IPage page : entry.pageList) if (page instanceof PageJsonRecipe) ((PageJsonRecipe) page).init(); } @SubscribeEvent public static void registerModels(ModelRegistryEvent event) { for (Pair<Book, IGuideBook> guide : AnnotationHandler.BOOK_CLASSES) guide.getRight().handleModel(GuideAPI.getStackFromBook(guide.getLeft())); } }
3e03508bdae228f8fe2b8a8de9de454cb2bf3b47
3,983
java
Java
server-spi/src/main/java/org/keycloak/models/UserCredentialModel.java
imransashraf/keycloak
d138b19adb51418f81d2f60b04297eeefef7612a
[ "Apache-2.0" ]
1
2020-08-17T20:44:14.000Z
2020-08-17T20:44:14.000Z
server-spi/src/main/java/org/keycloak/models/UserCredentialModel.java
OneIdentity/keycloak
2f4c2c20f9dbb5aa15781b9ca770182e12336d11
[ "Apache-2.0" ]
1
2021-02-23T14:13:32.000Z
2021-02-23T15:30:40.000Z
server-spi/src/main/java/org/keycloak/models/UserCredentialModel.java
OneIdentity/keycloak
2f4c2c20f9dbb5aa15781b9ca770182e12336d11
[ "Apache-2.0" ]
3
2016-03-24T18:44:57.000Z
2020-11-12T10:25:31.000Z
29.10219
75
0.670429
1,376
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.models; import java.util.UUID; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class UserCredentialModel { public static final String PASSWORD = "password"; public static final String PASSWORD_HISTORY = "password-history"; public static final String PASSWORD_TOKEN = "password-token"; // Secret is same as password but it is not hashed public static final String SECRET = "secret"; public static final String TOTP = "totp"; public static final String HOTP = "hotp"; public static final String CLIENT_CERT = "cert"; public static final String KERBEROS = "kerberos"; protected String type; protected String value; protected String device; protected String algorithm; public UserCredentialModel() { } public static UserCredentialModel password(String password) { UserCredentialModel model = new UserCredentialModel(); model.setType(PASSWORD); model.setValue(password); return model; } public static UserCredentialModel passwordToken(String passwordToken) { UserCredentialModel model = new UserCredentialModel(); model.setType(PASSWORD_TOKEN); model.setValue(passwordToken); return model; } public static UserCredentialModel secret(String password) { UserCredentialModel model = new UserCredentialModel(); model.setType(SECRET); model.setValue(password); return model; } public static UserCredentialModel otp(String type, String key) { if (type.equals(HOTP)) return hotp(key); if (type.equals(TOTP)) return totp(key); throw new RuntimeException("Unknown OTP type"); } public static UserCredentialModel totp(String key) { UserCredentialModel model = new UserCredentialModel(); model.setType(TOTP); model.setValue(key); return model; } public static UserCredentialModel hotp(String key) { UserCredentialModel model = new UserCredentialModel(); model.setType(HOTP); model.setValue(key); return model; } public static UserCredentialModel kerberos(String token) { UserCredentialModel model = new UserCredentialModel(); model.setType(KERBEROS); model.setValue(token); return model; } public static UserCredentialModel generateSecret() { UserCredentialModel model = new UserCredentialModel(); model.setType(SECRET); model.setValue(UUID.randomUUID().toString()); return model; } public static boolean isOtp(String type) { return TOTP.equals(type) || HOTP.equals(type); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } }
3e03510948bcc26c45ffe9e0631221226b016143
128
java
Java
src/main/java/ch05initialization/D10_Apricot.java
deguo/tij4
bc5e1a82516dd7ce89163c33e98a9c9f47d6bd7c
[ "Apache-2.0" ]
null
null
null
src/main/java/ch05initialization/D10_Apricot.java
deguo/tij4
bc5e1a82516dd7ce89163c33e98a9c9f47d6bd7c
[ "Apache-2.0" ]
null
null
null
src/main/java/ch05initialization/D10_Apricot.java
deguo/tij4
bc5e1a82516dd7ce89163c33e98a9c9f47d6bd7c
[ "Apache-2.0" ]
null
null
null
9.846154
27
0.515625
1,377
package ch05initialization; public class D10_Apricot { void pick() { /* ... */ } void pit() { pick(); /* ... */ } }
3e03516a4f98f297ce91658b3d64a0cf0674c950
1,131
java
Java
dawdler/dawdler-client/src/main/java/com/anywide/dawdler/client/filter/FilterChain.java
srchen1987/dawdler-series
40f5ac4cad0b1bbe19888568642450e859b1bd45
[ "Apache-2.0" ]
62
2018-11-15T07:03:15.000Z
2022-03-27T08:56:32.000Z
dawdler/dawdler-client/src/main/java/com/anywide/dawdler/client/filter/FilterChain.java
srchen1987/dawdler-series
40f5ac4cad0b1bbe19888568642450e859b1bd45
[ "Apache-2.0" ]
13
2020-06-09T13:57:57.000Z
2022-03-01T03:16:34.000Z
dawdler/dawdler-client/src/main/java/com/anywide/dawdler/client/filter/FilterChain.java
srchen1987/dawdler-series
40f5ac4cad0b1bbe19888568642450e859b1bd45
[ "Apache-2.0" ]
12
2018-11-15T07:03:18.000Z
2021-12-04T01:56:35.000Z
35.40625
75
0.755516
1,378
/* * 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.anywide.dawdler.client.filter; import com.anywide.dawdler.core.bean.RequestBean; /** * @author jackson.song * @version V1.0 * @Title FilterChain.java * @Description 过滤器链 * @date 2015年4月06日 * @email [email protected] */ public interface FilterChain { Object doFilter(RequestBean request) throws Exception; }
3e0351df0d497465bd3f40448cb25d04199d8adf
6,279
java
Java
src/main/java/com/chimericdream/minekea/block/containers/barrels/GenericBarrel.java
chimericdream/minekea-fabric
2cd8d74448defff67ec2728db2760977d643fd76
[ "MIT" ]
null
null
null
src/main/java/com/chimericdream/minekea/block/containers/barrels/GenericBarrel.java
chimericdream/minekea-fabric
2cd8d74448defff67ec2728db2760977d643fd76
[ "MIT" ]
null
null
null
src/main/java/com/chimericdream/minekea/block/containers/barrels/GenericBarrel.java
chimericdream/minekea-fabric
2cd8d74448defff67ec2728db2760977d643fd76
[ "MIT" ]
null
null
null
44.531915
154
0.625737
1,379
package com.chimericdream.minekea.block.containers.barrels; import com.chimericdream.minekea.ModInfo; import com.chimericdream.minekea.resource.MinekeaResourcePack; import com.chimericdream.minekea.resource.Texture; import net.devtech.arrp.json.blockstate.JBlockModel; import net.devtech.arrp.json.blockstate.JState; import net.devtech.arrp.json.loot.JCondition; import net.devtech.arrp.json.loot.JEntry; import net.devtech.arrp.json.loot.JLootTable; import net.devtech.arrp.json.models.JModel; import net.devtech.arrp.json.models.JTextures; import net.devtech.arrp.json.recipe.*; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.block.BarrelBlock; import net.minecraft.block.Blocks; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import java.util.Map; public class GenericBarrel extends BarrelBlock { private final String modId; private final String woodType; private final Identifier BLOCK_ID; private final Map<String, Identifier> materials; public GenericBarrel(String woodType, Map<String, Identifier> materials) { this(woodType, ModInfo.MOD_ID, materials); } public GenericBarrel(String woodType, String modId, Map<String, Identifier> materials) { super(FabricBlockSettings.copyOf(Blocks.BARREL).sounds(BlockSoundGroup.WOOD)); validateMaterials(materials); this.modId = modId; this.woodType = woodType; this.materials = materials; BLOCK_ID = new Identifier(ModInfo.MOD_ID, String.format("barrels/%s%s_barrel", ModInfo.getModPrefix(modId), woodType)); } protected void validateMaterials(Map<String, Identifier> materials) { String[] keys = new String[]{"planks", "slab", "log"}; for (String key : keys) { if (!materials.containsKey(key)) { throw new IllegalArgumentException(String.format("The materials must contain a '%s' key", key)); } } } public void register() { Registry.register(Registry.BLOCK, BLOCK_ID, this); Registry.register(Registry.ITEM, BLOCK_ID, new BlockItem(this, new Item.Settings().group(ItemGroup.DECORATIONS))); setupResources(); } protected void setupResources() { String PLANK_MATERIAL = materials.get("planks").toString(); String SLAB_MATERIAL = materials.get("slab").toString(); String LOG_MATERIAL = materials.get("log").toString(); Identifier MODEL_ID = new Identifier(ModInfo.MOD_ID, String.format("block/barrels/%s%s_barrel", ModInfo.getModPrefix(modId), woodType)); Identifier ITEM_MODEL_ID = new Identifier(ModInfo.MOD_ID, String.format("item/barrels/%s%s_barrel", ModInfo.getModPrefix(modId), woodType)); Identifier OPEN_MODEL_ID = new Identifier(ModInfo.MOD_ID, String.format("block/barrels/%s%s_barrel_open", ModInfo.getModPrefix(modId), woodType)); MinekeaResourcePack.RESOURCE_PACK.addRecipe( BLOCK_ID, JRecipe.shaped( JPattern.pattern("PSP", "P P", "PSP"), JKeys.keys() .key("P", JIngredient.ingredient().item(PLANK_MATERIAL)) .key("S", JIngredient.ingredient().item(SLAB_MATERIAL)), JResult.result(BLOCK_ID.toString()) ) ); MinekeaResourcePack.RESOURCE_PACK.addLootTable( new Identifier(BLOCK_ID.getNamespace(), "blocks/" + BLOCK_ID.getPath()), JLootTable.loot("minecraft:block") .pool( JLootTable.pool() .rolls(1) .entry( new JEntry() .type("minecraft:item") .name(BLOCK_ID.toString()) ) .condition(new JCondition().condition("minecraft:survives_explosion")) ) ); MinekeaResourcePack.RESOURCE_PACK.addModel( JModel.model("minekea:block/barrel_variant") .textures( new JTextures() .var("face", Texture.getBlockTextureID(LOG_MATERIAL).toString()) .var("sides", Texture.getBlockTextureID(PLANK_MATERIAL).toString()) ), MODEL_ID ); MinekeaResourcePack.RESOURCE_PACK.addModel( JModel.model("minekea:block/barrel_variant_open") .textures( new JTextures() .var("face", Texture.getBlockTextureID(LOG_MATERIAL).toString()) .var("sides", Texture.getBlockTextureID(PLANK_MATERIAL).toString()) ), OPEN_MODEL_ID ); MinekeaResourcePack.RESOURCE_PACK.addModel(JModel.model(MODEL_ID.toString()), ITEM_MODEL_ID); MinekeaResourcePack.RESOURCE_PACK.addBlockState( JState.state( JState.variant() .put("facing=down,open=false", new JBlockModel(MODEL_ID).x(180)) .put("facing=east,open=false", new JBlockModel(MODEL_ID).x(90).y(90)) .put("facing=north,open=false", new JBlockModel(MODEL_ID).x(90)) .put("facing=south,open=false", new JBlockModel(MODEL_ID).x(90).y(180)) .put("facing=up,open=false", new JBlockModel(MODEL_ID)) .put("facing=west,open=false", new JBlockModel(MODEL_ID).x(90).y(270)) .put("facing=down,open=true", new JBlockModel(OPEN_MODEL_ID).x(180)) .put("facing=east,open=true", new JBlockModel(OPEN_MODEL_ID).x(90).y(90)) .put("facing=north,open=true", new JBlockModel(OPEN_MODEL_ID).x(90)) .put("facing=south,open=true", new JBlockModel(OPEN_MODEL_ID).x(90).y(180)) .put("facing=up,open=true", new JBlockModel(OPEN_MODEL_ID)) .put("facing=west,open=true", new JBlockModel(OPEN_MODEL_ID).x(90).y(270)) ), BLOCK_ID ); } }
3e03537bd52e3766f8247a146bf8903b7b23fe25
595
java
Java
DataStructures-Algorithms/Udemy-Java-Masterclass/CodingExercises/CodingExercise_26_DiagonalStar.java
shoaibur/SWE
1e114a2750f2df5d6c50b48c8e439224894d65da
[ "MIT" ]
1
2020-11-14T18:28:13.000Z
2020-11-14T18:28:13.000Z
DataStructures-Algorithms/Udemy-Java-Masterclass/CodingExercises/CodingExercise_26_DiagonalStar.java
shoaibur/SWE
1e114a2750f2df5d6c50b48c8e439224894d65da
[ "MIT" ]
null
null
null
DataStructures-Algorithms/Udemy-Java-Masterclass/CodingExercises/CodingExercise_26_DiagonalStar.java
shoaibur/SWE
1e114a2750f2df5d6c50b48c8e439224894d65da
[ "MIT" ]
null
null
null
28.333333
66
0.378151
1,380
public class DiagonalStar { public static void printSquareStar(int number) { if (number < 5) { System.out.println("Invalid Value"); return; } for (int i = 0; i < number; i++) { for (int j = 0; j < number; j++) { if (i == 0 || j == 0 || i == j || i == number-1 || j == number-1 || i+j == number-1) System.out.print("*"); else System.out.print(" "); } System.out.println(); } return; } }
3e0354762a036d8156c0fcfa87ae6ae507784395
5,293
java
Java
CRUDExample/app/src/main/java/app/rhuangal/com/crudexample/storage/OperationsDatabase.java
rhuangal/database-android-example
1de99c7a07f4ff7a9a81889f0960b3675d56b122
[ "MIT" ]
null
null
null
CRUDExample/app/src/main/java/app/rhuangal/com/crudexample/storage/OperationsDatabase.java
rhuangal/database-android-example
1de99c7a07f4ff7a9a81889f0960b3675d56b122
[ "MIT" ]
null
null
null
CRUDExample/app/src/main/java/app/rhuangal/com/crudexample/storage/OperationsDatabase.java
rhuangal/database-android-example
1de99c7a07f4ff7a9a81889f0960b3675d56b122
[ "MIT" ]
null
null
null
31.505952
98
0.641224
1,381
package app.rhuangal.com.crudexample.storage; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; import app.rhuangal.com.crudexample.model.Persona; /** * Created by rober on 06-Oct-17. */ public class OperationsDatabase { private static final String TAG = "OperationsDatabase"; private DatabaseHelper openHelper; SQLiteDatabase database; public OperationsDatabase(SQLiteOpenHelper _helper) { super(); openHelper =(DatabaseHelper)_helper; } public void open(){ Log.i(TAG,"Database Opened"); database = openHelper.getWritableDatabase(); } public void close(){ Log.i(TAG, "Database Closed"); openHelper.close(); } /* * CRUD ==> Create, Read, Update y Delete */ /*public void createPersona(Persona noteEntity) { SQLiteDatabase db = openHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseHelper.COL_NOMBRE, noteEntity.getNombre()); values.put(DatabaseHelper.COL_TELEFONO, noteEntity.getTelefono()); values.put(DatabaseHelper.COL_CORREO, noteEntity.getCorreo()); db.insert(DatabaseHelper.TABLE_PERSONA, null, values); db.close(); }*/ public Persona createPersona(Persona noteEntity){ this.open(); ContentValues values = new ContentValues(); values.put(DatabaseHelper.COL_NOMBRE, noteEntity.getNombre()); values.put(DatabaseHelper.COL_TELEFONO, noteEntity.getTelefono()); values.put(DatabaseHelper.COL_CORREO, noteEntity.getCorreo()); long insertid = database.insert(DatabaseHelper.TABLE_PERSONA,null,values); noteEntity.setId(insertid); this.close(); return noteEntity; } public Persona readPersona(int id) { SQLiteDatabase db = openHelper.getReadableDatabase(); //modo lectura Cursor cursor = db.query(DatabaseHelper.TABLE_PERSONA, new String[]{DatabaseHelper.COL_ID, DatabaseHelper.COL_NOMBRE, DatabaseHelper.COL_TELEFONO, DatabaseHelper.COL_CORREO}, DatabaseHelper.COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null); if(cursor!=null) { cursor.moveToFirst(); } Persona persona= cursorToPersona(cursor); return persona; } public int updatePersona(Persona noteEntity) { SQLiteDatabase db = openHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseHelper.COL_NOMBRE, noteEntity.getNombre()); values.put(DatabaseHelper.COL_TELEFONO, noteEntity.getTelefono()); values.put(DatabaseHelper.COL_CORREO, noteEntity.getCorreo()); int row =db.update(DatabaseHelper.TABLE_PERSONA, values, DatabaseHelper.COL_ID+"=?", new String[]{String.valueOf(noteEntity.getId())}); db.close(); return row; } public int deletePersona(Persona noteEntity) { SQLiteDatabase db = openHelper.getWritableDatabase(); int row= db.delete(DatabaseHelper.TABLE_PERSONA, DatabaseHelper.COL_ID+"=?", new String[]{String.valueOf(noteEntity.getId())}); db.close(); return row; } /* * Operaciones extras */ public List<Persona> getAllPersona() { List<Persona> lista = new ArrayList<Persona>(); String sql= "SELECT * FROM " + DatabaseHelper.TABLE_PERSONA; SQLiteDatabase db = openHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql, null); if(cursor.moveToFirst()) { do{ lista.add(cursorToPersona(cursor)); }while (cursor.moveToNext()); } return lista; } public List<Persona> getAllPersona2() { String sql= "SELECT * FROM " + DatabaseHelper.TABLE_PERSONA; Cursor cursor = database.rawQuery(sql, null); List<Persona> personas = new ArrayList<>(); if(cursor.getCount() > 0){ while(cursor.moveToNext()){ personas.add(cursorToPersona(cursor)); } } return personas; } public int getPersonaCount() { String sql= "SELECT * FROM "+ DatabaseHelper.TABLE_PERSONA; SQLiteDatabase db = openHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql, null); cursor.close(); return cursor.getCount(); } /* * Metodos de ayuda */ private Persona cursorToPersona(Cursor cursor) { Persona persona =new Persona(); persona.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_ID))); persona.setNombre(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_NOMBRE))); persona.setTelefono(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_TELEFONO))); persona.setCorreo(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_CORREO))); return persona; } }
3e0354f37983b2c995dc708572db69a590add2e3
2,780
java
Java
src/main/java/org/webharvest/runtime/scripting/GroovyScriptEngine.java
wso2/wso2-webharvest
6b947ea21c37f9183dc7dbd410850abf064095b9
[ "Apache-2.0" ]
null
null
null
src/main/java/org/webharvest/runtime/scripting/GroovyScriptEngine.java
wso2/wso2-webharvest
6b947ea21c37f9183dc7dbd410850abf064095b9
[ "Apache-2.0" ]
null
null
null
src/main/java/org/webharvest/runtime/scripting/GroovyScriptEngine.java
wso2/wso2-webharvest
6b947ea21c37f9183dc7dbd410850abf064095b9
[ "Apache-2.0" ]
1
2022-03-02T11:29:47.000Z
2022-03-02T11:29:47.000Z
35.730769
80
0.700036
1,382
/* Copyright (c) 2006-2007, Vladimir Nikic All rights reserved. Redistribution and use of this software 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. * The name of Web-Harvest may not 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. You can contact Vladimir Nikic by sending e-mail to [email protected]. Please include the word "Web-Harvest" in the subject line. */ package org.webharvest.runtime.scripting; import groovy.lang.Binding; import groovy.lang.GroovyShell; import java.util.Map; /** * Groovy scripting engine. */ public class GroovyScriptEngine extends ScriptEngine { private Binding binding = new Binding(); private GroovyShell shell = new GroovyShell(binding); /** * Constructor - initializes context used in engine. * @param context */ public GroovyScriptEngine(Map context) { super(context); } /** * Sets variable in scripter context. * @param name * @param value */ public void setVariable(String name, Object value) { this.binding.setVariable(name, value); } /** * Evaluates specified expression or code block. * @return value of evaluation or null if there is nothing. */ public Object eval(String expression) { pushAllVariablesFromContextToScriptEngine(); return shell.evaluate(expression); } }
3e03553fee2a766967e02775b163deb33d9b6a36
1,138
java
Java
src/main/java/okky/team/chawchaw/chat/room/ChatRoomUserRepository.java
Chaw-Chaw/ChawChawBack1
a1f353656f1b92e61e852069e5d70649d3449a58
[ "MIT" ]
null
null
null
src/main/java/okky/team/chawchaw/chat/room/ChatRoomUserRepository.java
Chaw-Chaw/ChawChawBack1
a1f353656f1b92e61e852069e5d70649d3449a58
[ "MIT" ]
4
2021-12-05T20:07:17.000Z
2022-01-07T10:07:56.000Z
src/main/java/okky/team/chawchaw/chat/room/ChatRoomUserRepository.java
Chaw-Chaw/ChawChawBack2
a1f353656f1b92e61e852069e5d70649d3449a58
[ "MIT" ]
null
null
null
36.709677
95
0.710018
1,383
package okky.team.chawchaw.chat.room; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface ChatRoomUserRepository extends JpaRepository<ChatRoomUserEntity, Long> { List<ChatRoomUserEntity> findAllByUserId(Long userId); @EntityGraph(attributePaths = {"chatRoom", "user"}) List<ChatRoomUserEntity> findAllByChatRoomId(Long roomId); void deleteByUserId(Long userId); @Query("select ru.chatRoom.id " + "from ChatRoomUserEntity ru " + "where ru.user.id = :userId or ru.user.id = :userId2 " + "group by ru.chatRoom " + "having count(ru.chatRoom) = 2") Long findChatRoomIdByUserIds(@Param("userId") Long userId, @Param("userId2") Long userId2); @Query("select ru.chatRoom " + "from ChatRoomUserEntity ru " + "where ru.user.id = :userId") List<ChatRoomEntity> findChatRoomsByUserId(@Param("userId") Long userId); }
3e03560f89d24ba28b43112f8e868543ce142317
850
java
Java
plugin/ceph/src/main/java/org/zstack/storage/ceph/primary/APIQueryCephPrimaryStoragePoolMsg.java
anlow12/zstack
77ac7189c34a22aba944d3b7b36d5df84f7d4718
[ "Apache-2.0" ]
879
2017-02-16T02:01:44.000Z
2022-03-31T15:44:28.000Z
plugin/ceph/src/main/java/org/zstack/storage/ceph/primary/APIQueryCephPrimaryStoragePoolMsg.java
Abortbeen/zstack
40f195893250b84881798a702f3b2455c83336a1
[ "Apache-2.0" ]
482
2017-02-13T09:57:37.000Z
2022-03-31T07:17:29.000Z
plugin/ceph/src/main/java/org/zstack/storage/ceph/primary/APIQueryCephPrimaryStoragePoolMsg.java
Abortbeen/zstack
40f195893250b84881798a702f3b2455c83336a1
[ "Apache-2.0" ]
306
2017-02-13T08:31:29.000Z
2022-03-14T07:58:46.000Z
30.357143
122
0.76
1,384
package org.zstack.storage.ceph.primary; import org.springframework.http.HttpMethod; import org.zstack.header.query.APIQueryMessage; import org.zstack.header.query.AutoQuery; import org.zstack.header.rest.RestRequest; import java.util.List; import static java.util.Arrays.asList; /** * Created by xing5 on 2017/2/28. */ @RestRequest( path = "/primary-storage/ceph/pools", optionalPaths = {"/primary-storage/ceph/pools/{uuid}"}, method = HttpMethod.GET, responseClass = APIQueryCephPrimaryStoragePoolReply.class ) @AutoQuery(replyClass = APIQueryCephPrimaryStoragePoolReply.class, inventoryClass = CephPrimaryStoragePoolInventory.class) public class APIQueryCephPrimaryStoragePoolMsg extends APIQueryMessage { public static List<String> __example__() { return asList("name=highPerformance"); } }
3e0357994c6761864b9667051098d2bf955abcd8
1,708
java
Java
src/main/java/com/lorepo/icplayer/client/module/addon/param/AddonParamProvider.java
Magdalenaz/icplayer
1cf91a55fd4dc55ae839a9dbef09973917acb383
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lorepo/icplayer/client/module/addon/param/AddonParamProvider.java
Magdalenaz/icplayer
1cf91a55fd4dc55ae839a9dbef09973917acb383
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lorepo/icplayer/client/module/addon/param/AddonParamProvider.java
Magdalenaz/icplayer
1cf91a55fd4dc55ae839a9dbef09973917acb383
[ "Apache-2.0" ]
null
null
null
22.473684
75
0.744145
1,385
package com.lorepo.icplayer.client.module.addon.param; import java.util.ArrayList; import com.google.gwt.xml.client.Element; import com.google.gwt.xml.client.NodeList; import com.lorepo.icf.properties.IProperty; import com.lorepo.icf.properties.IPropertyListener; import com.lorepo.icf.properties.IPropertyProvider; import com.lorepo.icf.utils.XMLUtils; public class AddonParamProvider implements IPropertyProvider{ private ArrayList<IAddonParam> addonParams = new ArrayList<IAddonParam>(); public AddonParamProvider() { } @Override public String getProviderName() { return "Item"; } @Override public void addPropertyListener(IPropertyListener listener) { } @Override public void removePropertyListener(IPropertyListener listener) { } @Override public int getPropertyCount() { return addonParams.size(); } @Override public IProperty getProperty(int index) { return addonParams.get(index).getAsProperty(); } public void load(Element rootElement, String baseUrl) { AddonParamFactory paramFactory = new AddonParamFactory(); NodeList optionNodes = rootElement.getElementsByTagName("property"); for(int i = 0; i < optionNodes.getLength(); i++){ Element element = (Element)optionNodes.item(i); String type = XMLUtils.getAttributeAsString(element, "type"); IAddonParam addonParam = paramFactory.createAddonParam(null, type); addonParam.load(element, baseUrl); addonParams.add(addonParam); } } public String toXML() { String xml; xml ="<item>"; for(IAddonParam property: addonParams){ xml += property.toXML(); } xml +="</item>"; return xml; } public void addParam(IAddonParam param){ addonParams.add(param); } }
3e03580dd0bed1c4fe2d526cf142b65e97951482
2,288
java
Java
src/main/java/DiscUtils/Iscsi/InvalidProtocolException.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
null
null
null
src/main/java/DiscUtils/Iscsi/InvalidProtocolException.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
3
2020-10-02T10:46:22.000Z
2021-11-12T10:49:48.000Z
src/main/java/DiscUtils/Iscsi/InvalidProtocolException.java
umjammer/vavi-nio-file-discutils
21abbae058932eb1c0e71793c309cdfbcdbc7aee
[ "MIT" ]
null
null
null
35.75
92
0.716783
1,386
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // package DiscUtils.Iscsi; /** * Exception thrown when a low-level iSCSI failure is detected. */ public class InvalidProtocolException extends IscsiException { /** * Initializes a new instance of the InvalidProtocolException class. */ public InvalidProtocolException() { } /** * Initializes a new instance of the InvalidProtocolException class. * * @param message The reason for the exception. */ public InvalidProtocolException(String message) { super(message); } /** * Initializes a new instance of the InvalidProtocolException class. * * @param message The reason for the exception. * @param innerException The inner exception. */ public InvalidProtocolException(String message, Exception innerException) { super(message, innerException); } /** * Initializes a new instance of the InvalidProtocolException class. * * @param info The serialization info. * @param context Ther context. */ // protected InvalidProtocolException(SerializationInfo info, StreamingContext context) { // super(info, context); // } }
3e035934ce94ed97a720592263a10eadb361d8f2
6,165
java
Java
core/src/main/java/cucumber/runtime/table/TableDiffer.java
sherl0cks/cucumber-jvm
7744e8257ecfcac1079c2e7aa8b4e3f6a3b48935
[ "MIT" ]
1
2019-02-18T12:02:04.000Z
2019-02-18T12:02:04.000Z
core/src/main/java/cucumber/runtime/table/TableDiffer.java
sherl0cks/cucumber-jvm
7744e8257ecfcac1079c2e7aa8b4e3f6a3b48935
[ "MIT" ]
null
null
null
core/src/main/java/cucumber/runtime/table/TableDiffer.java
sherl0cks/cucumber-jvm
7744e8257ecfcac1079c2e7aa8b4e3f6a3b48935
[ "MIT" ]
1
2020-02-25T19:38:32.000Z
2020-02-25T19:38:32.000Z
41.375839
130
0.638118
1,387
package cucumber.runtime.table; import cucumber.api.DataTable; import cucumber.deps.difflib.Delta; import cucumber.deps.difflib.DiffUtils; import cucumber.deps.difflib.Patch; import gherkin.pickles.PickleCell; import gherkin.pickles.PickleRow; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static cucumber.runtime.table.DataTableDiff.DiffType; import static java.util.AbstractMap.SimpleEntry; public class TableDiffer { private final DataTable from; private final DataTable to; public TableDiffer(DataTable fromTable, DataTable toTable) { checkColumns(fromTable, toTable); this.from = fromTable; this.to = toTable; } private void checkColumns(DataTable a, DataTable b) { if (a.topCells().size() != b.topCells().size() && !b.topCells().isEmpty()) { throw new IllegalArgumentException("Tables must have equal number of columns:\n" + a + "\n" + b); } } public void calculateDiffs() throws TableDiffException { Patch patch = DiffUtils.diff(from.diffableRows(), to.diffableRows()); List<Delta> deltas = patch.getDeltas(); if (!deltas.isEmpty()) { Map<Integer, Delta> deltasByLine = createDeltasByLine(deltas); throw new TableDiffException(from, to, createTableDiff(deltasByLine)); } } public void calculateUnorderedDiffs() throws TableDiffException { boolean isDifferent = false; List<SimpleEntry<PickleRow, DiffType>> diffTableRows = new ArrayList<SimpleEntry<PickleRow, DiffType>>(); List<List<String>> missingRow = new ArrayList<List<String>>(); ArrayList<List<String>> extraRows = new ArrayList<List<String>>(); // 1. add all "to" row in extra table // 2. iterate over "from", when a common row occurs, remove it from extraRows // finally, only extra rows are kept and in same order that in "to". extraRows.addAll(to.raw()); for (PickleRow r : from.getPickleRows()) { if (!to.raw().contains(getCellValues(r))) { missingRow.add(getCellValues(r)); diffTableRows.add( new SimpleEntry<PickleRow, DiffType>(new PickleRow(r.getCells()), DiffType.DELETE)); isDifferent = true; } else { diffTableRows.add( new SimpleEntry<PickleRow, DiffType>(new PickleRow(r.getCells()), DiffType.NONE)); extraRows.remove(getCellValues(r)); } } for (List<String> e : extraRows) { diffTableRows.add( new SimpleEntry<PickleRow, DiffType>(new PickleRow(convertToPickleCells(e)), DiffType.INSERT)); isDifferent = true; } if (isDifferent) { throw new TableDiffException(from, to, DataTableDiff.create(diffTableRows, from.getTableConverter())); } } private List<PickleCell> convertToPickleCells(List<String> e) { List<PickleCell> cells = new ArrayList<PickleCell>(e.size()); for (String value : e) { cells.add(new PickleCell(null, value)); } return cells; } private List<String> getCellValues(PickleRow r) { List<String> values = new ArrayList<String>(r.getCells().size()); for (PickleCell cell : r.getCells()) { values.add(cell.getValue()); } return values; } private Map<Integer, Delta> createDeltasByLine(List<Delta> deltas) { Map<Integer, Delta> deltasByLine = new HashMap<Integer, Delta>(); for (Delta delta : deltas) { deltasByLine.put(delta.getOriginal().getPosition(), delta); } return deltasByLine; } private DataTable createTableDiff(Map<Integer, Delta> deltasByLine) { List<SimpleEntry<PickleRow, DiffType>> diffTableRows = new ArrayList<SimpleEntry<PickleRow, DiffType>>(); List<List<String>> rows = from.raw(); for (int i = 0; i < rows.size(); i++) { Delta delta = deltasByLine.get(i); if (delta == null) { diffTableRows.add(new SimpleEntry<PickleRow, DiffType>(from.getPickleRows().get(i), DiffType.NONE)); } else { addRowsToTableDiff(diffTableRows, delta); // skipping lines involved in a delta if (delta.getType() == Delta.TYPE.CHANGE || delta.getType() == Delta.TYPE.DELETE) { i += delta.getOriginal().getLines().size() - 1; } else { diffTableRows.add(new SimpleEntry<PickleRow, DiffType>(from.getPickleRows().get(i), DiffType.NONE)); } } } // Can have new lines at end Delta remainingDelta = deltasByLine.get(rows.size()); if (remainingDelta != null) { addRowsToTableDiff(diffTableRows, remainingDelta); } return DataTableDiff.create(diffTableRows, from.getTableConverter()); } private void addRowsToTableDiff(List<SimpleEntry<PickleRow, DiffType>> diffTableRows, Delta delta) { markChangedAndDeletedRowsInOriginalAsMissing(diffTableRows, delta); markChangedAndInsertedRowsInRevisedAsNew(diffTableRows, delta); } private void markChangedAndDeletedRowsInOriginalAsMissing(List<SimpleEntry<PickleRow, DiffType>> diffTableRows, Delta delta) { List<DiffableRow> deletedLines = (List<DiffableRow>) delta.getOriginal().getLines(); for (DiffableRow row : deletedLines) { diffTableRows.add(new SimpleEntry<PickleRow, DiffType>(new PickleRow(row.row.getCells()), DiffType.DELETE)); } } private void markChangedAndInsertedRowsInRevisedAsNew(List<SimpleEntry<PickleRow, DiffType>> diffTableRows, Delta delta) { List<DiffableRow> insertedLines = (List<DiffableRow>) delta.getRevised().getLines(); for (DiffableRow row : insertedLines) { diffTableRows.add(new SimpleEntry<PickleRow, DiffType>(new PickleRow(row.row.getCells()), DiffType.INSERT)); } } }
3e035af227bc91e0783a289104a9ebf7a7a49fa7
1,172
java
Java
src/net/raysforge/rest/server/HttpResponse.java
rhulha/GenericRestClient
7510a725b9b0d01ee554860fe79987c5068d5541
[ "MIT" ]
2
2018-06-16T10:16:44.000Z
2019-03-16T05:00:18.000Z
src/net/raysforge/rest/server/HttpResponse.java
rhulha/GenericRestClient
7510a725b9b0d01ee554860fe79987c5068d5541
[ "MIT" ]
null
null
null
src/net/raysforge/rest/server/HttpResponse.java
rhulha/GenericRestClient
7510a725b9b0d01ee554860fe79987c5068d5541
[ "MIT" ]
4
2017-01-31T03:04:18.000Z
2018-09-29T12:44:18.000Z
22.538462
102
0.708191
1,388
package net.raysforge.rest.server; public class HttpResponse { public final boolean error; public final int statusCode; public String message; public byte bytes[]; public boolean isBinary = false; public String contentType = "application/json"; public HttpResponse(boolean error, int statusCode, String message) { this.error = error; this.statusCode = statusCode; this.message = message; } public HttpResponse(int errorCode, String message) { this.error = true; this.statusCode = errorCode; this.message = message; } public HttpResponse(String message) { this.error = false; this.statusCode = 200; this.message = message; } public HttpResponse(byte bytes[], String contentType) { this.error = false; this.statusCode = 200; this.bytes = bytes; this.contentType = contentType; this.isBinary = true; } public HttpResponse(String message, String contentType) { this.error = false; this.statusCode = 200; this.message = message; this.contentType = contentType; } @Override public String toString() { return "HttpResponse [error=" + error + ", statusCode=" + statusCode + ", message=" + message + "]"; } }
3e035b0362feaeafbe29e167c3ec248cfafd7fc1
9,547
java
Java
rocketmq-example/src/main/java/com/alibaba/rocketmq/example/benchmark/TransactionProducer.java
lizhanhui/Alibaba_RocketMQ
44e7c67805af1b1aebbcecfd0a21d153efa7437e
[ "Apache-2.0" ]
30
2015-01-15T04:13:43.000Z
2019-07-08T21:18:22.000Z
rocketmq-example/src/main/java/com/alibaba/rocketmq/example/benchmark/TransactionProducer.java
lizhanhui/Alibaba_RocketMQ
44e7c67805af1b1aebbcecfd0a21d153efa7437e
[ "Apache-2.0" ]
5
2015-06-24T14:22:34.000Z
2017-04-30T03:37:03.000Z
rocketmq-example/src/main/java/com/alibaba/rocketmq/example/benchmark/TransactionProducer.java
lizhanhui/Alibaba_RocketMQ
44e7c67805af1b1aebbcecfd0a21d153efa7437e
[ "Apache-2.0" ]
21
2015-02-26T07:47:17.000Z
2021-02-07T09:35:29.000Z
34.716364
135
0.597884
1,389
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.example.benchmark; import com.alibaba.rocketmq.client.exception.MQClientException; import com.alibaba.rocketmq.client.producer.*; import com.alibaba.rocketmq.common.message.Message; import com.alibaba.rocketmq.common.message.MessageExt; import java.util.LinkedList; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; /** * 性能测试,多线程同步发送事务消息 */ public class TransactionProducer { private static int threadCount; private static int messageSize; private static boolean ischeck; private static boolean ischeckffalse; public static void main(String[] args) throws MQClientException { threadCount = args.length >= 1 ? Integer.parseInt(args[0]) : 32; messageSize = args.length >= 2 ? Integer.parseInt(args[1]) : 1024 * 2; ischeck = args.length >= 3 && Boolean.parseBoolean(args[2]); ischeckffalse = args.length >= 4 && Boolean.parseBoolean(args[3]); final Message msg = buildMessage(messageSize); final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount); final StatsBenchmarkTProducer statsBenchmark = new StatsBenchmarkTProducer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmark.createSnapshot()); while (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000); timer.scheduleAtFixedRate(new TimerTask() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L); final double averageRT = ((end[5] - begin[5]) / (double) (end[3] - begin[3])); System.out.printf( "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d transaction checkCount: %d \n"// , sendTps// , statsBenchmark.getSendMessageMaxRT().get()// , averageRT// , end[2]// , end[4]// , end[6]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); final TransactionCheckListener transactionCheckListener = new TransactionCheckListenerBImpl(ischeckffalse, statsBenchmark); final TransactionMQProducer producer = new TransactionMQProducer("benchmark_transaction_producer"); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.setTransactionCheckListener(transactionCheckListener); producer.setDefaultTopicQueueNums(1000); producer.start(); final TransactionExecutorBImpl tranExecuter = new TransactionExecutorBImpl(ischeck); for (int i = 0; i < threadCount; i++) { sendThreadPool.execute(new Runnable() { @Override public void run() { while (true) { try { // Thread.sleep(1000); final long beginTimestamp = System.currentTimeMillis(); SendResult sendResult = producer.sendMessageInTransaction(msg, tranExecuter, null); if (sendResult != null) { statsBenchmark.getSendRequestSuccessCount().incrementAndGet(); statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet(); } final long currentRT = System.currentTimeMillis() - beginTimestamp; statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT); long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); while (currentRT > prevMaxRT) { boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT, currentRT); if (updated) break; prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); } } catch (MQClientException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); } } } }); } } private static Message buildMessage(final int messageSize) { Message msg = new Message(); msg.setTopic("BenchmarkTest"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < messageSize; i += 10) { sb.append("hello baby"); } msg.setBody(sb.toString().getBytes()); return msg; } } class TransactionExecutorBImpl implements LocalTransactionExecutor { private boolean ischeck; public TransactionExecutorBImpl(boolean ischeck) { this.ischeck = ischeck; } @Override public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg) { if (ischeck) { return LocalTransactionState.UNKNOWN; } return LocalTransactionState.COMMIT_MESSAGE; } } class TransactionCheckListenerBImpl implements TransactionCheckListener { private boolean ischeckffalse; private StatsBenchmarkTProducer statsBenchmarkTProducer; public TransactionCheckListenerBImpl(boolean ischeckffalse, StatsBenchmarkTProducer statsBenchmarkTProducer) { this.ischeckffalse = ischeckffalse; this.statsBenchmarkTProducer = statsBenchmarkTProducer; } @Override public LocalTransactionState checkLocalTransactionState(MessageExt msg) { // System.out.println("server checking TrMsg " + msg.toString()); statsBenchmarkTProducer.getCheckRequestSuccessCount().incrementAndGet(); if (ischeckffalse) { return LocalTransactionState.ROLLBACK_MESSAGE; } return LocalTransactionState.COMMIT_MESSAGE; } } class StatsBenchmarkTProducer { // 1 private final AtomicLong sendRequestSuccessCount = new AtomicLong(0L); // 2 private final AtomicLong sendRequestFailedCount = new AtomicLong(0L); // 3 private final AtomicLong receiveResponseSuccessCount = new AtomicLong(0L); // 4 private final AtomicLong receiveResponseFailedCount = new AtomicLong(0L); // 5 private final AtomicLong sendMessageSuccessTimeTotal = new AtomicLong(0L); // 6 private final AtomicLong sendMessageMaxRT = new AtomicLong(0L); // 7 private final AtomicLong checkRequestSuccessCount = new AtomicLong(0L); public Long[] createSnapshot() { Long[] snap = new Long[] {// System.currentTimeMillis(),// this.sendRequestSuccessCount.get(),// this.sendRequestFailedCount.get(),// this.receiveResponseSuccessCount.get(),// this.receiveResponseFailedCount.get(),// this.sendMessageSuccessTimeTotal.get(), // this.checkRequestSuccessCount.get(), }; return snap; } public AtomicLong getSendRequestSuccessCount() { return sendRequestSuccessCount; } public AtomicLong getSendRequestFailedCount() { return sendRequestFailedCount; } public AtomicLong getReceiveResponseSuccessCount() { return receiveResponseSuccessCount; } public AtomicLong getReceiveResponseFailedCount() { return receiveResponseFailedCount; } public AtomicLong getSendMessageSuccessTimeTotal() { return sendMessageSuccessTimeTotal; } public AtomicLong getSendMessageMaxRT() { return sendMessageMaxRT; } public AtomicLong getCheckRequestSuccessCount() { return checkRequestSuccessCount; } }
3e035b17e6c6f89e553315bedffb0a36f8049489
1,985
java
Java
CharacterReplacement.java
padmajeetpawar/Educative.io-Grokking-Coding-Patterns-Solution
5901830b6e3fd9f7255b8e44e8b036c4f8afff27
[ "MIT" ]
null
null
null
CharacterReplacement.java
padmajeetpawar/Educative.io-Grokking-Coding-Patterns-Solution
5901830b6e3fd9f7255b8e44e8b036c4f8afff27
[ "MIT" ]
null
null
null
CharacterReplacement.java
padmajeetpawar/Educative.io-Grokking-Coding-Patterns-Solution
5901830b6e3fd9f7255b8e44e8b036c4f8afff27
[ "MIT" ]
null
null
null
47.261905
107
0.651385
1,390
package com.educative; import java.util.*; class CharacterReplacement { public static int findLength(String str, int k) { int windowStart = 0, maxLength = 0, maxRepeatLetterCount = 0; Map<Character, Integer> letterFrequencyMap = new HashMap<>(); // try to extend the range [windowStart, windowEnd] for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) { char rightChar = str.charAt(windowEnd); letterFrequencyMap.put(rightChar, letterFrequencyMap.getOrDefault(rightChar, 0) + 1); System.out.println(letterFrequencyMap); maxRepeatLetterCount = Math.max(maxRepeatLetterCount, letterFrequencyMap.get(rightChar)); System.out.println("maxRepeatLetterCount: "+maxRepeatLetterCount); // current window size is from windowStart to windowEnd, overall we have a letter which is // repeating 'maxRepeatLetterCount' times, this means we can have a window which has one letter // repeating 'maxRepeatLetterCount' times and the remaining letters we should replace. // if the remaining letters are more than 'k', it is the time to shrink the window as we // are not allowed to replace more than 'k' letters if (windowEnd - windowStart + 1 - maxRepeatLetterCount > k) { char leftChar = str.charAt(windowStart); letterFrequencyMap.put(leftChar, letterFrequencyMap.get(leftChar) - 1); windowStart++; } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); System.out.println("maxLength: "+maxLength+"\n"); } return maxLength; } public static void main(String[] args) { System.out.println(CharacterReplacement.findLength("aabccbb", 2)); //System.out.println(CharacterReplacement.findLength("abbcb", 1)); //System.out.println(CharacterReplacement.findLength("abccde", 1)); } }
3e035d906ff8847ee5d47ab3680a577e94c9778f
4,087
java
Java
app/src/main/java/com/example/davidvalentin/pace/Runner.java
david-valentin/Pace
b66a2d3c91e800272ce367c786573f9cad3beb3d
[ "MIT" ]
null
null
null
app/src/main/java/com/example/davidvalentin/pace/Runner.java
david-valentin/Pace
b66a2d3c91e800272ce367c786573f9cad3beb3d
[ "MIT" ]
null
null
null
app/src/main/java/com/example/davidvalentin/pace/Runner.java
david-valentin/Pace
b66a2d3c91e800272ce367c786573f9cad3beb3d
[ "MIT" ]
null
null
null
27.066225
125
0.61561
1,391
package com.example.davidvalentin.pace; import android.content.Context; import android.location.Location; import android.util.Log; /** * Created by davidvalentin on 12/28/17. * * The class basically holds some of the properties of a runner * 1. Running * 2. Paused * 3. Restarted * * TODO: * Remove the RESTART and SAVED state as they don't do anything * and really aren't connected to the behavior of the Runner class itself * */ public class Runner { private static final String TAG = "Runner"; // Protected Member Variables: protected int time; protected RunnerState state; //Location Variables: protected Location startLocation; protected Location endLocation; protected Location intermediaryLocation; // Private Member Variables private Context context; private java.util.Date noteTS; /* STATES EXPLAINED: * RUNNING => The runner is running: * 1. The service = running * 2. Location listener = running * 3. TextViews = updating * SAVED => The runner has stopped and finished their run: * 1. The service != running i.e. unbinded/stopped * 2. The location listener != running * 3. TextViews != updating => TextViews set to defaults * PAUSED => The runner has paused their running i.e. for some reason * 1. The service = running * 2. Location listener = running * 3. TextViews != updating => TextViews and distance is calculated from the latest point * */ public enum RunnerState { ERROR, RUNNING, PAUSED, RESTARTED } /** * Runner * Constructor for the Runner Class * */ public Runner(Context context) { Log.d(TAG, "Runner"); this.state = RunnerState.PAUSED; // So that we can instantiate the start location member class in the runnerClass: // https://stackoverflow.com/questions/4870667/how-can-i-use-getsystemservice-in-a-non-activity-class-locationmanager this.context = context; } /** * Initiates that the runner is running and would like * 1. Record their time and distance travelled * */ public void run() { Log.d(TAG, "run"); if(this.state == RunnerState.PAUSED) { Log.d(TAG, "run"); this.state = RunnerState.RUNNING; // Made a separate if else to know when we are in the restarted state } else if (this.state == RunnerState.RESTARTED) { Log.d(TAG, "RESTARTED => RUNNING"); this.state = RunnerState.RUNNING; } } /** * Initiates that the runner has paused running but would still like to: * 1. Resume their run and track their time * */ public void pause() { Log.d(TAG, "pause"); if(this.state == RunnerState.RUNNING) { this.state = RunnerState.PAUSED; } } /** * Initiates that the runner is running and would like * 1. Record their time and distance travelled * */ public void restart() { Log.d(TAG, "restart"); if(this.state == RunnerState.PAUSED) { this.state = RunnerState.RESTARTED; } } /* * GETTERS AND SETTERS * * */ public RunnerState getState() { return this.state; } public Location getStartLocation() { return startLocation; } public void setStartLocation(Location startLocation) { this.startLocation = startLocation; } public Location getEndLocation() { return endLocation; } public void setEndLocation(Location endLocation) { this.endLocation = endLocation; } public Location getIntermediaryLocation() { return intermediaryLocation; } public void setIntermediaryLocation(Location intermediaryLocation) { this.intermediaryLocation = intermediaryLocation; } public void setRunnerState(RunnerState state) { this.state = state; } }
3e035fb81ae9e33035fb9963b2b6b1efa342c859
708
java
Java
px-checkout/src/main/java/com/mercadopago/android/px/internal/repository/PaymentRewardRepository.java
tomascorchonML/px-android
c05ca6a09c7f11593b8572db4da55383d5330b69
[ "MIT" ]
null
null
null
px-checkout/src/main/java/com/mercadopago/android/px/internal/repository/PaymentRewardRepository.java
tomascorchonML/px-android
c05ca6a09c7f11593b8572db4da55383d5330b69
[ "MIT" ]
null
null
null
px-checkout/src/main/java/com/mercadopago/android/px/internal/repository/PaymentRewardRepository.java
tomascorchonML/px-android
c05ca6a09c7f11593b8572db4da55383d5330b69
[ "MIT" ]
null
null
null
44.25
112
0.80791
1,392
package com.mercadopago.android.px.internal.repository; import android.support.annotation.NonNull; import com.mercadopago.android.px.model.IPaymentDescriptor; import com.mercadopago.android.px.model.PaymentResult; import com.mercadopago.android.px.model.internal.PaymentReward; public interface PaymentRewardRepository { void getPaymentReward(@NonNull final IPaymentDescriptor payment, @NonNull final PaymentResult paymentResult, @NonNull final PaymentRewardCallback callback); interface PaymentRewardCallback { void handleResult(@NonNull final IPaymentDescriptor payment, @NonNull final PaymentResult paymentResult, @NonNull final PaymentReward paymentReward); } }
3e0360141e3042531848c76b251e88ef5e35161c
170
java
Java
src/main/java/com/github/maasdi/react/assets/builder/IAssetBuilder.java
maasdi/react-assets-maven-plugin
cac711fe4e6fa1a0309944798200c4ae03dec6dc
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/maasdi/react/assets/builder/IAssetBuilder.java
maasdi/react-assets-maven-plugin
cac711fe4e6fa1a0309944798200c4ae03dec6dc
[ "Apache-2.0" ]
3
2020-11-16T03:46:35.000Z
2021-04-22T14:28:14.000Z
src/main/java/com/github/maasdi/react/assets/builder/IAssetBuilder.java
maasdi/react-assets-maven-plugin
cac711fe4e6fa1a0309944798200c4ae03dec6dc
[ "Apache-2.0" ]
null
null
null
17
55
0.752941
1,393
package com.github.maasdi.react.assets.builder; import java.util.List; public interface IAssetBuilder { String build(List<String> assets) throws Exception; }
3e03607d7c00aa3cd2125e3cbe8967f51605cb40
3,224
java
Java
shop-service/shop-service-product/src/main/java/com/sunny/shop/action/CategoryParameterAction.java
tec-feng/saas-shop
a040a54169541481a03830edba7f91cf15931284
[ "Apache-2.0" ]
2
2020-06-03T05:39:08.000Z
2020-06-30T00:38:03.000Z
shop-service/shop-service-product/src/main/java/com/sunny/shop/action/CategoryParameterAction.java
tec-feng/saas-shop
a040a54169541481a03830edba7f91cf15931284
[ "Apache-2.0" ]
3
2020-04-30T16:49:04.000Z
2021-06-04T22:09:55.000Z
shop-service/shop-service-product/src/main/java/com/sunny/shop/action/CategoryParameterAction.java
tec-feng/saas-shop
a040a54169541481a03830edba7f91cf15931284
[ "Apache-2.0" ]
2
2020-10-16T05:46:33.000Z
2022-01-09T04:10:06.000Z
40.810127
111
0.741625
1,394
package com.sunny.shop.action; import cn.hutool.core.date.DateUtil; import com.sunny.base.*; import com.sunny.product.model.CategoryParameter; import com.sunny.product.model.CategoryParameterExample; import com.sunny.product.model.ProductCategory; import com.sunny.shop.service.CategoryParameterService; import com.sunny.shop.service.ProductCategoryService; import com.sunny.tools.SnowFlakeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * @author tec_feng * @create 2020-06-17 01:08:09 */ @Component public class CategoryParameterAction extends BaseAction<CategoryParameter,CategoryParameterExample>{ @Autowired CategoryParameterService categoryParameterService; @Autowired ProductCategoryService productCategoryService; @Override protected BaseService<CategoryParameter, CategoryParameterExample> getService() { return categoryParameterService; } @Override public int save(CategoryParameter record) { CategoryParameterExample example = new CategoryParameterExample(); example.createCriteria().andNameEqualTo(record.getName()).andAreaUserIdEqualTo(record.getAreaUserId()); long count = countByExample(example); if(count>0){ throw new ApiException(ApiCode.CATEGORY_PARAMETER_EXIST); } ProductCategory category = productCategoryService.selectByKey(record.getCategoryId()); if(category == null){ throw new ApiException(ApiCode.CATEGORY_NOT_EXIST); } record.setId(SnowFlakeUtils.nextId()); record.setCreateTime(DateUtil.date()); record.setStatus(0); if(record.getSort() == null){ record.setSort(0); } return super.save(record); } public int deleteSelf(long id,long userId) { CategoryParameterExample example = new CategoryParameterExample(); example.createCriteria().andIdEqualTo(id).andAreaUserIdEqualTo(userId); CategoryParameter parameter = new CategoryParameter(); parameter.setId(id); parameter.setStatus(BaseStatus.DELETE_STATUS); return super.updateByExampleSelective(parameter,example); } public int updateSelf(CategoryParameter parameter,long userId) { CategoryParameterExample example = new CategoryParameterExample(); example.createCriteria().andIdEqualTo(parameter.getId()).andAreaUserIdEqualTo(userId); return super.updateByExampleSelective(parameter,example); } public CategoryParameter getSelf(long id,long userId) { CategoryParameterExample example = new CategoryParameterExample(); example.createCriteria().andIdEqualTo(id).andAreaUserIdEqualTo(userId); return super.selectOne(example); } public List<CategoryParameter> listSelf(long categoryId, long userId, Integer page, Integer pageSize) { CategoryParameterExample example = new CategoryParameterExample(); example.createCriteria().andCategoryIdEqualTo(categoryId).andAreaUserIdEqualTo(userId) .andStatusEqualTo(BaseStatus.NORMAL_STATUS); return super.selectByExample(example,page,pageSize); } }
3e036095ee34b4b0d621de59888bc44f7ff8806d
325
java
Java
src/test/java/com/kittentracker/KittenPluginTest.java
ZenithStar/kitten-tracker
49d0d2d98a8acfa4175f7d0752c4a93b3ec23ce1
[ "BSD-2-Clause" ]
null
null
null
src/test/java/com/kittentracker/KittenPluginTest.java
ZenithStar/kitten-tracker
49d0d2d98a8acfa4175f7d0752c4a93b3ec23ce1
[ "BSD-2-Clause" ]
null
null
null
src/test/java/com/kittentracker/KittenPluginTest.java
ZenithStar/kitten-tracker
49d0d2d98a8acfa4175f7d0752c4a93b3ec23ce1
[ "BSD-2-Clause" ]
null
null
null
29.545455
65
0.769231
1,395
package com.kittentracker; import net.runelite.client.RuneLite; import net.runelite.client.externalplugins.ExternalPluginManager; public class KittenPluginTest { public static void main(String[] args) throws Exception { ExternalPluginManager.loadBuiltin(KittenPlugin.class); RuneLite.main(args); } }
3e03613e610ed2f91a9cdc72da8d57fa481b24fd
1,913
java
Java
CSC-252/HW2AlgoAnalysis/Fragment7.java
FrancesCoronel/cs-hu
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
2
2016-12-05T06:15:34.000Z
2016-12-15T10:56:50.000Z
CSC-252/HW2AlgoAnalysis/Fragment7.java
fvcproductions/CS-HU
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
null
null
null
CSC-252/HW2AlgoAnalysis/Fragment7.java
fvcproductions/CS-HU
ecd103a525fd312146d3b6c69ee7c1452548c5e2
[ "MIT" ]
3
2019-04-06T01:45:54.000Z
2020-04-24T16:55:32.000Z
25.506667
117
0.488238
1,396
/** * @author FVCproductions * @see HW2 - Algorithm Analysis - Problem 4 Part B * @version 1.0 * @since 1-3-15 * * Fragment 7 */ class Timing { public static final int NUM_TIMINGS = 5; public static void main(String[] args) { // it is best to do the timing a few times because when Java can appear // "slower when it starts", so if you see slower results for the first // couple of timing runs, it is reasonable to discard them int n = 0; // fragment 7 System.out.println("FRAGMENT 7"); System.out.println("\nn = 64"); n = 64; fragment7(n); System.out.println("\nn = 128"); n = 128; fragment7(n); System.out.println("\nn = 256"); n = 256; fragment7(n); System.out.println("\nn = 512"); n = 512; fragment7(n); } private static void fragment7(int n) { long total = 0; for (int timing = 0; timing < NUM_TIMINGS; ++timing) { long startTime = System.nanoTime(); // ... The code being timed ... // Replace this code with your own code: // begin code to replace: int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < i * i; j++) sum++; // end code to replace long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; // 1 second = 1000000000 (10^9) nanoseconds. total = total + elapsedTime; //ADDED System.out.println(elapsedTime + " nanoseconds or " + elapsedTime / (1000000000.0) + " seconds elapsed"); } System.out.println("Average Time (nanoseconds): " + total / 5); } }
3e03613eb88082f04928b8727abf9786a4085e44
4,136
java
Java
phoenix-core/src/main/java/org/apache/phoenix/parse/CastParseNode.java
wwjiang007/phoenix
6ea9dec20f1302c10d7831f544cf9615eba633f5
[ "Apache-2.0" ]
984
2015-01-04T20:25:27.000Z
2022-03-22T08:06:36.000Z
phoenix-core/src/main/java/org/apache/phoenix/parse/CastParseNode.java
wwjiang007/phoenix
6ea9dec20f1302c10d7831f544cf9615eba633f5
[ "Apache-2.0" ]
953
2015-01-15T07:08:52.000Z
2022-03-25T09:07:56.000Z
phoenix-core/src/main/java/org/apache/phoenix/parse/CastParseNode.java
wwjiang007/phoenix
6ea9dec20f1302c10d7831f544cf9615eba633f5
[ "Apache-2.0" ]
1,077
2015-01-05T13:00:26.000Z
2022-03-31T08:40:59.000Z
29.542857
111
0.640474
1,397
/* * 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.phoenix.parse; import java.sql.SQLException; import java.util.Collections; import java.util.List; import org.apache.phoenix.compile.ColumnResolver; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.util.SchemaUtil; /** * * Node representing the CAST operator in SQL. * * * @since 0.1 * */ public class CastParseNode extends UnaryParseNode { private final PDataType dt; private final Integer maxLength; private final Integer scale; CastParseNode(ParseNode expr, String dataType, Integer maxLength, Integer scale, boolean arr) { this(expr, PDataType.fromSqlTypeName(SchemaUtil.normalizeIdentifier(dataType)), maxLength, scale, arr); } CastParseNode(ParseNode expr, PDataType dataType, Integer maxLength, Integer scale, boolean arr) { super(expr); if (arr == true) { dt = PDataType.fromTypeId(dataType.getSqlType() + PDataType.ARRAY_TYPE_BASE); } else { dt = dataType; } this.maxLength = maxLength; this.scale = scale; } @Override public <T> T accept(ParseNodeVisitor<T> visitor) throws SQLException { List<T> l = Collections.emptyList(); if (visitor.visitEnter(this)) { l = acceptChildren(visitor); } return visitor.visitLeave(this, l); } public PDataType getDataType() { return dt; } public Integer getMaxLength() { return maxLength; } public Integer getScale() { return scale; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((dt == null) ? 0 : dt.hashCode()); result = prime * result + ((maxLength == null) ? 0 : maxLength.hashCode()); result = prime * result + ((scale == null) ? 0 : scale.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CastParseNode other = (CastParseNode) obj; if (dt == null) { if (other.dt != null) return false; } else if (!dt.equals(other.dt)) return false; if (maxLength == null) { if (other.maxLength != null) return false; } else if (!maxLength.equals(other.maxLength)) return false; if (scale == null) { if (other.scale != null) return false; } else if (!scale.equals(other.scale)) return false; return true; } @Override public void toSQL(ColumnResolver resolver, StringBuilder buf) { List<ParseNode> children = getChildren(); buf.append(" CAST("); children.get(0).toSQL(resolver, buf); buf.append(" AS "); boolean isArray = dt.isArrayType(); PDataType type = isArray ? PDataType.arrayBaseType(dt) : dt; buf.append(type.getSqlTypeName()); if (maxLength != null) { buf.append('('); buf.append(maxLength); if (scale != null) { buf.append(','); buf.append(scale); // has both max length and scale. For ex- decimal(10,2) } buf.append(')'); } if (isArray) { buf.append(' '); buf.append(PDataType.ARRAY_TYPE_SUFFIX); } buf.append(")"); } }
3e036256a2b154da5b5cba506ff63b95ae510415
4,385
java
Java
JPS_SCENARIOS/src/uk/ac/cam/cares/jps/scenario/kb/KnowledgeBaseBlazegraph.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
null
null
null
JPS_SCENARIOS/src/uk/ac/cam/cares/jps/scenario/kb/KnowledgeBaseBlazegraph.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
null
null
null
JPS_SCENARIOS/src/uk/ac/cam/cares/jps/scenario/kb/KnowledgeBaseBlazegraph.java
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
011aee78c016b76762eaf511c78fabe3f98189f4
[ "MIT" ]
null
null
null
34.527559
163
0.690992
1,398
package uk.ac.cam.cares.jps.scenario.kb; import java.io.InputStream; import org.apache.http.client.methods.HttpGet; import org.eclipse.rdf4j.rio.RDFFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.cam.cares.jps.base.discovery.MediaType; import uk.ac.cam.cares.jps.base.http.Http; import uk.ac.cam.cares.jps.base.util.FileUtil; public class KnowledgeBaseBlazegraph extends KnowledgeBaseAbstract { private static Logger logger = LoggerFactory.getLogger(KnowledgeBaseBlazegraph.class); public KnowledgeBaseBlazegraph(String datasetUrl, String datasetName, String endpointUrl) { super(datasetUrl, datasetName, endpointUrl); } private String getEndpointUrl() { return endpointUrl + "/sparql"; } @Override public void put(String resourceUrl, String content, String contentType) { logger.info("put resourceUrl=" + resourceUrl + " (kb url=" + datasetUrl + ")"); String url = getEndpointUrl(); if (contentType == null) { contentType = MediaType.APPLICATION_RDF_XML.type; } if (resourceUrl == null) { throw new UnsupportedOperationException(); } else { // Blazegraph server allow HTTP PUT in combination with an SPARQL CONSTRUCT query for deletion // see https://wiki.blazegraph.com/wiki/index.php/REST_API#UPDATE_.28DELETE_statements_selected_by_a_QUERY_plus_INSERT_statements_from_Request_Body_using_PUT.29 // here, we use to consecutive requests DELETE and POST Http.execute(Http.delete(url, "c", "<" + resourceUrl + ">")); Http.execute(Http.post(url, content, contentType, null, "context-uri", resourceUrl)); } } @Override public void update(String resourceUrl, String sparql) { logger.info("update resourceUrl=" + resourceUrl + " (kb url=" + datasetUrl + ")"); String url = getEndpointUrl(); if (resourceUrl == null) { Http.execute(Http.post(url, null, null, null, "update", sparql)); } else { // neither context-iri nor using-graph-uri nor using-named-graph-uri works here //Http.execute(Http.post(url, null, null, null, "update", sparql, // "using-named-graph-uri", resourceUrl)); // must be solved within the sparql statement: INSERT DATA { GRAPH <resourceurl> { ... } } //Http.execute(Http.post(url, null, null, null, "update", sparql)); throw new UnsupportedOperationException(); } } @Override public String get(String resourceUrl, String accept) { logger.info("get resourceUrl=" + resourceUrl + " (kb url=" + datasetUrl + ")"); String url = getEndpointUrl(); if (resourceUrl == null) { // does not work without changing JPS_BASE_LIB //return Http.execute(Http.get(url, accept, "default")); HttpGet get = Http.get(url, accept); // try { // URI extended = new URI(get.getURI() + "?default"); // get.setURI(extended); // } catch (URISyntaxException e) { // throw new JPSRuntimeException(e.getMessage(), e); // } return Http.execute(get); } else { //HttpGet get = Http.get(url, accept); //, "c", resourceUrl); //HttpGet get = Http.get(url, accept, "default-graph-uri", resourceUrl); HttpGet get = Http.get(url, accept, "query", "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }", "default-graph-uri", resourceUrl); // try { // URI extended = new URI(get.getURI() + "?GETSTMTS"); // get.setURI(extended); // } catch (URISyntaxException e) { // throw new JPSRuntimeException(e.getMessage(), e); // } return Http.execute(get); } } @Override public String query(String resourceUrl, String sparql) { logger.info("query resourceUrl=" + resourceUrl + " (kb url=" + datasetUrl + ")"); String url = getEndpointUrl(); String result = null; if (resourceUrl == null) { // no special treatment of default graph necessary result = Http.execute(Http.get(url, MediaType.APPLICATION_SPARQL.type, "query", sparql)); } else { RDFFormat format = getRDFFormatFromFileType(resourceUrl); if (format == null) { format = RDFFormat.RDFXML; } String content = get(resourceUrl, format.getDefaultMIMEType()); InputStream inputStream = FileUtil.stringToInputStream(content); result = query(inputStream, format, sparql); } return result; } @Override public boolean exists(String resourceUrl) { logger.info("exists resourceUrl=" + resourceUrl + " (kb url=" + datasetUrl + ")"); throw new UnsupportedOperationException(); } }
3e0364f39abee4e1c9f2941da03ed3f79d0dc66a
881
java
Java
src/main/java/org/slos/battle/abilities/attack/ShieldAbility.java
Jarunik/sm-team-finder
f31f94a6f686ec79bf5adfdb692bb9ca27e44b6d
[ "MIT" ]
2
2020-07-07T14:38:59.000Z
2020-07-08T11:38:24.000Z
src/main/java/org/slos/battle/abilities/attack/ShieldAbility.java
Jarunik/sm-team-finder
f31f94a6f686ec79bf5adfdb692bb9ca27e44b6d
[ "MIT" ]
1
2021-11-12T07:35:10.000Z
2021-11-12T07:35:10.000Z
src/main/java/org/slos/battle/abilities/attack/ShieldAbility.java
Jarunik/sm-team-finder
f31f94a6f686ec79bf5adfdb692bb9ca27e44b6d
[ "MIT" ]
4
2020-07-07T11:03:28.000Z
2021-11-11T06:11:23.000Z
31.464286
78
0.780931
1,399
package org.slos.battle.abilities.attack; import org.slos.battle.abilities.Ability; import org.slos.battle.abilities.AbilityClassification; import org.slos.battle.abilities.AbilityEffect; import org.slos.battle.abilities.AbilityType; import org.slos.battle.abilities.rule.ReduceHalfDamageRule; import org.slos.battle.abilities.rule.attack.DamageRule; import org.slos.battle.abilities.rule.target.TargetRuleset; import org.slos.splinterlands.domain.monster.DamageType; public class ShieldAbility extends Ability implements AbilityEffect { public ShieldAbility() { super(AbilityType.SHIELD, AbilityClassification.ATTACK); } @Override public TargetRuleset getTargetRuleset() { return TargetRuleset.SELF; } @Override public DamageRule getEffect() { return new ReduceHalfDamageRule(DamageType.ATTACK, DamageType.RANGED); } }
3e0367156e46502eaf6b344ac177872a4dbe06fc
1,898
java
Java
pds/java/src/main/java/com/aliyun/pds/client/models/SharePermissionPolicy.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
4
2020-08-21T08:40:27.000Z
2021-04-04T03:39:06.000Z
pds/java/src/main/java/com/aliyun/pds/client/models/SharePermissionPolicy.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
35
2020-08-31T08:10:53.000Z
2022-03-24T09:43:11.000Z
pds/java/src/main/java/com/aliyun/pds/client/models/SharePermissionPolicy.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
16
2020-08-24T05:42:43.000Z
2022-03-16T03:03:53.000Z
26.732394
94
0.690727
1,400
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.pds.client.models; import com.aliyun.tea.*; /** * */ public class SharePermissionPolicy extends TeaModel { @NameInMap("file_id") public String fileId; @NameInMap("file_path") public String filePath; @NameInMap("permission_inheritable") public Boolean permissionInheritable; @NameInMap("permission_list") public java.util.List<String> permissionList; @NameInMap("permission_type") public String permissionType; public static SharePermissionPolicy build(java.util.Map<String, ?> map) throws Exception { SharePermissionPolicy self = new SharePermissionPolicy(); return TeaModel.build(map, self); } public SharePermissionPolicy setFileId(String fileId) { this.fileId = fileId; return this; } public String getFileId() { return this.fileId; } public SharePermissionPolicy setFilePath(String filePath) { this.filePath = filePath; return this; } public String getFilePath() { return this.filePath; } public SharePermissionPolicy setPermissionInheritable(Boolean permissionInheritable) { this.permissionInheritable = permissionInheritable; return this; } public Boolean getPermissionInheritable() { return this.permissionInheritable; } public SharePermissionPolicy setPermissionList(java.util.List<String> permissionList) { this.permissionList = permissionList; return this; } public java.util.List<String> getPermissionList() { return this.permissionList; } public SharePermissionPolicy setPermissionType(String permissionType) { this.permissionType = permissionType; return this; } public String getPermissionType() { return this.permissionType; } }
3e03671a6974266944dea42cca375b99014ceafa
10,965
java
Java
randomizer/fates/model/processors/chapter/ChapterHandler.java
libertyernie/3DSFE-Randomizer
abe42676ea65cf4f58c4a4e55a073ae14c0d793d
[ "MIT" ]
9
2017-04-12T14:26:47.000Z
2021-04-05T19:02:15.000Z
randomizer/fates/model/processors/chapter/ChapterHandler.java
libertyernie/3DSFE-Randomizer
abe42676ea65cf4f58c4a4e55a073ae14c0d793d
[ "MIT" ]
12
2017-03-07T03:14:53.000Z
2017-08-23T14:23:48.000Z
randomizer/fates/model/processors/chapter/ChapterHandler.java
libertyernie/3DSFE-Randomizer
abe42676ea65cf4f58c4a4e55a073ae14c0d793d
[ "MIT" ]
2
2019-11-29T02:46:53.000Z
2022-01-18T19:59:27.000Z
43.511905
124
0.561423
1,401
package randomizer.fates.model.processors.chapter; import feflib.fates.castle.join.FatesJoin; import feflib.fates.castle.join.JoinBlock; import feflib.fates.gamedata.dispo.DispoBlock; import feflib.fates.gamedata.dispo.DispoFaction; import feflib.fates.gamedata.dispo.FatesDispo; import feflib.fates.gamedata.person.FatesPerson; import feflib.fates.gamedata.person.PersonBlock; import randomizer.common.enums.CharacterType; import randomizer.common.structures.Chapter; import randomizer.common.utils.CompressionUtils; import randomizer.fates.model.structures.FatesCharacter; import randomizer.fates.singletons.*; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ChapterHandler { private static boolean[] options = FatesGui.getInstance().getSelectedOptions(); private static FatesItems fatesItems = FatesItems.getInstance(); private static FatesCharacters fatesCharacters = FatesCharacters.getInstance(); private static FatesJobs fatesJobs = FatesJobs.getInstance(); private static FatesChapters fatesChapters = FatesChapters.getInstance(); private static FatesFiles fileData = FatesFiles.getInstance(); public static void randomizeChapterData() { List<FatesCharacter> selected = FatesCharacters.getInstance().getWorkingCharacters(); List<Chapter> chapters = fatesChapters.getSelectedChapters(); for(Chapter c : chapters) { HashMap<String, List<String>> aliasMap = randomizePerson(c, selected); randomizeDispo(c, selected, aliasMap); } randomizeJoin(selected); } private static HashMap<String, List<String>> randomizePerson(Chapter chapter, List<FatesCharacter> selected) { if(chapter == null) throw new IllegalArgumentException("Violation of precondition: randomizePerson." + "chapter must not be null."); if(selected == null) throw new IllegalArgumentException("Violation of precondition: randomizePerson." + "selected must not be null."); HashMap<String, List<String>> aliasMap = new HashMap<>(); FatesPerson person = new FatesPerson(fileData.getPerson().get(chapter.getCid())); // Iterate over every block in the person file. for(PersonBlock p : person.getCharacters()) { // ... And see if the block matches with one of the characters // in the randomizer pool. for(FatesCharacter c : selected) { if(c.getCharacterType() == CharacterType.Player) // The player should never be swapped. continue; FatesCharacter target = fatesCharacters.getByPid(c.getTargetPid()); if(target == null) throw new RuntimeException("Error: randomizePerson. Target character for " + c.getName() + " returned null."); // If the block matches the character, reclass it and replace the assets. if(p.getAid().equals(target.getAid())) { // Change character. p.setAid(c.getAid()); p.setFid(c.getFid()); p.setMPid(c.getMPid()); p.setMPidH(c.getMPidH()); if(chapter.getCid().equals("A001")) // Fix for chapter 1 crash. break; // If the PID isn't banned, reclass. if(!fatesCharacters.getBannedPids().contains(p.getPid())) { // Reclass block. if(options[13]) { p.setClasses(new short[] { c.getCharacterClass().getId(), c.getCharacterClass().getTiedJob() }); p.setWeaponRanks(fatesJobs.generateWeaponsRanks(c.getCharacterClass())); } // Add block to alias map. if(aliasMap.containsKey(c.getPid())) { aliasMap.get(c.getPid()).add(p.getPid()); } else { List<String> aliases = new ArrayList<>(); aliases.add(p.getPid()); aliasMap.put(c.getPid(), aliases); } } break; } } } // Finally, recompress the file so its usable in game. try { Files.write(fileData.getPerson().get(chapter.getCid()).toPath(), CompressionUtils.compress(person.serialize())); } catch(IOException ex) { ex.printStackTrace(); } return aliasMap; } private static void randomizeDispo(Chapter chapter, List<FatesCharacter> selected, HashMap<String, List<String>> aliasMap) { if(chapter == null) throw new IllegalArgumentException("Violation of precondition: randomizeDispo." + "chapter must not be null."); if(selected == null) throw new IllegalArgumentException("Violation of precondition: randomizeDispo." + "selected must not be null."); if(aliasMap == null) throw new IllegalArgumentException("Violation of precondition: aliasMap." + "aliasMap must not be null."); FatesDispo dispo = new FatesDispo(fileData.getDispos().get(chapter.getCid())); // Special fixes for chapters with unusual settings. if(chapter.getCid().equals("A011")) patchA011Dispo(dispo); // Iterate over every block... for(DispoFaction f : dispo.getFactions()) { // ... And every block within the faction... for(DispoBlock b : f.getSpawns()) { // ... And compare it's PID against every character and alias. for(FatesCharacter c : selected) { // Swap out matching dispos and distribute new items. FatesCharacter target = fatesCharacters.getByPid(c.getTargetPid()); if(pidMatches(target, b)) { b.setPid(c.getPid()); b.addItem(fatesItems.generateItem(c.getCharacterClass()).getIid()); if(c.getCharacterType() == CharacterType.Player) b.addItem(fatesItems.generateItem(c.getCharacterClass()).getIid()); break; } else if(aliasMap.get(c.getPid()) != null && options[13]) { // Swap out aliases and distribute items. for(String s : aliasMap.get(c.getPid())) { if(s.equals(b.getPid())) { b.addItem(fatesItems.generateItem(c.getCharacterClass()).getIid()); if(s.contains("ボス")) { // Workaround for bugged bosses. b.addItem(fatesItems.generateItem(c.getCharacterClass()).getIid()); } break; } } } } } } // Write file. try { Files.write(fileData.getDispos().get(chapter.getCid()).toPath(), CompressionUtils.compress(dispo.serialize())); } catch(IOException ex) { ex.printStackTrace(); } } private static void randomizeJoin(List<FatesCharacter> selected) { if(selected == null) throw new IllegalArgumentException("Violation of precondition: randomizeJoin." + "selected must not be null."); // Swap out join blocks. FatesJoin join = new FatesJoin(fileData.getCastleJoin()); for(JoinBlock j : join.getBlocks()) { for(FatesCharacter c : selected) { if(j.getCharacter().equals(c.getPid())) { j.setCharacter(fatesCharacters.getReplacement(c.getPid()).getPid()); break; } } } // Add block for Anna's replacement. if(options[8]) { JoinBlock block = new JoinBlock(); block.setBirthrightJoin("CID_A006"); block.setConquestJoin("CID_B006"); block.setRevelationJoin("CID_C006"); block.setUnknownOne(join.getBlocks().get(0).getUnknownOne()); for(FatesCharacter c : selected) { if(c.getPid().equals("PID_アンナ")) { block.setCharacter(fatesCharacters.getReplacement(c.getPid()).getPid()); join.getBlocks().add(block); break; } } } // TODO: Fix stats for castle join servants. // Write file. try { Files.write(fileData.getCastleJoin().toPath(), CompressionUtils.compress(join.serialize())); } catch(IOException ex) { ex.printStackTrace(); } } /** * Determine if the given randomizer character and dispo block refer to * the same character. * * @param c The randomizer character to check. * @param b The dispo block to check. * @return A boolean value representing whether or not the blocks match. */ private static boolean pidMatches(FatesCharacter c, DispoBlock b) { if(c == null) throw new IllegalArgumentException("Violation of precondition: pidMatches." + "c must not be null."); if(b == null) throw new IllegalArgumentException("Violation of precondition: pidMatches." + "b must not be null."); return c.getPid().equals(b.getPid()) || c.getPidA().equals(b.getPid()) || c.getPidB().equals(b.getPid()) || c.getPidC().equals(b.getPid()); } /** * Make adjustments to Birthright chapter 11's spawn file * to prevent crashing when Reina's replacement spawns. * * @param dispo The dispo file to be patched. */ private static void patchA011Dispo(FatesDispo dispo) { if(dispo == null) throw new IllegalArgumentException("Violation of precondition: patchA011Dispo." + "dispo must not be null."); DispoFaction faction = dispo.getByName("Support01"); assert(faction != null); if(options[3]) { dispo.getFactions().remove(faction); } // Fix for Reina's starting position. faction = dispo.getByName("Support02"); assert(faction != null); faction.getSpawns().get(0).setFirstCoord(new byte[] { 0x1C, 0x8 }); faction.getSpawns().get(0).setSecondCoord(new byte[] { 0x1C, 0x7 }); } }
3e0367f97b07c1fbece169e76f90cf17975f622c
2,700
java
Java
core/target/java/org/apache/spark/ui/WebUI.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
core/target/java/org/apache/spark/ui/WebUI.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
core/target/java/org/apache/spark/ui/WebUI.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
72.972973
194
0.741111
1,402
package org.apache.spark.ui; /** * The top level component of the UI hierarchy that contains the server. * <p> * Each WebUI represents a collection of tabs, each of which in turn represents a collection of * pages. The use of tabs is optional, however; a WebUI may choose to include pages directly. */ private abstract class WebUI implements org.apache.spark.Logging { public WebUI (org.apache.spark.SecurityManager securityManager, int port, org.apache.spark.SparkConf conf, java.lang.String basePath, java.lang.String name) { throw new RuntimeException(); } protected scala.collection.mutable.ArrayBuffer<org.apache.spark.ui.WebUITab> tabs () { throw new RuntimeException(); } protected scala.collection.mutable.ArrayBuffer<org.eclipse.jetty.servlet.ServletContextHandler> handlers () { throw new RuntimeException(); } protected scala.Option<org.apache.spark.ui.ServerInfo> serverInfo () { throw new RuntimeException(); } protected java.lang.String localHostName () { throw new RuntimeException(); } protected java.lang.String publicHostName () { throw new RuntimeException(); } private java.lang.String className () { throw new RuntimeException(); } public java.lang.String getBasePath () { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.ui.WebUITab> getTabs () { throw new RuntimeException(); } public scala.collection.Seq<org.eclipse.jetty.servlet.ServletContextHandler> getHandlers () { throw new RuntimeException(); } public org.apache.spark.SecurityManager getSecurityManager () { throw new RuntimeException(); } /** Attach a tab to this UI, along with all of its attached pages. */ public void attachTab (org.apache.spark.ui.WebUITab tab) { throw new RuntimeException(); } /** Attach a page to this UI. */ public void attachPage (org.apache.spark.ui.WebUIPage page) { throw new RuntimeException(); } /** Attach a handler to this UI. */ public void attachHandler (org.eclipse.jetty.servlet.ServletContextHandler handler) { throw new RuntimeException(); } /** Detach a handler from this UI. */ public void detachHandler (org.eclipse.jetty.servlet.ServletContextHandler handler) { throw new RuntimeException(); } /** Initialize all components of the server. */ public abstract void initialize () ; /** Bind to the HTTP server behind this web interface. */ public void bind () { throw new RuntimeException(); } /** Return the actual port to which this server is bound. Only valid after bind(). */ public int boundPort () { throw new RuntimeException(); } /** Stop the server behind this web interface. Only valid after bind(). */ public void stop () { throw new RuntimeException(); } }
3e0368282922b669b42dca562abbe280e5678be1
2,437
java
Java
test/com/facebook/buck/android/AndroidProjectWorkspace.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
test/com/facebook/buck/android/AndroidProjectWorkspace.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
test/com/facebook/buck/android/AndroidProjectWorkspace.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
38.68254
100
0.763644
1,403
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.android; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.EnvVariablesProvider; import java.io.IOException; /** * Wraps {@link TestDataHelper#createProjectWorkspaceForScenario} for Android integration tests, * adding support for dynamically configuring the build-tools and compile_sdk versions. */ final class AndroidProjectWorkspace { private AndroidProjectWorkspace() {} /** * Creates a project workspace for Android integration tests. If the following environment * variables are set, then the equivalent Buck properties will be set automatically in the project * workspace: * * <ul> * <li><code>BUCK_TEST_ANDROID_BUILD_TOOLS_VERSION</code>: android.build_tools_version * <li><code>BUCK_TEST_ANDROID_COMPILE_SDK_VERSION</code>: android.compile_sdk_version * </ul> */ static ProjectWorkspace create(Object testCase, String scenario, TemporaryPaths tempFolder) throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(testCase, scenario, tempFolder); addConfigOptionFromEnvironment( workspace, "BUCK_TEST_ANDROID_BUILD_TOOLS_VERSION", "build_tools_version"); addConfigOptionFromEnvironment( workspace, "BUCK_TEST_ANDROID_COMPILE_SDK_VERSION", "compile_sdk_version"); return workspace; } private static void addConfigOptionFromEnvironment( ProjectWorkspace workspace, String env, String key) throws IOException { String value = EnvVariablesProvider.getSystemEnv().get(env); if (value != null) { workspace.addBuckConfigLocalOption("android", key, value); } } }
3e0369d1ae18e0d381534756b33d6e85dac36d14
124
java
Java
sources/b/j/a/c/b0/j.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T07:33:30.000Z
2021-06-29T18:50:21.000Z
sources/b/j/a/c/b0/j.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
null
null
null
sources/b/j/a/c/b0/j.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T15:56:20.000Z
2021-03-21T02:06:29.000Z
12.4
24
0.596774
1,404
package b.j.a.c.b0; import b.j.a.c.d; import b.j.a.c.g; import b.j.a.c.o; public interface j { o a(g gVar, d dVar); }
3e0369d5307b3707a4b2b6bbae326e2f313e2654
18,462
java
Java
plugins/org.jkiss.dbeaver.erd.ui/src/org/jkiss/dbeaver/erd/ui/export/ERDExportGraphML.java
Cynyard999/dbeaver
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
[ "Apache-2.0" ]
22,779
2017-12-23T15:47:03.000Z
2022-03-31T15:48:15.000Z
plugins/org.jkiss.dbeaver.erd.ui/src/org/jkiss/dbeaver/erd/ui/export/ERDExportGraphML.java
Cynyard999/dbeaver
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
[ "Apache-2.0" ]
10,922
2017-12-23T12:01:39.000Z
2022-03-31T23:52:18.000Z
plugins/org.jkiss.dbeaver.erd.ui/src/org/jkiss/dbeaver/erd/ui/export/ERDExportGraphML.java
Cynyard999/dbeaver
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
[ "Apache-2.0" ]
2,552
2017-12-26T21:31:27.000Z
2022-03-31T09:05:03.000Z
44.594203
189
0.55162
1,405
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * 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.jkiss.dbeaver.erd.ui.export; import org.eclipse.draw2dl.Bendpoint; import org.eclipse.draw2dl.IFigure; import org.eclipse.draw2dl.geometry.Rectangle; import org.eclipse.swt.graphics.Color; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.erd.model.*; import org.jkiss.dbeaver.erd.ui.ERDUIUtils; import org.jkiss.dbeaver.erd.ui.figures.AttributeListFigure; import org.jkiss.dbeaver.erd.ui.figures.EntityFigure; import org.jkiss.dbeaver.erd.ui.model.EntityDiagram; import org.jkiss.dbeaver.erd.ui.part.*; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.ui.ShellUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.Pair; import org.jkiss.utils.xml.XMLBuilder; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * GraphML exporter */ public class ERDExportGraphML implements ERDExportFormatHandler { private static final Log log = Log.getLog(ERDExportGraphML.class); private static final int fontSize = 12; @Override public void exportDiagram(EntityDiagram diagram, IFigure figure, DiagramPart diagramPart, File targetFile) { try { try (final OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(targetFile), GeneralUtils.UTF8_CHARSET)) { XMLBuilder xml = new XMLBuilder(osw, GeneralUtils.UTF8_ENCODING); xml.setButify(true); xml.startElement("graphml"); xml.addAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns"); xml.addAttribute("xmlns:java", "http://www.yworks.com/xml/yfiles-common/1.0/java"); xml.addAttribute("xmlns:sys", "http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0"); xml.addAttribute("xmlns:x", "http://www.yworks.com/xml/yfiles-common/markup/2.0"); xml.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xml.addAttribute("xmlns:y", "http://www.yworks.com/xml/graphml"); xml.addAttribute("xmlns:yed", "http://www.yworks.com/xml/yed/3"); xml.addAttribute("xsi:schemaLocation", "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"); xml.startElement("key"); xml.addAttribute("for", "node"); xml.addAttribute("id", "nodegraph"); xml.addAttribute("yfiles.type", "nodegraphics"); xml.endElement(); xml.startElement("key"); xml.addAttribute("for", "edge"); xml.addAttribute("id", "edgegraph"); xml.addAttribute("yfiles.type", "edgegraphics"); xml.endElement(); xml.startElement("graph"); xml.addAttribute("edgedefault", "directed"); xml.addAttribute("id", "G"); // A list of diagram elements sorted according to their z-order final List<ERDElement<?>> elements = Stream .concat( diagram.getEntities().stream().map(x -> new Pair<>(x, diagram.getVisualInfo(x.getObject()))), diagram.getNotes().stream().map(x -> new Pair<>(x, diagram.getVisualInfo(x)))) .sorted(Comparator.comparing(x -> x.getSecond() == null ? 0 : x.getSecond().zOrder)) .map(Pair::getFirst) .collect(Collectors.toList()); final Map<ERDElement<?>, String> associations = new HashMap<>(); // Export elements and collect their associations for (int index = 0; index < elements.size(); index++) { final ERDElement<?> element = elements.get(index); if (element instanceof ERDEntity) { exportEntity(index, (ERDEntity) element, diagramPart.getEntityPart((ERDEntity) element), diagram, associations, xml); } else if (element instanceof ERDNote) { exportNote(index, (ERDNote) element, diagramPart.getNotePart((ERDNote) element), associations, xml); } else { log.debug("Unsupported ERD element: " + element); } } // Export edges using collected associations for (int index = 0; index < elements.size(); index++) { final ERDElement<?> element = elements.get(index); if (element instanceof ERDEntity) { exportEdge(index, element, diagramPart.getEntityPart((ERDEntity) element), associations, xml); } else if (element instanceof ERDNote) { exportEdge(index, element, diagramPart.getNotePart((ERDNote) element), associations, xml); } else { log.debug("Unsupported ERD element: " + element); } } xml.endElement(); xml.endElement(); xml.flush(); osw.flush(); } ShellUtils.launchProgram(targetFile.getAbsolutePath()); } catch (Exception e) { DBWorkbench.getPlatformUI().showError("Save ERD as GraphML", null, e); } } private static void exportEntity(int index, ERDEntity entity, EntityPart entityPart, EntityDiagram diagram, Map<ERDElement<?>, String> associations, XMLBuilder xml) throws IOException { final String entityId = "entity" + index; final EntityFigure entityFigure = entityPart.getFigure(); final Rectangle partBounds = entityPart.getBounds(); associations.put(entity, entityId); // node xml.startElement("node"); xml.addAttribute("id", entityId); { // Graph data xml.startElement("data"); xml.addAttribute("key", "nodegraph"); { // Generic node xml.startElement("y:GenericNode"); xml.addAttribute("configuration", "com.yworks.entityRelationship.big_entity"); // Geometry xml.startElement("y:Geometry"); xml.addAttribute("height", partBounds.height); xml.addAttribute("width", partBounds.width + getExtraTableLength(diagram, entity)); xml.addAttribute("x", partBounds.x()); xml.addAttribute("y", partBounds.y()); xml.endElement(); // Fill xml.startElement("y:Fill"); xml.addAttribute("color", getHtmlColor(entityFigure.getBackgroundColor())); //xml.addAttribute("color2", partBounds.width); xml.addAttribute("transparent", "false"); xml.endElement(); // Border xml.startElement("y:BorderStyle"); xml.addAttribute("color", getHtmlColor(entityFigure.getForegroundColor())); xml.addAttribute("type", "line"); xml.addAttribute("width", "1.0"); xml.endElement(); { // Entity Name Rectangle nameBounds = entityFigure.getNameLabel().getBounds(); xml.startElement("y:NodeLabel"); xml.addAttribute("alignment", "center"); xml.addAttribute("autoSizePolicy", "content"); xml.addAttribute("configuration", "com.yworks.entityRelationship.label.name"); xml.addAttribute("fontFamily", "Courier"); xml.addAttribute("fontSize", fontSize); xml.addAttribute("fontStyle", "plain"); xml.addAttribute("hasLineColor", "false"); xml.addAttribute("modelName", "internal"); xml.addAttribute("modelPosition", "t"); xml.addAttribute("backgroundColor", getHtmlColor(entityFigure.getNameLabel().getBackgroundColor())); xml.addAttribute("textColor", "#FFFFFF"); xml.addAttribute("visible", "true"); xml.addAttribute("horizontalTextPosition", "center"); xml.addAttribute("iconTextGap", "4"); xml.addAttribute("height", nameBounds.height); xml.addAttribute("width", nameBounds.width); xml.addAttribute("x", 0); xml.addAttribute("y", 4); xml.addText(entity.getName()); xml.endElement(); } { // Attributes AttributeListFigure columnsFigure = entityFigure.getColumnsFigure(); Rectangle attrsBounds = columnsFigure.getBounds(); xml.startElement("y:NodeLabel"); xml.addAttribute("alignment", "left"); xml.addAttribute("autoSizePolicy", "content"); xml.addAttribute("configuration", "com.yworks.entityRelationship.label.attributes"); xml.addAttribute("fontFamily", "Courier"); xml.addAttribute("fontSize", fontSize); xml.addAttribute("fontStyle", "plain"); xml.addAttribute("hasLineColor", "false"); xml.addAttribute("modelName", "custom"); xml.addAttribute("modelPosition", "t"); xml.addAttribute("backgroundColor", getHtmlColor(columnsFigure.getBackgroundColor())); xml.addAttribute("textColor", getHtmlColor(columnsFigure.getForegroundColor())); xml.addAttribute("visible", "true"); xml.addAttribute("horizontalTextPosition", "center"); xml.addAttribute("iconTextGap", "4"); xml.addAttribute("height", attrsBounds.height); xml.addAttribute("width", attrsBounds.width); xml.addAttribute("x", 2); //numbers from yEd Graph Editor xml.addAttribute("y", 31.66796875); StringBuilder attrsString = new StringBuilder(); for (ERDEntityAttribute attr : entity.getAttributes()) { if (attrsString.length() > 0) { attrsString.append("\n"); } attrsString.append(ERDUIUtils.getFullAttributeLabel(diagram, attr, true)); } xml.addText(attrsString.toString()); xml.startElement("y:LabelModel"); xml.startElement("y:ErdAttributesNodeLabelModel"); xml.endElement(); xml.endElement(); xml.startElement("y:ModelParameter"); xml.startElement("y:ErdAttributesNodeLabelModelParameter"); xml.endElement(); xml.endElement(); xml.endElement(); } xml.endElement(); } xml.endElement(); } xml.endElement(); } private static void exportNote(int index, ERDNote note, NotePart notePart, Map<ERDElement<?>, String> associations, XMLBuilder xml) throws IOException { final String noteId = "note" + index; final IFigure noteFigure = notePart.getFigure(); final Rectangle noteBounds = notePart.getBounds(); associations.put(note, noteId); xml.startElement("node"); { xml.addAttribute("id", noteId); xml.startElement("data"); { xml.addAttribute("key", "nodegraph"); xml.startElement("y:ShapeNode"); { xml.startElement("y:Geometry"); { xml.addAttribute("height", noteBounds.height); xml.addAttribute("width", noteBounds.width); xml.addAttribute("x", noteBounds.x()); xml.addAttribute("y", noteBounds.y()); } xml.endElement(); xml.startElement("y:Fill"); { xml.addAttribute("color", getHtmlColor(noteFigure.getBackgroundColor())); xml.addAttribute("transparent", "false"); } xml.endElement(); xml.startElement("y:BorderStyle"); { xml.addAttribute("color", getHtmlColor(noteFigure.getForegroundColor())); xml.addAttribute("type", "line"); xml.addAttribute("width", "1.0"); } xml.endElement(); xml.startElement("y:NodeLabel"); { xml.addAttribute("alignment", "left"); xml.addAttribute("autoSizePolicy", "content"); xml.addAttribute("fontFamily", "Courier"); xml.addAttribute("fontSize", fontSize); xml.addAttribute("fontStyle", "plain"); xml.addAttribute("hasLineColor", "false"); xml.addAttribute("modelName", "custom"); xml.addAttribute("modelPosition", "t"); xml.addAttribute("backgroundColor", getHtmlColor(noteFigure.getBackgroundColor())); xml.addAttribute("textColor", getHtmlColor(noteFigure.getForegroundColor())); xml.addAttribute("visible", "true"); xml.addAttribute("iconTextGap", "4"); xml.addAttribute("height", noteBounds.height); xml.addAttribute("width", noteBounds.width); xml.addAttribute("x", 2); xml.addAttribute("y", 2); xml.addText(note.getObject()); } xml.endElement(); } xml.endElement(); } xml.endElement(); } xml.endElement(); } private static void exportEdge(int index, ERDElement<?> node, NodePart nodePart, Map<ERDElement<?>, String> associations, XMLBuilder xml) throws IOException { for (ERDAssociation association : node.getAssociations()) { AssociationPart associationPart = nodePart.getConnectionPart(association, true); if (associationPart == null) { log.debug("Association part not found"); continue; } xml.startElement("edge"); xml.addAttribute("id", "edge" + index); xml.addAttribute("source", associations.get(node)); xml.addAttribute("target", associations.get(association.getTargetEntity())); xml.startElement("data"); xml.addAttribute("key", "edgegraph"); xml.startElement("y:PolyLineEdge"); xml.startElement("y:Path"); // sx="0.0" sy="0.0" tx="0.0" ty="0.0"/> xml.addAttribute("sx", 0.0); xml.addAttribute("sy", 0.0); xml.addAttribute("tx", 0.0); xml.addAttribute("ty", 0.0); for (Bendpoint bp : associationPart.getBendpoints()) { xml.startElement("y:Point"); xml.addAttribute("x", bp.getLocation().x); xml.addAttribute("y", bp.getLocation().y); xml.endElement(); } xml.endElement(); boolean identifying = ERDUtils.isIdentifyingAssociation(association); xml.startElement("y:LineStyle"); xml.addAttribute("color", "#000000"); xml.addAttribute("type", !identifying || association.isLogical() ? "dashed" : "line"); xml.addAttribute("width", "1.0"); xml.endElement(); xml.startElement("y:Arrows"); String sourceStyle = !identifying ? "white_diamond" : "none"; xml.addAttribute("source", sourceStyle); xml.addAttribute("target", "circle"); xml.endElement(); xml.startElement("y:BendStyle"); xml.addAttribute("smoothed", "false"); xml.endElement(); xml.endElement(); xml.endElement(); xml.endElement(); } } private static double getExtraTableLength(EntityDiagram diagram, ERDEntity entity) { int maxLength = 0; for (ERDEntityAttribute attr : entity.getAttributes()) { int attributeLength = (ERDUIUtils.getFullAttributeLabel(diagram, attr, true)).length(); if (attributeLength > maxLength) { maxLength = attributeLength; } } if (entity.getName().length() > maxLength){ maxLength = entity.getName().length(); } if (maxLength < 18) { // basic table size is enough maxLength = 0; } return (maxLength * (fontSize * 0.12)); } private static String getHtmlColor(Color color) { return "#" + getHexColor(color.getRed()) + getHexColor(color.getGreen()) + getHexColor(color.getBlue()); } private static String getHexColor(int value) { String hex = Integer.toHexString(value).toUpperCase(); return hex.length() < 2 ? "0" + hex : hex; } }
3e036fadb03ef07dbd631c7fa4227462a0974ae3
2,416
java
Java
pulse/auth/src/test/java/gov/ca/emsa/pulse/auth/jwt/JWTConsumerTest.java
pulse-admin/broker
9ba698866ab61bfc8528ab46fad760866e5efc15
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
pulse/auth/src/test/java/gov/ca/emsa/pulse/auth/jwt/JWTConsumerTest.java
pulse-admin/broker
9ba698866ab61bfc8528ab46fad760866e5efc15
[ "BSD-2-Clause-FreeBSD" ]
4
2016-06-28T18:24:17.000Z
2017-05-08T21:44:02.000Z
pulse/auth/src/test/java/gov/ca/emsa/pulse/auth/jwt/JWTConsumerTest.java
pulse-admin/broker
9ba698866ab61bfc8528ab46fad760866e5efc15
[ "BSD-2-Clause-FreeBSD" ]
5
2016-06-02T17:43:48.000Z
2018-01-15T19:19:06.000Z
30.582278
115
0.725166
1,406
package gov.ca.emsa.pulse.auth.jwt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //import io.jsonwebtoken.Jwts; //import io.jsonwebtoken.SignatureAlgorithm; import gov.ca.emsa.pulse.auth.authentication.JWTUserConverter; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { gov.ca.emsa.pulse.auth.TestConfig.class }) public class JWTConsumerTest { @Autowired private JWTAuthor jwtAuthor; @Autowired private JWTConsumer jwtConsumer; @Autowired @Qualifier("RsaJose4JWebKey") JSONWebKey jwk; @Autowired JWTUserConverter jwtUserConverter; @Autowired Environment env; @Autowired JSONWebKey jsonWebKey; @Test public void consumerIsNotNull() { assertNotNull(jwtConsumer); } @Test public void testConsumer() throws Exception { Map<String, Object> claims = new HashMap<String, Object>(); List<String> authorities = new ArrayList<String>(); authorities.add("ROLE_SUPERSTAR"); claims.put(JWTUserConverter.AUTHORITIES, authorities); Map<String, Long> orgs = new HashMap<String, Long>(); orgs.put("pulse_us", 1L); orgs.put("pulse_va", 2L); orgs.put("va_acf", 3L); claims.put(JWTUserConverter.ORGANIZATIONS, orgs); String jwt = jwtAuthor.createJWT("testsubject", claims); Map<String, Object> claimObjects = jwtConsumer.consume(jwt); List<String> recoveredAuthorities = (List<String>) claimObjects.get(JWTUserConverter.AUTHORITIES); assertEquals(authorities.get(0), recoveredAuthorities.get(0)); Map<String, Object> recoveredOrgs = (Map<String, Object>) claimObjects.get(JWTUserConverter.ORGANIZATIONS); assertEquals(orgs.get(0), recoveredOrgs.get(0)); assertEquals(orgs.get(1), recoveredOrgs.get(1)); assertEquals(orgs.get(2), recoveredOrgs.get(2)); } }
3e03702c86644e0c8b155d713782704e552bfc59
2,809
java
Java
endpoints/citrus-http/src/main/java/com/consol/citrus/http/model/FormData.java
zauggmori/citrus
a7422540e5b7396adfb19defaf33401e0bf61467
[ "Apache-2.0" ]
177
2018-05-18T20:48:00.000Z
2022-03-21T12:23:55.000Z
endpoints/citrus-http/src/main/java/com/consol/citrus/http/model/FormData.java
zauggmori/citrus
a7422540e5b7396adfb19defaf33401e0bf61467
[ "Apache-2.0" ]
432
2018-05-16T21:56:38.000Z
2022-03-16T13:19:45.000Z
endpoints/citrus-http/src/main/java/com/consol/citrus/http/model/FormData.java
zauggmori/citrus
a7422540e5b7396adfb19defaf33401e0bf61467
[ "Apache-2.0" ]
71
2018-06-18T11:42:55.000Z
2021-12-27T12:10:59.000Z
22.653226
76
0.606622
1,408
/* * Copyright 2006-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.http.model; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * @author Christoph Deppisch */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "contentType", "action", "controls" }) @XmlRootElement(name = "form-data") public class FormData { @XmlElement(name = "content-type") protected String contentType; @XmlElement protected String action; @XmlElement(required = true) protected FormData.Controls controls; /** * Gets the content type. * @return */ public String getContentType() { return contentType; } /** * Sets the content type. * @param contentType */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Gets the action. * @return */ public String getAction() { return action; } /** * Sets the action. * @param action */ public void setAction(String action) { this.action = action; } /** * Gets the controls. * @return */ public FormData.Controls getControls() { return controls; } /** * Sets the controls. * @param controls */ public void setControls(FormData.Controls controls) { this.controls = controls; } /** * Adds new form control. * @param control */ public void addControl(Control control) { if (controls == null) { controls = new FormData.Controls(); } this.controls.add(control); } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "controls" }) @XmlSeeAlso({ Control.class }) public static class Controls { @XmlElement(name = "control", required = true) protected List<Control> controls = new ArrayList<Control>(); public List<Control> getControls() { return this.controls; } public void add(Control control) { this.controls.add(control); } } }
3e0371783117ffca8d38f53f85eccc62225d5cce
10,703
java
Java
src/test/java/systemtests/AddressBookSystemTest.java
jcjxwy/main
ba82f4bb7cdb2a71c4eeda01fc0d5e0c6b3be233
[ "MIT" ]
null
null
null
src/test/java/systemtests/AddressBookSystemTest.java
jcjxwy/main
ba82f4bb7cdb2a71c4eeda01fc0d5e0c6b3be233
[ "MIT" ]
1
2018-10-17T13:53:47.000Z
2018-10-17T13:53:47.000Z
src/test/java/systemtests/AddressBookSystemTest.java
jcjxwy/main
ba82f4bb7cdb2a71c4eeda01fc0d5e0c6b3be233
[ "MIT" ]
null
null
null
38.225
119
0.719985
1,409
package systemtests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.ui.StatusBarFooter.SYNC_STATUS_UPDATED; import static seedu.address.ui.testutil.GuiTestAssert.assertListMatching; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Date; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import guitests.guihandles.BudgetPanelHandle; import guitests.guihandles.CommandBoxHandle; import guitests.guihandles.ExpenseListPanelHandle; import guitests.guihandles.MainMenuHandle; import guitests.guihandles.MainWindowHandle; import guitests.guihandles.ResultDisplayHandle; import guitests.guihandles.StatusBarFooterHandle; import seedu.address.TestApp; import seedu.address.commons.core.EventsCenter; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.model.AddressBook; import seedu.address.model.Model; import seedu.address.model.exceptions.NoUserSelectedException; import seedu.address.testutil.TypicalExpenses; import seedu.address.ui.CommandBox; /** * A system test class for AddressBook, which provides access to handles of GUI components and helper methods * for test verification. */ public abstract class AddressBookSystemTest { @ClassRule public static ClockRule clockRule = new ClockRule(); private static final List<String> COMMAND_BOX_DEFAULT_STYLE = Arrays.asList("text-input", "text-field"); private static final List<String> COMMAND_BOX_ERROR_STYLE = Arrays.asList("text-input", "text-field", CommandBox.ERROR_STYLE_CLASS); protected TestApp testApp; private MainWindowHandle mainWindowHandle; private SystemTestSetupHelper setupHelper; @BeforeClass public static void setupBeforeClass() { SystemTestSetupHelper.initialize(); } @Before public void setUp() throws NoUserSelectedException { setupHelper = new SystemTestSetupHelper(); testApp = setupHelper.setupApplication(this::getInitialData, getDataFileLocation()); mainWindowHandle = setupHelper.setupMainWindowHandle(); assertApplicationStartingStateIsCorrect(); } @After public void tearDown() { setupHelper.tearDownStage(); EventsCenter.clearSubscribers(); } /** * Returns the data to be loaded into the file in {@link #getDataFileLocation()}. */ protected AddressBook getInitialData() { return TypicalExpenses.getTypicalAddressBook(); } /** * Returns the directory of the data file. */ protected Path getDataFileLocation() { return TestApp.SAVE_LOCATION_FOR_TESTING; } public MainWindowHandle getMainWindowHandle() { return mainWindowHandle; } public CommandBoxHandle getCommandBox() { return mainWindowHandle.getCommandBox(); } public ExpenseListPanelHandle getExpenseListPanel() { return mainWindowHandle.getExpenseListPanel(); } public MainMenuHandle getMainMenu() { return mainWindowHandle.getMainMenu(); } public StatusBarFooterHandle getStatusBarFooter() { return mainWindowHandle.getStatusBarFooter(); } public ResultDisplayHandle getResultDisplay() { return mainWindowHandle.getResultDisplay(); } public BudgetPanelHandle getBudgetPanel() { return mainWindowHandle.getBudgetPanel(); } /** * Executes {@code command} in the application's {@code CommandBox}. * Method returns after UI components have been updated. */ protected void executeCommand(String command) { rememberStates(); // Injects a fixed clock before executing a command so that the time stamp shown in the status bar // after each command is predictable and also different from the previous command. clockRule.setInjectedClockToCurrentTime(); mainWindowHandle.getCommandBox().run(command); } /** * Displays all expenses in the address book. */ protected void showAllExpenses() throws NoUserSelectedException { executeCommand(ListCommand.COMMAND_WORD); assertEquals(getModel().getAddressBook().getExpenseList().size(), getModel().getFilteredExpenseList().size()); } /** * Displays all expenses with any parts of their names matching {@code keyword} (case-insensitive). */ protected void showExpensesWithName(String keyword) throws NoUserSelectedException { executeCommand(FindCommand.COMMAND_WORD + " " + keyword); assertTrue(getModel().getFilteredExpenseList().size() < getModel().getAddressBook().getExpenseList().size()); } /** * Selects the expense at {@code index} of the displayed list. */ protected void selectExpense(Index index) { executeCommand(SelectCommand.COMMAND_WORD + " " + index.getOneBased()); assertEquals(index.getZeroBased(), getExpenseListPanel().getSelectedCardIndex()); } /** * Deletes all expenses in the address book. */ protected void deleteAllExpenses() throws NoUserSelectedException { executeCommand(ClearCommand.COMMAND_WORD); try { Thread.sleep(1000); assertTrue(getBudgetPanel().isExpenseCorrect("0.00")); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(0, getModel().getAddressBook().getExpenseList().size()); } /** * Asserts that the {@code CommandBox} displays {@code expectedCommandInput}, the {@code ResultDisplay} displays * {@code expectedResultMessage}, the storage contains the same expense objects as {@code expectedModel} * and the expense list panel displays the expenses in the model correctly. */ protected void assertApplicationDisplaysExpected(String expectedCommandInput, String expectedResultMessage, Model expectedModel) throws NoUserSelectedException { assertEquals(expectedCommandInput, getCommandBox().getInput()); assertEquals(expectedResultMessage, getResultDisplay().getText()); assertEquals(new AddressBook(expectedModel.getAddressBook()), testApp.readStorageAddressBook()); assertListMatching(getExpenseListPanel(), expectedModel.getFilteredExpenseList()); } /** * Calls {@code BrowserPanelHandle}, {@code ExpenseListPanelHandle} and {@code StatusBarFooterHandle} to remember * their current state. */ private void rememberStates() { StatusBarFooterHandle statusBarFooterHandle = getStatusBarFooter(); statusBarFooterHandle.rememberSaveLocation(); statusBarFooterHandle.rememberSyncStatus(); getExpenseListPanel().rememberSelectedExpenseCard(); } /** * Asserts that the previously selected card is now deselected and the browser's url remains displaying the details * of the previously selected expense. */ protected void assertSelectedCardDeselected() { assertFalse(getExpenseListPanel().isAnyCardSelected()); } /** * Asserts that the browser's url is changed to display the details of the expense in the expense list panel at * {@code expectedSelectedCardIndex}, and only the card at {@code expectedSelectedCardIndex} is selected. * @see ExpenseListPanelHandle#isSelectedExpenseCardChanged() */ protected void assertSelectedCardChanged(Index expectedSelectedCardIndex) { getExpenseListPanel().navigateToCard(getExpenseListPanel().getSelectedCardIndex()); assertEquals(expectedSelectedCardIndex.getZeroBased(), getExpenseListPanel().getSelectedCardIndex()); } /** * Asserts that the browser's url and the selected card in the expense list panel remain unchanged. * @see ExpenseListPanelHandle#isSelectedExpenseCardChanged() */ protected void assertSelectedCardUnchanged() { assertFalse(getExpenseListPanel().isSelectedExpenseCardChanged()); } /** * Asserts that the command box's shows the default style. */ protected void assertCommandBoxShowsDefaultStyle() { assertEquals(COMMAND_BOX_DEFAULT_STYLE, getCommandBox().getStyleClass()); } /** * Asserts that the command box's shows the error style. */ protected void assertCommandBoxShowsErrorStyle() { assertEquals(COMMAND_BOX_ERROR_STYLE, getCommandBox().getStyleClass()); } /** * Asserts that the entire status bar remains the same. */ protected void assertStatusBarUnchanged() { StatusBarFooterHandle handle = getStatusBarFooter(); assertFalse(handle.isSaveLocationChanged()); assertFalse(handle.isSyncStatusChanged()); } /** * Asserts that only the sync status in the status bar was changed to the timing of * {@code ClockRule#getInjectedClock()}, while the save location remains the same. */ protected void assertStatusBarUnchangedExceptSyncStatus() { StatusBarFooterHandle handle = getStatusBarFooter(); String timestamp = new Date(clockRule.getInjectedClock().millis()).toString(); String expectedSyncStatus = String.format(SYNC_STATUS_UPDATED, timestamp); assertEquals(expectedSyncStatus, handle.getSyncStatus()); assertFalse(handle.isSaveLocationChanged()); } /** * Asserts that the starting state of the application is correct. */ private void assertApplicationStartingStateIsCorrect() throws NoUserSelectedException { assertEquals("", getCommandBox().getInput()); assertEquals("", getResultDisplay().getText()); //assertListMatching(getExpenseListPanel(), getModel().getFilteredExpenseList()); assertEquals(Paths.get(".").resolve(testApp.getStorageSaveLocation()).toString(), getStatusBarFooter().getSaveLocation()); /*assertTrue(getBudgetPanel().isExpenseCorrect(String.format("%.2f", TypicalExpenses.INTIIAL_EXPENSES))); assertTrue(getBudgetPanel().isBudgetCorrect(String.format("%.2f", TypicalExpenses.INTIIAL_BUDGET))); assertTrue(getBudgetPanel().isBudgetBarProgressAccurate(TypicalExpenses.INTIIAL_EXPENSES / TypicalExpenses.INTIIAL_BUDGET));*/ } /** * Returns a copy of the current model. */ protected Model getModel() { return testApp.getModel(); } }
3e0372c54dda1b0405036515b8dceec2234846cc
9,082
java
Java
app/src/main/java/com/bisa/health/cust/view/CustReportDialog.java
BISAECG/BisaRealTimeProject
d6053aaf18e5bd2b17440955a34c2c3517a5bbef
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bisa/health/cust/view/CustReportDialog.java
BISAECG/BisaRealTimeProject
d6053aaf18e5bd2b17440955a34c2c3517a5bbef
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bisa/health/cust/view/CustReportDialog.java
BISAECG/BisaRealTimeProject
d6053aaf18e5bd2b17440955a34c2c3517a5bbef
[ "Apache-2.0" ]
null
null
null
31.209622
117
0.630588
1,410
package com.bisa.health.cust.view; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.bisa.health.R; import static java.lang.Integer.parseInt; /** * Created by Administrator on 2017/11/29. */ public class CustReportDialog extends Dialog { private Context context; private View view; private int centerX; private int centerY; private int depthZ = 700; private int duration = 150; private Rotate3dAnimation openAnimation; private Rotate3dAnimation closeAnimation; private boolean isOpen = false; private FrameLayout dialog_view_main; private RelativeLayout rl_main; private RelativeLayout rl_main_daily; private RelativeLayout rl_main_all; /* 报告类型 */ private RelativeLayout rl_daily; private RelativeLayout rl_all; private Button btnDaily; private Button btnAll; private OnClickListenerInterface mListener; public static interface OnClickListenerInterface { /** * 确认, */ void doConfirm(int rType) throws RemoteException; /** * 取消 */ // public void doCancel(); } public CustReportDialog(Context context) { super(context); this.context = context; } @Override public void show() { if(rl_main!=null){ rl_main.setVisibility(View.VISIBLE); rl_main_daily.setVisibility(View.GONE); rl_main_all.setVisibility(View.GONE); } super.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去掉系统的黑色矩形边框 getWindow().setBackgroundDrawableResource(android.R.color.transparent); requestWindowFeature(Window.FEATURE_NO_TITLE); init(); } public void init() { LayoutInflater inflater = LayoutInflater.from(context); view = inflater.inflate(R.layout.dialog_report_main, null); setContentView(view); //父容器 dialog_view_main=(FrameLayout) view.findViewById(R.id.dialog_view_main); //报告类型 rl_main= (RelativeLayout) view.findViewById(R.id.rl_main); //免费报告 rl_main_daily= (RelativeLayout) view.findViewById(R.id.rl_main_daily); //OTG报告 rl_main_all= (RelativeLayout) view.findViewById(R.id.rl_main_all); rl_daily= (RelativeLayout) view.findViewById(R.id.rl_daily); rl_daily.setOnClickListener(new OnWidgetClickListener()); rl_all= (RelativeLayout) view.findViewById(R.id.rl_all); rl_all.setOnClickListener(new OnWidgetClickListener()); btnDaily= (Button) view.findViewById(R.id.btn_commit_report_daily); btnDaily.setOnClickListener(new OnWidgetClickListener()); btnAll= (Button) view.findViewById(R.id.btn_commit_report_all); btnAll.setOnClickListener(new OnWidgetClickListener()); Window dialogWindow = getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用 // lp.width = (int) (d.widthPixels * 0.8); // 高度设置为屏幕的0.6 // lp.height = (int) (d.heightPixels * 0.6); // 高度设置为屏幕的0.6 WindowManager.LayoutParams layoutParams= new WindowManager.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); dialogWindow.setAttributes(lp); setCanceledOnTouchOutside(false); setCancelable(true); } public void setClicklistener(OnClickListenerInterface clickListenerInterface) { this.mListener = clickListenerInterface; } private class OnWidgetClickListener implements View.OnClickListener { @Override public void onClick(View v) { int rType= parseInt(v.getTag().toString()); int id = v.getId(); switch (id) { case R.id.rl_daily: startAnimation(rl_main,rl_main_daily); break; case R.id.rl_all: startAnimation(rl_main,rl_main_all); break; case R.id.btn_commit_report_daily: case R.id.btn_commit_report_all: try { mListener.doConfirm(rType); } catch (RemoteException e) { e.printStackTrace(); } break; } } } private void startAnimation(final View inView,final View outView) { //接口回调传递参数 // mListener.doConfirm(); // centerX = mContainer.getWidth() / 2; // centerY = mContainer.getHeight() / 2; centerX = rl_main.getWidth() / 2; centerY = rl_main.getHeight() / 2; // if (openAnimation != null) { Log.i("----","out View2:"+outView.getId()); initOpenAnim(inView,outView); initCloseAnim(inView,outView); // } //用作判断当前点击事件发生时动画是否正在执行 if (openAnimation.hasStarted() && !openAnimation.hasEnded()) { return; } if (closeAnimation.hasStarted() && !closeAnimation.hasEnded()) { return; } //判断动画执行 if (isOpen) { dialog_view_main.startAnimation(openAnimation); } else { dialog_view_main.startAnimation(closeAnimation); } isOpen = !isOpen; } /** * 卡牌文本介绍打开效果:注意旋转角度 */ private void initOpenAnim(final View inView,final View outView) { //从0到90度,顺时针旋转视图,此时reverse参数为true,达到90度时动画结束时视图变得不可见, openAnimation = new Rotate3dAnimation(0, 90, centerX, centerY, depthZ, true); openAnimation.setDuration(duration); openAnimation.setFillAfter(true); openAnimation.setInterpolator(new AccelerateInterpolator()); openAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { inView.setVisibility(View.GONE); outView.setVisibility(View.VISIBLE); //从270到360度,顺时针旋转视图,此时reverse参数为false,达到360度动画结束时视图变得可见 Rotate3dAnimation rotateAnimation = new Rotate3dAnimation(270, 360, centerX, centerY, depthZ, false); rotateAnimation.setDuration(duration); rotateAnimation.setFillAfter(true); rotateAnimation.setInterpolator(new DecelerateInterpolator()); dialog_view_main.startAnimation(rotateAnimation); } }); } /** * 卡牌文本介绍关闭效果:旋转角度与打开时逆行即可 */ private void initCloseAnim(final View inView,final View outView) { closeAnimation = new Rotate3dAnimation(360, 270, centerX, centerY, depthZ, true); closeAnimation.setDuration(duration); closeAnimation.setFillAfter(true); closeAnimation.setInterpolator(new AccelerateInterpolator()); closeAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { // rl_main_daily.setVisibility(View.VISIBLE); // rl_main.setVisibility(View.GONE); outView.setVisibility(View.VISIBLE); inView.setVisibility(View.GONE); Rotate3dAnimation rotateAnimation = new Rotate3dAnimation(90, 0, centerX, centerY, depthZ, false); rotateAnimation.setDuration(duration); rotateAnimation.setFillAfter(true); rotateAnimation.setInterpolator(new DecelerateInterpolator()); dialog_view_main.startAnimation(rotateAnimation); } }); } // 改变视角距离, 贴近屏幕 private void setCameraDistance() { int distance = 16000; float scale = this.context.getResources().getDisplayMetrics().density * distance; dialog_view_main.setCameraDistance(scale); rl_main.setCameraDistance(scale); rl_daily.setCameraDistance(scale); rl_all.setCameraDistance(scale); } }
3e0372d86b499663edb36f7717153fcf73e4d4d3
4,009
java
Java
android/src/main/java/com/centaurwarchief/smslistener/SmsReceiver.java
hengkx/react-native-android-sms-listener
b47fd15eef6efb2ba884bf5831313410a8212726
[ "MIT" ]
2
2020-04-22T11:34:53.000Z
2020-08-19T08:21:28.000Z
android/src/main/java/com/centaurwarchief/smslistener/SmsReceiver.java
hengkx/react-native-android-sms-listener
b47fd15eef6efb2ba884bf5831313410a8212726
[ "MIT" ]
null
null
null
android/src/main/java/com/centaurwarchief/smslistener/SmsReceiver.java
hengkx/react-native-android-sms-listener
b47fd15eef6efb2ba884bf5831313410a8212726
[ "MIT" ]
1
2021-11-03T09:31:26.000Z
2021-11-03T09:31:26.000Z
34.264957
86
0.605388
1,411
package com.centaurwarchief.smslistener; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.provider.Telephony; import android.telephony.SmsMessage; import android.util.Log; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class SmsReceiver extends BroadcastReceiver { private ReactApplicationContext mContext; private static final String EVENT = "com.centaurwarchief.smslistener:smsReceived"; public SmsReceiver() { super(); } public SmsReceiver(ReactApplicationContext context) { mContext = context; } private void receiveMessages(SmsMessage[] messages) throws Exception { if (mContext == null || messages == null) { return; } if (!mContext.hasActiveCatalystInstance()) { return; } Class ownerClass = Class.forName("android.telephony.SmsMessage"); Method method = ownerClass.getMethod("getSubId"); Map<String, String> msg = new HashMap<String, String>(messages.length); Map<String, Integer> msgSubId = new HashMap<String, Integer>(messages.length); Map<String, Long> msgTime = new HashMap<String, Long>(messages.length); for (SmsMessage message : messages) { String originatingAddress = message.getOriginatingAddress(); // Check if index with number exists if (!msg.containsKey(originatingAddress)) { msg.put(originatingAddress, message.getMessageBody()); int subId = (int) method.invoke(message); msgSubId.put(originatingAddress, subId); msgTime.put(originatingAddress, message.getTimestampMillis()); } else { String previousParts = msg.get(originatingAddress); String msgString = previousParts + message.getMessageBody(); msg.put(originatingAddress, msgString); } } for (String sender : msg.keySet()) { Log.d( SmsListenerPackage.TAG, String.format("%s: %s", sender, msg.get(sender)) ); WritableNativeMap receivedMessage = new WritableNativeMap(); receivedMessage.putString("originatingAddress", sender); receivedMessage.putString("body", msg.get(sender)); receivedMessage.putDouble("time", msgTime.get(sender)); receivedMessage.putInt("subId", msgSubId.get(sender)); mContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(EVENT, receivedMessage); } } @Override public void onReceive(Context context, Intent intent) { SmsMessage[] messages = null; ; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { messages = Telephony.Sms.Intents.getMessagesFromIntent(intent); } else { try { final Bundle bundle = intent.getExtras(); if (bundle == null || !bundle.containsKey("pdus")) { return; } final Object[] pdus = (Object[]) bundle.get("pdus"); messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { byte[] pdu = (byte[]) pdus[i]; messages[i] = SmsMessage.createFromPdu(pdu); } } catch (Exception e) { Log.e(SmsListenerPackage.TAG, e.getMessage()); } } try { receiveMessages(messages); } catch (Exception e) { e.printStackTrace(); } } }