hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e04cf70ab8644e9230422a3c37b9194f76befab
976
java
Java
junit-jupiter/src/integTest/java/com/tngtech/test/junit/dataprovider/custom/meta/DataProviderLocation.java
mseibt/junit-dataprovider
bcc612fd5e06d9dfd419cab5358226268ae38ed6
[ "Apache-2.0" ]
238
2015-01-14T17:28:29.000Z
2022-03-13T11:11:02.000Z
junit-jupiter/src/integTest/java/com/tngtech/test/junit/dataprovider/custom/meta/DataProviderLocation.java
mseibt/junit-dataprovider
bcc612fd5e06d9dfd419cab5358226268ae38ed6
[ "Apache-2.0" ]
96
2015-01-09T15:17:05.000Z
2022-03-11T13:46:15.000Z
junit-jupiter/src/integTest/java/com/tngtech/test/junit/dataprovider/custom/meta/DataProviderLocation.java
mseibt/junit-dataprovider
bcc612fd5e06d9dfd419cab5358226268ae38ed6
[ "Apache-2.0" ]
50
2015-01-09T04:24:46.000Z
2022-02-23T03:37:18.000Z
24.4
62
0.418033
2,013
package com.tngtech.test.junit.dataprovider.custom.meta; import static com.tngtech.junit.dataprovider.DataProviders.$; import static com.tngtech.junit.dataprovider.DataProviders.$$; import com.tngtech.junit.dataprovider.DataProvider; class DataProviderLocation { @DataProvider static Object[][] dataProviderAdd() { //@formatter:off return new Object[][] { { 0, 0, 0 }, { 0, 1, 1 }, { 1, 0, 1 }, { 1, 1, 2 }, { 0, -1, -1 }, { -1, -1, -2 }, }; //@formatter:on } @DataProvider static Object[][] dataProviderMinus() { // @formatter:off return $$( $( 0, 0, 0 ), $( 0, 1, -1 ), $( 0, -1, 1 ), $( 1, 0, 1 ), $( 1, 1, 0 ), $( -1, 0, -1 ), $( -1, -1, 0 ) ); // @formatter:on } }
3e04cf9cac1f9eb948afe70cfba475808c8de1d9
22,377
java
Java
test/com/facebook/buck/artifact_cache/ThriftArtifactCacheTest.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/artifact_cache/ThriftArtifactCacheTest.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/artifact_cache/ThriftArtifactCacheTest.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
42.541825
105
0.710864
2,014
/* * 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.artifact_cache; import static com.facebook.buck.artifact_cache.thrift.ContainsResultType.CONTAINS; import static com.facebook.buck.artifact_cache.thrift.ContainsResultType.DOES_NOT_CONTAIN; import static com.facebook.buck.artifact_cache.thrift.ContainsResultType.UNKNOWN_DUE_TO_TRANSIENT_ERRORS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.facebook.buck.artifact_cache.config.ArtifactCacheMode; import com.facebook.buck.artifact_cache.config.CacheReadMode; import com.facebook.buck.artifact_cache.thrift.ArtifactMetadata; import com.facebook.buck.artifact_cache.thrift.BuckCacheDeleteResponse; import com.facebook.buck.artifact_cache.thrift.BuckCacheFetchResponse; import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiContainsResponse; import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiFetchResponse; import com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType; import com.facebook.buck.artifact_cache.thrift.BuckCacheResponse; import com.facebook.buck.artifact_cache.thrift.ContainsResult; import com.facebook.buck.artifact_cache.thrift.FetchResult; import com.facebook.buck.artifact_cache.thrift.FetchResultType; import com.facebook.buck.artifact_cache.thrift.PayloadInfo; import com.facebook.buck.artifact_cache.thrift.RuleKey; import com.facebook.buck.core.cell.CellPathResolver; import com.facebook.buck.core.cell.TestCellPathResolver; import com.facebook.buck.core.model.BuildId; import com.facebook.buck.core.model.TargetConfigurationSerializerForTests; import com.facebook.buck.core.parser.buildtargetparser.ParsingUnconfiguredBuildTargetViewFactory; import com.facebook.buck.event.BuckEventBusForTests; import com.facebook.buck.io.file.LazyPath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.slb.HttpResponse; import com.facebook.buck.slb.HttpService; import com.facebook.buck.slb.ThriftException; import com.facebook.buck.slb.ThriftUtil; import com.facebook.buck.testutil.TemporaryPaths; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; import org.apache.thrift.TBase; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; public class ThriftArtifactCacheTest { @Rule public TemporaryPaths tempPaths = new TemporaryPaths(); @Test public void testFetchResponseWithoutPayloadInfo() throws IOException { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.addToRuleKeys(new RuleKey().setHashString("012345")); testWithMetadataAndPayloadInfo(metadata, false); } @Test public void testFetchResponseWithCorruptedRuleKeys() throws IOException { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.addToRuleKeys(new RuleKey().setHashString("123\uFFFF")); testWithMetadata(metadata); } @Test public void testFetchResponseWithUnevenRuleKeyHash() throws IOException { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.addToRuleKeys(new RuleKey().setHashString("akjdasadasdas")); testWithMetadata(metadata); } @Test public void testFetchResponseWithEmptyMetadata() throws IOException { testWithMetadata(new ArtifactMetadata()); } @Test public void testFetchResponseWithoutMetadata() throws IOException { testWithMetadata(null); } private void testWithMetadata(@Nullable ArtifactMetadata artifactMetadata) throws IOException { testWithMetadataAndPayloadInfo(artifactMetadata, true); } private void testWithMetadataAndPayloadInfo( @Nullable ArtifactMetadata artifactMetadata, boolean setPayloadInfo) throws IOException { HttpService storeClient = new TestHttpService(); TestHttpService fetchClient = new TestHttpService( () -> makeResponseWithCorruptedRuleKeys(artifactMetadata, setPayloadInfo)); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tempPaths.getRoot()); ListeningExecutorService service = MoreExecutors.newDirectExecutorService(); CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem); NetworkCacheArgs networkArgs = ImmutableNetworkCacheArgs.builder() .setCacheName("default_cache_name") .setRepository("default_repository") .setCacheReadMode(CacheReadMode.READONLY) .setCacheMode(ArtifactCacheMode.thrift_over_http) .setScheduleType("default_schedule_type") .setTargetConfigurationSerializer( TargetConfigurationSerializerForTests.create(cellPathResolver)) .setUnconfiguredBuildTargetFactory( target -> new ParsingUnconfiguredBuildTargetViewFactory() .create(target, cellPathResolver.getCellNameResolver())) .setProjectFilesystem(filesystem) .setFetchClient(fetchClient) .setStoreClient(storeClient) .setBuckEventBus(BuckEventBusForTests.newInstance()) .setHttpWriteExecutorService(service) .setHttpFetchExecutorService(service) .setErrorTextTemplate("my super error msg") .setErrorTextLimit(100) .build(); try (ThriftArtifactCache cache = new ThriftArtifactCache( networkArgs, "/nice_as_well", new BuildId("aabb"), 0, 0, false, "test://", "hostname")) { Path artifactPath = tempPaths.newFile().toAbsolutePath(); CacheResult result = Futures.getUnchecked( cache.fetchAsync( null, new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(42)), LazyPath.ofInstance(artifactPath))); assertEquals(CacheResultType.ERROR, result.getType()); } assertEquals(1, fetchClient.getCallsCount()); } private HttpResponse makeResponseWithCorruptedRuleKeys( @Nullable ArtifactMetadata artifactMetadata, boolean setPayloadInfo) { BuckCacheFetchResponse fetchResponse = new BuckCacheFetchResponse().setArtifactExists(true); if (artifactMetadata != null) { fetchResponse.setMetadata(artifactMetadata); } BuckCacheResponse response = new BuckCacheResponse() .setWasSuccessful(true) .setType(BuckCacheRequestType.FETCH) .setFetchResponse(fetchResponse); if (setPayloadInfo) { PayloadInfo payloadInfo = new PayloadInfo().setSizeBytes(0); response.addToPayloads(payloadInfo); } return new InMemoryThriftResponse(response); } private static class InMemoryThriftResponse implements HttpResponse { private byte[] response; public InMemoryThriftResponse(TBase<?, ?> thrift, byte[]... payloads) { byte[] serializedThrift = null; try { serializedThrift = ThriftUtil.serialize(ThriftArtifactCache.PROTOCOL, thrift); } catch (ThriftException e) { throw new RuntimeException(e); } ByteBuffer buffer = ByteBuffer.allocate( 4 + serializedThrift.length + Arrays.stream(payloads).mapToInt(p -> p.length).reduce(0, (l, r) -> l + r)); buffer.order(ByteOrder.BIG_ENDIAN); buffer.putInt(serializedThrift.length); buffer.put(serializedThrift); for (byte[] payload : payloads) { buffer.put(payload); } response = buffer.array(); } @Override public int statusCode() { return 200; } @Override public String statusMessage() { return ""; } @Override public long contentLength() { return response.length; } @Override public InputStream getBody() { return new ByteArrayInputStream(response); } @Override public String requestUrl() { return ""; } @Override public void close() {} } @Test public void testMultiFetch() throws IOException { AtomicReference<BuckCacheResponse> responseRef = new AtomicReference<>(); AtomicReference<byte[]> payload1Ref = new AtomicReference<>(); AtomicReference<byte[]> payload3Ref = new AtomicReference<>(); HttpService storeClient = new TestHttpService(); TestHttpService fetchClient = new TestHttpService( () -> new InMemoryThriftResponse( responseRef.get(), payload1Ref.get(), payload3Ref.get())); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tempPaths.getRoot()); ListeningExecutorService service = MoreExecutors.newDirectExecutorService(); CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem); NetworkCacheArgs networkArgs = ImmutableNetworkCacheArgs.builder() .setCacheName("default_cache_name") .setRepository("default_repository") .setCacheReadMode(CacheReadMode.READONLY) .setCacheMode(ArtifactCacheMode.thrift_over_http) .setScheduleType("default_schedule_type") .setTargetConfigurationSerializer( TargetConfigurationSerializerForTests.create(cellPathResolver)) .setUnconfiguredBuildTargetFactory( target -> new ParsingUnconfiguredBuildTargetViewFactory() .create(target, cellPathResolver.getCellNameResolver())) .setProjectFilesystem(filesystem) .setFetchClient(fetchClient) .setStoreClient(storeClient) .setBuckEventBus(BuckEventBusForTests.newInstance()) .setHttpWriteExecutorService(service) .setHttpFetchExecutorService(service) .setErrorTextTemplate("my super error msg") .setErrorTextLimit(100) .build(); // 0 -> Miss, 1 -> Hit, 2 -> Skip, 3 -> Hit. Path output0 = filesystem.getPath("output0"); Path output1 = filesystem.getPath("output1"); Path output2 = filesystem.getPath("output2"); Path output3 = filesystem.getPath("output3"); SettableFuture<CacheResult> future = SettableFuture.create(); com.facebook.buck.core.rulekey.RuleKey key0 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(0)); com.facebook.buck.core.rulekey.RuleKey key1 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(1)); com.facebook.buck.core.rulekey.RuleKey key2 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(2)); com.facebook.buck.core.rulekey.RuleKey key3 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(3)); ImmutableList<AbstractAsynchronousCache.FetchRequest> requests = ImmutableList.of( new AbstractAsynchronousCache.FetchRequest( null, key0, LazyPath.ofInstance(output0), future), new AbstractAsynchronousCache.FetchRequest( null, key1, LazyPath.ofInstance(output1), future), new AbstractAsynchronousCache.FetchRequest( null, key2, LazyPath.ofInstance(output2), future), new AbstractAsynchronousCache.FetchRequest( null, key3, LazyPath.ofInstance(output3), future)); String payload1 = "payload1"; String payload3 = "bigger payload3"; byte[] payloadBytes1 = payload1.getBytes(Charsets.UTF_8); payload1Ref.set(payloadBytes1); byte[] payloadBytes3 = payload3.getBytes(Charsets.UTF_8); payload3Ref.set(payloadBytes3); ArtifactMetadata metadata1 = new ArtifactMetadata(); metadata1.addToRuleKeys(new RuleKey().setHashString(key1.getHashCode().toString())); metadata1.setArtifactPayloadMd5(Hashing.md5().hashBytes(payloadBytes1).toString()); metadata1.setMetadata(ImmutableMap.of()); ArtifactMetadata metadata3 = new ArtifactMetadata(); metadata3.addToRuleKeys(new RuleKey().setHashString(key3.getHashCode().toString())); metadata3.setArtifactPayloadMd5(Hashing.md5().hashBytes(payloadBytes3).toString()); metadata3.setMetadata(ImmutableMap.of()); BuckCacheMultiFetchResponse multiFetchResponse = new BuckCacheMultiFetchResponse(); FetchResult result0 = new FetchResult().setResultType(FetchResultType.MISS); FetchResult result1 = new FetchResult().setResultType(FetchResultType.HIT).setMetadata(metadata1); FetchResult result2 = new FetchResult().setResultType(FetchResultType.SKIPPED); FetchResult result3 = new FetchResult().setResultType(FetchResultType.HIT).setMetadata(metadata3); multiFetchResponse.addToResults(result0); multiFetchResponse.addToResults(result1); multiFetchResponse.addToResults(result2); multiFetchResponse.addToResults(result3); PayloadInfo payloadInfo1 = new PayloadInfo().setSizeBytes(payloadBytes1.length); PayloadInfo payloadInfo3 = new PayloadInfo().setSizeBytes(payloadBytes3.length); BuckCacheResponse response = new BuckCacheResponse() .setWasSuccessful(true) .setType(BuckCacheRequestType.MULTI_FETCH) .setMultiFetchResponse(multiFetchResponse) .setPayloads(ImmutableList.of(payloadInfo1, payloadInfo3)); responseRef.set(response); try (ThriftArtifactCache cache = new ThriftArtifactCache( networkArgs, "/nice_as_well", new BuildId("aabb"), 0, 0, false, "test://", "hostname")) { AbstractAsynchronousCache.MultiFetchResult result = cache.multiFetchImpl(requests); assertEquals(4, result.getResults().size()); assertEquals(CacheResultType.MISS, result.getResults().get(0).getCacheResult().getType()); assertEquals( String.format("%s", result.getResults().get(1)), CacheResultType.HIT, result.getResults().get(1).getCacheResult().getType()); assertEquals(CacheResultType.SKIPPED, result.getResults().get(2).getCacheResult().getType()); assertEquals(CacheResultType.HIT, result.getResults().get(3).getCacheResult().getType()); assertFalse(filesystem.exists(output0)); assertEquals(payload1, filesystem.readFileIfItExists(output1).get()); assertFalse(filesystem.exists(output2)); assertEquals(payload3, filesystem.readFileIfItExists(output3).get()); } assertEquals(1, fetchClient.getCallsCount()); } @Test public void testMultiContains() throws IOException { AtomicReference<BuckCacheResponse> responseRef = new AtomicReference<>(); HttpService storeClient = new TestHttpService(); TestHttpService fetchClient = new TestHttpService(() -> new InMemoryThriftResponse(responseRef.get())); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tempPaths.getRoot()); ListeningExecutorService service = MoreExecutors.newDirectExecutorService(); CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem); NetworkCacheArgs networkArgs = ImmutableNetworkCacheArgs.builder() .setCacheName("default_cache_name") .setRepository("default_repository") .setCacheReadMode(CacheReadMode.READONLY) .setCacheMode(ArtifactCacheMode.thrift_over_http) .setScheduleType("default_schedule_type") .setTargetConfigurationSerializer( TargetConfigurationSerializerForTests.create(cellPathResolver)) .setUnconfiguredBuildTargetFactory( target -> new ParsingUnconfiguredBuildTargetViewFactory() .create(target, cellPathResolver.getCellNameResolver())) .setProjectFilesystem(filesystem) .setFetchClient(fetchClient) .setStoreClient(storeClient) .setBuckEventBus(BuckEventBusForTests.newInstance()) .setHttpWriteExecutorService(service) .setHttpFetchExecutorService(service) .setErrorTextTemplate("my super error msg") .setErrorTextLimit(100) .build(); com.facebook.buck.core.rulekey.RuleKey key0 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(0)); com.facebook.buck.core.rulekey.RuleKey key1 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(1)); com.facebook.buck.core.rulekey.RuleKey key2 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(2)); com.facebook.buck.core.rulekey.RuleKey key3 = new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(3)); ImmutableSet<com.facebook.buck.core.rulekey.RuleKey> ruleKeys = ImmutableSet.of(key0, key1, key2, key3); BuckCacheMultiContainsResponse multiContainsResponse = new BuckCacheMultiContainsResponse(); ContainsResult result0 = new ContainsResult().setResultType(DOES_NOT_CONTAIN); ContainsResult result1 = new ContainsResult().setResultType(CONTAINS); ContainsResult result2 = new ContainsResult().setResultType(UNKNOWN_DUE_TO_TRANSIENT_ERRORS); ContainsResult result3 = new ContainsResult().setResultType(CONTAINS); multiContainsResponse.addToResults(result0); multiContainsResponse.addToResults(result1); multiContainsResponse.addToResults(result2); multiContainsResponse.addToResults(result3); BuckCacheResponse response = new BuckCacheResponse() .setWasSuccessful(true) .setType(BuckCacheRequestType.CONTAINS) .setMultiContainsResponse(multiContainsResponse); responseRef.set(response); try (ThriftArtifactCache cache = new ThriftArtifactCache( networkArgs, "/nice_as_well", new BuildId("aabb"), 1, 1, false, "test://", "hostname")) { AbstractAsynchronousCache.MultiContainsResult result = cache.multiContainsImpl(ruleKeys); assertEquals(4, result.getCacheResults().size()); assertEquals(CacheResultType.MISS, result.getCacheResults().get(key0).getType()); assertEquals(CacheResultType.CONTAINS, result.getCacheResults().get(key1).getType()); assertEquals(CacheResultType.ERROR, result.getCacheResults().get(key2).getType()); assertEquals(CacheResultType.CONTAINS, result.getCacheResults().get(key3).getType()); } assertEquals(1, fetchClient.getCallsCount()); } private HttpResponse makeSuccessfulDeleteResponse() { BuckCacheDeleteResponse deleteResponse = new BuckCacheDeleteResponse(); BuckCacheResponse response = new BuckCacheResponse() .setWasSuccessful(true) .setType(BuckCacheRequestType.DELETE_REQUEST) .setDeleteResponse(deleteResponse); return new InMemoryThriftResponse(response); } @Test public void testDelete() { HttpService storeClient = new TestHttpService(this::makeSuccessfulDeleteResponse); TestHttpService fetchClient = new TestHttpService(); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tempPaths.getRoot()); ListeningExecutorService service = MoreExecutors.newDirectExecutorService(); CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem); NetworkCacheArgs networkArgs = ImmutableNetworkCacheArgs.builder() .setCacheName("default_cache_name") .setRepository("default_repository") .setCacheReadMode(CacheReadMode.READWRITE) .setCacheMode(ArtifactCacheMode.thrift_over_http) .setScheduleType("default_schedule_type") .setTargetConfigurationSerializer( TargetConfigurationSerializerForTests.create(cellPathResolver)) .setUnconfiguredBuildTargetFactory( target -> new ParsingUnconfiguredBuildTargetViewFactory() .create(target, cellPathResolver.getCellNameResolver())) .setProjectFilesystem(filesystem) .setFetchClient(fetchClient) .setStoreClient(storeClient) .setBuckEventBus(BuckEventBusForTests.newInstance()) .setHttpWriteExecutorService(service) .setHttpFetchExecutorService(service) .setErrorTextTemplate("unused test error message") .setErrorTextLimit(100) .build(); try (ThriftArtifactCache cache = new ThriftArtifactCache( networkArgs, "/nice_as_well", new BuildId("aabb"), 0, 0, false, "test://", "hostname")) { CacheDeleteResult result = Futures.getUnchecked( cache.deleteAsync( Collections.singletonList( new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(42))))); assertThat(result.getCacheNames(), Matchers.hasSize(1)); } } }
3e04d276281a2bf1e43c41d7d7e5e8e5ee546cc2
477
java
Java
uitest/src/main/java/com/vaadin/tests/debug/DebugWindowPresent.java
jforge/vaadin
66df157ecfe9cea75c3c01e43ca6f37ed6ef0671
[ "Apache-2.0" ]
2
2016-12-06T09:05:58.000Z
2016-12-07T08:57:55.000Z
uitest/src/main/java/com/vaadin/tests/debug/DebugWindowPresent.java
jforge/vaadin
66df157ecfe9cea75c3c01e43ca6f37ed6ef0671
[ "Apache-2.0" ]
null
null
null
uitest/src/main/java/com/vaadin/tests/debug/DebugWindowPresent.java
jforge/vaadin
66df157ecfe9cea75c3c01e43ca6f37ed6ef0671
[ "Apache-2.0" ]
null
null
null
20.73913
102
0.675052
2,015
package com.vaadin.tests.debug; import com.vaadin.tests.components.TestBase; public class DebugWindowPresent extends TestBase { @Override protected void setup() { // Nothing to set up } @Override protected String getDescription() { return "The debug window should be present with &debug present in the url, but not othervise"; } @Override protected Integer getTicketNumber() { return Integer.valueOf(7555); } }
3e04d42a6bd3d598d20c12a349f1de16caea8a7b
10,212
java
Java
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/graphics/drawable/animated/R.java
wjboeve/MaterialMe-Starter
2e6b45b48efb46e65df5efefb78eb36e176805bc
[ "Apache-2.0" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/graphics/drawable/animated/R.java
wjboeve/MaterialMe-Starter
2e6b45b48efb46e65df5efefb78eb36e176805bc
[ "Apache-2.0" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/graphics/drawable/animated/R.java
wjboeve/MaterialMe-Starter
2e6b45b48efb46e65df5efefb78eb36e176805bc
[ "Apache-2.0" ]
null
null
null
54.903226
147
0.736193
2,016
/* 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 = 0x7f04007b; public static final int font = 0x7f0400a4; public static final int fontProviderAuthority = 0x7f0400a6; public static final int fontProviderCerts = 0x7f0400a7; public static final int fontProviderFetchStrategy = 0x7f0400a8; public static final int fontProviderFetchTimeout = 0x7f0400a9; public static final int fontProviderPackage = 0x7f0400aa; public static final int fontProviderQuery = 0x7f0400ab; public static final int fontStyle = 0x7f0400ac; public static final int fontWeight = 0x7f0400ad; public static final int keylines = 0x7f0400c7; public static final int layout_anchor = 0x7f0400ca; public static final int layout_anchorGravity = 0x7f0400cb; public static final int layout_behavior = 0x7f0400cc; public static final int layout_dodgeInsetEdges = 0x7f0400f8; public static final int layout_insetEdge = 0x7f040101; public static final int layout_keyline = 0x7f040102; public static final int statusBarBackground = 0x7f04014f; } 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 = 0x7f09003f; public static final int forever = 0x7f09004a; public static final int icon = 0x7f090050; public static final int icon_group = 0x7f090051; public static final int info = 0x7f090054; public static final int italic = 0x7f090056; public static final int left = 0x7f090059; public static final int line1 = 0x7f09005a; public static final int line3 = 0x7f09005b; public static final int none = 0x7f090068; public static final int normal = 0x7f090069; public static final int notification_background = 0x7f09006a; public static final int notification_main_column = 0x7f09006b; public static final int notification_main_column_container = 0x7f09006c; public static final int right = 0x7f090078; public static final int right_icon = 0x7f090079; public static final int right_side = 0x7f09007a; public static final int start = 0x7f0900a1; public static final int tag_transition_group = 0x7f0900a8; public static final int text = 0x7f0900a9; public static final int text2 = 0x7f0900aa; public static final int time = 0x7f0900b0; public static final int title = 0x7f0900b1; public static final int top = 0x7f0900b5; } 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 = { 0x7f0400c7, 0x7f04014f }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f0400ca, 0x7f0400cb, 0x7f0400cc, 0x7f0400f8, 0x7f040101, 0x7f040102 }; 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 = { 0x7f0400a6, 0x7f0400a7, 0x7f0400a8, 0x7f0400a9, 0x7f0400aa, 0x7f0400ab }; 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, 0x7f0400a4, 0x7f0400ac, 0x7f0400ad }; 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; } }
3e04d46d8edbdada122851d4294a3ea3e685d482
1,063
java
Java
src/main/java/com/techm/transport/entity/JourneyType.java
TransportTechm/DevOps
c2813246589eaebb56d704c7a73e07d9739f6414
[ "Apache-2.0" ]
null
null
null
src/main/java/com/techm/transport/entity/JourneyType.java
TransportTechm/DevOps
c2813246589eaebb56d704c7a73e07d9739f6414
[ "Apache-2.0" ]
null
null
null
src/main/java/com/techm/transport/entity/JourneyType.java
TransportTechm/DevOps
c2813246589eaebb56d704c7a73e07d9739f6414
[ "Apache-2.0" ]
null
null
null
18.016949
61
0.658514
2,017
package com.techm.transport.entity; import com.fasterxml.jackson.annotation.JsonIgnore; public class JourneyType { private Integer id; private String name; @JsonIgnore private Integer locId; public JourneyType(Integer id, String name, Integer locId) { this.id = id; this.name = name; this.locId = locId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLocId() { return locId; } public void setLocId(Integer locId) { this.locId = locId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JourneyType other = (JourneyType) obj; if (id != other.id) return false; return true; } }
3e04d5a28287d7d943b0dd9a751f5f1ed37e7a8b
928
java
Java
src/main/java/com/neko/seed/entity/po/Family.java
Yuki1999/springboot-restful-starter
9eaf9a44ace1ebde9fdddeabb44740683ea2b0ff
[ "MIT" ]
null
null
null
src/main/java/com/neko/seed/entity/po/Family.java
Yuki1999/springboot-restful-starter
9eaf9a44ace1ebde9fdddeabb44740683ea2b0ff
[ "MIT" ]
null
null
null
src/main/java/com/neko/seed/entity/po/Family.java
Yuki1999/springboot-restful-starter
9eaf9a44ace1ebde9fdddeabb44740683ea2b0ff
[ "MIT" ]
null
null
null
16.872727
54
0.621767
2,018
package com.neko.seed.entity.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import lombok.Data; /** * null * @TableName family */ @TableName(value ="family") @Data public class Family implements Serializable { /** * 户号 */ @TableId(type = IdType.AUTO) private Integer id; /** * */ private String familyNo; /** * 户主姓名 */ private String name; /** * 住址 */ private String address; /** * 户别:1居民户口,2农村户口 */ private String type; /** * 户口登记机关 */ private String regiAuth; /** * 承办人 */ private String contractor; @TableField(exist = false) private static final long serialVersionUID = 1L; }
3e04d5b0e3ff5d9c3bff76ad85a54c7fb81d5f46
4,447
java
Java
src/test/java/com/notnoop/apns/ApnsGatewayServerSocket.java
blastlab/java-apns
180a190d4cb49458441596ca7c69d50ec7f1dba5
[ "BSD-3-Clause" ]
1,155
2015-01-01T19:26:41.000Z
2022-03-23T12:26:13.000Z
src/test/java/com/notnoop/apns/ApnsGatewayServerSocket.java
blastlab/java-apns
180a190d4cb49458441596ca7c69d50ec7f1dba5
[ "BSD-3-Clause" ]
170
2015-01-08T12:30:56.000Z
2021-12-09T20:37:04.000Z
src/test/java/com/notnoop/apns/ApnsGatewayServerSocket.java
blastlab/java-apns
180a190d4cb49458441596ca7c69d50ec7f1dba5
[ "BSD-3-Clause" ]
512
2015-01-05T12:25:28.000Z
2021-12-28T07:57:23.000Z
35.576
78
0.7387
2,019
/* * Copyright 2009, Mahmood Ali. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Mahmood Ali. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.notnoop.apns; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.concurrent.ExecutorService; import javax.net.ssl.SSLContext; /** * Represents the Apple APNS server. This allows testing outside of the Apple * servers. */ @SuppressWarnings("deprecation") public class ApnsGatewayServerSocket extends AbstractApnsServerSocket { private final ApnsServerService apnsServerService; public ApnsGatewayServerSocket(SSLContext sslContext, int port, ExecutorService executorService, ApnsServerService apnsServerService, ApnsServerExceptionDelegate exceptionDelegate) throws IOException { super(sslContext, port, executorService, exceptionDelegate); this.apnsServerService = apnsServerService; } @Override void handleSocket(Socket socket) throws IOException { InputStream inputStream = socket.getInputStream(); DataInputStream dataInputStream = new DataInputStream(inputStream); while (true) { int identifier = 0; try { int read = dataInputStream.read(); if (read == -1) { break; } boolean enhancedFormat = read == 1; int expiry = 0; if (enhancedFormat) { identifier = dataInputStream.readInt(); expiry = dataInputStream.readInt(); } int deviceTokenLength = dataInputStream.readShort(); byte[] deviceTokenBytes = toArray(inputStream, deviceTokenLength); int payloadLength = dataInputStream.readShort(); byte[] payloadBytes = toArray(inputStream, payloadLength); ApnsNotification message; if (enhancedFormat) { message = new EnhancedApnsNotification(identifier, expiry, deviceTokenBytes, payloadBytes); } else { message = new SimpleApnsNotification(deviceTokenBytes, payloadBytes); } apnsServerService.messageReceived(message); } catch (IOException ioe) { writeResponse(socket, identifier, 8, 1); break; } catch (Exception e) { writeResponse(socket, identifier, 8, 1); break; } } } private void writeResponse(Socket socket, int identifier, int command, int status) { try { BufferedOutputStream bos = new BufferedOutputStream( socket.getOutputStream()); DataOutputStream dataOutputStream = new DataOutputStream(bos); dataOutputStream.writeByte(command); dataOutputStream.writeByte(status); dataOutputStream.writeInt(identifier); dataOutputStream.flush(); } catch (IOException ioe) { // if we can't write a response, nothing we can do } } private byte[] toArray(InputStream inputStream, int size) throws IOException { byte[] bytes = new byte[size]; final DataInputStream dis = new DataInputStream(inputStream); dis.readFully(bytes); return bytes; } }
3e04d5f71febce1b3771d9c0ec7fd2243f167f90
2,023
java
Java
core/src/main/java/org/jruby/ir/instructions/CheckArgsArrayArityInstr.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
3
2015-12-29T07:34:53.000Z
2020-05-30T12:29:14.000Z
core/src/main/java/org/jruby/ir/instructions/CheckArgsArrayArityInstr.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
null
null
null
core/src/main/java/org/jruby/ir/instructions/CheckArgsArrayArityInstr.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
1
2018-03-08T03:57:56.000Z
2018-03-08T03:57:56.000Z
29.75
125
0.695996
2,020
package org.jruby.ir.instructions; import org.jruby.RubyArray; import org.jruby.ir.IRVisitor; import org.jruby.ir.Operation; import org.jruby.ir.operands.Operand; import org.jruby.ir.transformations.inlining.InlinerInfo; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.DynamicScope; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import java.util.Map; import org.jruby.runtime.Helpers; public class CheckArgsArrayArityInstr extends Instr { public final int required; public final int opt; public final int rest; private Operand argsArray; public CheckArgsArrayArityInstr(Operand argsArray, int required, int opt, int rest) { super(Operation.CHECK_ARGS_ARRAY_ARITY); this.required = required; this.opt = opt; this.rest = rest; this.argsArray = argsArray; } public Operand getArgsArray() { return argsArray; } @Override public Operand[] getOperands() { return new Operand[] { argsArray }; } @Override public void simplifyOperands(Map<Operand, Operand> valueMap, boolean force) { argsArray = argsArray.getSimplifiedOperand(valueMap, force); } @Override public String toString() { return super.toString() + "(" + argsArray + ", " + required + ", " + opt + ", " + rest + ")"; } @Override public Instr cloneForInlining(InlinerInfo ii) { return new CheckArgsArrayArityInstr(argsArray.cloneForInlining(ii), required, opt, rest); } @Override public Object interpret(ThreadContext context, DynamicScope currDynScope, IRubyObject self, Object[] temp, Block block) { RubyArray args = (RubyArray) argsArray.retrieve(context, self, currDynScope, temp); Helpers.irCheckArgsArrayArity(context, args, required, opt, rest); return null; } @Override public void visit(IRVisitor visitor) { visitor.CheckArgsArrayArityInstr(this); } }
3e04d6f585eb6ef3269f76419e06068c9f0c3f7e
1,485
java
Java
FinalProjectCheckOutTest/src/lm44_xw47/model/dataPacketAlgoCmd/InvitationCmd.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
FinalProjectCheckOutTest/src/lm44_xw47/model/dataPacketAlgoCmd/InvitationCmd.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
FinalProjectCheckOutTest/src/lm44_xw47/model/dataPacketAlgoCmd/InvitationCmd.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
32.282609
123
0.812121
2,021
package lm44_xw47.model.dataPacketAlgoCmd; import common.DataPacketCR; import common.DataPacketUser; import common.DataPacketUserAlgoCmd; import common.IChatRoom; import common.IReceiver; import common.IUserCmd2ModelAdapter; import common.datatype.chatroom.IAddReceiverType; import common.datatype.user.IInvitationType; import lm44_xw47.chatRoom.model.dataType.AddReceiverType; import lm44_xw47.model.ILocalUserCmd2ModelAdapter; /** * command that invites * */ public class InvitationCmd extends DataPacketUserAlgoCmd<IInvitationType>{ /** * An auto-generated id for serialization. */ private static final long serialVersionUID = 3391248506497811811L; private transient ILocalUserCmd2ModelAdapter cmd2ModelAdpt; public InvitationCmd(IUserCmd2ModelAdapter cmd2ModelAdpt) { this.cmd2ModelAdpt = (ILocalUserCmd2ModelAdapter) cmd2ModelAdpt; } @Override public String apply(Class<?> index, DataPacketUser<IInvitationType> host, String... params) { IChatRoom chatRoom = host.getData().getChatRoom(); IReceiver receiver = cmd2ModelAdpt.joinTeam(chatRoom); System.out.println("Add Receiver."); chatRoom.sendPacket(new DataPacketCR<IAddReceiverType>(IAddReceiverType.class, new AddReceiverType(receiver), receiver)); chatRoom.addIReceiverStub(receiver); return "Invitation command has been executed"; } @Override public void setCmd2ModelAdpt(IUserCmd2ModelAdapter cmd2ModelAdpt) { this.cmd2ModelAdpt = (ILocalUserCmd2ModelAdapter) cmd2ModelAdpt; } }
3e04d7bf5dd8cb8cde2291ba82aea0387b699fc8
1,860
java
Java
app/src/main/java/mess056/includes/tpi6525H.java
javaemus/ArcoFlexDroid
e9ece569f14b65c906612e2574d15dacbf4bfc80
[ "Apache-2.0" ]
null
null
null
app/src/main/java/mess056/includes/tpi6525H.java
javaemus/ArcoFlexDroid
e9ece569f14b65c906612e2574d15dacbf4bfc80
[ "Apache-2.0" ]
null
null
null
app/src/main/java/mess056/includes/tpi6525H.java
javaemus/ArcoFlexDroid
e9ece569f14b65c906612e2574d15dacbf4bfc80
[ "Apache-2.0" ]
null
null
null
25.671233
87
0.549626
2,022
/*************************************************************************** mos tri port interface 6525 mos triple interface adapter 6523 [email protected] used in commodore b series used in commodore c1551 floppy disk drive ***************************************************************************/ /* * ported to v0.56 * using automatic conversion tool v0.01 */ package mess056.includes; public class tpi6525H { /* tia6523 is a tpi6525 without control register!? */ /* * tia6523 * * only some lines of port b and c are in the pinout ! * * connector to floppy c1551 (delivered with c1551 as c16 expansion) * port a for data read/write * port b * 0 status 0 * 1 status 1 * port c * 6 dav output edge data on port a available * 7 ack input edge ready for next datum */ public static abstract interface ReadTPI6525Ptr { public abstract int handler(); } public static abstract interface WriteTPI6525Ptr { public abstract void handler(int data); } public static class _blockA { public ReadTPI6525Ptr read = null; public WriteTPI6525Ptr output = null; public int port, ddr, in; } public static class _blockB { public WriteTPI6525Ptr output = null; public int level; } /* fill in the callback functions */ public static class TPI6525 { public int number; public _blockA a=new _blockA(),b=new _blockA(),c=new _blockA(); public _blockB ca=new _blockB(), cb=new _blockB(), interrupt=new _blockB(); public int cr; public int air; public int[] irq_level = new int[5]; public TPI6525(int _num){ this.number = _num; } }; }
3e04d7d7a6b4f9cb43227d49d4cd8e841d44fb29
2,626
java
Java
src/main/java/org/kcctl/command/GetPluginsCommand.java
jvenant/kcctl
44861aa8aa95a940407e2b3619611efaa7f2baad
[ "Apache-2.0" ]
null
null
null
src/main/java/org/kcctl/command/GetPluginsCommand.java
jvenant/kcctl
44861aa8aa95a940407e2b3619611efaa7f2baad
[ "Apache-2.0" ]
null
null
null
src/main/java/org/kcctl/command/GetPluginsCommand.java
jvenant/kcctl
44861aa8aa95a940407e2b3619611efaa7f2baad
[ "Apache-2.0" ]
null
null
null
37.514286
120
0.722011
2,023
/* * Copyright 2021 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kcctl.command; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.kcctl.service.ConnectorPlugin; import org.kcctl.service.KafkaConnectApi; import org.kcctl.util.ConfigurationContext; import com.github.freva.asciitable.AsciiTable; import com.github.freva.asciitable.Column; import com.github.freva.asciitable.HorizontalAlign; import picocli.CommandLine; import picocli.CommandLine.Command; @Command(name = "plugins", description = "Displays information about available connector plug-ins") public class GetPluginsCommand implements Runnable { private final ConfigurationContext context; @CommandLine.Spec CommandLine.Model.CommandSpec spec; @Inject public GetPluginsCommand(ConfigurationContext context) { this.context = context; } // Hack : Picocli currently require an empty constructor to generate the completion file public GetPluginsCommand() { context = new ConfigurationContext(); } @Override public void run() { KafkaConnectApi kafkaConnectApi = RestClientBuilder.newBuilder() .baseUri(context.getCurrentContext().getCluster()) .build(KafkaConnectApi.class); List<ConnectorPlugin> connectorPlugins = kafkaConnectApi.getConnectorPlugins(); connectorPlugins.sort((c1, c2) -> -c1.type.compareTo(c2.type)); spec.commandLine().getOut().println(); spec.commandLine().getOut().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, connectorPlugins, Arrays.asList( new Column().header("TYPE").dataAlign(HorizontalAlign.LEFT).with(plugin -> plugin.type), new Column().header(" CLASS").dataAlign(HorizontalAlign.LEFT).with(plugin -> " " + plugin.clazz), new Column().header(" VERSION").dataAlign(HorizontalAlign.LEFT).with(plugin -> " " + plugin.version)))); spec.commandLine().getOut().println(); } }
3e04d889ac3cb19d0533c462603633a7e7dc7968
2,288
java
Java
src/main/java/com/microsoft/graph/requests/extensions/TrendingCollectionRequestBuilder.java
Krisoblucki-okta/msgraph-sdk-java
8e1960974f24aef28d8a0fde5a786a33c2f9cb3a
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/TrendingCollectionRequestBuilder.java
Krisoblucki-okta/msgraph-sdk-java
8e1960974f24aef28d8a0fde5a786a33c2f9cb3a
[ "MIT" ]
22
2020-09-17T05:53:52.000Z
2022-02-14T01:03:31.000Z
src/main/java/com/microsoft/graph/requests/extensions/TrendingCollectionRequestBuilder.java
Krisoblucki-okta/msgraph-sdk-java
8e1960974f24aef28d8a0fde5a786a33c2f9cb3a
[ "MIT" ]
null
null
null
43.169811
179
0.727273
2,024
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.OfficeGraphInsights; import com.microsoft.graph.models.extensions.Trending; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.requests.extensions.ITrendingCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.ITrendingRequestBuilder; import com.microsoft.graph.requests.extensions.ITrendingCollectionRequest; import com.microsoft.graph.http.BaseRequestBuilder; import com.microsoft.graph.core.IBaseClient; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Trending Collection Request Builder. */ public class TrendingCollectionRequestBuilder extends BaseRequestBuilder implements ITrendingCollectionRequestBuilder { /** * The request builder for this collection of OfficeGraphInsights * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public TrendingCollectionRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } public ITrendingCollectionRequest buildRequest() { return buildRequest(getOptions()); } public ITrendingCollectionRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new TrendingCollectionRequest(getRequestUrl(), getClient(), requestOptions); } public ITrendingRequestBuilder byId(final String id) { return new TrendingRequestBuilder(getRequestUrlWithAdditionalSegment(id), getClient(), getOptions()); } }
3e04d8a776bd9c657ec06d92115f1f9e692a3699
214
java
Java
src/main/java/com/webank/webase/chain/mgr/front/entity/ReqAbandonedFrontByAgencyIdVO.java
YongYuIT/WeBASE-Chain-Manager
8bed42aaf5e2c4a4c700c482d2044c2d2b41b9d8
[ "Apache-2.0" ]
13
2019-12-30T12:26:35.000Z
2021-07-14T02:12:58.000Z
src/main/java/com/webank/webase/chain/mgr/front/entity/ReqAbandonedFrontByAgencyIdVO.java
YongYuIT/WeBASE-Chain-Manager
8bed42aaf5e2c4a4c700c482d2044c2d2b41b9d8
[ "Apache-2.0" ]
2
2020-06-19T09:43:28.000Z
2020-11-03T09:36:57.000Z
src/main/java/com/webank/webase/chain/mgr/front/entity/ReqAbandonedFrontByAgencyIdVO.java
YongYuIT/WeBASE-Chain-Manager
8bed42aaf5e2c4a4c700c482d2044c2d2b41b9d8
[ "Apache-2.0" ]
24
2019-12-24T09:42:42.000Z
2021-11-01T07:15:39.000Z
17.833333
49
0.78972
2,025
package com.webank.webase.chain.mgr.front.entity; import lombok.Data; import javax.validation.constraints.NotNull; @Data public class ReqAbandonedFrontByAgencyIdVO { @NotNull private Integer agencyId; }
3e04d8fe73e5f36e7b6db6be39a82adf6fdc3311
543
java
Java
src/rasterization/light/AmbientLight.java
zackziegler95/PhysicsEngineRasterizer
5c608d59342ff8cef8d4aa6f99768c55d0287b6b
[ "MIT" ]
1
2021-04-23T15:37:43.000Z
2021-04-23T15:37:43.000Z
src/rasterization/light/AmbientLight.java
zackziegler95/PhysicsEngineRasterizer
5c608d59342ff8cef8d4aa6f99768c55d0287b6b
[ "MIT" ]
null
null
null
src/rasterization/light/AmbientLight.java
zackziegler95/PhysicsEngineRasterizer
5c608d59342ff8cef8d4aa6f99768c55d0287b6b
[ "MIT" ]
null
null
null
24.681818
60
0.629834
2,026
/** * Ambient light that illuminates everything */ package rasterization.light; import rasterization.geometry.Poly; import rasterization.tools.Vector3; public class AmbientLight extends Light { public AmbientLight(double Ia) { super(new Vector3(Ia, Ia, Ia)); } @Override public Vector3 getColors(Poly p, Vector3 cameraPos) { return new Vector3(color.array[0]*p.color.array[0], color.array[1]*p.color.array[1], color.array[2]*p.color.array[2]); } }
3e04d935792d18be171dd10e34a251269b40d9c5
19,792
java
Java
src/main/java/skadistats/clarity/processor/entities/Entities.java
Noxville/clarity
14134756759b77aa94af052096dccec7004b9bba
[ "BSD-3-Clause" ]
1
2021-01-09T19:51:49.000Z
2021-01-09T19:51:49.000Z
src/main/java/skadistats/clarity/processor/entities/Entities.java
Noxville/clarity
14134756759b77aa94af052096dccec7004b9bba
[ "BSD-3-Clause" ]
null
null
null
src/main/java/skadistats/clarity/processor/entities/Entities.java
Noxville/clarity
14134756759b77aa94af052096dccec7004b9bba
[ "BSD-3-Clause" ]
null
null
null
37.27307
175
0.585944
2,027
package skadistats.clarity.processor.entities; import com.google.protobuf.ByteString; import org.slf4j.Logger; import skadistats.clarity.ClarityException; import skadistats.clarity.LogChannel; import skadistats.clarity.decoder.FieldReader; import skadistats.clarity.decoder.bitstream.BitStream; import skadistats.clarity.event.Event; import skadistats.clarity.event.EventListener; import skadistats.clarity.event.Initializer; import skadistats.clarity.event.Insert; import skadistats.clarity.event.InsertEvent; import skadistats.clarity.event.Provides; import skadistats.clarity.logger.PrintfLoggerFactory; import skadistats.clarity.model.DTClass; import skadistats.clarity.model.EngineId; import skadistats.clarity.model.EngineType; import skadistats.clarity.model.Entity; import skadistats.clarity.model.FieldPath; import skadistats.clarity.model.StringTable; import skadistats.clarity.model.state.ClientFrame; import skadistats.clarity.model.state.EntityRegistry; import skadistats.clarity.model.state.EntityState; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.reader.OnReset; import skadistats.clarity.processor.reader.ResetPhase; import skadistats.clarity.processor.runner.OnInit; import skadistats.clarity.processor.sendtables.DTClasses; import skadistats.clarity.processor.sendtables.OnDTClassesComplete; import skadistats.clarity.processor.sendtables.UsesDTClasses; import skadistats.clarity.processor.stringtables.OnStringTableEntry; import skadistats.clarity.util.Predicate; import skadistats.clarity.util.SimpleIterator; import skadistats.clarity.wire.common.proto.Demo; import skadistats.clarity.wire.common.proto.NetMessages; import skadistats.clarity.wire.common.proto.NetworkBaseTypes; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; @Provides({UsesEntities.class, OnEntityCreated.class, OnEntityUpdated.class, OnEntityDeleted.class, OnEntityEntered.class, OnEntityLeft.class, OnEntityUpdatesCompleted.class}) @UsesDTClasses public class Entities { public static final String BASELINE_TABLE = "instancebaseline"; private static final Logger log = PrintfLoggerFactory.getLogger(LogChannel.entities); private int entityCount; private FieldReader<DTClass> fieldReader; private int[] deletions; private int serverTick; private EntityRegistry entityRegistry = new EntityRegistry(); private Map<Integer, ByteString> rawBaselines = new HashMap<>(); private class Baseline { private int dtClassId = -1; private EntityState state; private void reset() { state = null; } private void copyFrom(Baseline other) { this.dtClassId = other.dtClassId; this.state = other.state; } } private Baseline[] classBaselines; private Baseline[][] entityBaselines; private final FieldPath[] updatedFieldPaths = new FieldPath[FieldReader.MAX_PROPERTIES]; private ClientFrame entities; private boolean resetInProgress; private ClientFrame.Capsule resetCapsule; @Insert private EngineType engineType; @Insert private DTClasses dtClasses; @InsertEvent private Event<OnEntityCreated> evCreated; @InsertEvent private Event<OnEntityUpdated> evUpdated; @InsertEvent private Event<OnEntityDeleted> evDeleted; @InsertEvent private Event<OnEntityEntered> evEntered; @InsertEvent private Event<OnEntityLeft> evLeft; @InsertEvent private Event<OnEntityUpdatesCompleted> evUpdatesCompleted; @Initializer(OnEntityCreated.class) public void initOnEntityCreated(final EventListener<OnEntityCreated> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityDeleted.class) public void initOnEntityDeleted(final EventListener<OnEntityDeleted> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityUpdated.class) public void initOnEntityUpdated(final EventListener<OnEntityUpdated> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityEntered.class) public void initOnEntityEntered(final EventListener<OnEntityEntered> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityLeft.class) public void initOnEntityLeft(final EventListener<OnEntityLeft> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } private Predicate<Object[]> getInvocationPredicate(String classPattern) { if (".*".equals(classPattern)) { return null; } final Pattern p = Pattern.compile(classPattern); return value -> { Entity e = (Entity) value[0]; return p.matcher(e.getDtClass().getDtName()).matches(); }; } @OnInit public void onInit() { entityCount = 1 << engineType.getIndexBits(); entities = new ClientFrame(entityCount); fieldReader = engineType.getNewFieldReader(); deletions = new int[entityCount]; entityBaselines = new Baseline[entityCount][2]; for (int i = 0; i < entityCount; i++) { entityBaselines[i][0] = new Baseline(); entityBaselines[i][1] = new Baseline(); } } @OnDTClassesComplete public void onDTClassesComplete() { classBaselines = new Baseline[dtClasses.getClassCount()]; for (int i = 0; i < classBaselines.length; i++) { classBaselines[i] = new Baseline(); classBaselines[i].dtClassId = i; } } @OnReset public void onReset(Demo.CDemoStringTables packet, ResetPhase phase) { switch (phase) { case START: resetInProgress = true; resetCapsule = entities.createCapsule(); break; case CLEAR: entities = new ClientFrame(entityCount); for (int i = 0; i < classBaselines.length; i++) { classBaselines[i].reset(); } for (int i = 0; i < entityBaselines.length; i++) { entityBaselines[i][0].reset(); entityBaselines[i][1].reset(); } break; case COMPLETE: resetInProgress = false; //updateEventDebug = true; Entity entity; for (int eIdx = 0; eIdx < entityCount; eIdx++) { entity = entities.getEntity(eIdx); if (resetCapsule.isExistent(eIdx)) { if (entity == null || entity.getHandle() != resetCapsule.getHandle(eIdx)) { Entity deletedEntity = entityRegistry.get(resetCapsule.getHandle(eIdx)); if (resetCapsule.isActive(eIdx)) { emitLeftEvent(deletedEntity); } emitDeletedEvent(deletedEntity); } } if (entity != null) { if (!resetCapsule.isExistent(eIdx) || entity.getHandle() != resetCapsule.getHandle(eIdx)) { emitCreatedEvent(entity); if (entity.isActive()) { emitEnteredEvent(entity); } } else { Iterator<FieldPath> iter = entity.getState().fieldPathIterator(); int n = 0; while (iter.hasNext()) { updatedFieldPaths[n++] = iter.next(); } emitUpdatedEvent(entity, n); } } } resetCapsule = null; //updateEventDebug = false; evUpdatesCompleted.raise(); break; } } @OnStringTableEntry(BASELINE_TABLE) public void onBaselineEntry(StringTable table, int index, String key, ByteString value) { Integer dtClassId = Integer.valueOf(key); rawBaselines.put(dtClassId, value); if (classBaselines != null) { classBaselines[dtClassId].reset(); } } @OnMessage(NetworkBaseTypes.CNETMsg_Tick.class) public void onMessage(NetworkBaseTypes.CNETMsg_Tick message) { serverTick = message.getTick(); } boolean debug = false; boolean updateEventDebug = false; void debugUpdateEvent(String which, Entity entity) { if (!updateEventDebug) return; log.info("\t%6s: index: %4d, serial: %03x, handle: %7d, class: %s", which, entity.getIndex(), entity.getSerial(), entity.getHandle(), entity.getDtClass().getDtName() ); } @OnMessage(NetMessages.CSVCMsg_PacketEntities.class) public void onPacketEntities(NetMessages.CSVCMsg_PacketEntities message) { if (log.isDebugEnabled()) { log.debug( "processing packet entities: now: %6d, delta-from: %6d, update-count: %5d, baseline: %d, update-baseline: %5s", serverTick, message.getDeltaFrom(), message.getUpdatedEntries(), message.getBaseline(), message.getUpdateBaseline() ); } if (message.getIsDelta()) { if (serverTick == message.getDeltaFrom()) { throw new ClarityException("received self-referential delta update for tick %d", serverTick); } log.debug("performing delta update, using previous frame from tick %d", message.getDeltaFrom()); } else { log.debug("performing full update"); } if (message.getUpdateBaseline()) { int iFrom = message.getBaseline(); int iTo = 1 - message.getBaseline(); for (Baseline[] baseline : entityBaselines) { baseline[iTo].copyFrom(baseline[iFrom]); } } BitStream stream = BitStream.createBitStream(message.getEntityData()); int updateCount = message.getUpdatedEntries(); int updateType; int eIdx = -1; Entity eEnt; while (updateCount-- != 0) { eIdx += stream.readUBitVar() + 1; eEnt = entities.getEntity(eIdx); updateType = stream.readUBitInt(2); switch (updateType) { case 2: // CREATE int dtClassId = stream.readUBitInt(dtClasses.getClassBits()); DTClass dtClass = dtClasses.forClassId(dtClassId); if (dtClass == null) { throw new ClarityException("class for new entity %d is %d, but no dtClass found!.", eIdx, dtClassId); } int serial = stream.readUBitInt(engineType.getSerialBits()); if (engineType.getId() == EngineId.SOURCE2) { // TODO: there is an extra VarInt encoded here for S2, figure out what it is stream.readVarUInt(); } if (eEnt != null) { if (eEnt.getHandle() == engineType.handleForIndexAndSerial(eIdx, serial)) { if (!eEnt.isActive()) { processEntityEnter(eEnt); } processEntityUpdate(eEnt, stream, false); break; } if (eEnt.isActive()) { processEntityLeave(eEnt); } processEntityDelete(eEnt); } processEntityCreate(eIdx, serial, dtClass, message, stream); break; case 0: // UPDATE if (eEnt == null) { int lastHandle = entities.getLastHandle(eIdx); eEnt = entityRegistry.get(lastHandle); processEntityUpdate(eEnt, stream, true); break; } processEntityUpdate(eEnt, stream, false); break; case 1: // LEAVE if (eEnt != null && eEnt.isActive()) { processEntityLeave(eEnt); } break; case 3: // DELETE if (eEnt != null) { if (eEnt.isActive()) { processEntityLeave(eEnt); } processEntityDelete(eEnt); } break; } } if (engineType.handleDeletions() && message.getIsDelta()) { int n = fieldReader.readDeletions(stream, engineType.getIndexBits(), deletions); for (int i = 0; i < n; i++) { eIdx = deletions[i]; eEnt = entities.getEntity(eIdx); if (eEnt != null) { if (eEnt.isActive()) { processEntityLeave(eEnt); } processEntityDelete(eEnt); } } } log.debug("update finished for tick %d", serverTick); if (!resetInProgress) { evUpdatesCompleted.raise(); } } private void processEntityCreate(int eIdx, int serial, DTClass dtClass, NetMessages.CSVCMsg_PacketEntities message, BitStream stream) { Baseline baseline = getBaseline(dtClass.getClassId(), message.getBaseline(), eIdx, message.getIsDelta()); EntityState newState = baseline.state.copy(); fieldReader.readFields(stream, dtClass, newState, null, debug); Entity entity = entityRegistry.create( eIdx, serial, engineType.handleForIndexAndSerial(eIdx, serial), dtClass); entity.setExistent(true); entity.setState(newState); entities.setEntity(entity); logModification("CREATE", entity); emitCreatedEvent(entity); processEntityEnter(entity); if (message.getUpdateBaseline()) { Baseline updatedBaseline = entityBaselines[eIdx][1 - message.getBaseline()]; updatedBaseline.dtClassId = dtClass.getClassId(); updatedBaseline.state = newState.copy(); } } private void processEntityUpdate(Entity entity, BitStream stream, boolean silent) { assert silent || (entity.isExistent() && entity.isActive()); int nUpdated = fieldReader.readFields(stream, entity.getDtClass(), entity.getState(), (i, f) -> updatedFieldPaths[i] = f, debug); logModification("UPDATE", entity); if (!silent) { emitUpdatedEvent(entity, nUpdated); } } private void processEntityEnter(Entity entity) { assert !entity.isActive(); entity.setActive(true); logModification("ENTER", entity); emitEnteredEvent(entity); } private void processEntityLeave(Entity entity) { assert entity.isActive(); entity.setActive(false); logModification("LEAVE", entity); emitLeftEvent(entity); } private void processEntityDelete(Entity entity) { assert entity.isExistent(); entity.setExistent(false); entities.removeEntity(entity); logModification("DELETE", entity); emitDeletedEvent(entity); } private void emitCreatedEvent(Entity entity) { if (resetInProgress || !evCreated.isListenedTo()) return; debugUpdateEvent("CREATE", entity); evCreated.raise(entity); } private void emitEnteredEvent(Entity entity) { if (resetInProgress || !evEntered.isListenedTo()) return; debugUpdateEvent("ENTER", entity); evEntered.raise(entity); } private void emitUpdatedEvent(Entity entity, int nUpdated) { if (resetInProgress || !evUpdated.isListenedTo()) return; debugUpdateEvent("UPDATE", entity); evUpdated.raise(entity, updatedFieldPaths, nUpdated); } private void emitLeftEvent(Entity entity) { if (resetInProgress || !evLeft.isListenedTo()) return; debugUpdateEvent("LEAVE", entity); evLeft.raise(entity); } private void emitDeletedEvent(Entity entity) { if (resetInProgress || !evDeleted.isListenedTo()) return; debugUpdateEvent("DELETE", entity); evDeleted.raise(entity); } private void logModification(String which, Entity entity) { if (!log.isDebugEnabled()) return; log.debug("\t%6s: index: %4d, serial: %03x, handle: %7d, class: %s", which, entity.getIndex(), entity.getSerial(), entity.getHandle(), entity.getDtClass().getDtName() ); } private Baseline getBaseline(int clsId, int baseline, int entityIdx, boolean delta) { Baseline b; if (delta) { b = entityBaselines[entityIdx][baseline]; if (b.dtClassId == clsId && b.state != null) { return b; } } b = classBaselines[clsId]; if (b.state != null) { return b; } DTClass cls = dtClasses.forClassId(clsId); if (cls == null) { throw new ClarityException("DTClass for id %d not found.", clsId); } b.state = cls.getEmptyState(); ByteString raw = rawBaselines.get(clsId); if (raw == null) { throw new ClarityException("Baseline for class %s (%d) not found.", cls.getDtName(), clsId); } if (raw.size() > 0) { BitStream stream = BitStream.createBitStream(raw); fieldReader.readFields(stream, cls, b.state, null, false); } return b; } public Entity getByIndex(int index) { return entities.getEntity(index); } public Entity getByHandle(int handle) { Entity e = getByIndex(engineType.indexForHandle(handle)); return e == null || e.getHandle() != handle ? null : e; } public Iterator<Entity> getAllByPredicate(final Predicate<Entity> predicate) { return new SimpleIterator<Entity>() { int i = -1; @Override public Entity readNext() { while (++i < entityCount) { Entity e = getByIndex(i); if (e != null && predicate.apply(e)) { return e; } } return null; } }; } public Entity getByPredicate(Predicate<Entity> predicate) { Iterator<Entity> iter = getAllByPredicate(predicate); return iter.hasNext() ? iter.next() : null; } public Iterator<Entity> getAllByDtName(final String dtClassName) { return getAllByPredicate( e -> dtClassName.equals(e.getDtClass().getDtName())); } public Entity getByDtName(final String dtClassName) { Iterator<Entity> iter = getAllByDtName(dtClassName); return iter.hasNext() ? iter.next() : null; } }
3e04d9adcf5924a4b8bbd925d3b2b7302d6cffd8
1,913
java
Java
xill-processor/src/main/java/nl/xillio/xill/plugins/collection/constructs/DuplicateConstruct.java
xillio/xill-platform
1da3697f39b4c3997b6b40dda82977b293234b36
[ "Apache-2.0" ]
4
2018-05-03T15:39:10.000Z
2021-12-14T15:19:50.000Z
xill-processor/src/main/java/nl/xillio/xill/plugins/collection/constructs/DuplicateConstruct.java
RobAaldijk/xill-platform
1da3697f39b4c3997b6b40dda82977b293234b36
[ "Apache-2.0" ]
46
2018-04-13T10:04:43.000Z
2022-01-21T23:20:29.000Z
xill-processor/src/main/java/nl/xillio/xill/plugins/collection/constructs/DuplicateConstruct.java
RobAaldijk/xill-platform
1da3697f39b4c3997b6b40dda82977b293234b36
[ "Apache-2.0" ]
3
2018-03-29T18:52:13.000Z
2021-12-15T09:38:10.000Z
33.578947
90
0.717346
2,028
/** * Copyright (C) 2014 Xillio ([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 nl.xillio.xill.plugins.collection.constructs; import com.google.inject.Inject; import nl.xillio.xill.api.components.MetaExpression; import nl.xillio.xill.api.construct.Argument; import nl.xillio.xill.api.construct.Construct; import nl.xillio.xill.api.construct.ConstructContext; import nl.xillio.xill.api.construct.ConstructProcessor; import nl.xillio.xill.plugins.collection.services.duplicate.Duplicate; /** * Returns a deep copy of the given list or object. * * @author Sander Visser */ public class DuplicateConstruct extends Construct { @Inject private Duplicate duplicate; @Override public ConstructProcessor prepareProcess(final ConstructContext context) { return new ConstructProcessor( input -> process(input, duplicate), new Argument("collection", LIST, OBJECT)); } /** * Returns a deep copy of the given list or object. * * @param input the list or object. * @return the deep copy of the list or object. */ static MetaExpression process(final MetaExpression input, final Duplicate duplicate) { Object obj = extractValue(input); obj = duplicate.duplicate(obj); MetaExpression output = MetaExpression.parseObject(obj); return output; } }
3e04d9d104539392bca67c7554911dd814e60a5d
2,067
java
Java
autocache-core/src/main/java/com/haozi/cache/core/interceptor/CacheOperation.java
haozi2015/AutoCache
2e6066fbf74c8d4746f3bcc7449d9ddf65ab9737
[ "Apache-2.0" ]
8
2020-11-13T08:52:07.000Z
2021-03-21T03:15:32.000Z
autocache-core/src/main/java/com/haozi/cache/core/interceptor/CacheOperation.java
haozi2015/AutoCache
2e6066fbf74c8d4746f3bcc7449d9ddf65ab9737
[ "Apache-2.0" ]
null
null
null
autocache-core/src/main/java/com/haozi/cache/core/interceptor/CacheOperation.java
haozi2015/AutoCache
2e6066fbf74c8d4746f3bcc7449d9ddf65ab9737
[ "Apache-2.0" ]
1
2022-02-11T05:51:53.000Z
2022-02-11T05:51:53.000Z
31.318182
134
0.643928
2,029
package com.haozi.cache.core.interceptor; import com.haozi.cache.core.AutoCache; import com.haozi.cache.core.AutoCacheEvict; import com.haozi.cache.core.util.CacheUtil; import lombok.Builder; import lombok.Data; import org.springframework.util.StringUtils; import java.lang.reflect.Method; /** * 缓存定义 * * @author haozi */ @Data @Builder public class CacheOperation { private String keySEL; private Long localCacheMaximumSize; private Long localCacheExpire; private Long remoteCacheExpire; private boolean elementCache; private String cacheName; // 删除标识 true private boolean evict; /** * 是否定义key * * @return true:是;false;否 */ public boolean isDefinitionKey() { return keySEL != null && !"".equals(keySEL); } public static CacheOperation build(AutoCacheEvict autoCacheEvict) { String cacheName = autoCacheEvict.cacheName(); if (StringUtils.isEmpty(cacheName)) { throw new IllegalArgumentException("AutoCacheEvict[cacheName] must be not blank"); } return CacheOperation.builder() .keySEL(autoCacheEvict.key()) .cacheName(cacheName) .evict(true) .build(); } public static CacheOperation build(AutoCache autoCache, Method method) { if (autoCache.localTTL() <= 0L && autoCache.remoteTTL() <= 0L) { throw new IllegalArgumentException("AutoCache [localTTL] > 0 or [remoteTTL] > 0"); } return CacheOperation.builder() .localCacheExpire(autoCache.localTTL() <= 0L ? null : autoCache.localTTL()) .localCacheMaximumSize(autoCache.localMaxSize()) .remoteCacheExpire(autoCache.remoteTTL() <= 0L ? null : autoCache.remoteTTL()) .keySEL(autoCache.key()) .elementCache(autoCache.elementCache()) .cacheName(StringUtils.isEmpty(autoCache.cacheName()) ? CacheUtil.getDefaultCacheName(method) : autoCache.cacheName()) .build(); } }
3e04d9f894b3374e972198fd1cf51049574979ef
458
java
Java
mall-pms/pms-biz/src/main/java/com/youlai/mall/pms/mapper/PmsSkuMapper.java
gxh9153/youlai-mall
6b04c5a5b40c571cb204cffdf6bd63bc27dcc1b7
[ "MulanPSL-1.0" ]
1
2021-01-28T12:06:52.000Z
2021-01-28T12:06:52.000Z
mall-pms/pms-biz/src/main/java/com/youlai/mall/pms/mapper/PmsSkuMapper.java
gxh9153/youlai-mall
6b04c5a5b40c571cb204cffdf6bd63bc27dcc1b7
[ "MulanPSL-1.0" ]
1
2021-01-21T07:20:24.000Z
2021-01-21T07:20:24.000Z
mall-pms/pms-biz/src/main/java/com/youlai/mall/pms/mapper/PmsSkuMapper.java
leixiao0212/unmall
f616b6d44faa5af9fef150e01c1c8bc9883ff46b
[ "MulanPSL-1.0" ]
null
null
null
24.105263
62
0.71179
2,030
package com.youlai.mall.pms.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.youlai.mall.pms.pojo.PmsSku; import org.apache.ibatis.annotations.Select; import org.mapstruct.Mapper; import java.util.List; @Mapper public interface PmsSkuMapper extends BaseMapper<PmsSku> { @Select("<script>" + " select * from pms_sku where spu_id=#{spuId} " + "</script>") List<PmsSku> listBySpuId(Long spuId); }
3e04da88008c3414263407b9ff707c255dbd7bf2
1,306
java
Java
src/main/java/com/helion3/prism/api/storage/StorageDeleteResult.java
Dirt-Craft/Prism
83da88c19493d811d3d8275b4c9916e429c1a228
[ "MIT" ]
5
2021-04-15T21:25:17.000Z
2022-02-13T17:12:23.000Z
src/main/java/com/helion3/prism/api/storage/StorageDeleteResult.java
Dirt-Craft/Prism
83da88c19493d811d3d8275b4c9916e429c1a228
[ "MIT" ]
null
null
null
src/main/java/com/helion3/prism/api/storage/StorageDeleteResult.java
Dirt-Craft/Prism
83da88c19493d811d3d8275b4c9916e429c1a228
[ "MIT" ]
1
2022-01-19T14:10:31.000Z
2022-01-19T14:10:31.000Z
46.642857
80
0.762634
2,031
/* * This file is part of Prism, licensed under the MIT License (MIT). * * Copyright (c) 2015 Helion3 http://helion3.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.helion3.prism.api.storage; public class StorageDeleteResult implements StorageResult { }
3e04dbd98c30582fb9af72c5a12bec8195bca01b
592
java
Java
Data-Structures/DataStructures/src/graph/TrieNode.java
caow2/Data-Struc
3308592d57e23e9af2809aa1a230a0eeafb4c0d2
[ "MIT" ]
null
null
null
Data-Structures/DataStructures/src/graph/TrieNode.java
caow2/Data-Struc
3308592d57e23e9af2809aa1a230a0eeafb4c0d2
[ "MIT" ]
null
null
null
Data-Structures/DataStructures/src/graph/TrieNode.java
caow2/Data-Struc
3308592d57e23e9af2809aa1a230a0eeafb4c0d2
[ "MIT" ]
null
null
null
23.68
59
0.641892
2,032
package graph; import java.util.HashMap; import java.util.Map; public class TrieNode { Character value; Map<Character, TrieNode> children; boolean terminating; public TrieNode(Character value, boolean terminating) { children = new HashMap<Character, TrieNode>(); this.value = value; this.terminating = terminating; } public boolean addChild(TrieNode node) { Character c = node.value; if (children.containsKey(c)) return false; //already has this child children.put(c, node); return true; } }
3e04dce11cbbe81f9326ef2c16e93b42e576b9ed
921
java
Java
LACCPlus/Camel/151_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Camel/151_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Camel/151_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
48.473684
145
0.504886
2,033
//,temp,AsyncEndpointRedeliveryErrorHandlerNonBlockedDelayTest.java,64,77,temp,AsyncEndpointRedeliveryErrorHandlerNonBlockedDelay2Test.java,67,80 //,2 public class xxx { public void process(Exchange exchange) throws Exception { LOG.info("Processing at attempt {} {}", attempt, exchange); String body = exchange.getIn().getBody(String.class); if (body.contains("Camel")) { if (++attempt <= 2) { LOG.info("Processing failed will thrown an exception"); throw new IllegalArgumentException("Damn"); } } exchange.getIn().setBody("Hello " + body); LOG.info("Processing at attempt {} complete {}", attempt, exchange); } };
3e04dd2d03edcc095a7749c689a3ce4aacbcae00
1,040
java
Java
overlord-commons-auth-jetty8/src/main/java/org/overlord/commons/auth/jetty8/JettyAuthConstants.java
objectiser/overlord-commons
5b293246997ab20233e0f5b6d01ca367e540c7d2
[ "Apache-2.0" ]
null
null
null
overlord-commons-auth-jetty8/src/main/java/org/overlord/commons/auth/jetty8/JettyAuthConstants.java
objectiser/overlord-commons
5b293246997ab20233e0f5b6d01ca367e540c7d2
[ "Apache-2.0" ]
null
null
null
overlord-commons-auth-jetty8/src/main/java/org/overlord/commons/auth/jetty8/JettyAuthConstants.java
objectiser/overlord-commons
5b293246997ab20233e0f5b6d01ca367e540c7d2
[ "Apache-2.0" ]
1
2022-02-09T07:20:35.000Z
2022-02-09T07:20:35.000Z
33.774194
84
0.711557
2,034
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.commons.auth.jetty8; /** * Some jetty 8 auth constants. * * @author [email protected] */ public class JettyAuthConstants { public static final String [] ROLE_CLASSES = new String [] { "org.eclipse.jetty.security.MappedLoginService$RolePrincipal", //$NON-NLS-1$ "org.eclipse.jetty.plus.jaas.JAASRole", //$NON-NLS-1$ "org.apache.karaf.jaas.boot.principal.RolePrincipal" //$NON-NLS-1$ }; }
3e04dda52c8d3221a61c0bbc3ea9234122ca016b
1,760
java
Java
drawme/src/main/java/com/github/shareme/greenandroid/drawme/DrawMeFrameLayout.java
shareme/GreenAndroid
f9f9db8317c0d5e26855e891b31883bf5f18fc64
[ "Apache-2.0" ]
2
2016-11-28T09:57:01.000Z
2017-01-24T10:20:48.000Z
drawme/src/main/java/com/github/shareme/greenandroid/drawme/DrawMeFrameLayout.java
shareme/GreenAndroid
f9f9db8317c0d5e26855e891b31883bf5f18fc64
[ "Apache-2.0" ]
null
null
null
drawme/src/main/java/com/github/shareme/greenandroid/drawme/DrawMeFrameLayout.java
shareme/GreenAndroid
f9f9db8317c0d5e26855e891b31883bf5f18fc64
[ "Apache-2.0" ]
null
null
null
33.846154
88
0.744886
2,035
/* Copyright 2016 Rafał Kobyłko Modifications Copyright(C) 2016 Fred Grott(GrottWorkShop) 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.github.shareme.greenandroid.drawme; import android.content.Context; import android.util.AttributeSet; import android.widget.FrameLayout; import com.github.shareme.greenandroid.drawme.delegate.DrawMe; import com.github.shareme.greenandroid.drawme.delegate.DrawMeShape; @SuppressWarnings("unused") public class DrawMeFrameLayout extends FrameLayout { private final DrawMe drawMe; public DrawMeFrameLayout(Context context) { super(context); drawMe = new DrawMeShape(context, this, null); } public DrawMeFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); drawMe = new DrawMeShape(context, this, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int[] size = drawMe.onMeasure(widthMeasureSpec, heightMeasureSpec); super.onMeasure(size[0], size[1]); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); drawMe.onLayout(changed, left, top, right, bottom); } }
3e04de055cf5693d118032f3e335339d67c6cca8
494
java
Java
src/main/java/com/denizenscript/depenizen/bukkit/bungee/packets/out/MyInfoPacketOut.java
jplusc/Depenizen
2086ead41b6041f6b8a49765f16a27eaf8105693
[ "MIT" ]
32
2016-12-19T19:54:11.000Z
2022-03-05T22:42:29.000Z
src/main/java/com/denizenscript/depenizen/bukkit/bungee/packets/out/MyInfoPacketOut.java
jplusc/Depenizen
2086ead41b6041f6b8a49765f16a27eaf8105693
[ "MIT" ]
245
2016-10-02T21:54:18.000Z
2022-03-05T23:26:39.000Z
src/main/java/com/denizenscript/depenizen/bukkit/bungee/packets/out/MyInfoPacketOut.java
jplusc/Depenizen
2086ead41b6041f6b8a49765f16a27eaf8105693
[ "MIT" ]
44
2016-12-11T20:22:28.000Z
2022-03-06T22:35:34.000Z
19.76
62
0.674089
2,036
package com.denizenscript.depenizen.bukkit.bungee.packets.out; import com.denizenscript.depenizen.bukkit.bungee.PacketOut; import io.netty.buffer.ByteBuf; public class MyInfoPacketOut extends PacketOut { public MyInfoPacketOut(int port) { this.port = port; canBeFirstPacket = true; } public int port; @Override public int getPacketId() { return 11; } @Override public void writeTo(ByteBuf buf) { buf.writeInt(port); } }
3e04df0a76ed9bc4ece8c6ba2f11b6b46090bcff
264
java
Java
sourcecode/Android/dConnectSDK/dConnectSDKForAndroid/src/com/nttdocomo/dconnect/message/intent/impl/conn/package-info.java
nokok/DeviceConnect
fa93a692f3ad231f869304b02a17e96326205eb0
[ "MIT" ]
1
2015-11-08T09:17:26.000Z
2015-11-08T09:17:26.000Z
sourcecode/Android/dConnectSDK/dConnectSDKForAndroid/src/com/nttdocomo/dconnect/message/intent/impl/conn/package-info.java
nokok/DeviceConnect
fa93a692f3ad231f869304b02a17e96326205eb0
[ "MIT" ]
null
null
null
sourcecode/Android/dConnectSDK/dConnectSDKForAndroid/src/com/nttdocomo/dconnect/message/intent/impl/conn/package-info.java
nokok/DeviceConnect
fa93a692f3ad231f869304b02a17e96326205eb0
[ "MIT" ]
null
null
null
24
56
0.761364
2,037
/* com.nttdocomo.dconnect.message.intent.impl.conn Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ /** * Intentメッセージコネクションパッケージ. */ package com.nttdocomo.dconnect.message.intent.impl.conn;
3e04df15be0f25ed02a43d0c3b64d7b13bbc5c61
3,336
java
Java
zoltar-tensorflow/src/main/java/com/spotify/zoltar/tf/TensorFlowModel.java
regadas/zoltar
fdcad8d91ae004b001ea6f9979c68e565a0e3203
[ "Apache-2.0" ]
null
null
null
zoltar-tensorflow/src/main/java/com/spotify/zoltar/tf/TensorFlowModel.java
regadas/zoltar
fdcad8d91ae004b001ea6f9979c68e565a0e3203
[ "Apache-2.0" ]
null
null
null
zoltar-tensorflow/src/main/java/com/spotify/zoltar/tf/TensorFlowModel.java
regadas/zoltar
fdcad8d91ae004b001ea6f9979c68e565a0e3203
[ "Apache-2.0" ]
null
null
null
29.263158
158
0.686151
2,038
/*- * -\-\- * zoltar-tensorflow * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * 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.spotify.zoltar.tf; import com.google.auto.value.AutoValue; import com.spotify.zoltar.Model; import com.spotify.zoltar.fs.FileSystemExtras; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.List; import org.tensorflow.SavedModelBundle; /** * This model can be used to load TensorFlow {@link SavedModelBundle} model. Whenever possible * {@link TensorFlowModel} should be used in favour of {@link TensorFlowGraphModel}. * * <p>TensorFlowModel is thread-safe.</p> */ @AutoValue public abstract class TensorFlowModel implements Model<SavedModelBundle> { private static final Options DEFAULT_OPTIONS = Options.builder() .tags(Collections.singletonList("serve")) .build(); /** * Note: Please use Models from zoltar-models module. * * <p>Returns a TensorFlow model given {@link SavedModelBundle} export directory URI.</p> */ public static TensorFlowModel create(final URI modelResource) throws IOException { return create(modelResource, DEFAULT_OPTIONS); } /** * Note: Please use Models from zoltar-models module. * * <p>Returns a TensorFlow model given {@link SavedModelBundle} export directory URI and * {@link Options}.</p> */ public static TensorFlowModel create(final URI modelResource, final Options options) throws IOException { final URI localDir = FileSystemExtras.downloadIfNonLocal(modelResource); final SavedModelBundle model = SavedModelBundle.load(localDir.toString(), options.tags().toArray(new String[0])); return new AutoValue_TensorFlowModel(model, options); } /** * Close the model. */ @Override public void close() throws Exception { if (instance() != null) { instance().close(); } } /** * Returns TensorFlow {@link SavedModelBundle}. */ @Override public abstract SavedModelBundle instance(); /** * {@link Options} of this model. */ public abstract Options options(); /** * Value class for our TensorFlow options. */ @AutoValue public abstract static class Options { /** * Returns a list of Tags, see <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/tag_constants.py#L26">tags</a>. */ public abstract List<String> tags(); public static Builder builder() { return new AutoValue_TensorFlowModel_Options.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder tags(List<String> tags); public abstract Options build(); } } }
3e04df524adf8cc90feb24e2eeb5eaf2c8fa6c90
3,833
java
Java
src/test/java/de/neuland/pug4j/Pug4JIntegrationTest.java
neuland/pug4j
383ce47fdb79094205bdd285b82cf6ae7f12a097
[ "MIT" ]
27
2020-09-20T07:27:11.000Z
2022-03-30T19:39:22.000Z
src/test/java/de/neuland/pug4j/Pug4JIntegrationTest.java
neuland/pug4j
383ce47fdb79094205bdd285b82cf6ae7f12a097
[ "MIT" ]
8
2020-12-15T02:06:17.000Z
2022-01-28T15:02:37.000Z
src/test/java/de/neuland/pug4j/Pug4JIntegrationTest.java
neuland/pug4j
383ce47fdb79094205bdd285b82cf6ae7f12a097
[ "MIT" ]
6
2021-01-22T11:41:51.000Z
2022-02-28T00:39:38.000Z
37.213592
109
0.660579
2,039
package de.neuland.pug4j; import de.neuland.pug4j.expression.JexlExpressionHandler; import de.neuland.pug4j.filter.CDATAFilter; import de.neuland.pug4j.filter.Filter; import de.neuland.pug4j.filter.MarkdownFilter; import de.neuland.pug4j.filter.PlainFilter; import de.neuland.pug4j.template.FileTemplateLoader; import de.neuland.pug4j.template.PugTemplate; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class Pug4JIntegrationTest { private static String[] ignoredCases = new String[] { "include-with-filter" }; private String file; public Pug4JIntegrationTest(String file) { this.file = file; } @Test public void shouldCompilePugToHtml() throws Exception { PugConfiguration pug = new PugConfiguration(); pug.setExpressionHandler(new JexlExpressionHandler()); String fileTemplateLoaderPath = TestFileHelper.getPug4JTestsResourcePath(""); FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(fileTemplateLoaderPath, "pug"); String basePath = "cases"; fileTemplateLoader.setBase(basePath); pug.setTemplateLoader(fileTemplateLoader); pug.setMode(Pug4J.Mode.XHTML); // original jade uses xhtml by default pug.setFilter("plain", new PlainFilter()); pug.setFilter("cdata", new CDATAFilter()); pug.setFilter("markdown", new MarkdownFilter()); pug.setFilter("markdown-it", new MarkdownFilter()); pug.setFilter("custom", new Filter() { @Override public String convert(String source, Map<String, Object> attributes, Map<String, Object> model) { Object opt = attributes.get("opt"); Object num = attributes.get("num"); assertEquals("val",opt); assertEquals(2,num); return "BEGIN"+source+"END"; } }); pug.setFilter("verbatim", new Filter() { @Override public String convert(String source, Map<String, Object> attributes, Map<String, Object> model) { return "\n"+source+"\n"; } }); pug.setPrettyPrint(true); PugTemplate template = pug.getTemplate("" + file); Writer writer = new StringWriter(); HashMap<String, Object> model = new HashMap<String, Object>(); model.put("title","Pug"); pug.renderTemplate(template,model, writer); String html = writer.toString(); String pathToExpectedHtml = fileTemplateLoaderPath +basePath+ file.replace(".pug", ".html"); String expected = readFile(pathToExpectedHtml).trim().replaceAll("\r", ""); assertEquals(file, expected, html.trim()); } private String readFile(String fileName) throws IOException { return FileUtils.readFileToString(new File(fileName)); } @Parameterized.Parameters(name="{0}") public static Collection<String[]> data() { File folder = new File(TestFileHelper.getPug4JTestsResourcePath("/cases")); Collection<File> files = FileUtils.listFiles(folder, new String[]{"pug"}, false); Collection<String[]> data = new ArrayList<String[]>(); for (File file : files) { if (!ArrayUtils.contains(ignoredCases, file.getName().replace(".pug", ""))) { data.add(new String[]{"/"+file.getName()}); } } return data; } }
3e04e0203b0995a5b7bf4bad23a9d782a3d2490f
4,170
java
Java
src/main/java/de/dm/microservices/controller/ServiceController.java
dm-drogeriemarkt/selavi
593ca805632762b64e7d8049034e714813c58f36
[ "MIT" ]
22
2017-11-24T15:08:04.000Z
2020-11-14T22:45:29.000Z
src/main/java/de/dm/microservices/controller/ServiceController.java
dm-drogeriemarkt/selavi
593ca805632762b64e7d8049034e714813c58f36
[ "MIT" ]
21
2017-11-28T20:11:39.000Z
2018-09-21T15:50:58.000Z
src/main/java/de/dm/microservices/controller/ServiceController.java
dm-drogeriemarkt/selavi
593ca805632762b64e7d8049034e714813c58f36
[ "MIT" ]
8
2017-11-27T08:16:42.000Z
2021-07-27T12:35:28.000Z
55.6
158
0.776978
2,040
package de.dm.microservices.controller; import de.dm.microservices.business.ServiceRegistryContentProvider; import de.dm.microservices.domain.ConsumeDto; import de.dm.microservices.business.MicroserviceConditioningService; import de.dm.microservices.domain.MicroserviceDto; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Collection; @RestController @RequestMapping("/services") public class ServiceController { private final MicroserviceConditioningService microserviceConditioningService; private final ServiceRegistryContentProvider serviceRegistryContentProvider; @Autowired public ServiceController(MicroserviceConditioningService microserviceConditioningService, ServiceRegistryContentProvider serviceRegistryContentProvider) { this.microserviceConditioningService = microserviceConditioningService; this.serviceRegistryContentProvider = serviceRegistryContentProvider; } @ApiOperation(value = "Get the names of all available deployment stages (eg, 'dev', 'rls', 'prod', ...)") @RequestMapping(value = "/stages", method = RequestMethod.GET) public Collection<String> getAllStageNames() { return serviceRegistryContentProvider.getAllStageNames(); } @ApiOperation(value = "Read all microservices from the specified stage of the registry and enrich them with saved additional properties from db.") @RequestMapping(value = "/{stage}", method = RequestMethod.GET) public Collection<MicroserviceDto> readAllServices(@PathVariable String stage) { return microserviceConditioningService.getAllMicroserviceDtos(stage); } @ApiOperation(value = "Add a new service as node to add properties and relations to other services.") @RequestMapping(value = "/{stage}", method = RequestMethod.POST) public void addNewService(@PathVariable String stage, @RequestBody MicroserviceDto dto) { microserviceConditioningService.addNewService(stage, dto); } @ApiOperation(value = "Add a new property or update an existing. Properties internal properties are not allowed to be set.") @RequestMapping(value = "/{stage}/{serviceName}/properties", method = RequestMethod.PUT) public void updateService(@PathVariable String stage, @PathVariable String serviceName, @RequestBody MicroserviceDto dto) { microserviceConditioningService.updateService(stage, dto); } @ApiOperation(value = "Delete a service node. Only manually added and not from the registry loaded are allowed to delete.") @RequestMapping(value = "/{stage}/{serviceName}", method = RequestMethod.DELETE) public void deleteService(@PathVariable String stage, @PathVariable String serviceName) { microserviceConditioningService.deleteService(stage, serviceName); } @ApiOperation(value = "Add a new relation between two services.") @RequestMapping(value = "/{stage}/{serviceName}/relations", method = RequestMethod.POST) public void addNewRelation(@PathVariable String stage, @PathVariable String serviceName, @RequestBody ConsumeDto consumeDto) { microserviceConditioningService.addNewRelation(stage, serviceName, consumeDto); } @ApiOperation(value = "Delete a relation between two services. If the last relation ist removed, the 'consumes' property will also removed.") @RequestMapping(value = "/{stage}/{serviceName}/relations/{relatedServiceName}", method = RequestMethod.DELETE) public void deleteRelation(@PathVariable String stage, @PathVariable String serviceName, @PathVariable String relatedServiceName) { microserviceConditioningService.deleteRelation(stage, serviceName, relatedServiceName); } @ApiOperation(value = "Edit a relation between two services.") @RequestMapping(value = "/{serviceName}/relations/{consumeDto}", method = RequestMethod.PUT) public void editRelation(@PathVariable String stage, @PathVariable String serviceName, @RequestBody ConsumeDto consumeDto) { microserviceConditioningService.editRelation(stage, serviceName, consumeDto); } }
3e04e0a8d99e96e2ff5a775bb00c8023f2d928cb
1,223
java
Java
src/main/test/com/numberONe/SpringTest.java
GGFocus/Logistics
f4500a9639ad306e813b31b609445e6b57aa502f
[ "Apache-2.0" ]
1
2018-01-30T08:49:02.000Z
2018-01-30T08:49:02.000Z
src/main/test/com/numberONe/SpringTest.java
progressiveDevelopers/Logistics
f4500a9639ad306e813b31b609445e6b57aa502f
[ "Apache-2.0" ]
null
null
null
src/main/test/com/numberONe/SpringTest.java
progressiveDevelopers/Logistics
f4500a9639ad306e813b31b609445e6b57aa502f
[ "Apache-2.0" ]
null
null
null
22.236364
81
0.636958
2,041
package com.numberONe; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.numberONe.util.TimeConUtil; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring-application.xml"}) //加载配置文件 public class SpringTest { @Autowired private EmailUtil emailUtil; @Autowired private TimeConUtil timeConUtil; @Test public void TimeTask() { System.out.println(timeConUtil); try { timeConUtil.sendEmailForUnRate(); } catch (Exception e) { e.printStackTrace(); } } @Test public void emailProperties() { System.out.println("测试email发送人员"); emailUtil.sendHtmlMailAndBc("1","1","1","1"); } @Test public void TimeTaskRateInfo() { System.out.println(timeConUtil); try { timeConUtil.findUserInfoList(); } catch (Exception e) { e.printStackTrace(); } } }
3e04e3c70b7889db73676414699b0794b5dbf864
3,592
java
Java
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntityComposer.java
jvalkeal/kite
ac4dc8d9af8534965a86e61a36f73d1b30004572
[ "Apache-2.0" ]
342
2015-01-01T11:17:24.000Z
2022-02-11T06:11:00.000Z
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntityComposer.java
jvalkeal/kite
ac4dc8d9af8534965a86e61a36f73d1b30004572
[ "Apache-2.0" ]
189
2015-01-01T00:59:01.000Z
2022-01-13T09:30:11.000Z
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntityComposer.java
jvalkeal/kite
ac4dc8d9af8534965a86e61a36f73d1b30004572
[ "Apache-2.0" ]
238
2015-01-03T18:35:10.000Z
2022-03-24T06:32:18.000Z
30.700855
80
0.677895
2,042
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.hbase.impl; import java.util.Map; import org.kitesdk.data.PartitionStrategy; import org.kitesdk.data.spi.PartitionKey; /** * An EntityComposer is an interface that supports entity construction and * de-construction methods. This includes getting a Builder for an entity, * building keyAsColumn field values, and extracting fields and keyAsColumn * fields. * * These are basically all methods an EntityMapper would need to do the entity * record construction/de-construction from HBase column values. * * @param <E> * The type of entity this composer works with. */ public interface EntityComposer<E> { /** * Get an Entity Builder that can build Entity types for this composer. * * @return The entity builder. */ public Builder<E> getBuilder(); /** * Extract a field from the entity by name * * @param entity * The entity to extract a field from. * @param fieldName * The name of the field to extract * @return The field value */ public Object extractField(E entity, String fieldName); /** * Extract a PartitionKey for the given Strategy. * * @param strategy a PartitionStrategy for the entity * @param entity The entity to extract a partition key from. * @return a PartitionKey for the entity */ public PartitionKey extractKey(PartitionStrategy strategy, E entity); /** * Transform the keyAsColumn field value into a Map * * @param fieldName * The name of the keyAsColumn field. * @param fieldValue * The value of the entities field specified by field name. The value * can be any type the implementation supports for keyAsColumn fields * @return The keyAsColumn field value as a map */ public Map<CharSequence, Object> extractKeyAsColumnValues(String fieldName, Object fieldValue); /** * Build a keyAsColumn field for the entity from a map of keyAsColumn values. * This is the inverse of extractKeyAsColumnValues. It will turn the map into * the type the entity uses for its keyAsColumn field. * * @param fieldName * The name of the field * @param keyAsColumnValues * The map of keyAsColumn values. * @return The field value */ public Object buildKeyAsColumnField(String fieldName, Map<CharSequence, Object> keyAsColumnValues); /** * An interface for entity builders. * * @param <E> * The type of the entity this builder builds. */ public interface Builder<E> { /** * Put a field value into the entity. * * @param fieldName * The name of the field * @param value * The value of the field * @return A reference to the Builder, so puts can be chained. */ public Builder<E> put(String fieldName, Object value); /** * Builds the entity, and returns it. * * @return The built entity */ public E build(); } }
3e04e68b86a0ec8e8ecbb59d23f5d0a323af0a4f
5,354
java
Java
core/src/main/java/de/adorsys/keymanagement/core/view/EntryViewImpl.java
hoggmania/keystore-management
61668194d19456a5dac3ae0949ab1ad7aa716ce0
[ "Apache-2.0" ]
14
2019-10-21T09:48:40.000Z
2021-12-20T13:02:05.000Z
core/src/main/java/de/adorsys/keymanagement/core/view/EntryViewImpl.java
mohbadar/keystore-management
cf7fbc9801bea1866bdbbaec2dd228604281f1b1
[ "Apache-2.0" ]
1
2020-04-22T09:26:20.000Z
2021-08-16T06:55:53.000Z
core/src/main/java/de/adorsys/keymanagement/core/view/EntryViewImpl.java
mohbadar/keystore-management
cf7fbc9801bea1866bdbbaec2dd228604281f1b1
[ "Apache-2.0" ]
6
2019-11-20T11:08:58.000Z
2021-11-02T10:22:30.000Z
37.180556
118
0.728054
2,043
package de.adorsys.keymanagement.core.view; import com.googlecode.cqengine.IndexedCollection; import com.googlecode.cqengine.TransactionalIndexedCollection; import com.googlecode.cqengine.attribute.SimpleAttribute; import com.googlecode.cqengine.attribute.SimpleNullableAttribute; import com.googlecode.cqengine.index.Index; import com.googlecode.cqengine.index.hash.HashIndex; import com.googlecode.cqengine.index.radix.RadixTreeIndex; import com.googlecode.cqengine.query.Query; import com.googlecode.cqengine.query.parser.sql.SQLParser; import com.googlecode.cqengine.resultset.ResultSet; import de.adorsys.keymanagement.api.CqeQueryResult; import de.adorsys.keymanagement.api.source.KeySource; import de.adorsys.keymanagement.api.types.ResultCollection; import de.adorsys.keymanagement.api.types.entity.KeyEntry; import de.adorsys.keymanagement.api.types.entity.metadata.KeyMetadata; import de.adorsys.keymanagement.api.types.template.provided.ProvidedKeyEntry; import de.adorsys.keymanagement.api.view.EntryView; import de.adorsys.keymanagement.api.view.QueryResult; import lombok.Getter; import lombok.SneakyThrows; import java.util.Collection; import java.util.stream.Collectors; import static com.googlecode.cqengine.codegen.AttributeBytecodeGenerator.createAttributes; import static com.googlecode.cqengine.codegen.MemberFilters.GETTER_METHODS_ONLY; import static com.googlecode.cqengine.query.QueryFactory.and; import static com.googlecode.cqengine.query.QueryFactory.attribute; import static com.googlecode.cqengine.query.QueryFactory.equal; import static com.googlecode.cqengine.query.QueryFactory.nullableAttribute; import static de.adorsys.keymanagement.core.view.ViewUtil.SNAKE_CASE; public class EntryViewImpl extends BaseUpdatingView<Query<KeyEntry>, KeyEntry> implements EntryView<Query<KeyEntry>> { public static final SimpleAttribute<KeyEntry, String> A_ID = attribute("alias", KeyEntry::getAlias); public static final SimpleNullableAttribute<KeyEntry, KeyMetadata> META = nullableAttribute( "meta", KeyEntry::getMeta ); public static final SimpleAttribute<KeyEntry, Boolean> IS_META = attribute( "is_meta", KeyEntry::isMetadataEntry ); private static final SQLParser<KeyEntry> PARSER = SQLParser.forPojoWithAttributes( KeyEntry.class, createAttributes(KeyEntry.class, GETTER_METHODS_ONLY, SNAKE_CASE) ); @Getter private final KeySource source; private final Query<KeyEntry> viewFilter; /** * Note that keystore aliases are case-insensitive in general case */ private final IndexedCollection<KeyEntry> keys = new TransactionalIndexedCollection<>(KeyEntry.class); @SneakyThrows public EntryViewImpl(KeySource source, Query<KeyEntry> viewFilter, Collection<Index<KeyEntry>> indexes) { this.source = source; this.viewFilter = viewFilter; keys.addAll( source.aliasesFor(ProvidedKeyEntry.class) .map(it -> new KeyEntry(it.getKey(), source.asEntry(it.getKey()))) .collect(Collectors.toList()) ); this.keys.addIndex(RadixTreeIndex.onAttribute(A_ID)); this.keys.addIndex(HashIndex.onAttribute(META)); this.keys.addIndex(HashIndex.onAttribute(IS_META)); indexes.forEach(keys::addIndex); } @Override public QueryResult<KeyEntry> retrieve(Query<KeyEntry> query) { return new CqeQueryResult<>(keys.retrieve(and(viewFilter, query))); } @Override public QueryResult<KeyEntry> retrieve(String query) { return new CqeQueryResult<>(keys.retrieve(and(viewFilter, PARSER.parse(query).getQuery()))); } @Override public KeyEntry uniqueResult(Query<KeyEntry> query) { try (ResultSet<KeyEntry> unique = keys.retrieve(and(viewFilter, query))) { return unique.uniqueResult(); } } @Override public KeyEntry uniqueResult(String query) { try (ResultSet<KeyEntry> unique = keys.retrieve(and(viewFilter, PARSER.query(query)))) { return unique.uniqueResult(); } } @Override public ResultCollection<KeyEntry> all() { return new CqeQueryResult<>(keys.retrieve(viewFilter)).toCollection(); } @Override public QueryResult<KeyEntry> secretKeys() { return retrieve("SELECT * FROM keys WHERE is_secret = true"); } @Override public QueryResult<KeyEntry> privateKeys() { return retrieve("SELECT * FROM keys WHERE is_private = true"); } @Override public QueryResult<KeyEntry> trustedCerts() { return retrieve("SELECT * FROM keys WHERE is_trusted_cert = true"); } @Override protected String getKeyId(KeyEntry ofKey) { return ofKey.getAlias(); } @Override protected KeyEntry fromSource(String ofKey) { return new KeyEntry(ofKey, source.asEntry(ofKey)); } @Override protected KeyEntry fromCollection(String ofKey) { // Skip view filter try (ResultSet<KeyEntry> byId = keys.retrieve(equal(A_ID, ofKey))) { return byId.uniqueResult(); } } @Override protected boolean updateCollection(Collection<KeyEntry> keysToRemove, Collection<KeyEntry> keysToAdd) { return keys.update(keysToRemove, keysToAdd); } }
3e04e69404c2978d20ae9677550bf69bad09ca0d
2,036
java
Java
src/main/java/com/wedevol/xmpp/EntryPoint.java
duonglam22/xmppServerProtocolDemo
04c029d7e8781ed2a901c82a2e61b2781bd6588f
[ "Apache-2.0" ]
2
2022-03-21T07:38:47.000Z
2022-03-31T02:25:45.000Z
src/main/java/com/wedevol/xmpp/EntryPoint.java
duonglam22/xmppServerProtocolDemo
04c029d7e8781ed2a901c82a2e61b2781bd6588f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wedevol/xmpp/EntryPoint.java
duonglam22/xmppServerProtocolDemo
04c029d7e8781ed2a901c82a2e61b2781bd6588f
[ "Apache-2.0" ]
null
null
null
32.83871
179
0.765717
2,044
package com.wedevol.xmpp; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.XMPPException; import com.wedevol.xmpp.bean.CcsOutMessage; import com.wedevol.xmpp.server.CcsClient; import com.wedevol.xmpp.server.MessageHelper; import com.wedevol.xmpp.util.Util; /** * Entry Point class for the XMPP Server in dev mode for debugging and testing * purposes */ public class EntryPoint { public static final Logger logger = Logger.getLogger(EntryPoint.class.getName()); public static void main(String[] args) { // final String fcmProjectSenderId = args[0]; // final String fcmServerKey = args[1]; // final String toRegId = args[2]; // String fcmProjectSenderId = "messagecloudexample"; String fcmProjectSenderId = "97098250087"; String fcmServerKey = "AAAAFpuBt2c:APA91bEtr3dDnEooTASU_W24bn13d2G0W_VXOXXLSJSJxSZpLNKxQEENYl-mgr-Juap2U8Qj61C8WEVEbKBYl7gLJFwE9RIRVJXMXuncF3MdhBOTmp-sfQB4OPRI2N4vFFkDuf9SZROd"; String toRegId = "registerId"; CcsClient ccsClient = CcsClient.prepareClient(fcmProjectSenderId, fcmServerKey, false); try { ccsClient.connect(); } catch (XMPPException e) { logger.log(Level.SEVERE, "Error trying to connect.", e); } // Send a sample downstream message to a device // String messageId = Util.getUniqueMessageId(); // Map<String, String> dataPayload = new HashMap<String, String>(); // dataPayload.put(Util.PAYLOAD_ATTRIBUTE_MESSAGE, "This is the simple sample message"); // CcsOutMessage message = new CcsOutMessage(toRegId, messageId, dataPayload); // String jsonRequest = MessageHelper.createJsonOutMessage(message); // ccsClient.send(jsonRequest); Process process = new Process(ccsClient); int numberOfMsg; Scanner scanner = new Scanner(System.in); System.out.println("input number of msg: "); numberOfMsg = scanner.nextInt(); process.fillNotificationQueue(numberOfMsg); // process.fillDataQueue(numberOfMsg); process.start(); } }
3e04e6d45c9d885699a0bfd9122999603cbe2b38
979
java
Java
Dalton/UnitTest/Test.java
anjukumar/workspace
d7a8a4088a230592bfb3b78d3e007705904ad56b
[ "Apache-2.0" ]
null
null
null
Dalton/UnitTest/Test.java
anjukumar/workspace
d7a8a4088a230592bfb3b78d3e007705904ad56b
[ "Apache-2.0" ]
null
null
null
Dalton/UnitTest/Test.java
anjukumar/workspace
d7a8a4088a230592bfb3b78d3e007705904ad56b
[ "Apache-2.0" ]
null
null
null
25.102564
105
0.688458
2,045
import static org.junit.Assert.*; import java.util.List; import customTools.DbCustomers; import model.Daltoncustomer; public class Test { @org.junit.Test public void test() { List<Daltoncustomer> customers = DbCustomers.Daltoncustomer(1); System.out.println(customers); int numberofaccounts = customers.get(0).getDaltonaccounts().size(); System.out.println("Customer has " +numberofaccounts +"accounts"); long balance = 0; for(int i =0 ; i< numberofaccounts;i ++) { int numberOfTransactions = customers.get(0).getDaltonaccounts().get(i).getDaltontransactions().size(); System.out.println("Number of transactions Account Number: " +i +" has is " +numberOfTransactions); for(int j = 0 ; j<numberOfTransactions; j++) { balance = customers.get(0).getDaltonaccounts().get(i).getDaltontransactions().get(j).getAmount(); } System.out.println("Current Balance is : " +balance); } } public void test3(){ } }
3e04e75e1669e89f5bd4f23e212a6725a3d77268
21,630
java
Java
server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
karesti/infinispan
8380034e101e3c5d8e6818f1bdf92ad8248d8735
[ "Apache-2.0" ]
null
null
null
server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
karesti/infinispan
8380034e101e3c5d8e6818f1bdf92ad8248d8735
[ "Apache-2.0" ]
1
2017-09-15T18:57:37.000Z
2017-09-15T18:57:37.000Z
server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
karesti/infinispan
8380034e101e3c5d8e6818f1bdf92ad8248d8735
[ "Apache-2.0" ]
null
null
null
43.433735
167
0.738927
2,046
package org.infinispan.server.hotrod; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import javax.security.sasl.SaslServerFactory; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.IllegalLifecycleStateException; import org.infinispan.commons.CacheException; import org.infinispan.commons.equivalence.AnyEquivalence; import org.infinispan.commons.logging.LogFactory; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.CollectionFactory; import org.infinispan.commons.util.ServiceFinder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.context.Flag; import org.infinispan.distexec.DefaultExecutorService; import org.infinispan.distexec.DistributedCallable; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.factories.ComponentRegistry; import org.infinispan.filter.KeyValueFilterConverterFactory; import org.infinispan.filter.NamedFactory; import org.infinispan.filter.ParamKeyValueFilterConverterFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.remoting.transport.Address; import org.infinispan.server.core.AbstractProtocolServer; import org.infinispan.server.core.QueryFacade; import org.infinispan.server.core.security.SaslUtils; import org.infinispan.server.core.transport.NettyInitializers; import org.infinispan.server.hotrod.configuration.HotRodServerConfiguration; import org.infinispan.server.hotrod.event.KeyValueWithPreviousEventConverterFactory; import org.infinispan.server.hotrod.iteration.DefaultIterationManager; import org.infinispan.server.hotrod.iteration.IterationManager; import org.infinispan.server.hotrod.logging.Log; import org.infinispan.server.hotrod.transport.HotRodChannelInitializer; import org.infinispan.server.hotrod.transport.TimeoutEnabledChannelInitializer; import org.infinispan.upgrade.RollingUpgradeManager; import org.infinispan.util.concurrent.IsolationLevel; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandler; import io.netty.util.concurrent.DefaultThreadFactory; /** * Hot Rod server, in charge of defining its encoder/decoder and, if clustered, update the topology information on * startup and shutdown. * <p> * TODO: It's too late for 5.1.1 series. In 5.2, split class into: local and cluster hot rod servers This should safe * some memory for the local case and the code should be cleaner * * @author Galder Zamarreño * @since 4.1 */ public class HotRodServer extends AbstractProtocolServer<HotRodServerConfiguration> { private static final Log log = LogFactory.getLog(HotRodServer.class, Log.class); public HotRodServer() { super("HotRod"); } private boolean isClustered; private Address clusterAddress; private ServerAddress address; private Cache<Address, ServerAddress> addressCache; private Map<String, AdvancedCache> knownCaches = CollectionFactory.makeConcurrentMap(4, 0.9f, 16); private Map<String, Configuration> knownCacheConfigurations = CollectionFactory.makeConcurrentMap(4, 0.9f, 16); private Map<String, ComponentRegistry> knownCacheRegistries = CollectionFactory.makeConcurrentMap(4, 0.9f, 16); private List<QueryFacade> queryFacades; private Map<String, SaslServerFactory> saslMechFactories = CollectionFactory.makeConcurrentMap(4, 0.9f, 16); private ClientListenerRegistry clientListenerRegistry; private Marshaller marshaller; private DefaultExecutorService distributedExecutorService; private CrashedMemberDetectorListener viewChangeListener; private ReAddMyAddressListener topologyChangeListener; protected ExecutorService executor; private IterationManager iterationManager; public ServerAddress getAddress() { return address; } public Marshaller getMarshaller() { return marshaller; } byte[] query(AdvancedCache<byte[], byte[]> cache, byte[] query) { return queryFacades.get(0).query(cache, query); } public ClientListenerRegistry getClientListenerRegistry() { return clientListenerRegistry; } @Override public ChannelOutboundHandler getEncoder() { return new HotRodEncoder(cacheManager, this); } @Override public HotRodDecoder getDecoder() { return new HotRodDecoder(cacheManager, transport, this, this::isCacheIgnored); } @Override protected void startInternal(HotRodServerConfiguration configuration, EmbeddedCacheManager cacheManager) { // These are also initialized by super.startInternal, but we need them before this.configuration = configuration; this.cacheManager = cacheManager; this.iterationManager = new DefaultIterationManager(cacheManager); // populate the sasl factories based on the required mechs setupSasl(); // Initialize query-specific stuff queryFacades = loadQueryFacades(); clientListenerRegistry = new ClientListenerRegistry(configuration); addCacheEventConverterFactory("key-value-with-previous-converter-factory", new KeyValueWithPreviousEventConverterFactory()); loadFilterConverterFactories(ParamKeyValueFilterConverterFactory.class, (name, f) -> addKeyValueFilterConverterFactory(name, (KeyValueFilterConverterFactory) f)); loadFilterConverterFactories(CacheEventFilterConverterFactory.class, this::addCacheEventFilterConverterFactory); loadFilterConverterFactories(CacheEventConverterFactory.class, this::addCacheEventConverterFactory); loadFilterConverterFactories(KeyValueFilterConverterFactory.class, this::addKeyValueFilterConverterFactory); // Start default cache and the endpoint before adding self to // topology in order to avoid topology updates being used before // endpoint is available. super.startInternal(configuration, cacheManager); // Add self to topology cache last, after everything is initialized GlobalConfiguration globalConfig = cacheManager.getCacheManagerConfiguration(); isClustered = globalConfig.transport().transport() != null; if (isClustered) { defineTopologyCacheConfig(cacheManager); if (log.isDebugEnabled()) log.debugf("Externally facing address is %s:%d", configuration.proxyHost(), configuration.proxyPort()); addSelfToTopologyView(cacheManager); } } AbortPolicy abortPolicy = new AbortPolicy() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (executor.isShutdown()) throw new IllegalLifecycleStateException("Server has been stopped"); else super.rejectedExecution(r, e); } }; public ExecutorService getExecutor(String threadPrefix) { if (this.executor == null || this.executor.isShutdown()) { DefaultThreadFactory factory = new DefaultThreadFactory(threadPrefix + "ServerHandler"); this.executor = new ThreadPoolExecutor( getConfiguration().workerThreads(), getConfiguration().workerThreads(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), factory, abortPolicy); } return executor; } @Override public ChannelInitializer<Channel> getInitializer() { if (configuration.idleTimeout() > 0) return new NettyInitializers(Arrays.asList(new HotRodChannelInitializer(this, transport, getEncoder(), getExecutor(getQualifiedName())), new TimeoutEnabledChannelInitializer<>(this))); else // Idle timeout logic is disabled with -1 or 0 values return new NettyInitializers(new HotRodChannelInitializer(this, transport, getEncoder(), getExecutor(getQualifiedName()))); } private <T> void loadFilterConverterFactories(Class<T> c, BiConsumer<String, T> biConsumer) { ServiceFinder.load(c).forEach(factory -> { NamedFactory annotation = factory.getClass().getAnnotation(NamedFactory.class); if (annotation != null) { String name = annotation.name(); biConsumer.accept(name, factory); } }); } private List<QueryFacade> loadQueryFacades() { List<QueryFacade> facades = new ArrayList<>(); ServiceLoader.load(QueryFacade.class, getClass().getClassLoader()).forEach(facades::add); return facades; } @Override protected void startTransport() { // Start predefined caches preStartCaches(); super.startTransport(); } @Override protected void startDefaultCache() { Cache<Object, Object> cache = cacheManager.getCache(configuration.defaultCacheName()); validateCacheConfiguration(cache.getCacheConfiguration()); getCacheInstance(configuration.defaultCacheName(), cacheManager, true, true); } private void preStartCaches() { // Start defined caches to avoid issues with lazily started caches. Skip internal caches if authorization is not // enabled InternalCacheRegistry icr = cacheManager.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); boolean authz = cacheManager.getCacheManagerConfiguration().security().authorization().enabled(); for (String cacheName : cacheManager.getCacheNames()) { AdvancedCache cache = getCacheInstance(cacheName, cacheManager, false, (!icr.internalCacheHasFlag(cacheName, InternalCacheRegistry.Flag.PROTECTED) || authz)); Configuration cacheCfg = SecurityActions.getCacheConfiguration(cache); validateCacheConfiguration(cacheCfg); } } private void validateCacheConfiguration(Configuration cacheCfg) { IsolationLevel isolationLevel = cacheCfg.locking().isolationLevel(); if ((isolationLevel == IsolationLevel.REPEATABLE_READ || isolationLevel == IsolationLevel.SERIALIZABLE) && !cacheCfg.locking().writeSkewCheck()) throw log.invalidIsolationLevel(isolationLevel); } private void addSelfToTopologyView(EmbeddedCacheManager cacheManager) { addressCache = cacheManager.getCache(configuration.topologyCacheName()); clusterAddress = cacheManager.getAddress(); address = new ServerAddress(configuration.proxyHost(), configuration.proxyPort()); distributedExecutorService = new DefaultExecutorService(addressCache); viewChangeListener = new CrashedMemberDetectorListener(addressCache, this); cacheManager.addListener(viewChangeListener); topologyChangeListener = new ReAddMyAddressListener(addressCache, clusterAddress, address); addressCache.addListener(topologyChangeListener); // Map cluster address to server endpoint address log.debugf("Map %s cluster address with %s server endpoint in address cache", clusterAddress, address); // Guaranteed delivery required since if data is lost, there won't be // any further cache calls, so negative acknowledgment can cause issues. addressCache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD, Flag.GUARANTEED_DELIVERY) .put(clusterAddress, address); } private void defineTopologyCacheConfig(EmbeddedCacheManager cacheManager) { InternalCacheRegistry internalCacheRegistry = cacheManager.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class); internalCacheRegistry.registerInternalCache(configuration.topologyCacheName(), createTopologyCacheConfig(cacheManager.getCacheManagerConfiguration().transport().distributedSyncTimeout()).build(), EnumSet.of(InternalCacheRegistry.Flag.EXCLUSIVE)); } protected ConfigurationBuilder createTopologyCacheConfig(long distSyncTimeout) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.REPL_SYNC).remoteTimeout(configuration.topologyReplTimeout()) .locking().lockAcquisitionTimeout(configuration.topologyLockTimeout()) .eviction().strategy(EvictionStrategy.NONE) .expiration().lifespan(-1).maxIdle(-1); if (configuration.topologyStateTransfer()) { builder .clustering() .stateTransfer() .awaitInitialTransfer(configuration.topologyAwaitInitialTransfer()) .fetchInMemoryState(true) .timeout(distSyncTimeout + configuration.topologyReplTimeout()); } else { builder.persistence().addClusterLoader().remoteCallTimeout(configuration.topologyReplTimeout()); } return builder; } AdvancedCache getKnownCacheInstance(String cacheName) { return knownCaches.get(cacheName); } AdvancedCache getCacheInstance(String cacheName, EmbeddedCacheManager cacheManager, Boolean skipCacheCheck, Boolean addToKnownCaches) { AdvancedCache cache = null; if (!skipCacheCheck) cache = knownCaches.get(cacheName); if (cache == null) { String validCacheName = cacheName.isEmpty() ? configuration.defaultCacheName() : cacheName; Cache<byte[], byte[]> tmpCache = SecurityActions.getCache(cacheManager, validCacheName); Configuration cacheConfiguration = SecurityActions.getCacheConfiguration(tmpCache.getAdvancedCache()); boolean compatibility = cacheConfiguration.compatibility().enabled(); boolean indexing = cacheConfiguration.indexing().index().isEnabled(); // Use flag when compatibility is enabled, otherwise it's unnecessary if (compatibility || indexing) cache = tmpCache.getAdvancedCache().withFlags(Flag.OPERATION_HOTROD); else cache = tmpCache.getAdvancedCache(); // We don't need synchronization as long as we store the cache last knownCacheConfigurations.put(cacheName, cacheConfiguration); knownCacheRegistries.put(cacheName, SecurityActions.getCacheComponentRegistry(tmpCache.getAdvancedCache())); if (addToKnownCaches) { knownCaches.put(cacheName, cache); } // make sure we register a Migrator for this cache! tryRegisterMigrationManager(cacheName, cache); } return cache; } Configuration getCacheConfiguration(String cacheName) { return knownCacheConfigurations.get(cacheName); } ComponentRegistry getCacheRegistry(String cacheName) { return knownCacheRegistries.get(cacheName); } void tryRegisterMigrationManager(String cacheName, AdvancedCache<byte[], byte[]> cache) { ComponentRegistry cr = SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache()); RollingUpgradeManager migrationManager = cr.getComponent(RollingUpgradeManager.class); if (migrationManager != null) migrationManager.addSourceMigrator(new HotRodSourceMigrator(cache)); } private void setupSasl() { Iterator<SaslServerFactory> saslFactories = SaslUtils.getSaslServerFactories(this.getClass().getClassLoader(), true); while (saslFactories.hasNext()) { SaslServerFactory saslFactory = saslFactories.next(); String[] saslFactoryMechs = saslFactory.getMechanismNames(configuration.authentication().mechProperties()); for (String supportedMech : saslFactoryMechs) { for (String mech : configuration.authentication().allowedMechs()) { if (supportedMech.equals(mech)) { saslMechFactories.putIfAbsent(mech, saslFactory); } } } } } SaslServerFactory getSaslServerFactory(String mech) { return saslMechFactories.get(mech); } private Cache<Address, ServerAddress> getAddressCache() { return addressCache; } public void addCacheEventFilterFactory(String name, CacheEventFilterFactory factory) { clientListenerRegistry.addCacheEventFilterFactory(name, factory); } public void removeCacheEventFilterFactory(String name) { clientListenerRegistry.removeCacheEventFilterFactory(name); } public void addCacheEventConverterFactory(String name, CacheEventConverterFactory factory) { clientListenerRegistry.addCacheEventConverterFactory(name, factory); } public void removeCacheEventConverterFactory(String name) { clientListenerRegistry.removeCacheEventConverterFactory(name); } public void addCacheEventFilterConverterFactory(String name, CacheEventFilterConverterFactory factory) { clientListenerRegistry.addCacheEventFilterConverterFactory(name, factory); } public void removeCacheEventFilterConverterFactory(String name) { clientListenerRegistry.removeCacheEventFilterConverterFactory(name); } public void setMarshaller(Marshaller marshaller) { this.marshaller = marshaller; Optional<Marshaller> optMarshaller = Optional.ofNullable(marshaller); clientListenerRegistry.setEventMarshaller(optMarshaller); iterationManager.setMarshaller(optMarshaller); } public void addKeyValueFilterConverterFactory(String name, KeyValueFilterConverterFactory factory) { iterationManager.addKeyValueFilterConverterFactory(name, factory); } public void removeKeyValueFilterConverterFactory(String name) { iterationManager.removeKeyValueFilterConverterFactory(name); } public IterationManager getIterationManager() { return iterationManager; } @Override public void stop() { if (viewChangeListener != null) { SecurityActions.removeListener(cacheManager, viewChangeListener); } if (topologyChangeListener != null) { SecurityActions.removeListener(addressCache, topologyChangeListener); } if (distributedExecutorService != null) { distributedExecutorService.shutdownNow(); } if (clientListenerRegistry != null) clientListenerRegistry.stop(); if (executor != null) executor.shutdownNow(); super.stop(); } @Listener(sync = false, observation = Listener.Observation.POST) class ReAddMyAddressListener { private final Cache<Address, ServerAddress> addressCache; private final Address clusterAddress; private final ServerAddress address; ReAddMyAddressListener(Cache<Address, ServerAddress> addressCache, Address clusterAddress, ServerAddress address) { this.addressCache = addressCache; this.clusterAddress = clusterAddress; this.address = address; } @TopologyChanged public void topologyChanged(TopologyChangedEvent<Address, ServerAddress> event) { boolean success = false; while (!success && !distributedExecutorService.isShutdown() && addressCache.getStatus().allowInvocations()) { try { List<CompletableFuture<Boolean>> futures = distributedExecutorService.submitEverywhere( new CheckAddressTask(clusterAddress)); // No need for a timeout here, the distributed executor has a default task timeout AtomicBoolean result = new AtomicBoolean(true); futures.forEach(f -> { try { if (!f.get()) { result.set(false); } } catch (InterruptedException | ExecutionException e) { throw new CacheException(e); } }); if (!result.get()) { log.debugf("Re-adding %s to the topology cache", clusterAddress); addressCache.putAsync(clusterAddress, address); } success = true; } catch (Throwable e) { log.debug("Error re-adding address to topology cache, retrying", e); } } } } } class CheckAddressTask implements DistributedCallable<Address, ServerAddress, Boolean>, Serializable { private final Address clusterAddress; private volatile Cache<Address, ServerAddress> cache = null; CheckAddressTask(Address clusterAddress) { this.clusterAddress = clusterAddress; } @Override public void setEnvironment(Cache<Address, ServerAddress> cache, Set<Address> inputKeys) { this.cache = cache; } @Override public Boolean call() throws Exception { return cache.containsKey(clusterAddress); } }
3e04e7cbe0d139547816d87712102e02157fcf56
5,291
java
Java
src/main/java/com/marcomorais/datastructures/Tree.java
Morlis/Data-Structures
c49d1882e9b99e1d717172bedcef7a09b01d1668
[ "Apache-2.0" ]
null
null
null
src/main/java/com/marcomorais/datastructures/Tree.java
Morlis/Data-Structures
c49d1882e9b99e1d717172bedcef7a09b01d1668
[ "Apache-2.0" ]
null
null
null
src/main/java/com/marcomorais/datastructures/Tree.java
Morlis/Data-Structures
c49d1882e9b99e1d717172bedcef7a09b01d1668
[ "Apache-2.0" ]
null
null
null
23.620536
88
0.6409
2,047
package com.marcomorais.datastructures; import java.util.function.Consumer; /** * Binary Search Tree implementation * @author marco morais * * @param <T> */ public class Tree<T extends Comparable<T>> { private TreeNode<T> root = null; private TreeNode<T> parent; private int size = 0; /** * Add value to tree * * @param value Value to add */ public void add(T value) { if (root == null) { root = new TreeNode<T>(value); } else { addTo(root, value); } size++; } /** * Add value to node * * @param node Node to add the value * @param value Value to add */ private void addTo(TreeNode<T> node, T value) { if (node.value.compareTo(value) > 0) { if (node.left == null) { node.left = new TreeNode<T>(value); } else { addTo(node.left, value); } } else { if (node.right == null) { node.right = new TreeNode<T>(value); } else { addTo(node.right, value); } } } /** * Return true if value is found in tree otherwise return false * * @param value Value to search for * @return True if the value is found */ public boolean contains(T value) { return findWithParent(value) != null; } /** * Remove value from tree * @param value Value to remove * @return return true if thevalue is found */ public boolean remove(T value) { TreeNode<T> current = findWithParent(value); if (current == null) { return false; } size--; // Case 1: If the current has no right child, then the current's left replaces current if (current.right == null) { if (parent == null) { root = current.left; } else { int result = parent.value.compareTo(current.value); if (result > 0) { // If parent value is greater than the current value // make the current left child a left child of parent parent.left = current.left; } else if (result < 0) { // if parent value is less than the current value // make the current left child a right child of parent parent.right = current.left; } } } // Case 2: If current's right child has no left child, then current's right child // replaces current else if (current.right.left == null) { current.right.left = current.left; if (parent == null) { root = current.right; } else { int result = parent.value.compareTo(current.value); if (result > 0) { // If parent value is greater than the current value // make the current right child a left child of parent parent.left = current.right; } else if (result < 0) { // if parent value is less than the current value // make the current right child a right child of parent parent.right = current.right; } } } // Case 3: If current's right child has a left child, replace current with current's // right child's left most child else { // find the right's left-most child TreeNode<T> leftmost = current.right.left; TreeNode<T> leftmostParent = current.right; while (leftmost.left != null) { leftmostParent = leftmost; leftmost = leftmost.left; } // the parent's left subtree becomes the leftmost's right subtree leftmostParent.left = leftmost.right; // assign's leftmost left and right to current's left and right children leftmost.left = current.left; leftmost.right = current.right; if (parent == null) { root = leftmost; } else { int result = parent.value.compareTo(current.value); if (result > 0) { // If parent value is greater than the current value // make leftmost the parent's left child parent.left = leftmost; } else if (result < 0) { // if parent value is less than the current value // make leftmost the parent's right child parent.right = leftmost; } } } return true; } private TreeNode<T> findWithParent(T value) { TreeNode<T> node = root; parent = null; while (node != null) { int result = node.value.compareTo(value); if (result > 0) { parent = node; node = node.left; } else if (result < 0) { parent = node; node = node.right; } else { // Found it break; } } return node; } public void preOrder(Consumer<T> consumer) { preOrderTraversal(root, consumer); } private void preOrderTraversal(TreeNode<T> node, Consumer<T> consumer) { if (node == null) { return; } consumer.accept(node.value); preOrderTraversal(node.left, consumer); preOrderTraversal(node.right, consumer); } public void inOrder(Consumer<T> consumer) { inOrderTraversal(root, consumer); } private void inOrderTraversal(TreeNode<T> node, Consumer<T> consumer) { if (node == null) { return; } inOrderTraversal(node.left, consumer); consumer.accept(node.value); inOrderTraversal(node.right, consumer); } public void postOrder(Consumer<T> consumer) { postOrderTraversal(root, consumer); } private void postOrderTraversal(TreeNode<T> node, Consumer<T> consumer) { if (node == null) { return; } postOrderTraversal(node.left, consumer); postOrderTraversal(node.right, consumer); consumer.accept(node.value); } public void clear() { size = 0; root = null; } public int size() { return size; } public boolean isEmpty() { return size == 0; } }
3e04e7e5a2fbfeca0a33eb48c0b93d13e2c4feb2
12,842
java
Java
org.metaborg.spt.core/src/main/java/org/metaborg/spt/core/extract/expectations/AnalyzeExpectationProvider.java
pmisteliac/spt
c4a92f8da34533a1b07485388356f9a8466426d0
[ "Apache-2.0" ]
null
null
null
org.metaborg.spt.core/src/main/java/org/metaborg/spt/core/extract/expectations/AnalyzeExpectationProvider.java
pmisteliac/spt
c4a92f8da34533a1b07485388356f9a8466426d0
[ "Apache-2.0" ]
20
2016-05-23T15:50:04.000Z
2022-01-10T12:36:35.000Z
org.metaborg.spt.core/src/main/java/org/metaborg/spt/core/extract/expectations/AnalyzeExpectationProvider.java
pmisteliac/spt
c4a92f8da34533a1b07485388356f9a8466426d0
[ "Apache-2.0" ]
7
2015-06-11T17:32:17.000Z
2020-03-23T20:49:50.000Z
38.334328
122
0.622567
2,048
package org.metaborg.spt.core.extract.expectations; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.metaborg.core.messages.MessageSeverity; import org.metaborg.core.source.ISourceLocation; import org.metaborg.core.source.ISourceRegion; import org.metaborg.mbt.core.model.IFragment; import org.metaborg.mbt.core.model.expectations.AnalysisMessageExpectation; import org.metaborg.mbt.core.model.expectations.AnalysisMessageExpectation.Operation; import org.metaborg.mbt.core.model.expectations.ITestExpectation; import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService; import org.metaborg.spt.core.SPTUtil; import org.metaborg.spt.core.extract.ISpoofaxTestExpectationProvider; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.LoggerUtils; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.terms.util.TermUtils; import javax.annotation.Nullable; import java.util.List; public class AnalyzeExpectationProvider implements ISpoofaxTestExpectationProvider { private static final ILogger logger = LoggerUtils.logger(AnalyzeExpectationProvider.class); // AnalyzeMessages(Some(<operation>), <number>, <severity>, Some(AtPart([<i>, <j>]))) private static final String CONS = "AnalyzeMessages"; // AnalyzeMessagePattern(severity, content, optional at part) private static final String LIKE = "AnalyzeMessagePattern"; private static final String AT_PART = "AtPart"; private static final String ERR = "Error"; private static final String WARN = "Warning"; private static final String NOTE = "Note"; private static final String EQ = "Equal"; private static final String LT = "Less"; private static final String LE = "LessOrEqual"; private static final String MT = "More"; private static final String ME = "MoreOrEqual"; private final ISpoofaxTracingService traceService; @Inject public AnalyzeExpectationProvider(ISpoofaxTracingService traceService) { this.traceService = traceService; } @Override public boolean canEvaluate(IFragment inputFragment, IStrategoTerm expectationTerm) { @Nullable final String cons = SPTUtil.consName(expectationTerm); switch(cons) { case CONS: // this is a check for the number of messages of a given severity return NumCheck.check(expectationTerm); case LIKE: // this is a check for the content of messages return LikeCheck.check(expectationTerm); default: return false; } } @Override public ITestExpectation createExpectation(IFragment inputFragment, IStrategoTerm expectationTerm) { logger.debug("Creating an expectation object for {}", expectationTerm); @Nullable final String cons = SPTUtil.consName(expectationTerm); switch(cons) { case CONS: return getNumCheckExpectation(inputFragment, expectationTerm); case LIKE: return getLikeExpectation(inputFragment, expectationTerm); default: throw new IllegalArgumentException( "This provider never claimed to be able to handle a " + expectationTerm); } } private ISourceRegion getRegion(IFragment inputFragment, IStrategoTerm expectationTerm) { final ISourceLocation loc = traceService.location(expectationTerm); return loc == null ? inputFragment.getRegion() : loc.region(); } private AnalysisMessageExpectation getLikeExpectation(IFragment inputFragment, IStrategoTerm expectationTerm) { // get the severity final IStrategoTerm sevTerm = LikeCheck.getSeverityTerm(expectationTerm); final MessageSeverity severity = getSeverity(sevTerm); // get the contents that should be part of the message final String content = TermUtils.toJavaString(LikeCheck.getContentTerm(expectationTerm)); // get the selections from the 'at' part final IStrategoTerm optionalAtPart = LikeCheck.getOptionalAtPartTerm(expectationTerm); final List<Integer> selections = getSelections(optionalAtPart); // get the region final ISourceRegion region = getRegion(inputFragment, expectationTerm); // we expect at least 1 message with the given content return new AnalysisMessageExpectation(region, 1, severity, selections, Operation.MORE_OR_EQUAL, content); } private AnalysisMessageExpectation getNumCheckExpectation(IFragment inputFragment, IStrategoTerm expectationTerm) { // get the severity final IStrategoTerm sevTerm = NumCheck.getSeverityTerm(expectationTerm); final MessageSeverity severity = getSeverity(sevTerm); // get the selections from the 'at' part final IStrategoTerm optionalAtPart = NumCheck.getOptionalAtPartTerm(expectationTerm); final List<Integer> selections = getSelections(optionalAtPart); // get the operation (defaults to 'equal') final @Nullable IStrategoTerm optTerm = SPTUtil.getOptionValue(NumCheck.getOptionalOperatorTerm(expectationTerm)); final Operation opt; if(optTerm == null) { // it was a None() opt = Operation.EQUAL; } else { // it was a Some(optTerm) @Nullable final String optStr = SPTUtil.consName(optTerm); switch(optStr) { case EQ: opt = Operation.EQUAL; break; case LT: opt = Operation.LESS; break; case LE: opt = Operation.LESS_OR_EQUAL; break; case MT: opt = Operation.MORE; break; case ME: opt = Operation.MORE_OR_EQUAL; break; default: throw new IllegalArgumentException( "This test expectation provider can't evaluate messages with operator " + optStr); } } // get the region final ISourceRegion region = getRegion(inputFragment, expectationTerm); return new AnalysisMessageExpectation(region, TermUtils.toJavaInt(NumCheck.getNumTerm(expectationTerm)), severity, selections, opt, null); } // AnalyzeMessages(Some(<operation>), <number>, <severity>, optional AtPart) expectation private static class NumCheck { public static IStrategoTerm getOptionalOperatorTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(0); } public static IStrategoTerm getNumTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(1); } public static IStrategoTerm getSeverityTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(2); } public static IStrategoTerm getOptionalAtPartTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(3); } // check if the given term is an optional operator that we recognize public static boolean checkOptionalOperator(IStrategoTerm optOp) { if(!SPTUtil.checkOption(optOp)) { return false; } final IStrategoTerm op = SPTUtil.getOptionValue(optOp); if(op == null) { // it was a None() return true; } switch(SPTUtil.consName(op)) { case EQ: case LT: case LE: case MT: case ME: return true; default: return false; } } /** * Check if the given term is an AnalyzeMessages term that we can handle. */ public static boolean check(IStrategoTerm numCheck) { // AnalyzeMessages(optional opt, num, severity, optional atpart) if(!CONS.equals(SPTUtil.consName(numCheck)) || numCheck.getSubtermCount() != 4) { return false; } if(!checkOptionalOperator(getOptionalOperatorTerm(numCheck))) { return false; } if(!TermUtils.isInt(getNumTerm(numCheck))) { return false; } if(!checkSeverity(getSeverityTerm(numCheck))) { return false; } if(!checkOptionalAtPart(getOptionalAtPartTerm(numCheck))) { return false; } return true; } } // AnalyzeMessagePattern(severity, content, optional at part) private static class LikeCheck { public static IStrategoTerm getSeverityTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(0); } public static IStrategoTerm getContentTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(1); } public static IStrategoTerm getOptionalAtPartTerm(IStrategoTerm expectationTerm) { return expectationTerm.getSubterm(2); } /** * Check if the given term is an AnalyzeMessagePattern term that we can handle. */ public static boolean check(IStrategoTerm expectationTerm) { // AnalyzeMessagePattern(severity, content, optional at part) if(!LIKE.equals(SPTUtil.consName(expectationTerm)) || expectationTerm.getSubtermCount() != 3) { return false; } if(!checkSeverity(getSeverityTerm(expectationTerm))) { return false; } if(!TermUtils.isString(getContentTerm(expectationTerm))) { return false; } if(!checkOptionalAtPart(getOptionalAtPartTerm(expectationTerm))) { return false; } return true; } } private static IStrategoTerm getAtPartSelectionsTerm(IStrategoTerm atPart) { return atPart.getSubterm(0); } // check if the given term is a valid severity private static boolean checkSeverity(IStrategoTerm sev) { switch(SPTUtil.consName(sev)) { case ERR: case WARN: case NOTE: return true; default: return false; } } /** * Convert the term into a MessageSeverity. */ private MessageSeverity getSeverity(IStrategoTerm sevTerm) { switch(SPTUtil.consName(sevTerm)) { case ERR: return MessageSeverity.ERROR; case WARN: return MessageSeverity.WARNING; case NOTE: return MessageSeverity.NOTE; default: throw new IllegalArgumentException( "This test expectation provider can't evaluate messages of severity " + sevTerm); } } // AtPart([<i>, <j>, ...]) private static boolean checkOptionalAtPart(IStrategoTerm optAtPart) { if(!SPTUtil.checkOption(optAtPart)) { return false; } final IStrategoTerm atPart = SPTUtil.getOptionValue(optAtPart); if(atPart == null) { // None() return true; } else { // Some(atPart) if(!AT_PART.equals(SPTUtil.consName(atPart)) || atPart.getSubtermCount() != 1) { return false; } // check list of selections final IStrategoTerm selections = getAtPartSelectionsTerm(atPart); if(!TermUtils.isList(selections)) { return false; } final IStrategoList selectionsList = (IStrategoList) selections; for(IStrategoTerm selectionRef : selectionsList) { // should be an int if(!TermUtils.isInt(selectionRef)) { return false; } } return true; } } /** * Get the numbers of the selections from an optional AtPart term. */ private List<Integer> getSelections(IStrategoTerm optionalAtPart) { final List<Integer> selections = Lists.newArrayList(); final IStrategoTerm atPart = SPTUtil.getOptionValue(optionalAtPart); if(atPart != null) { // Some(AtPart([SelectionRef(i), ...])) final IStrategoList list = (IStrategoList) getAtPartSelectionsTerm(atPart); for(IStrategoTerm sel : list) { selections.add(TermUtils.toJavaInt(sel)); } } return selections; } }
3e04e8c974d94af6a258d01bdad466fc3d85b1d1
9,145
java
Java
document-processor/src/test/java/io/automatiko/examples/document/processor/VerificationTests.java
automatiko-io/automatiko-examples
0d4df6f04637acbd6a58eeaf08d71fac1727ffdc
[ "Apache-2.0" ]
1
2021-01-26T16:49:03.000Z
2021-01-26T16:49:03.000Z
document-processor/src/test/java/io/automatiko/examples/document/processor/VerificationTests.java
automatiko-io/automatiko-examples
0d4df6f04637acbd6a58eeaf08d71fac1727ffdc
[ "Apache-2.0" ]
null
null
null
document-processor/src/test/java/io/automatiko/examples/document/processor/VerificationTests.java
automatiko-io/automatiko-examples
0d4df6f04637acbd6a58eeaf08d71fac1727ffdc
[ "Apache-2.0" ]
null
null
null
31.318493
111
0.540842
2,049
package io.automatiko.examples.document.processor; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.List; import java.util.Map; import javax.enterprise.inject.Produces; import javax.inject.Singleton; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import io.automatiko.engine.api.event.EventPublisher; import io.automatiko.engine.services.event.impl.CountDownProcessInstanceEventPublisher; import io.automatiko.engine.services.utils.IoUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.http.ContentType; @SuppressWarnings({ "unchecked", "rawtypes" }) @QuarkusTest public class VerificationTests { // @formatter:off private CountDownProcessInstanceEventPublisher execCounter = new CountDownProcessInstanceEventPublisher(); @Produces @Singleton public EventPublisher publisher() { return execCounter; } @AfterAll public static void preapre() throws IOException { File processes = new File("target/processes"); File jobs = new File("target/jobs"); Files.walk(processes.toPath()) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); Files.walk(jobs.toPath()) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } @Test public void testSingleGreetingFileProcessing() throws Exception { execCounter.reset(1); Files.write(new File("target" + File.separator + "documents" + File.separator + "hello.txt").toPath(), "hello every body".getBytes()); execCounter.waitTillCompletion(3); } @Test public void testReportFileProcessingAbort() throws Exception { execCounter.reset(1); StringBuilder data = new StringBuilder("Report"); for (int i = 0; i < 50; i++) { data.append("Content of the report by line \n"); } Files.write(new File("target" + File.separator + "documents" + File.separator + "report.txt").toPath(), data.toString().getBytes()); execCounter.waitTillCompletion(3); List instances = given() .accept(ContentType.JSON) .when() .get("/text") .then().statusCode(200) .body("$.size()", is(1)).extract().as(List.class); Map<String, Object> instanceData = (Map<String, Object>) instances.get(0); String id = (String) instanceData.get("id"); // abort instance given() .accept(ContentType.JSON) .when() .delete("/text/" + id) .then() .statusCode(200); given() .accept(ContentType.JSON) .when() .get("/text") .then().statusCode(200) .body("$.size()", is(0)); } @Disabled @Test public void testReportFileProcessingApprove() throws Exception { execCounter.reset(1); StringBuilder data = new StringBuilder("Report"); for (int i = 0; i < 10; i++) { data.append("Content of the report by line \n"); } File file = new File("target" + File.separator + "documents" + File.separator + "report.tmp"); Files.write(file.toPath(), data.toString().getBytes()); file.renameTo(new File("target" + File.separator + "documents" + File.separator + "report.txt")); execCounter.waitTillCompletion(3); List instances = given() .accept(ContentType.JSON) .when() .get("/text") .then().statusCode(200) .body("$.size()", is(1)).extract().as(List.class); Map<String, Object> instanceData = (Map<String, Object>) instances.get(0); String id = (String) instanceData.get("id"); List<Map<String, String>> taskInfo = given() .accept(ContentType.JSON) .when() .get("/text/" + id + "/tasks") .then() .statusCode(200) .extract().as(List.class); assertEquals(1, taskInfo.size()); String taskId = taskInfo.get(0).get("id"); String taskName = taskInfo.get(0).get("name"); assertEquals("approveReport", taskName); String payload = "{}"; given(). contentType(ContentType.JSON) .accept(ContentType.JSON) .body(payload) .when() .post("/text/" + id + "/" + taskName + "/" + taskId) .then() .statusCode(200).body("id", is(id)); given() .accept(ContentType.JSON) .when() .get("/text") .then().statusCode(200) .body("$.size()", is(0)); } @Test public void testReportsFileProcessingApprove() throws Exception { execCounter.reset(1); StringBuilder data = new StringBuilder("Report"); for (int i = 0; i < 50; i++) { data.append("Content of the report by line \n"); } File file = new File("target" + File.separator + "documents" + File.separator + "reports2.tmp"); Files.write(file.toPath(), IoUtils.readBytesFromInputStream(this.getClass().getResourceAsStream("/a.zip"))); file.renameTo(new File("target" + File.separator + "documents" + File.separator + "reports2.zip")); execCounter.waitTillCompletion(3); List instances = given() .accept(ContentType.JSON) .when() .get("/zip") .then().statusCode(200) .body("$.size()", is(1)).extract().as(List.class); Map<String, Object> instanceData = (Map<String, Object>) instances.get(0); String id = (String) instanceData.get("id"); List<Map<String, String>> taskInfo = given() .accept(ContentType.JSON) .when() .get("/zip/" + id + "/tasks") .then() .statusCode(200) .extract().as(List.class); assertEquals(1, taskInfo.size()); String taskName = taskInfo.get(0).get("name"); String reference = taskInfo.get(0).get("reference"); assertEquals("approveReport", taskName); String payload = "{}"; given(). contentType(ContentType.JSON) .accept(ContentType.JSON) .body(payload) .when() .post(reference) .then() .statusCode(200); given() .accept(ContentType.JSON) .when() .get("/zip") .then().statusCode(200) .body("$.size()", is(0)); } @Test public void testReportsFileProcessingAbort() throws Exception { execCounter.reset(1); StringBuilder data = new StringBuilder("Report"); for (int i = 0; i < 50; i++) { data.append("Content of the report by line \n"); } File file = new File("target" + File.separator + "documents" + File.separator + "reports.tmp"); Files.write(file.toPath(), IoUtils.readBytesFromInputStream(this.getClass().getResourceAsStream("/a.zip"))); file.renameTo(new File("target" + File.separator + "documents" + File.separator + "reports.zip")); execCounter.waitTillCompletion(3); List instances = given() .accept(ContentType.JSON) .when() .get("/zip") .then().statusCode(200) .body("$.size()", is(1)).extract().as(List.class); Map<String, Object> instanceData = (Map<String, Object>) instances.get(0); String id = (String) instanceData.get("id"); List<Map<String, String>> taskInfo = given() .accept(ContentType.JSON) .when() .get("/zip/" + id + "/tasks") .then() .statusCode(200) .extract().as(List.class); assertEquals(1, taskInfo.size()); String taskName = taskInfo.get(0).get("name"); assertEquals("approveReport", taskName); // abort instance given() .accept(ContentType.JSON) .when() .delete("/zip/" + id) .then() .statusCode(200); given() .accept(ContentType.JSON) .when() .get("/zip") .then().statusCode(200) .body("$.size()", is(0)); } // @formatter:on }
3e04e8d6e0e31bffe00da6b6fbf39947092237a4
569
java
Java
src/com/IanThomas/resume/fragments/HomeFragment.java
ToxicBakery/Resume-App
ab884e3d57eb6aeed1b16e9cd43db87a1b58bbff
[ "Apache-2.0" ]
1
2015-03-21T01:59:04.000Z
2015-03-21T01:59:04.000Z
src/com/IanThomas/resume/fragments/HomeFragment.java
ToxicBakery/Resume-App
ab884e3d57eb6aeed1b16e9cd43db87a1b58bbff
[ "Apache-2.0" ]
null
null
null
src/com/IanThomas/resume/fragments/HomeFragment.java
ToxicBakery/Resume-App
ab884e3d57eb6aeed1b16e9cd43db87a1b58bbff
[ "Apache-2.0" ]
null
null
null
22.76
71
0.801406
2,050
package com.IanThomas.resume.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.IanThomas.resume.R; public class HomeFragment extends Fragment implements IResumeFragment { @Override public int getTitleResId() { return R.string.fragment_home_title; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home, container, false); } }
3e04e9180642baac6ca97c95bd87054c44b3ff70
6,998
java
Java
src/main/java/com/mazentop/entity/ProProductSecInfo.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
src/main/java/com/mazentop/entity/ProProductSecInfo.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
src/main/java/com/mazentop/entity/ProProductSecInfo.java
chanwaikit/fulin-test
e31ef03596b724ba48d72ca8021492e6f251ec20
[ "0BSD" ]
null
null
null
28.688525
158
0.639286
2,051
package com.mazentop.entity; import com.alibaba.fastjson.annotation.JSONField; import java.sql.ResultSetMetaData; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; import java.util.Map; import java.sql.ResultSet; import java.sql.SQLException; import com.mztframework.commons.Utils; import com.mztframework.dao.jdbc.BaseBean; import org.springframework.jdbc.core.RowMapper; /** * Author: zhaoqt * Mail: [email protected] * Date: 10:37 2020/04/20 * Company: 美赞拓 * Version: 1.0 * Description: ProProductSecInfo实体 */ @SuppressWarnings("all") public class ProProductSecInfo extends BaseBean<ProProductSecInfo> { /** * 表名 */ public static final String TABLE_NAME = "pro_product_sec_info"; /** * */ public static final String F_ID = "id"; /** * 商品主体编号 */ public static final String F_FK_PRODUCT_MASTER_ID = "fk_product_master_id"; /** * 库存编号 */ public static final String F_FK_STOCK_ID = "fk_stock_id"; /** * 规格父编号 */ public static final String F_FK_PARENT_SPEC_ID = "fk_parent_spec_id"; /** * 规格编号 */ public static final String F_FK_SPEC_ID = "fk_spec_id"; /** * 添加时间 */ public static final String F_ADD_TIME = "add_time"; /** * 添加人编号 */ public static final String F_ADD_USER_ID = "add_user_id"; @Override protected void initBeanValues(){ put(F_ID, null); put(F_FK_PRODUCT_MASTER_ID, null); put(F_FK_STOCK_ID, null); put(F_FK_PARENT_SPEC_ID, null); put(F_FK_SPEC_ID, null); put(F_ADD_TIME, null); put(F_ADD_USER_ID, null); } public ProProductSecInfo() { super(); } public ProProductSecInfo(Map<String, Object> map) { super(map); } public ProProductSecInfo(String id) { super(); setId(id); } /** * @return id to id <BR/> */ public String getId() { return getTypedValue(F_ID, String.class); } /** * @param id to id set */ public ProProductSecInfo setId(String id) { set(F_ID, id); return this; } /** * @return fk_product_master_id to fkProductMasterId 商品主体编号<BR/> */ public String getFkProductMasterId() { return getTypedValue(F_FK_PRODUCT_MASTER_ID, String.class); } /** * @param fkProductMasterId to fk_product_master_id 商品主体编号 set */ public ProProductSecInfo setFkProductMasterId(String fkProductMasterId) { set(F_FK_PRODUCT_MASTER_ID, fkProductMasterId); return this; } /** * @return fk_stock_id to fkStockId 库存编号<BR/> */ public String getFkStockId() { return getTypedValue(F_FK_STOCK_ID, String.class); } /** * @param fkStockId to fk_stock_id 库存编号 set */ public ProProductSecInfo setFkStockId(String fkStockId) { set(F_FK_STOCK_ID, fkStockId); return this; } /** * @return fk_parent_spec_id to fkParentSpecId 规格父编号<BR/> */ public String getFkParentSpecId() { return getTypedValue(F_FK_PARENT_SPEC_ID, String.class); } /** * @param fkParentSpecId to fk_parent_spec_id 规格父编号 set */ public ProProductSecInfo setFkParentSpecId(String fkParentSpecId) { set(F_FK_PARENT_SPEC_ID, fkParentSpecId); return this; } /** * @return fk_spec_id to fkSpecId 规格编号<BR/> */ public String getFkSpecId() { return getTypedValue(F_FK_SPEC_ID, String.class); } /** * @param fkSpecId to fk_spec_id 规格编号 set */ public ProProductSecInfo setFkSpecId(String fkSpecId) { set(F_FK_SPEC_ID, fkSpecId); return this; } /** * @return add_time to addTime 添加时间<BR/> */ public Long getAddTime() { return getTypedValue(F_ADD_TIME, Long.class); } /** * @param addTime to add_time 添加时间 set */ public ProProductSecInfo setAddTime(Long addTime) { set(F_ADD_TIME, addTime); return this; } /** * @return add_user_id to addUserId 添加人编号<BR/> */ public String getAddUserId() { return getTypedValue(F_ADD_USER_ID, String.class); } /** * @param addUserId to add_user_id 添加人编号 set */ public ProProductSecInfo setAddUserId(String addUserId) { set(F_ADD_USER_ID, addUserId); return this; } @JSONField(serialize = false) @Override public Object getPrimaryKey() { return getId(); } @Override public ProProductSecInfo setPrimaryKey(Object key) { setId(Utils.toCast(key, String.class)); return this; } @JSONField(serialize = false) @Override public String getTableName() { return TABLE_NAME; } public static ProProductSecInfo me(){ return new ProProductSecInfo(); } private static class Mapper implements RowMapper<ProProductSecInfo> { private Supplier<ProProductSecInfo> supplier; public Mapper(Supplier supplier) { this.supplier = supplier; } @Override public ProProductSecInfo mapRow(ResultSet rs, int rownum) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int cc = rsmd.getColumnCount(); Set<String> columnsName = new HashSet<>(cc); for(int i = 1; i<= cc; i++) { columnsName.add(rsmd.getColumnName(i)); } ProProductSecInfo bean = supplier.get(); bean.setId(Utils.toCast(columnsName.contains(F_ID) ? rs.getObject(F_ID) : null, String.class)); bean.setFkProductMasterId(Utils.toCast(columnsName.contains(F_FK_PRODUCT_MASTER_ID) ? rs.getObject(F_FK_PRODUCT_MASTER_ID) : null, String.class)); bean.setFkStockId(Utils.toCast(columnsName.contains(F_FK_STOCK_ID) ? rs.getObject(F_FK_STOCK_ID) : null, String.class)); bean.setFkParentSpecId(Utils.toCast(columnsName.contains(F_FK_PARENT_SPEC_ID) ? rs.getObject(F_FK_PARENT_SPEC_ID) : null, String.class)); bean.setFkSpecId(Utils.toCast(columnsName.contains(F_FK_SPEC_ID) ? rs.getObject(F_FK_SPEC_ID) : null, String.class)); bean.setAddTime(Utils.toCast(columnsName.contains(F_ADD_TIME) ? rs.getObject(F_ADD_TIME) : null, Long.class)); bean.setAddUserId(Utils.toCast(columnsName.contains(F_ADD_USER_ID) ? rs.getObject(F_ADD_USER_ID) : null, String.class)); bean.clearModifyKeys(); return bean; } } @Override public RowMapper<ProProductSecInfo> newMapper(){ return newMapper(ProProductSecInfo::new); } public RowMapper<ProProductSecInfo> newMapper(Supplier<ProProductSecInfo> supplier){ return new Mapper(supplier); } public static abstract class Sub extends ProProductSecInfo { @Override public abstract RowMapper<ProProductSecInfo> newMapper(); } }
3e04ea759006e2073533b49199842980e5ebd54f
1,986
java
Java
examples/ru.iiec.cxxdroid/sources/e/d/a/a/k0.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
examples/ru.iiec.cxxdroid/sources/e/d/a/a/k0.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
examples/ru.iiec.cxxdroid/sources/e/d/a/a/k0.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
29.205882
98
0.522155
2,052
package e.d.a.a; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; public class k0 extends k { /* renamed from: g reason: collision with root package name */ protected final m0 f8232g; public k0(File file, m0 m0Var, String str, String str2) { super(file, str, str2); this.f8232g = m0Var; } private void a() { } private char[] a(long j2) { o0.a(!this.f8227b.equals("Auto"), "AUTO encoding not yet resolved"); o0.a(!this.f8228c.equals("Auto"), "AUTO line break terminator not yet resolved"); if (this.f8227b.equals("UTF-16BE") || this.f8227b.equals("UTF-16LE")) { j2 >>>= 1; } if (j2 <= 2147483647L) { int p = m0.p((int) j2); if (p != -1) { return new char[p]; } throw new OutOfMemoryError(); } throw new OutOfMemoryError(); } public void a(String str) { byte[] bytes = str.getBytes(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); try { this.f8227b = "UTF-8"; byteArrayInputStream.mark(0); this.f8228c = a.a(byteArrayInputStream, this.f8227b); byteArrayInputStream.reset(); char[] a = a((long) bytes.length); h0 a2 = this.f8231f.a(byteArrayInputStream, a, this.f8227b, this.f8228c, this.f8229d); if (!this.f8229d.b()) { this.f8232g.a(a, this.f8227b, this.f8228c, a2.a(), a2.b()); b(1); } else { a(1); } } finally { byteArrayInputStream.close(); } } public void run() { this.f8229d.a(); try { a(); } catch (OutOfMemoryError unused) { a(1, 1, "Not enough memory"); } catch (IOException e2) { a(1, 0, e2.getLocalizedMessage()); } } }
3e04eaf2e3d200dbefd6cfe0f66123b6f48712c4
2,573
java
Java
plugin/src/main/java/it/multicoredev/aio/storage/config/modules/SpawnModule.java
MultiCoreNetwork/AIO
0c59a9137c7399897512aaf378112a73d8aa50f9
[ "BSD-3-Clause" ]
1
2022-03-19T16:56:01.000Z
2022-03-19T16:56:01.000Z
plugin/src/main/java/it/multicoredev/aio/storage/config/modules/SpawnModule.java
MultiCoreNetwork/AIO
0c59a9137c7399897512aaf378112a73d8aa50f9
[ "BSD-3-Clause" ]
null
null
null
plugin/src/main/java/it/multicoredev/aio/storage/config/modules/SpawnModule.java
MultiCoreNetwork/AIO
0c59a9137c7399897512aaf378112a73d8aa50f9
[ "BSD-3-Clause" ]
null
null
null
48.54717
145
0.74932
2,053
package it.multicoredev.aio.storage.config.modules; import com.google.gson.annotations.SerializedName; import it.multicoredev.aio.api.models.Module; import org.bukkit.Location; /** * Copyright &copy; 2021 - 2022 by Lorenzo Magni &amp; Daniele Patella * This file is part of AIO. * AIO is under "The 3-Clause BSD License", you can find a copy <a href="https://opensource.org/licenses/BSD-3-Clause">here</a>. * <p> * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * <p> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ public class SpawnModule extends Module { @SerializedName("respawn_override") public Boolean respawnOverride; @SerializedName("spawn_on_join") public Boolean spawnOnJoin; @SerializedName("spawn_location") public Location spawnLocation; @SerializedName("teleport_delay") public Long teleportDelay; public SpawnModule() { super("spawn"); } @Override public void init() { if (respawnOverride == null) respawnOverride = false; if (spawnOnJoin == null) spawnOnJoin = false; if (teleportDelay == null) teleportDelay = -1L; } @Override public boolean isValid() { return true; } }
3e04eb0d320947c09686aa1f0036a649fcf703dd
815
java
Java
solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/ActivateTestModeImpl.java
georghinkel/ttc2017smartGrids
2997f1c202f5af628e50f5645c900f4d35f44bb7
[ "MIT" ]
5
2017-04-25T13:06:44.000Z
2021-03-24T02:58:50.000Z
solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/ActivateTestModeImpl.java
georghinkel/ttc2017smartGrids
2997f1c202f5af628e50f5645c900f4d35f44bb7
[ "MIT" ]
7
2017-04-25T13:13:30.000Z
2017-09-02T11:46:25.000Z
solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/ActivateTestModeImpl.java
georghinkel/ttc2017smartGrids
2997f1c202f5af628e50f5645c900f4d35f44bb7
[ "MIT" ]
3
2017-04-25T13:08:02.000Z
2021-04-12T07:21:39.000Z
20.375
87
0.678528
2,054
/** */ package COSEM.COSEMObjects.impl; import COSEM.COSEMObjects.ActivateTestMode; import COSEM.COSEMObjects.COSEMObjectsPackage; import COSEM.InterfaceClasses.impl.ScripttableImpl; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Activate Test Mode</b></em>'. * <!-- end-user-doc --> * * @generated */ public class ActivateTestModeImpl extends ScripttableImpl implements ActivateTestMode { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ActivateTestModeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMObjectsPackage.eINSTANCE.getActivateTestMode(); } } //ActivateTestModeImpl
3e04eb89ea0809cc1058cc65f32d4d3ccbb22113
15,808
java
Java
app/src/main/java/com/github/sumimakito/awesomeqrsample/MainActivity.java
stefb965/AwesomeQRCode
1e608e32bed9d151bdbc9d0891ee9517bdc8cdf6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/sumimakito/awesomeqrsample/MainActivity.java
stefb965/AwesomeQRCode
1e608e32bed9d151bdbc9d0891ee9517bdc8cdf6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/sumimakito/awesomeqrsample/MainActivity.java
stefb965/AwesomeQRCode
1e608e32bed9d151bdbc9d0891ee9517bdc8cdf6
[ "Apache-2.0" ]
null
null
null
45.165714
139
0.604124
2,055
package com.github.sumimakito.awesomeqrsample; import android.Manifest; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.github.sumimakito.awesomeqr.AwesomeQRCode; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; public class MainActivity extends AppCompatActivity { private final int BKG_IMAGE = 822; private final int LOGO_IMAGE = 379; private ImageView qrCodeImageView; private EditText etColorLight, etColorDark, etContents, etMargin, etSize; private Button btGenerate, btSelectBG, btRemoveBackgroundImage; private CheckBox ckbWhiteMargin; private Bitmap backgroundImage = null; private AlertDialog progressDialog; private boolean generating = false; private CheckBox ckbAutoColor; private TextView tvAuthorHint; private ScrollView scrollView; private EditText etDotScale; private TextView tvJSHint; private CheckBox ckbBinarize; private CheckBox ckbRoundedDataDots; private EditText etBinarizeThreshold; private Bitmap qrBitmap; private Button btOpen; private EditText etLogoMargin; private EditText etLogoScale; private EditText etLogoCornerRadius; private Button btRemoveLogoImage; private Button btSelectLogo; private Bitmap logoImage; private ViewGroup configViewContainer, resultViewContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); configViewContainer = (ViewGroup) findViewById(R.id.configViewContainer); resultViewContainer = (ViewGroup) findViewById(R.id.resultViewContainer); scrollView = (ScrollView) findViewById(R.id.scrollView); scrollView = (ScrollView) findViewById(R.id.scrollView); tvAuthorHint = (TextView) findViewById(R.id.authorHint); tvJSHint = (TextView) findViewById(R.id.jsHint); qrCodeImageView = (ImageView) findViewById(R.id.qrcode); etColorLight = (EditText) findViewById(R.id.colorLight); etColorDark = (EditText) findViewById(R.id.colorDark); etContents = (EditText) findViewById(R.id.contents); etSize = (EditText) findViewById(R.id.size); etMargin = (EditText) findViewById(R.id.margin); etDotScale = (EditText) findViewById(R.id.dotScale); btSelectBG = (Button) findViewById(R.id.backgroundImage); btSelectLogo = (Button) findViewById(R.id.logoImage); btRemoveBackgroundImage = (Button) findViewById(R.id.removeBackgroundImage); btRemoveLogoImage = (Button) findViewById(R.id.removeLogoImage); btGenerate = (Button) findViewById(R.id.generate); btOpen = (Button) findViewById(R.id.open); ckbWhiteMargin = (CheckBox) findViewById(R.id.whiteMargin); ckbAutoColor = (CheckBox) findViewById(R.id.autoColor); ckbBinarize = (CheckBox) findViewById(R.id.binarize); ckbRoundedDataDots = (CheckBox) findViewById(R.id.rounded); etBinarizeThreshold = (EditText) findViewById(R.id.binarizeThreshold); etLogoMargin = (EditText) findViewById(R.id.logoMargin); etLogoScale = (EditText) findViewById(R.id.logoScale); etLogoCornerRadius = (EditText) findViewById(R.id.logoRadius); etBinarizeThreshold = (EditText) findViewById(R.id.binarizeThreshold); ckbAutoColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { etColorLight.setEnabled(!isChecked); etColorDark.setEnabled(!isChecked); } }); ckbBinarize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { etBinarizeThreshold.setEnabled(isChecked); } }); btSelectBG.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_GET_CONTENT); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); } intent.setType("image/*"); startActivityForResult(intent, BKG_IMAGE); } }); btSelectLogo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_GET_CONTENT); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); } intent.setType("image/*"); startActivityForResult(intent, LOGO_IMAGE); } }); btOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (qrBitmap != null) saveBitmap(qrBitmap); } }); btRemoveBackgroundImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backgroundImage = null; Toast.makeText(MainActivity.this, "Background image removed.", Toast.LENGTH_SHORT).show(); } }); btRemoveLogoImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logoImage = null; Toast.makeText(MainActivity.this, "Logo image removed.", Toast.LENGTH_SHORT).show(); } }); btGenerate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { generate(etContents.getText().length() == 0 ? "Makito loves Kafuu Chino." : etContents.getText().toString(), etSize.getText().length() == 0 ? 800 : Integer.parseInt(etSize.getText().toString()), etMargin.getText().length() == 0 ? 20 : Integer.parseInt(etMargin.getText().toString()), etDotScale.getText().length() == 0 ? 0.3f : Float.parseFloat(etDotScale.getText().toString()), ckbAutoColor.isChecked() ? Color.BLACK : Color.parseColor(etColorDark.getText().toString()), ckbAutoColor.isChecked() ? Color.WHITE : Color.parseColor(etColorLight.getText().toString()), backgroundImage, ckbWhiteMargin.isChecked(), ckbAutoColor.isChecked(), ckbBinarize.isChecked(), etBinarizeThreshold.getText().length() == 0 ? 128 : Integer.parseInt(etBinarizeThreshold.getText().toString()), ckbRoundedDataDots.isChecked(), logoImage, etLogoMargin.getText().length() == 0 ? 10 : Integer.parseInt(etLogoMargin.getText().toString()), etLogoCornerRadius.getText().length() == 0 ? 8 : Integer.parseInt(etLogoCornerRadius.getText().toString()), etLogoScale.getText().length() == 0 ? 10 : Float.parseFloat(etLogoScale.getText().toString()) ); } catch (Exception e) { Toast.makeText(MainActivity.this, "Error occurred, please check your configs.", Toast.LENGTH_LONG).show(); } } }); tvAuthorHint.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "https://github.com/SumiMakito/AwesomeQRCode"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); tvJSHint.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "https://github.com/SumiMakito/Awesome-qr.js"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); } @Override protected void onResume() { super.onResume(); acquireStoragePermissions(); } private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; private void acquireStoragePermissions() { int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && data.getData() != null) { try { Uri imageUri = data.getData(); if (requestCode == BKG_IMAGE) { backgroundImage = BitmapFactory.decodeFile(ContentHelper.absolutePathFromUri(this, imageUri)); Toast.makeText(this, "Background image added.", Toast.LENGTH_SHORT).show(); } else if (requestCode == LOGO_IMAGE) { logoImage = BitmapFactory.decodeFile(ContentHelper.absolutePathFromUri(this, imageUri)); Toast.makeText(this, "Logo image added.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); if (requestCode == BKG_IMAGE) { Toast.makeText(this, "Failed to add the background image.", Toast.LENGTH_SHORT).show(); } else if (requestCode == LOGO_IMAGE) { Toast.makeText(this, "Failed to add the logo image.", Toast.LENGTH_SHORT).show(); } } } super.onActivityResult(requestCode, resultCode, data); } private void generate(final String contents, final int size, final int margin, final float dotScale, final int colorDark, final int colorLight, final Bitmap background, final boolean whiteMargin, final boolean autoColor, final boolean binarize, final int binarizeThreshold, final boolean roundedDD, final Bitmap logoImage, final int logoMargin, final int logoCornerRadius, final float logoScale) { if (generating) return; generating = true; progressDialog = new ProgressDialog.Builder(this).setMessage("Generating...").setCancelable(false).create(); progressDialog.show(); new AwesomeQRCode.Renderer().contents(contents) .size(size).margin(margin).dotScale(dotScale) .colorDark(colorDark).colorLight(colorLight) .background(background).whiteMargin(whiteMargin) .autoColor(autoColor).roundedDots(roundedDD) .binarize(binarize).binarizeThreshold(binarizeThreshold) .logo(logoImage).logoMargin(logoMargin) .logoRadius(logoCornerRadius).logoScale(logoScale) .renderAsync(new AwesomeQRCode.Callback() { @Override public void onRendered(AwesomeQRCode.Renderer renderer, final Bitmap bitmap) { runOnUiThread(new Runnable() { @Override public void run() { qrCodeImageView.setImageBitmap(bitmap); configViewContainer.setVisibility(View.GONE); resultViewContainer.setVisibility(View.VISIBLE); if (progressDialog != null) progressDialog.dismiss(); generating = false; } }); } @Override public void onError(AwesomeQRCode.Renderer renderer, Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { if (progressDialog != null) progressDialog.dismiss(); configViewContainer.setVisibility(View.VISIBLE); resultViewContainer.setVisibility(View.GONE); generating = false; } }); } }); } private void saveBitmap(Bitmap bitmap) { FileOutputStream fos = null; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); File outputFile = new File(getPublicContainer(), System.currentTimeMillis() + ".png"); fos = new FileOutputStream(outputFile); fos.write(byteArray); fos.close(); Toast.makeText(this, "Image saved to " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Failed to save the image.", Toast.LENGTH_LONG).show(); } } public static File getPublicContainer() { File musicContainer = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File aqr = new File(musicContainer, "AwesomeQR"); if (aqr.exists() && !aqr.isDirectory()) { aqr.delete(); } aqr.mkdirs(); return aqr; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (configViewContainer.getVisibility() != View.VISIBLE) { configViewContainer.setVisibility(View.VISIBLE); resultViewContainer.setVisibility(View.GONE); return true; } } return super.onKeyDown(keyCode, event); } }
3e04eb9716967dd6f65fed26fd2f9bc3f3166081
403
java
Java
voogasalad/authoring/gui/animation/AnimationGUITester.java
narendly/VoogaSalad
39c77585ea6708d876b132e84be1dc144cd77765
[ "MIT" ]
3
2016-11-02T22:05:10.000Z
2019-04-06T01:51:23.000Z
voogasalad/authoring/gui/animation/AnimationGUITester.java
narendly/VoogaSalad
39c77585ea6708d876b132e84be1dc144cd77765
[ "MIT" ]
null
null
null
voogasalad/authoring/gui/animation/AnimationGUITester.java
narendly/VoogaSalad
39c77585ea6708d876b132e84be1dc144cd77765
[ "MIT" ]
null
null
null
16.791667
57
0.73201
2,056
package authoring.gui.animation; import javafx.application.Application; import javafx.stage.Stage; /** * Simple tester to debug. * * @author Aditya Srinivasan * */ public class AnimationGUITester extends Application { @Override public void start(Stage primaryStage) throws Exception { new AnimationEventBuilder().show(); } public static void main(String[] args) { launch(args); } }
3e04ec18f2038350479f88eca837d6c63e302a7c
309
java
Java
java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.xml/javax/xml/package-info.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.xml/javax/xml/package-info.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
java/jdk/jdk_14/jdk_code_view/src/com/company/source/java.xml/javax/xml/package-info.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
8.828571
79
0.543689
2,057
/* * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /** * * Defines constants for XML processing. * * @since 1.5 * */ package javax.xml;
3e04ec6d2efddea707b4e9e7de47ba7fa2737750
1,625
java
Java
src/main/java/com/woowacourse/pelotonbackend/certification/presentation/dto/CertificationRequest.java
woowacourse-teams/2020-14f-guys
9ae16b690c4cf5ef2831f297ad6eade5d9165872
[ "MIT" ]
26
2020-07-08T04:23:17.000Z
2022-03-29T09:48:32.000Z
src/main/java/com/woowacourse/pelotonbackend/certification/presentation/dto/CertificationRequest.java
woowacourse-teams/2020-14f-guys
9ae16b690c4cf5ef2831f297ad6eade5d9165872
[ "MIT" ]
181
2020-07-04T13:35:34.000Z
2022-02-27T07:55:27.000Z
src/main/java/com/woowacourse/pelotonbackend/certification/presentation/dto/CertificationRequest.java
woowacourse-teams/2020-14f-guys
9ae16b690c4cf5ef2831f297ad6eade5d9165872
[ "MIT" ]
8
2020-07-08T04:24:05.000Z
2021-08-03T04:56:26.000Z
31.862745
111
0.726769
2,058
package com.woowacourse.pelotonbackend.certification.presentation.dto; import java.beans.ConstructorProperties; import javax.validation.constraints.NotNull; import org.springframework.data.jdbc.core.mapping.AggregateReference; import com.woowacourse.pelotonbackend.certification.domain.Certification; import com.woowacourse.pelotonbackend.certification.domain.CertificationStatus; import com.woowacourse.pelotonbackend.vo.ImageUrl; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @AllArgsConstructor(onConstructor_ = @ConstructorProperties({"status", "description", "riderId", "missionId"})) @Builder @Getter public class CertificationRequest { @NotNull private final CertificationStatus status; private final String description; @NotNull private final Long riderId; @NotNull private final Long missionId; public Certification toCertification(final String imageUrl) { return Certification.builder() .status(status) .description(description) .riderId(AggregateReference.to(riderId)) .missionId(AggregateReference.to(missionId)) .image(new ImageUrl(imageUrl)) .build(); } public Certification toUpdatedCertification(final Certification certification, final String imageUrl) { return certification.toBuilder() .status(status) .description(description) .image(new ImageUrl(imageUrl)) .missionId(AggregateReference.to(missionId)) .riderId(AggregateReference.to(riderId)) .build(); } }
3e04ec90573d1114d04486fdde2294682c1bb71d
2,500
java
Java
deliverable4/Trap.java
0matls/HungerGames-Board-Game
13844fcb07a16ef21af39d5404830c2e1dde25a0
[ "MIT" ]
null
null
null
deliverable4/Trap.java
0matls/HungerGames-Board-Game
13844fcb07a16ef21af39d5404830c2e1dde25a0
[ "MIT" ]
null
null
null
deliverable4/Trap.java
0matls/HungerGames-Board-Game
13844fcb07a16ef21af39d5404830c2e1dde25a0
[ "MIT" ]
null
null
null
23.364486
121
0.5124
2,059
package deliverable4; /** * * Class denoting a trap on the board.Traps can be either ropes or animals. * */ public class Trap { private int id; private int x; private int y; private String type; private int points; /** * Constructor of the class; initializes its identity (counting starts from one),and its type (i.e. rope or animal). * * NOTE THAT : its x and y coordinates on the board aren't needed as arguments as they will be set in * function createRandomTrap in class Board, so for now they are temporarily set to 0. * Points (the player loses them when he comes across a trap's tile on the board) are also temporarily set to 0 * as their value will be defined (randomly) in function createRandomTrap in class Board. * * @param id the unique identifier of the trap * @param type (i.e rope or animal) */ public Trap(int id, String type) { this.id = id; this.x = 0; this.y = 0; this.type = type; this.points = 0; } /** * Constructor of the class; initializes its variables by a Trap object given as an argument * @param trap object */ public Trap(Trap trap) { this.id = trap.id; this.x = trap.x; this.y = trap.y; this.type = trap.type; this.points = trap.points; } /** * functions (a.k.a setters) to set the values of the variables in the class * @param id, x, y, type, points */ public void setId(int id) { this.id = id; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setType(String type) { this.type = type; } public void setPoints(int points) { this.points = points; } /** * functions (a.k.a getters) to get the values of the variables in the class * @return id, x, y, type, points */ public int getId() { return id; } public int getX() { return x; } public int getY() { return y; } public String getType() { return type; } public int getPoints() { return points; } }
3e04ed5b847654460c90c2784c2671f830e20efe
1,020
java
Java
intermediate/challenge-1/backend/challenge/src/main/java/com/mg/challenge/services/UserDetailsService.java
MortadaGh/amaze-us
cd46f3a7447fc9662f1d2fb398f6783c7b48a1e3
[ "Apache-2.0" ]
null
null
null
intermediate/challenge-1/backend/challenge/src/main/java/com/mg/challenge/services/UserDetailsService.java
MortadaGh/amaze-us
cd46f3a7447fc9662f1d2fb398f6783c7b48a1e3
[ "Apache-2.0" ]
null
null
null
intermediate/challenge-1/backend/challenge/src/main/java/com/mg/challenge/services/UserDetailsService.java
MortadaGh/amaze-us
cd46f3a7447fc9662f1d2fb398f6783c7b48a1e3
[ "Apache-2.0" ]
null
null
null
28.333333
83
0.785294
2,060
package com.mg.challenge.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.mg.challenge.pojos.Role; import com.mg.challenge.pojos.User; import com.mg.challenge.repositories.UserRepository; @Service public class UserDetailsService { @Autowired private UserRepository userRepository; public User loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found - username: " + username); } return user; } public List<Role> getUserRoles(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found - username: " + username); } return user.getRoles(); } }
3e04ee4ea76e75be9a1ce2d41f0bcc8efd11bc74
4,266
java
Java
ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureConfirmation.java
mmoayyed/ws-wss4j
022dcafd761d184442a957a15bb0dc4b0ac3b8ad
[ "Apache-2.0" ]
10
2019-11-01T15:25:53.000Z
2021-11-30T02:11:55.000Z
ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureConfirmation.java
mmoayyed/ws-wss4j
022dcafd761d184442a957a15bb0dc4b0ac3b8ad
[ "Apache-2.0" ]
29
2019-11-27T12:02:23.000Z
2022-03-15T09:05:34.000Z
ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureConfirmation.java
mmoayyed/ws-wss4j
022dcafd761d184442a957a15bb0dc4b0ac3b8ad
[ "Apache-2.0" ]
27
2019-11-21T14:43:48.000Z
2022-02-12T22:36:53.000Z
32.815385
94
0.680731
2,061
/** * 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.wss4j.dom.message; import org.apache.wss4j.dom.message.token.SignatureConfirmation; import org.apache.wss4j.dom.util.WSSecurityUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Builds a WS SignatureConfirmation and inserts it into the SOAP Envelope. */ public class WSSecSignatureConfirmation extends WSSecBase { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(WSSecSignatureConfirmation.class); private SignatureConfirmation sc; private byte[] signatureValue; public WSSecSignatureConfirmation(WSSecHeader securityHeader) { super(securityHeader); } public WSSecSignatureConfirmation(Document doc) { super(doc); } /** * Set the Signature value to store in this SignatureConfirmation. * * @param signatureValue The Signature value to store in the SignatureConfirmation element */ public void setSignatureValue(byte[] signatureValue) { this.signatureValue = signatureValue; } /** * Creates a SignatureConfimation element. * * The method prepares and initializes a WSSec SignatureConfirmation structure after * the relevant information was set. Before calling <code>prepare()</code> the * filed <code>signatureValue</code> must be set */ public void prepare() { sc = new SignatureConfirmation(getDocument(), signatureValue); sc.setID(getIdAllocator().createId("SC-", sc)); if (addWSUNamespace) { sc.addWSUNamespace(); } } /** * Prepends the SignatureConfirmation element to the elements already in the * Security header. * * The method can be called any time after <code>prepare()</code>. * This allows to insert the SignatureConfirmation element at any position in the * Security header. */ public void prependToHeader() { Element securityHeaderElement = getSecurityHeader().getSecurityHeaderElement(); WSSecurityUtil.prependChildElement(securityHeaderElement, sc.getElement()); } /** * Adds a new <code>SignatureConfirmation</code> to a soap envelope. * * A complete <code>SignatureConfirmation</code> is constructed and added * to the <code>wsse:Security</code> header. * * @param sigVal the Signature value. This will be the content of the "Value" attribute. * @return Document with SignatureConfirmation added */ public Document build(byte[] sigVal) { LOG.debug("Begin add signature confirmation..."); signatureValue = sigVal; prepare(); prependToHeader(); return getDocument(); } /** * Get the id generated during <code>prepare()</code>. * * Returns the the value of wsu:Id attribute of this SignatureConfirmation. * * @return Return the wsu:Id of this token or null if <code>prepareToken()</code> * was not called before. */ public String getId() { if (sc == null) { return null; } return sc.getID(); } /** * Get the SignatureConfirmation element generated during * <code>prepare()</code>. * * @return Return the SignatureConfirmation element or null if <code>prepare()</code> * was not called before. */ public Element getSignatureConfirmationElement() { return (sc != null) ? sc.getElement() : null; } }
3e04efd4e60708e7b9c54d5c00d7f89dc03ee975
3,400
java
Java
hadoop-tools/hadoop-posum/src/main/java/org/apache/hadoop/tools/posum/common/records/call/impl/pb/DeleteByQueryCallPBImpl.java
an3m0na/hadoop
9e8ce36b585c20fad4db7d6256d4ba7cac3f7d65
[ "Apache-2.0" ]
null
null
null
hadoop-tools/hadoop-posum/src/main/java/org/apache/hadoop/tools/posum/common/records/call/impl/pb/DeleteByQueryCallPBImpl.java
an3m0na/hadoop
9e8ce36b585c20fad4db7d6256d4ba7cac3f7d65
[ "Apache-2.0" ]
43
2016-07-16T13:44:18.000Z
2018-04-08T11:59:44.000Z
hadoop-tools/hadoop-posum/src/main/java/org/apache/hadoop/tools/posum/common/records/call/impl/pb/DeleteByQueryCallPBImpl.java
an3m0na/hadoop
9e8ce36b585c20fad4db7d6256d4ba7cac3f7d65
[ "Apache-2.0" ]
null
null
null
29.059829
98
0.730588
2,062
package org.apache.hadoop.tools.posum.common.records.call.impl.pb; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.TextFormat; import org.apache.hadoop.tools.posum.common.records.call.DeleteByQueryCall; import org.apache.hadoop.tools.posum.common.records.call.query.DatabaseQuery; import org.apache.hadoop.tools.posum.common.records.call.query.impl.pb.DatabaseQueryWrapperPBImpl; import org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection; import org.apache.hadoop.tools.posum.common.records.pb.PayloadPB; import org.apache.hadoop.yarn.proto.PosumProtos; import org.apache.hadoop.yarn.proto.PosumProtos.ByQueryCallProto; import org.apache.hadoop.yarn.proto.PosumProtos.ByQueryCallProtoOrBuilder; public class DeleteByQueryCallPBImpl extends DeleteByQueryCall implements PayloadPB { private ByQueryCallProto proto = ByQueryCallProto.getDefaultInstance(); private ByQueryCallProto.Builder builder = null; private boolean viaProto = false; public DeleteByQueryCallPBImpl() { builder = ByQueryCallProto.newBuilder(); } public DeleteByQueryCallPBImpl(ByQueryCallProto proto) { this.proto = proto; viaProto = true; } public ByQueryCallProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } private void mergeLocalToBuilder() { } private void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = ByQueryCallProto.newBuilder(proto); } viaProto = false; } @Override public DataEntityCollection getEntityCollection() { ByQueryCallProtoOrBuilder p = viaProto ? proto : builder; return DataEntityCollection.valueOf(p.getCollection().name().substring("COLL_".length())); } @Override public void setEntityCollection(DataEntityCollection type) { if (type == null) return; maybeInitBuilder(); builder.setCollection(PosumProtos.EntityCollectionProto.valueOf("COLL_" + type.name())); } @Override public DatabaseQuery getQuery() { ByQueryCallProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasQuery()) return null; return new DatabaseQueryWrapperPBImpl(p.getQuery()).getQuery(); } @Override public void setQuery(DatabaseQuery query) { maybeInitBuilder(); if (query == null) { builder.clearQuery(); return; } builder.setQuery(new DatabaseQueryWrapperPBImpl(query).getProto()); } @Override public ByteString getProtoBytes() { return getProto().toByteString(); } @Override public void populateFromProtoBytes(ByteString data) throws InvalidProtocolBufferException { this.proto = ByQueryCallProto.parseFrom(data); viaProto = true; } }
3e04f02945f19d7901af2369d6308963763191cd
8,791
java
Java
open-sphere-base/core/src/main/java/io/opensphere/core/geometry/debug/ellipsoid/EllipsoidDebugController.java
smagill/opensphere-desktop
ac18dac63d6496a9f9b96debf2e1d06841f92118
[ "Apache-2.0" ]
25
2018-01-25T23:01:39.000Z
2022-02-21T22:24:00.000Z
open-sphere-base/core/src/main/java/io/opensphere/core/geometry/debug/ellipsoid/EllipsoidDebugController.java
smagill/opensphere-desktop
ac18dac63d6496a9f9b96debf2e1d06841f92118
[ "Apache-2.0" ]
71
2019-11-22T22:39:25.000Z
2020-03-30T01:06:30.000Z
open-sphere-base/core/src/main/java/io/opensphere/core/geometry/debug/ellipsoid/EllipsoidDebugController.java
smagill/opensphere-desktop
ac18dac63d6496a9f9b96debf2e1d06841f92118
[ "Apache-2.0" ]
11
2018-09-04T09:35:01.000Z
2021-04-21T14:15:33.000Z
45.549223
130
0.687635
2,063
package io.opensphere.core.geometry.debug.ellipsoid; import io.opensphere.core.MapManager; import io.opensphere.core.geometry.EllipsoidGeometry; import io.opensphere.core.geometry.EllipsoidGeometryBuilder; import io.opensphere.core.geometry.GeometryRegistry; import io.opensphere.core.geometry.renderproperties.DefaultPolygonMeshRenderProperties; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL.ColorMaterialModeParameterType; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL.FaceParameterType; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL.LightModelVectorParameterType; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL.LightVectorParameterType; import io.opensphere.core.geometry.renderproperties.LightingModelConfigGL.MaterialVectorParameterType; import io.opensphere.core.geometry.renderproperties.ZOrderRenderProperties; import io.opensphere.core.model.Altitude.ReferenceLevel; import io.opensphere.core.model.GeographicPosition; import io.opensphere.core.model.LatLonAlt; import io.opensphere.core.preferences.Preferences; import io.opensphere.core.preferences.PreferencesRegistry; import io.opensphere.core.util.ColorUtilities; import io.opensphere.core.util.collections.New; /** * Publishes the ellipsoid geometry to the globe when user requests it from the * {@link EllipsoidDebugUI}. */ public class EllipsoidDebugController implements Runnable { /** * Used to publish the ellipsoids. */ private final GeometryRegistry myGeometryRegistry; /** * Used to build the geometry. */ private final MapManager myMapManager; /** * Contains all the user inputs. */ private final EllipsoidDebugModel myModel; /** * Used to store previous values. */ private final PreferencesRegistry myPrefs; /** * Constructs a new debug controller. * * @param mapManager Used to build the geometry. * @param geometryRegistry Used to publish the ellipsoids. * @param prefsRegistry Used to save the inputs. */ public EllipsoidDebugController(MapManager mapManager, GeometryRegistry geometryRegistry, PreferencesRegistry prefsRegistry) { myMapManager = mapManager; myGeometryRegistry = geometryRegistry; myPrefs = prefsRegistry; myModel = restoreModel(); } /** * Gets the model to edit. * * @return The model to edit. */ public EllipsoidDebugModel getModel() { return myModel; } /** * Publishes the ellipsoid to the globe. */ @Override public void run() { saveModel(); if (myModel.isRemovePrevious().get()) { myGeometryRegistry.removeGeometriesForSource(this.getClass()); } EllipsoidGeometryBuilder<GeographicPosition> builder = new EllipsoidGeometryBuilder<>(myMapManager); builder.setAxisAMeters(myModel.getAxisA().get()); builder.setAxisBMeters(myModel.getAxisB().get()); builder.setAxisCMeters(myModel.getAxisC().get()); builder.setColor(ColorUtilities.opacitizeColor(myModel.getColor(), myModel.getOpacity().get())); builder.setHeading(myModel.getHeading().get()); builder.setQuality(myModel.getQuality().get()); LatLonAlt location = LatLonAlt.createFromDegreesMeters(myModel.getLatitude().get(), myModel.getLongitude().get(), myModel.getAltitude().get(), ReferenceLevel.TERRAIN); builder.setLocation(new GeographicPosition(location)); builder.setPitch(myModel.getPitch().get()); builder.setRoll(myModel.getRoll().get()); DefaultPolygonMeshRenderProperties meshProps = new DefaultPolygonMeshRenderProperties(ZOrderRenderProperties.TOP_Z, true, true, false); if (myModel.isUseLighting().get()) { meshProps.setLighting(getLightingModel()); } EllipsoidGeometry geom = new EllipsoidGeometry(builder, meshProps, null); myGeometryRegistry.addGeometriesForSource(this.getClass(), New.list(geom)); } /** * Gets the lighting model to test light rendering ellipsoids. * * @return The lighting model. */ private LightingModelConfigGL getLightingModel() { LightingModelConfigGL.Builder builder = new LightingModelConfigGL.Builder(); builder.setLightNumber(0); builder.setFace(FaceParameterType.FRONT); builder.setColorMaterialMode(ColorMaterialModeParameterType.AMBIENT_AND_DIFFUSE); final float[] ambientLight = { 0.50f, 0.50f, 0.50f, 1f }; final float[] diffuseLight = { 1f, 1f, 1f, 1f }; final float[] position = { -0.17f, 0.61f, 0.81f, 0f }; final float[] specular = { 0.74f, 0.77f, 0.77f, 1f }; final float[] specularReflectivity = { 0.9f, 0.9f, 0.9f, 1f }; final float shininess = 80f; builder.addLightModelVectorParameter(LightModelVectorParameterType.LIGHT_MODEL_AMBIENT, ambientLight); builder.addLightParameterVector(LightVectorParameterType.DIFFUSE, diffuseLight); builder.addLightParameterVector(LightVectorParameterType.POSITION, position); builder.addLightParameterVector(LightVectorParameterType.SPECULAR, specular); builder.addMaterialVectorParameter(MaterialVectorParameterType.SPECULAR, specularReflectivity); builder.addMaterialShininessParameter(shininess); return new LightingModelConfigGL(builder); } /** * Restores the previous model values. * * @return The restored saved model. */ private EllipsoidDebugModel restoreModel() { Preferences prefs = myPrefs.getPreferences(EllipsoidDebugController.class); EllipsoidDebugModel model = new EllipsoidDebugModel(); model.getAltitude().set(prefs.getDouble("Altitude", model.getAltitude().get())); model.getAxisA().set(prefs.getDouble("AxisA", model.getAxisA().get())); model.getAxisB().set(prefs.getDouble("AxisB", model.getAxisB().get())); model.getAxisC().set(prefs.getDouble("AxisC", model.getAxisC().get())); model.setColor(ColorUtilities .convertFromColorString(prefs.getString("Color", ColorUtilities.convertToRGBAColorString(model.getColor())))); model.getHeading().set(prefs.getDouble("Heading", model.getHeading().get())); model.getLatitude().set(prefs.getDouble("Latitude", model.getLatitude().get())); model.getLongitude().set(prefs.getDouble("Longitude", model.getLongitude().get())); model.getOpacity().set(prefs.getInt("Opacity", model.getOpacity().get())); model.getPitch().set(prefs.getDouble("Pitch", model.getPitch().get())); model.getQuality().set(prefs.getInt("Quality", model.getQuality().get())); model.getRoll().set(prefs.getDouble("Roll", model.getRoll().get())); model.getAltitude().set(prefs.getDouble("Altitude", model.getAltitude().get())); model.isUseLighting().set(prefs.getBoolean("UseLighting", model.isUseLighting().get())); model.isRemovePrevious().set(prefs.getBoolean("RemovePrevious", model.isRemovePrevious().get())); return model; } /** * Saves the model to the preferences. */ private void saveModel() { Preferences prefs = myPrefs.getPreferences(EllipsoidDebugController.class); prefs.putDouble("Altitude", myModel.getAltitude().get(), this); prefs.putDouble("AxisA", myModel.getAxisA().get(), this); prefs.putDouble("AxisB", myModel.getAxisB().get(), this); prefs.putDouble("AxisC", myModel.getAxisC().get(), this); prefs.putString("Color", ColorUtilities.convertToRGBAColorString(myModel.getColor()), this); prefs.putDouble("Heading", myModel.getHeading().get(), this); prefs.putDouble("Latitude", myModel.getLatitude().get(), this); prefs.putDouble("Longitude", myModel.getLongitude().get(), this); prefs.putInt("Opacity", myModel.getOpacity().get(), this); prefs.putDouble("Pitch", myModel.getPitch().get(), this); prefs.putInt("Quality", myModel.getQuality().get(), this); prefs.putDouble("Roll", myModel.getRoll().get(), this); prefs.putDouble("Altitude", myModel.getAltitude().get(), this); prefs.putBoolean("UseLighting", myModel.isUseLighting().get(), this); prefs.putBoolean("RemovePrevious", myModel.isRemovePrevious().get(), this); } }
3e04f0ef69f4b3f7e9eaf79abe8163c931acdd56
6,115
java
Java
app/src/main/java/ludwig/samuel/thinn/data/User.java
JadeFoXx/Thinn
9773b2a5a46743770c7b295646d8598859bbf77a
[ "MIT" ]
null
null
null
app/src/main/java/ludwig/samuel/thinn/data/User.java
JadeFoXx/Thinn
9773b2a5a46743770c7b295646d8598859bbf77a
[ "MIT" ]
null
null
null
app/src/main/java/ludwig/samuel/thinn/data/User.java
JadeFoXx/Thinn
9773b2a5a46743770c7b295646d8598859bbf77a
[ "MIT" ]
null
null
null
29.258373
189
0.611447
2,064
package ludwig.samuel.thinn.data; import android.content.Context; import android.content.SharedPreferences; import android.databinding.BaseObservable; import android.databinding.Bindable; import ludwig.samuel.thinn.BR; public class User extends BaseObservable { private static User instance; private String sex = "male"; private String age = "25"; private String height = "197"; private String weight = "120"; private String neckCircumference = "45"; private String waistCircumference = "126"; private String hipCircumference = "140"; private String activity = "1.2"; private String delta = "-500"; public static User getInstance() { if (instance == null) { instance = new User(); } return instance; } @Bindable public String getSex() { return this.sex; } @Bindable public String getAge() { return this.age; } @Bindable public String getHeight() { return this.height; } @Bindable public String getWeight() { return this.weight; } @Bindable public String getNeckCircumference() { return neckCircumference; } @Bindable public String getWaistCircumference() { return waistCircumference; } @Bindable public String getHipCircumference() { return hipCircumference; } private int sti(String string) { if(!string.isEmpty()) { return Integer.valueOf(string); } return 0; } private double std(String string) { if(!string.isEmpty()) { return Double.valueOf(string); } return 0; } @Bindable public int getBodyfatPercentage() { if (sex.equals("male")) { return (int) (495 / (1.0324 - 0.19077 * Math.log10(sti(waistCircumference) - sti(neckCircumference)) + 0.15456 * Math.log10(sti(height))) - 450 + 0.5); } else { return (int) (495 / (1.29579 - 0.35004 * Math.log10(sti(waistCircumference) + sti(hipCircumference) - sti(neckCircumference)) + 0.22100 * Math.log10(sti(height))) - 450 + 0.5); } } @Bindable public String getActivity() { return activity; } @Bindable public int getTdee() { double leanBodyMass = sti(weight) * (1 - (getBodyfatPercentage() / 100.0)); double rdee = 370 + (21.6 * leanBodyMass); return (int) (std(activity) * rdee); } @Bindable public String getDelta() { return delta; } @Bindable public int getDailyCalories() { return getTdee() + sti(delta); } public void setSex(String sex) { this.sex = sex; setTdee(); notifyPropertyChanged(BR.sex); } public void setAge(String age) { this.age = age; setTdee(); notifyPropertyChanged(BR.age); } public void setHeight(String height) { this.height = height; setTdee(); notifyPropertyChanged(BR.height); } public void setWeight(String weight) { this.weight = weight; setTdee(); notifyPropertyChanged(BR.weight); } public void setNeckCircumference(String circumference) { this.neckCircumference = circumference; setBodyfatPercentage(); notifyPropertyChanged(BR.neckCircumference); } public void setWaistCircumference(String circumference) { this.waistCircumference = circumference; setBodyfatPercentage(); notifyPropertyChanged(BR.waistCircumference); } public void setHipCircumference(String circumference) { this.hipCircumference = circumference; setBodyfatPercentage(); notifyPropertyChanged(BR.hipCircumference); } public void setBodyfatPercentage() { setTdee(); notifyPropertyChanged(BR.bodyfatPercentage); } public void setActivity(String activity) { this.activity = activity; setTdee(); notifyPropertyChanged(BR.activity); } public void setTdee() { setDailyCalories(); notifyPropertyChanged(BR.tdee); } public void setDelta(String delta) { this.delta = delta; setDailyCalories(); notifyPropertyChanged(BR.delta); } public void setDailyCalories() { notifyPropertyChanged(BR.dailyCalories); } public void save(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences("thinn_user", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("sex", sex); editor.putString("age", age); editor.putString("height", height); editor.putString("weight", weight); editor.putString("neckCircumference", neckCircumference); editor.putString("waistCircumference", waistCircumference); editor.putString("hipCircumference", hipCircumference); editor.putString("activity", String.valueOf(activity)); editor.putString("delta", delta); editor.commit(); } public void restore(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences("thinn_user", Context.MODE_PRIVATE); sex = sharedPreferences.getString("sex", "male"); age = sharedPreferences.getString("age", "25"); height = sharedPreferences.getString("height", "197"); weight = sharedPreferences.getString("weight", "120"); neckCircumference = sharedPreferences.getString("neckCircumference", "45"); waistCircumference = sharedPreferences.getString("waistCircumference", "126"); hipCircumference = sharedPreferences.getString("hipCircumference", "140"); activity = sharedPreferences.getString("activity", "1.2"); delta = sharedPreferences.getString("delta", "-500"); } }
3e04f14dfdd5e26cf1915220887a591dcf04c617
2,514
java
Java
src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
pkwarren/pedantic-pom-enforcers
9b1ef0b1c83f5b0b07afdfb3c3778e8ea3d7f6dc
[ "Apache-2.0" ]
33
2015-09-15T21:30:45.000Z
2021-09-14T14:49:42.000Z
src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
pkwarren/pedantic-pom-enforcers
9b1ef0b1c83f5b0b07afdfb3c3778e8ea3d7f6dc
[ "Apache-2.0" ]
32
2015-01-06T13:08:55.000Z
2021-12-07T06:09:39.000Z
src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
pkwarren/pedantic-pom-enforcers
9b1ef0b1c83f5b0b07afdfb3c3778e8ea3d7f6dc
[ "Apache-2.0" ]
5
2015-01-07T16:37:42.000Z
2021-08-23T02:30:41.000Z
29.576471
93
0.699682
2,065
/* * Copyright (c) 2012 - 2020 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.github.ferstl.maven.pomenforcers.model; import java.util.Map; import com.google.common.collect.Maps; import static java.util.Objects.requireNonNull; public enum PomSection { MODEL_VERSION("modelVersion"), PREREQUISITES("prerequisites"), PARENT("parent"), GROUP_ID("groupId"), ARTIFACT_ID("artifactId"), VERSION("version"), PACKAGING("packaging"), NAME("name"), DESCRIPTION("description"), URL("url"), LICENSES("licenses"), ORGANIZATION("organization"), INCEPTION_YEAR("inceptionYear"), CI_MANAGEMENT("ciManagement"), MAILING_LISTS("mailingLists"), ISSUE_MANAGEMENT("issueManagement"), DEVELOPERS("developers"), CONTRIBUTORS("contributors"), SCM("scm"), REPOSITORIES("repositories"), PLUGIN_REPOSITORIES("pluginRepositories"), DISTRIBUTION_MANAGEMENT("distributionManagement"), MODULES("modules"), PROPERTIES("properties"), DEPENDENCY_MANAGEMENT("dependencyManagement"), DEPENDENCIES("dependencies"), BUILD("build"), PROFILES("profiles"), REPORTING("reporting"), REPORTS("reports"); private static final Map<String, PomSection> pomSectionMap; static { pomSectionMap = Maps.newHashMap(); for (PomSection pomSection : values()) { pomSectionMap.put(pomSection.getSectionName(), pomSection); } } public static PomSection getBySectionName(String sectionName) { requireNonNull(sectionName, "Section name is null."); PomSection value = pomSectionMap.get(sectionName); if (value == null) { throw new IllegalArgumentException("POM section " + sectionName + " does not exist."); } return value; } private final String sectionName; PomSection(String sectionName) { this.sectionName = sectionName; } public String getSectionName() { return this.sectionName; } }
3e04f287056377e08fe50fe29279289640e99cac
2,415
java
Java
plugins/jadaptive-builtin-users/src/main/java/com/jadaptive/plugins/builtin/BuiltinUser.java
ludup/jadaptive-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
2
2020-11-08T00:41:02.000Z
2021-08-21T02:40:53.000Z
plugins/jadaptive-builtin-users/src/main/java/com/jadaptive/plugins/builtin/BuiltinUser.java
ludup/jadaptive-app-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
null
null
null
plugins/jadaptive-builtin-users/src/main/java/com/jadaptive/plugins/builtin/BuiltinUser.java
ludup/jadaptive-app-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
null
null
null
21.756757
115
0.766046
2,066
package com.jadaptive.plugins.builtin; import com.jadaptive.api.entity.ObjectScope; import com.jadaptive.api.entity.ObjectType; import com.jadaptive.api.template.ObjectField; import com.jadaptive.api.template.FieldType; import com.jadaptive.api.template.ObjectDefinition; import com.jadaptive.api.user.EmailEnabledUser; import com.jadaptive.api.user.PasswordEnabledUser; import com.jadaptive.utils.PasswordEncryptionType; @ObjectDefinition(resourceKey = BuiltinUser.RESOURCE_KEY, scope = ObjectScope.GLOBAL, type = ObjectType.COLLECTION) public class BuiltinUser extends PasswordEnabledUser implements EmailEnabledUser { private static final long serialVersionUID = -4186606233520076592L; public static final String RESOURCE_KEY = "builtinUsers"; @ObjectField(required = true, searchable = true, type = FieldType.TEXT, unique = true) String username; @ObjectField(required = true, searchable = true, type = FieldType.TEXT) String name; String encodedPassword; String salt; PasswordEncryptionType encodingType; boolean passwordChangeRequired; @ObjectField(required = false, searchable = true, type = FieldType.TEXT) String email; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getEncodedPassword() { return encodedPassword; } @Override public void setEncodedPassword(String encodedPassword) { this.encodedPassword = encodedPassword; } @Override public String getSalt() { return salt; } @Override public void setSalt(String salt) { this.salt = salt; } @Override public PasswordEncryptionType getEncodingType() { return encodingType; } @Override public void setEncodingType(PasswordEncryptionType encodingType) { this.encodingType = encodingType; } public boolean getPasswordChangeRequired() { return passwordChangeRequired; } public void setPasswordChangeRequired(boolean passwordChangeRequired) { this.passwordChangeRequired = passwordChangeRequired; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String getResourceKey() { return RESOURCE_KEY; } @Override public String getSystemName() { return getUsername(); } }
3e04f32652815c164a0954c37cc294ce8bf381b4
2,045
java
Java
src/main/java/frc/robot/base/device/motor/EncoderMotorConfig.java
FRobotics/robot-2021
1db1e3e768804de820a822bc3c31986664e1ce7d
[ "BSD-3-Clause" ]
2
2021-10-05T23:31:28.000Z
2021-10-05T23:32:07.000Z
src/main/java/frc/robot/base/device/motor/EncoderMotorConfig.java
FRobotics/robot-2021
1db1e3e768804de820a822bc3c31986664e1ce7d
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/base/device/motor/EncoderMotorConfig.java
FRobotics/robot-2021
1db1e3e768804de820a822bc3c31986664e1ce7d
[ "BSD-3-Clause" ]
null
null
null
29.637681
134
0.621027
2,067
package frc.robot.base.device.motor; public class EncoderMotorConfig { /** * Constructs a new motor config where distance is in length * @param wheelRadius the radius of the wheels in inches * @param countsPerRevolution how many counts the encoder gives per revolution * @param f ??? * @param p ??? * @param i ??? * @param d ??? * @param integralZone ??? */ public EncoderMotorConfig(double wheelRadius, int countsPerRevolution, double f, double p, double i, double d, int integralZone) { PID_LOOP_INDEX = 0; TIMEOUT_MS = 30; F = f; P = p; I = i; D = d; INTEGRAL_ZONE = integralZone; double wheel_circumference = wheelRadius * 2 * Math.PI; DISTANCE_MULTIPLIER = wheel_circumference / countsPerRevolution; // 10 * turns 100ms -> 1s INPUT_MULTIPLIER = 10 * DISTANCE_MULTIPLIER; OUTPUT_MULTIPLIER = 1 / INPUT_MULTIPLIER; } /** * Constructs a new config where distance is in revolutions * @param countsPerRevolution how many counts the encoder gives per revolution * @param f ??? * @param p ??? * @param i ??? * @param d ??? * @param integralZone ??? */ public EncoderMotorConfig(int countsPerRevolution, double f, double p, double i, double d, int integralZone) { PID_LOOP_INDEX = 0; TIMEOUT_MS = 30; F = f; P = p; I = i; D = d; INTEGRAL_ZONE = integralZone; DISTANCE_MULTIPLIER = 1d / countsPerRevolution; // 10 * turns 100ms -> 1s INPUT_MULTIPLIER = 10d * DISTANCE_MULTIPLIER * 60d; OUTPUT_MULTIPLIER = 1d / INPUT_MULTIPLIER; } public final int PID_LOOP_INDEX; public final int TIMEOUT_MS; public double F; public double P; public double I; public double D; public int INTEGRAL_ZONE; public final double DISTANCE_MULTIPLIER; public final double INPUT_MULTIPLIER; public final double OUTPUT_MULTIPLIER; }
3e04f37669f518a7ec7789b9809fc35a6c3d4853
5,692
java
Java
com/planet_ink/coffee_mud/Abilities/Misc/Bleeding.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
com/planet_ink/coffee_mud/Abilities/Misc/Bleeding.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
com/planet_ink/coffee_mud/Abilities/Misc/Bleeding.java
kudos72/dbzcoffeemud
19a3a7439fcb0e06e25490e19e795394da1df490
[ "Apache-2.0" ]
null
null
null
35.135802
144
0.72189
2,068
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2008-2014 Bo Zimmerman 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. */ @SuppressWarnings("rawtypes") public class Bleeding extends StdAbility implements HealthCondition { @Override public String ID() { return "Bleeding"; } private final static String localizedName = CMLib.lang().L("Bleeding"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Bleeding)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode(){return CAN_ITEMS|Ability.CAN_MOBS;} @Override protected int canTargetCode(){return 0;} protected int hpToKeep=-1; protected int lastDir=-1; protected Room lastRoom=null; public double healthPct(MOB mob){ return CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints());} @Override public String getHealthConditionDesc() { return "Bleeding externally and excessively."; } @Override public void unInvoke() { if((affected instanceof MOB) &&(canBeUninvoked()) &&(!((MOB)affected).amDead()) &&(CMLib.flags().isInTheGame((MOB)affected,true))) ((MOB)affected).location().show((MOB)affected,null,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> stop(s) bleeding.")); super.unInvoke(); } @Override public void executeMsg(Environmental myHost, CMMsg msg) { super.executeMsg(myHost,msg); if((affected!=null)&&(msg.amITarget(affected))&&(affected instanceof MOB)) { if(msg.targetMinor()==CMMsg.TYP_HEALING) { hpToKeep=-1; if(healthPct((MOB)affected)>0.50) unInvoke(); } else if((msg.targetMinor()==CMMsg.TYP_LOOK) ||(msg.targetMinor()==CMMsg.TYP_EXAMINE)) msg.source().tell((MOB)msg.target(),null,null,L("^R<S-NAME> <S-IS-ARE> still bleeding...")); } else if((msg.source()==affected) &&(msg.target() instanceof Room) &&(msg.tool() instanceof Exit) &&(msg.targetMinor()==CMMsg.TYP_LEAVE)) { final Room R=(Room)msg.target(); int dir=-1; for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) if(msg.tool()==R.getReverseExit(d)) dir=d; if((dir>=0)&&(R.findItem(null,"a trail of blood")==null)) { final Item I=CMClass.getItem("GenFatWallpaper"); I.setName(L("A trail of blood")); if(lastDir>=0) I.setDisplayText(L("A faint trail of blood leads from @x1 to @x2.",Directions.getDirectionName(lastDir),Directions.getDirectionName(dir))); else I.setDisplayText(L("A faint trail of blood leads @x1.",Directions.getDirectionName(dir))); I.phyStats().setDisposition(I.phyStats().disposition()|PhyStats.IS_HIDDEN|PhyStats.IS_UNSAVABLE); I.setSecretIdentity(msg.source().Name()+"`s blood."); R.addItem(I,ItemPossessor.Expire.Monster_EQ); } lastDir=Directions.getOpDirectionCode(dir); lastRoom=R; } } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((ticking instanceof MOB)&&(tickID==Tickable.TICKID_MOB)) { final MOB mob=(MOB)ticking; if(hpToKeep<=0) { hpToKeep=mob.curState().getHitPoints(); mob.recoverMaxState(); } else { if(mob.curState().getHitPoints()>hpToKeep) mob.curState().setHitPoints(hpToKeep); final int maxMana=(int)Math.round(CMath.mul(mob.maxState().getMana(),healthPct(mob))); if(mob.curState().getMana()>maxMana) mob.curState().setMana(maxMana); final int maxMovement=(int)Math.round(CMath.mul(mob.maxState().getMovement(),healthPct(mob))); if(mob.curState().getMovement()>maxMovement) mob.curState().setMovement(maxMovement); } } return true; } @Override public boolean invoke(MOB mob, Vector commands, Physical target, boolean auto, int asLevel) { if(target==null) target=mob; if(!(target instanceof MOB)) return false; if(CMLib.flags().isGolem(target)) return false; if(((MOB)target).phyStats().level()<CMProps.getIntVar(CMProps.Int.INJBLEEDMINLEVEL)) return false; if(((MOB)target).fetchEffect(ID())!=null) return false; if(((MOB)target).location()==null) return false; if(((MOB)target).location().show((MOB)target,null,this,CMMsg.MSG_OK_VISUAL,L("^R<S-NAME> start(s) BLEEDING!^?"))) beneficialAffect(mob,target,asLevel,0); return true; } }
3e04f3963bf410ef4c0df721003eb713fc8b3341
552
java
Java
src/main/java/es/upm/miw/betca_tpv_core/domain/persistence/MessengerPersistence.java
miw-upm/betca-tpv-core
93d995ab6df4f69f231251049d830dcbf6630715
[ "MIT" ]
6
2021-05-04T01:32:10.000Z
2022-03-24T05:46:24.000Z
src/main/java/es/upm/miw/betca_tpv_core/domain/persistence/MessengerPersistence.java
miw-upm/betca-tpv-core
93d995ab6df4f69f231251049d830dcbf6630715
[ "MIT" ]
null
null
null
src/main/java/es/upm/miw/betca_tpv_core/domain/persistence/MessengerPersistence.java
miw-upm/betca-tpv-core
93d995ab6df4f69f231251049d830dcbf6630715
[ "MIT" ]
8
2021-02-22T10:15:24.000Z
2021-11-30T04:00:42.000Z
26.285714
56
0.804348
2,069
package es.upm.miw.betca_tpv_core.domain.persistence; import es.upm.miw.betca_tpv_core.domain.model.Message; import es.upm.miw.betca_tpv_core.domain.model.User; import org.springframework.stereotype.Repository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Repository public interface MessengerPersistence { Mono<Message> create(Message newMessage); Flux<Message> findByUserFromNullSafe(User userFrom); Flux<Message> findByUserToNullSafe(User userTo); Flux<Message> findNotReadMessages(User userTo); }
3e04f459751d1a4f9a95ee6abe7765e4781dac05
2,152
java
Java
xixiwan-platform-module/xixiwan-platform-module-web/src/main/java/com/xixiwan/platform/module/web/form/BaseForm.java
github-xixiwan/xixiwan-platform
7e4f7dec126ceeb593e13444c2fa168690f985ef
[ "Apache-2.0" ]
null
null
null
xixiwan-platform-module/xixiwan-platform-module-web/src/main/java/com/xixiwan/platform/module/web/form/BaseForm.java
github-xixiwan/xixiwan-platform
7e4f7dec126ceeb593e13444c2fa168690f985ef
[ "Apache-2.0" ]
null
null
null
xixiwan-platform-module/xixiwan-platform-module-web/src/main/java/com/xixiwan/platform/module/web/form/BaseForm.java
github-xixiwan/xixiwan-platform
7e4f7dec126ceeb593e13444c2fa168690f985ef
[ "Apache-2.0" ]
null
null
null
19.925926
63
0.651952
2,070
package com.xixiwan.platform.module.web.form; import java.time.LocalDateTime; import java.util.List; public class BaseForm { private String sortName; private String sortOrder; private long pageSize = 10; private long pageNumber = 1; private List<String> sortNames; private String sortOrders; private String rangesType; private String rangesDate; private LocalDateTime startDateTime; private LocalDateTime endDateTime; public String getSortName() { return sortName; } public void setSortName(String sortName) { this.sortName = sortName; } public String getSortOrder() { return sortOrder; } public void setSortOrder(String sortOrder) { this.sortOrder = sortOrder; } public long getPageSize() { return pageSize; } public void setPageSize(long pageSize) { this.pageSize = pageSize; } public long getPageNumber() { return pageNumber; } public void setPageNumber(long pageNumber) { this.pageNumber = pageNumber; } public List<String> getSortNames() { return sortNames; } public void setSortNames(List<String> sortNames) { this.sortNames = sortNames; } public String getSortOrders() { return sortOrders; } public void setSortOrders(String sortOrders) { this.sortOrders = sortOrders; } public String getRangesType() { return rangesType; } public void setRangesType(String rangesType) { this.rangesType = rangesType; } public String getRangesDate() { return rangesDate; } public void setRangesDate(String rangesDate) { this.rangesDate = rangesDate; } public LocalDateTime getStartDateTime() { return startDateTime; } public void setStartDateTime(LocalDateTime startDateTime) { this.startDateTime = startDateTime; } public LocalDateTime getEndDateTime() { return endDateTime; } public void setEndDateTime(LocalDateTime endDateTime) { this.endDateTime = endDateTime; } }
3e04f4c000536c99f3b6c71c266c8a065a72066a
2,661
java
Java
src/main/java/betterwithaddons/item/ItemTanto.java
democat3457/BetterWithAddons
111f864464acaff9d582e99714a7696ef145ccc8
[ "MIT" ]
17
2017-05-25T03:54:38.000Z
2020-12-11T16:42:30.000Z
src/main/java/betterwithaddons/item/ItemTanto.java
democat3457/BetterWithAddons
111f864464acaff9d582e99714a7696ef145ccc8
[ "MIT" ]
170
2016-11-27T01:04:44.000Z
2021-04-15T03:38:23.000Z
src/main/java/betterwithaddons/item/ItemTanto.java
democat3457/BetterWithAddons
111f864464acaff9d582e99714a7696ef145ccc8
[ "MIT" ]
8
2017-06-20T11:40:07.000Z
2020-08-07T20:53:59.000Z
33.683544
230
0.691094
2,071
package betterwithaddons.item; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.potion.PotionEffect; import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; public class ItemTanto extends ItemSword { private boolean disabled; private static final int USE_TIME = 5000; public ItemTanto() { super(ModItems.tamahaganeToolMaterial); } @Override public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { boolean hit = super.hitEntity(stack,target,attacker); if(hit && attacker.getHealth() < 12.0f) { target.attackEntityFrom(DamageSource.causeMobDamage(attacker).setDamageBypassesArmor(), 6.0f); attacker.addPotionEffect(new PotionEffect(MobEffects.SPEED,15 * 20)); } return hit; } @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand hand) { ItemStack itemStackIn = playerIn.getHeldItem(hand); if (playerIn.capabilities.isCreativeMode) { return new ActionResult(EnumActionResult.FAIL, itemStackIn); } else { playerIn.setActiveHand(hand); return new ActionResult(EnumActionResult.SUCCESS, itemStackIn); } } @Override public void onUsingTick(ItemStack stack, EntityLivingBase entityLiving, int timeLeft) { if (entityLiving instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer)entityLiving; int i = timeLeft; System.out.println(i); if(i < USE_TIME-20 && i % 10 == 0) { //entityplayer.getEntityWorld().playSound(null, entityplayer.posX, entityplayer.posY, entityplayer.posZ, SoundEvents.ENTITY_SKELETON_DEATH, SoundCategory.NEUTRAL, 1.0f, 1.0f / (itemRand.nextFloat() * 0.4f + 2.2f)); entityplayer.attackEntityFrom(DamageSource.CACTUS, 1.0f); entityplayer.addStat(StatList.getObjectUseStats(this)); } } } @Override public int getMaxItemUseDuration(ItemStack stack) { return USE_TIME; } @Override public EnumAction getItemUseAction(ItemStack stack) { return EnumAction.BOW; } }
3e04f5b932987e37cb3c1c6ec0ac3fd0a0a524e2
883
java
Java
products/src/main/java/products/ValidationService.java
edigonzales/first-micronaut-app
33de3751d44491c07874e74bec0560e256695b4d
[ "MIT" ]
null
null
null
products/src/main/java/products/ValidationService.java
edigonzales/first-micronaut-app
33de3751d44491c07874e74bec0560e256695b4d
[ "MIT" ]
null
null
null
products/src/main/java/products/ValidationService.java
edigonzales/first-micronaut-app
33de3751d44491c07874e74bec0560e256695b4d
[ "MIT" ]
null
null
null
29.433333
94
0.721404
2,072
package products; import javax.inject.Singleton; import org.interlis2.validator.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.ehi.basics.logging.EhiLogger; import ch.ehi.basics.settings.Settings; @Singleton public class ValidationService { private static final Logger log = LoggerFactory.getLogger(ValidationService.class); public void validate(String inputFileName) { log.info("Validating..."); log.info(inputFileName); EhiLogger.getInstance().setTraceFilter(false); Settings settings = new Settings(); settings.setValue(Validator.SETTING_ILIDIRS, Validator.SETTING_DEFAULT_ILIDIRS); settings.setValue(Validator.SETTING_LOGFILE, "/Users/stefan/tmp/fubar_validator.log"); boolean valid = Validator.runValidation(inputFileName, settings); } }
3e04f5e6022fec56e53a91ad40de4c23038e33ae
1,650
java
Java
seb-producer/testsrc/no/mnemonic/act/platform/seb/producer/v1/converters/ObjectInfoConverterTest.java
frbor/act-platform
424bc54389755d38bc0e1d137023ad95d4f637ae
[ "0BSD" ]
134
2017-06-12T16:24:06.000Z
2022-03-07T13:31:09.000Z
seb-producer/testsrc/no/mnemonic/act/platform/seb/producer/v1/converters/ObjectInfoConverterTest.java
frbor/act-platform
424bc54389755d38bc0e1d137023ad95d4f637ae
[ "0BSD" ]
8
2019-02-20T09:26:07.000Z
2021-12-14T10:55:12.000Z
seb-producer/testsrc/no/mnemonic/act/platform/seb/producer/v1/converters/ObjectInfoConverterTest.java
frbor/act-platform
424bc54389755d38bc0e1d137023ad95d4f637ae
[ "0BSD" ]
36
2017-11-13T13:55:32.000Z
2021-12-14T08:33:41.000Z
27.04918
84
0.741818
2,073
package no.mnemonic.act.platform.seb.producer.v1.converters; import no.mnemonic.act.platform.dao.api.record.ObjectRecord; import no.mnemonic.act.platform.seb.model.v1.ObjectInfoSEB; import no.mnemonic.act.platform.seb.model.v1.ObjectTypeInfoSEB; import no.mnemonic.act.platform.seb.producer.v1.resolvers.ObjectTypeInfoDaoResolver; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.util.UUID; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class ObjectInfoConverterTest { @Mock private ObjectTypeInfoDaoResolver typeResolver; private ObjectInfoConverter converter; @Before public void setUp() { initMocks(this); when(typeResolver.apply(any())).thenReturn(ObjectTypeInfoSEB.builder().build()); converter = new ObjectInfoConverter(typeResolver); } @Test public void testConvertNull() { assertNull(converter.apply(null)); } @Test public void testConvertEmpty() { assertNotNull(converter.apply(new ObjectRecord())); } @Test public void testConvertFull() { ObjectRecord record = new ObjectRecord() .setId(UUID.randomUUID()) .setTypeID(UUID.randomUUID()) .setValue("value"); ObjectInfoSEB seb = converter.apply(record); assertNotNull(seb); assertEquals(record.getId(), seb.getId()); assertNotNull(seb.getType()); assertEquals(record.getValue(), seb.getValue()); verify(typeResolver).apply(record.getTypeID()); } }
3e04f6369c6083a34801586fe746fb03578f092c
1,958
java
Java
src/main/java/com/xiaomi/infra/pegasus/operator/rrdb_check_and_set_operator.java
ZhongChaoqiang/pegasus-java-client
710725663c78987526c532187240f8cccbece696
[ "Apache-2.0" ]
28
2018-03-28T03:28:49.000Z
2021-11-08T20:11:46.000Z
src/main/java/com/xiaomi/infra/pegasus/operator/rrdb_check_and_set_operator.java
ZhongChaoqiang/pegasus-java-client
710725663c78987526c532187240f8cccbece696
[ "Apache-2.0" ]
63
2018-06-21T07:48:10.000Z
2022-03-14T03:23:42.000Z
src/main/java/com/xiaomi/infra/pegasus/operator/rrdb_check_and_set_operator.java
ZhongChaoqiang/pegasus-java-client
710725663c78987526c532187240f8cccbece696
[ "Apache-2.0" ]
27
2018-04-17T09:48:38.000Z
2021-09-27T11:40:52.000Z
34.350877
98
0.758938
2,074
// Copyright (c) 2017, Xiaomi, Inc. All rights reserved. // This source code is licensed under the Apache License Version 2.0, which // can be found in the LICENSE file in the root directory of this source tree. package com.xiaomi.infra.pegasus.operator; import com.xiaomi.infra.pegasus.apps.check_and_set_request; import com.xiaomi.infra.pegasus.apps.check_and_set_response; import com.xiaomi.infra.pegasus.apps.rrdb; import org.apache.thrift.TException; import org.apache.thrift.protocol.TMessage; import org.apache.thrift.protocol.TMessageType; import org.apache.thrift.protocol.TProtocol; public class rrdb_check_and_set_operator extends client_operator { public rrdb_check_and_set_operator( com.xiaomi.infra.pegasus.base.gpid gpid, String tableName, check_and_set_request request, long partitionHash) { super(gpid, tableName, partitionHash); this.request = request; } public String name() { return "check_and_set"; } public void send_data(org.apache.thrift.protocol.TProtocol oprot, int seqid) throws TException { TMessage msg = new TMessage("RPC_RRDB_RRDB_CHECK_AND_SET", TMessageType.CALL, seqid); oprot.writeMessageBegin(msg); rrdb.check_and_set_args incr_args = new rrdb.check_and_set_args(request); incr_args.write(oprot); oprot.writeMessageEnd(); } public void recv_data(TProtocol iprot) throws TException { rrdb.check_and_set_result result = new rrdb.check_and_set_result(); result.read(iprot); if (result.isSetSuccess()) resp = result.success; else throw new org.apache.thrift.TApplicationException( org.apache.thrift.TApplicationException.MISSING_RESULT, "check_and_set failed: unknown result"); } public check_and_set_response get_response() { return resp; } public check_and_set_request get_request() { return request; } private check_and_set_request request; private check_and_set_response resp; }
3e04f651f7ae27eeafc55165e2b46b524f238974
2,137
java
Java
src/main/java/edu/harvard/iq/dataverse/datavariable/VariableRangeType.java
OpenSourceFieldlinguistics/dataverse
188c93605a2b95427e409dd535ced4de075b23a3
[ "Apache-2.0" ]
1
2015-05-07T15:31:49.000Z
2015-05-07T15:31:49.000Z
src/main/java/edu/harvard/iq/dataverse/datavariable/VariableRangeType.java
OpenSourceFieldlinguistics/dataverse
188c93605a2b95427e409dd535ced4de075b23a3
[ "Apache-2.0" ]
null
null
null
src/main/java/edu/harvard/iq/dataverse/datavariable/VariableRangeType.java
OpenSourceFieldlinguistics/dataverse
188c93605a2b95427e409dd535ced4de075b23a3
[ "Apache-2.0" ]
null
null
null
20.747573
79
0.576041
2,075
/* * 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 edu.harvard.iq.dataverse.datavariable; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author Leonid Andreev * * Largely based on the VariableRangeType entity from the DVN v2-3; * original author: Ellen Kraffmiller (2006). * */ @Entity public class VariableRangeType implements Serializable { /* * Simple constructor: */ public VariableRangeType() { } /* * Definitions of class properties: */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /* * name: self-explanatory */ private String name; /* * Getter and Setter methods: */ public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /* * Custom overrides for hashCode(), equals() and toString() methods: */ @Override public int hashCode() { int hash = 0; hash += (this.id != null ? this.id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof VariableRangeType)) { return false; } VariableRangeType other = (VariableRangeType)object; if (this.id != other.id) { if (this.id == null || !this.id.equals(other.id)) { return false; } } return true; } @Override public String toString() { return "edu.harvard.iq.dataverse.VariableRangeType[ id=" + id + " ]"; } }
3e04f6c752ad59f2d8a1a464f20983a2a08f681d
4,885
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivityFragment.java
ngonz232/Twitter
68a4ce25f9a586a1103be58c663609df0af5cd60
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivityFragment.java
ngonz232/Twitter
68a4ce25f9a586a1103be58c663609df0af5cd60
[ "MIT" ]
2
2021-07-02T11:01:48.000Z
2021-07-03T07:33:52.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/ComposeActivityFragment.java
ngonz232/Twitter
68a4ce25f9a586a1103be58c663609df0af5cd60
[ "MIT" ]
null
null
null
41.05042
114
0.613101
2,076
package com.codepath.apps.restclienttemplate; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import com.codepath.apps.restclienttemplate.models.Tweet; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import org.json.JSONException; import okhttp3.Headers; public class ComposeActivityFragment extends DialogFragment { private static int requestCode; public final String TAG = "ComposeDialogFragment"; private static Tweet replyTweet; public final int MAX_TWEET_LENGTH = 280; private EditText etCompose; private Button btnTweet; public interface ComposeDialogListener { void onFinishComposeDialog(Tweet tweet, int requestCode); } public ComposeActivityFragment() { // empty constructor required by DialogFragment. Use newInstance below instead } public static ComposeActivityFragment newInstance(String title, Tweet tweet, int code) { ComposeActivityFragment frag = new ComposeActivityFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); replyTweet = tweet; requestCode = code; return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_compose, container); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // gets the field from view etCompose = (EditText) view.findViewById(R.id.etCompose); btnTweet = (Button) view.findViewById(R.id.btnTweet); // fetch arguments and get title String title = getArguments().getString("title", "Enter Name"); getDialog().setTitle(title); // user that wrote original tweet is automatically "@" in the reply if (replyTweet != null) { etCompose.setText("@" + replyTweet.user.screenName + " "); } // automatically shows soft keyboard and requests focus to field etCompose.requestFocus(); getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); // set ups a call back when the "done" button is pressed on the keyboard btnTweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String tweetContent = etCompose.getText().toString(); // Tweet content validation if (tweetContent.isEmpty()) { makeToast("Sorry, your tweet can't be empty"); return; } else if (tweetContent.length() > MAX_TWEET_LENGTH) { makeToast("Sorry, your tweet is too long"); return; } // Twitter API call for publishing the tweet String replyId = replyTweet == null? "": replyTweet.id; TwitterClient client = TwitterApp.getRestClient(getContext()); client.publishTweet(tweetContent, replyId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { try { // passing the new tweet and closing the activity Tweet tweet = Tweet.fromJson(json.jsonObject); ComposeDialogListener listener = (ComposeDialogListener) getActivity(); listener.onFinishComposeDialog(tweet, requestCode); // closes the dialogue and returns to the parent activity dismiss(); } catch (JSONException e) { // console error log Log.e(TAG, "jsonObject error"); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { // Console error log Log.e(TAG, "onFailure to publish tweet " + response, throwable); } }); } }); } // helper method for a short toast private void makeToast(String message) { Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } }
3e04f6ff3370fb7175805a715b50f1e4f1ab05a0
1,658
java
Java
plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/tokens/predicates/ExactTokenEntryComparator.java
troizet/dbeaver
b58138b3114f2bcaf822fa8f8d9ba558be052a3d
[ "Apache-2.0" ]
1
2022-03-02T19:47:32.000Z
2022-03-02T19:47:32.000Z
plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/tokens/predicates/ExactTokenEntryComparator.java
frankfanslc/dbeaver
51567498d4368cb6d88e984bcbfedfdc84999c73
[ "Apache-2.0" ]
null
null
null
plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/tokens/predicates/ExactTokenEntryComparator.java
frankfanslc/dbeaver
51567498d4368cb6d88e984bcbfedfdc84999c73
[ "Apache-2.0" ]
1
2020-01-03T22:24:12.000Z
2020-01-03T22:24:12.000Z
36.844444
133
0.743064
2,077
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 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.model.sql.parser.tokens.predicates; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.model.sql.parser.TokenEntry; import java.util.Comparator; /** * Strong comparator implementing foll comparison of data carried by two token entries. * Establishes strong ordering on the continuity of possible token entries. */ class ExactTokenEntryComparator extends TokenEntryComparatorBase implements Comparator<TokenEntry> { public static final ExactTokenEntryComparator INSTANCE = new ExactTokenEntryComparator(); private ExactTokenEntryComparator() { } @Override public int compare(@NotNull TokenEntry first, @NotNull TokenEntry second) { // keep in sync with TokenEntryMatchingComparator implementation: look at the partially comparable part of the data at first! int result = compareByTokenTypes(first, second); if (result != 0) { return result; } return compareByStrings(first, second); } }
3e04f7f27a21ac069e2350ae9c87a1e555e3968c
786
java
Java
src/main/java/com/absmis/actuator/CustomHealth.java
XXBM/absmisWeb
4b5c14180896df3fe3949fa833007f7731a7a287
[ "MIT" ]
null
null
null
src/main/java/com/absmis/actuator/CustomHealth.java
XXBM/absmisWeb
4b5c14180896df3fe3949fa833007f7731a7a287
[ "MIT" ]
1
2018-03-29T07:52:02.000Z
2018-03-29T07:52:02.000Z
src/main/java/com/absmis/actuator/CustomHealth.java
XXBM/absmisWeb
4b5c14180896df3fe3949fa833007f7731a7a287
[ "MIT" ]
null
null
null
26.2
82
0.684478
2,078
package com.absmis.actuator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; /** * Created by xuling on 2016/10/22. * 自定义健康指示器 */ @Component public class CustomHealth implements HealthIndicator { @Override public Health health() { try { RestTemplate restTemplate = new RestTemplate(); // 如果这里写一个不存在的URL status为down restTemplate.getForObject("http://localhost:8080/index",String.class); return Health.up().build(); }catch (Exception e){ return Health.down().withDetail("down的原因:",e.getMessage()).build(); } } }
3e04f82e84397786ec8abe72847989a2106017f9
1,184
java
Java
sm-shop/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java
michaelthecsguy/shopizer
6670e67f2cc89decad7f245818e208777f158f3e
[ "Apache-2.0" ]
2,881
2015-01-02T09:11:32.000Z
2022-03-31T18:24:07.000Z
sm-shop/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java
michaelthecsguy/shopizer
6670e67f2cc89decad7f245818e208777f158f3e
[ "Apache-2.0" ]
674
2019-11-05T17:32:25.000Z
2021-08-03T18:27:07.000Z
sm-shop/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java
michaelthecsguy/shopizer
6670e67f2cc89decad7f245818e208777f158f3e
[ "Apache-2.0" ]
2,600
2015-01-01T16:33:11.000Z
2022-03-31T17:35:09.000Z
24.666667
113
0.79223
2,079
package com.salesmanager.shop.model.shoppingcart; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.salesmanager.shop.model.catalog.product.ReadableProduct; /** * compatible with v1 version * @author c.samson * */ public class ReadableShoppingCartItem extends ReadableProduct implements Serializable { /** * */ private static final long serialVersionUID = 1L; private BigDecimal subTotal; private String displaySubTotal; private List<ReadableShoppingCartAttribute> cartItemattributes = new ArrayList<ReadableShoppingCartAttribute>(); public BigDecimal getSubTotal() { return subTotal; } public void setSubTotal(BigDecimal subTotal) { this.subTotal = subTotal; } public String getDisplaySubTotal() { return displaySubTotal; } public void setDisplaySubTotal(String displaySubTotal) { this.displaySubTotal = displaySubTotal; } public List<ReadableShoppingCartAttribute> getCartItemattributes() { return cartItemattributes; } public void setCartItemattributes(List<ReadableShoppingCartAttribute> cartItemattributes) { this.cartItemattributes = cartItemattributes; } }
3e04f8611ba65caae08d1dd827ab0a7e2cf00f0d
3,365
java
Java
Mage/src/main/java/mage/abilities/effects/common/DoIfClashWonEffect.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage/src/main/java/mage/abilities/effects/common/DoIfClashWonEffect.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage/src/main/java/mage/abilities/effects/common/DoIfClashWonEffect.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
35.052083
122
0.623477
2,080
package mage.abilities.effects.common; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.constants.Outcome; import mage.game.Game; import mage.players.Player; import mage.target.targetpointer.FixedTarget; import mage.util.CardUtil; /** * * @author LevelX2 */ public class DoIfClashWonEffect extends OneShotEffect { protected final Effect executingEffect; private String chooseUseText; private boolean setTargetPointerToClashedOpponent; public DoIfClashWonEffect(Effect effect) { this(effect, false, null); } public DoIfClashWonEffect(Effect effect, boolean setTargetPointerToClashedOpponent, String chooseUseText) { super(Outcome.Benefit); this.executingEffect = effect; this.chooseUseText = chooseUseText; this.setTargetPointerToClashedOpponent = setTargetPointerToClashedOpponent; } public DoIfClashWonEffect(final DoIfClashWonEffect effect) { super(effect); this.executingEffect = effect.executingEffect.copy(); this.chooseUseText = effect.chooseUseText; this.setTargetPointerToClashedOpponent = effect.setTargetPointerToClashedOpponent; } @Override public boolean apply(Game game, Ability source) { Player player = getPayingPlayer(game, source); MageObject mageObject = game.getObject(source.getSourceId()); if (player != null && mageObject != null) { String message = null; if (chooseUseText != null) { message = chooseUseText; message = CardUtil.replaceSourceName(message, mageObject.getLogName()); } if (chooseUseText == null || player.chooseUse(executingEffect.getOutcome(), message, source, game)) { if (ClashEffect.getInstance().apply(game, source)) { if (setTargetPointerToClashedOpponent) { Object opponent = getValue("clashOpponent"); if (opponent instanceof Player) { executingEffect.setTargetPointer(new FixedTarget(((Player)opponent).getId())); } } else { executingEffect.setTargetPointer(this.targetPointer); } if (executingEffect instanceof OneShotEffect) { return executingEffect.apply(game, source); } else { game.addEffect((ContinuousEffect) executingEffect, source); } } } return true; } return false; } protected Player getPayingPlayer(Game game, Ability source) { return game.getPlayer(source.getControllerId()); } @Override public String getText(Mode mode) { if (!staticText.isEmpty()) { return staticText; } return new StringBuilder("clash with an opponent. If you win, ").append(executingEffect.getText(mode)).toString(); } @Override public DoIfClashWonEffect copy() { return new DoIfClashWonEffect(this); } }
3e04f89e23e6cfd53fee53abb743cd8fd3c3643d
262
java
Java
compiler/testData/loadJava/compiledJavaCompareWithKotlin/kotlinSignature/ConstructorWithParentTypeParams.java
develar/kotlin
bf5b387580265cba01efc8fd30d1d0c0b41ac5a9
[ "Apache-2.0" ]
5
2015-08-01T10:35:57.000Z
2021-02-11T16:25:41.000Z
compiler/testData/loadJava/compiledJavaCompareWithKotlin/kotlinSignature/ConstructorWithParentTypeParams.java
develar/kotlin
bf5b387580265cba01efc8fd30d1d0c0b41ac5a9
[ "Apache-2.0" ]
null
null
null
compiler/testData/loadJava/compiledJavaCompareWithKotlin/kotlinSignature/ConstructorWithParentTypeParams.java
develar/kotlin
bf5b387580265cba01efc8fd30d1d0c0b41ac5a9
[ "Apache-2.0" ]
1
2017-04-21T06:19:05.000Z
2017-04-21T06:19:05.000Z
26.2
69
0.782443
2,081
package test; import java.util.*; import jet.runtime.typeinfo.KotlinSignature; public class ConstructorWithParentTypeParams<T> { @KotlinSignature("fun ConstructorWithParentTypeParams(first: T)") public ConstructorWithParentTypeParams(T first) { } }
3e04f8d048a412dbc6eb68f98254d4613d282a03
990
java
Java
evtp-app-jade/src/main/java/com/StartMainAgent.java
wuhuaqiang/evtp-app
ce9cda14e99872ec51712cd9f9584165953f09a0
[ "Apache-2.0" ]
null
null
null
evtp-app-jade/src/main/java/com/StartMainAgent.java
wuhuaqiang/evtp-app
ce9cda14e99872ec51712cd9f9584165953f09a0
[ "Apache-2.0" ]
null
null
null
evtp-app-jade/src/main/java/com/StartMainAgent.java
wuhuaqiang/evtp-app
ce9cda14e99872ec51712cd9f9584165953f09a0
[ "Apache-2.0" ]
null
null
null
36.666667
97
0.631313
2,082
package com; import jade.core.Profile; import jade.core.ProfileImpl; import jade.core.Runtime; import jade.wrapper.AgentContainer; import jade.wrapper.AgentController; public class StartMainAgent { public static void main(String[] asgs) { try { Runtime rt = Runtime.instance(); rt.setCloseVM(true); Profile pMain = new ProfileImpl("172.20.0.1", 8888, null); System.out.println("Launching a whole in-process platform..." + pMain); AgentContainer mc = rt.createMainContainer(pMain); // set now the default Profile to start a container ProfileImpl pContainer = new ProfileImpl("172.20.0.1", 8888, null); System.out.println("Launching the agent container ..." + pContainer); AgentController custom = mc.createNewAgent("mainAgent", "com.agent.MainAgent", null); custom.start(); } catch (Exception e) { e.printStackTrace(); } } }
3e04fa85bdafa862f535c29dcd3f3e8bfa521ddc
5,664
java
Java
pki-dao/src/main/java/com/senior/cyber/pki/dao/flyway/V001__RoleTable.java
senior-cyber/pki-master
b2207f5b08c7ba5c5740c474dc7c277ee072a5a0
[ "Apache-2.0" ]
null
null
null
pki-dao/src/main/java/com/senior/cyber/pki/dao/flyway/V001__RoleTable.java
senior-cyber/pki-master
b2207f5b08c7ba5c5740c474dc7c277ee072a5a0
[ "Apache-2.0" ]
null
null
null
pki-dao/src/main/java/com/senior/cyber/pki/dao/flyway/V001__RoleTable.java
senior-cyber/pki-master
b2207f5b08c7ba5c5740c474dc7c277ee072a5a0
[ "Apache-2.0" ]
null
null
null
60.903226
155
0.805614
2,083
package com.senior.cyber.pki.dao.flyway; import com.senior.cyber.pki.dao.LiquibaseMigration; import com.senior.cyber.pki.dao.entity.Role; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class V001__RoleTable extends LiquibaseMigration { @Override protected List<String> getXmlChecksum() { return List.of("V001__RoleTable.xml"); } @Override protected void doMigrate(NamedParameterJdbcTemplate named) throws Exception { updateLiquibase("V001__RoleTable.xml"); Map<String, String> roles = new LinkedHashMap<>(); roles.put(Role.NAME_ROOT, Role.DESCRIPTION_ROOT); roles.put(Role.NAME_Page_MyCertificateBrowse, Role.DESCRIPTION_Page_MyCertificateBrowse); roles.put(Role.NAME_Page_MyCertificateBrowse_IssueNewCertificate_Action, Role.DESCRIPTION_Page_MyCertificateBrowse_IssueNewCertificate_Action); roles.put(Role.NAME_Page_MyCertificateBrowse_Copy_Action, Role.DESCRIPTION_Page_MyCertificateBrowse_Copy_Action); roles.put(Role.NAME_Page_MyCertificateBrowse_Revoke_Action, Role.DESCRIPTION_Page_MyCertificateBrowse_Revoke_Action); roles.put(Role.NAME_Page_MyCertificateBrowse_Download_Action, Role.DESCRIPTION_Page_MyCertificateBrowse_Download_Action); roles.put(Role.NAME_Page_MyCertificateGenerate, Role.DESCRIPTION_Page_MyCertificateGenerate); roles.put(Role.NAME_Page_MyCertificateGenerate_Issue_Action, Role.DESCRIPTION_Page_MyCertificateGenerate_Issue_Action); roles.put(Role.NAME_Page_MyCertificateRevoke, Role.DESCRIPTION_Page_MyCertificateRevoke); roles.put(Role.NAME_Page_MyCertificateRevoke_Revoke_Action, Role.DESCRIPTION_Page_MyCertificateRevoke_Revoke_Action); roles.put(Role.NAME_Page_MyIntermediateBrowse, Role.DESCRIPTION_Page_MyIntermediateBrowse); roles.put(Role.NAME_Page_MyIntermediateBrowse_IssueNewIntermediate_Action, Role.DESCRIPTION_Page_MyIntermediateBrowse_IssueNewIntermediate_Action); roles.put(Role.NAME_Page_MyIntermediateBrowse_Copy_Action, Role.DESCRIPTION_Page_MyIntermediateBrowse_Copy_Action); roles.put(Role.NAME_Page_MyIntermediateBrowse_Download_Action, Role.DESCRIPTION_Page_MyIntermediateBrowse_Download_Action); roles.put(Role.NAME_Page_MyIntermediateBrowse_Revoke_Action, Role.DESCRIPTION_Page_MyIntermediateBrowse_Revoke_Action); roles.put(Role.NAME_Page_MyIntermediateGenerate, Role.DESCRIPTION_Page_MyIntermediateGenerate); roles.put(Role.NAME_Page_MyIntermediateGenerate_Issue_Action, Role.DESCRIPTION_Page_MyIntermediateGenerate_Issue_Action); roles.put(Role.NAME_Page_CsrSubmit, Role.DESCRIPTION_Page_CsrGenerate); roles.put(Role.NAME_Page_CsrGenerate, Role.DESCRIPTION_Page_CsrSubmit); roles.put(Role.NAME_Page_MyIntermediateRevoke, Role.DESCRIPTION_Page_MyIntermediateRevoke); roles.put(Role.NAME_Page_MyIntermediateRevoke_Revoke_Action, Role.DESCRIPTION_Page_MyIntermediateRevoke_Revoke_Action); roles.put(Role.NAME_Page_MyRootBrowse, Role.DESCRIPTION_Page_MyRootBrowse); roles.put(Role.NAME_Page_MyRootBrowse_IssueNewRoot_Action, Role.DESCRIPTION_Page_MyRootBrowse_IssueNewRoot_Action); roles.put(Role.NAME_Page_MyRootBrowse_Copy_Action, Role.DESCRIPTION_Page_MyRootBrowse_Copy_Action); roles.put(Role.NAME_Page_MyRootBrowse_Download_Action, Role.DESCRIPTION_Page_MyRootBrowse_Download_Action); roles.put(Role.NAME_Page_MyRootBrowse_Revoke_Action, Role.DESCRIPTION_Page_MyRootBrowse_Revoke_Action); roles.put(Role.NAME_Page_MyRootGenerate, Role.DESCRIPTION_Page_MyRootGenerate); roles.put(Role.NAME_Page_MyRootGenerate_Issue_Action, Role.DESCRIPTION_Page_MyRootGenerate_Issue_Action); roles.put(Role.NAME_Page_MyRootRevoke, Role.DESCRIPTION_Page_MyRootRevoke); roles.put(Role.NAME_Page_MyRootRevoke_Revoke_Action, Role.DESCRIPTION_Page_MyRootRevoke_Revoke_Action); roles.put(Role.NAME_Page_MyProfile, Role.DESCRIPTION_Page_MyProfile); roles.put(Role.NAME_Page_MyKey, Role.DESCRIPTION_Page_MyKey); roles.put(Role.NAME_Page_MyKey_Create_Action, Role.DESCRIPTION_Page_MyKey_Create_Action); roles.put(Role.NAME_Page_MyKey_Delete_Action, Role.DESCRIPTION_Page_MyKey_Delete_Action); roles.put(Role.NAME_Page_MyKey_ShowSecret_Action, Role.DESCRIPTION_Page_MyKey_ShowSecret_Action); roles.put(Role.NAME_Page_SessionBrowse, Role.DESCRIPTION_Page_SessionBrowse); roles.put(Role.NAME_Page_SessionBrowse_Revoke_Action, Role.DESCRIPTION_Page_SessionBrowse_Revoke_Action); roles.put(Role.NAME_Page_RoleBrowse, Role.DESCRIPTION_Page_RoleBrowse); roles.put(Role.NAME_Page_GroupBrowse, Role.DESCRIPTION_Page_GroupBrowse); roles.put(Role.NAME_Page_GroupModify, Role.DESCRIPTION_Page_GroupModify); roles.put(Role.NAME_Page_UserBrowse, Role.DESCRIPTION_Page_UserBrowse); roles.put(Role.NAME_Page_UserModify, Role.DESCRIPTION_Page_UserModify); roles.put(Role.NAME_Page_UserSwitch, Role.DESCRIPTION_Page_UserSwitch); roles.put(Role.NAME_Page_UserExit, Role.DESCRIPTION_Page_UserExit); String insert = "INSERT INTO tbl_role(name, description, enabled) VALUES(:name, :description, true)"; for (Map.Entry<String, String> role : roles.entrySet()) { Map<String, Object> params = new HashMap<>(); params.put("name", role.getKey()); params.put("description", role.getValue()); named.update(insert, params); } } }
3e04fb978864f57767def4987028b0ad7f701347
1,704
java
Java
src/main/java/com/project/MTmess/Service/MessageServiceImpl.java
ThomasBerinde/MTmess
d1420558aed005af271d9270dd75896969a6587f
[ "MIT" ]
null
null
null
src/main/java/com/project/MTmess/Service/MessageServiceImpl.java
ThomasBerinde/MTmess
d1420558aed005af271d9270dd75896969a6587f
[ "MIT" ]
null
null
null
src/main/java/com/project/MTmess/Service/MessageServiceImpl.java
ThomasBerinde/MTmess
d1420558aed005af271d9270dd75896969a6587f
[ "MIT" ]
null
null
null
37.866667
138
0.772887
2,084
package com.project.MTmess.Service; import com.project.MTmess.Exception.InvalidMessageException; import com.project.MTmess.Model.MessageEntity; import com.project.MTmess.Repository.MessageRepository; import com.project.MTmess.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; @Service public class MessageServiceImpl implements MessageService { @Autowired private MessageRepository messageRepository; @Override public MessageEntity saveMessage(MessageEntity message) throws InvalidMessageException { // Check if sender and receiver are existing users, using the API + Spring RestTemplate String url = "http://localhost:8080/friendship/find?user1=+ " + message.getSender() + "&user2=" + message.getReceiver(); RestTemplate restTemplate = new RestTemplate(); String req = restTemplate.getForObject(url, String.class); if ( req == null ) throw new InvalidMessageException("Sender and receiver are not friends..."); return messageRepository.save(message); } @Override public List<MessageEntity> findAllBySenderOrReceiver(String sender, String receiver) { return messageRepository.findAllBySenderOrReceiver(sender, receiver); } @Override public List<MessageEntity> findAllBySenderAndReceiverOrReceiverAndSender(String user11, String user12, String user21, String user22) { return messageRepository.findAllBySenderAndReceiverOrReceiverAndSender(user11, user12, user21, user22); } }
3e04fcac8ac099e3965c49e3e474506ca4793cb1
576
java
Java
router/src/main/java/com/chenenyu/router/RouteInterceptor.java
ZhouLiang0000/Router-master
699e1b021318a9d067100966e4afa3e4be763d66
[ "Apache-2.0" ]
null
null
null
router/src/main/java/com/chenenyu/router/RouteInterceptor.java
ZhouLiang0000/Router-master
699e1b021318a9d067100966e4afa3e4be763d66
[ "Apache-2.0" ]
null
null
null
router/src/main/java/com/chenenyu/router/RouteInterceptor.java
ZhouLiang0000/Router-master
699e1b021318a9d067100966e4afa3e4be763d66
[ "Apache-2.0" ]
null
null
null
25.043478
82
0.708333
2,085
package com.chenenyu.router; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; /** * Interceptor before route. * <p> * Created by Cheney on 2016/12/20. */ public interface RouteInterceptor { /** * @param context Context * @param uri Uri * @param extras Bundle * @return True if you want to intercept this route, false otherwise. */ boolean intercept(Context context, @NonNull Uri uri, @Nullable Bundle extras); }
3e04fd1b37828fa9e6f624e85d3aa20320f4c950
1,685
java
Java
backend/src/main/java/com/softwear/webapp5/data/ProductView.java
CodeURJC-DAW-2021-22/webapp5
52ead25e58ce4fa10b790092b194980d64877ebf
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/com/softwear/webapp5/data/ProductView.java
CodeURJC-DAW-2021-22/webapp5
52ead25e58ce4fa10b790092b194980d64877ebf
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/com/softwear/webapp5/data/ProductView.java
CodeURJC-DAW-2021-22/webapp5
52ead25e58ce4fa10b790092b194980d64877ebf
[ "Apache-2.0" ]
null
null
null
20.059524
105
0.693769
2,086
package com.softwear.webapp5.data; import java.util.ArrayList; import java.util.List; import com.softwear.webapp5.model.Product; public class ProductView { private Long id; private String name; private String description; private double price; private long stock; private ProductSize size; private List<String> images; public ProductView(Product p) { this.id = p.getId(); this.name = p.getName(); this.description = p.getDescription(); this.price = p.getPrice(); this.stock = p.getStock(); this.size = p.getSize(); this.images = p.getImages(); } public ProductView(Long id, String name, String description, double price, long stock, ProductSize size, ArrayList<String> images) { this.id = id; this.name = name; this.description = description; this.price = price; this.stock = stock; this.size = size; this.images = images; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public long getStock() { return stock; } public void setStock(long stock) { this.stock = stock; } public ProductSize getSize() { return size; } public void setSize(ProductSize size) { this.size = size; } public List<String> getImages() { return images; } public void setImages(ArrayList<String> images) { this.images = images; } }
3e04fd4f5ee272b8b06c63389beb7890b997d9a3
2,466
java
Java
app/src/main/java/zzu/zhaoxuezhao/com/oneday/ui/activity/ConstellationActivity.java
aotuzhao/OneDay
2dffd34731fa0b5966368628e1a3769cf82eb248
[ "Apache-2.0" ]
null
null
null
app/src/main/java/zzu/zhaoxuezhao/com/oneday/ui/activity/ConstellationActivity.java
aotuzhao/OneDay
2dffd34731fa0b5966368628e1a3769cf82eb248
[ "Apache-2.0" ]
null
null
null
app/src/main/java/zzu/zhaoxuezhao/com/oneday/ui/activity/ConstellationActivity.java
aotuzhao/OneDay
2dffd34731fa0b5966368628e1a3769cf82eb248
[ "Apache-2.0" ]
null
null
null
28.022727
74
0.645174
2,087
package zzu.zhaoxuezhao.com.oneday.ui.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import zzu.zhaoxuezhao.com.oneday.R; public class ConstellationActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_constellation); } public void getBaiyang(View view) { getInfo("baiyang", 1); Toast.makeText(this,"白羊座",Toast.LENGTH_SHORT).show(); } public void getJinniu(View view) { getInfo("jinniu", 2); Toast.makeText(this,"金牛座",Toast.LENGTH_SHORT).show(); } public void getShuangzi(View view) { getInfo("shuangzi", 3); Toast.makeText(this,"双子座",Toast.LENGTH_SHORT).show(); } public void getJuxie(View view) { getInfo("juxie", 4); Toast.makeText(this,"巨蟹座",Toast.LENGTH_SHORT).show(); } public void getShizi(View view) { getInfo("shizi", 5); Toast.makeText(this,"狮子座",Toast.LENGTH_SHORT).show(); } public void getChunv(View view) { getInfo("chunv", 6); Toast.makeText(this,"处女座",Toast.LENGTH_SHORT).show(); } public void getTiancheng(View view) { getInfo("tiancheng", 7); Toast.makeText(this,"天秤座",Toast.LENGTH_SHORT).show(); } public void getTianxie(View view) { getInfo("tianxie", 8); Toast.makeText(this,"天蝎座",Toast.LENGTH_SHORT).show(); } public void getSheshou(View view) { getInfo("sheshou", 9); Toast.makeText(this,"射手座",Toast.LENGTH_SHORT).show(); } public void getMojie(View view) { getInfo("mojie", 10); Toast.makeText(this,"摩羯座",Toast.LENGTH_SHORT).show(); } public void getShuiping(View view) { getInfo("shuiping", 11); Toast.makeText(this,"水瓶座",Toast.LENGTH_SHORT).show(); } public void getShuangyu(View view) { getInfo("shuangyu", 12); Toast.makeText(this,"双鱼座",Toast.LENGTH_SHORT).show(); } public void getInfo(String star, int image) { Intent intent = new Intent(this, ConstellationInfoActivity.class); intent.putExtra("star", star); intent.putExtra("image", image); startActivity(intent); } }
3e04fe661173ab81b05e5e79aa7c57307542f13e
3,286
java
Java
lucene-3.0-src/src/main/java/org/apache/lucene/search/Scorer.java
lihongjie/solr-tutorial
5441337081841b9d912e4cd30a5073dbdbeb0df9
[ "Apache-2.0" ]
1
2020-02-12T10:05:34.000Z
2020-02-12T10:05:34.000Z
lucene-3.0-src/src/main/java/org/apache/lucene/search/Scorer.java
lihongjie/solr-tutorial
5441337081841b9d912e4cd30a5073dbdbeb0df9
[ "Apache-2.0" ]
7
2020-03-04T21:45:38.000Z
2021-12-09T19:59:55.000Z
lucene-3.0-src/src/main/java/org/apache/lucene/search/Scorer.java
lihongjie/solr-tutorial
5441337081841b9d912e4cd30a5073dbdbeb0df9
[ "Apache-2.0" ]
null
null
null
33.530612
92
0.69933
2,088
package org.apache.lucene.search; /** * 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. */ import java.io.IOException; /** * Expert: Common scoring functionality for different types of queries. * * <p> * A <code>Scorer</code> iterates over documents matching a * query in increasing order of doc Id. * </p> * <p> * Document scores are computed using a given <code>Similarity</code> * implementation. * </p> * * <p><b>NOTE</b>: The values Float.Nan, * Float.NEGATIVE_INFINITY and Float.POSITIVE_INFINITY are * not valid scores. Certain collectors (eg {@link * TopScoreDocCollector}) will not properly collect hits * with these scores. */ public abstract class Scorer extends DocIdSetIterator { private Similarity similarity; /** Constructs a Scorer. * @param similarity The <code>Similarity</code> implementation used by this scorer. */ protected Scorer(Similarity similarity) { this.similarity = similarity; } /** Returns the Similarity implementation used by this scorer. */ public Similarity getSimilarity() { return this.similarity; } /** Scores and collects all matching documents. * @param collector The collector to which all matching documents are passed. */ public void score(Collector collector) throws IOException { collector.setScorer(this); int doc; while ((doc = nextDoc()) != NO_MORE_DOCS) { collector.collect(doc); } } /** * Expert: Collects matching documents in a range. Hook for optimization. * Note, <code>firstDocID</code> is added to ensure that {@link #nextDoc()} * was called before this method. * * @param collector * The collector to which all matching documents are passed. * @param max * Do not score documents past this. * @param firstDocID * The first document ID (ensures {@link #nextDoc()} is called before * this method. * @return true if more matching documents may remain. */ protected boolean score(Collector collector, int max, int firstDocID) throws IOException { collector.setScorer(this); int doc = firstDocID; while (doc < max) { collector.collect(doc); doc = nextDoc(); } return doc != NO_MORE_DOCS; } /** Returns the score of the current document matching the query. * Initially invalid, until {@link #nextDoc()} or {@link #advance(int)} * is called the first time, or when called from within * {@link Collector#collect}. */ public abstract float score() throws IOException; }
3e04fe88dcfca355e6a073cf5bc5d0b327ab665d
38,525
java
Java
core/src/main/java/org/axonframework/config/EventHandlingConfiguration.java
szymek22/AxonFramework
6faa2aa9bdd589104a9af536b1da2ed5afdcb474
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/axonframework/config/EventHandlingConfiguration.java
szymek22/AxonFramework
6faa2aa9bdd589104a9af536b1da2ed5afdcb474
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/axonframework/config/EventHandlingConfiguration.java
szymek22/AxonFramework
6faa2aa9bdd589104a9af536b1da2ed5afdcb474
[ "Apache-2.0" ]
null
null
null
55.511527
174
0.667411
2,089
/* * Copyright (c) 2010-2018. Axon Framework * 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.axonframework.config; import org.axonframework.common.annotation.AnnotationUtils; import org.axonframework.common.transaction.NoTransactionManager; import org.axonframework.common.transaction.TransactionManager; import org.axonframework.eventhandling.*; import org.axonframework.eventhandling.async.SequencingPolicy; import org.axonframework.eventhandling.async.SequentialPerAggregatePolicy; import org.axonframework.eventhandling.tokenstore.TokenStore; import org.axonframework.eventhandling.tokenstore.inmemory.InMemoryTokenStore; import org.axonframework.messaging.Message; import org.axonframework.messaging.MessageHandlerInterceptor; import org.axonframework.messaging.StreamableMessageSource; import org.axonframework.messaging.SubscribableMessageSource; import org.axonframework.messaging.interceptors.CorrelationDataInterceptor; import org.axonframework.messaging.unitofwork.RollbackConfigurationType; import org.axonframework.monitoring.MessageMonitor; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import static java.util.Comparator.comparing; /** * Module Configuration implementation that defines an Event Handling component. Typically, such a configuration * consists of a number of Event Handlers and one or more Event Processors that define the transactional semantics of * the processing. Each Event Handler is assigned to one Event Processor. */ public class EventHandlingConfiguration implements ModuleConfiguration { private final List<Component<Object>> eventHandlers = new ArrayList<>(); private final List<BiFunction<Configuration, String, MessageHandlerInterceptor<? super EventMessage<?>>>> defaultHandlerInterceptors = new ArrayList<>(); private final Map<String, List<Function<Configuration, MessageHandlerInterceptor<? super EventMessage<?>>>>> handlerInterceptors = new HashMap<>(); private final Map<String, EventProcessorBuilder> eventProcessors = new HashMap<>(); private final List<ProcessorSelector> selectors = new ArrayList<>(); private final List<EventProcessor> initializedProcessors = new ArrayList<>(); private final Map<String, Function<Configuration, ListenerInvocationErrorHandler>> listenerInvocationErrorHandlers = new HashMap<>(); private final Map<String, MessageMonitorFactory> messageMonitorFactories = new HashMap<>(); private final Map<String, Function<Configuration, ErrorHandler>> errorHandlers = new HashMap<>(); private final Map<String, Function<Configuration, TokenStore>> tokenStore = new HashMap<>(); private EventProcessorBuilder defaultEventProcessorBuilder = this::defaultEventProcessor; // Set up the default selector that determines the processing group by inspecting the @ProcessingGroup annotation; // if no annotation is present, the package name is used private Function<Object, String> fallback = (o) -> o.getClass().getPackage().getName(); private final ProcessorSelector defaultSelector = new ProcessorSelector( Integer.MIN_VALUE, o -> { Class<?> handlerType = o.getClass(); Optional<Map<String, Object>> annAttr = AnnotationUtils.findAnnotationAttributes(handlerType, ProcessingGroup.class); return Optional.of(annAttr.map(attr -> (String) attr.get("processingGroup")) .orElse(fallback.apply(o))); }); private Configuration config; private final Component<ListenerInvocationErrorHandler> defaultListenerInvocationErrorHandler = new Component<>( () -> config, "listenerInvocationErrorHandler", c -> c.getComponent(ListenerInvocationErrorHandler.class, LoggingErrorHandler::new) ); private final Component<ErrorHandler> defaultErrorHandler = new Component<>( () -> config, "errorHandler", c -> c.getComponent(ErrorHandler.class, PropagatingErrorHandler::instance) ); /** * Creates a default configuration for an Event Handling module that creates a {@link SubscribingEventProcessor} * instance for all Event Handlers that have the same Processing Group name. The Processing Group name is determined * by inspecting the {@link ProcessingGroup} annotation; if no annotation is present, the package name is used as * the Processing Group name. This default behavior can be overridden in the instance returned. * <p> * At a minimum, the Event Handler beans need to be registered before this component is useful. */ public EventHandlingConfiguration() { } private SubscribingEventProcessor defaultEventProcessor(Configuration conf, String name, List<?> eh) { return subscribingEventProcessor(conf, name, eh, Configuration::eventBus); } private SubscribingEventProcessor subscribingEventProcessor(Configuration conf, String name, List<?> eh, Function<Configuration, SubscribableMessageSource<? extends EventMessage<?>>> messageSource) { return new SubscribingEventProcessor(name, new SimpleEventHandlerInvoker( eh, conf.parameterResolverFactory(), getListenerInvocationErrorHandler(conf, name) ), messageSource.apply(conf), DirectEventProcessingStrategy.INSTANCE, getErrorHandler(conf, name), getMessageMonitor(conf, SubscribingEventProcessor.class, name)); } /** * Returns the list of Message Handler Interceptors registered for the given {@code processorName}. * * @param configuration The main configuration * @param processorName The name of the processor to retrieve interceptors for * @return a list of Interceptors * * @see EventHandlingConfiguration#registerHandlerInterceptor(BiFunction) * @see EventHandlingConfiguration#registerHandlerInterceptor(String, Function) */ public List<MessageHandlerInterceptor<? super EventMessage<?>>> interceptorsFor(Configuration configuration, String processorName) { List<MessageHandlerInterceptor<? super EventMessage<?>>> interceptors = new ArrayList<>(); defaultHandlerInterceptors.stream() .map(f -> f.apply(configuration, processorName)) .filter(Objects::nonNull) .forEach(interceptors::add); handlerInterceptors.getOrDefault(processorName, Collections.emptyList()) .stream() .map(f -> f.apply(configuration)) .filter(Objects::nonNull) .forEach(interceptors::add); interceptors.add(new CorrelationDataInterceptor<>(configuration.correlationDataProviders())); return interceptors; } /** * Configure the use of Tracking Event Processors, instead of the default Subscribing ones. Tracking processors * work in their own thread(s), making processing asynchronous from the publication process. * <p> * The processor will use the {@link TokenStore} implementation provided in the global Configuration, and will * default to an {@link InMemoryTokenStore} when no Token Store was defined. Note that it is not recommended to use * the in-memory TokenStore in a production environment. * <p> * The processors will use the a {@link TrackingEventProcessorConfiguration} registered with the configuration, or * otherwise to a single threaded configuration (which means the processor will run in a single Thread and a batch * size of 1). * * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration usingTrackingProcessors() { return usingTrackingProcessors(c -> c.getComponent(TrackingEventProcessorConfiguration.class, TrackingEventProcessorConfiguration::forSingleThreadedProcessing), c -> new SequentialPerAggregatePolicy()); } /** * Configure the use of Tracking Event Processors, instead of the default Subscribing ones. Tracking processors * work in their own thread(s), making processing asynchronous from the publication process. * <p> * The processor will use the {@link TokenStore} implementation provided in the global Configuration, and will * default to an {@link InMemoryTokenStore} when no Token Store was defined. Note that it is not recommended to use * the in-memory TokenStore in a production environment. * * @param config The configuration for the processors to use * @param sequencingPolicy The policy for processing events sequentially * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration usingTrackingProcessors( Function<Configuration, TrackingEventProcessorConfiguration> config, Function<Configuration, SequencingPolicy<? super EventMessage<?>>> sequencingPolicy) { return registerEventProcessorFactory( (conf, name, handlers) -> buildTrackingEventProcessor(conf, name, handlers, config, Configuration::eventBus, sequencingPolicy)); } /** * Register a TrackingProcessor using default configuration for the given {@code name}. Unlike * {@link #usingTrackingProcessors()}, this method will not default all processors to tracking, but instead only * use tracking for event handler that have been assigned to the processor with given {@code name}. * <p> * Events will be read from the EventBus (or EventStore) registered with the main configuration * * @param name The name of the processor * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("UnusedReturnValue") public EventHandlingConfiguration registerTrackingProcessor(String name) { return registerTrackingProcessor(name, Configuration::eventBus); } /** * Registers a TrackingProcessor using the given {@code source} to read messages from. * * @param name The name of the TrackingProcessor * @param source The source of messages for this processor * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("unchecked") public EventHandlingConfiguration registerTrackingProcessor(String name, Function<Configuration, StreamableMessageSource<TrackedEventMessage<?>>> source) { return registerTrackingProcessor( name, source, c -> c.getComponent(TrackingEventProcessorConfiguration.class, TrackingEventProcessorConfiguration::forSingleThreadedProcessing), c -> c.getComponent(SequencingPolicy.class, SequentialPerAggregatePolicy::new) ); } /** * Registers a TrackingProcessor with the given {@code name}, reading from the Event Bus (or Store) from the main * configuration and using the given {@code processorConfiguration}. The given {@code sequencingPolicy} defines * the policy for events that need to be executed sequentially. * * @param name The name of the Tracking Processor * @param processorConfiguration The configuration for the processor * @param sequencingPolicy The sequencing policy to apply when processing events in parallel * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerTrackingProcessor(String name, Function<Configuration, TrackingEventProcessorConfiguration> processorConfiguration, Function<Configuration, SequencingPolicy<? super EventMessage<?>>> sequencingPolicy) { return registerTrackingProcessor(name, Configuration::eventBus, processorConfiguration, sequencingPolicy); } /** * Registers a TrackingProcessor with the given {@code name}, reading from the given {@code source} and using the * given {@code processorConfiguration}. The given {@code sequencingPolicy} defines the policy for events that need * to be executed sequentially. * * @param name The name of the Tracking Processor * @param source The source to read Events from * @param processorConfiguration The configuration for the processor * @param sequencingPolicy The sequencing policy to apply when processing events in parallel * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerTrackingProcessor(String name, Function<Configuration, StreamableMessageSource<TrackedEventMessage<?>>> source, Function<Configuration, TrackingEventProcessorConfiguration> processorConfiguration, Function<Configuration, SequencingPolicy<? super EventMessage<?>>> sequencingPolicy) { return registerEventProcessor(name, (conf, n, handlers) -> buildTrackingEventProcessor(conf, name, handlers, processorConfiguration, source, sequencingPolicy)); } private EventProcessor buildTrackingEventProcessor(Configuration conf, String name, List<?> handlers, Function<Configuration, TrackingEventProcessorConfiguration> config, Function<Configuration, StreamableMessageSource<TrackedEventMessage<?>>> source, Function<Configuration, SequencingPolicy<? super EventMessage<?>>> sequencingPolicy) { return new TrackingEventProcessor(name, new SimpleEventHandlerInvoker(handlers, conf.parameterResolverFactory(), getListenerInvocationErrorHandler(conf, name), sequencingPolicy.apply(conf)), source.apply(conf), tokenStore.getOrDefault( name, c -> c.getComponent(TokenStore.class, InMemoryTokenStore::new) ).apply(conf), conf.getComponent(TransactionManager.class, NoTransactionManager::instance), getMessageMonitor(conf, EventProcessor.class, name), RollbackConfigurationType.ANY_THROWABLE, getErrorHandler(conf, name), config.apply(conf)); } private ListenerInvocationErrorHandler getListenerInvocationErrorHandler(Configuration config, String componentName) { return listenerInvocationErrorHandlers.containsKey(componentName) ? listenerInvocationErrorHandlers.get(componentName).apply(config) : defaultListenerInvocationErrorHandler.get(); } private MessageMonitor<? super Message<?>> getMessageMonitor(Configuration configuration, Class<?> componentType, String componentName) { if (messageMonitorFactories.containsKey(componentName)) { return messageMonitorFactories.get(componentName).create(configuration, componentType, componentName); } else { return configuration.messageMonitor(componentType, componentName); } } private ErrorHandler getErrorHandler(Configuration config, String componentName) { return errorHandlers.containsKey(componentName) ? errorHandlers.get(componentName).apply(config) : defaultErrorHandler.get(); } /** * Allows for more fine-grained definition of the Event Processor to use for each group of Event Listeners. The * given builder is expected to create a fully initialized Event Processor implementation based on the name and * list of event handler beans. The builder also received the global configuration instance, from which it can * retrieve components. * <p> * Note that the processor must be initialized, but shouldn't be started yet. The processor's * {@link EventProcessor#start()} method is invoked when the global configuration is started. * * @param eventProcessorBuilder The builder function for the Event Processor * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerEventProcessorFactory(EventProcessorBuilder eventProcessorBuilder) { this.defaultEventProcessorBuilder = eventProcessorBuilder; return this; } /** * Defines the Event Processor builder for an Event Processor with the given {@code name}. Event Processors * registered using this method have priority over those defined in * {@link #registerEventProcessorFactory(EventProcessorBuilder)}. * <p> * The given builder is expected to create a fully initialized Event Processor implementation based on the name and * list of event handler beans. The builder also received the global configuration instance, from which it can * retrieve components. * <p> * Note that the processor must be initialized, but shouldn't be started yet. The processor's * {@link EventProcessor#start()} method is invoked when the global configuration is started. * * @param name The name of the Event Processor for which to use this builder * @param eventProcessorBuilder The builder function for the Event Processor * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerEventProcessor(String name, EventProcessorBuilder eventProcessorBuilder) { eventProcessors.put(name, eventProcessorBuilder); return this; } /** * Register the given {@code interceptorBuilder} to build an Message Handling Interceptor for the Event Processor * with given {@code processorName}. * <p> * The {@code interceptorBuilder} may return {@code null}, in which case the return value is ignored. * <p> * Note that a CorrelationDataInterceptor is registered by default. To change correlation data attached to messages, * see {@link Configurer#configureCorrelationDataProviders(Function)}. * * @param processorName The name of the processor to register the interceptor on * @param interceptorBuilder The function providing the interceptor to register, or {@code null} * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerHandlerInterceptor(String processorName, Function<Configuration, MessageHandlerInterceptor<? super EventMessage<?>>> interceptorBuilder) { handlerInterceptors .computeIfAbsent(processorName, k -> new ArrayList<>()) .add(interceptorBuilder); return this; } /** * Register the given {@code interceptorBuilder} to build an Message Handling Interceptor for Event Processors * created in this configuration. * <p> * The {@code interceptorBuilder} is invoked once for each processor created, and may return {@code null}, in which * case the return value is ignored. * <p> * Note that a CorrelationDataInterceptor is registered by default. To change correlation data attached to messages, * see {@link Configurer#configureCorrelationDataProviders(Function)}. * * @param interceptorBuilder The builder function that provides an interceptor for each available processor * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerHandlerInterceptor( BiFunction<Configuration, String, MessageHandlerInterceptor<? super EventMessage<?>>> interceptorBuilder) { defaultHandlerInterceptors.add(interceptorBuilder); return this; } /** * Registers the Event Processor name to assign Event Handler beans to when no other, more explicit, rule matches * and no {@link ProcessingGroup} annotation is found. * * @param name The Event Processor name to assign Event Handlers to * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration byDefaultAssignTo(String name) { return byDefaultAssignTo((object) -> name); } /** * Registers a function that defines the Event Processor name to assign Event Handler beans to when no other, more * explicit, rule matches and no {@link ProcessingGroup} annotation is found. * * @param assignmentFunction The function that returns a Processor Name for each Event Handler bean * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("UnusedReturnValue") public EventHandlingConfiguration byDefaultAssignTo(Function<Object, String> assignmentFunction) { fallback = assignmentFunction; return this; } /** * Configures a rule to assign Event Handler beans that match the given {@code criteria} to the Event Processor * with given {@code name}, with neutral priority (value 0). * <p> * Note that, when beans match multiple criteria for different processors with equal priority, the outcome is * undefined. * * @param name The name of the Event Processor to assign matching Event Handlers to * @param criteria The criteria for Event Handler to match * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("UnusedReturnValue") public EventHandlingConfiguration assignHandlersMatching(String name, Predicate<Object> criteria) { return assignHandlersMatching(name, 0, criteria); } /** * Configures a rule to assign Event Handler beans that match the given {@code criteria} to the Event Processor * with given {@code name}, with given {@code priority}. Rules with higher value of {@code priority} take precedence * over those with a lower value. * <p> * Note that, when beans match multiple criteria for different processors with equal priority, the outcome is * undefined. * * @param name The name of the Event Processor to assign matching Event Handlers to * @param priority The priority for this rule * @param criteria The criteria for Event Handler to match * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration assignHandlersMatching(String name, int priority, Predicate<Object> criteria) { selectors.add(new ProcessorSelector(name, priority, criteria)); return this; } /** * Register an Event Handler Bean with this configuration. The builder function receives the global Configuration * and is expected to return a fully initialized Event Handler bean, which is to be assigned to an Event Processor * using configured rules. * * @param eventHandlerBuilder The builder function for the Event Handler bean * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerEventHandler(Function<Configuration, Object> eventHandlerBuilder) { eventHandlers.add(new Component<>(() -> config, "eventHandler", eventHandlerBuilder)); return this; } @Override public void initialize(Configuration config) { selectors.sort(comparing(ProcessorSelector::getPriority).reversed()); this.config = config; Map<String, List<Object>> assignments = new HashMap<>(); eventHandlers.stream().map(Component::get).forEach(handler -> { String processor = selectors.stream().map(s -> s.select(handler)).filter(Optional::isPresent).map(Optional::get) .findFirst() .orElse(defaultSelector.select(handler).orElseThrow(IllegalStateException::new)); assignments.computeIfAbsent(processor, k -> new ArrayList<>()).add(handler); }); assignments.forEach((name, handlers) -> { EventProcessor eventProcessor = eventProcessors.getOrDefault(name, defaultEventProcessorBuilder) .createEventProcessor(config, name, handlers); interceptorsFor(config, name).forEach(eventProcessor::registerInterceptor); initializedProcessors.add(eventProcessor); }); } @Override public void start() { initializedProcessors.forEach(EventProcessor::start); } @Override public void shutdown() { initializedProcessors.forEach(EventProcessor::shutDown); } /** * Register a subscribing processor with given {@code name} that subscribes to the Event Bus. * * @param name The name of the Event Processor * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("UnusedReturnValue") public EventHandlingConfiguration registerSubscribingEventProcessor(String name) { return registerEventProcessor( name, (conf, n, eh) -> subscribingEventProcessor(conf, n, eh, Configuration::eventBus)); } /** * Register a subscribing processor with given {@code name} that subscribes to the given {@code messageSource}. * This allows the use of standard Subscribing Processors that listen to another source than the Event Bus. * * @param name The name of the Event Processor * @param messageSource The source the processor should read from * @return this EventHandlingConfiguration instance for further configuration */ @SuppressWarnings("UnusedReturnValue") public EventHandlingConfiguration registerSubscribingEventProcessor( String name, Function<Configuration, SubscribableMessageSource<? extends EventMessage<?>>> messageSource) { return registerEventProcessor( name, (c, n, eh) -> subscribingEventProcessor(c, n, eh, messageSource)); } /** * Register the TokenStore to use for a processor of given {@code name}. * <p> * If no explicit TokenStore implementation is available for a Processor, it is taken from the main Configuration. * <p> * Note that this configuration is ignored if the processor with given name isn't a Tracking Processor. * * @param name The name of the processor to configure the token store for * @param tokenStore The function providing the TokenStore based on a given Configuration * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration registerTokenStore(String name, Function<Configuration, TokenStore> tokenStore) { this.tokenStore.put(name, tokenStore); return this; } /** * Returns a list of Event Processors that have been initialized. Note that an empty list may be returned if this * configuration hasn't been {@link #initialize(Configuration) initialized} yet. * * @return a read-only list of processors initialized in this configuration. */ public List<EventProcessor> getProcessors() { return Collections.unmodifiableList(initializedProcessors); } /** * Returns the Event Processor with the given {@code name}, if present. This method also returns an unresolved * optional if the Processor was configured, but it hasn't been assigned any Event Handlers. * * @param name The name of the processor to return * @return an Optional referencing the processor, if present. */ public <T extends EventProcessor> Optional<T> getProcessor(String name) { //noinspection unchecked return (Optional<T>) initializedProcessors.stream().filter(p -> name.equals(p.getName())).findAny(); } /** * Returns the Event Processor with the given {@code name}, if present and of the given {@code expectedType}. This * method also returns an empty optional if the Processor was configured, but it hasn't been assigned any Event * Handlers. * * @param name The name of the processor to return * @param expectedType The type of processor expected * @param <T> The type of processor expected * @return an Optional referencing the processor, if present and of expected type. */ public <T extends EventProcessor> Optional<T> getProcessor(String name, Class<T> expectedType) { return getProcessor(name).filter(expectedType::isInstance).map(expectedType::cast); } /** * Configures the default {@link org.axonframework.eventhandling.ListenerInvocationErrorHandler} for any * {@link org.axonframework.eventhandling.EventProcessor}. This can be overridden per EventProcessor by calling the * {@link EventHandlingConfiguration#configureListenerInvocationErrorHandler(String, Function)} function. * * @param listenerInvocationErrorHandlerBuilder The {@link org.axonframework.eventhandling.ListenerInvocationErrorHandler} * to use for the {@link org.axonframework.eventhandling.EventProcessor} * with the given {@code name} * @return this {@link EventHandlingConfiguration} instance for further configuration */ public EventHandlingConfiguration configureListenerInvocationErrorHandler( Function<Configuration, ListenerInvocationErrorHandler> listenerInvocationErrorHandlerBuilder) { defaultListenerInvocationErrorHandler.update(listenerInvocationErrorHandlerBuilder); return this; } /** * Configures a {@link org.axonframework.eventhandling.ListenerInvocationErrorHandler} for the * {@link org.axonframework.eventhandling.EventProcessor} of the given {@code name}. This overrides the default * ListenerInvocationErrorHandler configured through the {@link org.axonframework.config.Configurer}. * * @param name The name of the event processor * @param listenerInvocationErrorHandlerBuilder The {@link org.axonframework.eventhandling.ListenerInvocationErrorHandler} * to use for the {@link org.axonframework.eventhandling.EventProcessor} * with the given {@code name} * @return this {@link EventHandlingConfiguration} instance for further configuration */ public EventHandlingConfiguration configureListenerInvocationErrorHandler(String name, Function<Configuration, ListenerInvocationErrorHandler> listenerInvocationErrorHandlerBuilder) { listenerInvocationErrorHandlers.put(name, listenerInvocationErrorHandlerBuilder); return this; } /** * Configures the builder function to create the Message Monitor for the {@link EventProcessor} of the given name. * This overrides any Message Monitor configured through {@link Configurer}. * * @param name The name of the event processor * @param messageMonitorBuilder The builder function to use * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration configureMessageMonitor(String name, Function<Configuration, MessageMonitor<Message<?>>> messageMonitorBuilder) { return configureMessageMonitor( name, (configuration, componentType, componentName) -> messageMonitorBuilder.apply(configuration) ); } /** * Configures the factory to create the Message Monitor for the {@link EventProcessor} of the given name. This * overrides any Message Monitor configured through {@link Configurer}. * * @param name The name of the event processor * @param messageMonitorFactory The factory to use * @return this EventHandlingConfiguration instance for further configuration */ public EventHandlingConfiguration configureMessageMonitor(String name, MessageMonitorFactory messageMonitorFactory) { messageMonitorFactories.put(name, messageMonitorFactory); return this; } /** * Configures the default {@link org.axonframework.eventhandling.ErrorHandler} for any * {@link org.axonframework.eventhandling.EventProcessor}. This can be overridden per EventProcessor by calling the * {@link EventHandlingConfiguration#configureErrorHandler(String, Function)} function. * * @param errorHandlerBuilder The {@link org.axonframework.eventhandling.ErrorHandler} to use for the * {@link org.axonframework.eventhandling.EventProcessor} with the given {@code name} * @return this {@link EventHandlingConfiguration} instance for further configuration */ public EventHandlingConfiguration configureErrorHandler(Function<Configuration, ErrorHandler> errorHandlerBuilder) { defaultErrorHandler.update(errorHandlerBuilder); return this; } /** * Configures a {@link org.axonframework.eventhandling.ErrorHandler} for the * {@link org.axonframework.eventhandling.EventProcessor} of the given {@code name}. This * overrides the default ErrorHandler configured through the {@link org.axonframework.config.Configurer}. * * @param name The name of the event processor * @param errorHandlerBuilder The {@link org.axonframework.eventhandling.ErrorHandler} to use for the * {@link org.axonframework.eventhandling.EventProcessor} with the given {@code name} * @return this {@link EventHandlingConfiguration} instance for further configuration */ public EventHandlingConfiguration configureErrorHandler(String name, Function<Configuration, ErrorHandler> errorHandlerBuilder) { errorHandlers.put(name, errorHandlerBuilder); return this; } /** * Interface describing a Builder function for Event Processors. * * @see #createEventProcessor(Configuration, String, List) */ @FunctionalInterface public interface EventProcessorBuilder { /** * Builder function for an Event Processor. * * @param configuration The global configuration the implementation may use to obtain dependencies * @param name The name of the Event Processor to create * @param eventHandlers The Event Handler beans assigned to this processor * @return a fully initialized Event Processor */ EventProcessor createEventProcessor(Configuration configuration, String name, List<?> eventHandlers); } private static class ProcessorSelector { private final int priority; private final Function<Object, Optional<String>> function; private ProcessorSelector(int priority, Function<Object, Optional<String>> selectorFunction) { this.priority = priority; this.function = selectorFunction; } private ProcessorSelector(String name, int priority, Predicate<Object> criteria) { this(priority, handler -> { if (criteria.test(handler)) { return Optional.of(name); } return Optional.empty(); }); } public Optional<String> select(Object handler) { return function.apply(handler); } public int getPriority() { return priority; } } }
3e04ff1a7bc62cdb30cd4850dd939c6393e6c645
1,240
java
Java
src/main/java/org/flathub/api/service/ApiService.java
jgarciao/flathub-store-backend
da80c7bc96c9d7f6cb30723d7e1cf2e413a0a766
[ "Apache-2.0" ]
12
2018-04-14T02:13:57.000Z
2020-09-08T02:38:24.000Z
src/main/java/org/flathub/api/service/ApiService.java
jgarciao/flathub-store-backend
da80c7bc96c9d7f6cb30723d7e1cf2e413a0a766
[ "Apache-2.0" ]
18
2018-04-12T17:30:01.000Z
2021-04-05T15:13:12.000Z
src/main/java/org/flathub/api/service/ApiService.java
jgarciao/flathub-store-backend
da80c7bc96c9d7f6cb30723d7e1cf2e413a0a766
[ "Apache-2.0" ]
7
2018-12-13T03:50:09.000Z
2020-10-02T10:26:38.000Z
21.754386
97
0.762097
2,090
package org.flathub.api.service; import java.util.List; import com.rometools.rome.feed.rss.Channel; import com.rometools.rome.io.FeedException; import org.flathub.api.model.*; /** * Created by jorge on 24/03/17. */ public interface ApiService { /** Categories */ void updateCategory(Category category); Category findCategoryByName(String categoryName); /** Apps */ void updateApp(App app); List<App> findAllApps(); List<App> findAllAppsByCategoryName(String categoryName); List<App> findAllAppsByCollectionName(String collectionName); App findAppByFlatpakAppId(String flatpakAppId); /** App Releases */ void updateAppRelease(AppRelease appRelease); List<AppRelease> findAppReleaseByAppAndArch(App app, Arch arch); AppRelease findLastAppReleaseByAppAndArch(App app, Arch x8664); AppRelease findOneAppReleaseByAppAndArchAndOstreeCommitHash(App app, Arch arch, String commit); /** Repos */ void updateFlatpakRepo(FlatpakRepo repo); FlatpakRepo findRepoByName(String name); /** Screenshots */ void updateScreenshot(Screenshot screenshot); void deleteScrenshotsByApp(App app); /** RSS Feeds */ String getRssFeedByCollectionName(String collectionName) throws FeedException; }
3e04ffdb733a443e9691d9f76f4cb7bf0b0173fe
2,563
java
Java
web/rest-ui/src/main/java/org/artifactory/ui/rest/model/artifacts/browse/treebrowser/tabs/general/VirtualRemoteFolderGeneralArtifactInfo.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
3
2016-01-21T11:49:08.000Z
2018-12-11T21:02:11.000Z
web/rest-ui/src/main/java/org/artifactory/ui/rest/model/artifacts/browse/treebrowser/tabs/general/VirtualRemoteFolderGeneralArtifactInfo.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
null
null
null
web/rest-ui/src/main/java/org/artifactory/ui/rest/model/artifacts/browse/treebrowser/tabs/general/VirtualRemoteFolderGeneralArtifactInfo.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
5
2015-12-08T10:22:21.000Z
2021-06-15T16:14:00.000Z
36.614286
117
0.725322
2,091
package org.artifactory.ui.rest.model.artifacts.browse.treebrowser.tabs.general; import org.artifactory.api.config.CentralConfigService; import org.artifactory.api.context.ContextHelper; import org.artifactory.api.repo.BaseBrowsableItem; import org.artifactory.api.repo.RepositoryService; import org.artifactory.api.repo.VirtualBrowsableItem; import org.artifactory.api.security.AuthorizationService; import org.artifactory.repo.InternalRepoPathFactory; import org.artifactory.repo.RepoPath; import org.artifactory.rest.common.util.JsonUtil; import org.artifactory.ui.rest.model.artifacts.browse.treebrowser.tabs.BaseArtifactInfo; import org.artifactory.ui.rest.model.artifacts.browse.treebrowser.tabs.general.info.BaseInfo; import org.artifactory.ui.rest.model.artifacts.browse.treebrowser.tabs.general.info.FolderInfo; /** * @author Chen Keinan */ public class VirtualRemoteFolderGeneralArtifactInfo extends BaseArtifactInfo { private BaseInfo info; public VirtualRemoteFolderGeneralArtifactInfo() { } public VirtualRemoteFolderGeneralArtifactInfo(String name) { super(name); } public void populateGeneralData(BaseBrowsableItem item) { BaseInfo baseInfo; if (item instanceof VirtualBrowsableItem || item.isRemote()) { baseInfo = populateVirtualRemoteFolderInfo(item); this.info = baseInfo; } else { // get local or cached repo key String repoKey = item.getRepoKey(); RepositoryService repositoryService = ContextHelper.get().getRepositoryService(); FolderInfo folderInfo = new FolderInfo(); CentralConfigService centralConfig = ContextHelper.get().getCentralConfig(); AuthorizationService authService = ContextHelper.get().getAuthorizationService(); RepoPath repoPath = InternalRepoPathFactory.create(repoKey, item.getRelativePath()); folderInfo.populateFolderInfo(repositoryService, repoPath, centralConfig, authService.currentUsername()); this.info = folderInfo; } } /*** * @param item * @return */ private BaseInfo populateVirtualRemoteFolderInfo(BaseBrowsableItem item) { FolderInfo repoInfo = new FolderInfo(); repoInfo.populateVirtualRemoteFolderInfo(item); return repoInfo; } public BaseInfo getInfo() { return info; } public void setInfo(BaseInfo info) { this.info = info; } public String toString() { return JsonUtil.jsonToString(this); } }
3e050045decea8be90d390fea230b9d3c0613668
1,895
java
Java
src/me/dokollari/course/manager/Verify.java
rdok/online-classes
0d603b8f524b31e0f60ccaf462cd5cefcc7c477a
[ "MIT" ]
1
2017-04-30T12:01:17.000Z
2017-04-30T12:01:17.000Z
src/me/dokollari/course/manager/Verify.java
rdok/online-classes
0d603b8f524b31e0f60ccaf462cd5cefcc7c477a
[ "MIT" ]
null
null
null
src/me/dokollari/course/manager/Verify.java
rdok/online-classes
0d603b8f524b31e0f60ccaf462cd5cefcc7c477a
[ "MIT" ]
null
null
null
41.195652
87
0.642744
2,092
/******************************************************************************* * The MIT License * * Copyright (c) 2014 Rizart Dokollari. * * 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 me.dokollari.course.manager; public class Verify { public static final String NAME_REQ = "Only letters of length 1-45 are acceptable"; public static final String ID_REQ = "ID can consist of integers only"; public static void checkName(String name) throws Exception { if (!name.matches("[a-zA-z]{1,45}")) { throw new Exception(NAME_REQ); } } public static void checkID(String name) throws Exception { if (!name.matches("[0-9]+")) { throw new Exception(ID_REQ); } } }
3e0500530bac956998abce7471b58823fbfdc437
7,903
java
Java
rapid-common/src/main/java/com/chy/rapid/common/util/JSONUtil.java
Korben-CHY/rapid-demo
563489dd2221cc319ce9c585d6dd088048a29072
[ "Apache-2.0" ]
null
null
null
rapid-common/src/main/java/com/chy/rapid/common/util/JSONUtil.java
Korben-CHY/rapid-demo
563489dd2221cc319ce9c585d6dd088048a29072
[ "Apache-2.0" ]
null
null
null
rapid-common/src/main/java/com/chy/rapid/common/util/JSONUtil.java
Korben-CHY/rapid-demo
563489dd2221cc319ce9c585d6dd088048a29072
[ "Apache-2.0" ]
null
null
null
37.813397
142
0.648361
2,093
package com.chy.rapid.common.util; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.chy.rapid.common.constants.BasicConst; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.List; import java.util.Optional; public class JSONUtil { public static final String CODE = "code"; public static final String STATUS = "status"; public static final String DATA = "data"; public static final String MESSAGE = "message"; private static final ObjectMapper mapper = new ObjectMapper(); private static final JsonFactory jasonFactory = mapper.getFactory(); static { // 序列化时候,只序列化非空字段 // mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setDateFormat(new SimpleDateFormat(BasicConst.DATE_FORMAT)); // 当反序列化出现未定义字段时候,不出现错误 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // dubbo泛化调用去除class字段 mapper.addMixIn(Object.class, ExcludeFilter.class); mapper.setFilterProvider(new SimpleFilterProvider().addFilter("excludeFilter", SimpleBeanPropertyFilter.serializeAllExcept("class"))); } public static String toJSONString(Object obj) { try { return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException("object format to json error:" + obj, e); } } public static void outputToWriter(Writer out, Object value) { try { mapper.writeValue(out, value); } catch (Exception e) { throw new RuntimeException("output to writer error:" + value, e); } } /* * JsonNode反转为bean的时候,bean必须有缺省的构造函数,不然json直接用clz.getConstructor时候,无法找到默认构造 */ public static <T> T parse(JsonNode body, Class<T> clz) { try { return mapper.readValue(body.traverse(), clz); } catch (Exception e) { throw new RuntimeException("json node parse to object [" + clz + "] error:" + body, e); } } public static <T> T parse(String str, Class<T> clz) { try { return mapper.readValue(str == null ? "{}" : str, clz); } catch (Exception e) { throw new RuntimeException("json parse to object [" + clz + "] error:" + str, e); } } public static <T> T parse(Optional<String> json, Class<T> clz) { return json.map((str) -> parse(str, clz)).orElse(null); } public static <T> T parse(String str, TypeReference<T> tr) { try { return mapper.readValue(str, tr); } catch (Exception e) { throw new RuntimeException("json parse to object [" + tr + "] error:" + str, e); } } public static <T> T parse(JsonNode body, JavaType javaType) { try { return mapper.readValue(body.traverse(), javaType); } catch (Exception e) { throw new RuntimeException("json parse to object [" + body + "] error:" + body, e); } } public static <T> T parse(String str, JavaType javaType) { try { return mapper.readValue(str, javaType); } catch (Exception e) { throw new RuntimeException("json parse to object [" + str + "] error:" + str, e); } } public static <T> List<T> parseToList(String json, Class<T> clz){ return parse(json,getCollectionType(List.class,clz)); } public static JsonNode tree(String json) { try { return mapper.readTree(json); } catch (Exception e) { throw new RuntimeException("object format to json error:" + json, e); } } @SuppressWarnings("serial") public static String serializeAllExcept(Object obj, String... filterFields) { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); FilterProvider filters = new SimpleFilterProvider().addFilter(obj.getClass().getName(), SimpleBeanPropertyFilter.serializeAllExcept(filterFields)); mapper.setFilterProvider(filters).setAnnotationIntrospector(new JacksonAnnotationIntrospector() { @Override public Object findFilterId(Annotated ac) { return ac.getName(); } }); return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException("object format to json error:" + obj, e); } } @SuppressWarnings("serial") public static String filterOutAllExcept(Object obj, String... filterFields) { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); FilterProvider filters = new SimpleFilterProvider().addFilter(obj.getClass().getName(), SimpleBeanPropertyFilter.filterOutAllExcept(filterFields)); mapper.setFilterProvider(filters).setAnnotationIntrospector(new JacksonAnnotationIntrospector() { @Override public Object findFilterId(Annotated ac) { return ac.getName(); } }); return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException("object format to json error:" + obj, e); } } public static String parseOneField(String str, String fieldName) { try { JsonParser jsonParser = jasonFactory.createParser(str); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { // get the current token String fieldname = jsonParser.getCurrentName(); if (fieldName.equals(fieldname)) { // move to next token jsonParser.nextToken(); return jsonParser.getText(); } } } catch (Exception e) { throw new RuntimeException("object format to json error:", e); } return null; } public static ObjectNode createObjectNode() { return mapper.createObjectNode(); } public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } public static <T> T convertValue(Object fromValue, Class<T> toValueType) { return mapper.convertValue(fromValue, toValueType); } @JsonFilter("excludeFilter") public static class ExcludeFilter { } }
3e050064ceef8a659d763484068b8563c499a7e7
950
java
Java
src/test/java/com/github/dozedoff/commonj/filefilter/ArchiveFilterTest.java
dozedoff/commonj
f8d3c16147f6335c939f6452e1f3a180af1c0d09
[ "MIT" ]
1
2016-10-18T01:13:45.000Z
2016-10-18T01:13:45.000Z
src/test/java/com/github/dozedoff/commonj/filefilter/ArchiveFilterTest.java
dozedoff/commonj
f8d3c16147f6335c939f6452e1f3a180af1c0d09
[ "MIT" ]
5
2015-01-25T16:57:52.000Z
2017-05-19T15:06:22.000Z
src/test/java/com/github/dozedoff/commonj/filefilter/ArchiveFilterTest.java
dozedoff/commonj
f8d3c16147f6335c939f6452e1f3a180af1c0d09
[ "MIT" ]
null
null
null
22.093023
65
0.697895
2,094
/* * The MIT License (MIT) * Copyright (c) 2022 Nicholas Wright * http://opensource.org/licenses/MIT */ package com.github.dozedoff.commonj.filefilter; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Before; import org.junit.Test; public class ArchiveFilterTest { private ArchiveFilter af; @Before public void setUp() { af = new ArchiveFilter(); } private File createTempFile(String suffix) throws IOException { File file = Files.createTempFile("", suffix).toFile(); return file; } @Test public void test7zArchive() throws IOException { Path file = createTempFile("test.7z").toPath(); assertTrue(af.accept(file)); } @Test public void testZipArchive() throws IOException { Path file = createTempFile("test.zip").toPath(); assertTrue(af.accept(file)); } }
3e0501be2128fb749e4bf909ca899ce38db1b284
1,796
java
Java
src/api/main/org/phema/workbench/api/resources/ohdsi/cohortdefinition/CohortDefinitionRequest.java
PheMA/phema-workbench-api
38c1806f3637c0be768ccfd2fd27c91339a106f4
[ "Apache-2.0" ]
1
2018-11-22T10:35:32.000Z
2018-11-22T10:35:32.000Z
src/api/main/org/phema/workbench/api/resources/ohdsi/cohortdefinition/CohortDefinitionRequest.java
PheMA/phex
38c1806f3637c0be768ccfd2fd27c91339a106f4
[ "Apache-2.0" ]
14
2018-11-29T19:46:50.000Z
2020-03-31T02:50:43.000Z
src/api/main/org/phema/workbench/api/resources/ohdsi/cohortdefinition/CohortDefinitionRequest.java
PheMA/phema-workbench-api
38c1806f3637c0be768ccfd2fd27c91339a106f4
[ "Apache-2.0" ]
1
2018-12-13T13:31:39.000Z
2018-12-13T13:31:39.000Z
18.708333
84
0.673163
2,095
package org.phema.workbench.api.resources.ohdsi.cohortdefinition; import org.codehaus.jackson.annotate.JsonProperty; public class CohortDefinitionRequest { public CohortDefinitionRequest() { } /** * CQL code to execute */ @JsonProperty("code") private String code; /** * The name of the phenotype */ @JsonProperty("name") private String name; /** * The base URL of the OMOP server (WebAPI) * ex., http://omop.test/WebAPI/ */ @JsonProperty("omopServerUrl") private String omopServerUrl; /** * The OMOP data source that queries should be run against */ @JsonProperty("source") private String source; /** * The target database dialect (e.g., pgsql) that should be used when generating a * SQL representation of a phenotype */ @JsonProperty("targetDialect") private String targetDialect; /** * A String representation of a JSON FHIR Bundle. */ @JsonProperty("bundle") private String bundle; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOmopServerUrl() { return omopServerUrl; } public void setOmopServerUrl(String omopServerUrl) { this.omopServerUrl = omopServerUrl; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getTargetDialect() { return targetDialect; } public void setTargetDialect(String targetDialect) { this.targetDialect = targetDialect; } public String getBundle() { return bundle; } public void setBundle(String bundle) { this.bundle = bundle; } }
3e050226bc53d288fcb40b292a67cb1e1392a181
32,049
java
Java
moduleBusinessLayerWS/src/be/naturalsciences/bmdc/ears/ontology/gui/AsConceptNode.java
naturalsciences/ears
f74bb08e7e20f68df09eca90856bdab07eaa7db1
[ "BSD-3-Clause" ]
null
null
null
moduleBusinessLayerWS/src/be/naturalsciences/bmdc/ears/ontology/gui/AsConceptNode.java
naturalsciences/ears
f74bb08e7e20f68df09eca90856bdab07eaa7db1
[ "BSD-3-Clause" ]
2
2021-08-02T17:15:31.000Z
2021-08-19T07:17:54.000Z
moduleBusinessLayerWS/src/be/naturalsciences/bmdc/ears/ontology/gui/AsConceptNode.java
naturalsciences/ears
f74bb08e7e20f68df09eca90856bdab07eaa7db1
[ "BSD-3-Clause" ]
1
2019-04-24T12:11:48.000Z
2019-04-24T12:11:48.000Z
42.903614
194
0.597523
2,096
package be.naturalsciences.bmdc.ears.ontology.gui; import be.naturalsciences.bmdc.ears.entities.CurrentVessel; import be.naturalsciences.bmdc.ears.ontology.Individuals; import be.naturalsciences.bmdc.ears.ontology.entities.FakeConcept; import be.naturalsciences.bmdc.ears.ontology.entities.Tool; import be.naturalsciences.bmdc.ears.ontology.entities.ToolCategory; import be.naturalsciences.bmdc.ears.ontology.entities.Vessel; import be.naturalsciences.bmdc.ears.utils.Message; import be.naturalsciences.bmdc.ears.utils.Messaging; import be.naturalsciences.bmdc.ontology.AsConceptEvent; import be.naturalsciences.bmdc.ontology.AsConceptEventListener; import be.naturalsciences.bmdc.ontology.ConceptHierarchy; import be.naturalsciences.bmdc.ontology.EarsException; import be.naturalsciences.bmdc.ontology.IAsConceptFactory; import be.naturalsciences.bmdc.ontology.IIndividuals; import be.naturalsciences.bmdc.ontology.IOntologyModel; import be.naturalsciences.bmdc.ontology.entities.AsConcept; import be.naturalsciences.bmdc.ontology.entities.EarsTermLabel; import be.naturalsciences.bmdc.ontology.entities.IAction; import be.naturalsciences.bmdc.ontology.entities.IEarsTerm; import be.naturalsciences.bmdc.ontology.entities.IProcess; import be.naturalsciences.bmdc.ontology.entities.IProperty; import be.naturalsciences.bmdc.ontology.entities.ITool; import be.naturalsciences.bmdc.ontology.entities.IToolCategory; import be.naturalsciences.bmdc.ontology.entities.Term; import gnu.trove.set.hash.THashSet; import java.awt.Image; import java.awt.datatransfer.Transferable; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import javax.swing.Action; import org.netbeans.core.multiview.MultiViewTopComponent; import org.openide.ErrorManager; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.NodeEvent; import org.openide.nodes.NodeListener; import org.openide.nodes.NodeMemberEvent; import org.openide.nodes.NodeReorderEvent; import org.openide.nodes.PropertySupport; import org.openide.nodes.Sheet; import org.openide.util.ImageUtilities; import org.openide.util.Utilities; import org.openide.util.actions.SystemAction; import org.openide.util.datatransfer.PasteType; import org.openide.util.lookup.Lookups; import org.openide.windows.TopComponent; /** * * @author Thomas Vandenberghe */ public class AsConceptNode extends AbstractNode implements NodeListener, AsConceptEventListener { public static String CHILD_ADDED = "CHILD_ADDED"; @Override public void propertyChange(PropertyChangeEvent evt) { /* if ("prefLabel".equals(evt.getPropertyName())) { this.fireDisplayNameChange(null, getDisplayName()); //this.getConcept().getTermRef().getEarsTermLabel().setPrefLabel((String) evt.getNewValue()); PropertyChangeEvent evt2 = new PropertyChangeEvent(this, "prefLabel", evt.getOldValue(), evt.getNewValue()); IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.change(evt2); individuals.refresh(); }*/ } @Override public void childrenAdded(NodeMemberEvent nme) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); if (individuals != null) { individuals.add(nme); individuals.refresh(); } } @Override public void childrenRemoved(NodeMemberEvent nme) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); if (individuals != null) { individuals.remove(nme); individuals.refresh(); } } @Override public void childrenReordered(NodeReorderEvent nre) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void nodeDestroyed(NodeEvent ne) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.remove(ne); individuals.refresh(); } @Override public void nodeRenamed(AsConceptEvent ace) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.change(ace); individuals.refresh(); } @Override public void nodeAdded(AsConceptEvent ace) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.add(ace); individuals.refresh(); } @Override public void nodeDestroyed(AsConceptEvent ace) { IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.remove(ace); individuals.refresh(); } public static class ContextBehaviour { public boolean moveFromWithin; public boolean moveToOther; public boolean moveFromOther; public IAsConceptFactory factory; public PropertyChangeListener pcListener; public NodeListener nListener; private ContextBehaviour(boolean moveFromWithin, boolean moveToOther, boolean moveFromOther, PropertyChangeListener pcListener, NodeListener nListener) { this.moveFromWithin = moveFromWithin; this.moveToOther = moveToOther; this.moveFromOther = moveFromOther; this.nListener = nListener; this.pcListener = pcListener; } private ContextBehaviour(boolean moveFromWithin, boolean moveToOther, boolean moveFromOther) { this(moveFromWithin, moveToOther, moveFromOther, null, null); } } public List<PropertyChangeListener> pcListenerList; public List<NodeListener> nodeListenerList; public static final ContextBehaviour BROWSE_BEHAVIOUR = new ContextBehaviour(false, true, false, null, null); public static final ContextBehaviour EDIT_BEHAVIOUR = new ContextBehaviour(true, false, true); private AsConcept concept; public AsConceptNode parentNode; private ContextBehaviour behaviour; private AsConceptChildFactory childFactory; ConceptHierarchy ConceptHierarchy; public AsConceptChildFactory getChildFactory() { return childFactory; } public AsConcept getConcept() { return concept; } public void setConcept(AsConcept concept) { this.concept = concept; } public ContextBehaviour getBehaviour() { return behaviour; } public void addPropertyChangeListenerUseThis(PropertyChangeListener pcl) { if (this.pcListenerList == null) { this.pcListenerList = new ArrayList(); } pcListenerList.add(pcl); this.addPropertyChangeListener(pcl); } public void addNodeListenerUseThis(NodeListener nl) { if (this.nodeListenerList == null) { this.nodeListenerList = new ArrayList(); } nodeListenerList.add(nl); this.addNodeListener(nl); } public void removeNodeListeners() { this.nodeListenerList.clear(); } protected AsConceptNode(AsConceptNode parent, AsConcept obj, IOntologyModel ontModel, ContextBehaviour behaviour) { //InstanceContent ic, super(Children.create(new AsConceptChildFactory(), true), Lookups.singleton(obj)); this.parentNode = parent; this.concept = obj; this.behaviour = behaviour; this.ConceptHierarchy = new ConceptHierarchy(this.getParentsAsConcept()); this.childFactory = new AsConceptChildFactory(parent, obj, this.ConceptHierarchy, ontModel, behaviour); if (childFactory.hasChildren()) { this.setChildren(Children.create(childFactory, true)); } else { this.setChildren(Children.LEAF); } this.setValue("nodeDescription", getShortDescription()); this.setShortDescription(getShortDescription()); /* if (obj.getTermRef() != null) { EarsTermLabel label = obj.getTermRef().getEarsTermLabel(IEarsTerm.Language.en); label.addPropertyChangeListener(WeakListeners.propertyChange(this, label)); label.addPropertyChangeListener(WeakListeners.propertyChange(behaviour.pcListener, label)); }*/ this.addPropertyChangeListenerUseThis(this.behaviour.pcListener); this.addNodeListenerUseThis(this); //listen to my own changes } /** * * * Constructor for a root node * * @param ontModel * @param behaviour */ public AsConceptNode(IOntologyModel ontModel, ContextBehaviour behaviour) { super(Children.create(new AsConceptChildFactory(), true)); this.parentNode = null; this.concept = new FakeConcept("Root", "Root", "Nothing to see here", true, ontModel.getNodes()); this.behaviour = behaviour; setName("root"); this.ConceptHierarchy = new ConceptHierarchy(); this.childFactory = new AsConceptChildFactory(null, this.concept, this.ConceptHierarchy, ontModel, behaviour); this.setChildren(Children.create(childFactory, true)); this.addNodeListenerUseThis(this); //listen to my own changes } @Override public String toString() { return this.getDisplayName(); } public Collection<AsConceptNode> getParents() { Collection<AsConceptNode> ca = this.getParents(new HashSet()); ca.remove(this); return ca; } public final Collection<AsConcept> getParentsAsConcept() { Collection<AsConcept> sa = new THashSet(); Collection<AsConceptNode> ca = this.getParents(); for (AsConceptNode conceptNode : ca) { sa.add(conceptNode.getConcept()); } return sa; } private Collection<AsConceptNode> getParents(Collection l) { if (this.parentNode == null) { //if (this.getParentNode() == null) { l.add(this); } else { l.add(this); l.addAll(((AsConceptNode) this.parentNode).getParents(l)); //l.addAll(((AsConceptNode) this.getParentNode()).getParents(l)); } return l; } public static Set<Node> getAllChildren(Node thisNode) { Set<Node> nodes = new THashSet(); // ignore root -- root acts as a container Node node; if (thisNode.getChildren().getNodes().length > 0) { node = thisNode.getChildren().getNodes()[0]; } else { return nodes; } while (node != null && node.getParentNode() != null) { // print node information //System.out.println(node. + "=" + node.getNodeValue()); nodes.add(node); if (node.getChildren().getNodesCount() > 0) {//node.hasChildren() //branch node = node.getChildren().getNodes()[0]; //node = node.getFirstChild(); } else { // leaf // find the parent level Node nodeParent = node.getParentNode(); int siblings = 0; try { siblings = nodeParent.getChildren().getNodesCount() - 1; } catch (Exception e) { int a = 5; } int nodeIndex = getNodeIndex(nodeParent, node); int remainingSiblings = siblings - nodeIndex; //for (int i = 1; i < siblings; i++) { //Node nextSibling = //Arrays.asList(nodeParent.getChildren().getNodes()).remove().iterator().next(); //} while (remainingSiblings == 0 && node != thisNode) //while (node.getNextSibling() == null && node != rootNode) // use child-parent link to get to the parent level { node = node.getParentNode(); } if (nodeIndex < siblings) { try { node = nodeParent.getChildren().getNodes()[nodeIndex + 1]; //node = node.getNextSibling(); } catch (Exception e) { int a = 5; } } else { node = null; } } } return nodes; } private static int getNodeIndex(Node parentNode, Node ofNode) { int c = 0; try { c = parentNode.getChildren().getNodesCount(); } catch (Exception e) { int a = 5; } for (int i = 0; i < c; i++) { if (parentNode.getChildren().getNodes()[i].equals(ofNode)) { return i; } } return -1; } @Override public String getHtmlDisplayName() { if (this.concept instanceof IToolCategory) { return "<font color='#0B486B'>" + getDisplayName() + "</font>"; } else if (this.concept instanceof ITool) { return "<font color='#02779E'>" + getDisplayName() + "</font>"; } else if (this.concept instanceof IProcess) { return "<font color='#DC4B40'>" + getDisplayName() + "</font>"; } else if (this.concept instanceof IAction) { return "<font color='#F59E03'>" + getDisplayName() + "</font>"; } else if (this.concept instanceof IProperty) { return "<font color='#EB540A'>" + getDisplayName() + "</font>"; } else { return "<font color='#2C3539'>" + getDisplayName() + "</font>"; } } @Override public String getDisplayName() { if (isRoot()) { return "root"; } else if (concept != null && concept.getTermRef() != null) { return concept.getTermRef().getEarsTermLabel().getPrefLabel(); } else { return "root"; } } public boolean isRoot() { if (this.concept instanceof FakeConcept) { FakeConcept c = (FakeConcept) this.concept; return c.isIsRoot(); } else { return false; } } @Override public final String getShortDescription() { if (concept != null && concept.getTermRef() != null) { if (concept.getTermRef().getEarsTermLabel().getDefinition() != null) { return concept.getKind() + ": " + concept.getTermRef().getEarsTermLabel().getDefinition().replace("><", "> <"); } else { return concept.getKind(); } } return ""; } @Override public Image getIcon(int type) { if (this.concept instanceof IToolCategory) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/toolcategory.png"); //flaticon } else if (this.concept instanceof ITool) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/tool.png"); //flaticon } else if (this.concept instanceof IProcess) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/process.png"); //flaticon } else if (this.concept instanceof IAction) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/action.png"); //flaticon } else if (this.concept instanceof IProperty) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/property.png"); //flaticon } else if (this.isRoot()) { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/root.png"); //flaticon } else { return ImageUtilities.loadImage("be/naturalsciences/bmdc/ears/ontology/treeviewer/unknown.png"); //flaticon } } @Override public Image getOpenedIcon(int i) { return getIcon(i); } @Override public Action[] getActions(boolean context) { // Action a = SystemAction.get(ExpandNodeAction.class); if (this.behaviour == EDIT_BEHAVIOUR) { return new Action[]{ SystemAction.get(DeleteNodeAction.class), SystemAction.get(ExpandNodeAction.class), //SystemAction.get(CollapseNodeAction.class), SystemAction.get(CreateChildNodeAction.class), //After discussion during ODIP 2 in October 2017 in Galway it was decided to only allow creating new tools or properties. SystemAction.get(CreateEventAction.class)}; } else { return new Action[]{ SystemAction.get(ExpandNodeAction.class), //SystemAction.get(CollapseNodeAction.class), SystemAction.get(CreateEventAction.class)}; } } @Override public PasteType getDropType(Transferable t, int arg1, int arg2) { if (behaviour == AsConceptNode.EDIT_BEHAVIOUR && t instanceof AsConcept) { AsConcept transferred = AsConceptChildFactory.getTransferData(t); boolean dropPermission = AsConceptChildFactory.isDropPermitted(t, concept, transferred); if (dropPermission) { return new PasteType() { @Override public Transferable paste() throws IOException { AsConcept transferredCopy = null; boolean removePreviousBottomUpAssociations = true; TopComponent originalTopcomponent = TopComponent.getRegistry().getActivated(); AsConceptNode originalNode = originalTopcomponent.getLookup().lookup(AsConceptNode.class); try { transferredCopy = transferred.clone(new IdentityHashMap()); } catch (CloneNotSupportedException ex) { Messaging.report("Could not clone the dragged object " + transferred.getUri(), ex, this.getClass(), true); } if (originalTopcomponent instanceof MultiViewTopComponent) { //ugly hack removePreviousBottomUpAssociations = false; } if (transferredCopy != null) { if (transferredCopy instanceof ToolCategory) { ToolCategory child = (ToolCategory) transferredCopy; try { child.reduceGevsToSevs(AsConceptNode.this.behaviour.factory); } catch (EarsException ex) { throw new RuntimeException(ex); } } if (transferredCopy instanceof Tool) { Tool child = (Tool) transferredCopy; child.setToolIdentifier(null); child.setSerialNumber(null); } addAsChild(transferredCopy, removePreviousBottomUpAssociations, originalNode); //:false should be dependent on whether the donor is the same instance as the reciever. } return null; //We put nothing in the clipboard } }; } else { return null; } } else { //open the node return null; } } private void addAsChild(AsConcept newChild, boolean removePreviousBottomUpAssociations, AsConceptNode originalNode) { if (originalNode != null) { concept.addToChildren(ConceptHierarchy, newChild, removePreviousBottomUpAssociations, originalNode.ConceptHierarchy, this.behaviour.factory); } else { concept.addToChildren(ConceptHierarchy, newChild, removePreviousBottomUpAssociations, null, this.behaviour.factory); } if (concept instanceof FakeConcept && newChild instanceof ToolCategory) { childFactory.getOntModel().getNodes().getNodes().add(newChild); } if (isLeaf()) { setChildren(Children.create(childFactory, true)); } addNodeListenerUseThis(behaviour.nListener); childFactory.refresh(); } @Override public boolean canCut() { return false; } @Override public boolean canCopy() { return true; } @Override public Transferable drag() { if (this.concept instanceof ToolCategory) { ToolCategory c = (ToolCategory) this.concept; return c; } else if (this.concept instanceof Tool) { Tool c = (Tool) this.concept; return c; } else if (this.concept instanceof Vessel) { Vessel c = (Vessel) this.concept; return c; } else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Process) { be.naturalsciences.bmdc.ears.ontology.entities.Process c = (be.naturalsciences.bmdc.ears.ontology.entities.Process) this.concept; return c; } else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Action) { be.naturalsciences.bmdc.ears.ontology.entities.Action c = (be.naturalsciences.bmdc.ears.ontology.entities.Action) this.concept; return c; } else if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Property) { be.naturalsciences.bmdc.ears.ontology.entities.Property c = (be.naturalsciences.bmdc.ears.ontology.entities.Property) this.concept; return c; } else { return null; } } public void delete() { concept.delete(this.ConceptHierarchy); addNodeListenerUseThis(behaviour.nListener); fireNodeDestroyed(); /* IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.remove(concept); individuals.refresh();*/ } public void createNewChild() { AsConcept newChild = null; try { newChild = this.behaviour.factory.buildChild(concept); if (newChild != null) { /*IIndividuals individuals = childFactory.getOntModel().getIndividuals(); //TODO replaced by event individuals.add(newChild); individuals.refresh();*/ addAsChild(newChild, false, null); } } catch (EarsException ex) { Messaging.report("Could not create a child node", ex, this.getClass(), true); } } public class EarsTermRenamer { private EarsTermLabel termLabel; public EarsTermLabel getTermLabel() { return termLabel; } public void setTermLabel(EarsTermLabel termLabel) { this.termLabel = termLabel; } public EarsTermRenamer(EarsTermLabel termLabel) { this.termLabel = termLabel; } public String getPrefLabel() { return termLabel.getPrefLabel(); } public void setPrefLabel(String label) { String nameExists = Individuals.nameExists(label); if (nameExists != null) { Messaging.report(nameExists, Message.State.BAD, ClassChildren.class, true); } else { //IIndividuals individuals = childFactory.getOntModel().getIndividuals(); //individuals.remove(concept); String oldPrefLabel = this.termLabel.getPrefLabel(); this.termLabel.setPrefLabel(label); PropertyChangeEvent evt2 = new PropertyChangeEvent(AsConceptNode.this, "prefLabel", oldPrefLabel, label); AsConceptNode.this.fireDisplayNameChange(null, getDisplayName()); for (PropertyChangeListener pcl : AsConceptNode.this.pcListenerList) { pcl.propertyChange(evt2); } IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.change(evt2); individuals.refresh(); // individuals.change(concept); //individuals.refresh(); } } public String getDefinition() { return termLabel.getDefinition(); } public void setDefinition(String definition) { this.termLabel.setDefinition(definition); IIndividuals individuals = childFactory.getOntModel().getIndividuals(); individuals.refresh(); } } @Override protected Sheet createSheet() { Sheet sheet = Sheet.createDefault(); if (!(this.concept instanceof FakeConcept)) { Sheet.Set set = Sheet.createPropertiesSet(); if (this.concept != null) { IOntologyModel currentModel = childFactory.getOntModel(); Term term = this.concept.getTermRef(); if (term != null) { URI uri = term.getUri(); be.naturalsciences.bmdc.ears.ontology.entities.Property infoProperty = null; Tool infoTool = null; EarsTermLabel label = term.getEarsTermLabel(IEarsTerm.Language.en); EarsTermRenamer termRenamer = new EarsTermRenamer(label); if (this.concept instanceof be.naturalsciences.bmdc.ears.ontology.entities.Property) { infoProperty = (be.naturalsciences.bmdc.ears.ontology.entities.Property) this.concept; } if (this.concept instanceof Tool) { infoTool = (Tool) this.concept; } try { Property nameProp = null; Property altNameProp = null; Property defProp = null; Property mandatoryPropertyProp = null; Property multiplePropertyProp = null; Property serialNumberProp = null; Property toolIdentifierProp = null; CurrentVessel currentVessel = Utilities.actionsGlobalContext().lookup(CurrentVessel.class); String currentVesselCode = null; if (currentVessel != null && currentVessel.getConcept() != null) { currentVesselCode = currentVessel.getConcept().getCode(); } if (currentVesselCode != null && this.behaviour == EDIT_BEHAVIOUR && currentModel.isEditable() && concept.getTermRef().isOwnTerm(currentVesselCode)) { nameProp = new PropertySupport.Reflection(termRenamer, String.class, "getPrefLabel", "setPrefLabel"); altNameProp = new PropertySupport.Reflection(label, String.class, "altLabel"); defProp = new PropertySupport.Reflection(termRenamer, String.class, "getDefinition", "setDefinition"); if (infoProperty != null) { mandatoryPropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMultiple", "setMultiple"); multiplePropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMandatory", "setMandatory"); mandatoryPropertyProp.setName("is mandatory"); multiplePropertyProp.setName("can occur multiple times"); set.put(mandatoryPropertyProp); set.put(multiplePropertyProp); } } else { nameProp = new PropertySupport.Reflection(label, String.class, "getPrefLabel", null); altNameProp = new PropertySupport.Reflection(label, String.class, "getAltLabel", null); defProp = new PropertySupport.Reflection(label, String.class, "getDefinition", null); if (infoProperty != null) { mandatoryPropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMultiple", null); multiplePropertyProp = new PropertySupport.Reflection(infoProperty, Boolean.class, "isMandatory", null); mandatoryPropertyProp.setName("is mandatory"); multiplePropertyProp.setName("can occur multiple times"); set.put(mandatoryPropertyProp); set.put(multiplePropertyProp); } } /*if (currentVesselCode != null && this.behaviour == editBehaviour && currentModel.isEditable() && infoTool != null) { serialNumberProp = new PropertySupport.Reflection(infoTool, String.class, "getSerialNumber", "setSerialNumber"); serialNumberProp.setName("tool serial number"); toolIdentifierProp = new PropertySupport.Reflection(infoTool, String.class, "getToolIdentifier", "setToolIdentifier"); toolIdentifierProp.setName("tool identifier"); }*/ Property kindProp = new PropertySupport.Reflection(this.concept, String.class, "getKind", null); Property uriProp = new PropertySupport.Reflection(uri, String.class, "toASCIIString", null); Property urnProp = new PropertySupport.Reflection(term, String.class, "getIdentifierUrn", null); Property statusProp = new PropertySupport.Reflection(term, String.class, "getStatusName", null); Property creationDateProp = new PropertySupport.Reflection(term, Date.class, "getCreationDate", null); Property toStringProp = new PropertySupport.Reflection(this.concept, String.class, "toString", null); //Property printProp = new PropertySupport.Reflection(this.concept, String.class, "print", null); nameProp.setName("label"); altNameProp.setName("alt label"); defProp.setName("definition"); kindProp.setName("kind"); uriProp.setName("uri"); urnProp.setName("urn"); statusProp.setName("status"); creationDateProp.setName("creation date"); toStringProp.setName("internal details"); //printProp.setName("relations"); set.put(nameProp); set.put(altNameProp); set.put(defProp); set.put(kindProp); /*if (serialNumberProp != null) { set.put(serialNumberProp); } if (toolIdentifierProp != null) { set.put(toolIdentifierProp); }*/ set.put(uriProp); set.put(urnProp); set.put(statusProp); set.put(creationDateProp); set.put(toStringProp); //set.put(printProp); } catch (NoSuchMethodException ex) { ErrorManager.getDefault(); } sheet.put(set); } } } return sheet; } }
3e050235496e2e276cc14618acff3f347a39f725
1,933
java
Java
app/src/main/java/com/zmq/shopmall/fragmen/SpecialOfferFragment.java
dsh923713/MallLibrary
c3becdfed778ef1648d02405746de1149f9d5539
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zmq/shopmall/fragmen/SpecialOfferFragment.java
dsh923713/MallLibrary
c3becdfed778ef1648d02405746de1149f9d5539
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zmq/shopmall/fragmen/SpecialOfferFragment.java
dsh923713/MallLibrary
c3becdfed778ef1648d02405746de1149f9d5539
[ "Apache-2.0" ]
null
null
null
39.44898
129
0.749095
2,097
package com.zmq.shopmall.fragmen; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.ogaclejapan.smarttablayout.SmartTabLayout; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems; import com.zmq.shopmall.R; import com.zmq.shopmall.R2; import com.zmq.shopmall.base.BaseFragment; import butterknife.BindView; /** * Created by Administrator on 2017/6/13. */ public class SpecialOfferFragment extends BaseFragment { @BindView(R2.id.stl_specical) SmartTabLayout stlSpecical; @BindView(R2.id.vp_special) ViewPager vpSpecial; private FragmentPagerItemAdapter adapter; @Override protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_special_offer_library, container, false); return view; } @Override protected void initView(View view) { adapter = new FragmentPagerItemAdapter(activity.getSupportFragmentManager(), FragmentPagerItems.with(activity).add(R .string.myself, MyselfFragment.class).add(R.string.classify, ClassifyFragment.class).add(R.string.myself, MyselfFragment.class).add(R.string.classify, ClassifyFragment.class).add(R.string.myself, MyselfFragment.class) .add(R.string.classify, ClassifyFragment.class).add(R.string.myself, MyselfFragment.class).add(R.string .classify, ClassifyFragment.class).add(R.string.myself, MyselfFragment.class).add(R.string.classify, ClassifyFragment.class).create()); vpSpecial.setAdapter(adapter); stlSpecical.setViewPager(vpSpecial); } }
3e0503cd8b5ff108c79b5591cc764de9a95c37cf
694
java
Java
roncoo-education-course/roncoo-education-course-feign/src/main/java/com/roncoo/education/course/feign/vo/CourseRecommendVO.java
itzhangdd/lby-education
32a809928d0b506db4e96dc3fea57fe3c4ed938e
[ "MIT" ]
1,019
2018-12-25T01:01:04.000Z
2022-03-29T03:15:01.000Z
roncoo-education-course/roncoo-education-course-feign/src/main/java/com/roncoo/education/course/feign/vo/CourseRecommendVO.java
openokay/roncoo-education
2601f9c8f67471ecd6ddb7c227688139534a4b8e
[ "MIT" ]
8
2018-12-20T06:07:39.000Z
2022-03-10T06:39:06.000Z
roncoo-education-course/roncoo-education-course-feign/src/main/java/com/roncoo/education/course/feign/vo/CourseRecommendVO.java
openokay/roncoo-education
2601f9c8f67471ecd6ddb7c227688139534a4b8e
[ "MIT" ]
491
2018-12-18T13:54:21.000Z
2022-03-12T15:53:26.000Z
12.851852
56
0.644092
2,098
package com.roncoo.education.course.feign.vo; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; /** * 课程推荐 * * @author wujing */ @Data @Accessors(chain = true) public class CourseRecommendVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ private Long id; /** * 创建时间 */ private Date gmtCreate; /** * 修改时间 */ private Date gmtModified; /** * 状态(1:正常;0:禁用) */ private Integer statusId; /** * 排序 */ private Integer sort; /** * 分类ID */ private Long categoryId; /** * 课程ID */ private Long courseId; /** * 课程名称 */ private String courseName; }
3e05049208d4a7177d84f8926e32680a9b5b78c7
9,062
java
Java
message-builder-hl7v3-release-pcs_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/pcs_cerx_v01_r04_3/common/quqi_mt120000ca/TriggerEventBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
1
2022-03-09T12:17:41.000Z
2022-03-09T12:17:41.000Z
message-builder-hl7v3-release-pcs_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/pcs_cerx_v01_r04_3/common/quqi_mt120000ca/TriggerEventBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
message-builder-hl7v3-release-pcs_cerx_v01_r04_3/src/main/java/ca/infoway/messagebuilder/model/pcs_cerx_v01_r04_3/common/quqi_mt120000ca/TriggerEventBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
32.24911
94
0.672037
2,099
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.pcs_cerx_v01_r04_3.common.quqi_mt120000ca; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.annotation.Hl7RootType; import ca.infoway.messagebuilder.annotation.Hl7XmlMapping; import ca.infoway.messagebuilder.datatype.CV; import ca.infoway.messagebuilder.datatype.II; import ca.infoway.messagebuilder.datatype.TS; import ca.infoway.messagebuilder.datatype.impl.CVImpl; import ca.infoway.messagebuilder.datatype.impl.IIImpl; import ca.infoway.messagebuilder.datatype.impl.TSImpl; import ca.infoway.messagebuilder.datatype.lang.Identifier; import ca.infoway.messagebuilder.domainvalue.ControlActReason; import ca.infoway.messagebuilder.domainvalue.HL7TriggerEventCode; import ca.infoway.messagebuilder.model.MessagePartBean; import ca.infoway.messagebuilder.model.pcs_cerx_v01_r04_3.common.merged.QueryDefinitionBean; import ca.infoway.messagebuilder.model.pcs_cerx_v01_r04_3.common.merged.RefersToBean; import ca.infoway.messagebuilder.model.pcs_cerx_v01_r04_3.pharmacy.porx_mt980020ca.IssuesBean; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * <p>Business Name: Trigger Event</p> * * <p>Key to understanding what action a message * represents.</p> * * <p>There may be constraints on the usage of the reasonCode * attribute in the definition of the interaction or the * trigger events which are conveyed with this wrapper.</p> * * <p>Identifies the action that resulted in this message being * sent.</p> */ @Hl7PartTypeMapping({"QUQI_MT120000CA.ControlActEvent"}) @Hl7RootType public class TriggerEventBean<ACT,PL> extends MessagePartBean { private static final long serialVersionUID = 20190730L; private II id = new IIImpl(); private CV code = new CVImpl(); private TS effectiveTime = new TSImpl(); private CV reasonCode = new CVImpl(); private List<RefersToBean<ACT>> subject = new ArrayList<RefersToBean<ACT>>(); private List<IssuesBean> subjectOfDetectedIssueEvent = new ArrayList<IssuesBean>(); private QueryResponseInformationBean queryAck; private QueryDefinitionBean<PL> queryByParameter; /** * <p>Business Name: B:Event Identifier</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Used for audit purposes and therefore mandatory.</p> * * <p>A unique identifier for this particular event assigned by * the system in which the event occurred.</p> */ @Hl7XmlMapping({"id"}) public Identifier getId() { return this.id.getValue(); } /** * <p>Business Name: B:Event Identifier</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.id</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>Used for audit purposes and therefore mandatory.</p> * * <p>A unique identifier for this particular event assigned by * the system in which the event occurred.</p> */ public void setId(Identifier id) { this.id.setValue(id); } /** * <p>Business Name: A:Event Type</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>This is mandatory because it is essential to * understanding the meaning of the event.</p> * * <p>Identifies the trigger event that occurred.</p> */ @Hl7XmlMapping({"code"}) public HL7TriggerEventCode getCode() { return (HL7TriggerEventCode) this.code.getValue(); } /** * <p>Business Name: A:Event Type</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.code</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> * * <p>This is mandatory because it is essential to * understanding the meaning of the event.</p> * * <p>Identifies the trigger event that occurred.</p> */ public void setCode(HL7TriggerEventCode code) { this.code.setValue(code); } /** * <p>Business Name: C:Event Effective Period</p> * * <p>Relationship: * QUQI_MT120000CA.ControlActEvent.effectiveTime</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> * * <p>Sometimes messages may be constructed and sent at a * significantly different time than the query was actually * processed.</p> * * <p>Indicates when the query was performed. If not specified, * the assumption is that the query was performed at the same * time the message was constructed.</p> */ @Hl7XmlMapping({"effectiveTime"}) public Date getEffectiveTime() { return this.effectiveTime.getValue(); } /** * <p>Business Name: C:Event Effective Period</p> * * <p>Relationship: * QUQI_MT120000CA.ControlActEvent.effectiveTime</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> * * <p>Sometimes messages may be constructed and sent at a * significantly different time than the query was actually * processed.</p> * * <p>Indicates when the query was performed. If not specified, * the assumption is that the query was performed at the same * time the message was constructed.</p> */ public void setEffectiveTime(Date effectiveTime) { this.effectiveTime.setValue(effectiveTime); } /** * <p>Business Name: E:Event Reason</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.reasonCode</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> * * <p>Usually used to indicate a reason why a query was * unsuccessful or was not processed.</p> * * <p>Indicates the reason for the response given</p> */ @Hl7XmlMapping({"reasonCode"}) public ControlActReason getReasonCode() { return (ControlActReason) this.reasonCode.getValue(); } /** * <p>Business Name: E:Event Reason</p> * * <p>Relationship: QUQI_MT120000CA.ControlActEvent.reasonCode</p> * * <p>Conformance/Cardinality: REQUIRED (0-1)</p> * * <p>Usually used to indicate a reason why a query was * unsuccessful or was not processed.</p> * * <p>Indicates the reason for the response given</p> */ public void setReasonCode(ControlActReason reasonCode) { this.reasonCode.setValue(reasonCode); } /** * <p>Relationship: QUQI_MT120000CA.ControlActEvent.subject</p> * * <p>Conformance/Cardinality: REQUIRED (0-999)</p> */ @Hl7XmlMapping({"subject"}) public List<RefersToBean<ACT>> getSubject() { return this.subject; } /** * <p>Relationship: QUQI_MT120000CA.Subject.detectedIssueEvent</p> * * <p>Conformance/Cardinality: REQUIRED (1)</p> */ @Hl7XmlMapping({"subjectOf/detectedIssueEvent"}) public List<IssuesBean> getSubjectOfDetectedIssueEvent() { return this.subjectOfDetectedIssueEvent; } /** * <p>Relationship: QUQI_MT120000CA.ControlActEvent.queryAck</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"queryAck"}) public QueryResponseInformationBean getQueryAck() { return this.queryAck; } /** * <p>Relationship: QUQI_MT120000CA.ControlActEvent.queryAck</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setQueryAck(QueryResponseInformationBean queryAck) { this.queryAck = queryAck; } /** * <p>Relationship: * QUQI_MT120000CA.ControlActEvent.queryByParameter</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"queryByParameter"}) public QueryDefinitionBean<PL> getQueryByParameter() { return this.queryByParameter; } /** * <p>Relationship: * QUQI_MT120000CA.ControlActEvent.queryByParameter</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setQueryByParameter(QueryDefinitionBean<PL> queryByParameter) { this.queryByParameter = queryByParameter; } }
3e0504d759636d7a2b4a97208be5c0d5a529604b
1,699
java
Java
metrics-guice/src/main/java/com/yammer/metrics/guice/ExceptionMeteredListener.java
chids/metrics
8ab9a9b8d48737b4ab3628a8c6c2452851ac1438
[ "MIT" ]
1
2016-08-26T06:37:54.000Z
2016-08-26T06:37:54.000Z
metrics-guice/src/main/java/com/yammer/metrics/guice/ExceptionMeteredListener.java
daggerrz/metrics
2889e6f539f2202cdcbd728f296729fa843153a0
[ "MIT" ]
null
null
null
metrics-guice/src/main/java/com/yammer/metrics/guice/ExceptionMeteredListener.java
daggerrz/metrics
2889e6f539f2202cdcbd728f296729fa843153a0
[ "MIT" ]
null
null
null
38.613636
142
0.713949
2,100
package com.yammer.metrics.guice; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import com.yammer.metrics.core.MetricsRegistry; import com.yammer.metrics.core.MeterMetric; import java.lang.reflect.Method; /** * A listener which adds method interceptors to methods that should be instrumented for exceptions */ public class ExceptionMeteredListener implements TypeListener { private final MetricsRegistry metricsRegistry; public ExceptionMeteredListener(MetricsRegistry metricsRegistry) { this.metricsRegistry = metricsRegistry; } @Override public <T> void hear(TypeLiteral<T> literal, TypeEncounter<T> encounter) { for (Method method : literal.getRawType().getDeclaredMethods()) { final ExceptionMetered annotation = method.getAnnotation(ExceptionMetered.class); if (annotation != null) { final String name = determineName(annotation, method); final MeterMetric meter = metricsRegistry.newMeter(literal.getRawType(), name, annotation.eventType(), annotation.rateUnit()); ExceptionMeteredInterceptor interceptor = new ExceptionMeteredInterceptor(meter, annotation.cause()); encounter.bindInterceptor(Matchers.only(method), interceptor); } } } private String determineName(final ExceptionMetered annotation, final Method method) { if (annotation.name().isEmpty()) { return method.getName() + ExceptionMetered.DEFAULT_NAME_SUFFIX; } else { return annotation.name(); } } }
3e050573a50e51c93f9227b9f4561880e80aa3ae
15,724
java
Java
com.archimatetool.editor/src/com/archimatetool/editor/preferences/GeneralPreferencePage.java
borkdominik/eGEAA
0eba4e192c794b1a0debf7d4d9e2bfa1b1a58949
[ "MIT" ]
2
2021-10-06T16:49:05.000Z
2022-02-15T08:11:05.000Z
com.archimatetool.editor/src/com/archimatetool/editor/preferences/GeneralPreferencePage.java
borkdominik/eGEAA
0eba4e192c794b1a0debf7d4d9e2bfa1b1a58949
[ "MIT" ]
null
null
null
com.archimatetool.editor/src/com/archimatetool/editor/preferences/GeneralPreferencePage.java
borkdominik/eGEAA
0eba4e192c794b1a0debf7d4d9e2bfa1b1a58949
[ "MIT" ]
1
2022-02-15T07:16:24.000Z
2022-02-15T07:16:24.000Z
41.488127
165
0.692127
2,101
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.preferences; import java.util.ArrayList; import java.util.List; import org.eclipse.e4.ui.css.swt.theme.ITheme; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; import com.archimatetool.editor.ui.ThemeUtils; import com.archimatetool.editor.utils.PlatformUtils; /** * General Preferences Page * * @author Phillip Beauvoir */ @SuppressWarnings("restriction") public class GeneralPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IPreferenceConstants { private static String HELP_ID = "com.archimatetool.help.prefsGeneral"; //$NON-NLS-1$ private Button fOpenDiagramsOnLoadButton; private Button fBackupOnSaveButton; private Spinner fMRUSizeSpinner; private ComboViewer fThemeComboViewer; private Button fShowStatusLineButton; private Button fShowUnusedElementsInModelTreeButton; private Button fAutoSearchButton; private Button fWarnOnDeleteButton; private Button fScaleImagesButton; private Button fUseLabelExpressionsButton; private ITheme fCurrentTheme; /** * Pseudo theme to set automatic light/dark on startup */ private static ITheme AUTOMATIC_THEME = new ITheme() { @Override public String getId() { return "autoTheme"; //$NON-NLS-1$ } @Override public String getLabel() { return Messages.GeneralPreferencePage_15; } }; public GeneralPreferencePage() { setPreferenceStore(Preferences.STORE); } @Override protected Control createContents(Composite parent) { // Help PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, HELP_ID); Composite client = new Composite(parent, SWT.NULL); client.setLayout(new GridLayout()); Group fileGroup = new Group(client, SWT.NULL); fileGroup.setText(Messages.GeneralPreferencePage_0); fileGroup.setLayout(new GridLayout(2, false)); fileGroup.setLayoutData(createHorizontalGridData(1)); // Automatically open views when opening a model file fOpenDiagramsOnLoadButton = new Button(fileGroup, SWT.CHECK); fOpenDiagramsOnLoadButton.setText(Messages.GeneralPreferencePage_1); fOpenDiagramsOnLoadButton.setLayoutData(createHorizontalGridData(2)); // Backup file on save fBackupOnSaveButton = new Button(fileGroup, SWT.CHECK); fBackupOnSaveButton.setText(Messages.GeneralPreferencePage_5); fBackupOnSaveButton.setLayoutData(createHorizontalGridData(2)); // Size of recently opened file list Label label = new Label(fileGroup, SWT.NULL); label.setText(Messages.GeneralPreferencePage_2); fMRUSizeSpinner = new Spinner(fileGroup, SWT.BORDER); fMRUSizeSpinner.setMinimum(3); fMRUSizeSpinner.setMaximum(15); // Appearance Group appearanceGroup = new Group(client, SWT.NULL); appearanceGroup.setText(Messages.GeneralPreferencePage_3); appearanceGroup.setLayout(new GridLayout(2, false)); appearanceGroup.setLayoutData(createHorizontalGridData(1)); // Themes label = new Label(appearanceGroup, SWT.NULL); label.setText(Messages.GeneralPreferencePage_4); fThemeComboViewer = new ComboViewer(appearanceGroup, SWT.READ_ONLY); fThemeComboViewer.getCombo().setLayoutData(createHorizontalGridData(1)); fThemeComboViewer.setContentProvider(new IStructuredContentProvider() { @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public void dispose() { } @Override public Object[] getElements(Object inputElement) { return (Object[])inputElement; } }); fThemeComboViewer.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return ((ITheme)element).getLabel(); } }); fThemeComboViewer.setComparator(new ViewerComparator()); // Show Status Line fShowStatusLineButton = new Button(appearanceGroup, SWT.CHECK); fShowStatusLineButton.setText(Messages.GeneralPreferencePage_9); fShowStatusLineButton.setLayoutData(createHorizontalGridData(2)); label = new Label(appearanceGroup, SWT.NULL); label.setText(Messages.GeneralPreferencePage_8); label.setLayoutData(createHorizontalGridData(2)); // Model Tree Group modelTreeGroup = new Group(client, SWT.NULL); modelTreeGroup.setText(Messages.GeneralPreferencePage_10); modelTreeGroup.setLayout(new GridLayout(2, false)); modelTreeGroup.setLayoutData(createHorizontalGridData(1)); fShowUnusedElementsInModelTreeButton = new Button(modelTreeGroup, SWT.CHECK); fShowUnusedElementsInModelTreeButton.setText(Messages.GeneralPreferencePage_11); fShowUnusedElementsInModelTreeButton.setLayoutData(createHorizontalGridData(2)); fAutoSearchButton = new Button(modelTreeGroup, SWT.CHECK); fAutoSearchButton.setText(Messages.GeneralPreferencePage_6); fAutoSearchButton.setLayoutData(createHorizontalGridData(2)); label = new Label(modelTreeGroup, SWT.NULL); label.setText(Messages.GeneralPreferencePage_7); label.setLayoutData(createHorizontalGridData(2)); fWarnOnDeleteButton = new Button(modelTreeGroup, SWT.CHECK); fWarnOnDeleteButton.setText(Messages.GeneralPreferencePage_16); fWarnOnDeleteButton.setLayoutData(createHorizontalGridData(2)); // Label Expressions Group expressionsGroup = new Group(client, SWT.NULL); expressionsGroup.setText(Messages.GeneralPreferencePage_17); expressionsGroup.setLayout(new GridLayout(2, false)); expressionsGroup.setLayoutData(createHorizontalGridData(1)); fUseLabelExpressionsButton = new Button(expressionsGroup, SWT.CHECK); fUseLabelExpressionsButton.setText(Messages.GeneralPreferencePage_18); fUseLabelExpressionsButton.setLayoutData(createHorizontalGridData(2)); // Other Group otherGroup = new Group(client, SWT.NULL); otherGroup.setText(Messages.GeneralPreferencePage_12); otherGroup.setLayout(new GridLayout(2, false)); otherGroup.setLayoutData(createHorizontalGridData(1)); fScaleImagesButton = new Button(otherGroup, SWT.CHECK); fScaleImagesButton.setText(Messages.GeneralPreferencePage_13); fScaleImagesButton.setLayoutData(createHorizontalGridData(2)); label = new Label(otherGroup, SWT.NULL); label.setText(Messages.GeneralPreferencePage_14); label.setLayoutData(createHorizontalGridData(2)); setValues(); fThemeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ITheme theme = (ITheme)((IStructuredSelection)fThemeComboViewer.getSelection()).getFirstElement(); setTheme(theme, false); } }); return client; } private void setValues() { setSpinnerValues(); fBackupOnSaveButton.setSelection(getPreferenceStore().getBoolean(BACKUP_ON_SAVE)); fOpenDiagramsOnLoadButton.setSelection(getPreferenceStore().getBoolean(OPEN_DIAGRAMS_ON_LOAD)); fShowStatusLineButton.setSelection(getPreferenceStore().getBoolean(SHOW_STATUS_LINE)); fShowUnusedElementsInModelTreeButton.setSelection(getPreferenceStore().getBoolean(HIGHLIGHT_UNUSED_ELEMENTS_IN_MODEL_TREE)); fAutoSearchButton.setSelection(getPreferenceStore().getBoolean(TREE_SEARCH_AUTO)); fWarnOnDeleteButton.setSelection(getPreferenceStore().getBoolean(SHOW_WARNING_ON_DELETE_FROM_TREE)); fUseLabelExpressionsButton.setSelection(getPreferenceStore().getBoolean(USE_LABEL_EXPRESSIONS_IN_ANALYSIS_TABLE)); // Themes list List<ITheme> themes = new ArrayList<ITheme>(); // Add our pseudo theme if supported if(ThemeUtils.isAutoThemeSupported()) { themes.add(AUTOMATIC_THEME); } // Get Themes for this OS for(ITheme theme : ThemeUtils.getThemeEngine().getThemes()) { if(!theme.getId().contains("linux") && !theme.getId().contains("macosx") && !theme.getId().contains("win32")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ themes.add(theme); } } fThemeComboViewer.setInput(themes.toArray()); if(ThemeUtils.isAutoThemeSupported() && getPreferenceStore().getBoolean(THEME_AUTO)) { fThemeComboViewer.setSelection(new StructuredSelection(AUTOMATIC_THEME)); } else { ITheme activeTheme = ThemeUtils.getThemeEngine().getActiveTheme(); if(activeTheme != null) { fThemeComboViewer.setSelection(new StructuredSelection(activeTheme)); } } fScaleImagesButton.setSelection(getPreferenceStore().getBoolean(SCALE_IMAGE_EXPORT)); } private void setSpinnerValues() { fMRUSizeSpinner.setSelection(getPreferenceStore().getInt(MRU_MAX)); } @Override public boolean performOk() { getPreferenceStore().setValue(BACKUP_ON_SAVE, fBackupOnSaveButton.getSelection()); getPreferenceStore().setValue(OPEN_DIAGRAMS_ON_LOAD, fOpenDiagramsOnLoadButton.getSelection()); getPreferenceStore().setValue(MRU_MAX, fMRUSizeSpinner.getSelection()); getPreferenceStore().setValue(SHOW_STATUS_LINE, fShowStatusLineButton.getSelection()); getPreferenceStore().setValue(HIGHLIGHT_UNUSED_ELEMENTS_IN_MODEL_TREE, fShowUnusedElementsInModelTreeButton.getSelection()); getPreferenceStore().setValue(TREE_SEARCH_AUTO, fAutoSearchButton.getSelection()); getPreferenceStore().setValue(SHOW_WARNING_ON_DELETE_FROM_TREE, fWarnOnDeleteButton.getSelection()); getPreferenceStore().setValue(USE_LABEL_EXPRESSIONS_IN_ANALYSIS_TABLE, fUseLabelExpressionsButton.getSelection()); ITheme theme = (ITheme)((IStructuredSelection)fThemeComboViewer.getSelection()).getFirstElement(); if(theme != null) { setTheme(theme, true); } getPreferenceStore().setValue(SCALE_IMAGE_EXPORT, fScaleImagesButton.getSelection()); return true; } @Override protected void performDefaults() { fBackupOnSaveButton.setSelection(getPreferenceStore().getDefaultBoolean(BACKUP_ON_SAVE)); fOpenDiagramsOnLoadButton.setSelection(getPreferenceStore().getDefaultBoolean(OPEN_DIAGRAMS_ON_LOAD)); fMRUSizeSpinner.setSelection(getPreferenceStore().getDefaultInt(MRU_MAX)); fShowStatusLineButton.setSelection(getPreferenceStore().getDefaultBoolean(SHOW_STATUS_LINE)); fShowUnusedElementsInModelTreeButton.setSelection(getPreferenceStore().getDefaultBoolean(HIGHLIGHT_UNUSED_ELEMENTS_IN_MODEL_TREE)); fAutoSearchButton.setSelection(getPreferenceStore().getDefaultBoolean(TREE_SEARCH_AUTO)); fWarnOnDeleteButton.setSelection(getPreferenceStore().getDefaultBoolean(SHOW_WARNING_ON_DELETE_FROM_TREE)); fUseLabelExpressionsButton.setSelection(getPreferenceStore().getDefaultBoolean(USE_LABEL_EXPRESSIONS_IN_ANALYSIS_TABLE)); if(ThemeUtils.isAutoThemeSupported() && getPreferenceStore().getDefaultBoolean(THEME_AUTO)) { setTheme(AUTOMATIC_THEME, false); fThemeComboViewer.setSelection(new StructuredSelection(AUTOMATIC_THEME)); } else { ThemeUtils.getThemeEngine().setTheme(ThemeUtils.getDefaultThemeName(), false); ITheme activeTheme = ThemeUtils.getThemeEngine().getActiveTheme(); if(activeTheme != null) { fThemeComboViewer.setSelection(new StructuredSelection(activeTheme)); } } fScaleImagesButton.setSelection(getPreferenceStore().getDefaultBoolean(SCALE_IMAGE_EXPORT)); super.performDefaults(); } @Override public boolean performCancel() { if(fCurrentTheme != ThemeUtils.getThemeEngine().getActiveTheme()) { ThemeUtils.getThemeEngine().setTheme(fCurrentTheme, false); } return super.performCancel(); } private GridData createHorizontalGridData(int span) { GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = span; return gd; } @Override public void init(IWorkbench workbench) { fCurrentTheme = ThemeUtils.getThemeEngine().getActiveTheme(); } private void setTheme(ITheme theme, boolean persist) { hideEmptyShells(true); if(theme == AUTOMATIC_THEME) { ThemeUtils.getThemeEngine().setTheme(Display.isSystemDarkTheme() ? ThemeUtils.E4_DARK_THEME_ID : ThemeUtils.E4_DEFAULT_THEME_ID, persist); } else { ThemeUtils.getThemeEngine().setTheme(theme, persist); } hideEmptyShells(false); if(persist) { if(ThemeUtils.isAutoThemeSupported()) { getPreferenceStore().setValue(THEME_AUTO, theme == AUTOMATIC_THEME); } fCurrentTheme = ThemeUtils.getThemeEngine().getActiveTheme(); } } /** * Hack for e4 bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=435915 * Changing the Appearance Theme causes any hidden Shell to momentarily appear * such as the one created by FigureUtilities.getGC(). * So find each empty Shell and set its Alpha to 0 before setting the theme and set it back to 255 * This hides the Shell and unhides it. */ private void hideEmptyShells(boolean set) { if(PlatformUtils.isWindows()) { for(Shell shell : Display.getCurrent().getShells()) { if(shell.getChildren().length == 0) { shell.setAlpha(set ? 0 : 255); } } } } }
3e0505d9643ae81c2c7b826974a1761698a8edef
7,943
java
Java
app/src/main/java/com/example/calc/MainActivity.java
zengdev/Calc
7aa93a550d2dc0d3ead2f6c23a75e68f1cf04d85
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/calc/MainActivity.java
zengdev/Calc
7aa93a550d2dc0d3ead2f6c23a75e68f1cf04d85
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/calc/MainActivity.java
zengdev/Calc
7aa93a550d2dc0d3ead2f6c23a75e68f1cf04d85
[ "Apache-2.0" ]
null
null
null
25.056782
96
0.681984
2,102
package com.example.calc; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; //import com.example.calc.Utils.LogUtil; import com.example.calc.Utils.Util; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private static final String TAG = "MainActivity"; // 控件 private static TextView calcTextView; // 计算式显示区域 private static TextView resultTextView; // 结果显示区域 // private static Button addBtn; // + // private static Button subBtn; // - // private static Button mulBtn; // × // private static Button divBtn; // ÷ // private static Button pointBtn; // 小数点 // 运算操作类型 private static final int OPERA_TYPE_NONE = 0; private static final int OPERA_TYPE_ADD = 1; private static final int OPERA_TYPE_SUB = 2; private static final int OPERA_TYPE_MUL = 3; private static final int OPERA_TYPE_DIV = 4; private static int currentOperaType; // 当前运算操作类型 // flag private static boolean isExistResult; private static boolean isOperaSuccess; // str private static StringBuilder calcStr; // 计算式 private static String operaStr; // 运算操作 // 操作数对象 private static OperaNum operaNum1; private static OperaNum operaNum2; private static OperaNum currentOperaNum; private static double result = 0; // 运算结果 class OperaNum { public boolean havePoint = false; // 是否包含小数点 public double value = 0; // 操作数double值 public StringBuilder valueStr; // 操作数 public OperaNum() { valueStr = new StringBuilder(""); init(); } public OperaNum(StringBuilder valueStr) { this.valueStr = valueStr; } public double getValue() { value = Double.valueOf(valueStr.toString()).doubleValue(); return value; } public void init() { value = 0; Util.clearStringBuilder(valueStr); havePoint = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { calcStr = new StringBuilder(""); operaNum1 = new OperaNum(); operaNum2 = new OperaNum(); calcTextView = findViewById(R.id.calc_textview); resultTextView = findViewById(R.id.result_textview); // addBtn = findViewById(R.id.btn_add); // subBtn = findViewById(R.id.btn_sub); // mulBtn = findViewById(R.id.btn_mul); // divBtn = findViewById(R.id.btn_div); // pointBtn = findViewById(R.id.btn_point); clearClick(); } private void initData() { currentOperaType = OPERA_TYPE_NONE; currentOperaNum = operaNum1; isExistResult = false; operaNum1.init(); operaNum2.init(); Util.clearStringBuilder(calcStr); operaStr = ""; } private void clearClick() { initData(); Util.clearTextView(calcTextView, resultTextView); } private void numClick(String num) { String tempNum = num; if (isExistResult) { clearClick(); } if (0 == currentOperaNum.valueStr.length() && num.equals("00")) { tempNum = "0"; } else if (currentOperaNum.valueStr.toString().equals("0")) { if (num.equals("0") || num.equals("00")) { return; } else { Util.clearStringBuilder(currentOperaNum.valueStr); calcStr.deleteCharAt(calcStr.length() - 1); } } currentOperaNum.valueStr.append(tempNum); calcStr.append(tempNum); calcTextView.setText(calcStr.toString()); } private void pointClick() { if (isExistResult || currentOperaNum.havePoint || currentOperaNum.valueStr.length() == 0) { return; } currentOperaNum.valueStr.append("."); currentOperaNum.havePoint = true; calcStr.append("."); calcTextView.setText(calcStr.toString()); } private boolean operaClick(String operaStr) { if (isExistResult || calcStr.length() == 0) { return false; }else if (calcStr.length() > 0) { String currentOperaNumLastOneStr = Util.getStringBuilderLastOneStr(currentOperaNum.valueStr); if (currentOperaNumLastOneStr.equals(".")) { Util.showTipText(getApplicationContext(), "操作数最后一位不能为小数点!"); return false; } if (currentOperaNum == operaNum2) { if (currentOperaNum.valueStr.length() == 0) { calcStr.deleteCharAt(calcStr.length() - 1); this.operaStr = operaStr; calcStr.append(operaStr); calcTextView.setText(calcStr.toString()); return true; } return false; } else { this.operaStr = operaStr; calcStr.append(operaStr); calcTextView.setText(calcStr.toString()); currentOperaNum = operaNum2; return true; } } return false; } private void delClick() { String calcLastOneStr; if (calcStr.length() > 0) { calcLastOneStr = Util.getStringBuilderLastOneStr(calcStr); } else { return; } if (isExistResult) { Util.clearTextView(resultTextView); isExistResult = false; } else if (calcLastOneStr.equals(operaStr)) { operaStr = ""; currentOperaType = OPERA_TYPE_NONE; currentOperaNum = operaNum1; } else { currentOperaNum.valueStr.deleteCharAt(currentOperaNum.valueStr.length() - 1); if (calcLastOneStr.equals(".")) { currentOperaNum.havePoint = false; } } calcStr.deleteCharAt(calcStr.length() - 1); calcTextView.setText(calcStr.toString()); } private void add() { result = operaNum1.getValue() + operaNum2.getValue(); isOperaSuccess = true; } private void sub() { result = operaNum1.getValue() - operaNum2.getValue(); isOperaSuccess = true; } private void mul() { result = operaNum1.getValue() * operaNum2.getValue(); isOperaSuccess = true; } private void div() { if (0 == operaNum2.getValue()) { // 未验证---------------------- Util.showTipText(getApplicationContext(), "除数不能为0!"); isOperaSuccess = false; } else { result = operaNum1.getValue() / operaNum2.getValue(); isOperaSuccess = true; } } private void calc() { if (isExistResult) { return; } String calcLastOneStr = Util.getStringBuilderLastOneStr(calcStr); if (calcLastOneStr.equals(".")) { Util.showTipText(getApplicationContext(), "操作数最后一位不能为小数点!"); return; } if (calcLastOneStr.equals(operaStr)) { Util.showTipText(getApplicationContext(), "请输入正确的计算式!"); return; } if (currentOperaNum == operaNum1) { result = operaNum1.getValue(); isOperaSuccess = true; } else if (OPERA_TYPE_NONE == currentOperaType) { isOperaSuccess = false; } else if (OPERA_TYPE_ADD == currentOperaType) { add(); } else if (OPERA_TYPE_SUB == currentOperaType) { sub(); } else if (OPERA_TYPE_MUL == currentOperaType) { mul(); } else if (OPERA_TYPE_DIV == currentOperaType) { div(); } if (isOperaSuccess) { showResult(); isExistResult = true; } else { Util.showTipText(getApplicationContext(), "请检查计算式是否有错!"); } } private void showResult() { calcStr.append("="); calcTextView.setText(calcStr.toString()); resultTextView.setText(Double.toString(result)); } @Override public void onClick(View view) { String btnText = ((Button)findViewById(view.getId())).getText().toString(); switch (view.getId()) { case R.id.btn_Clear: clearClick(); break; case R.id.btn_del: delClick(); break; case R.id.btn_add: if (operaClick(btnText)) { currentOperaType = OPERA_TYPE_ADD; } break; case R.id.btn_sub: if (operaClick(btnText)) { currentOperaType = OPERA_TYPE_SUB; } break; case R.id.btn_mul: if (operaClick(btnText)) { currentOperaType = OPERA_TYPE_MUL; } break; case R.id.btn_div: if (operaClick(btnText)) { currentOperaType = OPERA_TYPE_DIV; } break; case R.id.btn_equal: calc(); break; case R.id.btn_point: pointClick(); break; case R.id.btn_00: case R.id.btn_0: case R.id.btn_1: case R.id.btn_2: case R.id.btn_3: case R.id.btn_4: case R.id.btn_5: case R.id.btn_6: case R.id.btn_7: case R.id.btn_8: case R.id.btn_9: numClick(btnText); break; } } }
3e05062e411d8407fc969231449eacf31002799b
3,179
java
Java
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/core/events/EventsProperties.java
tswstarplanet/cas
c026d1a7598e02e11cd9ed248b76a7973ee67052
[ "Apache-2.0" ]
2
2019-05-23T15:45:42.000Z
2021-07-01T01:49:54.000Z
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/core/events/EventsProperties.java
tswstarplanet/cas
c026d1a7598e02e11cd9ed248b76a7973ee67052
[ "Apache-2.0" ]
3
2019-02-26T14:14:14.000Z
2019-02-26T14:24:06.000Z
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/core/events/EventsProperties.java
tswstarplanet/cas
c026d1a7598e02e11cd9ed248b76a7973ee67052
[ "Apache-2.0" ]
1
2020-10-14T04:44:19.000Z
2020-10-14T04:44:19.000Z
30.27619
93
0.715948
2,103
package org.apereo.cas.configuration.model.core.events; import org.apereo.cas.configuration.model.support.couchdb.BaseAsynchronousCouchDbProperties; import org.apereo.cas.configuration.model.support.influxdb.InfluxDbProperties; import org.apereo.cas.configuration.model.support.jpa.AbstractJpaProperties; import org.apereo.cas.configuration.model.support.mongo.SingleCollectionMongoDbProperties; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * Configuration properties class for events. * * @author Dmitriy Kopylenko * @since 5.0.0 */ @RequiresModule(name = "cas-server-core-events", automated = true) @Getter @Setter public class EventsProperties implements Serializable { private static final long serialVersionUID = 1734523424737956370L; /** * Whether geolocation should be tracked as part of collected authentication events. * This of course require's consent from the user's browser to collect stats on location. */ private boolean trackGeolocation; /** * Whether CAS should track the underlying configuration store for changes. * This depends on whether the store provides that sort of functionality. * When running in standalone mode, this typically translates to CAS monitoring * configuration files and reloading context conditionally if there are any changes. */ private boolean trackConfigurationModifications = true; /** * Track authentication events inside a database. */ private Jpa jpa = new Jpa(); /** * Track authentication events inside an influxdb database. */ private InfluxDb influxDb = new InfluxDb(); /** * Track authentication events inside a mongodb instance. */ private MongoDb mongo = new MongoDb(); /** * Track authentication events inside a couchdb instance. */ private CouchDb couchDb = new CouchDb(); @RequiresModule(name = "cas-server-support-events-jpa") @Getter @Setter public static class Jpa extends AbstractJpaProperties { private static final long serialVersionUID = 7647381223153797806L; } @RequiresModule(name = "cas-server-support-events-mongo") @Getter @Setter public static class MongoDb extends SingleCollectionMongoDbProperties { private static final long serialVersionUID = -1918436901491275547L; public MongoDb() { setCollection("MongoDbCasEventRepository"); } } @RequiresModule(name = "cas-server-support-events-influxdb") @Getter @Setter public static class InfluxDb extends InfluxDbProperties { private static final long serialVersionUID = -3918436901491275547L; public InfluxDb() { setDatabase("CasInfluxDbEvents"); } } @RequiresModule(name = "cas-server-support-events-couchdb") @Getter @Setter public static class CouchDb extends BaseAsynchronousCouchDbProperties { private static final long serialVersionUID = -1587160128953366615L; public CouchDb() { setDbName("events"); } } }
3e050638084cff8cc788f1fb9c02e69453d3c034
4,328
java
Java
src/test/java/at/ac/tuwien/student/sese2017/xp/hotelmanagement/service/ReceiptServiceTest.java
querqueq/sese-xp3-ws2017
4ad5362ac443744820f1af91c31c70784a2f6a3c
[ "MIT" ]
null
null
null
src/test/java/at/ac/tuwien/student/sese2017/xp/hotelmanagement/service/ReceiptServiceTest.java
querqueq/sese-xp3-ws2017
4ad5362ac443744820f1af91c31c70784a2f6a3c
[ "MIT" ]
40
2017-11-02T16:41:28.000Z
2017-12-19T01:16:45.000Z
src/test/java/at/ac/tuwien/student/sese2017/xp/hotelmanagement/service/ReceiptServiceTest.java
querqueq/sese-xp3-ws2017
4ad5362ac443744820f1af91c31c70784a2f6a3c
[ "MIT" ]
null
null
null
33.8125
99
0.763401
2,104
package at.ac.tuwien.student.sese2017.xp.hotelmanagement.service; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.List; import javax.transaction.Transactional; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import at.ac.tuwien.student.sese2017.xp.hotelmanagement.HotelManagementApplicationTests; import at.ac.tuwien.student.sese2017.xp.hotelmanagement.domain.data.ReceiptEntity; import at.ac.tuwien.student.sese2017.xp.hotelmanagement.domain.repository.ReceiptRepository; import at.ac.tuwien.student.sese2017.xp.hotelmanagement.domain.test.TestDataInjector; import at.ac.tuwien.student.sese2017.xp.hotelmanagement.exceptions.NotFoundException; @Transactional public class ReceiptServiceTest extends HotelManagementApplicationTests { @Autowired ReceiptService receiptService; @Autowired private ReceiptRepository receiptRepository; /** * Find all receipt on empty db */ @Test public void getAllReceipts_emptyDB() throws Exception { // Clear all receipts to enable room removal receiptRepository.deleteAll(); // Define expected result ReceiptEntity[] expectedResult = new ReceiptEntity[] {}; // Execute service function List<ReceiptEntity> allReceiptsByCriteria = receiptService.search("Non-existant"); // Check result assertNotNull("Null returned by service", allReceiptsByCriteria); assertEquals("Result size not correct", expectedResult.length, allReceiptsByCriteria.size()); assertThat("Not the right elements returned", allReceiptsByCriteria, containsInAnyOrder(expectedResult)); } /** * Tests if a NotFoundException is thrown if a non existing receipt is canceled. */ @Test(expected = NotFoundException.class) public void testCancelNonExistingReceipt() { receiptService.cancelReceipt(Long.MAX_VALUE); } /** * Tests if an existing receipt can be canceled and is not found by findById after deletion. */ @Test public void testCancelExistingReceipt() { long receiptId = TestDataInjector.RECEIPT_1.getReceiptId(); assertTrue(receiptRepository.findById(receiptId).isPresent()); receiptService.cancelReceipt(receiptId); assertFalse(receiptRepository.findById(receiptId).isPresent()); } /** * Tests if null receiptId throws an IllegalArgumentException. */ @Test(expected = IllegalArgumentException.class) public void testCancelNullReceipt() { receiptService.cancelReceipt(null); } /** * Tests if an already canceled receipt throws a NotFoundException. */ @Test(expected = NotFoundException.class) public void testCancelAlreadyCanceledReceipt() { long receiptId = TestDataInjector.RECEIPT_1.getReceiptId(); assertTrue(receiptRepository.findById(receiptId).isPresent()); receiptService.cancelReceipt(receiptId); receiptService.cancelReceipt(receiptId); } /** * Tests if an existing receipt can be fetched using its receiptId. */ @Test public void testGetReceipt() { assertThat(receiptService.getReceipt(TestDataInjector.RECEIPT_1.getReceiptId()).getReceiptId(), is(TestDataInjector.RECEIPT_1.getReceiptId())); } /** * Tests if getting a non existing receipt throws a NotFoundException. */ @Test(expected = NotFoundException.class) public void testGetNonExistingReceipt() { receiptService.getReceipt(Long.MAX_VALUE); } /** * Tests if null receiptId throws an IllegalArgumentException. */ @Test(expected = IllegalArgumentException.class) public void testGetNullReceipt() { receiptService.getReceipt(null); } /** * Tests if all receipts for a customer are returned. */ @Test public void testGetReceiptsForCustomer() { assertEquals(1, receiptService.getReceiptsForCustomer(TestDataInjector.CUSTOMER_1.getId()).size()); } /** * Tests if null customerId throws an IllegalArgumentException. */ @Test(expected = IllegalArgumentException.class) public void testGetReceiptsNull() { receiptService.getReceiptsForCustomer(null); } }
3e05072b4158a082f55d45735d256838dfbd32cb
6,151
java
Java
src/jat/coreNOSA/astronomy/Angle.java
atmelino/JATexperimental
53be8127b1e9d6166e15ea48cd4d254080501d1e
[ "Apache-2.0" ]
1
2021-01-17T16:23:00.000Z
2021-01-17T16:23:00.000Z
src/jat/coreNOSA/astronomy/Angle.java
atmelino/JATexperimental
53be8127b1e9d6166e15ea48cd4d254080501d1e
[ "Apache-2.0" ]
null
null
null
src/jat/coreNOSA/astronomy/Angle.java
atmelino/JATexperimental
53be8127b1e9d6166e15ea48cd4d254080501d1e
[ "Apache-2.0" ]
null
null
null
26.512931
105
0.657617
2,105
/* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2002 National Aeronautics and Space Administration. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement * * * 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 * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package jat.coreNOSA.astronomy; import jat.coreNOSA.math.MathUtils; /** * @author Tobias Berthold * internally uses radians */ public class Angle { public final static int RADIANS = 1, DEGREES = 2, DECIMALHOURS = 3; public final static int ARCDEGREES = 4, HOURANGLE = 5, SHA=6; public double radians; double degrees; double hours; HourAngle h = new HourAngle(); ArcDegrees a = new ArcDegrees(); ArcDegrees sha = new ArcDegrees(); public Angle(double angle, int mode) { if (mode == RADIANS) radians = angle; if (mode == DEGREES) radians = Math.toRadians(angle); if (mode == DECIMALHOURS) radians = Math.toRadians(angle * 15.); convert(); } public Angle(boolean positive, int hours_arcdegrees, int minutes, double seconds, int mode) { h.positive = positive; a.positive = positive; if (mode == ARCDEGREES) radians = Math.toRadians(hours_arcdegrees + minutes / 60. + seconds / 3600.); if (mode == HOURANGLE) radians = Math.toRadians(15. * (hours_arcdegrees + minutes / 60. + seconds / 3600.)); if (!positive) radians = -radians; convert(); } /** * assumes that angle is store in radians */ void convert() { double tmpdegrees; double shadegrees; degrees = Math.toDegrees(radians); hours = degrees / 15.; if (radians > 0.) { a.positive=true; sha.positive=true; h.positive=true; tmpdegrees = degrees; shadegrees = 360.-degrees; } else { a.positive=false; sha.positive=false; h.positive=false; tmpdegrees = -degrees; shadegrees = -degrees; } // Angle expressed in degrees, minutes, seconds a.degrees = (int) tmpdegrees; a.minutes = (int) (MathUtils.Frac(tmpdegrees) * 60.0); a.seconds = (tmpdegrees - a.degrees - a.minutes / 60.) * 3600.; // Angle expressed as SHA in degrees, minutes, seconds //double shadegrees=360.-degrees; sha.degrees = (int) shadegrees; sha.minutes = (int) (MathUtils.Frac(shadegrees) * 60.0); sha.seconds = (shadegrees - sha.degrees - sha.minutes / 60.) * 3600.; // Angle expressed as hour angle in hours, minutes, seconds double tmphours=tmpdegrees/15.; h.hours = (int) tmphours; //System.out.println(decimalhours+ " decimal hours"); double tmpminutes = 60. * MathUtils.Frac(tmphours); //System.out.println(decimalminutes+ " decimal minutes"); h.minutes = (int) (60. * MathUtils.Frac(tmphours)); h.seconds = 60. * MathUtils.Frac(tmpminutes); } public Angle add(Angle b) { Angle result = new Angle(radians + b.radians, RADIANS); result.convert(); return result; } public double sin(Angle a) { return Math.sin(a.radians); } public double tan(Angle a) { return Math.tan(a.radians); } public double cos(Angle a) { return Math.cos(a.radians); } public void print() { System.out.println(radians + " Radians"); System.out.println(degrees + " Decimal degrees"); if (a.positive) System.out.print("+"); else System.out.print("-"); System.out.println(a.degrees + " degrees " + a.minutes + " minutes " + a.seconds + " seconds"); if (h.positive) System.out.print("+"); else System.out.print("-"); System.out.println(h.hours + " hours " + h.minutes + " minutes " + h.seconds + " seconds"); //System.out.println(decimalhours + " Decimal hours"); } public void println() { print(); System.out.println(); } public void println(String title) { System.out.println(title); println(); } public void println(String title, int mode) { System.out.print(title+" = "); switch (mode) { case RADIANS : System.out.println(radians + " Radians"); break; case DEGREES : System.out.println(degrees + " Decimal degrees"); break; case DECIMALHOURS : System.out.println(hours + " Decimal hours"); break; case ARCDEGREES : if (a.positive) System.out.print("+"); else System.out.print("-"); System.out.println(a.degrees + " Degrees " + a.minutes + " Minutes " + a.seconds + " Seconds"); break; case SHA : if (sha.positive) System.out.print("+"); else System.out.print("-"); System.out.println(sha.degrees + " Degrees " + sha.minutes + " Minutes " + sha.seconds + " Seconds"); break; case HOURANGLE : if (h.positive) System.out.print("+"); else System.out.print("-"); System.out.println(h.hours + " Hours " + h.minutes + " Minutes " + h.seconds + " Seconds"); break; } } public static void main(String[] args) { System.out.println("Angle class example"); //Angle alpha = new Angle(1.5, Angle.RADIANS); Angle alpha = new Angle(59.51, Angle.DEGREES); alpha.println(); System.out.println(1002.23 + " arcseconds "); Angle beta = new Angle(true, 0, 0, 1002.23, Angle.ARCDEGREES); // Angle beta = new Angle(0,16,42.23, Angle.ARCDEGREES); // Angle beta = new Angle(0,0,20.04, Angle.ARCDEGREES); beta.println(); // Example from Duffett-Smith System.out.println(18.52417 + " decimal hours"); Angle gamma = new Angle(18.52417, Angle.DECIMALHOURS); gamma.println(); System.out.println("18 h 31 m 27.012 s"); Angle delta = new Angle(true, 18, 31, 27.012, Angle.HOURANGLE); delta.println(); System.out.println(""); Angle n_1960 = new Angle(true, 0, 0, 1.33612, Angle.HOURANGLE); n_1960.println(); Angle a1 = new Angle(40., Angle.DEGREES); Angle a2 = new Angle(45., Angle.DEGREES); a1.add(a2).println(); } }
3e05072bd1ad1a6376b6ea4f7f16e129c17a4e2f
15,182
java
Java
java/pdfclown.lib/src/org/pdfclown/documents/interaction/annotations/Annotation.java
XoriantOpenSource/PDFClown
ed4eb7b74c7b6702ae13f1fc4891c9fff73b877c
[ "Apache-2.0" ]
2
2020-11-18T12:41:50.000Z
2021-12-01T18:10:45.000Z
java/pdfclown.lib/src/org/pdfclown/documents/interaction/annotations/Annotation.java
XoriantOpenSource/PDFClown
ed4eb7b74c7b6702ae13f1fc4891c9fff73b877c
[ "Apache-2.0" ]
null
null
null
java/pdfclown.lib/src/org/pdfclown/documents/interaction/annotations/Annotation.java
XoriantOpenSource/PDFClown
ed4eb7b74c7b6702ae13f1fc4891c9fff73b877c
[ "Apache-2.0" ]
null
null
null
26.403478
136
0.670531
2,106
/* Copyright 2008-2012 Stefano Chizzolini. http://www.pdfclown.org Contributors: * Stefano Chizzolini (original code developer, http://www.stefanochizzolini.it) This file should be part of the source code distribution of "PDF Clown library" (the Program): see the accompanying README files for more info. This Program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 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, either expressed or implied; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more details. You should have received a copy of the GNU Lesser General Public License along with this Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/). Redistribution and use, with or without modification, are permitted provided that such redistributions retain the above copyright notice, license and disclaimer, along with this list of conditions. */ package org.pdfclown.documents.interaction.annotations; import java.awt.geom.Rectangle2D; import java.util.Date; import java.util.EnumSet; import org.pdfclown.PDF; import org.pdfclown.VersionEnum; import org.pdfclown.documents.Document; import org.pdfclown.documents.Page; import org.pdfclown.documents.contents.PropertyList; import org.pdfclown.documents.contents.colorSpaces.DeviceColor; import org.pdfclown.documents.contents.layers.ILayerable; import org.pdfclown.documents.contents.layers.LayerEntity; import org.pdfclown.documents.interaction.actions.Action; import org.pdfclown.objects.PdfArray; import org.pdfclown.objects.PdfDate; import org.pdfclown.objects.PdfDictionary; import org.pdfclown.objects.PdfDirectObject; import org.pdfclown.objects.PdfInteger; import org.pdfclown.objects.PdfName; import org.pdfclown.objects.PdfObjectWrapper; import org.pdfclown.objects.PdfSimpleObject; import org.pdfclown.objects.PdfTextString; import org.pdfclown.util.EnumUtils; /** Annotation [PDF:1.6:8.4]. @author Stefano Chizzolini (http://www.stefanochizzolini.it) @since 0.0.7 @version 0.1.2, 12/28/12 */ @PDF(VersionEnum.PDF10) public class Annotation extends PdfObjectWrapper<PdfDictionary> implements ILayerable { // <class> // <classes> /** Field flags [PDF:1.6:8.4.2]. */ public enum FlagsEnum { // <class> // <static> // <fields> /** Hide the annotation, both on screen and on print, if it does not belong to one of the standard annotation types and no annotation handler is available. */ Invisible(0x1), /** Hide the annotation, both on screen and on print (regardless of its annotation type or whether an annotation handler is available). */ Hidden(0x2), /** Print the annotation when the page is printed. */ Print(0x4), /** Do not scale the annotation's appearance to match the magnification of the page. */ NoZoom(0x8), /** Do not rotate the annotation's appearance to match the rotation of the page. */ NoRotate(0x10), /** Hide the annotation on the screen. */ NoView(0x20), /** Do not allow the annotation to interact with the user. */ ReadOnly(0x40), /** Do not allow the annotation to be deleted or its properties to be modified by the user. */ Locked(0x80), /** Invert the interpretation of the NoView flag. */ ToggleNoView(0x100); // </fields> // <interface> // <public> /** Converts an enumeration set into its corresponding bit mask representation. */ public static int toInt( EnumSet<FlagsEnum> flags ) { int flagsMask = 0; for(FlagsEnum flag : flags) {flagsMask |= flag.getCode();} return flagsMask; } /** Converts a bit mask into its corresponding enumeration representation. */ public static EnumSet<FlagsEnum> toEnumSet( int flagsMask ) { EnumSet<FlagsEnum> flags = EnumSet.noneOf(FlagsEnum.class); for(FlagsEnum flag : FlagsEnum.values()) { if((flagsMask & flag.getCode()) > 0) {flags.add(flag);} } return flags; } // </public> // </interface> // </static> // <dynamic> // <fields> /** <h3>Remarks</h3> <p>Bitwise code MUST be explicitly distinct from the ordinal position of the enum constant as they don't coincide.</p> */ private final int code; // </fields> // <constructors> private FlagsEnum( int code ) {this.code = code;} // </constructors> // <interface> // <public> public int getCode( ) {return code;} // </public> // </interface> // </dynamic> // </class> } // </classes> // <static> // <fields> // </fields> // <interface> // <public> /** Wraps an annotation base object into an annotation object. @param baseObject Annotation base object. @return Annotation object associated to the base object. */ public static final Annotation wrap( PdfDirectObject baseObject ) { if(baseObject == null) return null; PdfName annotationType = (PdfName)((PdfDictionary)baseObject.resolve()).get(PdfName.Subtype); if(annotationType.equals(PdfName.Text)) return new Note(baseObject); else if(annotationType.equals(PdfName.Link)) return new Link(baseObject); else if(annotationType.equals(PdfName.FreeText)) return new CalloutNote(baseObject); else if(annotationType.equals(PdfName.Line)) return new Line(baseObject); else if(annotationType.equals(PdfName.Square)) return new Rectangle(baseObject); else if(annotationType.equals(PdfName.Circle)) return new Ellipse(baseObject); else if(annotationType.equals(PdfName.Polygon)) return new Polygon(baseObject); else if(annotationType.equals(PdfName.PolyLine)) return new Polyline(baseObject); else if(annotationType.equals(PdfName.Highlight) || annotationType.equals(PdfName.Underline) || annotationType.equals(PdfName.Squiggly) || annotationType.equals(PdfName.StrikeOut)) return new TextMarkup(baseObject); else if(annotationType.equals(PdfName.Stamp)) return new RubberStamp(baseObject); else if(annotationType.equals(PdfName.Caret)) return new Caret(baseObject); else if(annotationType.equals(PdfName.Ink)) return new Scribble(baseObject); else if(annotationType.equals(PdfName.Popup)) return new Popup(baseObject); else if(annotationType.equals(PdfName.FileAttachment)) return new FileAttachment(baseObject); else if(annotationType.equals(PdfName.Sound)) return new Sound(baseObject); else if(annotationType.equals(PdfName.Movie)) return new Movie(baseObject); else if(annotationType.equals(PdfName.Widget)) return new Widget(baseObject); else if(annotationType.equals(PdfName.Screen)) return new Screen(baseObject); //TODO // else if(annotationType.equals(PdfName.PrinterMark)) return new PrinterMark(baseObject); // else if(annotationType.equals(PdfName.TrapNet)) return new TrapNet(baseObject); // else if(annotationType.equals(PdfName.Watermark)) return new Watermark(baseObject); // else if(annotationType.equals(PdfName.3DAnnotation)) return new 3DAnnotation(baseObject); else // Other annotation type. return new Annotation(baseObject); } // </public> // </interface> // </static> // <dynamic> // <constructors> protected Annotation( Page page, PdfName subtype, Rectangle2D box, String text ) { super( page.getDocument(), new PdfDictionary( new PdfName[] { PdfName.Type, PdfName.Subtype, PdfName.Border }, new PdfDirectObject[] { PdfName.Annot, subtype, new PdfArray(new PdfDirectObject[]{PdfInteger.Default,PdfInteger.Default,PdfInteger.Default}) // NOTE: Hide border by default. } ) ); page.getAnnotations().add(this); setBox(box); setText(text); } protected Annotation( PdfDirectObject baseObject ) {super(baseObject);} // </constructors> // <interface> // <public> @Override public Annotation clone( Document context ) {return (Annotation)super.clone(context);} /** Deletes this annotation removing also its reference on the page. */ @Override public boolean delete( ) { // Shallow removal (references): // * reference on page getPage().getAnnotations().remove(this); // Deep removal (indirect object). return super.delete(); } /** Gets the action to be performed when the annotation is activated. */ @PDF(VersionEnum.PDF11) public Action getAction( ) {return Action.wrap(getBaseDataObject().get(PdfName.A));} /** Gets the annotation's behavior in response to various trigger events. */ @PDF(VersionEnum.PDF12) public AnnotationActions getActions( ) {return new AnnotationActions(this, getBaseDataObject().get(PdfName.AA, PdfDictionary.class));} /** Gets the appearance specifying how the annotation is presented visually on the page. */ @PDF(VersionEnum.PDF12) public Appearance getAppearance( ) {return Appearance.wrap(getBaseDataObject().get(PdfName.AP, PdfDictionary.class));} /** Gets the border style. */ @PDF(VersionEnum.PDF11) public Border getBorder( ) {return new Border(getBaseDataObject().get(PdfName.BS, PdfDictionary.class));} /** Gets the location of the annotation on the page in default user space units. */ public Rectangle2D getBox( ) { org.pdfclown.objects.Rectangle box = org.pdfclown.objects.Rectangle.wrap(getBaseDataObject().get(PdfName.Rect)); return new Rectangle2D.Double( box.getLeft(), getPageHeight() - box.getTop(), box.getWidth(), box.getHeight() ); } /** Gets the annotation color. @since 0.1.1 */ @PDF(VersionEnum.PDF11) public DeviceColor getColor( ) {return DeviceColor.get((PdfArray)getBaseDataObject().get(PdfName.C));} /** Gets the annotation flags. */ @PDF(VersionEnum.PDF11) public EnumSet<FlagsEnum> getFlags( ) { PdfInteger flagsObject = (PdfInteger)getBaseDataObject().get(PdfName.F); return flagsObject == null ? EnumSet.noneOf(FlagsEnum.class) : FlagsEnum.toEnumSet(flagsObject.getValue()); } /** Gets the date and time when the annotation was most recently modified. */ @PDF(VersionEnum.PDF11) public Date getModificationDate( ) { /* NOTE: Despite PDF date being the preferred format, loose formats are tolerated by the spec. */ PdfDirectObject modificationDateObject = getBaseDataObject().get(PdfName.M); return modificationDateObject instanceof PdfDate ? ((PdfDate)modificationDateObject).getValue() : null; } /** Gets the annotation name. <p>The annotation name uniquely identifies the annotation among all the annotations on its page.</p> */ @PDF(VersionEnum.PDF14) public String getName( ) {return (String)PdfSimpleObject.getValue(getBaseDataObject().get(PdfName.NM));} /** Gets the associated page. */ @PDF(VersionEnum.PDF13) public Page getPage( ) {return Page.wrap(getBaseDataObject().get(PdfName.P));} /** Gets the annotation text. <p>Depending on the annotation type, the text may be either directly displayed or (in case of non-textual annotations) used as alternate description.</p> */ public String getText( ) {return (String)PdfSimpleObject.getValue(getBaseDataObject().get(PdfName.Contents));} /** Gets whether to print the annotation when the page is printed. */ @PDF(VersionEnum.PDF11) public boolean isPrintable( ) {return getFlags().contains(FlagsEnum.Print);} /** Gets whether the annotation is visible. */ @PDF(VersionEnum.PDF11) public boolean isVisible( ) {return !getFlags().contains(FlagsEnum.Hidden);} /** @see #getAction() */ public void setAction( Action value ) {getBaseDataObject().put(PdfName.A, PdfObjectWrapper.getBaseObject(value));} /** @see #getActions() */ public void setActions( AnnotationActions value ) {getBaseDataObject().put(PdfName.AA, PdfObjectWrapper.getBaseObject(value));} /** @see #getAppearance() */ public void setAppearance( Appearance value ) {getBaseDataObject().put(PdfName.AP, PdfObjectWrapper.getBaseObject(value));} /** @see #getBorder() */ public void setBorder( Border value ) { getBaseDataObject().put(PdfName.BS, PdfObjectWrapper.getBaseObject(value)); if(value != null) {getBaseDataObject().remove(PdfName.Border);} } /** @see #getBox() */ public void setBox( Rectangle2D value ) { getBaseDataObject().put( PdfName.Rect, new org.pdfclown.objects.Rectangle( value.getX(), getPageHeight() - value.getY(), value.getWidth(), value.getHeight() ).getBaseDataObject() ); } /** @see #getColor() */ public void setColor( DeviceColor value ) {getBaseDataObject().put(PdfName.C, PdfObjectWrapper.getBaseObject(value));} /** @see #getFlags() */ public void setFlags( EnumSet<FlagsEnum> value ) {getBaseDataObject().put(PdfName.F, PdfInteger.get(FlagsEnum.toInt(value)));} /** @see #getModificationDate() */ public void setModificationDate( Date value ) {getBaseDataObject().put(PdfName.M, PdfDate.get(value));} /** @see #getName() */ public void setName( String value ) {getBaseDataObject().put(PdfName.NM, PdfTextString.get(value));} /** @see #isPrintable() */ public void setPrintable( boolean value ) {setFlags(EnumUtils.mask(getFlags(), FlagsEnum.Print, value));} /** @see #getText() */ public void setText( String value ) {getBaseDataObject().put(PdfName.Contents, PdfTextString.get(value));} /** @see #isVisible() */ public void setVisible( boolean value ) {setFlags(EnumUtils.mask(getFlags(), FlagsEnum.Hidden, !value));} // <ILayerable> @Override @PDF(VersionEnum.PDF15) public LayerEntity getLayer( ) {return (LayerEntity)PropertyList.wrap(getBaseDataObject().get(PdfName.OC));} @Override public void setLayer( LayerEntity value ) {getBaseDataObject().put(PdfName.OC, PdfObjectWrapper.getBaseObject(value));} // </ILayerable> // </public> // <private> private double getPageHeight( ) { Page page = getPage(); return (page != null ? page.getBox().getHeight() : getDocument().getSize().getHeight()); } // </private> // </interface> // </dynamic> // </class> }
3e05087154d9806f9dbb70ab6de3512bb022eb6e
217
java
Java
src/com/git/practice/GitTest2.java
mdikbal99/AzureDemo
825b9312320424ccafabf22a232a97c1bbc85e2f
[ "MIT" ]
null
null
null
src/com/git/practice/GitTest2.java
mdikbal99/AzureDemo
825b9312320424ccafabf22a232a97c1bbc85e2f
[ "MIT" ]
null
null
null
src/com/git/practice/GitTest2.java
mdikbal99/AzureDemo
825b9312320424ccafabf22a232a97c1bbc85e2f
[ "MIT" ]
null
null
null
9.863636
42
0.571429
2,107
/** * */ package com.git.practice; /** * @author mdikbal99 * */ public class GitTest2 { /** * @param args */ public static void main(String[] args) { System.out.println(" in Develop Brach"); } }
3e0509083bdd7e48d8b7dece087d88aa65142e3f
5,443
java
Java
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/repositories/metadata/GradleModuleMetadataCompatibilityConverter.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
2
2015-12-10T21:06:45.000Z
2016-08-04T19:35:30.000Z
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/repositories/metadata/GradleModuleMetadataCompatibilityConverter.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
null
null
null
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/repositories/metadata/GradleModuleMetadataCompatibilityConverter.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
1
2019-06-26T20:28:16.000Z
2019-06-26T20:28:16.000Z
54.43
192
0.724233
2,108
/* * Copyright 2019 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 org.gradle.api.internal.artifacts.repositories.metadata; import com.google.common.collect.Lists; import org.gradle.api.attributes.Attribute; import org.gradle.api.attributes.LibraryElements; import org.gradle.api.attributes.Usage; import org.gradle.api.internal.artifacts.repositories.resolver.MavenUniqueSnapshotComponentIdentifier; import org.gradle.api.internal.attributes.ImmutableAttributes; import org.gradle.api.internal.attributes.ImmutableAttributesFactory; import org.gradle.api.internal.model.NamedObjectInstantiator; import org.gradle.internal.component.external.model.ComponentVariant; import org.gradle.internal.component.external.model.MutableComponentVariant; import org.gradle.internal.component.external.model.MutableModuleComponentResolveMetadata; import org.gradle.internal.snapshot.impl.CoercingStringValueSnapshot; import java.util.List; public class GradleModuleMetadataCompatibilityConverter { private static final Attribute<String> USAGE_STRING_ATTRIBUTE = Attribute.of(Usage.USAGE_ATTRIBUTE.getName(), String.class); private static final Attribute<String> LIBRARY_ELEMENTS_STRING_ATTRIBUTE = Attribute.of(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE.getName(), String.class); private final ImmutableAttributesFactory attributesFactory; private final NamedObjectInstantiator instantiator; public GradleModuleMetadataCompatibilityConverter(ImmutableAttributesFactory attributesFactory, NamedObjectInstantiator instantiator) { this.attributesFactory = attributesFactory; this.instantiator = instantiator; } public void process(MutableModuleComponentResolveMetadata metaDataFromResource) { handleAttributeCompatibility(metaDataFromResource); handleMavenSnapshotCompatibility(metaDataFromResource); } private void handleMavenSnapshotCompatibility(MutableModuleComponentResolveMetadata metaDataFromResource) { if (metaDataFromResource.getId() instanceof MavenUniqueSnapshotComponentIdentifier) { // Action needed only for Maven unique snapshots // Verify that the URL of the artifacts properly references the unique version and not -SNAPSHOT MavenUniqueSnapshotComponentIdentifier uniqueIdentifier = (MavenUniqueSnapshotComponentIdentifier) metaDataFromResource.getId(); for (MutableComponentVariant mutableVariant : metaDataFromResource.getMutableVariants()) { List<ComponentVariant.File> invalidFiles = null; for (ComponentVariant.File file : mutableVariant.getFiles()) { if (file.getUri().contains("SNAPSHOT")) { if (invalidFiles == null) { invalidFiles = Lists.newArrayListWithExpectedSize(2); } invalidFiles.add(file); } } if (invalidFiles != null) { for (ComponentVariant.File invalidFile : invalidFiles) { mutableVariant.removeFile(invalidFile); mutableVariant.addFile(invalidFile.getName(), invalidFile.getUri().replace("SNAPSHOT", uniqueIdentifier.getTimestamp())); } } } } } private void handleAttributeCompatibility(MutableModuleComponentResolveMetadata metaDataFromResource) { // This code path will always be a no-op following the changes in DefaultImmutableAttributesFactory // However this code will have to remain forever while the other one should be removed at some point (Gradle 7.0?) for (MutableComponentVariant variant : metaDataFromResource.getMutableVariants()) { ImmutableAttributes attributes = variant.getAttributes(); ImmutableAttributes updatedAttributes = ImmutableAttributes.EMPTY; if (attributes.contains(USAGE_STRING_ATTRIBUTE)) { String attributeValue = attributes.getAttribute(USAGE_STRING_ATTRIBUTE); if (attributeValue.endsWith("-jars")) { updatedAttributes = attributesFactory.concat(updatedAttributes, USAGE_STRING_ATTRIBUTE, new CoercingStringValueSnapshot(attributeValue.replace("-jars", ""), instantiator)); } } if (!updatedAttributes.isEmpty() && !attributes.contains(LIBRARY_ELEMENTS_STRING_ATTRIBUTE)) { updatedAttributes = attributesFactory.concat(updatedAttributes, LIBRARY_ELEMENTS_STRING_ATTRIBUTE, new CoercingStringValueSnapshot(LibraryElements.JAR, instantiator)); } if (!updatedAttributes.isEmpty()) { updatedAttributes = attributesFactory.concat(attributes, updatedAttributes); variant.setAttributes(updatedAttributes); } } } }
3e0509a89659f32bf26503746ef27d3c950065ee
541
java
Java
src/main/java/com/maybeapexin/asteroid/registry/items/armor/BaseArmor.java
MaybeApexin/asteroid-rewritten
5fdf675fd16fae15668601fcbd1ba8d01ff3c2a2
[ "Unlicense" ]
null
null
null
src/main/java/com/maybeapexin/asteroid/registry/items/armor/BaseArmor.java
MaybeApexin/asteroid-rewritten
5fdf675fd16fae15668601fcbd1ba8d01ff3c2a2
[ "Unlicense" ]
null
null
null
src/main/java/com/maybeapexin/asteroid/registry/items/armor/BaseArmor.java
MaybeApexin/asteroid-rewritten
5fdf675fd16fae15668601fcbd1ba8d01ff3c2a2
[ "Unlicense" ]
null
null
null
28.473684
108
0.791128
2,109
package com.maybeapexin.asteroid.registry.items.armor; import com.maybeapexin.asteroid.registry.AsteroidItemGroups; import net.minecraft.entity.EquipmentSlot; import net.minecraft.item.ArmorItem; import net.minecraft.item.ArmorMaterial; import net.minecraft.item.Item; import net.minecraft.util.Rarity; public class BaseArmor extends ArmorItem { public BaseArmor(ArmorMaterial material, EquipmentSlot slot ) { super(material, slot, new Item.Settings().group(AsteroidItemGroups.ITEM_GROUP).rarity(Rarity.EPIC)); } }
3e0509da71ecdc2bfe57e3f6a08185f9e18b3845
1,931
java
Java
spring-data-datty/src/test/java/io/datty/spring/converter/code/NumericEntityTest.java
datty-io/datty
d826c0fd452f658e9c1aeb208ef2ecfd93284e02
[ "Apache-2.0" ]
null
null
null
spring-data-datty/src/test/java/io/datty/spring/converter/code/NumericEntityTest.java
datty-io/datty
d826c0fd452f658e9c1aeb208ef2ecfd93284e02
[ "Apache-2.0" ]
null
null
null
spring-data-datty/src/test/java/io/datty/spring/converter/code/NumericEntityTest.java
datty-io/datty
d826c0fd452f658e9c1aeb208ef2ecfd93284e02
[ "Apache-2.0" ]
null
null
null
27.585714
100
0.723977
2,110
/* * Copyright (C) 2016 Datty.io 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 io.datty.spring.converter.code; import org.junit.Assert; import org.junit.Test; import io.datty.api.DattyRecord; import io.datty.spring.support.DattyConverterUtil; import io.netty.buffer.ByteBuf; /** * NumericEntityTest * * @author Alex Shvid * */ public class NumericEntityTest { @Test public void testNames() { NumericEntity entity = new NumericEntity(); entity.setId(123L); entity.setName("Alex"); DattyRecord rec = new DattyRecord(); DattyConverterUtil.write(entity, rec, true); ByteBuf bb = rec.get("1").asByteBuf(); Assert.assertNotNull(bb); bb = rec.get("2").asByteBuf(); Assert.assertNotNull(bb); NumericMigratedEntity actual = DattyConverterUtil.read(NumericMigratedEntity.class, rec); Assert.assertEquals(entity.getId(), actual.getId()); Assert.assertEquals(entity.getName(), actual.getFirst()); rec = new DattyRecord(); DattyConverterUtil.write(actual, rec, true); bb = rec.get("1").asByteBuf(); Assert.assertNotNull(bb); bb = rec.get("2").asByteBuf(); Assert.assertNotNull(bb); //System.out.println(Arrays.toString(ByteBufUtil.getBytes(bb))); actual = DattyConverterUtil.read(NumericMigratedEntity.class, rec); Assert.assertEquals(entity.getId(), actual.getId()); Assert.assertEquals(entity.getName(), actual.getFirst()); } }
3e050c0908ff34ca94954c9221cec0fcba16eb7d
1,533
java
Java
Yaoqiang/src/org/yaoqiang/bpmn/editor/swing/DefaultFileFilter.java
duarterafael/Conformitate
c1da7401c62a6d8c8d5046ef6aa03cf0f9304e89
[ "Apache-2.0" ]
null
null
null
Yaoqiang/src/org/yaoqiang/bpmn/editor/swing/DefaultFileFilter.java
duarterafael/Conformitate
c1da7401c62a6d8c8d5046ef6aa03cf0f9304e89
[ "Apache-2.0" ]
null
null
null
Yaoqiang/src/org/yaoqiang/bpmn/editor/swing/DefaultFileFilter.java
duarterafael/Conformitate
c1da7401c62a6d8c8d5046ef6aa03cf0f9304e89
[ "Apache-2.0" ]
null
null
null
19.974026
79
0.658648
2,111
package org.yaoqiang.bpmn.editor.swing; import java.io.File; import javax.swing.filechooser.FileFilter; /** * AboutDialog * * @author Shi Yaoqiang([email protected]) */ public class DefaultFileFilter extends FileFilter { /** * Extension of accepted files. */ protected String ext; /** * Description of accepted files. */ protected String desc; /** * Constructs a new filter for the specified extension and descpription. * * @param extension * The extension to accept files with. * @param description * The description of the file format. */ public DefaultFileFilter(String extension, String description) { ext = extension.toLowerCase(); desc = description; } /** * Returns true if <code>file</code> is a directory or ends with {@link #ext}. * * @param file * The file to be checked. * @return Returns true if the file is accepted. */ public boolean accept(File file) { return file.isDirectory() || file.getName().toLowerCase().endsWith(ext); } /** * Returns the description for accepted files. * * @return Returns the description. */ public String getDescription() { return desc; } /** * Returns the extension for accepted files. * * @return Returns the extension. */ public String getExtension() { return ext; } /** * Sets the extension for accepted files. * * @param extension * The extension to set. */ public void setExtension(String extension) { this.ext = extension; } }
3e050c38a88f395529a1f63b6bbf8460625beded
2,031
java
Java
src/main/java/tech/zettervall/openlibrary/rxclient/models/Subject.java
rickardzettervall/openlibrary-api-rxclient
91506dd66dd642f0ed76fe72c362bf2ce0a7ce6e
[ "Apache-2.0" ]
2
2021-03-10T18:24:41.000Z
2021-08-17T08:45:02.000Z
src/main/java/tech/zettervall/openlibrary/rxclient/models/Subject.java
rickardzettervall/openlibrary-api-rxclient
91506dd66dd642f0ed76fe72c362bf2ce0a7ce6e
[ "Apache-2.0" ]
null
null
null
src/main/java/tech/zettervall/openlibrary/rxclient/models/Subject.java
rickardzettervall/openlibrary-api-rxclient
91506dd66dd642f0ed76fe72c362bf2ce0a7ce6e
[ "Apache-2.0" ]
1
2021-06-12T09:22:17.000Z
2021-06-12T09:22:17.000Z
23.344828
94
0.606105
2,112
package tech.zettervall.openlibrary.rxclient.models; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; /** * API response Object. * Reference: https://openlibrary.org/dev/docs/api/subjects */ public class Subject implements Comparable<Subject> { @SerializedName("key") private final String key; @SerializedName("name") private final String name; @SerializedName("subject_type") private final String subjectType; @SerializedName("work_count") private final int workCount; @SerializedName("works") private final Work[] works; public Subject(String key, String name, String subjectType, int workCount, Work[] works) { this.key = key; this.name = name; this.subjectType = subjectType; this.workCount = workCount; this.works = works; } /** * Factory for testing, should only set field used in Comparable. */ public static Subject newSubjectForTesting(String name) { return new Subject(null, name, null, 0, null); } public String getKey() { return key; } public String getName() { return name; } public String getSubjectType() { return subjectType; } public int getWorkCount() { return workCount; } public Work[] getWorks() { return works; } @Override public String toString() { return "Subject{" + "key='" + key + '\'' + ", name='" + name + '\'' + ", workCount=" + workCount + '}'; } /** * Natural sorting by title. */ @Override public int compareTo(Subject subject) { return name.compareTo(subject.getName()); } /** * Convert Subject API response to Subject. */ public static <T extends Subject> T jsonConverter(Class<T> subjectClass, JsonObject obj) { return new Gson().fromJson(obj, subjectClass); } }